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