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