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