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