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