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