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