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