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