blob: 6fbe7959b436c84da3e84ad9dd71c58dd314d785 [file] [log] [blame]
Chris Lattner80f43d32010-01-04 07:53:58 +00001//===- InstCombineCasts.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 visit functions for cast operations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "InstCombine.h"
15#include "llvm/Target/TargetData.h"
16#include "llvm/Support/PatternMatch.h"
17using namespace llvm;
18using namespace PatternMatch;
19
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +000020/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
21/// expression. If so, decompose it, returning some value X, such that Val is
22/// X*Scale+Offset.
23///
24static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
25 int &Offset) {
Benjamin Kramer11acaa32010-01-05 20:07:06 +000026 assert(Val->getType()->isInteger(32) && "Unexpected allocation size type!");
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +000027 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
28 Offset = CI->getZExtValue();
29 Scale = 0;
30 return ConstantInt::get(Type::getInt32Ty(Val->getContext()), 0);
Chris Lattnerf86d7992010-01-05 20:57:30 +000031 }
32
33 if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +000034 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
35 if (I->getOpcode() == Instruction::Shl) {
36 // This is a value scaled by '1 << the shift amt'.
37 Scale = 1U << RHS->getZExtValue();
38 Offset = 0;
39 return I->getOperand(0);
Chris Lattnerf86d7992010-01-05 20:57:30 +000040 }
41
42 if (I->getOpcode() == Instruction::Mul) {
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +000043 // This value is scaled by 'RHS'.
44 Scale = RHS->getZExtValue();
45 Offset = 0;
46 return I->getOperand(0);
Chris Lattnerf86d7992010-01-05 20:57:30 +000047 }
48
49 if (I->getOpcode() == Instruction::Add) {
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +000050 // We have X+C. Check to see if we really have (X*C2)+C1,
51 // where C1 is divisible by C2.
52 unsigned SubScale;
53 Value *SubVal =
54 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
55 Offset += RHS->getZExtValue();
56 Scale = SubScale;
57 return SubVal;
58 }
59 }
60 }
61
62 // Otherwise, we can't look past this.
63 Scale = 1;
64 Offset = 0;
65 return Val;
66}
67
68/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
69/// try to eliminate the cast by moving the type information into the alloc.
70Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
71 AllocaInst &AI) {
72 // This requires TargetData to get the alloca alignment and size information.
73 if (!TD) return 0;
74
75 const PointerType *PTy = cast<PointerType>(CI.getType());
76
77 BuilderTy AllocaBuilder(*Builder);
78 AllocaBuilder.SetInsertPoint(AI.getParent(), &AI);
79
80 // Get the type really allocated and the type casted to.
81 const Type *AllocElTy = AI.getAllocatedType();
82 const Type *CastElTy = PTy->getElementType();
83 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
84
85 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
86 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
87 if (CastElTyAlign < AllocElTyAlign) return 0;
88
89 // If the allocation has multiple uses, only promote it if we are strictly
90 // increasing the alignment of the resultant allocation. If we keep it the
91 // same, we open the door to infinite loops of various kinds. (A reference
92 // from a dbg.declare doesn't count as a use for this purpose.)
93 if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
94 CastElTyAlign == AllocElTyAlign) return 0;
95
96 uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
97 uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
98 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
99
100 // See if we can satisfy the modulus by pulling a scale out of the array
101 // size argument.
102 unsigned ArraySizeScale;
103 int ArrayOffset;
104 Value *NumElements = // See if the array size is a decomposable linear expr.
105 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
106
107 // If we can now satisfy the modulus, by using a non-1 scale, we really can
108 // do the xform.
109 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
110 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
111
112 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
113 Value *Amt = 0;
114 if (Scale == 1) {
115 Amt = NumElements;
116 } else {
117 Amt = ConstantInt::get(Type::getInt32Ty(CI.getContext()), Scale);
118 // Insert before the alloca, not before the cast.
119 Amt = AllocaBuilder.CreateMul(Amt, NumElements, "tmp");
120 }
121
122 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
123 Value *Off = ConstantInt::get(Type::getInt32Ty(CI.getContext()),
124 Offset, true);
125 Amt = AllocaBuilder.CreateAdd(Amt, Off, "tmp");
126 }
127
128 AllocaInst *New = AllocaBuilder.CreateAlloca(CastElTy, Amt);
129 New->setAlignment(AI.getAlignment());
130 New->takeName(&AI);
131
132 // If the allocation has one real use plus a dbg.declare, just remove the
133 // declare.
134 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
135 EraseInstFromFunction(*(Instruction*)DI);
136 }
137 // If the allocation has multiple real uses, insert a cast and change all
138 // things that used it to use the new cast. This will also hack on CI, but it
139 // will die soon.
140 else if (!AI.hasOneUse()) {
141 // New is the allocation instruction, pointer typed. AI is the original
142 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
143 Value *NewCast = AllocaBuilder.CreateBitCast(New, AI.getType(), "tmpcast");
144 AI.replaceAllUsesWith(NewCast);
145 }
146 return ReplaceInstUsesWith(CI, New);
147}
148
149
Chris Lattner5f0290e2010-01-04 07:54:59 +0000150/// CanEvaluateInDifferentType - Return true if we can take the specified value
151/// and return it as type Ty without inserting any new casts and without
152/// changing the computed value. This is used by code that tries to decide
153/// whether promoting or shrinking integer operations to wider or smaller types
154/// will allow us to eliminate a truncate or extend.
155///
Chris Lattnere0e4cc72010-01-06 01:56:21 +0000156/// This is a truncation operation if Ty is smaller than V->getType(), or a zero
Chris Lattner5f0290e2010-01-04 07:54:59 +0000157/// extension operation if Ty is larger.
158///
159/// If CastOpc is a truncation, then Ty will be a type smaller than V. We
160/// should return true if trunc(V) can be computed by computing V in the smaller
161/// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
162/// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
163/// efficiently truncated.
164///
Chris Lattner5c24a6d2010-01-06 05:32:15 +0000165/// If CastOpc is zext, we are asking if the low bits of the value can be
Chris Lattnere0e4cc72010-01-06 01:56:21 +0000166/// computed in a larger type, which is then and'd to get the final result.
Chris Lattner94aab492010-01-05 22:30:42 +0000167static bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnere0e4cc72010-01-06 01:56:21 +0000168 unsigned CastOpc,
169 unsigned &NumCastsRemoved) {
Chris Lattner075f6922010-01-07 23:41:00 +0000170 // FIXME: Eliminate CastOpc
171 assert(CastOpc == Instruction::Trunc);
Chris Lattnere0e4cc72010-01-06 01:56:21 +0000172
Chris Lattner5f0290e2010-01-04 07:54:59 +0000173 // We can always evaluate constants in another type.
174 if (isa<Constant>(V))
175 return true;
176
177 Instruction *I = dyn_cast<Instruction>(V);
178 if (!I) return false;
179
180 const Type *OrigTy = V->getType();
181
182 // If this is an extension or truncate, we can often eliminate it.
183 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
184 // If this is a cast from the destination type, we can trivially eliminate
185 // it, and this will remove a cast overall.
186 if (I->getOperand(0)->getType() == Ty) {
187 // If the first operand is itself a cast, and is eliminable, do not count
188 // this as an eliminable cast. We would prefer to eliminate those two
189 // casts first.
190 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
191 ++NumCastsRemoved;
192 return true;
193 }
194 }
195
196 // We can't extend or shrink something that has multiple uses: doing so would
197 // require duplicating the instruction in general, which isn't profitable.
198 if (!I->hasOneUse()) return false;
199
200 unsigned Opc = I->getOpcode();
201 switch (Opc) {
202 case Instruction::Add:
203 case Instruction::Sub:
204 case Instruction::Mul:
205 case Instruction::And:
206 case Instruction::Or:
207 case Instruction::Xor:
208 // These operators can all arbitrarily be extended or truncated.
209 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
210 NumCastsRemoved) &&
211 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
212 NumCastsRemoved);
213
214 case Instruction::UDiv:
215 case Instruction::URem: {
216 // UDiv and URem can be truncated if all the truncated bits are zero.
217 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
218 uint32_t BitWidth = Ty->getScalarSizeInBits();
219 if (BitWidth < OrigBitWidth) {
220 APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
221 if (MaskedValueIsZero(I->getOperand(0), Mask) &&
222 MaskedValueIsZero(I->getOperand(1), Mask)) {
223 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
224 NumCastsRemoved) &&
225 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
226 NumCastsRemoved);
227 }
228 }
229 break;
230 }
231 case Instruction::Shl:
232 // If we are truncating the result of this SHL, and if it's a shift of a
233 // constant amount, we can always perform a SHL in a smaller type.
234 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
235 uint32_t BitWidth = Ty->getScalarSizeInBits();
236 if (BitWidth < OrigTy->getScalarSizeInBits() &&
237 CI->getLimitedValue(BitWidth) < BitWidth)
238 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
239 NumCastsRemoved);
240 }
241 break;
242 case Instruction::LShr:
243 // If this is a truncate of a logical shr, we can truncate it to a smaller
244 // lshr iff we know that the bits we would otherwise be shifting in are
245 // already zeros.
246 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
247 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
248 uint32_t BitWidth = Ty->getScalarSizeInBits();
249 if (BitWidth < OrigBitWidth &&
250 MaskedValueIsZero(I->getOperand(0),
251 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
252 CI->getLimitedValue(BitWidth) < BitWidth) {
253 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
254 NumCastsRemoved);
255 }
256 }
257 break;
258 case Instruction::ZExt:
259 case Instruction::SExt:
260 case Instruction::Trunc:
261 // If this is the same kind of case as our original (e.g. zext+zext), we
262 // can safely replace it. Note that replacing it does not reduce the number
263 // of casts in the input.
264 if (Opc == CastOpc)
265 return true;
266
267 // sext (zext ty1), ty2 -> zext ty2
268 if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
269 return true;
270 break;
271 case Instruction::Select: {
272 SelectInst *SI = cast<SelectInst>(I);
273 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
274 NumCastsRemoved) &&
275 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
276 NumCastsRemoved);
277 }
278 case Instruction::PHI: {
Chris Lattner94aab492010-01-05 22:30:42 +0000279 // We can change a phi if we can change all operands. Note that we never
280 // get into trouble with cyclic PHIs here because we only consider
281 // instructions with a single use.
Chris Lattner5f0290e2010-01-04 07:54:59 +0000282 PHINode *PN = cast<PHINode>(I);
283 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
284 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
285 NumCastsRemoved))
286 return false;
287 return true;
288 }
289 default:
290 // TODO: Can handle more cases here.
291 break;
292 }
293
294 return false;
295}
296
Chris Lattner075f6922010-01-07 23:41:00 +0000297/// GetLeadingZeros - Compute the number of known-zero leading bits.
298static unsigned GetLeadingZeros(Value *V, const TargetData *TD) {
299 unsigned Bits = V->getType()->getScalarSizeInBits();
300 APInt KnownZero(Bits, 0), KnownOne(Bits, 0);
301 ComputeMaskedBits(V, APInt::getAllOnesValue(Bits), KnownZero, KnownOne, TD);
302 return KnownZero.countLeadingOnes();
303}
304
305/// CanEvaluateZExtd - Determine if the specified value can be computed in the
306/// specified wider type and produce the same low bits. If not, return -1. If
307/// it is possible, return the number of high bits that are known to be zero in
308/// the promoted value.
309static int CanEvaluateZExtd(Value *V, const Type *Ty,unsigned &NumCastsRemoved,
310 const TargetData *TD) {
311 const Type *OrigTy = V->getType();
312
313 if (isa<Constant>(V)) {
314 unsigned Extended = Ty->getScalarSizeInBits()-OrigTy->getScalarSizeInBits();
315
316 // Constants can always be zero ext'd, even if it requires a ConstantExpr.
317 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
318 return Extended + CI->getValue().countLeadingZeros();
319 return Extended;
320 }
321
322 Instruction *I = dyn_cast<Instruction>(V);
323 if (!I) return -1;
324
325 // If the input is a truncate from the destination type, we can trivially
326 // eliminate it, and this will remove a cast overall.
327 if (isa<TruncInst>(I) && I->getOperand(0)->getType() == Ty) {
328 // If the first operand is itself a cast, and is eliminable, do not count
329 // this as an eliminable cast. We would prefer to eliminate those two
330 // casts first.
331 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
332 ++NumCastsRemoved;
333
334 // Figure out the number of known-zero bits coming in.
335 return GetLeadingZeros(I->getOperand(0), TD);
336 }
337
338 // We can't extend or shrink something that has multiple uses: doing so would
339 // require duplicating the instruction in general, which isn't profitable.
340 if (!I->hasOneUse()) return -1;
341
342 int Tmp1, Tmp2;
343 unsigned Opc = I->getOpcode();
344 switch (Opc) {
345 case Instruction::And:
346 Tmp1 = CanEvaluateZExtd(I->getOperand(0), Ty, NumCastsRemoved, TD);
347 if (Tmp1 == -1) return -1;
348 Tmp2 = CanEvaluateZExtd(I->getOperand(1), Ty, NumCastsRemoved, TD);
349 if (Tmp2 == -1) return -1;
350 return std::max(Tmp1, Tmp2);
351 case Instruction::Or:
352 case Instruction::Xor:
353 Tmp1 = CanEvaluateZExtd(I->getOperand(0), Ty, NumCastsRemoved, TD);
354 if (Tmp1 == -1) return -1;
355 Tmp2 = CanEvaluateZExtd(I->getOperand(1), Ty, NumCastsRemoved, TD);
356 return std::min(Tmp1, Tmp2);
357
358 case Instruction::Add:
359 case Instruction::Sub:
360 case Instruction::Mul:
361 Tmp1 = CanEvaluateZExtd(I->getOperand(0), Ty, NumCastsRemoved, TD);
362 if (Tmp1 == -1) return -1;
363 Tmp2 = CanEvaluateZExtd(I->getOperand(1), Ty, NumCastsRemoved, TD);
364 if (Tmp2 == -1) return -1;
365 return 0;
366
367 //case Instruction::Shl:
368 //case Instruction::LShr:
369 case Instruction::ZExt:
370 // zext(zext(x)) -> zext(x). Since we're replacing it, it isn't eliminated.
371 Tmp1 = Ty->getScalarSizeInBits()-OrigTy->getScalarSizeInBits();
372 return GetLeadingZeros(I, TD)+Tmp1;
373
374 //case Instruction::SExt: zext(sext(x)) -> sext(x) with no upper bits known.
375 //case Instruction::Trunc:
376 case Instruction::Select:
377 Tmp1 = CanEvaluateZExtd(I->getOperand(1), Ty, NumCastsRemoved, TD);
378 if (Tmp1 == -1) return -1;
379 Tmp2 = CanEvaluateZExtd(I->getOperand(2), Ty, NumCastsRemoved, TD);
380 return std::min(Tmp1, Tmp2);
381
382 case Instruction::PHI: {
383 // We can change a phi if we can change all operands. Note that we never
384 // get into trouble with cyclic PHIs here because we only consider
385 // instructions with a single use.
386 PHINode *PN = cast<PHINode>(I);
387 int Result = CanEvaluateZExtd(PN->getIncomingValue(0), Ty,
388 NumCastsRemoved, TD);
389 for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i) {
390 if (Result == -1) return -1;
391 Tmp1 = CanEvaluateZExtd(PN->getIncomingValue(i), Ty, NumCastsRemoved, TD);
392 Result = std::min(Result, Tmp1);
393 }
394 return Result;
395 }
396 default:
397 // TODO: Can handle more cases here.
398 return -1;
399 }
400}
401
Chris Lattnere0e4cc72010-01-06 01:56:21 +0000402/// CanEvaluateSExtd - Return true if we can take the specified value
403/// and return it as type Ty without inserting any new casts and without
Chris Lattner5c24a6d2010-01-06 05:32:15 +0000404/// changing the value of the common low bits. This is used by code that tries
405/// to promote integer operations to a wider types will allow us to eliminate
406/// the extension.
Chris Lattnere0e4cc72010-01-06 01:56:21 +0000407///
408/// This returns 0 if we can't do this or the number of sign bits that would be
409/// set if we can. For example, CanEvaluateSExtd(i16 1, i64) would return 63,
410/// because the computation can be extended (to "i64 1") and the resulting
411/// computation has 63 equal sign bits.
412///
413/// This function works on both vectors and scalars. For vectors, the result is
414/// the number of bits known sign extended in each element.
415///
416static unsigned CanEvaluateSExtd(Value *V, const Type *Ty,
417 unsigned &NumCastsRemoved, TargetData *TD) {
418 assert(V->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits() &&
419 "Can't sign extend type to a smaller type");
420 // If this is a constant, return the number of sign bits the extended version
421 // of it would have.
422 if (Constant *C = dyn_cast<Constant>(V))
423 return ComputeNumSignBits(ConstantExpr::getSExt(C, Ty), TD);
424
425 Instruction *I = dyn_cast<Instruction>(V);
426 if (!I) return 0;
427
428 // If this is a truncate from the destination type, we can trivially eliminate
429 // it, and this will remove a cast overall.
430 if (isa<TruncInst>(I) && I->getOperand(0)->getType() == Ty) {
431 // If the operand of the truncate is itself a cast, and is eliminable, do
432 // not count this as an eliminable cast. We would prefer to eliminate those
433 // two casts first.
434 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
435 ++NumCastsRemoved;
436 return ComputeNumSignBits(I->getOperand(0), TD);
437 }
438
439 // We can't extend or shrink something that has multiple uses: doing so would
440 // require duplicating the instruction in general, which isn't profitable.
441 if (!I->hasOneUse()) return 0;
442
443 const Type *OrigTy = V->getType();
444
445 unsigned Opc = I->getOpcode();
446 unsigned Tmp1, Tmp2;
447 switch (Opc) {
448 case Instruction::And:
449 case Instruction::Or:
450 case Instruction::Xor:
451 // These operators can all arbitrarily be extended or truncated.
452 Tmp1 = CanEvaluateSExtd(I->getOperand(0), Ty, NumCastsRemoved, TD);
453 if (Tmp1 == 0) return 0;
454 Tmp2 = CanEvaluateSExtd(I->getOperand(1), Ty, NumCastsRemoved, TD);
455 return std::min(Tmp1, Tmp2);
456 case Instruction::Add:
457 case Instruction::Sub:
458 // Add/Sub can have at most one carry/borrow bit.
459 Tmp1 = CanEvaluateSExtd(I->getOperand(0), Ty, NumCastsRemoved, TD);
460 if (Tmp1 == 0) return 0;
461 Tmp2 = CanEvaluateSExtd(I->getOperand(1), Ty, NumCastsRemoved, TD);
462 if (Tmp2 == 0) return 0;
463 return std::min(Tmp1, Tmp2)-1;
464 case Instruction::Mul:
465 // These operators can all arbitrarily be extended or truncated.
466 if (!CanEvaluateSExtd(I->getOperand(0), Ty, NumCastsRemoved, TD))
467 return 0;
468 if (!CanEvaluateSExtd(I->getOperand(1), Ty, NumCastsRemoved, TD))
469 return 0;
470 return 1; // IMPROVE?
471
472 //case Instruction::Shl: TODO
473 //case Instruction::LShr: TODO
474 //case Instruction::Trunc: TODO
475
476 case Instruction::SExt:
477 case Instruction::ZExt: {
478 // sext(sext(x)) -> sext(x)
479 // sext(zext(x)) -> zext(x)
480 // Note that replacing a cast does not reduce the number of casts in the
481 // input.
482 unsigned InSignBits = ComputeNumSignBits(I, TD);
483 unsigned ExtBits = Ty->getScalarSizeInBits()-OrigTy->getScalarSizeInBits();
484 // We'll end up extending it all the way out.
485 return InSignBits+ExtBits;
486 }
487 case Instruction::Select: {
488 SelectInst *SI = cast<SelectInst>(I);
489 Tmp1 = CanEvaluateSExtd(SI->getTrueValue(), Ty, NumCastsRemoved, TD);
490 if (Tmp1 == 0) return 0;
491 Tmp2 = CanEvaluateSExtd(SI->getFalseValue(), Ty, NumCastsRemoved,TD);
492 return std::min(Tmp1, Tmp2);
493 }
494 case Instruction::PHI: {
495 // We can change a phi if we can change all operands. Note that we never
496 // get into trouble with cyclic PHIs here because we only consider
497 // instructions with a single use.
498 PHINode *PN = cast<PHINode>(I);
499 unsigned Result = ~0U;
500 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
501 Result = std::min(Result,
502 CanEvaluateSExtd(PN->getIncomingValue(i), Ty,
503 NumCastsRemoved, TD));
504 if (Result == 0) return 0;
505 }
506 return Result;
507 }
508 default:
509 // TODO: Can handle more cases here.
510 break;
511 }
512
513 return 0;
514}
515
516
Chris Lattner5f0290e2010-01-04 07:54:59 +0000517/// EvaluateInDifferentType - Given an expression that
Chris Lattnere0e4cc72010-01-06 01:56:21 +0000518/// CanEvaluateInDifferentType or CanEvaluateSExtd returns true for, actually
519/// insert the code to evaluate the expression.
Chris Lattner5f0290e2010-01-04 07:54:59 +0000520Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
521 bool isSigned) {
522 if (Constant *C = dyn_cast<Constant>(V))
523 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
524
525 // Otherwise, it must be an instruction.
526 Instruction *I = cast<Instruction>(V);
527 Instruction *Res = 0;
528 unsigned Opc = I->getOpcode();
529 switch (Opc) {
530 case Instruction::Add:
531 case Instruction::Sub:
532 case Instruction::Mul:
533 case Instruction::And:
534 case Instruction::Or:
535 case Instruction::Xor:
536 case Instruction::AShr:
537 case Instruction::LShr:
538 case Instruction::Shl:
539 case Instruction::UDiv:
540 case Instruction::URem: {
541 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
542 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
543 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
544 break;
545 }
546 case Instruction::Trunc:
547 case Instruction::ZExt:
548 case Instruction::SExt:
549 // If the source type of the cast is the type we're trying for then we can
550 // just return the source. There's no need to insert it because it is not
551 // new.
552 if (I->getOperand(0)->getType() == Ty)
553 return I->getOperand(0);
554
555 // Otherwise, must be the same type of cast, so just reinsert a new one.
556 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),Ty);
557 break;
558 case Instruction::Select: {
559 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
560 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
561 Res = SelectInst::Create(I->getOperand(0), True, False);
562 break;
563 }
564 case Instruction::PHI: {
565 PHINode *OPN = cast<PHINode>(I);
566 PHINode *NPN = PHINode::Create(Ty);
567 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
568 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
569 NPN->addIncoming(V, OPN->getIncomingBlock(i));
570 }
571 Res = NPN;
572 break;
573 }
574 default:
575 // TODO: Can handle more cases here.
576 llvm_unreachable("Unreachable!");
577 break;
578 }
579
580 Res->takeName(I);
581 return InsertNewInstBefore(Res, *I);
582}
Chris Lattner80f43d32010-01-04 07:53:58 +0000583
584
585/// This function is a wrapper around CastInst::isEliminableCastPair. It
586/// simply extracts arguments and returns what that function returns.
587static Instruction::CastOps
588isEliminableCastPair(
589 const CastInst *CI, ///< The first cast instruction
590 unsigned opcode, ///< The opcode of the second cast instruction
591 const Type *DstTy, ///< The target type for the second cast instruction
592 TargetData *TD ///< The target data for pointer size
593) {
594
595 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
596 const Type *MidTy = CI->getType(); // B from above
597
598 // Get the opcodes of the two Cast instructions
599 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
600 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
601
602 unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
603 DstTy,
604 TD ? TD->getIntPtrType(CI->getContext()) : 0);
605
606 // We don't want to form an inttoptr or ptrtoint that converts to an integer
607 // type that differs from the pointer size.
608 if ((Res == Instruction::IntToPtr &&
609 (!TD || SrcTy != TD->getIntPtrType(CI->getContext()))) ||
610 (Res == Instruction::PtrToInt &&
611 (!TD || DstTy != TD->getIntPtrType(CI->getContext()))))
612 Res = 0;
613
614 return Instruction::CastOps(Res);
615}
616
617/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
618/// in any code being generated. It does not require codegen if V is simple
619/// enough or if the cast can be folded into other casts.
620bool InstCombiner::ValueRequiresCast(Instruction::CastOps opcode,const Value *V,
621 const Type *Ty) {
622 if (V->getType() == Ty || isa<Constant>(V)) return false;
623
624 // If this is another cast that can be eliminated, it isn't codegen either.
625 if (const CastInst *CI = dyn_cast<CastInst>(V))
626 if (isEliminableCastPair(CI, opcode, Ty, TD))
627 return false;
628 return true;
629}
630
631
632/// @brief Implement the transforms common to all CastInst visitors.
633Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
634 Value *Src = CI.getOperand(0);
635
636 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
637 // eliminate it now.
638 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
639 if (Instruction::CastOps opc =
640 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
641 // The first cast (CSrc) is eliminable so we need to fix up or replace
642 // the second cast (CI). CSrc will then have a good chance of being dead.
643 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
644 }
645 }
646
647 // If we are casting a select then fold the cast into the select
648 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
649 if (Instruction *NV = FoldOpIntoSelect(CI, SI))
650 return NV;
651
652 // If we are casting a PHI then fold the cast into the PHI
653 if (isa<PHINode>(Src)) {
654 // We don't do this if this would create a PHI node with an illegal type if
655 // it is currently legal.
656 if (!isa<IntegerType>(Src->getType()) ||
657 !isa<IntegerType>(CI.getType()) ||
658 ShouldChangeType(CI.getType(), Src->getType()))
659 if (Instruction *NV = FoldOpIntoPhi(CI))
660 return NV;
661 }
662
663 return 0;
664}
665
Chris Lattner80f43d32010-01-04 07:53:58 +0000666/// commonIntCastTransforms - This function implements the common transforms
667/// for trunc, zext, and sext.
668Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
669 if (Instruction *Result = commonCastTransforms(CI))
670 return Result;
671
Chris Lattner80f43d32010-01-04 07:53:58 +0000672 // See if we can simplify any instructions used by the LHS whose sole
673 // purpose is to compute bits we don't care about.
674 if (SimplifyDemandedInstructionBits(CI))
675 return &CI;
Chris Lattner274ad682010-01-05 22:07:33 +0000676
Chris Lattner80f43d32010-01-04 07:53:58 +0000677 // If the source isn't an instruction or has more than one use then we
678 // can't do anything more.
Chris Lattner274ad682010-01-05 22:07:33 +0000679 Instruction *Src = dyn_cast<Instruction>(CI.getOperand(0));
680 if (!Src || !Src->hasOneUse())
Chris Lattner80f43d32010-01-04 07:53:58 +0000681 return 0;
Chris Lattner68c6e892010-01-05 23:00:30 +0000682
683 // Check to see if we can eliminate the cast by changing the entire
684 // computation chain to do the computation in the result type.
Chris Lattner274ad682010-01-05 22:07:33 +0000685 const Type *SrcTy = Src->getType();
686 const Type *DestTy = CI.getType();
Chris Lattner68c6e892010-01-05 23:00:30 +0000687
Chris Lattner80f43d32010-01-04 07:53:58 +0000688 // Only do this if the dest type is a simple type, don't convert the
689 // expression tree to something weird like i93 unless the source is also
690 // strange.
Chris Lattner68c6e892010-01-05 23:00:30 +0000691 if (!isa<VectorType>(DestTy) && !ShouldChangeType(SrcTy, DestTy))
692 return 0;
693
Chris Lattner075f6922010-01-07 23:41:00 +0000694 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
695 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
696
Chris Lattner68c6e892010-01-05 23:00:30 +0000697 // Attempt to propagate the cast into the instruction for int->int casts.
Chris Lattnere0e4cc72010-01-06 01:56:21 +0000698 unsigned NumCastsRemoved = 0;
Chris Lattner68c6e892010-01-05 23:00:30 +0000699 switch (CI.getOpcode()) {
700 default: assert(0 && "not an integer cast");
Chris Lattner075f6922010-01-07 23:41:00 +0000701 case Instruction::Trunc: {
Chris Lattnere0e4cc72010-01-06 01:56:21 +0000702 if (!CanEvaluateInDifferentType(Src, DestTy,
703 Instruction::Trunc, NumCastsRemoved))
704 return 0;
705
Chris Lattner80f43d32010-01-04 07:53:58 +0000706 // If this cast is a truncate, evaluting in a different type always
Chris Lattner68c6e892010-01-05 23:00:30 +0000707 // eliminates the cast, so it is always a win.
Chris Lattner075f6922010-01-07 23:41:00 +0000708 DEBUG(dbgs() << "ICE: EvaluateInDifferentType converting expression type"
709 " to avoid cast: " << CI);
710 Value *Res = EvaluateInDifferentType(Src, DestTy, false);
711 assert(Res->getType() == DestTy);
712 return ReplaceInstUsesWith(CI, Res);
713 }
714 case Instruction::ZExt: {
715 int BitsZExt = CanEvaluateZExtd(Src, DestTy, NumCastsRemoved, TD);
716 if (BitsZExt == -1) return 0;
717
Chris Lattner68c6e892010-01-05 23:00:30 +0000718 // If this is a zero-extension, we need to do an AND to maintain the clear
Chris Lattner075f6922010-01-07 23:41:00 +0000719 // top-part of the computation. If we know the result will be zero
720 // extended enough already, we don't need the and.
721 if (NumCastsRemoved < 1 &&
722 unsigned(BitsZExt) < DestBitSize-SrcBitSize)
Chris Lattner68c6e892010-01-05 23:00:30 +0000723 return 0;
Chris Lattner075f6922010-01-07 23:41:00 +0000724
725 // Okay, we can transform this! Insert the new expression now.
726 DEBUG(dbgs() << "ICE: EvaluateInDifferentType converting expression type"
727 " to avoid zero extend: " << CI);
728 Value *Res = EvaluateInDifferentType(Src, DestTy, false);
729 assert(Res->getType() == DestTy);
730
731 // If the high bits are already filled with zeros, just replace this
732 // cast with the result.
733 if (unsigned(BitsZExt) >= DestBitSize-SrcBitSize ||
734 MaskedValueIsZero(Res, APInt::getHighBitsSet(DestBitSize,
735 DestBitSize-SrcBitSize)))
736 return ReplaceInstUsesWith(CI, Res);
737
738 // We need to emit an AND to clear the high bits.
739 Constant *C = ConstantInt::get(CI.getContext(),
740 APInt::getLowBitsSet(DestBitSize, SrcBitSize));
741 return BinaryOperator::CreateAnd(Res, C);
742 }
Chris Lattnere0e4cc72010-01-06 01:56:21 +0000743 case Instruction::SExt: {
744 // Check to see if we can do this transformation, and if so, how many bits
745 // of the promoted expression will be known copies of the sign bit in the
746 // result.
747 unsigned NumBitsSExt = CanEvaluateSExtd(Src, DestTy, NumCastsRemoved, TD);
748 if (NumBitsSExt == 0)
Chris Lattner68c6e892010-01-05 23:00:30 +0000749 return 0;
Chris Lattnere0e4cc72010-01-06 01:56:21 +0000750
Chris Lattnere0e4cc72010-01-06 01:56:21 +0000751 // Because this is a sign extension, we can always transform it by inserting
752 // two new shifts (to do the extension). However, this is only profitable
753 // if we've eliminated two or more casts from the input. If we know the
Chris Lattner5c24a6d2010-01-06 05:32:15 +0000754 // result will be sign-extended enough to not require these shifts, we can
Chris Lattnere0e4cc72010-01-06 01:56:21 +0000755 // always do the transformation.
756 if (NumCastsRemoved < 2 &&
757 NumBitsSExt <= DestBitSize-SrcBitSize)
758 return 0;
759
760 // Okay, we can transform this! Insert the new expression now.
Chris Lattner5c24a6d2010-01-06 05:32:15 +0000761 DEBUG(dbgs() << "ICE: EvaluateInDifferentType converting expression type"
Chris Lattnere0e4cc72010-01-06 01:56:21 +0000762 " to avoid sign extend: " << CI);
763 Value *Res = EvaluateInDifferentType(Src, DestTy, true);
764 assert(Res->getType() == DestTy);
765
766 // If the high bits are already filled with sign bit, just replace this
767 // cast with the result.
768 if (NumBitsSExt > DestBitSize - SrcBitSize ||
769 ComputeNumSignBits(Res) > DestBitSize - SrcBitSize)
770 return ReplaceInstUsesWith(CI, Res);
771
772 // We need to emit a cast to truncate, then a cast to sext.
773 return new SExtInst(Builder->CreateTrunc(Res, Src->getType()), DestTy);
774 }
Chris Lattner80f43d32010-01-04 07:53:58 +0000775 }
Chris Lattner80f43d32010-01-04 07:53:58 +0000776}
777
Chris Lattner80f43d32010-01-04 07:53:58 +0000778Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
779 if (Instruction *Result = commonIntCastTransforms(CI))
780 return Result;
781
782 Value *Src = CI.getOperand(0);
Chris Lattner49bdfef2010-01-05 21:11:17 +0000783 const Type *DestTy = CI.getType();
Chris Lattner80f43d32010-01-04 07:53:58 +0000784
Chris Lattner7a34d6c2010-01-05 22:21:18 +0000785 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0), likewise for vector.
786 if (DestTy->getScalarSizeInBits() == 1) {
Chris Lattner80f43d32010-01-04 07:53:58 +0000787 Constant *One = ConstantInt::get(Src->getType(), 1);
788 Src = Builder->CreateAnd(Src, One, "tmp");
789 Value *Zero = Constant::getNullValue(Src->getType());
790 return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
791 }
792
Chris Lattner80f43d32010-01-04 07:53:58 +0000793 return 0;
794}
795
796/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
797/// in order to eliminate the icmp.
798Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
799 bool DoXform) {
800 // If we are just checking for a icmp eq of a single bit and zext'ing it
801 // to an integer, then shift the bit to the appropriate place and then
802 // cast to integer to avoid the comparison.
803 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
804 const APInt &Op1CV = Op1C->getValue();
805
806 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
807 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
808 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
809 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
810 if (!DoXform) return ICI;
811
812 Value *In = ICI->getOperand(0);
813 Value *Sh = ConstantInt::get(In->getType(),
814 In->getType()->getScalarSizeInBits()-1);
815 In = Builder->CreateLShr(In, Sh, In->getName()+".lobit");
816 if (In->getType() != CI.getType())
817 In = Builder->CreateIntCast(In, CI.getType(), false/*ZExt*/, "tmp");
818
819 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
820 Constant *One = ConstantInt::get(In->getType(), 1);
821 In = Builder->CreateXor(In, One, In->getName()+".not");
822 }
823
824 return ReplaceInstUsesWith(CI, In);
825 }
826
827
828
829 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
830 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
831 // zext (X == 1) to i32 --> X iff X has only the low bit set.
832 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
833 // zext (X != 0) to i32 --> X iff X has only the low bit set.
834 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
835 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
836 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
837 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
838 // This only works for EQ and NE
839 ICI->isEquality()) {
840 // If Op1C some other power of two, convert:
841 uint32_t BitWidth = Op1C->getType()->getBitWidth();
842 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
843 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
844 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
845
846 APInt KnownZeroMask(~KnownZero);
847 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
848 if (!DoXform) return ICI;
849
850 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
851 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
852 // (X&4) == 2 --> false
853 // (X&4) != 2 --> true
854 Constant *Res = ConstantInt::get(Type::getInt1Ty(CI.getContext()),
855 isNE);
856 Res = ConstantExpr::getZExt(Res, CI.getType());
857 return ReplaceInstUsesWith(CI, Res);
858 }
859
860 uint32_t ShiftAmt = KnownZeroMask.logBase2();
861 Value *In = ICI->getOperand(0);
862 if (ShiftAmt) {
863 // Perform a logical shr by shiftamt.
864 // Insert the shift to put the result in the low bit.
865 In = Builder->CreateLShr(In, ConstantInt::get(In->getType(),ShiftAmt),
866 In->getName()+".lobit");
867 }
868
869 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
870 Constant *One = ConstantInt::get(In->getType(), 1);
871 In = Builder->CreateXor(In, One, "tmp");
872 }
873
874 if (CI.getType() == In->getType())
875 return ReplaceInstUsesWith(CI, In);
876 else
877 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
878 }
879 }
880 }
881
882 // icmp ne A, B is equal to xor A, B when A and B only really have one bit.
883 // It is also profitable to transform icmp eq into not(xor(A, B)) because that
884 // may lead to additional simplifications.
885 if (ICI->isEquality() && CI.getType() == ICI->getOperand(0)->getType()) {
886 if (const IntegerType *ITy = dyn_cast<IntegerType>(CI.getType())) {
887 uint32_t BitWidth = ITy->getBitWidth();
888 Value *LHS = ICI->getOperand(0);
889 Value *RHS = ICI->getOperand(1);
890
891 APInt KnownZeroLHS(BitWidth, 0), KnownOneLHS(BitWidth, 0);
892 APInt KnownZeroRHS(BitWidth, 0), KnownOneRHS(BitWidth, 0);
893 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
894 ComputeMaskedBits(LHS, TypeMask, KnownZeroLHS, KnownOneLHS);
895 ComputeMaskedBits(RHS, TypeMask, KnownZeroRHS, KnownOneRHS);
896
897 if (KnownZeroLHS == KnownZeroRHS && KnownOneLHS == KnownOneRHS) {
898 APInt KnownBits = KnownZeroLHS | KnownOneLHS;
899 APInt UnknownBit = ~KnownBits;
900 if (UnknownBit.countPopulation() == 1) {
901 if (!DoXform) return ICI;
902
903 Value *Result = Builder->CreateXor(LHS, RHS);
904
905 // Mask off any bits that are set and won't be shifted away.
906 if (KnownOneLHS.uge(UnknownBit))
907 Result = Builder->CreateAnd(Result,
908 ConstantInt::get(ITy, UnknownBit));
909
910 // Shift the bit we're testing down to the lsb.
911 Result = Builder->CreateLShr(
912 Result, ConstantInt::get(ITy, UnknownBit.countTrailingZeros()));
913
914 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
915 Result = Builder->CreateXor(Result, ConstantInt::get(ITy, 1));
916 Result->takeName(ICI);
917 return ReplaceInstUsesWith(CI, Result);
918 }
919 }
920 }
921 }
922
923 return 0;
924}
925
926Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
927 // If one of the common conversion will work, do it.
928 if (Instruction *Result = commonIntCastTransforms(CI))
929 return Result;
930
931 Value *Src = CI.getOperand(0);
932
933 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
934 // types and if the sizes are just right we can convert this into a logical
935 // 'and' which will be much cheaper than the pair of casts.
936 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
937 // Get the sizes of the types involved. We know that the intermediate type
938 // will be smaller than A or C, but don't know the relation between A and C.
939 Value *A = CSrc->getOperand(0);
940 unsigned SrcSize = A->getType()->getScalarSizeInBits();
941 unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
942 unsigned DstSize = CI.getType()->getScalarSizeInBits();
943 // If we're actually extending zero bits, then if
944 // SrcSize < DstSize: zext(a & mask)
945 // SrcSize == DstSize: a & mask
946 // SrcSize > DstSize: trunc(a) & mask
947 if (SrcSize < DstSize) {
948 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
949 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
950 Value *And = Builder->CreateAnd(A, AndConst, CSrc->getName()+".mask");
951 return new ZExtInst(And, CI.getType());
952 }
953
954 if (SrcSize == DstSize) {
955 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
956 return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
957 AndValue));
958 }
959 if (SrcSize > DstSize) {
960 Value *Trunc = Builder->CreateTrunc(A, CI.getType(), "tmp");
961 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
962 return BinaryOperator::CreateAnd(Trunc,
963 ConstantInt::get(Trunc->getType(),
964 AndValue));
965 }
966 }
967
968 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
969 return transformZExtICmp(ICI, CI);
970
971 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
972 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
973 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
974 // of the (zext icmp) will be transformed.
975 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
976 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
977 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
978 (transformZExtICmp(LHS, CI, false) ||
979 transformZExtICmp(RHS, CI, false))) {
980 Value *LCast = Builder->CreateZExt(LHS, CI.getType(), LHS->getName());
981 Value *RCast = Builder->CreateZExt(RHS, CI.getType(), RHS->getName());
982 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
983 }
984 }
985
986 // zext(trunc(t) & C) -> (t & zext(C)).
987 if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
988 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
989 if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
990 Value *TI0 = TI->getOperand(0);
991 if (TI0->getType() == CI.getType())
992 return
993 BinaryOperator::CreateAnd(TI0,
994 ConstantExpr::getZExt(C, CI.getType()));
995 }
996
997 // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
998 if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
999 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
1000 if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
1001 if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
1002 And->getOperand(1) == C)
1003 if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
1004 Value *TI0 = TI->getOperand(0);
1005 if (TI0->getType() == CI.getType()) {
1006 Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
1007 Value *NewAnd = Builder->CreateAnd(TI0, ZC, "tmp");
1008 return BinaryOperator::CreateXor(NewAnd, ZC);
1009 }
1010 }
1011
Chris Lattner718bf3f2010-01-05 21:04:47 +00001012 // zext (xor i1 X, true) to i32 --> xor (zext i1 X to i32), 1
1013 Value *X;
Chris Lattner49bdfef2010-01-05 21:11:17 +00001014 if (SrcI && SrcI->hasOneUse() && SrcI->getType()->isInteger(1) &&
1015 match(SrcI, m_Not(m_Value(X))) &&
Chris Lattner718bf3f2010-01-05 21:04:47 +00001016 (!X->hasOneUse() || !isa<CmpInst>(X))) {
1017 Value *New = Builder->CreateZExt(X, CI.getType());
1018 return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
1019 }
1020
Chris Lattner80f43d32010-01-04 07:53:58 +00001021 return 0;
1022}
1023
1024Instruction *InstCombiner::visitSExt(SExtInst &CI) {
1025 if (Instruction *I = commonIntCastTransforms(CI))
1026 return I;
1027
1028 Value *Src = CI.getOperand(0);
1029
1030 // Canonicalize sign-extend from i1 to a select.
Benjamin Kramer11acaa32010-01-05 20:07:06 +00001031 if (Src->getType()->isInteger(1))
Chris Lattner80f43d32010-01-04 07:53:58 +00001032 return SelectInst::Create(Src,
1033 Constant::getAllOnesValue(CI.getType()),
1034 Constant::getNullValue(CI.getType()));
1035
1036 // See if the value being truncated is already sign extended. If so, just
1037 // eliminate the trunc/sext pair.
1038 if (Operator::getOpcode(Src) == Instruction::Trunc) {
1039 Value *Op = cast<User>(Src)->getOperand(0);
1040 unsigned OpBits = Op->getType()->getScalarSizeInBits();
1041 unsigned MidBits = Src->getType()->getScalarSizeInBits();
1042 unsigned DestBits = CI.getType()->getScalarSizeInBits();
1043 unsigned NumSignBits = ComputeNumSignBits(Op);
1044
1045 if (OpBits == DestBits) {
1046 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
1047 // bits, it is already ready.
1048 if (NumSignBits > DestBits-MidBits)
1049 return ReplaceInstUsesWith(CI, Op);
1050 } else if (OpBits < DestBits) {
1051 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
1052 // bits, just sext from i32.
1053 if (NumSignBits > OpBits-MidBits)
1054 return new SExtInst(Op, CI.getType(), "tmp");
1055 } else {
1056 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
1057 // bits, just truncate to i32.
1058 if (NumSignBits > OpBits-MidBits)
1059 return new TruncInst(Op, CI.getType(), "tmp");
1060 }
1061 }
1062
1063 // If the input is a shl/ashr pair of a same constant, then this is a sign
1064 // extension from a smaller value. If we could trust arbitrary bitwidth
1065 // integers, we could turn this into a truncate to the smaller bit and then
1066 // use a sext for the whole extension. Since we don't, look deeper and check
1067 // for a truncate. If the source and dest are the same type, eliminate the
1068 // trunc and extend and just do shifts. For example, turn:
1069 // %a = trunc i32 %i to i8
1070 // %b = shl i8 %a, 6
1071 // %c = ashr i8 %b, 6
1072 // %d = sext i8 %c to i32
1073 // into:
1074 // %a = shl i32 %i, 30
1075 // %d = ashr i32 %a, 30
1076 Value *A = 0;
1077 ConstantInt *BA = 0, *CA = 0;
1078 if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
1079 m_ConstantInt(CA))) &&
1080 BA == CA && isa<TruncInst>(A)) {
1081 Value *I = cast<TruncInst>(A)->getOperand(0);
1082 if (I->getType() == CI.getType()) {
1083 unsigned MidSize = Src->getType()->getScalarSizeInBits();
1084 unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
1085 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
1086 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
1087 I = Builder->CreateShl(I, ShAmtV, CI.getName());
1088 return BinaryOperator::CreateAShr(I, ShAmtV);
1089 }
1090 }
1091
1092 return 0;
1093}
1094
1095
1096/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
1097/// in the specified FP type without changing its value.
1098static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
1099 bool losesInfo;
1100 APFloat F = CFP->getValueAPF();
1101 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
1102 if (!losesInfo)
1103 return ConstantFP::get(CFP->getContext(), F);
1104 return 0;
1105}
1106
1107/// LookThroughFPExtensions - If this is an fp extension instruction, look
1108/// through it until we get the source value.
1109static Value *LookThroughFPExtensions(Value *V) {
1110 if (Instruction *I = dyn_cast<Instruction>(V))
1111 if (I->getOpcode() == Instruction::FPExt)
1112 return LookThroughFPExtensions(I->getOperand(0));
1113
1114 // If this value is a constant, return the constant in the smallest FP type
1115 // that can accurately represent it. This allows us to turn
1116 // (float)((double)X+2.0) into x+2.0f.
1117 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
1118 if (CFP->getType() == Type::getPPC_FP128Ty(V->getContext()))
1119 return V; // No constant folding of this.
1120 // See if the value can be truncated to float and then reextended.
1121 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
1122 return V;
Benjamin Kramerf0127052010-01-05 13:12:22 +00001123 if (CFP->getType()->isDoubleTy())
Chris Lattner80f43d32010-01-04 07:53:58 +00001124 return V; // Won't shrink.
1125 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
1126 return V;
1127 // Don't try to shrink to various long double types.
1128 }
1129
1130 return V;
1131}
1132
1133Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
1134 if (Instruction *I = commonCastTransforms(CI))
1135 return I;
1136
1137 // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
1138 // smaller than the destination type, we can eliminate the truncate by doing
1139 // the add as the smaller type. This applies to fadd/fsub/fmul/fdiv as well
1140 // as many builtins (sqrt, etc).
1141 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
1142 if (OpI && OpI->hasOneUse()) {
1143 switch (OpI->getOpcode()) {
1144 default: break;
1145 case Instruction::FAdd:
1146 case Instruction::FSub:
1147 case Instruction::FMul:
1148 case Instruction::FDiv:
1149 case Instruction::FRem:
1150 const Type *SrcTy = OpI->getType();
1151 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
1152 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
1153 if (LHSTrunc->getType() != SrcTy &&
1154 RHSTrunc->getType() != SrcTy) {
1155 unsigned DstSize = CI.getType()->getScalarSizeInBits();
1156 // If the source types were both smaller than the destination type of
1157 // the cast, do this xform.
1158 if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
1159 RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
1160 LHSTrunc = Builder->CreateFPExt(LHSTrunc, CI.getType());
1161 RHSTrunc = Builder->CreateFPExt(RHSTrunc, CI.getType());
1162 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
1163 }
1164 }
1165 break;
1166 }
1167 }
1168 return 0;
1169}
1170
1171Instruction *InstCombiner::visitFPExt(CastInst &CI) {
1172 return commonCastTransforms(CI);
1173}
1174
1175Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
1176 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
1177 if (OpI == 0)
1178 return commonCastTransforms(FI);
1179
1180 // fptoui(uitofp(X)) --> X
1181 // fptoui(sitofp(X)) --> X
1182 // This is safe if the intermediate type has enough bits in its mantissa to
1183 // accurately represent all values of X. For example, do not do this with
1184 // i64->float->i64. This is also safe for sitofp case, because any negative
1185 // 'X' value would cause an undefined result for the fptoui.
1186 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
1187 OpI->getOperand(0)->getType() == FI.getType() &&
1188 (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
1189 OpI->getType()->getFPMantissaWidth())
1190 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
1191
1192 return commonCastTransforms(FI);
1193}
1194
1195Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
1196 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
1197 if (OpI == 0)
1198 return commonCastTransforms(FI);
1199
1200 // fptosi(sitofp(X)) --> X
1201 // fptosi(uitofp(X)) --> X
1202 // This is safe if the intermediate type has enough bits in its mantissa to
1203 // accurately represent all values of X. For example, do not do this with
1204 // i64->float->i64. This is also safe for sitofp case, because any negative
1205 // 'X' value would cause an undefined result for the fptoui.
1206 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
1207 OpI->getOperand(0)->getType() == FI.getType() &&
1208 (int)FI.getType()->getScalarSizeInBits() <=
1209 OpI->getType()->getFPMantissaWidth())
1210 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
1211
1212 return commonCastTransforms(FI);
1213}
1214
1215Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
1216 return commonCastTransforms(CI);
1217}
1218
1219Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
1220 return commonCastTransforms(CI);
1221}
1222
Chris Lattner80f43d32010-01-04 07:53:58 +00001223Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
1224 // If the source integer type is larger than the intptr_t type for
1225 // this target, do a trunc to the intptr_t type, then inttoptr of it. This
1226 // allows the trunc to be exposed to other transforms. Don't do this for
1227 // extending inttoptr's, because we don't know if the target sign or zero
1228 // extends to pointers.
1229 if (TD && CI.getOperand(0)->getType()->getScalarSizeInBits() >
1230 TD->getPointerSizeInBits()) {
1231 Value *P = Builder->CreateTrunc(CI.getOperand(0),
1232 TD->getIntPtrType(CI.getContext()), "tmp");
1233 return new IntToPtrInst(P, CI.getType());
1234 }
1235
1236 if (Instruction *I = commonCastTransforms(CI))
1237 return I;
1238
1239 return 0;
1240}
1241
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001242/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
1243Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
1244 Value *Src = CI.getOperand(0);
1245
1246 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
1247 // If casting the result of a getelementptr instruction with no offset, turn
1248 // this into a cast of the original pointer!
1249 if (GEP->hasAllZeroIndices()) {
1250 // Changing the cast operand is usually not a good idea but it is safe
1251 // here because the pointer operand is being replaced with another
1252 // pointer operand so the opcode doesn't need to change.
1253 Worklist.Add(GEP);
1254 CI.setOperand(0, GEP->getOperand(0));
1255 return &CI;
1256 }
1257
1258 // If the GEP has a single use, and the base pointer is a bitcast, and the
1259 // GEP computes a constant offset, see if we can convert these three
1260 // instructions into fewer. This typically happens with unions and other
1261 // non-type-safe code.
1262 if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0)) &&
1263 GEP->hasAllConstantIndices()) {
1264 // We are guaranteed to get a constant from EmitGEPOffset.
1265 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP));
1266 int64_t Offset = OffsetV->getSExtValue();
1267
1268 // Get the base pointer input of the bitcast, and the type it points to.
1269 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
1270 const Type *GEPIdxTy =
1271 cast<PointerType>(OrigBase->getType())->getElementType();
1272 SmallVector<Value*, 8> NewIndices;
1273 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices)) {
1274 // If we were able to index down into an element, create the GEP
1275 // and bitcast the result. This eliminates one bitcast, potentially
1276 // two.
1277 Value *NGEP = cast<GEPOperator>(GEP)->isInBounds() ?
1278 Builder->CreateInBoundsGEP(OrigBase,
1279 NewIndices.begin(), NewIndices.end()) :
1280 Builder->CreateGEP(OrigBase, NewIndices.begin(), NewIndices.end());
1281 NGEP->takeName(GEP);
1282
1283 if (isa<BitCastInst>(CI))
1284 return new BitCastInst(NGEP, CI.getType());
1285 assert(isa<PtrToIntInst>(CI));
1286 return new PtrToIntInst(NGEP, CI.getType());
1287 }
1288 }
1289 }
1290
1291 return commonCastTransforms(CI);
1292}
1293
1294Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
1295 // If the destination integer type is smaller than the intptr_t type for
1296 // this target, do a ptrtoint to intptr_t then do a trunc. This allows the
1297 // trunc to be exposed to other transforms. Don't do this for extending
1298 // ptrtoint's, because we don't know if the target sign or zero extends its
1299 // pointers.
1300 if (TD &&
1301 CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
1302 Value *P = Builder->CreatePtrToInt(CI.getOperand(0),
1303 TD->getIntPtrType(CI.getContext()),
1304 "tmp");
1305 return new TruncInst(P, CI.getType());
1306 }
1307
1308 return commonPointerCastTransforms(CI);
1309}
1310
Chris Lattner80f43d32010-01-04 07:53:58 +00001311Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
1312 // If the operands are integer typed then apply the integer transforms,
1313 // otherwise just apply the common ones.
1314 Value *Src = CI.getOperand(0);
1315 const Type *SrcTy = Src->getType();
1316 const Type *DestTy = CI.getType();
1317
Chris Lattner80f43d32010-01-04 07:53:58 +00001318 // Get rid of casts from one type to the same type. These are useless and can
1319 // be replaced by the operand.
1320 if (DestTy == Src->getType())
1321 return ReplaceInstUsesWith(CI, Src);
1322
1323 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
1324 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
1325 const Type *DstElTy = DstPTy->getElementType();
1326 const Type *SrcElTy = SrcPTy->getElementType();
1327
1328 // If the address spaces don't match, don't eliminate the bitcast, which is
1329 // required for changing types.
1330 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
1331 return 0;
1332
1333 // If we are casting a alloca to a pointer to a type of the same
1334 // size, rewrite the allocation instruction to allocate the "right" type.
1335 // There is no need to modify malloc calls because it is their bitcast that
1336 // needs to be cleaned up.
1337 if (AllocaInst *AI = dyn_cast<AllocaInst>(Src))
1338 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
1339 return V;
1340
1341 // If the source and destination are pointers, and this cast is equivalent
1342 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
1343 // This can enhance SROA and other transforms that want type-safe pointers.
1344 Constant *ZeroUInt =
1345 Constant::getNullValue(Type::getInt32Ty(CI.getContext()));
1346 unsigned NumZeros = 0;
1347 while (SrcElTy != DstElTy &&
1348 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
1349 SrcElTy->getNumContainedTypes() /* not "{}" */) {
1350 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
1351 ++NumZeros;
1352 }
1353
1354 // If we found a path from the src to dest, create the getelementptr now.
1355 if (SrcElTy == DstElTy) {
1356 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
1357 return GetElementPtrInst::CreateInBounds(Src, Idxs.begin(), Idxs.end(),"",
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001358 ((Instruction*)NULL));
Chris Lattner80f43d32010-01-04 07:53:58 +00001359 }
1360 }
1361
1362 if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001363 if (DestVTy->getNumElements() == 1 && !isa<VectorType>(SrcTy)) {
1364 Value *Elem = Builder->CreateBitCast(Src, DestVTy->getElementType());
1365 return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
Chris Lattner80f43d32010-01-04 07:53:58 +00001366 Constant::getNullValue(Type::getInt32Ty(CI.getContext())));
Chris Lattner80f43d32010-01-04 07:53:58 +00001367 // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
1368 }
1369 }
1370
1371 if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001372 if (SrcVTy->getNumElements() == 1 && !isa<VectorType>(DestTy)) {
1373 Value *Elem =
1374 Builder->CreateExtractElement(Src,
1375 Constant::getNullValue(Type::getInt32Ty(CI.getContext())));
1376 return CastInst::Create(Instruction::BitCast, Elem, DestTy);
Chris Lattner80f43d32010-01-04 07:53:58 +00001377 }
1378 }
1379
1380 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001381 // Okay, we have (bitcast (shuffle ..)). Check to see if this is
1382 // a bitconvert to a vector with the same # elts.
1383 if (SVI->hasOneUse() && isa<VectorType>(DestTy) &&
1384 cast<VectorType>(DestTy)->getNumElements() ==
1385 SVI->getType()->getNumElements() &&
1386 SVI->getType()->getNumElements() ==
1387 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
1388 BitCastInst *Tmp;
1389 // If either of the operands is a cast from CI.getType(), then
1390 // evaluating the shuffle in the casted destination's type will allow
1391 // us to eliminate at least one cast.
1392 if (((Tmp = dyn_cast<BitCastInst>(SVI->getOperand(0))) &&
1393 Tmp->getOperand(0)->getType() == DestTy) ||
1394 ((Tmp = dyn_cast<BitCastInst>(SVI->getOperand(1))) &&
1395 Tmp->getOperand(0)->getType() == DestTy)) {
1396 Value *LHS = Builder->CreateBitCast(SVI->getOperand(0), DestTy);
1397 Value *RHS = Builder->CreateBitCast(SVI->getOperand(1), DestTy);
1398 // Return a new shuffle vector. Use the same element ID's, as we
1399 // know the vector types match #elts.
1400 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner80f43d32010-01-04 07:53:58 +00001401 }
1402 }
1403 }
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001404
1405 if (isa<PointerType>(SrcTy))
1406 return commonPointerCastTransforms(CI);
1407 return commonCastTransforms(CI);
Chris Lattner80f43d32010-01-04 07:53:58 +00001408}