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