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.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "InstCombineInternal.h"
15 #include "llvm/Analysis/ValueTracking.h"
16 #include "llvm/IR/GetElementPtrTypeIterator.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"
21 
22 using namespace llvm;
23 using namespace llvm::PatternMatch;
24 
25 #define DEBUG_TYPE "instcombine"
26 
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");
34 
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;
40 
41   // If there are no bits set that aren't demanded, nothing to do.
42   if (C->isSubsetOf(Demanded))
43     return false;
44 
45   // This instruction is producing bits that are not demanded. Shrink the RHS.
46   I->setOperand(OpNo, ConstantInt::get(Op->getType(), *C & Demanded));
47 
48   return true;
49 }
50 
51 
52 
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::getAllOnes(BitWidth));
59 
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;
66 }
67 
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);
80 
81   replaceUse(U, NewVal);
82   return true;
83 }
84 
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.
102 ///
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");
120 
121   if (isa<Constant>(V)) {
122     computeKnownBits(V, Known, Depth, CxtI);
123     return nullptr;
124   }
125 
126   Known.resetAll();
127   if (DemandedMask.isZero()) // Not demanding any bits from V.
128     return UndefValue::get(VTy);
129 
130   if (Depth == MaxAnalysisRecursionDepth)
131     return nullptr;
132 
133   if (isa<ScalableVectorType>(VTy))
134     return nullptr;
135 
136   Instruction *I = dyn_cast<Instruction>(V);
137   if (!I) {
138     computeKnownBits(V, Known, Depth, CxtI);
139     return nullptr;        // Only analyze instructions.
140   }
141 
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);
147 
148   KnownBits LHSKnown(BitWidth), RHSKnown(BitWidth);
149 
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();
156 
157   // If the high-bits of an ADD/SUB/MUL are not demanded, then we do not care
158   // about the high bits of the operands.
159   auto simplifyOperandsBasedOnUnusedHighBits = [&](APInt &DemandedFromOps) {
160     unsigned NLZ = DemandedMask.countLeadingZeros();
161     // Right fill the mask of bits for the operands to demand the most
162     // significant bit and all those below it.
163     DemandedFromOps = APInt::getLowBitsSet(BitWidth, BitWidth - NLZ);
164     if (ShrinkDemandedConstant(I, 0, DemandedFromOps) ||
165         SimplifyDemandedBits(I, 0, DemandedFromOps, LHSKnown, Depth + 1) ||
166         ShrinkDemandedConstant(I, 1, DemandedFromOps) ||
167         SimplifyDemandedBits(I, 1, DemandedFromOps, RHSKnown, Depth + 1)) {
168       if (NLZ > 0) {
169         // Disable the nsw and nuw flags here: We can no longer guarantee that
170         // we won't wrap after simplification. Removing the nsw/nuw flags is
171         // legal here because the top bit is not demanded.
172         I->setHasNoSignedWrap(false);
173         I->setHasNoUnsignedWrap(false);
174       }
175       return true;
176     }
177     return false;
178   };
179 
180   switch (I->getOpcode()) {
181   default:
182     computeKnownBits(I, Known, Depth, CxtI);
183     break;
184   case Instruction::And: {
185     // If either the LHS or the RHS are Zero, the result is zero.
186     if (SimplifyDemandedBits(I, 1, DemandedMask, RHSKnown, Depth + 1) ||
187         SimplifyDemandedBits(I, 0, DemandedMask & ~RHSKnown.Zero, LHSKnown,
188                              Depth + 1))
189       return I;
190     assert(!RHSKnown.hasConflict() && "Bits known to be one AND zero?");
191     assert(!LHSKnown.hasConflict() && "Bits known to be one AND zero?");
192 
193     Known = LHSKnown & RHSKnown;
194 
195     // If the client is only demanding bits that we know, return the known
196     // constant.
197     if (DemandedMask.isSubsetOf(Known.Zero | Known.One))
198       return Constant::getIntegerValue(VTy, Known.One);
199 
200     // If all of the demanded bits are known 1 on one side, return the other.
201     // These bits cannot contribute to the result of the 'and'.
202     if (DemandedMask.isSubsetOf(LHSKnown.Zero | RHSKnown.One))
203       return I->getOperand(0);
204     if (DemandedMask.isSubsetOf(RHSKnown.Zero | LHSKnown.One))
205       return I->getOperand(1);
206 
207     // If the RHS is a constant, see if we can simplify it.
208     if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnown.Zero))
209       return I;
210 
211     break;
212   }
213   case Instruction::Or: {
214     // If either the LHS or the RHS are One, the result is One.
215     if (SimplifyDemandedBits(I, 1, DemandedMask, RHSKnown, Depth + 1) ||
216         SimplifyDemandedBits(I, 0, DemandedMask & ~RHSKnown.One, LHSKnown,
217                              Depth + 1))
218       return I;
219     assert(!RHSKnown.hasConflict() && "Bits known to be one AND zero?");
220     assert(!LHSKnown.hasConflict() && "Bits known to be one AND zero?");
221 
222     Known = LHSKnown | RHSKnown;
223 
224     // If the client is only demanding bits that we know, return the known
225     // constant.
226     if (DemandedMask.isSubsetOf(Known.Zero | Known.One))
227       return Constant::getIntegerValue(VTy, Known.One);
228 
229     // If all of the demanded bits are known zero on one side, return the other.
230     // These bits cannot contribute to the result of the 'or'.
231     if (DemandedMask.isSubsetOf(LHSKnown.One | RHSKnown.Zero))
232       return I->getOperand(0);
233     if (DemandedMask.isSubsetOf(RHSKnown.One | LHSKnown.Zero))
234       return I->getOperand(1);
235 
236     // If the RHS is a constant, see if we can simplify it.
237     if (ShrinkDemandedConstant(I, 1, DemandedMask))
238       return I;
239 
240     break;
241   }
242   case Instruction::Xor: {
243     if (SimplifyDemandedBits(I, 1, DemandedMask, RHSKnown, Depth + 1) ||
244         SimplifyDemandedBits(I, 0, DemandedMask, LHSKnown, Depth + 1))
245       return I;
246     Value *LHS, *RHS;
247     if (DemandedMask == 1 &&
248         match(I->getOperand(0), m_Intrinsic<Intrinsic::ctpop>(m_Value(LHS))) &&
249         match(I->getOperand(1), m_Intrinsic<Intrinsic::ctpop>(m_Value(RHS)))) {
250       // (ctpop(X) ^ ctpop(Y)) & 1 --> ctpop(X^Y) & 1
251       IRBuilderBase::InsertPointGuard Guard(Builder);
252       Builder.SetInsertPoint(I);
253       auto *Xor = Builder.CreateXor(LHS, RHS);
254       return Builder.CreateUnaryIntrinsic(Intrinsic::ctpop, Xor);
255     }
256 
257     assert(!RHSKnown.hasConflict() && "Bits known to be one AND zero?");
258     assert(!LHSKnown.hasConflict() && "Bits known to be one AND zero?");
259 
260     Known = LHSKnown ^ RHSKnown;
261 
262     // If the client is only demanding bits that we know, return the known
263     // constant.
264     if (DemandedMask.isSubsetOf(Known.Zero | Known.One))
265       return Constant::getIntegerValue(VTy, Known.One);
266 
267     // If all of the demanded bits are known zero on one side, return the other.
268     // These bits cannot contribute to the result of the 'xor'.
269     if (DemandedMask.isSubsetOf(RHSKnown.Zero))
270       return I->getOperand(0);
271     if (DemandedMask.isSubsetOf(LHSKnown.Zero))
272       return I->getOperand(1);
273 
274     // If all of the demanded bits are known to be zero on one side or the
275     // other, turn this into an *inclusive* or.
276     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
277     if (DemandedMask.isSubsetOf(RHSKnown.Zero | LHSKnown.Zero)) {
278       Instruction *Or =
279         BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
280                                  I->getName());
281       return InsertNewInstWith(Or, *I);
282     }
283 
284     // If all of the demanded bits on one side are known, and all of the set
285     // bits on that side are also known to be set on the other side, turn this
286     // into an AND, as we know the bits will be cleared.
287     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
288     if (DemandedMask.isSubsetOf(RHSKnown.Zero|RHSKnown.One) &&
289         RHSKnown.One.isSubsetOf(LHSKnown.One)) {
290       Constant *AndC = Constant::getIntegerValue(VTy,
291                                                  ~RHSKnown.One & DemandedMask);
292       Instruction *And = BinaryOperator::CreateAnd(I->getOperand(0), AndC);
293       return InsertNewInstWith(And, *I);
294     }
295 
296     // If the RHS is a constant, see if we can change it. Don't alter a -1
297     // constant because that's a canonical 'not' op, and that is better for
298     // combining, SCEV, and codegen.
299     const APInt *C;
300     if (match(I->getOperand(1), m_APInt(C)) && !C->isAllOnes()) {
301       if ((*C | ~DemandedMask).isAllOnes()) {
302         // Force bits to 1 to create a 'not' op.
303         I->setOperand(1, ConstantInt::getAllOnesValue(VTy));
304         return I;
305       }
306       // If we can't turn this into a 'not', try to shrink the constant.
307       if (ShrinkDemandedConstant(I, 1, DemandedMask))
308         return I;
309     }
310 
311     // If our LHS is an 'and' and if it has one use, and if any of the bits we
312     // are flipping are known to be set, then the xor is just resetting those
313     // bits to zero.  We can just knock out bits from the 'and' and the 'xor',
314     // simplifying both of them.
315     if (Instruction *LHSInst = dyn_cast<Instruction>(I->getOperand(0))) {
316       ConstantInt *AndRHS, *XorRHS;
317       if (LHSInst->getOpcode() == Instruction::And && LHSInst->hasOneUse() &&
318           match(I->getOperand(1), m_ConstantInt(XorRHS)) &&
319           match(LHSInst->getOperand(1), m_ConstantInt(AndRHS)) &&
320           (LHSKnown.One & RHSKnown.One & DemandedMask) != 0) {
321         APInt NewMask = ~(LHSKnown.One & RHSKnown.One & DemandedMask);
322 
323         Constant *AndC =
324             ConstantInt::get(I->getType(), NewMask & AndRHS->getValue());
325         Instruction *NewAnd = BinaryOperator::CreateAnd(I->getOperand(0), AndC);
326         InsertNewInstWith(NewAnd, *I);
327 
328         Constant *XorC =
329             ConstantInt::get(I->getType(), NewMask & XorRHS->getValue());
330         Instruction *NewXor = BinaryOperator::CreateXor(NewAnd, XorC);
331         return InsertNewInstWith(NewXor, *I);
332       }
333     }
334     break;
335   }
336   case Instruction::Select: {
337     if (SimplifyDemandedBits(I, 2, DemandedMask, RHSKnown, Depth + 1) ||
338         SimplifyDemandedBits(I, 1, DemandedMask, LHSKnown, Depth + 1))
339       return I;
340     assert(!RHSKnown.hasConflict() && "Bits known to be one AND zero?");
341     assert(!LHSKnown.hasConflict() && "Bits known to be one AND zero?");
342 
343     // If the operands are constants, see if we can simplify them.
344     // This is similar to ShrinkDemandedConstant, but for a select we want to
345     // try to keep the selected constants the same as icmp value constants, if
346     // we can. This helps not break apart (or helps put back together)
347     // canonical patterns like min and max.
348     auto CanonicalizeSelectConstant = [](Instruction *I, unsigned OpNo,
349                                          const APInt &DemandedMask) {
350       const APInt *SelC;
351       if (!match(I->getOperand(OpNo), m_APInt(SelC)))
352         return false;
353 
354       // Get the constant out of the ICmp, if there is one.
355       // Only try this when exactly 1 operand is a constant (if both operands
356       // are constant, the icmp should eventually simplify). Otherwise, we may
357       // invert the transform that reduces set bits and infinite-loop.
358       Value *X;
359       const APInt *CmpC;
360       ICmpInst::Predicate Pred;
361       if (!match(I->getOperand(0), m_ICmp(Pred, m_Value(X), m_APInt(CmpC))) ||
362           isa<Constant>(X) || CmpC->getBitWidth() != SelC->getBitWidth())
363         return ShrinkDemandedConstant(I, OpNo, DemandedMask);
364 
365       // If the constant is already the same as the ICmp, leave it as-is.
366       if (*CmpC == *SelC)
367         return false;
368       // If the constants are not already the same, but can be with the demand
369       // mask, use the constant value from the ICmp.
370       if ((*CmpC & DemandedMask) == (*SelC & DemandedMask)) {
371         I->setOperand(OpNo, ConstantInt::get(I->getType(), *CmpC));
372         return true;
373       }
374       return ShrinkDemandedConstant(I, OpNo, DemandedMask);
375     };
376     if (CanonicalizeSelectConstant(I, 1, DemandedMask) ||
377         CanonicalizeSelectConstant(I, 2, DemandedMask))
378       return I;
379 
380     // Only known if known in both the LHS and RHS.
381     Known = KnownBits::commonBits(LHSKnown, RHSKnown);
382     break;
383   }
384   case Instruction::Trunc: {
385     // If we do not demand the high bits of a right-shifted and truncated value,
386     // then we may be able to truncate it before the shift.
387     Value *X;
388     const APInt *C;
389     if (match(I->getOperand(0), m_OneUse(m_LShr(m_Value(X), m_APInt(C))))) {
390       // The shift amount must be valid (not poison) in the narrow type, and
391       // it must not be greater than the high bits demanded of the result.
392       if (C->ult(I->getType()->getScalarSizeInBits()) &&
393           C->ule(DemandedMask.countLeadingZeros())) {
394         // trunc (lshr X, C) --> lshr (trunc X), C
395         IRBuilderBase::InsertPointGuard Guard(Builder);
396         Builder.SetInsertPoint(I);
397         Value *Trunc = Builder.CreateTrunc(X, I->getType());
398         return Builder.CreateLShr(Trunc, C->getZExtValue());
399       }
400     }
401   }
402     LLVM_FALLTHROUGH;
403   case Instruction::ZExt: {
404     unsigned SrcBitWidth = I->getOperand(0)->getType()->getScalarSizeInBits();
405 
406     APInt InputDemandedMask = DemandedMask.zextOrTrunc(SrcBitWidth);
407     KnownBits InputKnown(SrcBitWidth);
408     if (SimplifyDemandedBits(I, 0, InputDemandedMask, InputKnown, Depth + 1))
409       return I;
410     assert(InputKnown.getBitWidth() == SrcBitWidth && "Src width changed?");
411     Known = InputKnown.zextOrTrunc(BitWidth);
412     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
413     break;
414   }
415   case Instruction::BitCast:
416     if (!I->getOperand(0)->getType()->isIntOrIntVectorTy())
417       return nullptr;  // vector->int or fp->int?
418 
419     if (VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
420       if (VectorType *SrcVTy =
421             dyn_cast<VectorType>(I->getOperand(0)->getType())) {
422         if (cast<FixedVectorType>(DstVTy)->getNumElements() !=
423             cast<FixedVectorType>(SrcVTy)->getNumElements())
424           // Don't touch a bitcast between vectors of different element counts.
425           return nullptr;
426       } else
427         // Don't touch a scalar-to-vector bitcast.
428         return nullptr;
429     } else if (I->getOperand(0)->getType()->isVectorTy())
430       // Don't touch a vector-to-scalar bitcast.
431       return nullptr;
432 
433     if (SimplifyDemandedBits(I, 0, DemandedMask, Known, Depth + 1))
434       return I;
435     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
436     break;
437   case Instruction::SExt: {
438     // Compute the bits in the result that are not present in the input.
439     unsigned SrcBitWidth = I->getOperand(0)->getType()->getScalarSizeInBits();
440 
441     APInt InputDemandedBits = DemandedMask.trunc(SrcBitWidth);
442 
443     // If any of the sign extended bits are demanded, we know that the sign
444     // bit is demanded.
445     if (DemandedMask.getActiveBits() > SrcBitWidth)
446       InputDemandedBits.setBit(SrcBitWidth-1);
447 
448     KnownBits InputKnown(SrcBitWidth);
449     if (SimplifyDemandedBits(I, 0, InputDemandedBits, InputKnown, Depth + 1))
450       return I;
451 
452     // If the input sign bit is known zero, or if the NewBits are not demanded
453     // convert this into a zero extension.
454     if (InputKnown.isNonNegative() ||
455         DemandedMask.getActiveBits() <= SrcBitWidth) {
456       // Convert to ZExt cast.
457       CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
458       return InsertNewInstWith(NewCast, *I);
459      }
460 
461     // If the sign bit of the input is known set or clear, then we know the
462     // top bits of the result.
463     Known = InputKnown.sext(BitWidth);
464     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
465     break;
466   }
467   case Instruction::Add:
468     if ((DemandedMask & 1) == 0) {
469       // If we do not need the low bit, try to convert bool math to logic:
470       // add iN (zext i1 X), (sext i1 Y) --> sext (~X & Y) to iN
471       Value *X, *Y;
472       if (match(I, m_c_Add(m_OneUse(m_ZExt(m_Value(X))),
473                            m_OneUse(m_SExt(m_Value(Y))))) &&
474           X->getType()->isIntOrIntVectorTy(1) && X->getType() == Y->getType()) {
475         // Truth table for inputs and output signbits:
476         //       X:0 | X:1
477         //      ----------
478         // Y:0  |  0 | 0 |
479         // Y:1  | -1 | 0 |
480         //      ----------
481         IRBuilderBase::InsertPointGuard Guard(Builder);
482         Builder.SetInsertPoint(I);
483         Value *AndNot = Builder.CreateAnd(Builder.CreateNot(X), Y);
484         return Builder.CreateSExt(AndNot, VTy);
485       }
486 
487       // add iN (sext i1 X), (sext i1 Y) --> sext (X | Y) to iN
488       // TODO: Relax the one-use checks because we are removing an instruction?
489       if (match(I, m_Add(m_OneUse(m_SExt(m_Value(X))),
490                          m_OneUse(m_SExt(m_Value(Y))))) &&
491           X->getType()->isIntOrIntVectorTy(1) && X->getType() == Y->getType()) {
492         // Truth table for inputs and output signbits:
493         //       X:0 | X:1
494         //      -----------
495         // Y:0  | -1 | -1 |
496         // Y:1  | -1 |  0 |
497         //      -----------
498         IRBuilderBase::InsertPointGuard Guard(Builder);
499         Builder.SetInsertPoint(I);
500         Value *Or = Builder.CreateOr(X, Y);
501         return Builder.CreateSExt(Or, VTy);
502       }
503     }
504     LLVM_FALLTHROUGH;
505   case Instruction::Sub: {
506     APInt DemandedFromOps;
507     if (simplifyOperandsBasedOnUnusedHighBits(DemandedFromOps))
508       return I;
509 
510     // If we are known to be adding/subtracting zeros to every bit below
511     // the highest demanded bit, we just return the other side.
512     if (DemandedFromOps.isSubsetOf(RHSKnown.Zero))
513       return I->getOperand(0);
514     // We can't do this with the LHS for subtraction, unless we are only
515     // demanding the LSB.
516     if ((I->getOpcode() == Instruction::Add || DemandedFromOps.isOne()) &&
517         DemandedFromOps.isSubsetOf(LHSKnown.Zero))
518       return I->getOperand(1);
519 
520     // Otherwise just compute the known bits of the result.
521     bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
522     Known = KnownBits::computeForAddSub(I->getOpcode() == Instruction::Add,
523                                         NSW, LHSKnown, RHSKnown);
524     break;
525   }
526   case Instruction::Mul: {
527     APInt DemandedFromOps;
528     if (simplifyOperandsBasedOnUnusedHighBits(DemandedFromOps))
529       return I;
530 
531     if (DemandedMask.isPowerOf2()) {
532       // The LSB of X*Y is set only if (X & 1) == 1 and (Y & 1) == 1.
533       // If we demand exactly one bit N and we have "X * (C' << N)" where C' is
534       // odd (has LSB set), then the left-shifted low bit of X is the answer.
535       unsigned CTZ = DemandedMask.countTrailingZeros();
536       const APInt *C;
537       if (match(I->getOperand(1), m_APInt(C)) &&
538           C->countTrailingZeros() == CTZ) {
539         Constant *ShiftC = ConstantInt::get(I->getType(), CTZ);
540         Instruction *Shl = BinaryOperator::CreateShl(I->getOperand(0), ShiftC);
541         return InsertNewInstWith(Shl, *I);
542       }
543     }
544     // For a squared value "X * X", the bottom 2 bits are 0 and X[0] because:
545     // X * X is odd iff X is odd.
546     // 'Quadratic Reciprocity': X * X -> 0 for bit[1]
547     if (I->getOperand(0) == I->getOperand(1) && DemandedMask.ult(4)) {
548       Constant *One = ConstantInt::get(VTy, 1);
549       Instruction *And1 = BinaryOperator::CreateAnd(I->getOperand(0), One);
550       return InsertNewInstWith(And1, *I);
551     }
552 
553     computeKnownBits(I, Known, Depth, CxtI);
554     break;
555   }
556   case Instruction::Shl: {
557     const APInt *SA;
558     if (match(I->getOperand(1), m_APInt(SA))) {
559       const APInt *ShrAmt;
560       if (match(I->getOperand(0), m_Shr(m_Value(), m_APInt(ShrAmt))))
561         if (Instruction *Shr = dyn_cast<Instruction>(I->getOperand(0)))
562           if (Value *R = simplifyShrShlDemandedBits(Shr, *ShrAmt, I, *SA,
563                                                     DemandedMask, Known))
564             return R;
565 
566       // TODO: If we only want bits that already match the signbit then we don't
567       // need to shift.
568 
569       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth-1);
570       APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
571 
572       // If the shift is NUW/NSW, then it does demand the high bits.
573       ShlOperator *IOp = cast<ShlOperator>(I);
574       if (IOp->hasNoSignedWrap())
575         DemandedMaskIn.setHighBits(ShiftAmt+1);
576       else if (IOp->hasNoUnsignedWrap())
577         DemandedMaskIn.setHighBits(ShiftAmt);
578 
579       if (SimplifyDemandedBits(I, 0, DemandedMaskIn, Known, Depth + 1))
580         return I;
581       assert(!Known.hasConflict() && "Bits known to be one AND zero?");
582 
583       bool SignBitZero = Known.Zero.isSignBitSet();
584       bool SignBitOne = Known.One.isSignBitSet();
585       Known.Zero <<= ShiftAmt;
586       Known.One  <<= ShiftAmt;
587       // low bits known zero.
588       if (ShiftAmt)
589         Known.Zero.setLowBits(ShiftAmt);
590 
591       // If this shift has "nsw" keyword, then the result is either a poison
592       // value or has the same sign bit as the first operand.
593       if (IOp->hasNoSignedWrap()) {
594         if (SignBitZero)
595           Known.Zero.setSignBit();
596         else if (SignBitOne)
597           Known.One.setSignBit();
598         if (Known.hasConflict())
599           return UndefValue::get(I->getType());
600       }
601     } else {
602       // This is a variable shift, so we can't shift the demand mask by a known
603       // amount. But if we are not demanding high bits, then we are not
604       // demanding those bits from the pre-shifted operand either.
605       if (unsigned CTLZ = DemandedMask.countLeadingZeros()) {
606         APInt DemandedFromOp(APInt::getLowBitsSet(BitWidth, BitWidth - CTLZ));
607         if (SimplifyDemandedBits(I, 0, DemandedFromOp, Known, Depth + 1)) {
608           // We can't guarantee that nsw/nuw hold after simplifying the operand.
609           I->dropPoisonGeneratingFlags();
610           return I;
611         }
612       }
613       computeKnownBits(I, Known, Depth, CxtI);
614     }
615     break;
616   }
617   case Instruction::LShr: {
618     const APInt *SA;
619     if (match(I->getOperand(1), m_APInt(SA))) {
620       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth-1);
621 
622       // If we are just demanding the shifted sign bit and below, then this can
623       // be treated as an ASHR in disguise.
624       if (DemandedMask.countLeadingZeros() >= ShiftAmt) {
625         // If we only want bits that already match the signbit then we don't
626         // need to shift.
627         unsigned NumHiDemandedBits =
628             BitWidth - DemandedMask.countTrailingZeros();
629         unsigned SignBits =
630             ComputeNumSignBits(I->getOperand(0), Depth + 1, CxtI);
631         if (SignBits >= NumHiDemandedBits)
632           return I->getOperand(0);
633 
634         // If we can pre-shift a left-shifted constant to the right without
635         // losing any low bits (we already know we don't demand the high bits),
636         // then eliminate the right-shift:
637         // (C << X) >> RightShiftAmtC --> (C >> RightShiftAmtC) << X
638         Value *X;
639         Constant *C;
640         if (match(I->getOperand(0), m_Shl(m_ImmConstant(C), m_Value(X)))) {
641           Constant *RightShiftAmtC = ConstantInt::get(VTy, ShiftAmt);
642           Constant *NewC = ConstantExpr::getLShr(C, RightShiftAmtC);
643           if (ConstantExpr::getShl(NewC, RightShiftAmtC) == C) {
644             Instruction *Shl = BinaryOperator::CreateShl(NewC, X);
645             return InsertNewInstWith(Shl, *I);
646           }
647         }
648       }
649 
650       // Unsigned shift right.
651       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
652 
653       // If the shift is exact, then it does demand the low bits (and knows that
654       // they are zero).
655       if (cast<LShrOperator>(I)->isExact())
656         DemandedMaskIn.setLowBits(ShiftAmt);
657 
658       if (SimplifyDemandedBits(I, 0, DemandedMaskIn, Known, Depth + 1))
659         return I;
660       assert(!Known.hasConflict() && "Bits known to be one AND zero?");
661       Known.Zero.lshrInPlace(ShiftAmt);
662       Known.One.lshrInPlace(ShiftAmt);
663       if (ShiftAmt)
664         Known.Zero.setHighBits(ShiftAmt);  // high bits known zero.
665     } else {
666       computeKnownBits(I, Known, Depth, CxtI);
667     }
668     break;
669   }
670   case Instruction::AShr: {
671     unsigned SignBits = ComputeNumSignBits(I->getOperand(0), Depth + 1, CxtI);
672 
673     // If we only want bits that already match the signbit then we don't need
674     // to shift.
675     unsigned NumHiDemandedBits = BitWidth - DemandedMask.countTrailingZeros();
676     if (SignBits >= NumHiDemandedBits)
677       return I->getOperand(0);
678 
679     // If this is an arithmetic shift right and only the low-bit is set, we can
680     // always convert this into a logical shr, even if the shift amount is
681     // variable.  The low bit of the shift cannot be an input sign bit unless
682     // the shift amount is >= the size of the datatype, which is undefined.
683     if (DemandedMask.isOne()) {
684       // Perform the logical shift right.
685       Instruction *NewVal = BinaryOperator::CreateLShr(
686                         I->getOperand(0), I->getOperand(1), I->getName());
687       return InsertNewInstWith(NewVal, *I);
688     }
689 
690     const APInt *SA;
691     if (match(I->getOperand(1), m_APInt(SA))) {
692       uint32_t ShiftAmt = SA->getLimitedValue(BitWidth-1);
693 
694       // Signed shift right.
695       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
696       // If any of the high bits are demanded, we should set the sign bit as
697       // demanded.
698       if (DemandedMask.countLeadingZeros() <= ShiftAmt)
699         DemandedMaskIn.setSignBit();
700 
701       // If the shift is exact, then it does demand the low bits (and knows that
702       // they are zero).
703       if (cast<AShrOperator>(I)->isExact())
704         DemandedMaskIn.setLowBits(ShiftAmt);
705 
706       if (SimplifyDemandedBits(I, 0, DemandedMaskIn, Known, Depth + 1))
707         return I;
708 
709       assert(!Known.hasConflict() && "Bits known to be one AND zero?");
710       // Compute the new bits that are at the top now plus sign bits.
711       APInt HighBits(APInt::getHighBitsSet(
712           BitWidth, std::min(SignBits + ShiftAmt - 1, BitWidth)));
713       Known.Zero.lshrInPlace(ShiftAmt);
714       Known.One.lshrInPlace(ShiftAmt);
715 
716       // If the input sign bit is known to be zero, or if none of the top bits
717       // are demanded, turn this into an unsigned shift right.
718       assert(BitWidth > ShiftAmt && "Shift amount not saturated?");
719       if (Known.Zero[BitWidth-ShiftAmt-1] ||
720           !DemandedMask.intersects(HighBits)) {
721         BinaryOperator *LShr = BinaryOperator::CreateLShr(I->getOperand(0),
722                                                           I->getOperand(1));
723         LShr->setIsExact(cast<BinaryOperator>(I)->isExact());
724         return InsertNewInstWith(LShr, *I);
725       } else if (Known.One[BitWidth-ShiftAmt-1]) { // New bits are known one.
726         Known.One |= HighBits;
727       }
728     } else {
729       computeKnownBits(I, Known, Depth, CxtI);
730     }
731     break;
732   }
733   case Instruction::UDiv: {
734     // UDiv doesn't demand low bits that are zero in the divisor.
735     const APInt *SA;
736     if (match(I->getOperand(1), m_APInt(SA))) {
737       // If the shift is exact, then it does demand the low bits.
738       if (cast<UDivOperator>(I)->isExact())
739         break;
740 
741       // FIXME: Take the demanded mask of the result into account.
742       unsigned RHSTrailingZeros = SA->countTrailingZeros();
743       APInt DemandedMaskIn =
744           APInt::getHighBitsSet(BitWidth, BitWidth - RHSTrailingZeros);
745       if (SimplifyDemandedBits(I, 0, DemandedMaskIn, LHSKnown, Depth + 1))
746         return I;
747 
748       // Propagate zero bits from the input.
749       Known.Zero.setHighBits(std::min(
750           BitWidth, LHSKnown.Zero.countLeadingOnes() + RHSTrailingZeros));
751     } else {
752       computeKnownBits(I, Known, Depth, CxtI);
753     }
754     break;
755   }
756   case Instruction::SRem: {
757     const APInt *Rem;
758     if (match(I->getOperand(1), m_APInt(Rem))) {
759       // X % -1 demands all the bits because we don't want to introduce
760       // INT_MIN % -1 (== undef) by accident.
761       if (Rem->isAllOnes())
762         break;
763       APInt RA = Rem->abs();
764       if (RA.isPowerOf2()) {
765         if (DemandedMask.ult(RA))    // srem won't affect demanded bits
766           return I->getOperand(0);
767 
768         APInt LowBits = RA - 1;
769         APInt Mask2 = LowBits | APInt::getSignMask(BitWidth);
770         if (SimplifyDemandedBits(I, 0, Mask2, LHSKnown, Depth + 1))
771           return I;
772 
773         // The low bits of LHS are unchanged by the srem.
774         Known.Zero = LHSKnown.Zero & LowBits;
775         Known.One = LHSKnown.One & LowBits;
776 
777         // If LHS is non-negative or has all low bits zero, then the upper bits
778         // are all zero.
779         if (LHSKnown.isNonNegative() || LowBits.isSubsetOf(LHSKnown.Zero))
780           Known.Zero |= ~LowBits;
781 
782         // If LHS is negative and not all low bits are zero, then the upper bits
783         // are all one.
784         if (LHSKnown.isNegative() && LowBits.intersects(LHSKnown.One))
785           Known.One |= ~LowBits;
786 
787         assert(!Known.hasConflict() && "Bits known to be one AND zero?");
788         break;
789       }
790     }
791 
792     // The sign bit is the LHS's sign bit, except when the result of the
793     // remainder is zero.
794     if (DemandedMask.isSignBitSet()) {
795       computeKnownBits(I->getOperand(0), LHSKnown, Depth + 1, CxtI);
796       // If it's known zero, our sign bit is also zero.
797       if (LHSKnown.isNonNegative())
798         Known.makeNonNegative();
799     }
800     break;
801   }
802   case Instruction::URem: {
803     KnownBits Known2(BitWidth);
804     APInt AllOnes = APInt::getAllOnes(BitWidth);
805     if (SimplifyDemandedBits(I, 0, AllOnes, Known2, Depth + 1) ||
806         SimplifyDemandedBits(I, 1, AllOnes, Known2, Depth + 1))
807       return I;
808 
809     unsigned Leaders = Known2.countMinLeadingZeros();
810     Known.Zero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
811     break;
812   }
813   case Instruction::Call: {
814     bool KnownBitsComputed = false;
815     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
816       switch (II->getIntrinsicID()) {
817       case Intrinsic::abs: {
818         if (DemandedMask == 1)
819           return II->getArgOperand(0);
820         break;
821       }
822       case Intrinsic::ctpop: {
823         // Checking if the number of clear bits is odd (parity)? If the type has
824         // an even number of bits, that's the same as checking if the number of
825         // set bits is odd, so we can eliminate the 'not' op.
826         Value *X;
827         if (DemandedMask == 1 && VTy->getScalarSizeInBits() % 2 == 0 &&
828             match(II->getArgOperand(0), m_Not(m_Value(X)))) {
829           Function *Ctpop = Intrinsic::getDeclaration(
830               II->getModule(), Intrinsic::ctpop, II->getType());
831           return InsertNewInstWith(CallInst::Create(Ctpop, {X}), *I);
832         }
833         break;
834       }
835       case Intrinsic::bswap: {
836         // If the only bits demanded come from one byte of the bswap result,
837         // just shift the input byte into position to eliminate the bswap.
838         unsigned NLZ = DemandedMask.countLeadingZeros();
839         unsigned NTZ = DemandedMask.countTrailingZeros();
840 
841         // Round NTZ down to the next byte.  If we have 11 trailing zeros, then
842         // we need all the bits down to bit 8.  Likewise, round NLZ.  If we
843         // have 14 leading zeros, round to 8.
844         NLZ = alignDown(NLZ, 8);
845         NTZ = alignDown(NTZ, 8);
846         // If we need exactly one byte, we can do this transformation.
847         if (BitWidth - NLZ - NTZ == 8) {
848           // Replace this with either a left or right shift to get the byte into
849           // the right place.
850           Instruction *NewVal;
851           if (NLZ > NTZ)
852             NewVal = BinaryOperator::CreateLShr(
853                 II->getArgOperand(0),
854                 ConstantInt::get(I->getType(), NLZ - NTZ));
855           else
856             NewVal = BinaryOperator::CreateShl(
857                 II->getArgOperand(0),
858                 ConstantInt::get(I->getType(), NTZ - NLZ));
859           NewVal->takeName(I);
860           return InsertNewInstWith(NewVal, *I);
861         }
862         break;
863       }
864       case Intrinsic::fshr:
865       case Intrinsic::fshl: {
866         const APInt *SA;
867         if (!match(I->getOperand(2), m_APInt(SA)))
868           break;
869 
870         // Normalize to funnel shift left. APInt shifts of BitWidth are well-
871         // defined, so no need to special-case zero shifts here.
872         uint64_t ShiftAmt = SA->urem(BitWidth);
873         if (II->getIntrinsicID() == Intrinsic::fshr)
874           ShiftAmt = BitWidth - ShiftAmt;
875 
876         APInt DemandedMaskLHS(DemandedMask.lshr(ShiftAmt));
877         APInt DemandedMaskRHS(DemandedMask.shl(BitWidth - ShiftAmt));
878         if (SimplifyDemandedBits(I, 0, DemandedMaskLHS, LHSKnown, Depth + 1) ||
879             SimplifyDemandedBits(I, 1, DemandedMaskRHS, RHSKnown, Depth + 1))
880           return I;
881 
882         Known.Zero = LHSKnown.Zero.shl(ShiftAmt) |
883                      RHSKnown.Zero.lshr(BitWidth - ShiftAmt);
884         Known.One = LHSKnown.One.shl(ShiftAmt) |
885                     RHSKnown.One.lshr(BitWidth - ShiftAmt);
886         KnownBitsComputed = true;
887         break;
888       }
889       case Intrinsic::umax: {
890         // UMax(A, C) == A if ...
891         // The lowest non-zero bit of DemandMask is higher than the highest
892         // non-zero bit of C.
893         const APInt *C;
894         unsigned CTZ = DemandedMask.countTrailingZeros();
895         if (match(II->getArgOperand(1), m_APInt(C)) &&
896             CTZ >= C->getActiveBits())
897           return II->getArgOperand(0);
898         break;
899       }
900       case Intrinsic::umin: {
901         // UMin(A, C) == A if ...
902         // The lowest non-zero bit of DemandMask is higher than the highest
903         // non-one bit of C.
904         // This comes from using DeMorgans on the above umax example.
905         const APInt *C;
906         unsigned CTZ = DemandedMask.countTrailingZeros();
907         if (match(II->getArgOperand(1), m_APInt(C)) &&
908             CTZ >= C->getBitWidth() - C->countLeadingOnes())
909           return II->getArgOperand(0);
910         break;
911       }
912       default: {
913         // Handle target specific intrinsics
914         Optional<Value *> V = targetSimplifyDemandedUseBitsIntrinsic(
915             *II, DemandedMask, Known, KnownBitsComputed);
916         if (V.hasValue())
917           return V.getValue();
918         break;
919       }
920       }
921     }
922 
923     if (!KnownBitsComputed)
924       computeKnownBits(V, Known, Depth, CxtI);
925     break;
926   }
927   }
928 
929   // If the client is only demanding bits that we know, return the known
930   // constant.
931   if (DemandedMask.isSubsetOf(Known.Zero|Known.One))
932     return Constant::getIntegerValue(VTy, Known.One);
933   return nullptr;
934 }
935 
936 /// Helper routine of SimplifyDemandedUseBits. It computes Known
937 /// bits. It also tries to handle simplifications that can be done based on
938 /// DemandedMask, but without modifying the Instruction.
939 Value *InstCombinerImpl::SimplifyMultipleUseDemandedBits(
940     Instruction *I, const APInt &DemandedMask, KnownBits &Known, unsigned Depth,
941     Instruction *CxtI) {
942   unsigned BitWidth = DemandedMask.getBitWidth();
943   Type *ITy = I->getType();
944 
945   KnownBits LHSKnown(BitWidth);
946   KnownBits RHSKnown(BitWidth);
947 
948   // Despite the fact that we can't simplify this instruction in all User's
949   // context, we can at least compute the known bits, and we can
950   // do simplifications that apply to *just* the one user if we know that
951   // this instruction has a simpler value in that context.
952   switch (I->getOpcode()) {
953   case Instruction::And: {
954     // If either the LHS or the RHS are Zero, the result is zero.
955     computeKnownBits(I->getOperand(1), RHSKnown, Depth + 1, CxtI);
956     computeKnownBits(I->getOperand(0), LHSKnown, Depth + 1,
957                      CxtI);
958 
959     Known = LHSKnown & RHSKnown;
960 
961     // If the client is only demanding bits that we know, return the known
962     // constant.
963     if (DemandedMask.isSubsetOf(Known.Zero | Known.One))
964       return Constant::getIntegerValue(ITy, Known.One);
965 
966     // If all of the demanded bits are known 1 on one side, return the other.
967     // These bits cannot contribute to the result of the 'and' in this
968     // context.
969     if (DemandedMask.isSubsetOf(LHSKnown.Zero | RHSKnown.One))
970       return I->getOperand(0);
971     if (DemandedMask.isSubsetOf(RHSKnown.Zero | LHSKnown.One))
972       return I->getOperand(1);
973 
974     break;
975   }
976   case Instruction::Or: {
977     // We can simplify (X|Y) -> X or Y in the user's context if we know that
978     // only bits from X or Y are demanded.
979 
980     // If either the LHS or the RHS are One, the result is One.
981     computeKnownBits(I->getOperand(1), RHSKnown, Depth + 1, CxtI);
982     computeKnownBits(I->getOperand(0), LHSKnown, Depth + 1,
983                      CxtI);
984 
985     Known = LHSKnown | RHSKnown;
986 
987     // If the client is only demanding bits that we know, return the known
988     // constant.
989     if (DemandedMask.isSubsetOf(Known.Zero | Known.One))
990       return Constant::getIntegerValue(ITy, Known.One);
991 
992     // If all of the demanded bits are known zero on one side, return the
993     // other.  These bits cannot contribute to the result of the 'or' in this
994     // context.
995     if (DemandedMask.isSubsetOf(LHSKnown.One | RHSKnown.Zero))
996       return I->getOperand(0);
997     if (DemandedMask.isSubsetOf(RHSKnown.One | LHSKnown.Zero))
998       return I->getOperand(1);
999 
1000     break;
1001   }
1002   case Instruction::Xor: {
1003     // We can simplify (X^Y) -> X or Y in the user's context if we know that
1004     // only bits from X or Y are demanded.
1005 
1006     computeKnownBits(I->getOperand(1), RHSKnown, Depth + 1, CxtI);
1007     computeKnownBits(I->getOperand(0), LHSKnown, Depth + 1,
1008                      CxtI);
1009 
1010     Known = LHSKnown ^ RHSKnown;
1011 
1012     // If the client is only demanding bits that we know, return the known
1013     // constant.
1014     if (DemandedMask.isSubsetOf(Known.Zero | Known.One))
1015       return Constant::getIntegerValue(ITy, Known.One);
1016 
1017     // If all of the demanded bits are known zero on one side, return the
1018     // other.
1019     if (DemandedMask.isSubsetOf(RHSKnown.Zero))
1020       return I->getOperand(0);
1021     if (DemandedMask.isSubsetOf(LHSKnown.Zero))
1022       return I->getOperand(1);
1023 
1024     break;
1025   }
1026   case Instruction::AShr: {
1027     // Compute the Known bits to simplify things downstream.
1028     computeKnownBits(I, Known, Depth, CxtI);
1029 
1030     // If this user is only demanding bits that we know, return the known
1031     // constant.
1032     if (DemandedMask.isSubsetOf(Known.Zero | Known.One))
1033       return Constant::getIntegerValue(ITy, Known.One);
1034 
1035     // If the right shift operand 0 is a result of a left shift by the same
1036     // amount, this is probably a zero/sign extension, which may be unnecessary,
1037     // if we do not demand any of the new sign bits. So, return the original
1038     // operand instead.
1039     const APInt *ShiftRC;
1040     const APInt *ShiftLC;
1041     Value *X;
1042     unsigned BitWidth = DemandedMask.getBitWidth();
1043     if (match(I,
1044               m_AShr(m_Shl(m_Value(X), m_APInt(ShiftLC)), m_APInt(ShiftRC))) &&
1045         ShiftLC == ShiftRC && ShiftLC->ult(BitWidth) &&
1046         DemandedMask.isSubsetOf(APInt::getLowBitsSet(
1047             BitWidth, BitWidth - ShiftRC->getZExtValue()))) {
1048       return X;
1049     }
1050 
1051     break;
1052   }
1053   default:
1054     // Compute the Known bits to simplify things downstream.
1055     computeKnownBits(I, Known, Depth, CxtI);
1056 
1057     // If this user is only demanding bits that we know, return the known
1058     // constant.
1059     if (DemandedMask.isSubsetOf(Known.Zero|Known.One))
1060       return Constant::getIntegerValue(ITy, Known.One);
1061 
1062     break;
1063   }
1064 
1065   return nullptr;
1066 }
1067 
1068 /// Helper routine of SimplifyDemandedUseBits. It tries to simplify
1069 /// "E1 = (X lsr C1) << C2", where the C1 and C2 are constant, into
1070 /// "E2 = X << (C2 - C1)" or "E2 = X >> (C1 - C2)", depending on the sign
1071 /// of "C2-C1".
1072 ///
1073 /// Suppose E1 and E2 are generally different in bits S={bm, bm+1,
1074 /// ..., bn}, without considering the specific value X is holding.
1075 /// This transformation is legal iff one of following conditions is hold:
1076 ///  1) All the bit in S are 0, in this case E1 == E2.
1077 ///  2) We don't care those bits in S, per the input DemandedMask.
1078 ///  3) Combination of 1) and 2). Some bits in S are 0, and we don't care the
1079 ///     rest bits.
1080 ///
1081 /// Currently we only test condition 2).
1082 ///
1083 /// As with SimplifyDemandedUseBits, it returns NULL if the simplification was
1084 /// not successful.
1085 Value *InstCombinerImpl::simplifyShrShlDemandedBits(
1086     Instruction *Shr, const APInt &ShrOp1, Instruction *Shl,
1087     const APInt &ShlOp1, const APInt &DemandedMask, KnownBits &Known) {
1088   if (!ShlOp1 || !ShrOp1)
1089     return nullptr; // No-op.
1090 
1091   Value *VarX = Shr->getOperand(0);
1092   Type *Ty = VarX->getType();
1093   unsigned BitWidth = Ty->getScalarSizeInBits();
1094   if (ShlOp1.uge(BitWidth) || ShrOp1.uge(BitWidth))
1095     return nullptr; // Undef.
1096 
1097   unsigned ShlAmt = ShlOp1.getZExtValue();
1098   unsigned ShrAmt = ShrOp1.getZExtValue();
1099 
1100   Known.One.clearAllBits();
1101   Known.Zero.setLowBits(ShlAmt - 1);
1102   Known.Zero &= DemandedMask;
1103 
1104   APInt BitMask1(APInt::getAllOnes(BitWidth));
1105   APInt BitMask2(APInt::getAllOnes(BitWidth));
1106 
1107   bool isLshr = (Shr->getOpcode() == Instruction::LShr);
1108   BitMask1 = isLshr ? (BitMask1.lshr(ShrAmt) << ShlAmt) :
1109                       (BitMask1.ashr(ShrAmt) << ShlAmt);
1110 
1111   if (ShrAmt <= ShlAmt) {
1112     BitMask2 <<= (ShlAmt - ShrAmt);
1113   } else {
1114     BitMask2 = isLshr ? BitMask2.lshr(ShrAmt - ShlAmt):
1115                         BitMask2.ashr(ShrAmt - ShlAmt);
1116   }
1117 
1118   // Check if condition-2 (see the comment to this function) is satified.
1119   if ((BitMask1 & DemandedMask) == (BitMask2 & DemandedMask)) {
1120     if (ShrAmt == ShlAmt)
1121       return VarX;
1122 
1123     if (!Shr->hasOneUse())
1124       return nullptr;
1125 
1126     BinaryOperator *New;
1127     if (ShrAmt < ShlAmt) {
1128       Constant *Amt = ConstantInt::get(VarX->getType(), ShlAmt - ShrAmt);
1129       New = BinaryOperator::CreateShl(VarX, Amt);
1130       BinaryOperator *Orig = cast<BinaryOperator>(Shl);
1131       New->setHasNoSignedWrap(Orig->hasNoSignedWrap());
1132       New->setHasNoUnsignedWrap(Orig->hasNoUnsignedWrap());
1133     } else {
1134       Constant *Amt = ConstantInt::get(VarX->getType(), ShrAmt - ShlAmt);
1135       New = isLshr ? BinaryOperator::CreateLShr(VarX, Amt) :
1136                      BinaryOperator::CreateAShr(VarX, Amt);
1137       if (cast<BinaryOperator>(Shr)->isExact())
1138         New->setIsExact(true);
1139     }
1140 
1141     return InsertNewInstWith(New, *Shl);
1142   }
1143 
1144   return nullptr;
1145 }
1146 
1147 /// The specified value produces a vector with any number of elements.
1148 /// This method analyzes which elements of the operand are undef or poison and
1149 /// returns that information in UndefElts.
1150 ///
1151 /// DemandedElts contains the set of elements that are actually used by the
1152 /// caller, and by default (AllowMultipleUsers equals false) the value is
1153 /// simplified only if it has a single caller. If AllowMultipleUsers is set
1154 /// to true, DemandedElts refers to the union of sets of elements that are
1155 /// used by all callers.
1156 ///
1157 /// If the information about demanded elements can be used to simplify the
1158 /// operation, the operation is simplified, then the resultant value is
1159 /// returned.  This returns null if no change was made.
1160 Value *InstCombinerImpl::SimplifyDemandedVectorElts(Value *V,
1161                                                     APInt DemandedElts,
1162                                                     APInt &UndefElts,
1163                                                     unsigned Depth,
1164                                                     bool AllowMultipleUsers) {
1165   // Cannot analyze scalable type. The number of vector elements is not a
1166   // compile-time constant.
1167   if (isa<ScalableVectorType>(V->getType()))
1168     return nullptr;
1169 
1170   unsigned VWidth = cast<FixedVectorType>(V->getType())->getNumElements();
1171   APInt EltMask(APInt::getAllOnes(VWidth));
1172   assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
1173 
1174   if (match(V, m_Undef())) {
1175     // If the entire vector is undef or poison, just return this info.
1176     UndefElts = EltMask;
1177     return nullptr;
1178   }
1179 
1180   if (DemandedElts.isZero()) { // If nothing is demanded, provide poison.
1181     UndefElts = EltMask;
1182     return PoisonValue::get(V->getType());
1183   }
1184 
1185   UndefElts = 0;
1186 
1187   if (auto *C = dyn_cast<Constant>(V)) {
1188     // Check if this is identity. If so, return 0 since we are not simplifying
1189     // anything.
1190     if (DemandedElts.isAllOnes())
1191       return nullptr;
1192 
1193     Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1194     Constant *Poison = PoisonValue::get(EltTy);
1195     SmallVector<Constant*, 16> Elts;
1196     for (unsigned i = 0; i != VWidth; ++i) {
1197       if (!DemandedElts[i]) {   // If not demanded, set to poison.
1198         Elts.push_back(Poison);
1199         UndefElts.setBit(i);
1200         continue;
1201       }
1202 
1203       Constant *Elt = C->getAggregateElement(i);
1204       if (!Elt) return nullptr;
1205 
1206       Elts.push_back(Elt);
1207       if (isa<UndefValue>(Elt))   // Already undef or poison.
1208         UndefElts.setBit(i);
1209     }
1210 
1211     // If we changed the constant, return it.
1212     Constant *NewCV = ConstantVector::get(Elts);
1213     return NewCV != C ? NewCV : nullptr;
1214   }
1215 
1216   // Limit search depth.
1217   if (Depth == 10)
1218     return nullptr;
1219 
1220   if (!AllowMultipleUsers) {
1221     // If multiple users are using the root value, proceed with
1222     // simplification conservatively assuming that all elements
1223     // are needed.
1224     if (!V->hasOneUse()) {
1225       // Quit if we find multiple users of a non-root value though.
1226       // They'll be handled when it's their turn to be visited by
1227       // the main instcombine process.
1228       if (Depth != 0)
1229         // TODO: Just compute the UndefElts information recursively.
1230         return nullptr;
1231 
1232       // Conservatively assume that all elements are needed.
1233       DemandedElts = EltMask;
1234     }
1235   }
1236 
1237   Instruction *I = dyn_cast<Instruction>(V);
1238   if (!I) return nullptr;        // Only analyze instructions.
1239 
1240   bool MadeChange = false;
1241   auto simplifyAndSetOp = [&](Instruction *Inst, unsigned OpNum,
1242                               APInt Demanded, APInt &Undef) {
1243     auto *II = dyn_cast<IntrinsicInst>(Inst);
1244     Value *Op = II ? II->getArgOperand(OpNum) : Inst->getOperand(OpNum);
1245     if (Value *V = SimplifyDemandedVectorElts(Op, Demanded, Undef, Depth + 1)) {
1246       replaceOperand(*Inst, OpNum, V);
1247       MadeChange = true;
1248     }
1249   };
1250 
1251   APInt UndefElts2(VWidth, 0);
1252   APInt UndefElts3(VWidth, 0);
1253   switch (I->getOpcode()) {
1254   default: break;
1255 
1256   case Instruction::GetElementPtr: {
1257     // The LangRef requires that struct geps have all constant indices.  As
1258     // such, we can't convert any operand to partial undef.
1259     auto mayIndexStructType = [](GetElementPtrInst &GEP) {
1260       for (auto I = gep_type_begin(GEP), E = gep_type_end(GEP);
1261            I != E; I++)
1262         if (I.isStruct())
1263           return true;
1264       return false;
1265     };
1266     if (mayIndexStructType(cast<GetElementPtrInst>(*I)))
1267       break;
1268 
1269     // Conservatively track the demanded elements back through any vector
1270     // operands we may have.  We know there must be at least one, or we
1271     // wouldn't have a vector result to get here. Note that we intentionally
1272     // merge the undef bits here since gepping with either an poison base or
1273     // index results in poison.
1274     for (unsigned i = 0; i < I->getNumOperands(); i++) {
1275       if (i == 0 ? match(I->getOperand(i), m_Undef())
1276                  : match(I->getOperand(i), m_Poison())) {
1277         // If the entire vector is undefined, just return this info.
1278         UndefElts = EltMask;
1279         return nullptr;
1280       }
1281       if (I->getOperand(i)->getType()->isVectorTy()) {
1282         APInt UndefEltsOp(VWidth, 0);
1283         simplifyAndSetOp(I, i, DemandedElts, UndefEltsOp);
1284         // gep(x, undef) is not undef, so skip considering idx ops here
1285         // Note that we could propagate poison, but we can't distinguish between
1286         // undef & poison bits ATM
1287         if (i == 0)
1288           UndefElts |= UndefEltsOp;
1289       }
1290     }
1291 
1292     break;
1293   }
1294   case Instruction::InsertElement: {
1295     // If this is a variable index, we don't know which element it overwrites.
1296     // demand exactly the same input as we produce.
1297     ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1298     if (!Idx) {
1299       // Note that we can't propagate undef elt info, because we don't know
1300       // which elt is getting updated.
1301       simplifyAndSetOp(I, 0, DemandedElts, UndefElts2);
1302       break;
1303     }
1304 
1305     // The element inserted overwrites whatever was there, so the input demanded
1306     // set is simpler than the output set.
1307     unsigned IdxNo = Idx->getZExtValue();
1308     APInt PreInsertDemandedElts = DemandedElts;
1309     if (IdxNo < VWidth)
1310       PreInsertDemandedElts.clearBit(IdxNo);
1311 
1312     // If we only demand the element that is being inserted and that element
1313     // was extracted from the same index in another vector with the same type,
1314     // replace this insert with that other vector.
1315     // Note: This is attempted before the call to simplifyAndSetOp because that
1316     //       may change UndefElts to a value that does not match with Vec.
1317     Value *Vec;
1318     if (PreInsertDemandedElts == 0 &&
1319         match(I->getOperand(1),
1320               m_ExtractElt(m_Value(Vec), m_SpecificInt(IdxNo))) &&
1321         Vec->getType() == I->getType()) {
1322       return Vec;
1323     }
1324 
1325     simplifyAndSetOp(I, 0, PreInsertDemandedElts, UndefElts);
1326 
1327     // If this is inserting an element that isn't demanded, remove this
1328     // insertelement.
1329     if (IdxNo >= VWidth || !DemandedElts[IdxNo]) {
1330       Worklist.push(I);
1331       return I->getOperand(0);
1332     }
1333 
1334     // The inserted element is defined.
1335     UndefElts.clearBit(IdxNo);
1336     break;
1337   }
1338   case Instruction::ShuffleVector: {
1339     auto *Shuffle = cast<ShuffleVectorInst>(I);
1340     assert(Shuffle->getOperand(0)->getType() ==
1341            Shuffle->getOperand(1)->getType() &&
1342            "Expected shuffle operands to have same type");
1343     unsigned OpWidth = cast<FixedVectorType>(Shuffle->getOperand(0)->getType())
1344                            ->getNumElements();
1345     // Handle trivial case of a splat. Only check the first element of LHS
1346     // operand.
1347     if (all_of(Shuffle->getShuffleMask(), [](int Elt) { return Elt == 0; }) &&
1348         DemandedElts.isAllOnes()) {
1349       if (!match(I->getOperand(1), m_Undef())) {
1350         I->setOperand(1, PoisonValue::get(I->getOperand(1)->getType()));
1351         MadeChange = true;
1352       }
1353       APInt LeftDemanded(OpWidth, 1);
1354       APInt LHSUndefElts(OpWidth, 0);
1355       simplifyAndSetOp(I, 0, LeftDemanded, LHSUndefElts);
1356       if (LHSUndefElts[0])
1357         UndefElts = EltMask;
1358       else
1359         UndefElts.clearAllBits();
1360       break;
1361     }
1362 
1363     APInt LeftDemanded(OpWidth, 0), RightDemanded(OpWidth, 0);
1364     for (unsigned i = 0; i < VWidth; i++) {
1365       if (DemandedElts[i]) {
1366         unsigned MaskVal = Shuffle->getMaskValue(i);
1367         if (MaskVal != -1u) {
1368           assert(MaskVal < OpWidth * 2 &&
1369                  "shufflevector mask index out of range!");
1370           if (MaskVal < OpWidth)
1371             LeftDemanded.setBit(MaskVal);
1372           else
1373             RightDemanded.setBit(MaskVal - OpWidth);
1374         }
1375       }
1376     }
1377 
1378     APInt LHSUndefElts(OpWidth, 0);
1379     simplifyAndSetOp(I, 0, LeftDemanded, LHSUndefElts);
1380 
1381     APInt RHSUndefElts(OpWidth, 0);
1382     simplifyAndSetOp(I, 1, RightDemanded, RHSUndefElts);
1383 
1384     // If this shuffle does not change the vector length and the elements
1385     // demanded by this shuffle are an identity mask, then this shuffle is
1386     // unnecessary.
1387     //
1388     // We are assuming canonical form for the mask, so the source vector is
1389     // operand 0 and operand 1 is not used.
1390     //
1391     // Note that if an element is demanded and this shuffle mask is undefined
1392     // for that element, then the shuffle is not considered an identity
1393     // operation. The shuffle prevents poison from the operand vector from
1394     // leaking to the result by replacing poison with an undefined value.
1395     if (VWidth == OpWidth) {
1396       bool IsIdentityShuffle = true;
1397       for (unsigned i = 0; i < VWidth; i++) {
1398         unsigned MaskVal = Shuffle->getMaskValue(i);
1399         if (DemandedElts[i] && i != MaskVal) {
1400           IsIdentityShuffle = false;
1401           break;
1402         }
1403       }
1404       if (IsIdentityShuffle)
1405         return Shuffle->getOperand(0);
1406     }
1407 
1408     bool NewUndefElts = false;
1409     unsigned LHSIdx = -1u, LHSValIdx = -1u;
1410     unsigned RHSIdx = -1u, RHSValIdx = -1u;
1411     bool LHSUniform = true;
1412     bool RHSUniform = true;
1413     for (unsigned i = 0; i < VWidth; i++) {
1414       unsigned MaskVal = Shuffle->getMaskValue(i);
1415       if (MaskVal == -1u) {
1416         UndefElts.setBit(i);
1417       } else if (!DemandedElts[i]) {
1418         NewUndefElts = true;
1419         UndefElts.setBit(i);
1420       } else if (MaskVal < OpWidth) {
1421         if (LHSUndefElts[MaskVal]) {
1422           NewUndefElts = true;
1423           UndefElts.setBit(i);
1424         } else {
1425           LHSIdx = LHSIdx == -1u ? i : OpWidth;
1426           LHSValIdx = LHSValIdx == -1u ? MaskVal : OpWidth;
1427           LHSUniform = LHSUniform && (MaskVal == i);
1428         }
1429       } else {
1430         if (RHSUndefElts[MaskVal - OpWidth]) {
1431           NewUndefElts = true;
1432           UndefElts.setBit(i);
1433         } else {
1434           RHSIdx = RHSIdx == -1u ? i : OpWidth;
1435           RHSValIdx = RHSValIdx == -1u ? MaskVal - OpWidth : OpWidth;
1436           RHSUniform = RHSUniform && (MaskVal - OpWidth == i);
1437         }
1438       }
1439     }
1440 
1441     // Try to transform shuffle with constant vector and single element from
1442     // this constant vector to single insertelement instruction.
1443     // shufflevector V, C, <v1, v2, .., ci, .., vm> ->
1444     // insertelement V, C[ci], ci-n
1445     if (OpWidth ==
1446         cast<FixedVectorType>(Shuffle->getType())->getNumElements()) {
1447       Value *Op = nullptr;
1448       Constant *Value = nullptr;
1449       unsigned Idx = -1u;
1450 
1451       // Find constant vector with the single element in shuffle (LHS or RHS).
1452       if (LHSIdx < OpWidth && RHSUniform) {
1453         if (auto *CV = dyn_cast<ConstantVector>(Shuffle->getOperand(0))) {
1454           Op = Shuffle->getOperand(1);
1455           Value = CV->getOperand(LHSValIdx);
1456           Idx = LHSIdx;
1457         }
1458       }
1459       if (RHSIdx < OpWidth && LHSUniform) {
1460         if (auto *CV = dyn_cast<ConstantVector>(Shuffle->getOperand(1))) {
1461           Op = Shuffle->getOperand(0);
1462           Value = CV->getOperand(RHSValIdx);
1463           Idx = RHSIdx;
1464         }
1465       }
1466       // Found constant vector with single element - convert to insertelement.
1467       if (Op && Value) {
1468         Instruction *New = InsertElementInst::Create(
1469             Op, Value, ConstantInt::get(Type::getInt32Ty(I->getContext()), Idx),
1470             Shuffle->getName());
1471         InsertNewInstWith(New, *Shuffle);
1472         return New;
1473       }
1474     }
1475     if (NewUndefElts) {
1476       // Add additional discovered undefs.
1477       SmallVector<int, 16> Elts;
1478       for (unsigned i = 0; i < VWidth; ++i) {
1479         if (UndefElts[i])
1480           Elts.push_back(UndefMaskElem);
1481         else
1482           Elts.push_back(Shuffle->getMaskValue(i));
1483       }
1484       Shuffle->setShuffleMask(Elts);
1485       MadeChange = true;
1486     }
1487     break;
1488   }
1489   case Instruction::Select: {
1490     // If this is a vector select, try to transform the select condition based
1491     // on the current demanded elements.
1492     SelectInst *Sel = cast<SelectInst>(I);
1493     if (Sel->getCondition()->getType()->isVectorTy()) {
1494       // TODO: We are not doing anything with UndefElts based on this call.
1495       // It is overwritten below based on the other select operands. If an
1496       // element of the select condition is known undef, then we are free to
1497       // choose the output value from either arm of the select. If we know that
1498       // one of those values is undef, then the output can be undef.
1499       simplifyAndSetOp(I, 0, DemandedElts, UndefElts);
1500     }
1501 
1502     // Next, see if we can transform the arms of the select.
1503     APInt DemandedLHS(DemandedElts), DemandedRHS(DemandedElts);
1504     if (auto *CV = dyn_cast<ConstantVector>(Sel->getCondition())) {
1505       for (unsigned i = 0; i < VWidth; i++) {
1506         // isNullValue() always returns false when called on a ConstantExpr.
1507         // Skip constant expressions to avoid propagating incorrect information.
1508         Constant *CElt = CV->getAggregateElement(i);
1509         if (isa<ConstantExpr>(CElt))
1510           continue;
1511         // TODO: If a select condition element is undef, we can demand from
1512         // either side. If one side is known undef, choosing that side would
1513         // propagate undef.
1514         if (CElt->isNullValue())
1515           DemandedLHS.clearBit(i);
1516         else
1517           DemandedRHS.clearBit(i);
1518       }
1519     }
1520 
1521     simplifyAndSetOp(I, 1, DemandedLHS, UndefElts2);
1522     simplifyAndSetOp(I, 2, DemandedRHS, UndefElts3);
1523 
1524     // Output elements are undefined if the element from each arm is undefined.
1525     // TODO: This can be improved. See comment in select condition handling.
1526     UndefElts = UndefElts2 & UndefElts3;
1527     break;
1528   }
1529   case Instruction::BitCast: {
1530     // Vector->vector casts only.
1531     VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1532     if (!VTy) break;
1533     unsigned InVWidth = cast<FixedVectorType>(VTy)->getNumElements();
1534     APInt InputDemandedElts(InVWidth, 0);
1535     UndefElts2 = APInt(InVWidth, 0);
1536     unsigned Ratio;
1537 
1538     if (VWidth == InVWidth) {
1539       // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1540       // elements as are demanded of us.
1541       Ratio = 1;
1542       InputDemandedElts = DemandedElts;
1543     } else if ((VWidth % InVWidth) == 0) {
1544       // If the number of elements in the output is a multiple of the number of
1545       // elements in the input then an input element is live if any of the
1546       // corresponding output elements are live.
1547       Ratio = VWidth / InVWidth;
1548       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1549         if (DemandedElts[OutIdx])
1550           InputDemandedElts.setBit(OutIdx / Ratio);
1551     } else if ((InVWidth % VWidth) == 0) {
1552       // If the number of elements in the input is a multiple of the number of
1553       // elements in the output then an input element is live if the
1554       // corresponding output element is live.
1555       Ratio = InVWidth / VWidth;
1556       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1557         if (DemandedElts[InIdx / Ratio])
1558           InputDemandedElts.setBit(InIdx);
1559     } else {
1560       // Unsupported so far.
1561       break;
1562     }
1563 
1564     simplifyAndSetOp(I, 0, InputDemandedElts, UndefElts2);
1565 
1566     if (VWidth == InVWidth) {
1567       UndefElts = UndefElts2;
1568     } else if ((VWidth % InVWidth) == 0) {
1569       // If the number of elements in the output is a multiple of the number of
1570       // elements in the input then an output element is undef if the
1571       // corresponding input element is undef.
1572       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1573         if (UndefElts2[OutIdx / Ratio])
1574           UndefElts.setBit(OutIdx);
1575     } else if ((InVWidth % VWidth) == 0) {
1576       // If the number of elements in the input is a multiple of the number of
1577       // elements in the output then an output element is undef if all of the
1578       // corresponding input elements are undef.
1579       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1580         APInt SubUndef = UndefElts2.lshr(OutIdx * Ratio).zextOrTrunc(Ratio);
1581         if (SubUndef.countPopulation() == Ratio)
1582           UndefElts.setBit(OutIdx);
1583       }
1584     } else {
1585       llvm_unreachable("Unimp");
1586     }
1587     break;
1588   }
1589   case Instruction::FPTrunc:
1590   case Instruction::FPExt:
1591     simplifyAndSetOp(I, 0, DemandedElts, UndefElts);
1592     break;
1593 
1594   case Instruction::Call: {
1595     IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1596     if (!II) break;
1597     switch (II->getIntrinsicID()) {
1598     case Intrinsic::masked_gather: // fallthrough
1599     case Intrinsic::masked_load: {
1600       // Subtlety: If we load from a pointer, the pointer must be valid
1601       // regardless of whether the element is demanded.  Doing otherwise risks
1602       // segfaults which didn't exist in the original program.
1603       APInt DemandedPtrs(APInt::getAllOnes(VWidth)),
1604           DemandedPassThrough(DemandedElts);
1605       if (auto *CV = dyn_cast<ConstantVector>(II->getOperand(2)))
1606         for (unsigned i = 0; i < VWidth; i++) {
1607           Constant *CElt = CV->getAggregateElement(i);
1608           if (CElt->isNullValue())
1609             DemandedPtrs.clearBit(i);
1610           else if (CElt->isAllOnesValue())
1611             DemandedPassThrough.clearBit(i);
1612         }
1613       if (II->getIntrinsicID() == Intrinsic::masked_gather)
1614         simplifyAndSetOp(II, 0, DemandedPtrs, UndefElts2);
1615       simplifyAndSetOp(II, 3, DemandedPassThrough, UndefElts3);
1616 
1617       // Output elements are undefined if the element from both sources are.
1618       // TODO: can strengthen via mask as well.
1619       UndefElts = UndefElts2 & UndefElts3;
1620       break;
1621     }
1622     default: {
1623       // Handle target specific intrinsics
1624       Optional<Value *> V = targetSimplifyDemandedVectorEltsIntrinsic(
1625           *II, DemandedElts, UndefElts, UndefElts2, UndefElts3,
1626           simplifyAndSetOp);
1627       if (V.hasValue())
1628         return V.getValue();
1629       break;
1630     }
1631     } // switch on IntrinsicID
1632     break;
1633   } // case Call
1634   } // switch on Opcode
1635 
1636   // TODO: We bail completely on integer div/rem and shifts because they have
1637   // UB/poison potential, but that should be refined.
1638   BinaryOperator *BO;
1639   if (match(I, m_BinOp(BO)) && !BO->isIntDivRem() && !BO->isShift()) {
1640     simplifyAndSetOp(I, 0, DemandedElts, UndefElts);
1641     simplifyAndSetOp(I, 1, DemandedElts, UndefElts2);
1642 
1643     // Output elements are undefined if both are undefined. Consider things
1644     // like undef & 0. The result is known zero, not undef.
1645     UndefElts &= UndefElts2;
1646   }
1647 
1648   // If we've proven all of the lanes undef, return an undef value.
1649   // TODO: Intersect w/demanded lanes
1650   if (UndefElts.isAllOnes())
1651     return UndefValue::get(I->getType());;
1652 
1653   return MadeChange ? I : nullptr;
1654 }
1655