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/ValueTracking.h"
16 #include "llvm/IR/IntrinsicInst.h"
17 #include "llvm/IR/IntrinsicsAMDGPU.h"
18 #include "llvm/IR/IntrinsicsX86.h"
19 #include "llvm/IR/PatternMatch.h"
20 #include "llvm/Support/KnownBits.h"
21 
22 using namespace llvm;
23 using namespace llvm::PatternMatch;
24 
25 #define DEBUG_TYPE "instcombine"
26 
27 namespace {
28 
29 struct AMDGPUImageDMaskIntrinsic {
30   unsigned Intr;
31 };
32 
33 #define GET_AMDGPUImageDMaskIntrinsicTable_IMPL
34 #include "InstCombineTables.inc"
35 
36 } // end anonymous namespace
37 
38 /// Check to see if the specified operand of the specified instruction is a
39 /// constant integer. If so, check to see if there are any bits set in the
40 /// constant that are not demanded. If so, shrink the constant and return true.
41 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
42                                    const APInt &Demanded) {
43   assert(I && "No instruction?");
44   assert(OpNo < I->getNumOperands() && "Operand index too large");
45 
46   // The operand must be a constant integer or splat integer.
47   Value *Op = I->getOperand(OpNo);
48   const APInt *C;
49   if (!match(Op, m_APInt(C)))
50     return false;
51 
52   // If there are no bits set that aren't demanded, nothing to do.
53   if (C->isSubsetOf(Demanded))
54     return false;
55 
56   // This instruction is producing bits that are not demanded. Shrink the RHS.
57   I->setOperand(OpNo, ConstantInt::get(Op->getType(), *C & Demanded));
58 
59   return true;
60 }
61 
62 
63 
64 /// Inst is an integer instruction that SimplifyDemandedBits knows about. See if
65 /// the instruction has any properties that allow us to simplify its operands.
66 bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
67   unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
68   KnownBits Known(BitWidth);
69   APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
70 
71   Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask, Known,
72                                      0, &Inst);
73   if (!V) return false;
74   if (V == &Inst) return true;
75   replaceInstUsesWith(Inst, V);
76   return true;
77 }
78 
79 /// This form of SimplifyDemandedBits simplifies the specified instruction
80 /// operand if possible, updating it in place. It returns true if it made any
81 /// change and false otherwise.
82 bool InstCombiner::SimplifyDemandedBits(Instruction *I, unsigned OpNo,
83                                         const APInt &DemandedMask,
84                                         KnownBits &Known,
85                                         unsigned Depth) {
86   Use &U = I->getOperandUse(OpNo);
87   Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask, Known,
88                                           Depth, I);
89   if (!NewVal) return false;
90   replaceUse(U, NewVal);
91   return true;
92 }
93 
94 
95 /// This function attempts to replace V with a simpler value based on the
96 /// demanded bits. When this function is called, it is known that only the bits
97 /// set in DemandedMask of the result of V are ever used downstream.
98 /// Consequently, depending on the mask and V, it may be possible to replace V
99 /// with a constant or one of its operands. In such cases, this function does
100 /// the replacement and returns true. In all other cases, it returns false after
101 /// analyzing the expression and setting KnownOne and known to be one in the
102 /// expression. Known.Zero contains all the bits that are known to be zero in
103 /// the expression. These are provided to potentially allow the caller (which
104 /// might recursively be SimplifyDemandedBits itself) to simplify the
105 /// expression.
106 /// Known.One and Known.Zero always follow the invariant that:
107 ///   Known.One & Known.Zero == 0.
108 /// That is, a bit can't be both 1 and 0. Note that the bits in Known.One and
109 /// Known.Zero may only be accurate for those bits set in DemandedMask. Note
110 /// also that the bitwidth of V, DemandedMask, Known.Zero and Known.One must all
111 /// be the same.
112 ///
113 /// This returns null if it did not change anything and it permits no
114 /// simplification.  This returns V itself if it did some simplification of V's
115 /// operands based on the information about what bits are demanded. This returns
116 /// some other non-null value if it found out that V is equal to another value
117 /// in the context where the specified bits are demanded, but not for all users.
118 Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
119                                              KnownBits &Known, unsigned Depth,
120                                              Instruction *CxtI) {
121   assert(V != nullptr && "Null pointer of Value???");
122   assert(Depth <= 6 && "Limit Search Depth");
123   uint32_t BitWidth = DemandedMask.getBitWidth();
124   Type *VTy = V->getType();
125   assert(
126       (!VTy->isIntOrIntVectorTy() || VTy->getScalarSizeInBits() == BitWidth) &&
127       Known.getBitWidth() == BitWidth &&
128       "Value *V, DemandedMask and Known must have same BitWidth");
129 
130   if (isa<Constant>(V)) {
131     computeKnownBits(V, Known, Depth, CxtI);
132     return nullptr;
133   }
134 
135   Known.resetAll();
136   if (DemandedMask.isNullValue())     // Not demanding any bits from V.
137     return UndefValue::get(VTy);
138 
139   if (Depth == 6)        // Limit search depth.
140     return nullptr;
141 
142   Instruction *I = dyn_cast<Instruction>(V);
143   if (!I) {
144     computeKnownBits(V, Known, Depth, CxtI);
145     return nullptr;        // Only analyze instructions.
146   }
147 
148   // If there are multiple uses of this value and we aren't at the root, then
149   // we can't do any simplifications of the operands, because DemandedMask
150   // only reflects the bits demanded by *one* of the users.
151   if (Depth != 0 && !I->hasOneUse())
152     return SimplifyMultipleUseDemandedBits(I, DemandedMask, Known, Depth, CxtI);
153 
154   KnownBits LHSKnown(BitWidth), RHSKnown(BitWidth);
155 
156   // If this is the root being simplified, allow it to have multiple uses,
157   // just set the DemandedMask to all bits so that we can try to simplify the
158   // operands.  This allows visitTruncInst (for example) to simplify the
159   // operand of a trunc without duplicating all the logic below.
160   if (Depth == 0 && !V->hasOneUse())
161     DemandedMask.setAllBits();
162 
163   switch (I->getOpcode()) {
164   default:
165     computeKnownBits(I, Known, Depth, CxtI);
166     break;
167   case Instruction::And: {
168     // If either the LHS or the RHS are Zero, the result is zero.
169     if (SimplifyDemandedBits(I, 1, DemandedMask, RHSKnown, Depth + 1) ||
170         SimplifyDemandedBits(I, 0, DemandedMask & ~RHSKnown.Zero, LHSKnown,
171                              Depth + 1))
172       return I;
173     assert(!RHSKnown.hasConflict() && "Bits known to be one AND zero?");
174     assert(!LHSKnown.hasConflict() && "Bits known to be one AND zero?");
175 
176     // Output known-0 are known to be clear if zero in either the LHS | RHS.
177     APInt IKnownZero = RHSKnown.Zero | LHSKnown.Zero;
178     // Output known-1 bits are only known if set in both the LHS & RHS.
179     APInt IKnownOne = RHSKnown.One & LHSKnown.One;
180 
181     // If the client is only demanding bits that we know, return the known
182     // constant.
183     if (DemandedMask.isSubsetOf(IKnownZero|IKnownOne))
184       return Constant::getIntegerValue(VTy, IKnownOne);
185 
186     // If all of the demanded bits are known 1 on one side, return the other.
187     // These bits cannot contribute to the result of the 'and'.
188     if (DemandedMask.isSubsetOf(LHSKnown.Zero | RHSKnown.One))
189       return I->getOperand(0);
190     if (DemandedMask.isSubsetOf(RHSKnown.Zero | LHSKnown.One))
191       return I->getOperand(1);
192 
193     // If the RHS is a constant, see if we can simplify it.
194     if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnown.Zero))
195       return I;
196 
197     Known.Zero = std::move(IKnownZero);
198     Known.One  = std::move(IKnownOne);
199     break;
200   }
201   case Instruction::Or: {
202     // If either the LHS or the RHS are One, the result is One.
203     if (SimplifyDemandedBits(I, 1, DemandedMask, RHSKnown, Depth + 1) ||
204         SimplifyDemandedBits(I, 0, DemandedMask & ~RHSKnown.One, LHSKnown,
205                              Depth + 1))
206       return I;
207     assert(!RHSKnown.hasConflict() && "Bits known to be one AND zero?");
208     assert(!LHSKnown.hasConflict() && "Bits known to be one AND zero?");
209 
210     // Output known-0 bits are only known if clear in both the LHS & RHS.
211     APInt IKnownZero = RHSKnown.Zero & LHSKnown.Zero;
212     // Output known-1 are known. to be set if s.et in either the LHS | RHS.
213     APInt IKnownOne = RHSKnown.One | LHSKnown.One;
214 
215     // If the client is only demanding bits that we know, return the known
216     // constant.
217     if (DemandedMask.isSubsetOf(IKnownZero|IKnownOne))
218       return Constant::getIntegerValue(VTy, IKnownOne);
219 
220     // If all of the demanded bits are known zero on one side, return the other.
221     // These bits cannot contribute to the result of the 'or'.
222     if (DemandedMask.isSubsetOf(LHSKnown.One | RHSKnown.Zero))
223       return I->getOperand(0);
224     if (DemandedMask.isSubsetOf(RHSKnown.One | LHSKnown.Zero))
225       return I->getOperand(1);
226 
227     // If the RHS is a constant, see if we can simplify it.
228     if (ShrinkDemandedConstant(I, 1, DemandedMask))
229       return I;
230 
231     Known.Zero = std::move(IKnownZero);
232     Known.One  = std::move(IKnownOne);
233     break;
234   }
235   case Instruction::Xor: {
236     if (SimplifyDemandedBits(I, 1, DemandedMask, RHSKnown, Depth + 1) ||
237         SimplifyDemandedBits(I, 0, DemandedMask, LHSKnown, Depth + 1))
238       return I;
239     assert(!RHSKnown.hasConflict() && "Bits known to be one AND zero?");
240     assert(!LHSKnown.hasConflict() && "Bits known to be one AND zero?");
241 
242     // Output known-0 bits are known if clear or set in both the LHS & RHS.
243     APInt IKnownZero = (RHSKnown.Zero & LHSKnown.Zero) |
244                        (RHSKnown.One & LHSKnown.One);
245     // Output known-1 are known to be set if set in only one of the LHS, RHS.
246     APInt IKnownOne =  (RHSKnown.Zero & LHSKnown.One) |
247                        (RHSKnown.One & LHSKnown.Zero);
248 
249     // If the client is only demanding bits that we know, return the known
250     // constant.
251     if (DemandedMask.isSubsetOf(IKnownZero|IKnownOne))
252       return Constant::getIntegerValue(VTy, IKnownOne);
253 
254     // If all of the demanded bits are known zero on one side, return the other.
255     // These bits cannot contribute to the result of the 'xor'.
256     if (DemandedMask.isSubsetOf(RHSKnown.Zero))
257       return I->getOperand(0);
258     if (DemandedMask.isSubsetOf(LHSKnown.Zero))
259       return I->getOperand(1);
260 
261     // If all of the demanded bits are known to be zero on one side or the
262     // other, turn this into an *inclusive* or.
263     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
264     if (DemandedMask.isSubsetOf(RHSKnown.Zero | LHSKnown.Zero)) {
265       Instruction *Or =
266         BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
267                                  I->getName());
268       return InsertNewInstWith(Or, *I);
269     }
270 
271     // If all of the demanded bits on one side are known, and all of the set
272     // bits on that side are also known to be set on the other side, turn this
273     // into an AND, as we know the bits will be cleared.
274     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
275     if (DemandedMask.isSubsetOf(RHSKnown.Zero|RHSKnown.One) &&
276         RHSKnown.One.isSubsetOf(LHSKnown.One)) {
277       Constant *AndC = Constant::getIntegerValue(VTy,
278                                                  ~RHSKnown.One & DemandedMask);
279       Instruction *And = BinaryOperator::CreateAnd(I->getOperand(0), AndC);
280       return InsertNewInstWith(And, *I);
281     }
282 
283     // If the RHS is a constant, see if we can simplify it.
284     // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
285     if (ShrinkDemandedConstant(I, 1, DemandedMask))
286       return I;
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       if (LHSInst->getOpcode() == Instruction::And && LHSInst->hasOneUse() &&
294           isa<ConstantInt>(I->getOperand(1)) &&
295           isa<ConstantInt>(LHSInst->getOperand(1)) &&
296           (LHSKnown.One & RHSKnown.One & DemandedMask) != 0) {
297         ConstantInt *AndRHS = cast<ConstantInt>(LHSInst->getOperand(1));
298         ConstantInt *XorRHS = cast<ConstantInt>(I->getOperand(1));
299         APInt NewMask = ~(LHSKnown.One & RHSKnown.One & DemandedMask);
300 
301         Constant *AndC =
302           ConstantInt::get(I->getType(), NewMask & AndRHS->getValue());
303         Instruction *NewAnd = BinaryOperator::CreateAnd(I->getOperand(0), AndC);
304         InsertNewInstWith(NewAnd, *I);
305 
306         Constant *XorC =
307           ConstantInt::get(I->getType(), NewMask & XorRHS->getValue());
308         Instruction *NewXor = BinaryOperator::CreateXor(NewAnd, XorC);
309         return InsertNewInstWith(NewXor, *I);
310       }
311 
312     // Output known-0 bits are known if clear or set in both the LHS & RHS.
313     Known.Zero = std::move(IKnownZero);
314     // Output known-1 are known to be set if set in only one of the LHS, RHS.
315     Known.One  = std::move(IKnownOne);
316     break;
317   }
318   case Instruction::Select: {
319     Value *LHS, *RHS;
320     SelectPatternFlavor SPF = matchSelectPattern(I, LHS, RHS).Flavor;
321     if (SPF == SPF_UMAX) {
322       // UMax(A, C) == A if ...
323       // The lowest non-zero bit of DemandMask is higher than the highest
324       // non-zero bit of C.
325       const APInt *C;
326       unsigned CTZ = DemandedMask.countTrailingZeros();
327       if (match(RHS, m_APInt(C)) && CTZ >= C->getActiveBits())
328         return LHS;
329     } else if (SPF == SPF_UMIN) {
330       // UMin(A, C) == A if ...
331       // The lowest non-zero bit of DemandMask is higher than the highest
332       // non-one bit of C.
333       // This comes from using DeMorgans on the above umax example.
334       const APInt *C;
335       unsigned CTZ = DemandedMask.countTrailingZeros();
336       if (match(RHS, m_APInt(C)) &&
337           CTZ >= C->getBitWidth() - C->countLeadingOnes())
338         return LHS;
339     }
340 
341     // If this is a select as part of any other min/max pattern, don't simplify
342     // any further in case we break the structure.
343     if (SPF != SPF_UNKNOWN)
344       return nullptr;
345 
346     if (SimplifyDemandedBits(I, 2, DemandedMask, RHSKnown, Depth + 1) ||
347         SimplifyDemandedBits(I, 1, DemandedMask, LHSKnown, Depth + 1))
348       return I;
349     assert(!RHSKnown.hasConflict() && "Bits known to be one AND zero?");
350     assert(!LHSKnown.hasConflict() && "Bits known to be one AND zero?");
351 
352     // If the operands are constants, see if we can simplify them.
353     // This is similar to ShrinkDemandedConstant, but for a select we want to
354     // try to keep the selected constants the same as icmp value constants, if
355     // we can. This helps not break apart (or helps put back together)
356     // canonical patterns like min and max.
357     auto CanonicalizeSelectConstant = [](Instruction *I, unsigned OpNo,
358                                          APInt DemandedMask) {
359       const APInt *SelC;
360       if (!match(I->getOperand(OpNo), m_APInt(SelC)))
361         return false;
362 
363       // Get the constant out of the ICmp, if there is one.
364       const APInt *CmpC;
365       ICmpInst::Predicate Pred;
366       if (!match(I->getOperand(0), m_c_ICmp(Pred, m_APInt(CmpC), m_Value())) ||
367           CmpC->getBitWidth() != SelC->getBitWidth())
368         return ShrinkDemandedConstant(I, OpNo, DemandedMask);
369 
370       // If the constant is already the same as the ICmp, leave it as-is.
371       if (*CmpC == *SelC)
372         return false;
373       // If the constants are not already the same, but can be with the demand
374       // mask, use the constant value from the ICmp.
375       if ((*CmpC & DemandedMask) == (*SelC & DemandedMask)) {
376         I->setOperand(OpNo, ConstantInt::get(I->getType(), *CmpC));
377         return true;
378       }
379       return ShrinkDemandedConstant(I, OpNo, DemandedMask);
380     };
381     if (CanonicalizeSelectConstant(I, 1, DemandedMask) ||
382         CanonicalizeSelectConstant(I, 2, DemandedMask))
383       return I;
384 
385     // Only known if known in both the LHS and RHS.
386     Known.One = RHSKnown.One & LHSKnown.One;
387     Known.Zero = RHSKnown.Zero & LHSKnown.Zero;
388     break;
389   }
390   case Instruction::ZExt:
391   case Instruction::Trunc: {
392     unsigned SrcBitWidth = I->getOperand(0)->getType()->getScalarSizeInBits();
393 
394     APInt InputDemandedMask = DemandedMask.zextOrTrunc(SrcBitWidth);
395     KnownBits InputKnown(SrcBitWidth);
396     if (SimplifyDemandedBits(I, 0, InputDemandedMask, InputKnown, Depth + 1))
397       return I;
398     assert(InputKnown.getBitWidth() == SrcBitWidth && "Src width changed?");
399     Known = InputKnown.zextOrTrunc(BitWidth);
400     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
401     break;
402   }
403   case Instruction::BitCast:
404     if (!I->getOperand(0)->getType()->isIntOrIntVectorTy())
405       return nullptr;  // vector->int or fp->int?
406 
407     if (VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
408       if (VectorType *SrcVTy =
409             dyn_cast<VectorType>(I->getOperand(0)->getType())) {
410         if (DstVTy->getNumElements() != SrcVTy->getNumElements())
411           // Don't touch a bitcast between vectors of different element counts.
412           return nullptr;
413       } else
414         // Don't touch a scalar-to-vector bitcast.
415         return nullptr;
416     } else if (I->getOperand(0)->getType()->isVectorTy())
417       // Don't touch a vector-to-scalar bitcast.
418       return nullptr;
419 
420     if (SimplifyDemandedBits(I, 0, DemandedMask, Known, Depth + 1))
421       return I;
422     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
423     break;
424   case Instruction::SExt: {
425     // Compute the bits in the result that are not present in the input.
426     unsigned SrcBitWidth = I->getOperand(0)->getType()->getScalarSizeInBits();
427 
428     APInt InputDemandedBits = DemandedMask.trunc(SrcBitWidth);
429 
430     // If any of the sign extended bits are demanded, we know that the sign
431     // bit is demanded.
432     if (DemandedMask.getActiveBits() > SrcBitWidth)
433       InputDemandedBits.setBit(SrcBitWidth-1);
434 
435     KnownBits InputKnown(SrcBitWidth);
436     if (SimplifyDemandedBits(I, 0, InputDemandedBits, InputKnown, Depth + 1))
437       return I;
438 
439     // If the input sign bit is known zero, or if the NewBits are not demanded
440     // convert this into a zero extension.
441     if (InputKnown.isNonNegative() ||
442         DemandedMask.getActiveBits() <= SrcBitWidth) {
443       // Convert to ZExt cast.
444       CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
445       return InsertNewInstWith(NewCast, *I);
446      }
447 
448     // If the sign bit of the input is known set or clear, then we know the
449     // top bits of the result.
450     Known = InputKnown.sext(BitWidth);
451     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
452     break;
453   }
454   case Instruction::Add:
455     if ((DemandedMask & 1) == 0) {
456       // If we do not need the low bit, try to convert bool math to logic:
457       // add iN (zext i1 X), (sext i1 Y) --> sext (~X & Y) to iN
458       Value *X, *Y;
459       if (match(I, m_c_Add(m_OneUse(m_ZExt(m_Value(X))),
460                            m_OneUse(m_SExt(m_Value(Y))))) &&
461           X->getType()->isIntOrIntVectorTy(1) && X->getType() == Y->getType()) {
462         // Truth table for inputs and output signbits:
463         //       X:0 | X:1
464         //      ----------
465         // Y:0  |  0 | 0 |
466         // Y:1  | -1 | 0 |
467         //      ----------
468         IRBuilderBase::InsertPointGuard Guard(Builder);
469         Builder.SetInsertPoint(I);
470         Value *AndNot = Builder.CreateAnd(Builder.CreateNot(X), Y);
471         return Builder.CreateSExt(AndNot, VTy);
472       }
473 
474       // add iN (sext i1 X), (sext i1 Y) --> sext (X | Y) to iN
475       // TODO: Relax the one-use checks because we are removing an instruction?
476       if (match(I, m_Add(m_OneUse(m_SExt(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  | -1 | -1 |
483         // Y:1  | -1 |  0 |
484         //      -----------
485         IRBuilderBase::InsertPointGuard Guard(Builder);
486         Builder.SetInsertPoint(I);
487         Value *Or = Builder.CreateOr(X, Y);
488         return Builder.CreateSExt(Or, VTy);
489       }
490     }
491     LLVM_FALLTHROUGH;
492   case Instruction::Sub: {
493     /// If the high-bits of an ADD/SUB are not demanded, then we do not care
494     /// about the high bits of the operands.
495     unsigned NLZ = DemandedMask.countLeadingZeros();
496     // Right fill the mask of bits for this ADD/SUB to demand the most
497     // significant bit and all those below it.
498     APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
499     if (ShrinkDemandedConstant(I, 0, DemandedFromOps) ||
500         SimplifyDemandedBits(I, 0, DemandedFromOps, LHSKnown, Depth + 1) ||
501         ShrinkDemandedConstant(I, 1, DemandedFromOps) ||
502         SimplifyDemandedBits(I, 1, DemandedFromOps, RHSKnown, Depth + 1)) {
503       if (NLZ > 0) {
504         // Disable the nsw and nuw flags here: We can no longer guarantee that
505         // we won't wrap after simplification. Removing the nsw/nuw flags is
506         // legal here because the top bit is not demanded.
507         BinaryOperator &BinOP = *cast<BinaryOperator>(I);
508         BinOP.setHasNoSignedWrap(false);
509         BinOP.setHasNoUnsignedWrap(false);
510       }
511       return I;
512     }
513 
514     // If we are known to be adding/subtracting zeros to every bit below
515     // the highest demanded bit, we just return the other side.
516     if (DemandedFromOps.isSubsetOf(RHSKnown.Zero))
517       return I->getOperand(0);
518     // We can't do this with the LHS for subtraction, unless we are only
519     // demanding the LSB.
520     if ((I->getOpcode() == Instruction::Add ||
521          DemandedFromOps.isOneValue()) &&
522         DemandedFromOps.isSubsetOf(LHSKnown.Zero))
523       return I->getOperand(1);
524 
525     // Otherwise just compute the known bits of the result.
526     bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
527     Known = KnownBits::computeForAddSub(I->getOpcode() == Instruction::Add,
528                                         NSW, LHSKnown, RHSKnown);
529     break;
530   }
531   case Instruction::Shl: {
532     const APInt *SA;
533     if (match(I->getOperand(1), m_APInt(SA))) {
534       const APInt *ShrAmt;
535       if (match(I->getOperand(0), m_Shr(m_Value(), m_APInt(ShrAmt))))
536         if (Instruction *Shr = dyn_cast<Instruction>(I->getOperand(0)))
537           if (Value *R = simplifyShrShlDemandedBits(Shr, *ShrAmt, I, *SA,
538                                                     DemandedMask, Known))
539             return R;
540 
541       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth-1);
542       APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
543 
544       // If the shift is NUW/NSW, then it does demand the high bits.
545       ShlOperator *IOp = cast<ShlOperator>(I);
546       if (IOp->hasNoSignedWrap())
547         DemandedMaskIn.setHighBits(ShiftAmt+1);
548       else if (IOp->hasNoUnsignedWrap())
549         DemandedMaskIn.setHighBits(ShiftAmt);
550 
551       if (SimplifyDemandedBits(I, 0, DemandedMaskIn, Known, Depth + 1))
552         return I;
553       assert(!Known.hasConflict() && "Bits known to be one AND zero?");
554 
555       bool SignBitZero = Known.Zero.isSignBitSet();
556       bool SignBitOne = Known.One.isSignBitSet();
557       Known.Zero <<= ShiftAmt;
558       Known.One  <<= ShiftAmt;
559       // low bits known zero.
560       if (ShiftAmt)
561         Known.Zero.setLowBits(ShiftAmt);
562 
563       // If this shift has "nsw" keyword, then the result is either a poison
564       // value or has the same sign bit as the first operand.
565       if (IOp->hasNoSignedWrap()) {
566         if (SignBitZero)
567           Known.Zero.setSignBit();
568         else if (SignBitOne)
569           Known.One.setSignBit();
570         if (Known.hasConflict())
571           return UndefValue::get(I->getType());
572       }
573     } else {
574       computeKnownBits(I, Known, Depth, CxtI);
575     }
576     break;
577   }
578   case Instruction::LShr: {
579     const APInt *SA;
580     if (match(I->getOperand(1), m_APInt(SA))) {
581       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth-1);
582 
583       // Unsigned shift right.
584       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
585 
586       // If the shift is exact, then it does demand the low bits (and knows that
587       // they are zero).
588       if (cast<LShrOperator>(I)->isExact())
589         DemandedMaskIn.setLowBits(ShiftAmt);
590 
591       if (SimplifyDemandedBits(I, 0, DemandedMaskIn, Known, Depth + 1))
592         return I;
593       assert(!Known.hasConflict() && "Bits known to be one AND zero?");
594       Known.Zero.lshrInPlace(ShiftAmt);
595       Known.One.lshrInPlace(ShiftAmt);
596       if (ShiftAmt)
597         Known.Zero.setHighBits(ShiftAmt);  // high bits known zero.
598     } else {
599       computeKnownBits(I, Known, Depth, CxtI);
600     }
601     break;
602   }
603   case Instruction::AShr: {
604     // If this is an arithmetic shift right and only the low-bit is set, we can
605     // always convert this into a logical shr, even if the shift amount is
606     // variable.  The low bit of the shift cannot be an input sign bit unless
607     // the shift amount is >= the size of the datatype, which is undefined.
608     if (DemandedMask.isOneValue()) {
609       // Perform the logical shift right.
610       Instruction *NewVal = BinaryOperator::CreateLShr(
611                         I->getOperand(0), I->getOperand(1), I->getName());
612       return InsertNewInstWith(NewVal, *I);
613     }
614 
615     // If the sign bit is the only bit demanded by this ashr, then there is no
616     // need to do it, the shift doesn't change the high bit.
617     if (DemandedMask.isSignMask())
618       return I->getOperand(0);
619 
620     const APInt *SA;
621     if (match(I->getOperand(1), m_APInt(SA))) {
622       uint32_t ShiftAmt = SA->getLimitedValue(BitWidth-1);
623 
624       // Signed shift right.
625       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
626       // If any of the high bits are demanded, we should set the sign bit as
627       // demanded.
628       if (DemandedMask.countLeadingZeros() <= ShiftAmt)
629         DemandedMaskIn.setSignBit();
630 
631       // If the shift is exact, then it does demand the low bits (and knows that
632       // they are zero).
633       if (cast<AShrOperator>(I)->isExact())
634         DemandedMaskIn.setLowBits(ShiftAmt);
635 
636       if (SimplifyDemandedBits(I, 0, DemandedMaskIn, Known, Depth + 1))
637         return I;
638 
639       unsigned SignBits = ComputeNumSignBits(I->getOperand(0), Depth + 1, CxtI);
640 
641       assert(!Known.hasConflict() && "Bits known to be one AND zero?");
642       // Compute the new bits that are at the top now plus sign bits.
643       APInt HighBits(APInt::getHighBitsSet(
644           BitWidth, std::min(SignBits + ShiftAmt - 1, BitWidth)));
645       Known.Zero.lshrInPlace(ShiftAmt);
646       Known.One.lshrInPlace(ShiftAmt);
647 
648       // If the input sign bit is known to be zero, or if none of the top bits
649       // are demanded, turn this into an unsigned shift right.
650       assert(BitWidth > ShiftAmt && "Shift amount not saturated?");
651       if (Known.Zero[BitWidth-ShiftAmt-1] ||
652           !DemandedMask.intersects(HighBits)) {
653         BinaryOperator *LShr = BinaryOperator::CreateLShr(I->getOperand(0),
654                                                           I->getOperand(1));
655         LShr->setIsExact(cast<BinaryOperator>(I)->isExact());
656         return InsertNewInstWith(LShr, *I);
657       } else if (Known.One[BitWidth-ShiftAmt-1]) { // New bits are known one.
658         Known.One |= HighBits;
659       }
660     } else {
661       computeKnownBits(I, Known, Depth, CxtI);
662     }
663     break;
664   }
665   case Instruction::UDiv: {
666     // UDiv doesn't demand low bits that are zero in the divisor.
667     const APInt *SA;
668     if (match(I->getOperand(1), m_APInt(SA))) {
669       // If the shift is exact, then it does demand the low bits.
670       if (cast<UDivOperator>(I)->isExact())
671         break;
672 
673       // FIXME: Take the demanded mask of the result into account.
674       unsigned RHSTrailingZeros = SA->countTrailingZeros();
675       APInt DemandedMaskIn =
676           APInt::getHighBitsSet(BitWidth, BitWidth - RHSTrailingZeros);
677       if (SimplifyDemandedBits(I, 0, DemandedMaskIn, LHSKnown, Depth + 1))
678         return I;
679 
680       // Propagate zero bits from the input.
681       Known.Zero.setHighBits(std::min(
682           BitWidth, LHSKnown.Zero.countLeadingOnes() + RHSTrailingZeros));
683     } else {
684       computeKnownBits(I, Known, Depth, CxtI);
685     }
686     break;
687   }
688   case Instruction::SRem:
689     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
690       // X % -1 demands all the bits because we don't want to introduce
691       // INT_MIN % -1 (== undef) by accident.
692       if (Rem->isMinusOne())
693         break;
694       APInt RA = Rem->getValue().abs();
695       if (RA.isPowerOf2()) {
696         if (DemandedMask.ult(RA))    // srem won't affect demanded bits
697           return I->getOperand(0);
698 
699         APInt LowBits = RA - 1;
700         APInt Mask2 = LowBits | APInt::getSignMask(BitWidth);
701         if (SimplifyDemandedBits(I, 0, Mask2, LHSKnown, Depth + 1))
702           return I;
703 
704         // The low bits of LHS are unchanged by the srem.
705         Known.Zero = LHSKnown.Zero & LowBits;
706         Known.One = LHSKnown.One & LowBits;
707 
708         // If LHS is non-negative or has all low bits zero, then the upper bits
709         // are all zero.
710         if (LHSKnown.isNonNegative() || LowBits.isSubsetOf(LHSKnown.Zero))
711           Known.Zero |= ~LowBits;
712 
713         // If LHS is negative and not all low bits are zero, then the upper bits
714         // are all one.
715         if (LHSKnown.isNegative() && LowBits.intersects(LHSKnown.One))
716           Known.One |= ~LowBits;
717 
718         assert(!Known.hasConflict() && "Bits known to be one AND zero?");
719         break;
720       }
721     }
722 
723     // The sign bit is the LHS's sign bit, except when the result of the
724     // remainder is zero.
725     if (DemandedMask.isSignBitSet()) {
726       computeKnownBits(I->getOperand(0), LHSKnown, Depth + 1, CxtI);
727       // If it's known zero, our sign bit is also zero.
728       if (LHSKnown.isNonNegative())
729         Known.makeNonNegative();
730     }
731     break;
732   case Instruction::URem: {
733     KnownBits Known2(BitWidth);
734     APInt AllOnes = APInt::getAllOnesValue(BitWidth);
735     if (SimplifyDemandedBits(I, 0, AllOnes, Known2, Depth + 1) ||
736         SimplifyDemandedBits(I, 1, AllOnes, Known2, Depth + 1))
737       return I;
738 
739     unsigned Leaders = Known2.countMinLeadingZeros();
740     Known.Zero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
741     break;
742   }
743   case Instruction::Call: {
744     bool KnownBitsComputed = false;
745     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
746       switch (II->getIntrinsicID()) {
747       default: break;
748       case Intrinsic::bswap: {
749         // If the only bits demanded come from one byte of the bswap result,
750         // just shift the input byte into position to eliminate the bswap.
751         unsigned NLZ = DemandedMask.countLeadingZeros();
752         unsigned NTZ = DemandedMask.countTrailingZeros();
753 
754         // Round NTZ down to the next byte.  If we have 11 trailing zeros, then
755         // we need all the bits down to bit 8.  Likewise, round NLZ.  If we
756         // have 14 leading zeros, round to 8.
757         NLZ &= ~7;
758         NTZ &= ~7;
759         // If we need exactly one byte, we can do this transformation.
760         if (BitWidth-NLZ-NTZ == 8) {
761           unsigned ResultBit = NTZ;
762           unsigned InputBit = BitWidth-NTZ-8;
763 
764           // Replace this with either a left or right shift to get the byte into
765           // the right place.
766           Instruction *NewVal;
767           if (InputBit > ResultBit)
768             NewVal = BinaryOperator::CreateLShr(II->getArgOperand(0),
769                     ConstantInt::get(I->getType(), InputBit-ResultBit));
770           else
771             NewVal = BinaryOperator::CreateShl(II->getArgOperand(0),
772                     ConstantInt::get(I->getType(), ResultBit-InputBit));
773           NewVal->takeName(I);
774           return InsertNewInstWith(NewVal, *I);
775         }
776         break;
777       }
778       case Intrinsic::fshr:
779       case Intrinsic::fshl: {
780         const APInt *SA;
781         if (!match(I->getOperand(2), m_APInt(SA)))
782           break;
783 
784         // Normalize to funnel shift left. APInt shifts of BitWidth are well-
785         // defined, so no need to special-case zero shifts here.
786         uint64_t ShiftAmt = SA->urem(BitWidth);
787         if (II->getIntrinsicID() == Intrinsic::fshr)
788           ShiftAmt = BitWidth - ShiftAmt;
789 
790         APInt DemandedMaskLHS(DemandedMask.lshr(ShiftAmt));
791         APInt DemandedMaskRHS(DemandedMask.shl(BitWidth - ShiftAmt));
792         if (SimplifyDemandedBits(I, 0, DemandedMaskLHS, LHSKnown, Depth + 1) ||
793             SimplifyDemandedBits(I, 1, DemandedMaskRHS, RHSKnown, Depth + 1))
794           return I;
795 
796         Known.Zero = LHSKnown.Zero.shl(ShiftAmt) |
797                      RHSKnown.Zero.lshr(BitWidth - ShiftAmt);
798         Known.One = LHSKnown.One.shl(ShiftAmt) |
799                     RHSKnown.One.lshr(BitWidth - ShiftAmt);
800         KnownBitsComputed = true;
801         break;
802       }
803       case Intrinsic::x86_mmx_pmovmskb:
804       case Intrinsic::x86_sse_movmsk_ps:
805       case Intrinsic::x86_sse2_movmsk_pd:
806       case Intrinsic::x86_sse2_pmovmskb_128:
807       case Intrinsic::x86_avx_movmsk_ps_256:
808       case Intrinsic::x86_avx_movmsk_pd_256:
809       case Intrinsic::x86_avx2_pmovmskb: {
810         // MOVMSK copies the vector elements' sign bits to the low bits
811         // and zeros the high bits.
812         unsigned ArgWidth;
813         if (II->getIntrinsicID() == Intrinsic::x86_mmx_pmovmskb) {
814           ArgWidth = 8; // Arg is x86_mmx, but treated as <8 x i8>.
815         } else {
816           auto Arg = II->getArgOperand(0);
817           auto ArgType = cast<VectorType>(Arg->getType());
818           ArgWidth = ArgType->getNumElements();
819         }
820 
821         // If we don't need any of low bits then return zero,
822         // we know that DemandedMask is non-zero already.
823         APInt DemandedElts = DemandedMask.zextOrTrunc(ArgWidth);
824         if (DemandedElts.isNullValue())
825           return ConstantInt::getNullValue(VTy);
826 
827         // We know that the upper bits are set to zero.
828         Known.Zero.setBitsFrom(ArgWidth);
829         KnownBitsComputed = true;
830         break;
831       }
832       case Intrinsic::x86_sse42_crc32_64_64:
833         Known.Zero.setBitsFrom(32);
834         KnownBitsComputed = true;
835         break;
836       }
837     }
838 
839     if (!KnownBitsComputed)
840       computeKnownBits(V, Known, Depth, CxtI);
841     break;
842   }
843   }
844 
845   // If the client is only demanding bits that we know, return the known
846   // constant.
847   if (DemandedMask.isSubsetOf(Known.Zero|Known.One))
848     return Constant::getIntegerValue(VTy, Known.One);
849   return nullptr;
850 }
851 
852 /// Helper routine of SimplifyDemandedUseBits. It computes Known
853 /// bits. It also tries to handle simplifications that can be done based on
854 /// DemandedMask, but without modifying the Instruction.
855 Value *InstCombiner::SimplifyMultipleUseDemandedBits(Instruction *I,
856                                                      const APInt &DemandedMask,
857                                                      KnownBits &Known,
858                                                      unsigned Depth,
859                                                      Instruction *CxtI) {
860   unsigned BitWidth = DemandedMask.getBitWidth();
861   Type *ITy = I->getType();
862 
863   KnownBits LHSKnown(BitWidth);
864   KnownBits RHSKnown(BitWidth);
865 
866   // Despite the fact that we can't simplify this instruction in all User's
867   // context, we can at least compute the known bits, and we can
868   // do simplifications that apply to *just* the one user if we know that
869   // this instruction has a simpler value in that context.
870   switch (I->getOpcode()) {
871   case Instruction::And: {
872     // If either the LHS or the RHS are Zero, the result is zero.
873     computeKnownBits(I->getOperand(1), RHSKnown, Depth + 1, CxtI);
874     computeKnownBits(I->getOperand(0), LHSKnown, Depth + 1,
875                      CxtI);
876 
877     // Output known-0 are known to be clear if zero in either the LHS | RHS.
878     APInt IKnownZero = RHSKnown.Zero | LHSKnown.Zero;
879     // Output known-1 bits are only known if set in both the LHS & RHS.
880     APInt IKnownOne = RHSKnown.One & LHSKnown.One;
881 
882     // If the client is only demanding bits that we know, return the known
883     // constant.
884     if (DemandedMask.isSubsetOf(IKnownZero|IKnownOne))
885       return Constant::getIntegerValue(ITy, IKnownOne);
886 
887     // If all of the demanded bits are known 1 on one side, return the other.
888     // These bits cannot contribute to the result of the 'and' in this
889     // context.
890     if (DemandedMask.isSubsetOf(LHSKnown.Zero | RHSKnown.One))
891       return I->getOperand(0);
892     if (DemandedMask.isSubsetOf(RHSKnown.Zero | LHSKnown.One))
893       return I->getOperand(1);
894 
895     Known.Zero = std::move(IKnownZero);
896     Known.One  = std::move(IKnownOne);
897     break;
898   }
899   case Instruction::Or: {
900     // We can simplify (X|Y) -> X or Y in the user's context if we know that
901     // only bits from X or Y are demanded.
902 
903     // If either the LHS or the RHS are One, the result is One.
904     computeKnownBits(I->getOperand(1), RHSKnown, Depth + 1, CxtI);
905     computeKnownBits(I->getOperand(0), LHSKnown, Depth + 1,
906                      CxtI);
907 
908     // Output known-0 bits are only known if clear in both the LHS & RHS.
909     APInt IKnownZero = RHSKnown.Zero & LHSKnown.Zero;
910     // Output known-1 are known to be set if set in either the LHS | RHS.
911     APInt IKnownOne = RHSKnown.One | LHSKnown.One;
912 
913     // If the client is only demanding bits that we know, return the known
914     // constant.
915     if (DemandedMask.isSubsetOf(IKnownZero|IKnownOne))
916       return Constant::getIntegerValue(ITy, IKnownOne);
917 
918     // If all of the demanded bits are known zero on one side, return the
919     // other.  These bits cannot contribute to the result of the 'or' in this
920     // context.
921     if (DemandedMask.isSubsetOf(LHSKnown.One | RHSKnown.Zero))
922       return I->getOperand(0);
923     if (DemandedMask.isSubsetOf(RHSKnown.One | LHSKnown.Zero))
924       return I->getOperand(1);
925 
926     Known.Zero = std::move(IKnownZero);
927     Known.One  = std::move(IKnownOne);
928     break;
929   }
930   case Instruction::Xor: {
931     // We can simplify (X^Y) -> X or Y in the user's context if we know that
932     // only bits from X or Y are demanded.
933 
934     computeKnownBits(I->getOperand(1), RHSKnown, Depth + 1, CxtI);
935     computeKnownBits(I->getOperand(0), LHSKnown, Depth + 1,
936                      CxtI);
937 
938     // Output known-0 bits are known if clear or set in both the LHS & RHS.
939     APInt IKnownZero = (RHSKnown.Zero & LHSKnown.Zero) |
940                        (RHSKnown.One & LHSKnown.One);
941     // Output known-1 are known to be set if set in only one of the LHS, RHS.
942     APInt IKnownOne =  (RHSKnown.Zero & LHSKnown.One) |
943                        (RHSKnown.One & LHSKnown.Zero);
944 
945     // If the client is only demanding bits that we know, return the known
946     // constant.
947     if (DemandedMask.isSubsetOf(IKnownZero|IKnownOne))
948       return Constant::getIntegerValue(ITy, IKnownOne);
949 
950     // If all of the demanded bits are known zero on one side, return the
951     // other.
952     if (DemandedMask.isSubsetOf(RHSKnown.Zero))
953       return I->getOperand(0);
954     if (DemandedMask.isSubsetOf(LHSKnown.Zero))
955       return I->getOperand(1);
956 
957     // Output known-0 bits are known if clear or set in both the LHS & RHS.
958     Known.Zero = std::move(IKnownZero);
959     // Output known-1 are known to be set if set in only one of the LHS, RHS.
960     Known.One  = std::move(IKnownOne);
961     break;
962   }
963   default:
964     // Compute the Known bits to simplify things downstream.
965     computeKnownBits(I, Known, Depth, CxtI);
966 
967     // If this user is only demanding bits that we know, return the known
968     // constant.
969     if (DemandedMask.isSubsetOf(Known.Zero|Known.One))
970       return Constant::getIntegerValue(ITy, Known.One);
971 
972     break;
973   }
974 
975   return nullptr;
976 }
977 
978 
979 /// Helper routine of SimplifyDemandedUseBits. It tries to simplify
980 /// "E1 = (X lsr C1) << C2", where the C1 and C2 are constant, into
981 /// "E2 = X << (C2 - C1)" or "E2 = X >> (C1 - C2)", depending on the sign
982 /// of "C2-C1".
983 ///
984 /// Suppose E1 and E2 are generally different in bits S={bm, bm+1,
985 /// ..., bn}, without considering the specific value X is holding.
986 /// This transformation is legal iff one of following conditions is hold:
987 ///  1) All the bit in S are 0, in this case E1 == E2.
988 ///  2) We don't care those bits in S, per the input DemandedMask.
989 ///  3) Combination of 1) and 2). Some bits in S are 0, and we don't care the
990 ///     rest bits.
991 ///
992 /// Currently we only test condition 2).
993 ///
994 /// As with SimplifyDemandedUseBits, it returns NULL if the simplification was
995 /// not successful.
996 Value *
997 InstCombiner::simplifyShrShlDemandedBits(Instruction *Shr, const APInt &ShrOp1,
998                                          Instruction *Shl, const APInt &ShlOp1,
999                                          const APInt &DemandedMask,
1000                                          KnownBits &Known) {
1001   if (!ShlOp1 || !ShrOp1)
1002     return nullptr; // No-op.
1003 
1004   Value *VarX = Shr->getOperand(0);
1005   Type *Ty = VarX->getType();
1006   unsigned BitWidth = Ty->getScalarSizeInBits();
1007   if (ShlOp1.uge(BitWidth) || ShrOp1.uge(BitWidth))
1008     return nullptr; // Undef.
1009 
1010   unsigned ShlAmt = ShlOp1.getZExtValue();
1011   unsigned ShrAmt = ShrOp1.getZExtValue();
1012 
1013   Known.One.clearAllBits();
1014   Known.Zero.setLowBits(ShlAmt - 1);
1015   Known.Zero &= DemandedMask;
1016 
1017   APInt BitMask1(APInt::getAllOnesValue(BitWidth));
1018   APInt BitMask2(APInt::getAllOnesValue(BitWidth));
1019 
1020   bool isLshr = (Shr->getOpcode() == Instruction::LShr);
1021   BitMask1 = isLshr ? (BitMask1.lshr(ShrAmt) << ShlAmt) :
1022                       (BitMask1.ashr(ShrAmt) << ShlAmt);
1023 
1024   if (ShrAmt <= ShlAmt) {
1025     BitMask2 <<= (ShlAmt - ShrAmt);
1026   } else {
1027     BitMask2 = isLshr ? BitMask2.lshr(ShrAmt - ShlAmt):
1028                         BitMask2.ashr(ShrAmt - ShlAmt);
1029   }
1030 
1031   // Check if condition-2 (see the comment to this function) is satified.
1032   if ((BitMask1 & DemandedMask) == (BitMask2 & DemandedMask)) {
1033     if (ShrAmt == ShlAmt)
1034       return VarX;
1035 
1036     if (!Shr->hasOneUse())
1037       return nullptr;
1038 
1039     BinaryOperator *New;
1040     if (ShrAmt < ShlAmt) {
1041       Constant *Amt = ConstantInt::get(VarX->getType(), ShlAmt - ShrAmt);
1042       New = BinaryOperator::CreateShl(VarX, Amt);
1043       BinaryOperator *Orig = cast<BinaryOperator>(Shl);
1044       New->setHasNoSignedWrap(Orig->hasNoSignedWrap());
1045       New->setHasNoUnsignedWrap(Orig->hasNoUnsignedWrap());
1046     } else {
1047       Constant *Amt = ConstantInt::get(VarX->getType(), ShrAmt - ShlAmt);
1048       New = isLshr ? BinaryOperator::CreateLShr(VarX, Amt) :
1049                      BinaryOperator::CreateAShr(VarX, Amt);
1050       if (cast<BinaryOperator>(Shr)->isExact())
1051         New->setIsExact(true);
1052     }
1053 
1054     return InsertNewInstWith(New, *Shl);
1055   }
1056 
1057   return nullptr;
1058 }
1059 
1060 /// Implement SimplifyDemandedVectorElts for amdgcn buffer and image intrinsics.
1061 ///
1062 /// Note: This only supports non-TFE/LWE image intrinsic calls; those have
1063 ///       struct returns.
1064 Value *InstCombiner::simplifyAMDGCNMemoryIntrinsicDemanded(IntrinsicInst *II,
1065                                                            APInt DemandedElts,
1066                                                            int DMaskIdx) {
1067 
1068   // FIXME: Allow v3i16/v3f16 in buffer intrinsics when the types are fully supported.
1069   if (DMaskIdx < 0 &&
1070       II->getType()->getScalarSizeInBits() != 32 &&
1071       DemandedElts.getActiveBits() == 3)
1072     return nullptr;
1073 
1074   unsigned VWidth = II->getType()->getVectorNumElements();
1075   if (VWidth == 1)
1076     return nullptr;
1077 
1078   IRBuilderBase::InsertPointGuard Guard(Builder);
1079   Builder.SetInsertPoint(II);
1080 
1081   // Assume the arguments are unchanged and later override them, if needed.
1082   SmallVector<Value *, 16> Args(II->arg_begin(), II->arg_end());
1083 
1084   if (DMaskIdx < 0) {
1085     // Buffer case.
1086 
1087     const unsigned ActiveBits = DemandedElts.getActiveBits();
1088     const unsigned UnusedComponentsAtFront = DemandedElts.countTrailingZeros();
1089 
1090     // Start assuming the prefix of elements is demanded, but possibly clear
1091     // some other bits if there are trailing zeros (unused components at front)
1092     // and update offset.
1093     DemandedElts = (1 << ActiveBits) - 1;
1094 
1095     if (UnusedComponentsAtFront > 0) {
1096       static const unsigned InvalidOffsetIdx = 0xf;
1097 
1098       unsigned OffsetIdx;
1099       switch (II->getIntrinsicID()) {
1100       case Intrinsic::amdgcn_raw_buffer_load:
1101         OffsetIdx = 1;
1102         break;
1103       case Intrinsic::amdgcn_s_buffer_load:
1104         // If resulting type is vec3, there is no point in trimming the
1105         // load with updated offset, as the vec3 would most likely be widened to
1106         // vec4 anyway during lowering.
1107         if (ActiveBits == 4 && UnusedComponentsAtFront == 1)
1108           OffsetIdx = InvalidOffsetIdx;
1109         else
1110           OffsetIdx = 1;
1111         break;
1112       case Intrinsic::amdgcn_struct_buffer_load:
1113         OffsetIdx = 2;
1114         break;
1115       default:
1116         // TODO: handle tbuffer* intrinsics.
1117         OffsetIdx = InvalidOffsetIdx;
1118         break;
1119       }
1120 
1121       if (OffsetIdx != InvalidOffsetIdx) {
1122         // Clear demanded bits and update the offset.
1123         DemandedElts &= ~((1 << UnusedComponentsAtFront) - 1);
1124         auto *Offset = II->getArgOperand(OffsetIdx);
1125         unsigned SingleComponentSizeInBits =
1126             getDataLayout().getTypeSizeInBits(II->getType()->getScalarType());
1127         unsigned OffsetAdd =
1128             UnusedComponentsAtFront * SingleComponentSizeInBits / 8;
1129         auto *OffsetAddVal = ConstantInt::get(Offset->getType(), OffsetAdd);
1130         Args[OffsetIdx] = Builder.CreateAdd(Offset, OffsetAddVal);
1131       }
1132     }
1133   } else {
1134     // Image case.
1135 
1136     ConstantInt *DMask = cast<ConstantInt>(II->getArgOperand(DMaskIdx));
1137     unsigned DMaskVal = DMask->getZExtValue() & 0xf;
1138 
1139     // Mask off values that are undefined because the dmask doesn't cover them
1140     DemandedElts &= (1 << countPopulation(DMaskVal)) - 1;
1141 
1142     unsigned NewDMaskVal = 0;
1143     unsigned OrigLoadIdx = 0;
1144     for (unsigned SrcIdx = 0; SrcIdx < 4; ++SrcIdx) {
1145       const unsigned Bit = 1 << SrcIdx;
1146       if (!!(DMaskVal & Bit)) {
1147         if (!!DemandedElts[OrigLoadIdx])
1148           NewDMaskVal |= Bit;
1149         OrigLoadIdx++;
1150       }
1151     }
1152 
1153     if (DMaskVal != NewDMaskVal)
1154       Args[DMaskIdx] = ConstantInt::get(DMask->getType(), NewDMaskVal);
1155   }
1156 
1157   unsigned NewNumElts = DemandedElts.countPopulation();
1158   if (!NewNumElts)
1159     return UndefValue::get(II->getType());
1160 
1161   if (NewNumElts >= VWidth && DemandedElts.isMask()) {
1162     if (DMaskIdx >= 0)
1163       II->setArgOperand(DMaskIdx, Args[DMaskIdx]);
1164     return nullptr;
1165   }
1166 
1167   // Determine the overload types of the original intrinsic.
1168   auto IID = II->getIntrinsicID();
1169   SmallVector<Intrinsic::IITDescriptor, 16> Table;
1170   getIntrinsicInfoTableEntries(IID, Table);
1171   ArrayRef<Intrinsic::IITDescriptor> TableRef = Table;
1172 
1173   // Validate function argument and return types, extracting overloaded types
1174   // along the way.
1175   FunctionType *FTy = II->getCalledFunction()->getFunctionType();
1176   SmallVector<Type *, 6> OverloadTys;
1177   Intrinsic::matchIntrinsicSignature(FTy, TableRef, OverloadTys);
1178 
1179   Module *M = II->getParent()->getParent()->getParent();
1180   Type *EltTy = II->getType()->getVectorElementType();
1181   Type *NewTy = (NewNumElts == 1) ? EltTy : VectorType::get(EltTy, NewNumElts);
1182 
1183   OverloadTys[0] = NewTy;
1184   Function *NewIntrin = Intrinsic::getDeclaration(M, IID, OverloadTys);
1185 
1186   CallInst *NewCall = Builder.CreateCall(NewIntrin, Args);
1187   NewCall->takeName(II);
1188   NewCall->copyMetadata(*II);
1189 
1190   if (NewNumElts == 1) {
1191     return Builder.CreateInsertElement(UndefValue::get(II->getType()), NewCall,
1192                                        DemandedElts.countTrailingZeros());
1193   }
1194 
1195   SmallVector<uint32_t, 8> EltMask;
1196   unsigned NewLoadIdx = 0;
1197   for (unsigned OrigLoadIdx = 0; OrigLoadIdx < VWidth; ++OrigLoadIdx) {
1198     if (!!DemandedElts[OrigLoadIdx])
1199       EltMask.push_back(NewLoadIdx++);
1200     else
1201       EltMask.push_back(NewNumElts);
1202   }
1203 
1204   Value *Shuffle =
1205       Builder.CreateShuffleVector(NewCall, UndefValue::get(NewTy), EltMask);
1206 
1207   return Shuffle;
1208 }
1209 
1210 /// The specified value produces a vector with any number of elements.
1211 /// This method analyzes which elements of the operand are undef and returns
1212 /// that information in UndefElts.
1213 ///
1214 /// DemandedElts contains the set of elements that are actually used by the
1215 /// caller, and by default (AllowMultipleUsers equals false) the value is
1216 /// simplified only if it has a single caller. If AllowMultipleUsers is set
1217 /// to true, DemandedElts refers to the union of sets of elements that are
1218 /// used by all callers.
1219 ///
1220 /// If the information about demanded elements can be used to simplify the
1221 /// operation, the operation is simplified, then the resultant value is
1222 /// returned.  This returns null if no change was made.
1223 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1224                                                 APInt &UndefElts,
1225                                                 unsigned Depth,
1226                                                 bool AllowMultipleUsers) {
1227   unsigned VWidth = V->getType()->getVectorNumElements();
1228   APInt EltMask(APInt::getAllOnesValue(VWidth));
1229   assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
1230 
1231   if (isa<UndefValue>(V)) {
1232     // If the entire vector is undefined, just return this info.
1233     UndefElts = EltMask;
1234     return nullptr;
1235   }
1236 
1237   if (DemandedElts.isNullValue()) { // If nothing is demanded, provide undef.
1238     UndefElts = EltMask;
1239     return UndefValue::get(V->getType());
1240   }
1241 
1242   UndefElts = 0;
1243 
1244   if (auto *C = dyn_cast<Constant>(V)) {
1245     // Check if this is identity. If so, return 0 since we are not simplifying
1246     // anything.
1247     if (DemandedElts.isAllOnesValue())
1248       return nullptr;
1249 
1250     Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1251     Constant *Undef = UndefValue::get(EltTy);
1252     SmallVector<Constant*, 16> Elts;
1253     for (unsigned i = 0; i != VWidth; ++i) {
1254       if (!DemandedElts[i]) {   // If not demanded, set to undef.
1255         Elts.push_back(Undef);
1256         UndefElts.setBit(i);
1257         continue;
1258       }
1259 
1260       Constant *Elt = C->getAggregateElement(i);
1261       if (!Elt) return nullptr;
1262 
1263       if (isa<UndefValue>(Elt)) {   // Already undef.
1264         Elts.push_back(Undef);
1265         UndefElts.setBit(i);
1266       } else {                               // Otherwise, defined.
1267         Elts.push_back(Elt);
1268       }
1269     }
1270 
1271     // If we changed the constant, return it.
1272     Constant *NewCV = ConstantVector::get(Elts);
1273     return NewCV != C ? NewCV : nullptr;
1274   }
1275 
1276   // Limit search depth.
1277   if (Depth == 10)
1278     return nullptr;
1279 
1280   if (!AllowMultipleUsers) {
1281     // If multiple users are using the root value, proceed with
1282     // simplification conservatively assuming that all elements
1283     // are needed.
1284     if (!V->hasOneUse()) {
1285       // Quit if we find multiple users of a non-root value though.
1286       // They'll be handled when it's their turn to be visited by
1287       // the main instcombine process.
1288       if (Depth != 0)
1289         // TODO: Just compute the UndefElts information recursively.
1290         return nullptr;
1291 
1292       // Conservatively assume that all elements are needed.
1293       DemandedElts = EltMask;
1294     }
1295   }
1296 
1297   Instruction *I = dyn_cast<Instruction>(V);
1298   if (!I) return nullptr;        // Only analyze instructions.
1299 
1300   bool MadeChange = false;
1301   auto simplifyAndSetOp = [&](Instruction *Inst, unsigned OpNum,
1302                               APInt Demanded, APInt &Undef) {
1303     auto *II = dyn_cast<IntrinsicInst>(Inst);
1304     Value *Op = II ? II->getArgOperand(OpNum) : Inst->getOperand(OpNum);
1305     if (Value *V = SimplifyDemandedVectorElts(Op, Demanded, Undef, Depth + 1)) {
1306       replaceOperand(*Inst, OpNum, V);
1307       MadeChange = true;
1308     }
1309   };
1310 
1311   APInt UndefElts2(VWidth, 0);
1312   APInt UndefElts3(VWidth, 0);
1313   switch (I->getOpcode()) {
1314   default: break;
1315 
1316   case Instruction::GetElementPtr: {
1317     // The LangRef requires that struct geps have all constant indices.  As
1318     // such, we can't convert any operand to partial undef.
1319     auto mayIndexStructType = [](GetElementPtrInst &GEP) {
1320       for (auto I = gep_type_begin(GEP), E = gep_type_end(GEP);
1321            I != E; I++)
1322         if (I.isStruct())
1323           return true;;
1324       return false;
1325     };
1326     if (mayIndexStructType(cast<GetElementPtrInst>(*I)))
1327       break;
1328 
1329     // Conservatively track the demanded elements back through any vector
1330     // operands we may have.  We know there must be at least one, or we
1331     // wouldn't have a vector result to get here. Note that we intentionally
1332     // merge the undef bits here since gepping with either an undef base or
1333     // index results in undef.
1334     for (unsigned i = 0; i < I->getNumOperands(); i++) {
1335       if (isa<UndefValue>(I->getOperand(i))) {
1336         // If the entire vector is undefined, just return this info.
1337         UndefElts = EltMask;
1338         return nullptr;
1339       }
1340       if (I->getOperand(i)->getType()->isVectorTy()) {
1341         APInt UndefEltsOp(VWidth, 0);
1342         simplifyAndSetOp(I, i, DemandedElts, UndefEltsOp);
1343         UndefElts |= UndefEltsOp;
1344       }
1345     }
1346 
1347     break;
1348   }
1349   case Instruction::InsertElement: {
1350     // If this is a variable index, we don't know which element it overwrites.
1351     // demand exactly the same input as we produce.
1352     ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1353     if (!Idx) {
1354       // Note that we can't propagate undef elt info, because we don't know
1355       // which elt is getting updated.
1356       simplifyAndSetOp(I, 0, DemandedElts, UndefElts2);
1357       break;
1358     }
1359 
1360     // The element inserted overwrites whatever was there, so the input demanded
1361     // set is simpler than the output set.
1362     unsigned IdxNo = Idx->getZExtValue();
1363     APInt PreInsertDemandedElts = DemandedElts;
1364     if (IdxNo < VWidth)
1365       PreInsertDemandedElts.clearBit(IdxNo);
1366 
1367     simplifyAndSetOp(I, 0, PreInsertDemandedElts, UndefElts);
1368 
1369     // If this is inserting an element that isn't demanded, remove this
1370     // insertelement.
1371     if (IdxNo >= VWidth || !DemandedElts[IdxNo]) {
1372       Worklist.push(I);
1373       return I->getOperand(0);
1374     }
1375 
1376     // The inserted element is defined.
1377     UndefElts.clearBit(IdxNo);
1378     break;
1379   }
1380   case Instruction::ShuffleVector: {
1381     auto *Shuffle = cast<ShuffleVectorInst>(I);
1382     assert(Shuffle->getOperand(0)->getType() ==
1383            Shuffle->getOperand(1)->getType() &&
1384            "Expected shuffle operands to have same type");
1385     unsigned OpWidth =
1386         Shuffle->getOperand(0)->getType()->getVectorNumElements();
1387     APInt LeftDemanded(OpWidth, 0), RightDemanded(OpWidth, 0);
1388     for (unsigned i = 0; i < VWidth; i++) {
1389       if (DemandedElts[i]) {
1390         unsigned MaskVal = Shuffle->getMaskValue(i);
1391         if (MaskVal != -1u) {
1392           assert(MaskVal < OpWidth * 2 &&
1393                  "shufflevector mask index out of range!");
1394           if (MaskVal < OpWidth)
1395             LeftDemanded.setBit(MaskVal);
1396           else
1397             RightDemanded.setBit(MaskVal - OpWidth);
1398         }
1399       }
1400     }
1401 
1402     APInt LHSUndefElts(OpWidth, 0);
1403     simplifyAndSetOp(I, 0, LeftDemanded, LHSUndefElts);
1404 
1405     APInt RHSUndefElts(OpWidth, 0);
1406     simplifyAndSetOp(I, 1, RightDemanded, RHSUndefElts);
1407 
1408     // If this shuffle does not change the vector length and the elements
1409     // demanded by this shuffle are an identity mask, then this shuffle is
1410     // unnecessary.
1411     //
1412     // We are assuming canonical form for the mask, so the source vector is
1413     // operand 0 and operand 1 is not used.
1414     //
1415     // Note that if an element is demanded and this shuffle mask is undefined
1416     // for that element, then the shuffle is not considered an identity
1417     // operation. The shuffle prevents poison from the operand vector from
1418     // leaking to the result by replacing poison with an undefined value.
1419     if (VWidth == OpWidth) {
1420       bool IsIdentityShuffle = true;
1421       for (unsigned i = 0; i < VWidth; i++) {
1422         unsigned MaskVal = Shuffle->getMaskValue(i);
1423         if (DemandedElts[i] && i != MaskVal) {
1424           IsIdentityShuffle = false;
1425           break;
1426         }
1427       }
1428       if (IsIdentityShuffle)
1429         return Shuffle->getOperand(0);
1430     }
1431 
1432     bool NewUndefElts = false;
1433     unsigned LHSIdx = -1u, LHSValIdx = -1u;
1434     unsigned RHSIdx = -1u, RHSValIdx = -1u;
1435     bool LHSUniform = true;
1436     bool RHSUniform = true;
1437     for (unsigned i = 0; i < VWidth; i++) {
1438       unsigned MaskVal = Shuffle->getMaskValue(i);
1439       if (MaskVal == -1u) {
1440         UndefElts.setBit(i);
1441       } else if (!DemandedElts[i]) {
1442         NewUndefElts = true;
1443         UndefElts.setBit(i);
1444       } else if (MaskVal < OpWidth) {
1445         if (LHSUndefElts[MaskVal]) {
1446           NewUndefElts = true;
1447           UndefElts.setBit(i);
1448         } else {
1449           LHSIdx = LHSIdx == -1u ? i : OpWidth;
1450           LHSValIdx = LHSValIdx == -1u ? MaskVal : OpWidth;
1451           LHSUniform = LHSUniform && (MaskVal == i);
1452         }
1453       } else {
1454         if (RHSUndefElts[MaskVal - OpWidth]) {
1455           NewUndefElts = true;
1456           UndefElts.setBit(i);
1457         } else {
1458           RHSIdx = RHSIdx == -1u ? i : OpWidth;
1459           RHSValIdx = RHSValIdx == -1u ? MaskVal - OpWidth : OpWidth;
1460           RHSUniform = RHSUniform && (MaskVal - OpWidth == i);
1461         }
1462       }
1463     }
1464 
1465     // Try to transform shuffle with constant vector and single element from
1466     // this constant vector to single insertelement instruction.
1467     // shufflevector V, C, <v1, v2, .., ci, .., vm> ->
1468     // insertelement V, C[ci], ci-n
1469     if (OpWidth == Shuffle->getType()->getNumElements()) {
1470       Value *Op = nullptr;
1471       Constant *Value = nullptr;
1472       unsigned Idx = -1u;
1473 
1474       // Find constant vector with the single element in shuffle (LHS or RHS).
1475       if (LHSIdx < OpWidth && RHSUniform) {
1476         if (auto *CV = dyn_cast<ConstantVector>(Shuffle->getOperand(0))) {
1477           Op = Shuffle->getOperand(1);
1478           Value = CV->getOperand(LHSValIdx);
1479           Idx = LHSIdx;
1480         }
1481       }
1482       if (RHSIdx < OpWidth && LHSUniform) {
1483         if (auto *CV = dyn_cast<ConstantVector>(Shuffle->getOperand(1))) {
1484           Op = Shuffle->getOperand(0);
1485           Value = CV->getOperand(RHSValIdx);
1486           Idx = RHSIdx;
1487         }
1488       }
1489       // Found constant vector with single element - convert to insertelement.
1490       if (Op && Value) {
1491         Instruction *New = InsertElementInst::Create(
1492             Op, Value, ConstantInt::get(Type::getInt32Ty(I->getContext()), Idx),
1493             Shuffle->getName());
1494         InsertNewInstWith(New, *Shuffle);
1495         return New;
1496       }
1497     }
1498     if (NewUndefElts) {
1499       // Add additional discovered undefs.
1500       SmallVector<Constant*, 16> Elts;
1501       for (unsigned i = 0; i < VWidth; ++i) {
1502         if (UndefElts[i])
1503           Elts.push_back(UndefValue::get(Type::getInt32Ty(I->getContext())));
1504         else
1505           Elts.push_back(ConstantInt::get(Type::getInt32Ty(I->getContext()),
1506                                           Shuffle->getMaskValue(i)));
1507       }
1508       I->setOperand(2, ConstantVector::get(Elts));
1509       MadeChange = true;
1510     }
1511     break;
1512   }
1513   case Instruction::Select: {
1514     // If this is a vector select, try to transform the select condition based
1515     // on the current demanded elements.
1516     SelectInst *Sel = cast<SelectInst>(I);
1517     if (Sel->getCondition()->getType()->isVectorTy()) {
1518       // TODO: We are not doing anything with UndefElts based on this call.
1519       // It is overwritten below based on the other select operands. If an
1520       // element of the select condition is known undef, then we are free to
1521       // choose the output value from either arm of the select. If we know that
1522       // one of those values is undef, then the output can be undef.
1523       simplifyAndSetOp(I, 0, DemandedElts, UndefElts);
1524     }
1525 
1526     // Next, see if we can transform the arms of the select.
1527     APInt DemandedLHS(DemandedElts), DemandedRHS(DemandedElts);
1528     if (auto *CV = dyn_cast<ConstantVector>(Sel->getCondition())) {
1529       for (unsigned i = 0; i < VWidth; i++) {
1530         // isNullValue() always returns false when called on a ConstantExpr.
1531         // Skip constant expressions to avoid propagating incorrect information.
1532         Constant *CElt = CV->getAggregateElement(i);
1533         if (isa<ConstantExpr>(CElt))
1534           continue;
1535         // TODO: If a select condition element is undef, we can demand from
1536         // either side. If one side is known undef, choosing that side would
1537         // propagate undef.
1538         if (CElt->isNullValue())
1539           DemandedLHS.clearBit(i);
1540         else
1541           DemandedRHS.clearBit(i);
1542       }
1543     }
1544 
1545     simplifyAndSetOp(I, 1, DemandedLHS, UndefElts2);
1546     simplifyAndSetOp(I, 2, DemandedRHS, UndefElts3);
1547 
1548     // Output elements are undefined if the element from each arm is undefined.
1549     // TODO: This can be improved. See comment in select condition handling.
1550     UndefElts = UndefElts2 & UndefElts3;
1551     break;
1552   }
1553   case Instruction::BitCast: {
1554     // Vector->vector casts only.
1555     VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1556     if (!VTy) break;
1557     unsigned InVWidth = VTy->getNumElements();
1558     APInt InputDemandedElts(InVWidth, 0);
1559     UndefElts2 = APInt(InVWidth, 0);
1560     unsigned Ratio;
1561 
1562     if (VWidth == InVWidth) {
1563       // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1564       // elements as are demanded of us.
1565       Ratio = 1;
1566       InputDemandedElts = DemandedElts;
1567     } else if ((VWidth % InVWidth) == 0) {
1568       // If the number of elements in the output is a multiple of the number of
1569       // elements in the input then an input element is live if any of the
1570       // corresponding output elements are live.
1571       Ratio = VWidth / InVWidth;
1572       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1573         if (DemandedElts[OutIdx])
1574           InputDemandedElts.setBit(OutIdx / Ratio);
1575     } else if ((InVWidth % VWidth) == 0) {
1576       // If the number of elements in the input is a multiple of the number of
1577       // elements in the output then an input element is live if the
1578       // corresponding output element is live.
1579       Ratio = InVWidth / VWidth;
1580       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1581         if (DemandedElts[InIdx / Ratio])
1582           InputDemandedElts.setBit(InIdx);
1583     } else {
1584       // Unsupported so far.
1585       break;
1586     }
1587 
1588     simplifyAndSetOp(I, 0, InputDemandedElts, UndefElts2);
1589 
1590     if (VWidth == InVWidth) {
1591       UndefElts = UndefElts2;
1592     } else if ((VWidth % InVWidth) == 0) {
1593       // If the number of elements in the output is a multiple of the number of
1594       // elements in the input then an output element is undef if the
1595       // corresponding input element is undef.
1596       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1597         if (UndefElts2[OutIdx / Ratio])
1598           UndefElts.setBit(OutIdx);
1599     } else if ((InVWidth % VWidth) == 0) {
1600       // If the number of elements in the input is a multiple of the number of
1601       // elements in the output then an output element is undef if all of the
1602       // corresponding input elements are undef.
1603       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1604         APInt SubUndef = UndefElts2.lshr(OutIdx * Ratio).zextOrTrunc(Ratio);
1605         if (SubUndef.countPopulation() == Ratio)
1606           UndefElts.setBit(OutIdx);
1607       }
1608     } else {
1609       llvm_unreachable("Unimp");
1610     }
1611     break;
1612   }
1613   case Instruction::FPTrunc:
1614   case Instruction::FPExt:
1615     simplifyAndSetOp(I, 0, DemandedElts, UndefElts);
1616     break;
1617 
1618   case Instruction::Call: {
1619     IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1620     if (!II) break;
1621     switch (II->getIntrinsicID()) {
1622     case Intrinsic::masked_gather: // fallthrough
1623     case Intrinsic::masked_load: {
1624       // Subtlety: If we load from a pointer, the pointer must be valid
1625       // regardless of whether the element is demanded.  Doing otherwise risks
1626       // segfaults which didn't exist in the original program.
1627       APInt DemandedPtrs(APInt::getAllOnesValue(VWidth)),
1628         DemandedPassThrough(DemandedElts);
1629       if (auto *CV = dyn_cast<ConstantVector>(II->getOperand(2)))
1630         for (unsigned i = 0; i < VWidth; i++) {
1631           Constant *CElt = CV->getAggregateElement(i);
1632           if (CElt->isNullValue())
1633             DemandedPtrs.clearBit(i);
1634           else if (CElt->isAllOnesValue())
1635             DemandedPassThrough.clearBit(i);
1636         }
1637       if (II->getIntrinsicID() == Intrinsic::masked_gather)
1638         simplifyAndSetOp(II, 0, DemandedPtrs, UndefElts2);
1639       simplifyAndSetOp(II, 3, DemandedPassThrough, UndefElts3);
1640 
1641       // Output elements are undefined if the element from both sources are.
1642       // TODO: can strengthen via mask as well.
1643       UndefElts = UndefElts2 & UndefElts3;
1644       break;
1645     }
1646     case Intrinsic::x86_xop_vfrcz_ss:
1647     case Intrinsic::x86_xop_vfrcz_sd:
1648       // The instructions for these intrinsics are speced to zero upper bits not
1649       // pass them through like other scalar intrinsics. So we shouldn't just
1650       // use Arg0 if DemandedElts[0] is clear like we do for other intrinsics.
1651       // Instead we should return a zero vector.
1652       if (!DemandedElts[0]) {
1653         Worklist.push(II);
1654         return ConstantAggregateZero::get(II->getType());
1655       }
1656 
1657       // Only the lower element is used.
1658       DemandedElts = 1;
1659       simplifyAndSetOp(II, 0, DemandedElts, UndefElts);
1660 
1661       // Only the lower element is undefined. The high elements are zero.
1662       UndefElts = UndefElts[0];
1663       break;
1664 
1665     // Unary scalar-as-vector operations that work column-wise.
1666     case Intrinsic::x86_sse_rcp_ss:
1667     case Intrinsic::x86_sse_rsqrt_ss:
1668       simplifyAndSetOp(II, 0, DemandedElts, UndefElts);
1669 
1670       // If lowest element of a scalar op isn't used then use Arg0.
1671       if (!DemandedElts[0]) {
1672         Worklist.push(II);
1673         return II->getArgOperand(0);
1674       }
1675       // TODO: If only low elt lower SQRT to FSQRT (with rounding/exceptions
1676       // checks).
1677       break;
1678 
1679     // Binary scalar-as-vector operations that work column-wise. The high
1680     // elements come from operand 0. The low element is a function of both
1681     // operands.
1682     case Intrinsic::x86_sse_min_ss:
1683     case Intrinsic::x86_sse_max_ss:
1684     case Intrinsic::x86_sse_cmp_ss:
1685     case Intrinsic::x86_sse2_min_sd:
1686     case Intrinsic::x86_sse2_max_sd:
1687     case Intrinsic::x86_sse2_cmp_sd: {
1688       simplifyAndSetOp(II, 0, DemandedElts, UndefElts);
1689 
1690       // If lowest element of a scalar op isn't used then use Arg0.
1691       if (!DemandedElts[0]) {
1692         Worklist.push(II);
1693         return II->getArgOperand(0);
1694       }
1695 
1696       // Only lower element is used for operand 1.
1697       DemandedElts = 1;
1698       simplifyAndSetOp(II, 1, DemandedElts, UndefElts2);
1699 
1700       // Lower element is undefined if both lower elements are undefined.
1701       // Consider things like undef&0.  The result is known zero, not undef.
1702       if (!UndefElts2[0])
1703         UndefElts.clearBit(0);
1704 
1705       break;
1706     }
1707 
1708     // Binary scalar-as-vector operations that work column-wise. The high
1709     // elements come from operand 0 and the low element comes from operand 1.
1710     case Intrinsic::x86_sse41_round_ss:
1711     case Intrinsic::x86_sse41_round_sd: {
1712       // Don't use the low element of operand 0.
1713       APInt DemandedElts2 = DemandedElts;
1714       DemandedElts2.clearBit(0);
1715       simplifyAndSetOp(II, 0, DemandedElts2, UndefElts);
1716 
1717       // If lowest element of a scalar op isn't used then use Arg0.
1718       if (!DemandedElts[0]) {
1719         Worklist.push(II);
1720         return II->getArgOperand(0);
1721       }
1722 
1723       // Only lower element is used for operand 1.
1724       DemandedElts = 1;
1725       simplifyAndSetOp(II, 1, DemandedElts, UndefElts2);
1726 
1727       // Take the high undef elements from operand 0 and take the lower element
1728       // from operand 1.
1729       UndefElts.clearBit(0);
1730       UndefElts |= UndefElts2[0];
1731       break;
1732     }
1733 
1734     // Three input scalar-as-vector operations that work column-wise. The high
1735     // elements come from operand 0 and the low element is a function of all
1736     // three inputs.
1737     case Intrinsic::x86_avx512_mask_add_ss_round:
1738     case Intrinsic::x86_avx512_mask_div_ss_round:
1739     case Intrinsic::x86_avx512_mask_mul_ss_round:
1740     case Intrinsic::x86_avx512_mask_sub_ss_round:
1741     case Intrinsic::x86_avx512_mask_max_ss_round:
1742     case Intrinsic::x86_avx512_mask_min_ss_round:
1743     case Intrinsic::x86_avx512_mask_add_sd_round:
1744     case Intrinsic::x86_avx512_mask_div_sd_round:
1745     case Intrinsic::x86_avx512_mask_mul_sd_round:
1746     case Intrinsic::x86_avx512_mask_sub_sd_round:
1747     case Intrinsic::x86_avx512_mask_max_sd_round:
1748     case Intrinsic::x86_avx512_mask_min_sd_round:
1749       simplifyAndSetOp(II, 0, DemandedElts, UndefElts);
1750 
1751       // If lowest element of a scalar op isn't used then use Arg0.
1752       if (!DemandedElts[0]) {
1753         Worklist.push(II);
1754         return II->getArgOperand(0);
1755       }
1756 
1757       // Only lower element is used for operand 1 and 2.
1758       DemandedElts = 1;
1759       simplifyAndSetOp(II, 1, DemandedElts, UndefElts2);
1760       simplifyAndSetOp(II, 2, DemandedElts, UndefElts3);
1761 
1762       // Lower element is undefined if all three lower elements are undefined.
1763       // Consider things like undef&0.  The result is known zero, not undef.
1764       if (!UndefElts2[0] || !UndefElts3[0])
1765         UndefElts.clearBit(0);
1766 
1767       break;
1768 
1769     case Intrinsic::x86_sse2_packssdw_128:
1770     case Intrinsic::x86_sse2_packsswb_128:
1771     case Intrinsic::x86_sse2_packuswb_128:
1772     case Intrinsic::x86_sse41_packusdw:
1773     case Intrinsic::x86_avx2_packssdw:
1774     case Intrinsic::x86_avx2_packsswb:
1775     case Intrinsic::x86_avx2_packusdw:
1776     case Intrinsic::x86_avx2_packuswb:
1777     case Intrinsic::x86_avx512_packssdw_512:
1778     case Intrinsic::x86_avx512_packsswb_512:
1779     case Intrinsic::x86_avx512_packusdw_512:
1780     case Intrinsic::x86_avx512_packuswb_512: {
1781       auto *Ty0 = II->getArgOperand(0)->getType();
1782       unsigned InnerVWidth = Ty0->getVectorNumElements();
1783       assert(VWidth == (InnerVWidth * 2) && "Unexpected input size");
1784 
1785       unsigned NumLanes = Ty0->getPrimitiveSizeInBits() / 128;
1786       unsigned VWidthPerLane = VWidth / NumLanes;
1787       unsigned InnerVWidthPerLane = InnerVWidth / NumLanes;
1788 
1789       // Per lane, pack the elements of the first input and then the second.
1790       // e.g.
1791       // v8i16 PACK(v4i32 X, v4i32 Y) - (X[0..3],Y[0..3])
1792       // v32i8 PACK(v16i16 X, v16i16 Y) - (X[0..7],Y[0..7]),(X[8..15],Y[8..15])
1793       for (int OpNum = 0; OpNum != 2; ++OpNum) {
1794         APInt OpDemandedElts(InnerVWidth, 0);
1795         for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
1796           unsigned LaneIdx = Lane * VWidthPerLane;
1797           for (unsigned Elt = 0; Elt != InnerVWidthPerLane; ++Elt) {
1798             unsigned Idx = LaneIdx + Elt + InnerVWidthPerLane * OpNum;
1799             if (DemandedElts[Idx])
1800               OpDemandedElts.setBit((Lane * InnerVWidthPerLane) + Elt);
1801           }
1802         }
1803 
1804         // Demand elements from the operand.
1805         APInt OpUndefElts(InnerVWidth, 0);
1806         simplifyAndSetOp(II, OpNum, OpDemandedElts, OpUndefElts);
1807 
1808         // Pack the operand's UNDEF elements, one lane at a time.
1809         OpUndefElts = OpUndefElts.zext(VWidth);
1810         for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
1811           APInt LaneElts = OpUndefElts.lshr(InnerVWidthPerLane * Lane);
1812           LaneElts = LaneElts.getLoBits(InnerVWidthPerLane);
1813           LaneElts <<= InnerVWidthPerLane * (2 * Lane + OpNum);
1814           UndefElts |= LaneElts;
1815         }
1816       }
1817       break;
1818     }
1819 
1820     // PSHUFB
1821     case Intrinsic::x86_ssse3_pshuf_b_128:
1822     case Intrinsic::x86_avx2_pshuf_b:
1823     case Intrinsic::x86_avx512_pshuf_b_512:
1824     // PERMILVAR
1825     case Intrinsic::x86_avx_vpermilvar_ps:
1826     case Intrinsic::x86_avx_vpermilvar_ps_256:
1827     case Intrinsic::x86_avx512_vpermilvar_ps_512:
1828     case Intrinsic::x86_avx_vpermilvar_pd:
1829     case Intrinsic::x86_avx_vpermilvar_pd_256:
1830     case Intrinsic::x86_avx512_vpermilvar_pd_512:
1831     // PERMV
1832     case Intrinsic::x86_avx2_permd:
1833     case Intrinsic::x86_avx2_permps: {
1834       simplifyAndSetOp(II, 1, DemandedElts, UndefElts);
1835       break;
1836     }
1837 
1838     // SSE4A instructions leave the upper 64-bits of the 128-bit result
1839     // in an undefined state.
1840     case Intrinsic::x86_sse4a_extrq:
1841     case Intrinsic::x86_sse4a_extrqi:
1842     case Intrinsic::x86_sse4a_insertq:
1843     case Intrinsic::x86_sse4a_insertqi:
1844       UndefElts.setHighBits(VWidth / 2);
1845       break;
1846     case Intrinsic::amdgcn_buffer_load:
1847     case Intrinsic::amdgcn_buffer_load_format:
1848     case Intrinsic::amdgcn_raw_buffer_load:
1849     case Intrinsic::amdgcn_raw_buffer_load_format:
1850     case Intrinsic::amdgcn_raw_tbuffer_load:
1851     case Intrinsic::amdgcn_s_buffer_load:
1852     case Intrinsic::amdgcn_struct_buffer_load:
1853     case Intrinsic::amdgcn_struct_buffer_load_format:
1854     case Intrinsic::amdgcn_struct_tbuffer_load:
1855     case Intrinsic::amdgcn_tbuffer_load:
1856       return simplifyAMDGCNMemoryIntrinsicDemanded(II, DemandedElts);
1857     default: {
1858       if (getAMDGPUImageDMaskIntrinsic(II->getIntrinsicID()))
1859         return simplifyAMDGCNMemoryIntrinsicDemanded(II, DemandedElts, 0);
1860 
1861       break;
1862     }
1863     } // switch on IntrinsicID
1864     break;
1865   } // case Call
1866   } // switch on Opcode
1867 
1868   // TODO: We bail completely on integer div/rem and shifts because they have
1869   // UB/poison potential, but that should be refined.
1870   BinaryOperator *BO;
1871   if (match(I, m_BinOp(BO)) && !BO->isIntDivRem() && !BO->isShift()) {
1872     simplifyAndSetOp(I, 0, DemandedElts, UndefElts);
1873     simplifyAndSetOp(I, 1, DemandedElts, UndefElts2);
1874 
1875     // Any change to an instruction with potential poison must clear those flags
1876     // because we can not guarantee those constraints now. Other analysis may
1877     // determine that it is safe to re-apply the flags.
1878     if (MadeChange)
1879       BO->dropPoisonGeneratingFlags();
1880 
1881     // Output elements are undefined if both are undefined. Consider things
1882     // like undef & 0. The result is known zero, not undef.
1883     UndefElts &= UndefElts2;
1884   }
1885 
1886   // If we've proven all of the lanes undef, return an undef value.
1887   // TODO: Intersect w/demanded lanes
1888   if (UndefElts.isAllOnesValue())
1889     return UndefValue::get(I->getType());;
1890 
1891   return MadeChange ? I : nullptr;
1892 }
1893