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