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