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