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