blob: 395d79d5a74a213c8e81f0e14778932c925b5281 [file] [log] [blame]
Chris Lattner9cdd5f32010-01-05 07:44:46 +00001//===- 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"
Chris Lattner818ff342010-01-23 18:49:30 +000015#include "llvm/IntrinsicInst.h"
Duncan Sandsc43cee32011-01-14 00:37:45 +000016#include "llvm/Analysis/InstructionSimplify.h"
Chris Lattner9cdd5f32010-01-05 07:44:46 +000017#include "llvm/Support/PatternMatch.h"
18using namespace llvm;
19using namespace PatternMatch;
20
21Instruction *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
Chris Lattner9cdd5f32010-01-05 07:44:46 +000025 // 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;
Benjamin Kramerb70ebd22010-11-23 18:52:42 +000038
Benjamin Kramerc21a8212010-11-23 20:33:57 +000039 // X shift (A srem B) -> X shift (A and B-1) iff B is a power of 2.
Benjamin Kramerb70ebd22010-11-23 18:52:42 +000040 // Because shifts by negative values are undefined.
41 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op1))
Benjamin Kramerc21a8212010-11-23 20:33:57 +000042 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 }
Benjamin Kramerb70ebd22010-11-23 18:52:42 +000050
Chris Lattner9cdd5f32010-01-05 07:44:46 +000051 return 0;
52}
53
Chris Lattner29cc0b32010-08-27 22:24:38 +000054/// 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.
66static 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.
Ted Kremenek584520e2011-01-23 17:05:06 +000079 ConstantInt *CI = 0;
Chris Lattner29cc0b32010-08-27 22:24:38 +000080 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
Chris Lattner4ece5772010-08-27 22:53:44 +0000113 case Instruction::Shl: {
Chris Lattner29cc0b32010-08-27 22:24:38 +0000114 // 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;
Chris Lattner4ece5772010-08-27 22:53:44 +0000123
124 unsigned TypeWidth = I->getType()->getScalarSizeInBits();
125
126 // We can turn shl(c1)+shr(c2) -> shl(c3)+and(c4), but it isn't
Chris Lattner29cc0b32010-08-27 22:24:38 +0000127 // profitable unless we know the and'd out bits are already zero.
Chris Lattner4ece5772010-08-27 22:53:44 +0000128 if (CI->getZExtValue() > NumBits) {
Dale Johannesen201ab3a2010-11-10 01:30:56 +0000129 unsigned LowBits = TypeWidth - CI->getZExtValue();
Chris Lattner4ece5772010-08-27 22:53:44 +0000130 if (MaskedValueIsZero(I->getOperand(0),
Dale Johannesen201ab3a2010-11-10 01:30:56 +0000131 APInt::getLowBitsSet(TypeWidth, NumBits) << LowBits))
Chris Lattner4ece5772010-08-27 22:53:44 +0000132 return true;
133 }
134
Chris Lattner29cc0b32010-08-27 22:24:38 +0000135 return false;
Chris Lattner4ece5772010-08-27 22:53:44 +0000136 }
137 case Instruction::LShr: {
Chris Lattner29cc0b32010-08-27 22:24:38 +0000138 // 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
Chris Lattner4ece5772010-08-27 22:53:44 +0000148 unsigned TypeWidth = I->getType()->getScalarSizeInBits();
149
Chris Lattner29cc0b32010-08-27 22:24:38 +0000150 // 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.
Chris Lattner4ece5772010-08-27 22:53:44 +0000152 if (CI->getZExtValue() > NumBits) {
Owen Andersonec3953f2010-12-23 23:56:24 +0000153 unsigned LowBits = CI->getZExtValue() - NumBits;
Chris Lattner4ece5772010-08-27 22:53:44 +0000154 if (MaskedValueIsZero(I->getOperand(0),
Owen Andersonec3953f2010-12-23 23:56:24 +0000155 APInt::getLowBitsSet(TypeWidth, NumBits) << LowBits))
Chris Lattner4ece5772010-08-27 22:53:44 +0000156 return true;
157 }
Chris Lattner29cc0b32010-08-27 22:24:38 +0000158
Chris Lattner4ece5772010-08-27 22:53:44 +0000159 return false;
160 }
Chris Lattner29cc0b32010-08-27 22:24:38 +0000161 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.
181static 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.
Chris Lattner4ece5772010-08-27 22:53:44 +0000227 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;
Chris Lattner29cc0b32010-08-27 22:24:38 +0000236 }
Chris Lattner4ece5772010-08-27 22:53:44 +0000237
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;
Chris Lattner29cc0b32010-08-27 22:24:38 +0000244 }
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.
Chris Lattner4ece5772010-08-27 22:53:44 +0000263 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;
Chris Lattner29cc0b32010-08-27 22:24:38 +0000272 }
Chris Lattner4ece5772010-08-27 22:53:44 +0000273
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;
Chris Lattner29cc0b32010-08-27 22:24:38 +0000280 }
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
Chris Lattner9cdd5f32010-01-05 07:44:46 +0000301Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
302 BinaryOperator &I) {
303 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner2d0822a2010-08-27 21:04:34 +0000304
Chris Lattner29cc0b32010-08-27 22:24:38 +0000305
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)) {
Chris Lattner3dd08732010-08-28 01:20:38 +0000310 DEBUG(dbgs() << "ICE: GetShiftedValue propagating shift through expression"
311 " to eliminate shift:\n IN: " << *Op0 << "\n SH: " << I <<"\n");
Chris Lattner29cc0b32010-08-27 22:24:38 +0000312
313 return ReplaceInstUsesWith(I,
314 GetShiftedValue(Op0, Op1->getZExtValue(), isLeftShift, *this));
315 }
316
317
Chris Lattner9cdd5f32010-01-05 07:44:46 +0000318 // 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()));
Chris Lattner818ff342010-01-23 18:49:30 +0000328 // ashr i32 X, 32 --> ashr i32 X, 31
329 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
330 return &I;
Chris Lattner9cdd5f32010-01-05 07:44:46 +0000331 }
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()) {
Chris Lattnerabff82d2010-01-10 06:59:55 +0000398 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)));
Chris Lattner9cdd5f32010-01-05 07:44:46 +0000416 }
Chris Lattnerabff82d2010-01-10 06:59:55 +0000417
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);
Chris Lattner9cdd5f32010-01-05 07:44:46 +0000432 }
433 }
Chris Lattnerabff82d2010-01-10 06:59:55 +0000434
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 }
Chris Lattner9cdd5f32010-01-05 07:44:46 +0000470
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()) {
Chris Lattnerabff82d2010-01-10 06:59:55 +0000479 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;
Chris Lattner9cdd5f32010-01-05 07:44:46 +0000490 }
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
Chris Lattner9cdd5f32010-01-05 07:44:46 +0000546 if (ShiftAmt1 == ShiftAmt2) {
547 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
Chris Lattner2d0822a2010-08-27 21:04:34 +0000548 if (I.getOpcode() == Instruction::Shl &&
549 ShiftOp->getOpcode() != Instruction::Shl) {
Chris Lattner9cdd5f32010-01-05 07:44:46 +0000550 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).
Chris Lattner2d0822a2010-08-27 21:04:34 +0000555 if (I.getOpcode() == Instruction::LShr &&
556 ShiftOp->getOpcode() == Instruction::Shl) {
Chris Lattner9cdd5f32010-01-05 07:44:46 +0000557 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
558 return BinaryOperator::CreateAnd(X,
559 ConstantInt::get(I.getContext(), Mask));
560 }
Chris Lattner9cdd5f32010-01-05 07:44:46 +0000561 } else if (ShiftAmt1 < ShiftAmt2) {
562 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
563
564 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattner2d0822a2010-08-27 21:04:34 +0000565 if (I.getOpcode() == Instruction::Shl &&
566 ShiftOp->getOpcode() != Instruction::Shl) {
Chris Lattner9cdd5f32010-01-05 07:44:46 +0000567 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)
Chris Lattner2d0822a2010-08-27 21:04:34 +0000577 if (I.getOpcode() == Instruction::LShr &&
578 ShiftOp->getOpcode() == Instruction::Shl) {
Chris Lattner9cdd5f32010-01-05 07:44:46 +0000579 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)
Chris Lattner2d0822a2010-08-27 21:04:34 +0000593 if (I.getOpcode() == Instruction::Shl &&
594 ShiftOp->getOpcode() != Instruction::Shl) {
Chris Lattner9cdd5f32010-01-05 07:44:46 +0000595 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)
Chris Lattner2d0822a2010-08-27 21:04:34 +0000604 if (I.getOpcode() == Instruction::LShr &&
605 ShiftOp->getOpcode() == Instruction::Shl) {
Chris Lattner9cdd5f32010-01-05 07:44:46 +0000606 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
619Instruction *InstCombiner::visitShl(BinaryOperator &I) {
Chris Lattner81a0dc92011-02-09 17:15:04 +0000620 if (Value *V = SimplifyShlInst(I.getOperand(0), I.getOperand(1),
621 I.hasNoSignedWrap(), I.hasNoUnsignedWrap(),
622 TD))
Duncan Sandsc43cee32011-01-14 00:37:45 +0000623 return ReplaceInstUsesWith(I, V);
Chris Lattner9cdd5f32010-01-05 07:44:46 +0000624 return commonShiftTransforms(I);
625}
626
627Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
Chris Lattner81a0dc92011-02-09 17:15:04 +0000628 if (Value *V = SimplifyLShrInst(I.getOperand(0), I.getOperand(1),
629 I.isExact(), TD))
Duncan Sandsc43cee32011-01-14 00:37:45 +0000630 return ReplaceInstUsesWith(I, V);
631
Chris Lattner818ff342010-01-23 18:49:30 +0000632 if (Instruction *R = commonShiftTransforms(I))
633 return R;
634
635 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
636
637 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1))
638 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op0)) {
Chris Lattnerf7d0d162010-01-23 23:31:46 +0000639 unsigned BitWidth = Op0->getType()->getScalarSizeInBits();
Chris Lattner818ff342010-01-23 18:49:30 +0000640 // ctlz.i32(x)>>5 --> zext(x == 0)
641 // cttz.i32(x)>>5 --> zext(x == 0)
642 // ctpop.i32(x)>>5 --> zext(x == -1)
643 if ((II->getIntrinsicID() == Intrinsic::ctlz ||
644 II->getIntrinsicID() == Intrinsic::cttz ||
645 II->getIntrinsicID() == Intrinsic::ctpop) &&
Chris Lattnerf7d0d162010-01-23 23:31:46 +0000646 isPowerOf2_32(BitWidth) && Log2_32(BitWidth) == Op1C->getZExtValue()){
Chris Lattner818ff342010-01-23 18:49:30 +0000647 bool isCtPop = II->getIntrinsicID() == Intrinsic::ctpop;
Chris Lattnerf7d0d162010-01-23 23:31:46 +0000648 Constant *RHS = ConstantInt::getSigned(Op0->getType(), isCtPop ? -1:0);
Gabor Greifde9f5452010-06-24 00:44:01 +0000649 Value *Cmp = Builder->CreateICmpEQ(II->getArgOperand(0), RHS);
Chris Lattner818ff342010-01-23 18:49:30 +0000650 return new ZExtInst(Cmp, II->getType());
651 }
652 }
653
654 return 0;
Chris Lattner9cdd5f32010-01-05 07:44:46 +0000655}
656
657Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner81a0dc92011-02-09 17:15:04 +0000658 if (Value *V = SimplifyAShrInst(I.getOperand(0), I.getOperand(1),
659 I.isExact(), TD))
Duncan Sandsc43cee32011-01-14 00:37:45 +0000660 return ReplaceInstUsesWith(I, V);
661
Chris Lattner9cdd5f32010-01-05 07:44:46 +0000662 if (Instruction *R = commonShiftTransforms(I))
663 return R;
664
Chris Lattnera85732f2010-01-08 19:04:21 +0000665 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Duncan Sandsc43cee32011-01-14 00:37:45 +0000666
Chris Lattnera85732f2010-01-08 19:04:21 +0000667 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
668 // If the input is a SHL by the same constant (ashr (shl X, C), C), then we
Chris Lattnercd5adbb2010-01-18 22:19:16 +0000669 // have a sign-extend idiom.
Chris Lattnera85732f2010-01-08 19:04:21 +0000670 Value *X;
Chris Lattnercd5adbb2010-01-18 22:19:16 +0000671 if (match(Op0, m_Shl(m_Value(X), m_Specific(Op1)))) {
672 // If the input value is known to already be sign extended enough, delete
673 // the extension.
674 if (ComputeNumSignBits(X) > Op1C->getZExtValue())
675 return ReplaceInstUsesWith(I, X);
676
677 // If the input is an extension from the shifted amount value, e.g.
678 // %x = zext i8 %A to i32
679 // %y = shl i32 %x, 24
680 // %z = ashr %y, 24
681 // then turn this into "z = sext i8 A to i32".
682 if (ZExtInst *ZI = dyn_cast<ZExtInst>(X)) {
683 uint32_t SrcBits = ZI->getOperand(0)->getType()->getScalarSizeInBits();
684 uint32_t DestBits = ZI->getType()->getScalarSizeInBits();
685 if (Op1C->getZExtValue() == DestBits-SrcBits)
686 return new SExtInst(ZI->getOperand(0), ZI->getType());
687 }
688 }
Chris Lattnera85732f2010-01-08 19:04:21 +0000689 }
Chris Lattner9cdd5f32010-01-05 07:44:46 +0000690
691 // See if we can turn a signed shr into an unsigned shr.
692 if (MaskedValueIsZero(Op0,
693 APInt::getSignBit(I.getType()->getScalarSizeInBits())))
Chris Lattnera85732f2010-01-08 19:04:21 +0000694 return BinaryOperator::CreateLShr(Op0, Op1);
Chris Lattner9cdd5f32010-01-05 07:44:46 +0000695
696 // Arithmetic shifting an all-sign-bit value is a no-op.
697 unsigned NumSignBits = ComputeNumSignBits(Op0);
698 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
699 return ReplaceInstUsesWith(I, Op0);
700
701 return 0;
702}
703