Null initialize a few variables flagged by
[oota-llvm.git] / lib / Transforms / InstCombine / InstCombineShifts.cpp
1 //===- InstCombineShifts.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 implements the visitShl, visitLShr, and visitAShr functions.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "InstCombine.h"
15 #include "llvm/IntrinsicInst.h"
16 #include "llvm/Analysis/InstructionSimplify.h"
17 #include "llvm/Support/PatternMatch.h"
18 using namespace llvm;
19 using namespace PatternMatch;
20
21 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
22   assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
23   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
24
25   // See if we can fold away this shift.
26   if (SimplifyDemandedInstructionBits(I))
27     return &I;
28
29   // Try to fold constant and into select arguments.
30   if (isa<Constant>(Op0))
31     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
32       if (Instruction *R = FoldOpIntoSelect(I, SI))
33         return R;
34
35   if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
36     if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
37       return Res;
38
39   // X shift (A srem B) -> X shift (A and B-1) iff B is a power of 2.
40   // Because shifts by negative values are undefined.
41   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op1))
42     if (BO->hasOneUse() && BO->getOpcode() == Instruction::SRem)
43       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1)))
44         if (CI->getValue().isPowerOf2()) {
45           Constant *C = ConstantInt::get(BO->getType(), CI->getValue()-1);
46           Value *Rem = Builder->CreateAnd(BO->getOperand(0), C, BO->getName());
47           I.setOperand(1, Rem);
48           return &I;
49         }
50
51   return 0;
52 }
53
54 /// CanEvaluateShifted - See if we can compute the specified value, but shifted
55 /// logically to the left or right by some number of bits.  This should return
56 /// true if the expression can be computed for the same cost as the current
57 /// expression tree.  This is used to eliminate extraneous shifting from things
58 /// like:
59 ///      %C = shl i128 %A, 64
60 ///      %D = shl i128 %B, 96
61 ///      %E = or i128 %C, %D
62 ///      %F = lshr i128 %E, 64
63 /// where the client will ask if E can be computed shifted right by 64-bits.  If
64 /// this succeeds, the GetShiftedValue function will be called to produce the
65 /// value.
66 static bool CanEvaluateShifted(Value *V, unsigned NumBits, bool isLeftShift,
67                                InstCombiner &IC) {
68   // We can always evaluate constants shifted.
69   if (isa<Constant>(V))
70     return true;
71   
72   Instruction *I = dyn_cast<Instruction>(V);
73   if (!I) return false;
74   
75   // If this is the opposite shift, we can directly reuse the input of the shift
76   // if the needed bits are already zero in the input.  This allows us to reuse
77   // the value which means that we don't care if the shift has multiple uses.
78   //  TODO:  Handle opposite shift by exact value.
79   ConstantInt *CI = 0;
80   if ((isLeftShift && match(I, m_LShr(m_Value(), m_ConstantInt(CI)))) ||
81       (!isLeftShift && match(I, m_Shl(m_Value(), m_ConstantInt(CI))))) {
82     if (CI->getZExtValue() == NumBits) {
83       // TODO: Check that the input bits are already zero with MaskedValueIsZero
84 #if 0
85       // If this is a truncate of a logical shr, we can truncate it to a smaller
86       // lshr iff we know that the bits we would otherwise be shifting in are
87       // already zeros.
88       uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
89       uint32_t BitWidth = Ty->getScalarSizeInBits();
90       if (MaskedValueIsZero(I->getOperand(0),
91             APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
92           CI->getLimitedValue(BitWidth) < BitWidth) {
93         return CanEvaluateTruncated(I->getOperand(0), Ty);
94       }
95 #endif
96       
97     }
98   }
99   
100   // We can't mutate something that has multiple uses: doing so would
101   // require duplicating the instruction in general, which isn't profitable.
102   if (!I->hasOneUse()) return false;
103   
104   switch (I->getOpcode()) {
105   default: return false;
106   case Instruction::And:
107   case Instruction::Or:
108   case Instruction::Xor:
109     // Bitwise operators can all arbitrarily be arbitrarily evaluated shifted.
110     return CanEvaluateShifted(I->getOperand(0), NumBits, isLeftShift, IC) &&
111            CanEvaluateShifted(I->getOperand(1), NumBits, isLeftShift, IC);
112       
113   case Instruction::Shl: {
114     // We can often fold the shift into shifts-by-a-constant.
115     CI = dyn_cast<ConstantInt>(I->getOperand(1));
116     if (CI == 0) return false;
117
118     // We can always fold shl(c1)+shl(c2) -> shl(c1+c2).
119     if (isLeftShift) return true;
120     
121     // We can always turn shl(c)+shr(c) -> and(c2).
122     if (CI->getValue() == NumBits) return true;
123       
124     unsigned TypeWidth = I->getType()->getScalarSizeInBits();
125
126     // We can turn shl(c1)+shr(c2) -> shl(c3)+and(c4), but it isn't
127     // profitable unless we know the and'd out bits are already zero.
128     if (CI->getZExtValue() > NumBits) {
129       unsigned LowBits = TypeWidth - CI->getZExtValue();
130       if (MaskedValueIsZero(I->getOperand(0),
131                        APInt::getLowBitsSet(TypeWidth, NumBits) << LowBits))
132         return true;
133     }
134       
135     return false;
136   }
137   case Instruction::LShr: {
138     // We can often fold the shift into shifts-by-a-constant.
139     CI = dyn_cast<ConstantInt>(I->getOperand(1));
140     if (CI == 0) return false;
141     
142     // We can always fold lshr(c1)+lshr(c2) -> lshr(c1+c2).
143     if (!isLeftShift) return true;
144     
145     // We can always turn lshr(c)+shl(c) -> and(c2).
146     if (CI->getValue() == NumBits) return true;
147       
148     unsigned TypeWidth = I->getType()->getScalarSizeInBits();
149
150     // We can always turn lshr(c1)+shl(c2) -> lshr(c3)+and(c4), but it isn't
151     // profitable unless we know the and'd out bits are already zero.
152     if (CI->getZExtValue() > NumBits) {
153       unsigned LowBits = CI->getZExtValue() - NumBits;
154       if (MaskedValueIsZero(I->getOperand(0),
155                           APInt::getLowBitsSet(TypeWidth, NumBits) << LowBits))
156         return true;
157     }
158       
159     return false;
160   }
161   case Instruction::Select: {
162     SelectInst *SI = cast<SelectInst>(I);
163     return CanEvaluateShifted(SI->getTrueValue(), NumBits, isLeftShift, IC) &&
164            CanEvaluateShifted(SI->getFalseValue(), NumBits, isLeftShift, IC);
165   }
166   case Instruction::PHI: {
167     // We can change a phi if we can change all operands.  Note that we never
168     // get into trouble with cyclic PHIs here because we only consider
169     // instructions with a single use.
170     PHINode *PN = cast<PHINode>(I);
171     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
172       if (!CanEvaluateShifted(PN->getIncomingValue(i), NumBits, isLeftShift,IC))
173         return false;
174     return true;
175   }
176   }      
177 }
178
179 /// GetShiftedValue - When CanEvaluateShifted returned true for an expression,
180 /// this value inserts the new computation that produces the shifted value.
181 static Value *GetShiftedValue(Value *V, unsigned NumBits, bool isLeftShift,
182                               InstCombiner &IC) {
183   // We can always evaluate constants shifted.
184   if (Constant *C = dyn_cast<Constant>(V)) {
185     if (isLeftShift)
186       V = IC.Builder->CreateShl(C, NumBits);
187     else
188       V = IC.Builder->CreateLShr(C, NumBits);
189     // If we got a constantexpr back, try to simplify it with TD info.
190     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
191       V = ConstantFoldConstantExpression(CE, IC.getTargetData());
192     return V;
193   }
194   
195   Instruction *I = cast<Instruction>(V);
196   IC.Worklist.Add(I);
197
198   switch (I->getOpcode()) {
199   default: assert(0 && "Inconsistency with CanEvaluateShifted");
200   case Instruction::And:
201   case Instruction::Or:
202   case Instruction::Xor:
203     // Bitwise operators can all arbitrarily be arbitrarily evaluated shifted.
204     I->setOperand(0, GetShiftedValue(I->getOperand(0), NumBits,isLeftShift,IC));
205     I->setOperand(1, GetShiftedValue(I->getOperand(1), NumBits,isLeftShift,IC));
206     return I;
207     
208   case Instruction::Shl: {
209     unsigned TypeWidth = I->getType()->getScalarSizeInBits();
210
211     // We only accept shifts-by-a-constant in CanEvaluateShifted.
212     ConstantInt *CI = cast<ConstantInt>(I->getOperand(1));
213     
214     // We can always fold shl(c1)+shl(c2) -> shl(c1+c2).
215     if (isLeftShift) {
216       // If this is oversized composite shift, then unsigned shifts get 0.
217       unsigned NewShAmt = NumBits+CI->getZExtValue();
218       if (NewShAmt >= TypeWidth)
219         return Constant::getNullValue(I->getType());
220
221       I->setOperand(1, ConstantInt::get(I->getType(), NewShAmt));
222       return I;
223     }
224     
225     // We turn shl(c)+lshr(c) -> and(c2) if the input doesn't already have
226     // zeros.
227     if (CI->getValue() == NumBits) {
228       APInt Mask(APInt::getLowBitsSet(TypeWidth, TypeWidth - NumBits));
229       V = IC.Builder->CreateAnd(I->getOperand(0),
230                                 ConstantInt::get(I->getContext(), Mask));
231       if (Instruction *VI = dyn_cast<Instruction>(V)) {
232         VI->moveBefore(I);
233         VI->takeName(I);
234       }
235       return V;
236     }
237     
238     // We turn shl(c1)+shr(c2) -> shl(c3)+and(c4), but only when we know that
239     // the and won't be needed.
240     assert(CI->getZExtValue() > NumBits);
241     I->setOperand(1, ConstantInt::get(I->getType(),
242                                       CI->getZExtValue() - NumBits));
243     return I;
244   }
245   case Instruction::LShr: {
246     unsigned TypeWidth = I->getType()->getScalarSizeInBits();
247     // We only accept shifts-by-a-constant in CanEvaluateShifted.
248     ConstantInt *CI = cast<ConstantInt>(I->getOperand(1));
249     
250     // We can always fold lshr(c1)+lshr(c2) -> lshr(c1+c2).
251     if (!isLeftShift) {
252       // If this is oversized composite shift, then unsigned shifts get 0.
253       unsigned NewShAmt = NumBits+CI->getZExtValue();
254       if (NewShAmt >= TypeWidth)
255         return Constant::getNullValue(I->getType());
256       
257       I->setOperand(1, ConstantInt::get(I->getType(), NewShAmt));
258       return I;
259     }
260     
261     // We turn lshr(c)+shl(c) -> and(c2) if the input doesn't already have
262     // zeros.
263     if (CI->getValue() == NumBits) {
264       APInt Mask(APInt::getHighBitsSet(TypeWidth, TypeWidth - NumBits));
265       V = IC.Builder->CreateAnd(I->getOperand(0),
266                                 ConstantInt::get(I->getContext(), Mask));
267       if (Instruction *VI = dyn_cast<Instruction>(V)) {
268         VI->moveBefore(I);
269         VI->takeName(I);
270       }
271       return V;
272     }
273     
274     // We turn lshr(c1)+shl(c2) -> lshr(c3)+and(c4), but only when we know that
275     // the and won't be needed.
276     assert(CI->getZExtValue() > NumBits);
277     I->setOperand(1, ConstantInt::get(I->getType(),
278                                       CI->getZExtValue() - NumBits));
279     return I;
280   }
281     
282   case Instruction::Select:
283     I->setOperand(1, GetShiftedValue(I->getOperand(1), NumBits,isLeftShift,IC));
284     I->setOperand(2, GetShiftedValue(I->getOperand(2), NumBits,isLeftShift,IC));
285     return I;
286   case Instruction::PHI: {
287     // We can change a phi if we can change all operands.  Note that we never
288     // get into trouble with cyclic PHIs here because we only consider
289     // instructions with a single use.
290     PHINode *PN = cast<PHINode>(I);
291     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
292       PN->setIncomingValue(i, GetShiftedValue(PN->getIncomingValue(i),
293                                               NumBits, isLeftShift, IC));
294     return PN;
295   }
296   }      
297 }
298
299
300
301 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
302                                                BinaryOperator &I) {
303   bool isLeftShift = I.getOpcode() == Instruction::Shl;
304   
305   
306   // See if we can propagate this shift into the input, this covers the trivial
307   // cast of lshr(shl(x,c1),c2) as well as other more complex cases.
308   if (I.getOpcode() != Instruction::AShr &&
309       CanEvaluateShifted(Op0, Op1->getZExtValue(), isLeftShift, *this)) {
310     DEBUG(dbgs() << "ICE: GetShiftedValue propagating shift through expression"
311               " to eliminate shift:\n  IN: " << *Op0 << "\n  SH: " << I <<"\n");
312     
313     return ReplaceInstUsesWith(I, 
314                  GetShiftedValue(Op0, Op1->getZExtValue(), isLeftShift, *this));
315   }
316   
317   
318   // See if we can simplify any instructions used by the instruction whose sole 
319   // purpose is to compute bits we don't care about.
320   uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
321   
322   // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
323   // a signed shift.
324   //
325   if (Op1->uge(TypeBits)) {
326     if (I.getOpcode() != Instruction::AShr)
327       return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
328     // ashr i32 X, 32 --> ashr i32 X, 31
329     I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
330     return &I;
331   }
332   
333   // ((X*C1) << C2) == (X * (C1 << C2))
334   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
335     if (BO->getOpcode() == Instruction::Mul && isLeftShift)
336       if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
337         return BinaryOperator::CreateMul(BO->getOperand(0),
338                                         ConstantExpr::getShl(BOOp, Op1));
339   
340   // Try to fold constant and into select arguments.
341   if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
342     if (Instruction *R = FoldOpIntoSelect(I, SI))
343       return R;
344   if (isa<PHINode>(Op0))
345     if (Instruction *NV = FoldOpIntoPhi(I))
346       return NV;
347   
348   // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
349   if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
350     Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
351     // If 'shift2' is an ashr, we would have to get the sign bit into a funny
352     // place.  Don't try to do this transformation in this case.  Also, we
353     // require that the input operand is a shift-by-constant so that we have
354     // confidence that the shifts will get folded together.  We could do this
355     // xform in more cases, but it is unlikely to be profitable.
356     if (TrOp && I.isLogicalShift() && TrOp->isShift() && 
357         isa<ConstantInt>(TrOp->getOperand(1))) {
358       // Okay, we'll do this xform.  Make the shift of shift.
359       Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
360       // (shift2 (shift1 & 0x00FF), c2)
361       Value *NSh = Builder->CreateBinOp(I.getOpcode(), TrOp, ShAmt,I.getName());
362
363       // For logical shifts, the truncation has the effect of making the high
364       // part of the register be zeros.  Emulate this by inserting an AND to
365       // clear the top bits as needed.  This 'and' will usually be zapped by
366       // other xforms later if dead.
367       unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
368       unsigned DstSize = TI->getType()->getScalarSizeInBits();
369       APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
370       
371       // The mask we constructed says what the trunc would do if occurring
372       // between the shifts.  We want to know the effect *after* the second
373       // shift.  We know that it is a logical shift by a constant, so adjust the
374       // mask as appropriate.
375       if (I.getOpcode() == Instruction::Shl)
376         MaskV <<= Op1->getZExtValue();
377       else {
378         assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
379         MaskV = MaskV.lshr(Op1->getZExtValue());
380       }
381
382       // shift1 & 0x00FF
383       Value *And = Builder->CreateAnd(NSh,
384                                       ConstantInt::get(I.getContext(), MaskV),
385                                       TI->getName());
386
387       // Return the value truncated to the interesting size.
388       return new TruncInst(And, I.getType());
389     }
390   }
391   
392   if (Op0->hasOneUse()) {
393     if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
394       // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
395       Value *V1, *V2;
396       ConstantInt *CC;
397       switch (Op0BO->getOpcode()) {
398       default: break;
399       case Instruction::Add:
400       case Instruction::And:
401       case Instruction::Or:
402       case Instruction::Xor: {
403         // These operators commute.
404         // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
405         if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
406             match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
407                   m_Specific(Op1)))) {
408           Value *YS =         // (Y << C)
409             Builder->CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName());
410           // (X + (Y << C))
411           Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), YS, V1,
412                                           Op0BO->getOperand(1)->getName());
413           uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
414           return BinaryOperator::CreateAnd(X, ConstantInt::get(I.getContext(),
415                      APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
416         }
417         
418         // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
419         Value *Op0BOOp1 = Op0BO->getOperand(1);
420         if (isLeftShift && Op0BOOp1->hasOneUse() &&
421             match(Op0BOOp1, 
422                   m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
423                         m_ConstantInt(CC))) &&
424             cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
425           Value *YS =   // (Y << C)
426             Builder->CreateShl(Op0BO->getOperand(0), Op1,
427                                          Op0BO->getName());
428           // X & (CC << C)
429           Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
430                                          V1->getName()+".mask");
431           return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
432         }
433       }
434         
435       // FALL THROUGH.
436       case Instruction::Sub: {
437         // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
438         if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
439             match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
440                   m_Specific(Op1)))) {
441           Value *YS =  // (Y << C)
442             Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
443           // (X + (Y << C))
444           Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), V1, YS,
445                                           Op0BO->getOperand(0)->getName());
446           uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
447           return BinaryOperator::CreateAnd(X, ConstantInt::get(I.getContext(),
448                      APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
449         }
450         
451         // Turn (((X >> C)&CC) + Y) << C  ->  (X + (Y << C)) & (CC << C)
452         if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
453             match(Op0BO->getOperand(0),
454                   m_And(m_Shr(m_Value(V1), m_Value(V2)),
455                         m_ConstantInt(CC))) && V2 == Op1 &&
456             cast<BinaryOperator>(Op0BO->getOperand(0))
457                 ->getOperand(0)->hasOneUse()) {
458           Value *YS = // (Y << C)
459             Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
460           // X & (CC << C)
461           Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
462                                          V1->getName()+".mask");
463           
464           return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
465         }
466         
467         break;
468       }
469       }
470       
471       
472       // If the operand is an bitwise operator with a constant RHS, and the
473       // shift is the only use, we can pull it out of the shift.
474       if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
475         bool isValid = true;     // Valid only for And, Or, Xor
476         bool highBitSet = false; // Transform if high bit of constant set?
477         
478         switch (Op0BO->getOpcode()) {
479         default: isValid = false; break;   // Do not perform transform!
480         case Instruction::Add:
481           isValid = isLeftShift;
482           break;
483         case Instruction::Or:
484         case Instruction::Xor:
485           highBitSet = false;
486           break;
487         case Instruction::And:
488           highBitSet = true;
489           break;
490         }
491         
492         // If this is a signed shift right, and the high bit is modified
493         // by the logical operation, do not perform the transformation.
494         // The highBitSet boolean indicates the value of the high bit of
495         // the constant which would cause it to be modified for this
496         // operation.
497         //
498         if (isValid && I.getOpcode() == Instruction::AShr)
499           isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
500         
501         if (isValid) {
502           Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
503           
504           Value *NewShift =
505             Builder->CreateBinOp(I.getOpcode(), Op0BO->getOperand(0), Op1);
506           NewShift->takeName(Op0BO);
507           
508           return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
509                                         NewRHS);
510         }
511       }
512     }
513   }
514   
515   // Find out if this is a shift of a shift by a constant.
516   BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
517   if (ShiftOp && !ShiftOp->isShift())
518     ShiftOp = 0;
519   
520   if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
521     ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
522     uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
523     uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
524     assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
525     if (ShiftAmt1 == 0) return 0;  // Will be simplified in the future.
526     Value *X = ShiftOp->getOperand(0);
527     
528     uint32_t AmtSum = ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
529     
530     const IntegerType *Ty = cast<IntegerType>(I.getType());
531     
532     // Check for (X << c1) << c2  and  (X >> c1) >> c2
533     if (I.getOpcode() == ShiftOp->getOpcode()) {
534       // If this is oversized composite shift, then unsigned shifts get 0, ashr
535       // saturates.
536       if (AmtSum >= TypeBits) {
537         if (I.getOpcode() != Instruction::AShr)
538           return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
539         AmtSum = TypeBits-1;  // Saturate to 31 for i32 ashr.
540       }
541       
542       return BinaryOperator::Create(I.getOpcode(), X,
543                                     ConstantInt::get(Ty, AmtSum));
544     }
545     
546     if (ShiftAmt1 == ShiftAmt2) {
547       // If we have ((X >>? C) << C), turn this into X & (-1 << C).
548       if (I.getOpcode() == Instruction::Shl &&
549           ShiftOp->getOpcode() != Instruction::Shl) {
550         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
551         return BinaryOperator::CreateAnd(X,
552                                          ConstantInt::get(I.getContext(),Mask));
553       }
554       // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
555       if (I.getOpcode() == Instruction::LShr &&
556           ShiftOp->getOpcode() == Instruction::Shl) {
557         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
558         return BinaryOperator::CreateAnd(X,
559                                         ConstantInt::get(I.getContext(), Mask));
560       }
561     } else if (ShiftAmt1 < ShiftAmt2) {
562       uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
563       
564       // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
565       if (I.getOpcode() == Instruction::Shl &&
566           ShiftOp->getOpcode() != Instruction::Shl) {
567         assert(ShiftOp->getOpcode() == Instruction::LShr ||
568                ShiftOp->getOpcode() == Instruction::AShr);
569         Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
570         
571         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
572         return BinaryOperator::CreateAnd(Shift,
573                                          ConstantInt::get(I.getContext(),Mask));
574       }
575       
576       // (X << C1) >>u C2  --> X >>u (C2-C1) & (-1 >> C2)
577       if (I.getOpcode() == Instruction::LShr &&
578           ShiftOp->getOpcode() == Instruction::Shl) {
579         assert(ShiftOp->getOpcode() == Instruction::Shl);
580         Value *Shift = Builder->CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
581         
582         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
583         return BinaryOperator::CreateAnd(Shift,
584                                          ConstantInt::get(I.getContext(),Mask));
585       }
586       
587       // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
588     } else {
589       assert(ShiftAmt2 < ShiftAmt1);
590       uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
591
592       // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
593       if (I.getOpcode() == Instruction::Shl &&
594           ShiftOp->getOpcode() != Instruction::Shl) {
595         Value *Shift = Builder->CreateBinOp(ShiftOp->getOpcode(), X,
596                                             ConstantInt::get(Ty, ShiftDiff));
597         
598         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
599         return BinaryOperator::CreateAnd(Shift,
600                                          ConstantInt::get(I.getContext(),Mask));
601       }
602       
603       // (X << C1) >>u C2  --> X << (C1-C2) & (-1 >> C2)
604       if (I.getOpcode() == Instruction::LShr &&
605           ShiftOp->getOpcode() == Instruction::Shl) {
606         Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
607         
608         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
609         return BinaryOperator::CreateAnd(Shift,
610                                          ConstantInt::get(I.getContext(),Mask));
611       }
612       
613       // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
614     }
615   }
616   return 0;
617 }
618
619 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
620   if (Value *V = SimplifyShlInst(I.getOperand(0), I.getOperand(1), TD))
621     return ReplaceInstUsesWith(I, V);
622   return commonShiftTransforms(I);
623 }
624
625 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
626   if (Value *V = SimplifyLShrInst(I.getOperand(0), I.getOperand(1), TD))
627     return ReplaceInstUsesWith(I, V);
628
629   if (Instruction *R = commonShiftTransforms(I))
630     return R;
631   
632   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
633   
634   if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1))
635     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op0)) {
636       unsigned BitWidth = Op0->getType()->getScalarSizeInBits();
637       // ctlz.i32(x)>>5  --> zext(x == 0)
638       // cttz.i32(x)>>5  --> zext(x == 0)
639       // ctpop.i32(x)>>5 --> zext(x == -1)
640       if ((II->getIntrinsicID() == Intrinsic::ctlz ||
641            II->getIntrinsicID() == Intrinsic::cttz ||
642            II->getIntrinsicID() == Intrinsic::ctpop) &&
643           isPowerOf2_32(BitWidth) && Log2_32(BitWidth) == Op1C->getZExtValue()){
644         bool isCtPop = II->getIntrinsicID() == Intrinsic::ctpop;
645         Constant *RHS = ConstantInt::getSigned(Op0->getType(), isCtPop ? -1:0);
646         Value *Cmp = Builder->CreateICmpEQ(II->getArgOperand(0), RHS);
647         return new ZExtInst(Cmp, II->getType());
648       }
649     }
650   
651   return 0;
652 }
653
654 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
655   if (Value *V = SimplifyAShrInst(I.getOperand(0), I.getOperand(1), TD))
656     return ReplaceInstUsesWith(I, V);
657
658   if (Instruction *R = commonShiftTransforms(I))
659     return R;
660   
661   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
662
663   if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
664     // If the input is a SHL by the same constant (ashr (shl X, C), C), then we
665     // have a sign-extend idiom.
666     Value *X;
667     if (match(Op0, m_Shl(m_Value(X), m_Specific(Op1)))) {
668       // If the input value is known to already be sign extended enough, delete
669       // the extension.
670       if (ComputeNumSignBits(X) > Op1C->getZExtValue())
671         return ReplaceInstUsesWith(I, X);
672
673       // If the input is an extension from the shifted amount value, e.g.
674       //   %x = zext i8 %A to i32
675       //   %y = shl i32 %x, 24
676       //   %z = ashr %y, 24
677       // then turn this into "z = sext i8 A to i32".
678       if (ZExtInst *ZI = dyn_cast<ZExtInst>(X)) {
679         uint32_t SrcBits = ZI->getOperand(0)->getType()->getScalarSizeInBits();
680         uint32_t DestBits = ZI->getType()->getScalarSizeInBits();
681         if (Op1C->getZExtValue() == DestBits-SrcBits)
682           return new SExtInst(ZI->getOperand(0), ZI->getType());
683       }
684     }
685   }            
686   
687   // See if we can turn a signed shr into an unsigned shr.
688   if (MaskedValueIsZero(Op0,
689                         APInt::getSignBit(I.getType()->getScalarSizeInBits())))
690     return BinaryOperator::CreateLShr(Op0, Op1);
691   
692   // Arithmetic shifting an all-sign-bit value is a no-op.
693   unsigned NumSignBits = ComputeNumSignBits(Op0);
694   if (NumSignBits == Op0->getType()->getScalarSizeInBits())
695     return ReplaceInstUsesWith(I, Op0);
696   
697   return 0;
698 }
699