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