InstCombine: Don't unconditionally preserve 'nsw' when shrinking constants
[oota-llvm.git] / 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 "InstCombine.h"
16 #include "llvm/IR/DataLayout.h"
17 #include "llvm/IR/IntrinsicInst.h"
18 #include "llvm/IR/PatternMatch.h"
19
20 using namespace llvm;
21 using namespace llvm::PatternMatch;
22
23 #define DEBUG_TYPE "instcombine"
24
25 /// ShrinkDemandedConstant - Check to see if the specified operand of the
26 /// specified instruction is a constant integer.  If so, check to see if there
27 /// are any bits set in the constant that are not demanded.  If so, shrink the
28 /// constant and return true.
29 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
30                                    APInt Demanded) {
31   assert(I && "No instruction?");
32   assert(OpNo < I->getNumOperands() && "Operand index too large");
33
34   // If the operand is not a constant integer, nothing to do.
35   ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
36   if (!OpC) return false;
37
38   // If there are no bits set that aren't demanded, nothing to do.
39   Demanded = Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
40   if ((~Demanded & OpC->getValue()) == 0)
41     return false;
42
43   // This instruction is producing bits that are not demanded. Shrink the RHS.
44   Demanded &= OpC->getValue();
45   I->setOperand(OpNo, ConstantInt::get(OpC->getType(), Demanded));
46
47   // If 'nsw' is set and the constant is negative, removing *any* bits from the
48   // constant could make overflow occur.  Remove 'nsw' from the instruction in
49   // this case.
50   if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(I))
51     if (OBO->hasNoSignedWrap() && OpC->getValue().isNegative())
52       cast<BinaryOperator>(OBO)->setHasNoSignedWrap(false);
53
54   return true;
55 }
56
57
58
59 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
60 /// SimplifyDemandedBits knows about.  See if the instruction has any
61 /// properties that allow us to simplify its operands.
62 bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
63   unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
64   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
65   APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
66
67   Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask,
68                                      KnownZero, KnownOne, 0);
69   if (!V) return false;
70   if (V == &Inst) return true;
71   ReplaceInstUsesWith(Inst, V);
72   return true;
73 }
74
75 /// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
76 /// specified instruction operand if possible, updating it in place.  It returns
77 /// true if it made any change and false otherwise.
78 bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask,
79                                         APInt &KnownZero, APInt &KnownOne,
80                                         unsigned Depth) {
81   Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
82                                           KnownZero, KnownOne, Depth);
83   if (!NewVal) return false;
84   U = NewVal;
85   return true;
86 }
87
88
89 /// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
90 /// value based on the demanded bits.  When this function is called, it is known
91 /// that only the bits set in DemandedMask of the result of V are ever used
92 /// downstream. Consequently, depending on the mask and V, it may be possible
93 /// to replace V with a constant or one of its operands. In such cases, this
94 /// function does the replacement and returns true. In all other cases, it
95 /// returns false after analyzing the expression and setting KnownOne and known
96 /// to be one in the expression.  KnownZero contains all the bits that are known
97 /// to be zero in the expression. These are provided to potentially allow the
98 /// caller (which might recursively be SimplifyDemandedBits itself) to simplify
99 /// the expression. KnownOne and KnownZero always follow the invariant that
100 /// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
101 /// the bits in KnownOne and KnownZero may only be accurate for those bits set
102 /// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
103 /// and KnownOne must all be the same.
104 ///
105 /// This returns null if it did not change anything and it permits no
106 /// simplification.  This returns V itself if it did some simplification of V's
107 /// operands based on the information about what bits are demanded. This returns
108 /// some other non-null value if it found out that V is equal to another value
109 /// in the context where the specified bits are demanded, but not for all users.
110 Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
111                                              APInt &KnownZero, APInt &KnownOne,
112                                              unsigned Depth) {
113   assert(V != nullptr && "Null pointer of Value???");
114   assert(Depth <= 6 && "Limit Search Depth");
115   uint32_t BitWidth = DemandedMask.getBitWidth();
116   Type *VTy = V->getType();
117   assert((DL || !VTy->isPointerTy()) &&
118          "SimplifyDemandedBits needs to know bit widths!");
119   assert((!DL || DL->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
120          (!VTy->isIntOrIntVectorTy() ||
121           VTy->getScalarSizeInBits() == BitWidth) &&
122          KnownZero.getBitWidth() == BitWidth &&
123          KnownOne.getBitWidth() == BitWidth &&
124          "Value *V, DemandedMask, KnownZero and KnownOne "
125          "must have same BitWidth");
126   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
127     // We know all of the bits for a constant!
128     KnownOne = CI->getValue() & DemandedMask;
129     KnownZero = ~KnownOne & DemandedMask;
130     return nullptr;
131   }
132   if (isa<ConstantPointerNull>(V)) {
133     // We know all of the bits for a constant!
134     KnownOne.clearAllBits();
135     KnownZero = DemandedMask;
136     return nullptr;
137   }
138
139   KnownZero.clearAllBits();
140   KnownOne.clearAllBits();
141   if (DemandedMask == 0) {   // Not demanding any bits from V.
142     if (isa<UndefValue>(V))
143       return nullptr;
144     return UndefValue::get(VTy);
145   }
146
147   if (Depth == 6)        // Limit search depth.
148     return nullptr;
149
150   APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
151   APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
152
153   Instruction *I = dyn_cast<Instruction>(V);
154   if (!I) {
155     computeKnownBits(V, KnownZero, KnownOne, Depth);
156     return nullptr;        // Only analyze instructions.
157   }
158
159   // If there are multiple uses of this value and we aren't at the root, then
160   // we can't do any simplifications of the operands, because DemandedMask
161   // only reflects the bits demanded by *one* of the users.
162   if (Depth != 0 && !I->hasOneUse()) {
163     // Despite the fact that we can't simplify this instruction in all User's
164     // context, we can at least compute the knownzero/knownone bits, and we can
165     // do simplifications that apply to *just* the one user if we know that
166     // this instruction has a simpler value in that context.
167     if (I->getOpcode() == Instruction::And) {
168       // If either the LHS or the RHS are Zero, the result is zero.
169       computeKnownBits(I->getOperand(1), RHSKnownZero, RHSKnownOne, Depth+1);
170       computeKnownBits(I->getOperand(0), LHSKnownZero, LHSKnownOne, Depth+1);
171
172       // If all of the demanded bits are known 1 on one side, return the other.
173       // These bits cannot contribute to the result of the 'and' in this
174       // context.
175       if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
176           (DemandedMask & ~LHSKnownZero))
177         return I->getOperand(0);
178       if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
179           (DemandedMask & ~RHSKnownZero))
180         return I->getOperand(1);
181
182       // If all of the demanded bits in the inputs are known zeros, return zero.
183       if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
184         return Constant::getNullValue(VTy);
185
186     } else if (I->getOpcode() == Instruction::Or) {
187       // We can simplify (X|Y) -> X or Y in the user's context if we know that
188       // only bits from X or Y are demanded.
189
190       // If either the LHS or the RHS are One, the result is One.
191       computeKnownBits(I->getOperand(1), RHSKnownZero, RHSKnownOne, Depth+1);
192       computeKnownBits(I->getOperand(0), LHSKnownZero, LHSKnownOne, Depth+1);
193
194       // If all of the demanded bits are known zero on one side, return the
195       // other.  These bits cannot contribute to the result of the 'or' in this
196       // context.
197       if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
198           (DemandedMask & ~LHSKnownOne))
199         return I->getOperand(0);
200       if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
201           (DemandedMask & ~RHSKnownOne))
202         return I->getOperand(1);
203
204       // If all of the potentially set bits on one side are known to be set on
205       // the other side, just use the 'other' side.
206       if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
207           (DemandedMask & (~RHSKnownZero)))
208         return I->getOperand(0);
209       if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
210           (DemandedMask & (~LHSKnownZero)))
211         return I->getOperand(1);
212     } else if (I->getOpcode() == Instruction::Xor) {
213       // We can simplify (X^Y) -> X or Y in the user's context if we know that
214       // only bits from X or Y are demanded.
215
216       computeKnownBits(I->getOperand(1), RHSKnownZero, RHSKnownOne, Depth+1);
217       computeKnownBits(I->getOperand(0), LHSKnownZero, LHSKnownOne, Depth+1);
218
219       // If all of the demanded bits are known zero on one side, return the
220       // other.
221       if ((DemandedMask & RHSKnownZero) == DemandedMask)
222         return I->getOperand(0);
223       if ((DemandedMask & LHSKnownZero) == DemandedMask)
224         return I->getOperand(1);
225     }
226
227     // Compute the KnownZero/KnownOne bits to simplify things downstream.
228     computeKnownBits(I, KnownZero, KnownOne, Depth);
229     return nullptr;
230   }
231
232   // If this is the root being simplified, allow it to have multiple uses,
233   // just set the DemandedMask to all bits so that we can try to simplify the
234   // operands.  This allows visitTruncInst (for example) to simplify the
235   // operand of a trunc without duplicating all the logic below.
236   if (Depth == 0 && !V->hasOneUse())
237     DemandedMask = APInt::getAllOnesValue(BitWidth);
238
239   switch (I->getOpcode()) {
240   default:
241     computeKnownBits(I, KnownZero, KnownOne, Depth);
242     break;
243   case Instruction::And:
244     // If either the LHS or the RHS are Zero, the result is zero.
245     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
246                              RHSKnownZero, RHSKnownOne, Depth+1) ||
247         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
248                              LHSKnownZero, LHSKnownOne, Depth+1))
249       return I;
250     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
251     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
252
253     // If all of the demanded bits are known 1 on one side, return the other.
254     // These bits cannot contribute to the result of the 'and'.
255     if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
256         (DemandedMask & ~LHSKnownZero))
257       return I->getOperand(0);
258     if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
259         (DemandedMask & ~RHSKnownZero))
260       return I->getOperand(1);
261
262     // If all of the demanded bits in the inputs are known zeros, return zero.
263     if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
264       return Constant::getNullValue(VTy);
265
266     // If the RHS is a constant, see if we can simplify it.
267     if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
268       return I;
269
270     // Output known-1 bits are only known if set in both the LHS & RHS.
271     KnownOne = RHSKnownOne & LHSKnownOne;
272     // Output known-0 are known to be clear if zero in either the LHS | RHS.
273     KnownZero = RHSKnownZero | LHSKnownZero;
274     break;
275   case Instruction::Or:
276     // If either the LHS or the RHS are One, the result is One.
277     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
278                              RHSKnownZero, RHSKnownOne, Depth+1) ||
279         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne,
280                              LHSKnownZero, LHSKnownOne, Depth+1))
281       return I;
282     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
283     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
284
285     // If all of the demanded bits are known zero on one side, return the other.
286     // These bits cannot contribute to the result of the 'or'.
287     if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
288         (DemandedMask & ~LHSKnownOne))
289       return I->getOperand(0);
290     if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
291         (DemandedMask & ~RHSKnownOne))
292       return I->getOperand(1);
293
294     // If all of the potentially set bits on one side are known to be set on
295     // the other side, just use the 'other' side.
296     if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
297         (DemandedMask & (~RHSKnownZero)))
298       return I->getOperand(0);
299     if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
300         (DemandedMask & (~LHSKnownZero)))
301       return I->getOperand(1);
302
303     // If the RHS is a constant, see if we can simplify it.
304     if (ShrinkDemandedConstant(I, 1, DemandedMask))
305       return I;
306
307     // Output known-0 bits are only known if clear in both the LHS & RHS.
308     KnownZero = RHSKnownZero & LHSKnownZero;
309     // Output known-1 are known to be set if set in either the LHS | RHS.
310     KnownOne = RHSKnownOne | LHSKnownOne;
311     break;
312   case Instruction::Xor: {
313     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
314                              RHSKnownZero, RHSKnownOne, Depth+1) ||
315         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
316                              LHSKnownZero, LHSKnownOne, Depth+1))
317       return I;
318     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
319     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
320
321     // If all of the demanded bits are known zero on one side, return the other.
322     // These bits cannot contribute to the result of the 'xor'.
323     if ((DemandedMask & RHSKnownZero) == DemandedMask)
324       return I->getOperand(0);
325     if ((DemandedMask & LHSKnownZero) == DemandedMask)
326       return I->getOperand(1);
327
328     // If all of the demanded bits are known to be zero on one side or the
329     // other, turn this into an *inclusive* or.
330     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
331     if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
332       Instruction *Or =
333         BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
334                                  I->getName());
335       return InsertNewInstWith(Or, *I);
336     }
337
338     // If all of the demanded bits on one side are known, and all of the set
339     // bits on that side are also known to be set on the other side, turn this
340     // into an AND, as we know the bits will be cleared.
341     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
342     if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
343       // all known
344       if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
345         Constant *AndC = Constant::getIntegerValue(VTy,
346                                                    ~RHSKnownOne & DemandedMask);
347         Instruction *And = BinaryOperator::CreateAnd(I->getOperand(0), AndC);
348         return InsertNewInstWith(And, *I);
349       }
350     }
351
352     // If the RHS is a constant, see if we can simplify it.
353     // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
354     if (ShrinkDemandedConstant(I, 1, DemandedMask))
355       return I;
356
357     // If our LHS is an 'and' and if it has one use, and if any of the bits we
358     // are flipping are known to be set, then the xor is just resetting those
359     // bits to zero.  We can just knock out bits from the 'and' and the 'xor',
360     // simplifying both of them.
361     if (Instruction *LHSInst = dyn_cast<Instruction>(I->getOperand(0)))
362       if (LHSInst->getOpcode() == Instruction::And && LHSInst->hasOneUse() &&
363           isa<ConstantInt>(I->getOperand(1)) &&
364           isa<ConstantInt>(LHSInst->getOperand(1)) &&
365           (LHSKnownOne & RHSKnownOne & DemandedMask) != 0) {
366         ConstantInt *AndRHS = cast<ConstantInt>(LHSInst->getOperand(1));
367         ConstantInt *XorRHS = cast<ConstantInt>(I->getOperand(1));
368         APInt NewMask = ~(LHSKnownOne & RHSKnownOne & DemandedMask);
369
370         Constant *AndC =
371           ConstantInt::get(I->getType(), NewMask & AndRHS->getValue());
372         Instruction *NewAnd = BinaryOperator::CreateAnd(I->getOperand(0), AndC);
373         InsertNewInstWith(NewAnd, *I);
374
375         Constant *XorC =
376           ConstantInt::get(I->getType(), NewMask & XorRHS->getValue());
377         Instruction *NewXor = BinaryOperator::CreateXor(NewAnd, XorC);
378         return InsertNewInstWith(NewXor, *I);
379       }
380
381     // Output known-0 bits are known if clear or set in both the LHS & RHS.
382     KnownZero= (RHSKnownZero & LHSKnownZero) | (RHSKnownOne & LHSKnownOne);
383     // Output known-1 are known to be set if set in only one of the LHS, RHS.
384     KnownOne = (RHSKnownZero & LHSKnownOne) | (RHSKnownOne & LHSKnownZero);
385     break;
386   }
387   case Instruction::Select:
388     if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
389                              RHSKnownZero, RHSKnownOne, Depth+1) ||
390         SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
391                              LHSKnownZero, LHSKnownOne, Depth+1))
392       return I;
393     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
394     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
395
396     // If the operands are constants, see if we can simplify them.
397     if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
398         ShrinkDemandedConstant(I, 2, DemandedMask))
399       return I;
400
401     // Only known if known in both the LHS and RHS.
402     KnownOne = RHSKnownOne & LHSKnownOne;
403     KnownZero = RHSKnownZero & LHSKnownZero;
404     break;
405   case Instruction::Trunc: {
406     unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
407     DemandedMask = DemandedMask.zext(truncBf);
408     KnownZero = KnownZero.zext(truncBf);
409     KnownOne = KnownOne.zext(truncBf);
410     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
411                              KnownZero, KnownOne, Depth+1))
412       return I;
413     DemandedMask = DemandedMask.trunc(BitWidth);
414     KnownZero = KnownZero.trunc(BitWidth);
415     KnownOne = KnownOne.trunc(BitWidth);
416     assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
417     break;
418   }
419   case Instruction::BitCast:
420     if (!I->getOperand(0)->getType()->isIntOrIntVectorTy())
421       return nullptr;  // vector->int or fp->int?
422
423     if (VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
424       if (VectorType *SrcVTy =
425             dyn_cast<VectorType>(I->getOperand(0)->getType())) {
426         if (DstVTy->getNumElements() != SrcVTy->getNumElements())
427           // Don't touch a bitcast between vectors of different element counts.
428           return nullptr;
429       } else
430         // Don't touch a scalar-to-vector bitcast.
431         return nullptr;
432     } else if (I->getOperand(0)->getType()->isVectorTy())
433       // Don't touch a vector-to-scalar bitcast.
434       return nullptr;
435
436     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
437                              KnownZero, KnownOne, Depth+1))
438       return I;
439     assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
440     break;
441   case Instruction::ZExt: {
442     // Compute the bits in the result that are not present in the input.
443     unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
444
445     DemandedMask = DemandedMask.trunc(SrcBitWidth);
446     KnownZero = KnownZero.trunc(SrcBitWidth);
447     KnownOne = KnownOne.trunc(SrcBitWidth);
448     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
449                              KnownZero, KnownOne, Depth+1))
450       return I;
451     DemandedMask = DemandedMask.zext(BitWidth);
452     KnownZero = KnownZero.zext(BitWidth);
453     KnownOne = KnownOne.zext(BitWidth);
454     assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
455     // The top bits are known to be zero.
456     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
457     break;
458   }
459   case Instruction::SExt: {
460     // Compute the bits in the result that are not present in the input.
461     unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
462
463     APInt InputDemandedBits = DemandedMask &
464                               APInt::getLowBitsSet(BitWidth, SrcBitWidth);
465
466     APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
467     // If any of the sign extended bits are demanded, we know that the sign
468     // bit is demanded.
469     if ((NewBits & DemandedMask) != 0)
470       InputDemandedBits.setBit(SrcBitWidth-1);
471
472     InputDemandedBits = InputDemandedBits.trunc(SrcBitWidth);
473     KnownZero = KnownZero.trunc(SrcBitWidth);
474     KnownOne = KnownOne.trunc(SrcBitWidth);
475     if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
476                              KnownZero, KnownOne, Depth+1))
477       return I;
478     InputDemandedBits = InputDemandedBits.zext(BitWidth);
479     KnownZero = KnownZero.zext(BitWidth);
480     KnownOne = KnownOne.zext(BitWidth);
481     assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
482
483     // If the sign bit of the input is known set or clear, then we know the
484     // top bits of the result.
485
486     // If the input sign bit is known zero, or if the NewBits are not demanded
487     // convert this into a zero extension.
488     if (KnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
489       // Convert to ZExt cast
490       CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
491       return InsertNewInstWith(NewCast, *I);
492     } else if (KnownOne[SrcBitWidth-1]) {    // Input sign bit known set
493       KnownOne |= NewBits;
494     }
495     break;
496   }
497   case Instruction::Add: {
498     // Figure out what the input bits are.  If the top bits of the and result
499     // are not demanded, then the add doesn't demand them from its input
500     // either.
501     unsigned NLZ = DemandedMask.countLeadingZeros();
502
503     // If there is a constant on the RHS, there are a variety of xformations
504     // we can do.
505     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
506       // If null, this should be simplified elsewhere.  Some of the xforms here
507       // won't work if the RHS is zero.
508       if (RHS->isZero())
509         break;
510
511       // If the top bit of the output is demanded, demand everything from the
512       // input.  Otherwise, we demand all the input bits except NLZ top bits.
513       APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
514
515       // Find information about known zero/one bits in the input.
516       if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits,
517                                LHSKnownZero, LHSKnownOne, Depth+1))
518         return I;
519
520       // If the RHS of the add has bits set that can't affect the input, reduce
521       // the constant.
522       if (ShrinkDemandedConstant(I, 1, InDemandedBits))
523         return I;
524
525       // Avoid excess work.
526       if (LHSKnownZero == 0 && LHSKnownOne == 0)
527         break;
528
529       // Turn it into OR if input bits are zero.
530       if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
531         Instruction *Or =
532           BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
533                                    I->getName());
534         return InsertNewInstWith(Or, *I);
535       }
536
537       // We can say something about the output known-zero and known-one bits,
538       // depending on potential carries from the input constant and the
539       // unknowns.  For example if the LHS is known to have at most the 0x0F0F0
540       // bits set and the RHS constant is 0x01001, then we know we have a known
541       // one mask of 0x00001 and a known zero mask of 0xE0F0E.
542
543       // To compute this, we first compute the potential carry bits.  These are
544       // the bits which may be modified.  I'm not aware of a better way to do
545       // this scan.
546       const APInt &RHSVal = RHS->getValue();
547       APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
548
549       // Now that we know which bits have carries, compute the known-1/0 sets.
550
551       // Bits are known one if they are known zero in one operand and one in the
552       // other, and there is no input carry.
553       KnownOne = ((LHSKnownZero & RHSVal) |
554                   (LHSKnownOne & ~RHSVal)) & ~CarryBits;
555
556       // Bits are known zero if they are known zero in both operands and there
557       // is no input carry.
558       KnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
559     } else {
560       // If the high-bits of this ADD are not demanded, then it does not demand
561       // the high bits of its LHS or RHS.
562       if (DemandedMask[BitWidth-1] == 0) {
563         // Right fill the mask of bits for this ADD to demand the most
564         // significant bit and all those below it.
565         APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
566         if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
567                                  LHSKnownZero, LHSKnownOne, Depth+1) ||
568             SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
569                                  LHSKnownZero, LHSKnownOne, Depth+1))
570           return I;
571       }
572     }
573     break;
574   }
575   case Instruction::Sub:
576     // If the high-bits of this SUB are not demanded, then it does not demand
577     // the high bits of its LHS or RHS.
578     if (DemandedMask[BitWidth-1] == 0) {
579       // Right fill the mask of bits for this SUB to demand the most
580       // significant bit and all those below it.
581       uint32_t NLZ = DemandedMask.countLeadingZeros();
582       APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
583       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
584                                LHSKnownZero, LHSKnownOne, Depth+1) ||
585           SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
586                                LHSKnownZero, LHSKnownOne, Depth+1))
587         return I;
588     }
589
590     // Otherwise just hand the sub off to computeKnownBits to fill in
591     // the known zeros and ones.
592     computeKnownBits(V, KnownZero, KnownOne, Depth);
593
594     // Turn this into a xor if LHS is 2^n-1 and the remaining bits are known
595     // zero.
596     if (ConstantInt *C0 = dyn_cast<ConstantInt>(I->getOperand(0))) {
597       APInt I0 = C0->getValue();
598       if ((I0 + 1).isPowerOf2() && (I0 | KnownZero).isAllOnesValue()) {
599         Instruction *Xor = BinaryOperator::CreateXor(I->getOperand(1), C0);
600         return InsertNewInstWith(Xor, *I);
601       }
602     }
603     break;
604   case Instruction::Shl:
605     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
606       {
607         Value *VarX; ConstantInt *C1;
608         if (match(I->getOperand(0), m_Shr(m_Value(VarX), m_ConstantInt(C1)))) {
609           Instruction *Shr = cast<Instruction>(I->getOperand(0));
610           Value *R = SimplifyShrShlDemandedBits(Shr, I, DemandedMask,
611                                                 KnownZero, KnownOne);
612           if (R)
613             return R;
614         }
615       }
616
617       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth-1);
618       APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
619
620       // If the shift is NUW/NSW, then it does demand the high bits.
621       ShlOperator *IOp = cast<ShlOperator>(I);
622       if (IOp->hasNoSignedWrap())
623         DemandedMaskIn |= APInt::getHighBitsSet(BitWidth, ShiftAmt+1);
624       else if (IOp->hasNoUnsignedWrap())
625         DemandedMaskIn |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
626
627       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
628                                KnownZero, KnownOne, Depth+1))
629         return I;
630       assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
631       KnownZero <<= ShiftAmt;
632       KnownOne  <<= ShiftAmt;
633       // low bits known zero.
634       if (ShiftAmt)
635         KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
636     }
637     break;
638   case Instruction::LShr:
639     // For a logical shift right
640     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
641       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth-1);
642
643       // Unsigned shift right.
644       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
645
646       // If the shift is exact, then it does demand the low bits (and knows that
647       // they are zero).
648       if (cast<LShrOperator>(I)->isExact())
649         DemandedMaskIn |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
650
651       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
652                                KnownZero, KnownOne, Depth+1))
653         return I;
654       assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
655       KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
656       KnownOne  = APIntOps::lshr(KnownOne, ShiftAmt);
657       if (ShiftAmt) {
658         // Compute the new bits that are at the top now.
659         APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
660         KnownZero |= HighBits;  // high bits known zero.
661       }
662     }
663     break;
664   case Instruction::AShr:
665     // If this is an arithmetic shift right and only the low-bit is set, we can
666     // always convert this into a logical shr, even if the shift amount is
667     // variable.  The low bit of the shift cannot be an input sign bit unless
668     // the shift amount is >= the size of the datatype, which is undefined.
669     if (DemandedMask == 1) {
670       // Perform the logical shift right.
671       Instruction *NewVal = BinaryOperator::CreateLShr(
672                         I->getOperand(0), I->getOperand(1), I->getName());
673       return InsertNewInstWith(NewVal, *I);
674     }
675
676     // If the sign bit is the only bit demanded by this ashr, then there is no
677     // need to do it, the shift doesn't change the high bit.
678     if (DemandedMask.isSignBit())
679       return I->getOperand(0);
680
681     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
682       uint32_t ShiftAmt = SA->getLimitedValue(BitWidth-1);
683
684       // Signed shift right.
685       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
686       // If any of the "high bits" are demanded, we should set the sign bit as
687       // demanded.
688       if (DemandedMask.countLeadingZeros() <= ShiftAmt)
689         DemandedMaskIn.setBit(BitWidth-1);
690
691       // If the shift is exact, then it does demand the low bits (and knows that
692       // they are zero).
693       if (cast<AShrOperator>(I)->isExact())
694         DemandedMaskIn |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
695
696       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
697                                KnownZero, KnownOne, Depth+1))
698         return I;
699       assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
700       // Compute the new bits that are at the top now.
701       APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
702       KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
703       KnownOne  = APIntOps::lshr(KnownOne, ShiftAmt);
704
705       // Handle the sign bits.
706       APInt SignBit(APInt::getSignBit(BitWidth));
707       // Adjust to where it is now in the mask.
708       SignBit = APIntOps::lshr(SignBit, ShiftAmt);
709
710       // If the input sign bit is known to be zero, or if none of the top bits
711       // are demanded, turn this into an unsigned shift right.
712       if (BitWidth <= ShiftAmt || KnownZero[BitWidth-ShiftAmt-1] ||
713           (HighBits & ~DemandedMask) == HighBits) {
714         // Perform the logical shift right.
715         BinaryOperator *NewVal = BinaryOperator::CreateLShr(I->getOperand(0),
716                                                             SA, I->getName());
717         NewVal->setIsExact(cast<BinaryOperator>(I)->isExact());
718         return InsertNewInstWith(NewVal, *I);
719       } else if ((KnownOne & SignBit) != 0) { // New bits are known one.
720         KnownOne |= HighBits;
721       }
722     }
723     break;
724   case Instruction::SRem:
725     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
726       // X % -1 demands all the bits because we don't want to introduce
727       // INT_MIN % -1 (== undef) by accident.
728       if (Rem->isAllOnesValue())
729         break;
730       APInt RA = Rem->getValue().abs();
731       if (RA.isPowerOf2()) {
732         if (DemandedMask.ult(RA))    // srem won't affect demanded bits
733           return I->getOperand(0);
734
735         APInt LowBits = RA - 1;
736         APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
737         if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
738                                  LHSKnownZero, LHSKnownOne, Depth+1))
739           return I;
740
741         // The low bits of LHS are unchanged by the srem.
742         KnownZero = LHSKnownZero & LowBits;
743         KnownOne = LHSKnownOne & LowBits;
744
745         // If LHS is non-negative or has all low bits zero, then the upper bits
746         // are all zero.
747         if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
748           KnownZero |= ~LowBits;
749
750         // If LHS is negative and not all low bits are zero, then the upper bits
751         // are all one.
752         if (LHSKnownOne[BitWidth-1] && ((LHSKnownOne & LowBits) != 0))
753           KnownOne |= ~LowBits;
754
755         assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
756       }
757     }
758
759     // The sign bit is the LHS's sign bit, except when the result of the
760     // remainder is zero.
761     if (DemandedMask.isNegative() && KnownZero.isNonNegative()) {
762       APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
763       computeKnownBits(I->getOperand(0), LHSKnownZero, LHSKnownOne, Depth+1);
764       // If it's known zero, our sign bit is also zero.
765       if (LHSKnownZero.isNegative())
766         KnownZero.setBit(KnownZero.getBitWidth() - 1);
767     }
768     break;
769   case Instruction::URem: {
770     APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
771     APInt AllOnes = APInt::getAllOnesValue(BitWidth);
772     if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
773                              KnownZero2, KnownOne2, Depth+1) ||
774         SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
775                              KnownZero2, KnownOne2, Depth+1))
776       return I;
777
778     unsigned Leaders = KnownZero2.countLeadingOnes();
779     Leaders = std::max(Leaders,
780                        KnownZero2.countLeadingOnes());
781     KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
782     break;
783   }
784   case Instruction::Call:
785     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
786       switch (II->getIntrinsicID()) {
787       default: break;
788       case Intrinsic::bswap: {
789         // If the only bits demanded come from one byte of the bswap result,
790         // just shift the input byte into position to eliminate the bswap.
791         unsigned NLZ = DemandedMask.countLeadingZeros();
792         unsigned NTZ = DemandedMask.countTrailingZeros();
793
794         // Round NTZ down to the next byte.  If we have 11 trailing zeros, then
795         // we need all the bits down to bit 8.  Likewise, round NLZ.  If we
796         // have 14 leading zeros, round to 8.
797         NLZ &= ~7;
798         NTZ &= ~7;
799         // If we need exactly one byte, we can do this transformation.
800         if (BitWidth-NLZ-NTZ == 8) {
801           unsigned ResultBit = NTZ;
802           unsigned InputBit = BitWidth-NTZ-8;
803
804           // Replace this with either a left or right shift to get the byte into
805           // the right place.
806           Instruction *NewVal;
807           if (InputBit > ResultBit)
808             NewVal = BinaryOperator::CreateLShr(II->getArgOperand(0),
809                     ConstantInt::get(I->getType(), InputBit-ResultBit));
810           else
811             NewVal = BinaryOperator::CreateShl(II->getArgOperand(0),
812                     ConstantInt::get(I->getType(), ResultBit-InputBit));
813           NewVal->takeName(I);
814           return InsertNewInstWith(NewVal, *I);
815         }
816
817         // TODO: Could compute known zero/one bits based on the input.
818         break;
819       }
820       case Intrinsic::x86_sse42_crc32_64_64:
821         KnownZero = APInt::getHighBitsSet(64, 32);
822         return nullptr;
823       }
824     }
825     computeKnownBits(V, KnownZero, KnownOne, Depth);
826     break;
827   }
828
829   // If the client is only demanding bits that we know, return the known
830   // constant.
831   if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask)
832     return Constant::getIntegerValue(VTy, KnownOne);
833   return nullptr;
834 }
835
836 /// Helper routine of SimplifyDemandedUseBits. It tries to simplify
837 /// "E1 = (X lsr C1) << C2", where the C1 and C2 are constant, into
838 /// "E2 = X << (C2 - C1)" or "E2 = X >> (C1 - C2)", depending on the sign
839 /// of "C2-C1".
840 ///
841 /// Suppose E1 and E2 are generally different in bits S={bm, bm+1,
842 /// ..., bn}, without considering the specific value X is holding.
843 /// This transformation is legal iff one of following conditions is hold:
844 ///  1) All the bit in S are 0, in this case E1 == E2.
845 ///  2) We don't care those bits in S, per the input DemandedMask.
846 ///  3) Combination of 1) and 2). Some bits in S are 0, and we don't care the
847 ///     rest bits.
848 ///
849 /// Currently we only test condition 2).
850 ///
851 /// As with SimplifyDemandedUseBits, it returns NULL if the simplification was
852 /// not successful.
853 Value *InstCombiner::SimplifyShrShlDemandedBits(Instruction *Shr,
854   Instruction *Shl, APInt DemandedMask, APInt &KnownZero, APInt &KnownOne) {
855
856   const APInt &ShlOp1 = cast<ConstantInt>(Shl->getOperand(1))->getValue();
857   const APInt &ShrOp1 = cast<ConstantInt>(Shr->getOperand(1))->getValue();
858   if (!ShlOp1 || !ShrOp1)
859       return nullptr; // Noop.
860
861   Value *VarX = Shr->getOperand(0);
862   Type *Ty = VarX->getType();
863   unsigned BitWidth = Ty->getIntegerBitWidth();
864   if (ShlOp1.uge(BitWidth) || ShrOp1.uge(BitWidth))
865     return nullptr; // Undef.
866
867   unsigned ShlAmt = ShlOp1.getZExtValue();
868   unsigned ShrAmt = ShrOp1.getZExtValue();
869
870   KnownOne.clearAllBits();
871   KnownZero = APInt::getBitsSet(KnownZero.getBitWidth(), 0, ShlAmt-1);
872   KnownZero &= DemandedMask;
873
874   APInt BitMask1(APInt::getAllOnesValue(BitWidth));
875   APInt BitMask2(APInt::getAllOnesValue(BitWidth));
876
877   bool isLshr = (Shr->getOpcode() == Instruction::LShr);
878   BitMask1 = isLshr ? (BitMask1.lshr(ShrAmt) << ShlAmt) :
879                       (BitMask1.ashr(ShrAmt) << ShlAmt);
880
881   if (ShrAmt <= ShlAmt) {
882     BitMask2 <<= (ShlAmt - ShrAmt);
883   } else {
884     BitMask2 = isLshr ? BitMask2.lshr(ShrAmt - ShlAmt):
885                         BitMask2.ashr(ShrAmt - ShlAmt);
886   }
887
888   // Check if condition-2 (see the comment to this function) is satified.
889   if ((BitMask1 & DemandedMask) == (BitMask2 & DemandedMask)) {
890     if (ShrAmt == ShlAmt)
891       return VarX;
892
893     if (!Shr->hasOneUse())
894       return nullptr;
895
896     BinaryOperator *New;
897     if (ShrAmt < ShlAmt) {
898       Constant *Amt = ConstantInt::get(VarX->getType(), ShlAmt - ShrAmt);
899       New = BinaryOperator::CreateShl(VarX, Amt);
900       BinaryOperator *Orig = cast<BinaryOperator>(Shl);
901       New->setHasNoSignedWrap(Orig->hasNoSignedWrap());
902       New->setHasNoUnsignedWrap(Orig->hasNoUnsignedWrap());
903     } else {
904       Constant *Amt = ConstantInt::get(VarX->getType(), ShrAmt - ShlAmt);
905       New = isLshr ? BinaryOperator::CreateLShr(VarX, Amt) :
906                      BinaryOperator::CreateAShr(VarX, Amt);
907       if (cast<BinaryOperator>(Shr)->isExact())
908         New->setIsExact(true);
909     }
910
911     return InsertNewInstWith(New, *Shl);
912   }
913
914   return nullptr;
915 }
916
917 /// SimplifyDemandedVectorElts - The specified value produces a vector with
918 /// any number of elements. DemandedElts contains the set of elements that are
919 /// actually used by the caller.  This method analyzes which elements of the
920 /// operand are undef and returns that information in UndefElts.
921 ///
922 /// If the information about demanded elements can be used to simplify the
923 /// operation, the operation is simplified, then the resultant value is
924 /// returned.  This returns null if no change was made.
925 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
926                                                 APInt &UndefElts,
927                                                 unsigned Depth) {
928   unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
929   APInt EltMask(APInt::getAllOnesValue(VWidth));
930   assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
931
932   if (isa<UndefValue>(V)) {
933     // If the entire vector is undefined, just return this info.
934     UndefElts = EltMask;
935     return nullptr;
936   }
937
938   if (DemandedElts == 0) { // If nothing is demanded, provide undef.
939     UndefElts = EltMask;
940     return UndefValue::get(V->getType());
941   }
942
943   UndefElts = 0;
944
945   // Handle ConstantAggregateZero, ConstantVector, ConstantDataSequential.
946   if (Constant *C = dyn_cast<Constant>(V)) {
947     // Check if this is identity. If so, return 0 since we are not simplifying
948     // anything.
949     if (DemandedElts.isAllOnesValue())
950       return nullptr;
951
952     Type *EltTy = cast<VectorType>(V->getType())->getElementType();
953     Constant *Undef = UndefValue::get(EltTy);
954
955     SmallVector<Constant*, 16> Elts;
956     for (unsigned i = 0; i != VWidth; ++i) {
957       if (!DemandedElts[i]) {   // If not demanded, set to undef.
958         Elts.push_back(Undef);
959         UndefElts.setBit(i);
960         continue;
961       }
962
963       Constant *Elt = C->getAggregateElement(i);
964       if (!Elt) return nullptr;
965
966       if (isa<UndefValue>(Elt)) {   // Already undef.
967         Elts.push_back(Undef);
968         UndefElts.setBit(i);
969       } else {                               // Otherwise, defined.
970         Elts.push_back(Elt);
971       }
972     }
973
974     // If we changed the constant, return it.
975     Constant *NewCV = ConstantVector::get(Elts);
976     return NewCV != C ? NewCV : nullptr;
977   }
978
979   // Limit search depth.
980   if (Depth == 10)
981     return nullptr;
982
983   // If multiple users are using the root value, proceed with
984   // simplification conservatively assuming that all elements
985   // are needed.
986   if (!V->hasOneUse()) {
987     // Quit if we find multiple users of a non-root value though.
988     // They'll be handled when it's their turn to be visited by
989     // the main instcombine process.
990     if (Depth != 0)
991       // TODO: Just compute the UndefElts information recursively.
992       return nullptr;
993
994     // Conservatively assume that all elements are needed.
995     DemandedElts = EltMask;
996   }
997
998   Instruction *I = dyn_cast<Instruction>(V);
999   if (!I) return nullptr;        // Only analyze instructions.
1000
1001   bool MadeChange = false;
1002   APInt UndefElts2(VWidth, 0);
1003   Value *TmpV;
1004   switch (I->getOpcode()) {
1005   default: break;
1006
1007   case Instruction::InsertElement: {
1008     // If this is a variable index, we don't know which element it overwrites.
1009     // demand exactly the same input as we produce.
1010     ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1011     if (!Idx) {
1012       // Note that we can't propagate undef elt info, because we don't know
1013       // which elt is getting updated.
1014       TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1015                                         UndefElts2, Depth+1);
1016       if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1017       break;
1018     }
1019
1020     // If this is inserting an element that isn't demanded, remove this
1021     // insertelement.
1022     unsigned IdxNo = Idx->getZExtValue();
1023     if (IdxNo >= VWidth || !DemandedElts[IdxNo]) {
1024       Worklist.Add(I);
1025       return I->getOperand(0);
1026     }
1027
1028     // Otherwise, the element inserted overwrites whatever was there, so the
1029     // input demanded set is simpler than the output set.
1030     APInt DemandedElts2 = DemandedElts;
1031     DemandedElts2.clearBit(IdxNo);
1032     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
1033                                       UndefElts, Depth+1);
1034     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1035
1036     // The inserted element is defined.
1037     UndefElts.clearBit(IdxNo);
1038     break;
1039   }
1040   case Instruction::ShuffleVector: {
1041     ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
1042     uint64_t LHSVWidth =
1043       cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
1044     APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
1045     for (unsigned i = 0; i < VWidth; i++) {
1046       if (DemandedElts[i]) {
1047         unsigned MaskVal = Shuffle->getMaskValue(i);
1048         if (MaskVal != -1u) {
1049           assert(MaskVal < LHSVWidth * 2 &&
1050                  "shufflevector mask index out of range!");
1051           if (MaskVal < LHSVWidth)
1052             LeftDemanded.setBit(MaskVal);
1053           else
1054             RightDemanded.setBit(MaskVal - LHSVWidth);
1055         }
1056       }
1057     }
1058
1059     APInt UndefElts4(LHSVWidth, 0);
1060     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
1061                                       UndefElts4, Depth+1);
1062     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1063
1064     APInt UndefElts3(LHSVWidth, 0);
1065     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1066                                       UndefElts3, Depth+1);
1067     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1068
1069     bool NewUndefElts = false;
1070     for (unsigned i = 0; i < VWidth; i++) {
1071       unsigned MaskVal = Shuffle->getMaskValue(i);
1072       if (MaskVal == -1u) {
1073         UndefElts.setBit(i);
1074       } else if (!DemandedElts[i]) {
1075         NewUndefElts = true;
1076         UndefElts.setBit(i);
1077       } else if (MaskVal < LHSVWidth) {
1078         if (UndefElts4[MaskVal]) {
1079           NewUndefElts = true;
1080           UndefElts.setBit(i);
1081         }
1082       } else {
1083         if (UndefElts3[MaskVal - LHSVWidth]) {
1084           NewUndefElts = true;
1085           UndefElts.setBit(i);
1086         }
1087       }
1088     }
1089
1090     if (NewUndefElts) {
1091       // Add additional discovered undefs.
1092       SmallVector<Constant*, 16> Elts;
1093       for (unsigned i = 0; i < VWidth; ++i) {
1094         if (UndefElts[i])
1095           Elts.push_back(UndefValue::get(Type::getInt32Ty(I->getContext())));
1096         else
1097           Elts.push_back(ConstantInt::get(Type::getInt32Ty(I->getContext()),
1098                                           Shuffle->getMaskValue(i)));
1099       }
1100       I->setOperand(2, ConstantVector::get(Elts));
1101       MadeChange = true;
1102     }
1103     break;
1104   }
1105   case Instruction::Select: {
1106     APInt LeftDemanded(DemandedElts), RightDemanded(DemandedElts);
1107     if (ConstantVector* CV = dyn_cast<ConstantVector>(I->getOperand(0))) {
1108       for (unsigned i = 0; i < VWidth; i++) {
1109         if (CV->getAggregateElement(i)->isNullValue())
1110           LeftDemanded.clearBit(i);
1111         else
1112           RightDemanded.clearBit(i);
1113       }
1114     }
1115
1116     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), LeftDemanded,
1117                                       UndefElts, Depth+1);
1118     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1119
1120     TmpV = SimplifyDemandedVectorElts(I->getOperand(2), RightDemanded,
1121                                       UndefElts2, Depth+1);
1122     if (TmpV) { I->setOperand(2, TmpV); MadeChange = true; }
1123
1124     // Output elements are undefined if both are undefined.
1125     UndefElts &= UndefElts2;
1126     break;
1127   }
1128   case Instruction::BitCast: {
1129     // Vector->vector casts only.
1130     VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1131     if (!VTy) break;
1132     unsigned InVWidth = VTy->getNumElements();
1133     APInt InputDemandedElts(InVWidth, 0);
1134     unsigned Ratio;
1135
1136     if (VWidth == InVWidth) {
1137       // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1138       // elements as are demanded of us.
1139       Ratio = 1;
1140       InputDemandedElts = DemandedElts;
1141     } else if (VWidth > InVWidth) {
1142       // Untested so far.
1143       break;
1144
1145       // If there are more elements in the result than there are in the source,
1146       // then an input element is live if any of the corresponding output
1147       // elements are live.
1148       Ratio = VWidth/InVWidth;
1149       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1150         if (DemandedElts[OutIdx])
1151           InputDemandedElts.setBit(OutIdx/Ratio);
1152       }
1153     } else {
1154       // Untested so far.
1155       break;
1156
1157       // If there are more elements in the source than there are in the result,
1158       // then an input element is live if the corresponding output element is
1159       // live.
1160       Ratio = InVWidth/VWidth;
1161       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1162         if (DemandedElts[InIdx/Ratio])
1163           InputDemandedElts.setBit(InIdx);
1164     }
1165
1166     // div/rem demand all inputs, because they don't want divide by zero.
1167     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1168                                       UndefElts2, Depth+1);
1169     if (TmpV) {
1170       I->setOperand(0, TmpV);
1171       MadeChange = true;
1172     }
1173
1174     UndefElts = UndefElts2;
1175     if (VWidth > InVWidth) {
1176       llvm_unreachable("Unimp");
1177       // If there are more elements in the result than there are in the source,
1178       // then an output element is undef if the corresponding input element is
1179       // undef.
1180       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1181         if (UndefElts2[OutIdx/Ratio])
1182           UndefElts.setBit(OutIdx);
1183     } else if (VWidth < InVWidth) {
1184       llvm_unreachable("Unimp");
1185       // If there are more elements in the source than there are in the result,
1186       // then a result element is undef if all of the corresponding input
1187       // elements are undef.
1188       UndefElts = ~0ULL >> (64-VWidth);  // Start out all undef.
1189       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1190         if (!UndefElts2[InIdx])            // Not undef?
1191           UndefElts.clearBit(InIdx/Ratio);    // Clear undef bit.
1192     }
1193     break;
1194   }
1195   case Instruction::And:
1196   case Instruction::Or:
1197   case Instruction::Xor:
1198   case Instruction::Add:
1199   case Instruction::Sub:
1200   case Instruction::Mul:
1201     // div/rem demand all inputs, because they don't want divide by zero.
1202     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1203                                       UndefElts, Depth+1);
1204     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1205     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1206                                       UndefElts2, Depth+1);
1207     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1208
1209     // Output elements are undefined if both are undefined.  Consider things
1210     // like undef&0.  The result is known zero, not undef.
1211     UndefElts &= UndefElts2;
1212     break;
1213   case Instruction::FPTrunc:
1214   case Instruction::FPExt:
1215     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1216                                       UndefElts, Depth+1);
1217     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1218     break;
1219
1220   case Instruction::Call: {
1221     IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1222     if (!II) break;
1223     switch (II->getIntrinsicID()) {
1224     default: break;
1225
1226     // Binary vector operations that work column-wise.  A dest element is a
1227     // function of the corresponding input elements from the two inputs.
1228     case Intrinsic::x86_sse_sub_ss:
1229     case Intrinsic::x86_sse_mul_ss:
1230     case Intrinsic::x86_sse_min_ss:
1231     case Intrinsic::x86_sse_max_ss:
1232     case Intrinsic::x86_sse2_sub_sd:
1233     case Intrinsic::x86_sse2_mul_sd:
1234     case Intrinsic::x86_sse2_min_sd:
1235     case Intrinsic::x86_sse2_max_sd:
1236       TmpV = SimplifyDemandedVectorElts(II->getArgOperand(0), DemandedElts,
1237                                         UndefElts, Depth+1);
1238       if (TmpV) { II->setArgOperand(0, TmpV); MadeChange = true; }
1239       TmpV = SimplifyDemandedVectorElts(II->getArgOperand(1), DemandedElts,
1240                                         UndefElts2, Depth+1);
1241       if (TmpV) { II->setArgOperand(1, TmpV); MadeChange = true; }
1242
1243       // If only the low elt is demanded and this is a scalarizable intrinsic,
1244       // scalarize it now.
1245       if (DemandedElts == 1) {
1246         switch (II->getIntrinsicID()) {
1247         default: break;
1248         case Intrinsic::x86_sse_sub_ss:
1249         case Intrinsic::x86_sse_mul_ss:
1250         case Intrinsic::x86_sse2_sub_sd:
1251         case Intrinsic::x86_sse2_mul_sd:
1252           // TODO: Lower MIN/MAX/ABS/etc
1253           Value *LHS = II->getArgOperand(0);
1254           Value *RHS = II->getArgOperand(1);
1255           // Extract the element as scalars.
1256           LHS = InsertNewInstWith(ExtractElementInst::Create(LHS,
1257             ConstantInt::get(Type::getInt32Ty(I->getContext()), 0U)), *II);
1258           RHS = InsertNewInstWith(ExtractElementInst::Create(RHS,
1259             ConstantInt::get(Type::getInt32Ty(I->getContext()), 0U)), *II);
1260
1261           switch (II->getIntrinsicID()) {
1262           default: llvm_unreachable("Case stmts out of sync!");
1263           case Intrinsic::x86_sse_sub_ss:
1264           case Intrinsic::x86_sse2_sub_sd:
1265             TmpV = InsertNewInstWith(BinaryOperator::CreateFSub(LHS, RHS,
1266                                                         II->getName()), *II);
1267             break;
1268           case Intrinsic::x86_sse_mul_ss:
1269           case Intrinsic::x86_sse2_mul_sd:
1270             TmpV = InsertNewInstWith(BinaryOperator::CreateFMul(LHS, RHS,
1271                                                          II->getName()), *II);
1272             break;
1273           }
1274
1275           Instruction *New =
1276             InsertElementInst::Create(
1277               UndefValue::get(II->getType()), TmpV,
1278               ConstantInt::get(Type::getInt32Ty(I->getContext()), 0U, false),
1279                                       II->getName());
1280           InsertNewInstWith(New, *II);
1281           return New;
1282         }
1283       }
1284
1285       // Output elements are undefined if both are undefined.  Consider things
1286       // like undef&0.  The result is known zero, not undef.
1287       UndefElts &= UndefElts2;
1288       break;
1289     }
1290     break;
1291   }
1292   }
1293   return MadeChange ? I : nullptr;
1294 }