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