blob: 4bea64d9a6f8f9e948318a94af031aff160087f9 [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 Lattnere0e4cc72010-01-06 01:56:21 +0000150
Chris Lattner5f0290e2010-01-04 07:54:59 +0000151/// EvaluateInDifferentType - Given an expression that
Chris Lattner14bf8f02010-01-08 19:19:23 +0000152/// CanEvaluateTruncated or CanEvaluateSExtd returns true for, actually
Chris Lattnere0e4cc72010-01-06 01:56:21 +0000153/// insert the code to evaluate the expression.
Chris Lattner5f0290e2010-01-04 07:54:59 +0000154Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
155 bool isSigned) {
Chris Lattnerc8b3fce2010-01-08 19:28:47 +0000156 if (Constant *C = dyn_cast<Constant>(V)) {
157 C = ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
158 // If we got a constantexpr back, try to simplify it with TD info.
159 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
160 C = ConstantFoldConstantExpression(CE, TD);
161 return C;
162 }
Chris Lattner5f0290e2010-01-04 07:54:59 +0000163
164 // Otherwise, it must be an instruction.
165 Instruction *I = cast<Instruction>(V);
166 Instruction *Res = 0;
167 unsigned Opc = I->getOpcode();
168 switch (Opc) {
169 case Instruction::Add:
170 case Instruction::Sub:
171 case Instruction::Mul:
172 case Instruction::And:
173 case Instruction::Or:
174 case Instruction::Xor:
175 case Instruction::AShr:
176 case Instruction::LShr:
177 case Instruction::Shl:
178 case Instruction::UDiv:
179 case Instruction::URem: {
180 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
181 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
182 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
183 break;
184 }
185 case Instruction::Trunc:
186 case Instruction::ZExt:
187 case Instruction::SExt:
188 // If the source type of the cast is the type we're trying for then we can
189 // just return the source. There's no need to insert it because it is not
190 // new.
191 if (I->getOperand(0)->getType() == Ty)
192 return I->getOperand(0);
193
194 // Otherwise, must be the same type of cast, so just reinsert a new one.
195 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),Ty);
196 break;
197 case Instruction::Select: {
198 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
199 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
200 Res = SelectInst::Create(I->getOperand(0), True, False);
201 break;
202 }
203 case Instruction::PHI: {
204 PHINode *OPN = cast<PHINode>(I);
205 PHINode *NPN = PHINode::Create(Ty);
206 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
207 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
208 NPN->addIncoming(V, OPN->getIncomingBlock(i));
209 }
210 Res = NPN;
211 break;
212 }
213 default:
214 // TODO: Can handle more cases here.
215 llvm_unreachable("Unreachable!");
216 break;
217 }
218
219 Res->takeName(I);
220 return InsertNewInstBefore(Res, *I);
221}
Chris Lattner80f43d32010-01-04 07:53:58 +0000222
223
224/// This function is a wrapper around CastInst::isEliminableCastPair. It
225/// simply extracts arguments and returns what that function returns.
226static Instruction::CastOps
227isEliminableCastPair(
228 const CastInst *CI, ///< The first cast instruction
229 unsigned opcode, ///< The opcode of the second cast instruction
230 const Type *DstTy, ///< The target type for the second cast instruction
231 TargetData *TD ///< The target data for pointer size
232) {
233
234 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
235 const Type *MidTy = CI->getType(); // B from above
236
237 // Get the opcodes of the two Cast instructions
238 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
239 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
240
241 unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
242 DstTy,
243 TD ? TD->getIntPtrType(CI->getContext()) : 0);
244
245 // We don't want to form an inttoptr or ptrtoint that converts to an integer
246 // type that differs from the pointer size.
247 if ((Res == Instruction::IntToPtr &&
248 (!TD || SrcTy != TD->getIntPtrType(CI->getContext()))) ||
249 (Res == Instruction::PtrToInt &&
250 (!TD || DstTy != TD->getIntPtrType(CI->getContext()))))
251 Res = 0;
252
253 return Instruction::CastOps(Res);
254}
255
256/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
257/// in any code being generated. It does not require codegen if V is simple
258/// enough or if the cast can be folded into other casts.
259bool InstCombiner::ValueRequiresCast(Instruction::CastOps opcode,const Value *V,
260 const Type *Ty) {
261 if (V->getType() == Ty || isa<Constant>(V)) return false;
262
263 // If this is another cast that can be eliminated, it isn't codegen either.
264 if (const CastInst *CI = dyn_cast<CastInst>(V))
265 if (isEliminableCastPair(CI, opcode, Ty, TD))
266 return false;
267 return true;
268}
269
270
271/// @brief Implement the transforms common to all CastInst visitors.
272Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
273 Value *Src = CI.getOperand(0);
274
275 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
276 // eliminate it now.
277 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
278 if (Instruction::CastOps opc =
279 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
280 // The first cast (CSrc) is eliminable so we need to fix up or replace
281 // the second cast (CI). CSrc will then have a good chance of being dead.
282 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
283 }
284 }
285
286 // If we are casting a select then fold the cast into the select
287 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
288 if (Instruction *NV = FoldOpIntoSelect(CI, SI))
289 return NV;
290
291 // If we are casting a PHI then fold the cast into the PHI
292 if (isa<PHINode>(Src)) {
293 // We don't do this if this would create a PHI node with an illegal type if
294 // it is currently legal.
295 if (!isa<IntegerType>(Src->getType()) ||
296 !isa<IntegerType>(CI.getType()) ||
297 ShouldChangeType(CI.getType(), Src->getType()))
298 if (Instruction *NV = FoldOpIntoPhi(CI))
299 return NV;
300 }
301
302 return 0;
303}
304
Chris Lattner75215c92010-01-10 00:58:42 +0000305/// CanEvaluateTruncated - Return true if we can evaluate the specified
306/// expression tree as type Ty instead of its larger type, and arrive with the
307/// same value. This is used by code that tries to eliminate truncates.
308///
309/// Ty will always be a type smaller than V. We should return true if trunc(V)
310/// can be computed by computing V in the smaller type. If V is an instruction,
311/// then trunc(inst(x,y)) can be computed as inst(trunc(x),trunc(y)), which only
312/// makes sense if x and y can be efficiently truncated.
313///
314static bool CanEvaluateTruncated(Value *V, const Type *Ty) {
315 // We can always evaluate constants in another type.
316 if (isa<Constant>(V))
317 return true;
Chris Lattner68c6e892010-01-05 23:00:30 +0000318
Chris Lattner75215c92010-01-10 00:58:42 +0000319 Instruction *I = dyn_cast<Instruction>(V);
320 if (!I) return false;
321
322 const Type *OrigTy = V->getType();
323
324 // If this is an extension from the dest type, we can eliminate it.
325 if ((isa<ZExtInst>(I) || isa<SExtInst>(I)) &&
326 I->getOperand(0)->getType() == Ty)
327 return true;
328
329 // We can't extend or shrink something that has multiple uses: doing so would
330 // require duplicating the instruction in general, which isn't profitable.
331 if (!I->hasOneUse()) return false;
332
333 unsigned Opc = I->getOpcode();
334 switch (Opc) {
335 case Instruction::Add:
336 case Instruction::Sub:
337 case Instruction::Mul:
338 case Instruction::And:
339 case Instruction::Or:
340 case Instruction::Xor:
341 // These operators can all arbitrarily be extended or truncated.
342 return CanEvaluateTruncated(I->getOperand(0), Ty) &&
343 CanEvaluateTruncated(I->getOperand(1), Ty);
344
345 case Instruction::UDiv:
346 case Instruction::URem: {
347 // UDiv and URem can be truncated if all the truncated bits are zero.
348 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
349 uint32_t BitWidth = Ty->getScalarSizeInBits();
350 if (BitWidth < OrigBitWidth) {
351 APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
352 if (MaskedValueIsZero(I->getOperand(0), Mask) &&
353 MaskedValueIsZero(I->getOperand(1), Mask)) {
354 return CanEvaluateTruncated(I->getOperand(0), Ty) &&
355 CanEvaluateTruncated(I->getOperand(1), Ty);
356 }
357 }
358 break;
359 }
360 case Instruction::Shl:
361 // If we are truncating the result of this SHL, and if it's a shift of a
362 // constant amount, we can always perform a SHL in a smaller type.
363 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
364 uint32_t BitWidth = Ty->getScalarSizeInBits();
365 if (CI->getLimitedValue(BitWidth) < BitWidth)
366 return CanEvaluateTruncated(I->getOperand(0), Ty);
367 }
368 break;
369 case Instruction::LShr:
370 // If this is a truncate of a logical shr, we can truncate it to a smaller
371 // lshr iff we know that the bits we would otherwise be shifting in are
372 // already zeros.
373 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
374 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
375 uint32_t BitWidth = Ty->getScalarSizeInBits();
376 if (MaskedValueIsZero(I->getOperand(0),
377 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
378 CI->getLimitedValue(BitWidth) < BitWidth) {
379 return CanEvaluateTruncated(I->getOperand(0), Ty);
380 }
381 }
382 break;
383 case Instruction::Trunc:
384 // trunc(trunc(x)) -> trunc(x)
385 return true;
386 case Instruction::Select: {
387 SelectInst *SI = cast<SelectInst>(I);
388 return CanEvaluateTruncated(SI->getTrueValue(), Ty) &&
389 CanEvaluateTruncated(SI->getFalseValue(), Ty);
390 }
391 case Instruction::PHI: {
392 // We can change a phi if we can change all operands. Note that we never
393 // get into trouble with cyclic PHIs here because we only consider
394 // instructions with a single use.
395 PHINode *PN = cast<PHINode>(I);
396 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
397 if (!CanEvaluateTruncated(PN->getIncomingValue(i), Ty))
398 return false;
399 return true;
400 }
401 default:
402 // TODO: Can handle more cases here.
403 break;
404 }
405
406 return false;
407}
408
409Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattnerd84dfa42010-01-10 01:00:46 +0000410 if (Instruction *Result = commonCastTransforms(CI))
Chris Lattner75215c92010-01-10 00:58:42 +0000411 return Result;
412
Chris Lattnerd84dfa42010-01-10 01:00:46 +0000413 // See if we can simplify any instructions used by the input whose sole
414 // purpose is to compute bits we don't care about.
415 if (SimplifyDemandedInstructionBits(CI))
416 return &CI;
417
Chris Lattner75215c92010-01-10 00:58:42 +0000418 Value *Src = CI.getOperand(0);
419 const Type *DestTy = CI.getType(), *SrcTy = Src->getType();
420
421 // Attempt to truncate the entire input expression tree to the destination
422 // type. Only do this if the dest type is a simple type, don't convert the
Chris Lattner80f43d32010-01-04 07:53:58 +0000423 // expression tree to something weird like i93 unless the source is also
424 // strange.
Chris Lattner75215c92010-01-10 00:58:42 +0000425 if ((isa<VectorType>(DestTy) || ShouldChangeType(SrcTy, DestTy)) &&
426 CanEvaluateTruncated(Src, DestTy)) {
Chris Lattnere0e4cc72010-01-06 01:56:21 +0000427
Chris Lattner80f43d32010-01-04 07:53:58 +0000428 // If this cast is a truncate, evaluting in a different type always
Chris Lattner68c6e892010-01-05 23:00:30 +0000429 // eliminates the cast, so it is always a win.
Chris Lattner075f6922010-01-07 23:41:00 +0000430 DEBUG(dbgs() << "ICE: EvaluateInDifferentType converting expression type"
431 " to avoid cast: " << CI);
432 Value *Res = EvaluateInDifferentType(Src, DestTy, false);
433 assert(Res->getType() == DestTy);
434 return ReplaceInstUsesWith(CI, Res);
435 }
Chris Lattner80f43d32010-01-04 07:53:58 +0000436
Chris Lattner7a34d6c2010-01-05 22:21:18 +0000437 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0), likewise for vector.
438 if (DestTy->getScalarSizeInBits() == 1) {
Chris Lattner80f43d32010-01-04 07:53:58 +0000439 Constant *One = ConstantInt::get(Src->getType(), 1);
440 Src = Builder->CreateAnd(Src, One, "tmp");
441 Value *Zero = Constant::getNullValue(Src->getType());
442 return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
443 }
444
Chris Lattner80f43d32010-01-04 07:53:58 +0000445 return 0;
446}
447
448/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
449/// in order to eliminate the icmp.
450Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
451 bool DoXform) {
452 // If we are just checking for a icmp eq of a single bit and zext'ing it
453 // to an integer, then shift the bit to the appropriate place and then
454 // cast to integer to avoid the comparison.
455 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
456 const APInt &Op1CV = Op1C->getValue();
457
458 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
459 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
460 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
461 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
462 if (!DoXform) return ICI;
463
464 Value *In = ICI->getOperand(0);
465 Value *Sh = ConstantInt::get(In->getType(),
466 In->getType()->getScalarSizeInBits()-1);
467 In = Builder->CreateLShr(In, Sh, In->getName()+".lobit");
468 if (In->getType() != CI.getType())
469 In = Builder->CreateIntCast(In, CI.getType(), false/*ZExt*/, "tmp");
470
471 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
472 Constant *One = ConstantInt::get(In->getType(), 1);
473 In = Builder->CreateXor(In, One, In->getName()+".not");
474 }
475
476 return ReplaceInstUsesWith(CI, In);
477 }
478
479
480
481 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
482 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
483 // zext (X == 1) to i32 --> X iff X has only the low bit set.
484 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
485 // zext (X != 0) to i32 --> X iff X has only the low bit set.
486 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
487 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
488 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
489 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
490 // This only works for EQ and NE
491 ICI->isEquality()) {
492 // If Op1C some other power of two, convert:
493 uint32_t BitWidth = Op1C->getType()->getBitWidth();
494 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
495 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
496 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
497
498 APInt KnownZeroMask(~KnownZero);
499 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
500 if (!DoXform) return ICI;
501
502 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
503 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
504 // (X&4) == 2 --> false
505 // (X&4) != 2 --> true
506 Constant *Res = ConstantInt::get(Type::getInt1Ty(CI.getContext()),
507 isNE);
508 Res = ConstantExpr::getZExt(Res, CI.getType());
509 return ReplaceInstUsesWith(CI, Res);
510 }
511
512 uint32_t ShiftAmt = KnownZeroMask.logBase2();
513 Value *In = ICI->getOperand(0);
514 if (ShiftAmt) {
515 // Perform a logical shr by shiftamt.
516 // Insert the shift to put the result in the low bit.
517 In = Builder->CreateLShr(In, ConstantInt::get(In->getType(),ShiftAmt),
518 In->getName()+".lobit");
519 }
520
521 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
522 Constant *One = ConstantInt::get(In->getType(), 1);
523 In = Builder->CreateXor(In, One, "tmp");
524 }
525
526 if (CI.getType() == In->getType())
527 return ReplaceInstUsesWith(CI, In);
528 else
529 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
530 }
531 }
532 }
533
534 // icmp ne A, B is equal to xor A, B when A and B only really have one bit.
535 // It is also profitable to transform icmp eq into not(xor(A, B)) because that
536 // may lead to additional simplifications.
537 if (ICI->isEquality() && CI.getType() == ICI->getOperand(0)->getType()) {
538 if (const IntegerType *ITy = dyn_cast<IntegerType>(CI.getType())) {
539 uint32_t BitWidth = ITy->getBitWidth();
540 Value *LHS = ICI->getOperand(0);
541 Value *RHS = ICI->getOperand(1);
542
543 APInt KnownZeroLHS(BitWidth, 0), KnownOneLHS(BitWidth, 0);
544 APInt KnownZeroRHS(BitWidth, 0), KnownOneRHS(BitWidth, 0);
545 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
546 ComputeMaskedBits(LHS, TypeMask, KnownZeroLHS, KnownOneLHS);
547 ComputeMaskedBits(RHS, TypeMask, KnownZeroRHS, KnownOneRHS);
548
549 if (KnownZeroLHS == KnownZeroRHS && KnownOneLHS == KnownOneRHS) {
550 APInt KnownBits = KnownZeroLHS | KnownOneLHS;
551 APInt UnknownBit = ~KnownBits;
552 if (UnknownBit.countPopulation() == 1) {
553 if (!DoXform) return ICI;
554
555 Value *Result = Builder->CreateXor(LHS, RHS);
556
557 // Mask off any bits that are set and won't be shifted away.
558 if (KnownOneLHS.uge(UnknownBit))
559 Result = Builder->CreateAnd(Result,
560 ConstantInt::get(ITy, UnknownBit));
561
562 // Shift the bit we're testing down to the lsb.
563 Result = Builder->CreateLShr(
564 Result, ConstantInt::get(ITy, UnknownBit.countTrailingZeros()));
565
566 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
567 Result = Builder->CreateXor(Result, ConstantInt::get(ITy, 1));
568 Result->takeName(ICI);
569 return ReplaceInstUsesWith(CI, Result);
570 }
571 }
572 }
573 }
574
575 return 0;
576}
577
Chris Lattner75215c92010-01-10 00:58:42 +0000578/// GetLeadingZeros - Compute the number of known-zero leading bits.
579static unsigned GetLeadingZeros(Value *V, const TargetData *TD) {
580 unsigned Bits = V->getType()->getScalarSizeInBits();
581 APInt KnownZero(Bits, 0), KnownOne(Bits, 0);
582 ComputeMaskedBits(V, APInt::getAllOnesValue(Bits), KnownZero, KnownOne, TD);
583 return KnownZero.countLeadingOnes();
584}
585
586/// CanEvaluateZExtd - Determine if the specified value can be computed in the
587/// specified wider type and produce the same low bits. If not, return -1. If
588/// it is possible, return the number of high bits that are known to be zero in
589/// the promoted value.
590static int CanEvaluateZExtd(Value *V, const Type *Ty,unsigned &NumCastsRemoved,
591 const TargetData *TD) {
592 const Type *OrigTy = V->getType();
593
594 if (isa<Constant>(V)) {
595 unsigned Extended = Ty->getScalarSizeInBits()-OrigTy->getScalarSizeInBits();
596
597 // Constants can always be zero ext'd, even if it requires a ConstantExpr.
598 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
599 return Extended + CI->getValue().countLeadingZeros();
600 return Extended;
601 }
602
603 Instruction *I = dyn_cast<Instruction>(V);
604 if (!I) return -1;
605
606 // If the input is a truncate from the destination type, we can trivially
607 // eliminate it, and this will remove a cast overall.
608 if (isa<TruncInst>(I) && I->getOperand(0)->getType() == Ty) {
609 // If the first operand is itself a cast, and is eliminable, do not count
610 // this as an eliminable cast. We would prefer to eliminate those two
611 // casts first.
612 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
613 ++NumCastsRemoved;
614
615 // Figure out the number of known-zero bits coming in.
616 return GetLeadingZeros(I->getOperand(0), TD);
617 }
618
619 // We can't extend or shrink something that has multiple uses: doing so would
620 // require duplicating the instruction in general, which isn't profitable.
621 if (!I->hasOneUse()) return -1;
622
623 int Tmp1, Tmp2;
624 unsigned Opc = I->getOpcode();
625 switch (Opc) {
626 case Instruction::And:
627 Tmp1 = CanEvaluateZExtd(I->getOperand(0), Ty, NumCastsRemoved, TD);
628 if (Tmp1 == -1) return -1;
629 Tmp2 = CanEvaluateZExtd(I->getOperand(1), Ty, NumCastsRemoved, TD);
630 if (Tmp2 == -1) return -1;
631 return std::max(Tmp1, Tmp2);
632 case Instruction::Or:
633 case Instruction::Xor:
634 Tmp1 = CanEvaluateZExtd(I->getOperand(0), Ty, NumCastsRemoved, TD);
635 if (Tmp1 == -1) return -1;
636 Tmp2 = CanEvaluateZExtd(I->getOperand(1), Ty, NumCastsRemoved, TD);
637 return std::min(Tmp1, Tmp2);
638
639 case Instruction::Add:
640 case Instruction::Sub:
641 case Instruction::Mul:
642 Tmp1 = CanEvaluateZExtd(I->getOperand(0), Ty, NumCastsRemoved, TD);
643 if (Tmp1 == -1) return -1;
644 Tmp2 = CanEvaluateZExtd(I->getOperand(1), Ty, NumCastsRemoved, TD);
645 if (Tmp2 == -1) return -1;
646 return 0;
647
648 //case Instruction::Shl:
649 //case Instruction::LShr:
650 case Instruction::ZExt:
651 // zext(zext(x)) -> zext(x). Since we're replacing it, it isn't eliminated.
652 Tmp1 = Ty->getScalarSizeInBits()-OrigTy->getScalarSizeInBits();
653 return GetLeadingZeros(I, TD)+Tmp1;
654
655 //case Instruction::SExt: zext(sext(x)) -> sext(x) with no upper bits known.
656 //case Instruction::Trunc:
657 case Instruction::Select:
658 Tmp1 = CanEvaluateZExtd(I->getOperand(1), Ty, NumCastsRemoved, TD);
659 if (Tmp1 == -1) return -1;
660 Tmp2 = CanEvaluateZExtd(I->getOperand(2), Ty, NumCastsRemoved, TD);
661 return std::min(Tmp1, Tmp2);
662
663 case Instruction::PHI: {
664 // We can change a phi if we can change all operands. Note that we never
665 // get into trouble with cyclic PHIs here because we only consider
666 // instructions with a single use.
667 PHINode *PN = cast<PHINode>(I);
668 int Result = CanEvaluateZExtd(PN->getIncomingValue(0), Ty,
669 NumCastsRemoved, TD);
670 for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i) {
671 if (Result == -1) return -1;
672 Tmp1 = CanEvaluateZExtd(PN->getIncomingValue(i), Ty, NumCastsRemoved, TD);
673 Result = std::min(Result, Tmp1);
674 }
675 return Result;
676 }
677 default:
678 // TODO: Can handle more cases here.
679 return -1;
680 }
681}
682
Chris Lattner80f43d32010-01-04 07:53:58 +0000683Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
684 // If one of the common conversion will work, do it.
Chris Lattnerd84dfa42010-01-10 01:00:46 +0000685 if (Instruction *Result = commonCastTransforms(CI))
Chris Lattner80f43d32010-01-04 07:53:58 +0000686 return Result;
687
Chris Lattnerd84dfa42010-01-10 01:00:46 +0000688 // See if we can simplify any instructions used by the input whose sole
689 // purpose is to compute bits we don't care about.
690 if (SimplifyDemandedInstructionBits(CI))
691 return &CI;
Chris Lattner75215c92010-01-10 00:58:42 +0000692
Chris Lattnerd84dfa42010-01-10 01:00:46 +0000693 Value *Src = CI.getOperand(0);
Chris Lattner75215c92010-01-10 00:58:42 +0000694 const Type *SrcTy = Src->getType(), *DestTy = CI.getType();
695
696 // Attempt to extend the entire input expression tree to the destination
697 // type. Only do this if the dest type is a simple type, don't convert the
698 // expression tree to something weird like i93 unless the source is also
699 // strange.
700 if (isa<VectorType>(DestTy) || ShouldChangeType(SrcTy, DestTy)) {
701 unsigned NumCastsRemoved = 0;
702 int BitsZExt = CanEvaluateZExtd(Src, DestTy, NumCastsRemoved, TD);
703 if (BitsZExt == -1) return 0;
704
705 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
706 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
707
708 // If this is a zero-extension, we need to do an AND to maintain the clear
709 // top-part of the computation. If we know the result will be zero
710 // extended enough already, we don't need the and.
711 if (NumCastsRemoved >= 1 ||
712 unsigned(BitsZExt) >= DestBitSize-SrcBitSize) {
713
714 // Okay, we can transform this! Insert the new expression now.
715 DEBUG(dbgs() << "ICE: EvaluateInDifferentType converting expression type"
716 " to avoid zero extend: " << CI);
717 Value *Res = EvaluateInDifferentType(Src, DestTy, false);
718 assert(Res->getType() == DestTy);
719
720 // If the high bits are already filled with zeros, just replace this
721 // cast with the result.
722 if (unsigned(BitsZExt) >= DestBitSize-SrcBitSize ||
723 MaskedValueIsZero(Res, APInt::getHighBitsSet(DestBitSize,
724 DestBitSize-SrcBitSize)))
725 return ReplaceInstUsesWith(CI, Res);
726
727 // We need to emit an AND to clear the high bits.
728 Constant *C = ConstantInt::get(CI.getContext(),
729 APInt::getLowBitsSet(DestBitSize, SrcBitSize));
730 return BinaryOperator::CreateAnd(Res, C);
731 }
732 }
Chris Lattner80f43d32010-01-04 07:53:58 +0000733
734 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
735 // types and if the sizes are just right we can convert this into a logical
736 // 'and' which will be much cheaper than the pair of casts.
737 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
738 // Get the sizes of the types involved. We know that the intermediate type
739 // will be smaller than A or C, but don't know the relation between A and C.
740 Value *A = CSrc->getOperand(0);
741 unsigned SrcSize = A->getType()->getScalarSizeInBits();
742 unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
743 unsigned DstSize = CI.getType()->getScalarSizeInBits();
744 // If we're actually extending zero bits, then if
745 // SrcSize < DstSize: zext(a & mask)
746 // SrcSize == DstSize: a & mask
747 // SrcSize > DstSize: trunc(a) & mask
748 if (SrcSize < DstSize) {
749 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
750 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
751 Value *And = Builder->CreateAnd(A, AndConst, CSrc->getName()+".mask");
752 return new ZExtInst(And, CI.getType());
753 }
754
755 if (SrcSize == DstSize) {
756 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
757 return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
758 AndValue));
759 }
760 if (SrcSize > DstSize) {
761 Value *Trunc = Builder->CreateTrunc(A, CI.getType(), "tmp");
762 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
763 return BinaryOperator::CreateAnd(Trunc,
764 ConstantInt::get(Trunc->getType(),
765 AndValue));
766 }
767 }
768
769 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
770 return transformZExtICmp(ICI, CI);
771
772 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
773 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
774 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
775 // of the (zext icmp) will be transformed.
776 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
777 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
778 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
779 (transformZExtICmp(LHS, CI, false) ||
780 transformZExtICmp(RHS, CI, false))) {
781 Value *LCast = Builder->CreateZExt(LHS, CI.getType(), LHS->getName());
782 Value *RCast = Builder->CreateZExt(RHS, CI.getType(), RHS->getName());
783 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
784 }
785 }
786
787 // zext(trunc(t) & C) -> (t & zext(C)).
788 if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
789 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
790 if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
791 Value *TI0 = TI->getOperand(0);
792 if (TI0->getType() == CI.getType())
793 return
794 BinaryOperator::CreateAnd(TI0,
795 ConstantExpr::getZExt(C, CI.getType()));
796 }
797
798 // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
799 if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
800 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
801 if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
802 if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
803 And->getOperand(1) == C)
804 if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
805 Value *TI0 = TI->getOperand(0);
806 if (TI0->getType() == CI.getType()) {
807 Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
808 Value *NewAnd = Builder->CreateAnd(TI0, ZC, "tmp");
809 return BinaryOperator::CreateXor(NewAnd, ZC);
810 }
811 }
812
Chris Lattner718bf3f2010-01-05 21:04:47 +0000813 // zext (xor i1 X, true) to i32 --> xor (zext i1 X to i32), 1
814 Value *X;
Chris Lattner49bdfef2010-01-05 21:11:17 +0000815 if (SrcI && SrcI->hasOneUse() && SrcI->getType()->isInteger(1) &&
816 match(SrcI, m_Not(m_Value(X))) &&
Chris Lattner718bf3f2010-01-05 21:04:47 +0000817 (!X->hasOneUse() || !isa<CmpInst>(X))) {
818 Value *New = Builder->CreateZExt(X, CI.getType());
819 return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
820 }
821
Chris Lattner80f43d32010-01-04 07:53:58 +0000822 return 0;
823}
824
Chris Lattner75215c92010-01-10 00:58:42 +0000825/// CanEvaluateSExtd - Return true if we can take the specified value
826/// and return it as type Ty without inserting any new casts and without
827/// changing the value of the common low bits. This is used by code that tries
828/// to promote integer operations to a wider types will allow us to eliminate
829/// the extension.
830///
831/// This returns 0 if we can't do this or the number of sign bits that would be
832/// set if we can. For example, CanEvaluateSExtd(i16 1, i64) would return 63,
833/// because the computation can be extended (to "i64 1") and the resulting
834/// computation has 63 equal sign bits.
835///
836/// This function works on both vectors and scalars. For vectors, the result is
837/// the number of bits known sign extended in each element.
838///
839static unsigned CanEvaluateSExtd(Value *V, const Type *Ty,
840 unsigned &NumCastsRemoved, TargetData *TD) {
841 assert(V->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits() &&
842 "Can't sign extend type to a smaller type");
843 // If this is a constant, return the number of sign bits the extended version
844 // of it would have.
845 if (Constant *C = dyn_cast<Constant>(V))
846 return ComputeNumSignBits(ConstantExpr::getSExt(C, Ty), TD);
847
848 Instruction *I = dyn_cast<Instruction>(V);
849 if (!I) return 0;
850
851 // If this is a truncate from the destination type, we can trivially eliminate
852 // it, and this will remove a cast overall.
853 if (isa<TruncInst>(I) && I->getOperand(0)->getType() == Ty) {
854 // If the operand of the truncate is itself a cast, and is eliminable, do
855 // not count this as an eliminable cast. We would prefer to eliminate those
856 // two casts first.
857 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
858 ++NumCastsRemoved;
859 return ComputeNumSignBits(I->getOperand(0), TD);
860 }
861
862 // We can't extend or shrink something that has multiple uses: doing so would
863 // require duplicating the instruction in general, which isn't profitable.
864 if (!I->hasOneUse()) return 0;
865
866 const Type *OrigTy = V->getType();
867
868 unsigned Opc = I->getOpcode();
869 unsigned Tmp1, Tmp2;
870 switch (Opc) {
871 case Instruction::And:
872 case Instruction::Or:
873 case Instruction::Xor:
874 // These operators can all arbitrarily be extended or truncated.
875 Tmp1 = CanEvaluateSExtd(I->getOperand(0), Ty, NumCastsRemoved, TD);
876 if (Tmp1 == 0) return 0;
877 Tmp2 = CanEvaluateSExtd(I->getOperand(1), Ty, NumCastsRemoved, TD);
878 return std::min(Tmp1, Tmp2);
879 case Instruction::Add:
880 case Instruction::Sub:
881 // Add/Sub can have at most one carry/borrow bit.
882 Tmp1 = CanEvaluateSExtd(I->getOperand(0), Ty, NumCastsRemoved, TD);
883 if (Tmp1 == 0) return 0;
884 Tmp2 = CanEvaluateSExtd(I->getOperand(1), Ty, NumCastsRemoved, TD);
885 if (Tmp2 == 0) return 0;
886 return std::min(Tmp1, Tmp2)-1;
887 case Instruction::Mul:
888 // These operators can all arbitrarily be extended or truncated.
889 if (!CanEvaluateSExtd(I->getOperand(0), Ty, NumCastsRemoved, TD))
890 return 0;
891 if (!CanEvaluateSExtd(I->getOperand(1), Ty, NumCastsRemoved, TD))
892 return 0;
893 return 1; // IMPROVE?
894
895 //case Instruction::Shl: TODO
896 //case Instruction::LShr: TODO
897 //case Instruction::Trunc: TODO
898
899 case Instruction::SExt:
900 case Instruction::ZExt: {
901 // sext(sext(x)) -> sext(x)
902 // sext(zext(x)) -> zext(x)
903 // Note that replacing a cast does not reduce the number of casts in the
904 // input.
905 unsigned InSignBits = ComputeNumSignBits(I, TD);
906 unsigned ExtBits = Ty->getScalarSizeInBits()-OrigTy->getScalarSizeInBits();
907 // We'll end up extending it all the way out.
908 return InSignBits+ExtBits;
909 }
910 case Instruction::Select: {
911 SelectInst *SI = cast<SelectInst>(I);
912 Tmp1 = CanEvaluateSExtd(SI->getTrueValue(), Ty, NumCastsRemoved, TD);
913 if (Tmp1 == 0) return 0;
914 Tmp2 = CanEvaluateSExtd(SI->getFalseValue(), Ty, NumCastsRemoved,TD);
915 return std::min(Tmp1, Tmp2);
916 }
917 case Instruction::PHI: {
918 // We can change a phi if we can change all operands. Note that we never
919 // get into trouble with cyclic PHIs here because we only consider
920 // instructions with a single use.
921 PHINode *PN = cast<PHINode>(I);
922 unsigned Result = ~0U;
923 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
924 Result = std::min(Result,
925 CanEvaluateSExtd(PN->getIncomingValue(i), Ty,
926 NumCastsRemoved, TD));
927 if (Result == 0) return 0;
928 }
929 return Result;
930 }
931 default:
932 // TODO: Can handle more cases here.
933 break;
934 }
935
936 return 0;
937}
938
Chris Lattner80f43d32010-01-04 07:53:58 +0000939Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattnerd84dfa42010-01-10 01:00:46 +0000940 if (Instruction *I = commonCastTransforms(CI))
Chris Lattner80f43d32010-01-04 07:53:58 +0000941 return I;
942
Chris Lattnerd84dfa42010-01-10 01:00:46 +0000943 // See if we can simplify any instructions used by the input whose sole
944 // purpose is to compute bits we don't care about.
945 if (SimplifyDemandedInstructionBits(CI))
946 return &CI;
947
Chris Lattner80f43d32010-01-04 07:53:58 +0000948 Value *Src = CI.getOperand(0);
Chris Lattner75215c92010-01-10 00:58:42 +0000949 const Type *SrcTy = Src->getType(), *DestTy = CI.getType();
950
Chris Lattner80f43d32010-01-04 07:53:58 +0000951 // Canonicalize sign-extend from i1 to a select.
Benjamin Kramer11acaa32010-01-05 20:07:06 +0000952 if (Src->getType()->isInteger(1))
Chris Lattner80f43d32010-01-04 07:53:58 +0000953 return SelectInst::Create(Src,
954 Constant::getAllOnesValue(CI.getType()),
955 Constant::getNullValue(CI.getType()));
956
957 // See if the value being truncated is already sign extended. If so, just
958 // eliminate the trunc/sext pair.
959 if (Operator::getOpcode(Src) == Instruction::Trunc) {
960 Value *Op = cast<User>(Src)->getOperand(0);
961 unsigned OpBits = Op->getType()->getScalarSizeInBits();
Chris Lattner75215c92010-01-10 00:58:42 +0000962 unsigned MidBits = SrcTy->getScalarSizeInBits();
963 unsigned DestBits = DestTy->getScalarSizeInBits();
Chris Lattner80f43d32010-01-04 07:53:58 +0000964 unsigned NumSignBits = ComputeNumSignBits(Op);
965
966 if (OpBits == DestBits) {
967 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
968 // bits, it is already ready.
969 if (NumSignBits > DestBits-MidBits)
970 return ReplaceInstUsesWith(CI, Op);
971 } else if (OpBits < DestBits) {
972 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
973 // bits, just sext from i32.
974 if (NumSignBits > OpBits-MidBits)
975 return new SExtInst(Op, CI.getType(), "tmp");
976 } else {
977 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
978 // bits, just truncate to i32.
979 if (NumSignBits > OpBits-MidBits)
980 return new TruncInst(Op, CI.getType(), "tmp");
981 }
982 }
Chris Lattner75215c92010-01-10 00:58:42 +0000983
984 // Attempt to extend the entire input expression tree to the destination
985 // type. Only do this if the dest type is a simple type, don't convert the
986 // expression tree to something weird like i93 unless the source is also
987 // strange.
988 if (isa<VectorType>(DestTy) || ShouldChangeType(SrcTy, DestTy)) {
989 unsigned NumCastsRemoved = 0;
990 // Check to see if we can do this transformation, and if so, how many bits
991 // of the promoted expression will be known copies of the sign bit in the
992 // result.
993 unsigned NumBitsSExt = CanEvaluateSExtd(Src, DestTy, NumCastsRemoved, TD);
994 if (NumBitsSExt == 0)
995 return 0;
996
997 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
998 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
999
1000 // Because this is a sign extension, we can always transform it by inserting
1001 // two new shifts (to do the extension). However, this is only profitable
1002 // if we've eliminated two or more casts from the input. If we know the
1003 // result will be sign-extended enough to not require these shifts, we can
1004 // always do the transformation.
1005 if (NumCastsRemoved >= 2 ||
1006 NumBitsSExt > DestBitSize-SrcBitSize) {
1007 // Okay, we can transform this! Insert the new expression now.
1008 DEBUG(dbgs() << "ICE: EvaluateInDifferentType converting expression type"
1009 " to avoid sign extend: " << CI);
1010 Value *Res = EvaluateInDifferentType(Src, DestTy, true);
1011 assert(Res->getType() == DestTy);
1012
1013 // If the high bits are already filled with sign bit, just replace this
1014 // cast with the result.
1015 if (NumBitsSExt > DestBitSize - SrcBitSize ||
1016 ComputeNumSignBits(Res) > DestBitSize - SrcBitSize)
1017 return ReplaceInstUsesWith(CI, Res);
1018
1019 // We need to emit a cast to truncate, then a cast to sext.
1020 return new SExtInst(Builder->CreateTrunc(Res, Src->getType()), DestTy);
1021 }
1022 }
Chris Lattner80f43d32010-01-04 07:53:58 +00001023
1024 // If the input is a shl/ashr pair of a same constant, then this is a sign
1025 // extension from a smaller value. If we could trust arbitrary bitwidth
1026 // integers, we could turn this into a truncate to the smaller bit and then
1027 // use a sext for the whole extension. Since we don't, look deeper and check
1028 // for a truncate. If the source and dest are the same type, eliminate the
1029 // trunc and extend and just do shifts. For example, turn:
1030 // %a = trunc i32 %i to i8
1031 // %b = shl i8 %a, 6
1032 // %c = ashr i8 %b, 6
1033 // %d = sext i8 %c to i32
1034 // into:
1035 // %a = shl i32 %i, 30
1036 // %d = ashr i32 %a, 30
1037 Value *A = 0;
Chris Lattner75215c92010-01-10 00:58:42 +00001038 // FIXME: GENERALIZE WITH SIGN BITS.
Chris Lattner80f43d32010-01-04 07:53:58 +00001039 ConstantInt *BA = 0, *CA = 0;
1040 if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
1041 m_ConstantInt(CA))) &&
1042 BA == CA && isa<TruncInst>(A)) {
1043 Value *I = cast<TruncInst>(A)->getOperand(0);
1044 if (I->getType() == CI.getType()) {
1045 unsigned MidSize = Src->getType()->getScalarSizeInBits();
1046 unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
1047 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
1048 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
1049 I = Builder->CreateShl(I, ShAmtV, CI.getName());
1050 return BinaryOperator::CreateAShr(I, ShAmtV);
1051 }
1052 }
1053
1054 return 0;
1055}
1056
1057
1058/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
1059/// in the specified FP type without changing its value.
1060static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
1061 bool losesInfo;
1062 APFloat F = CFP->getValueAPF();
1063 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
1064 if (!losesInfo)
1065 return ConstantFP::get(CFP->getContext(), F);
1066 return 0;
1067}
1068
1069/// LookThroughFPExtensions - If this is an fp extension instruction, look
1070/// through it until we get the source value.
1071static Value *LookThroughFPExtensions(Value *V) {
1072 if (Instruction *I = dyn_cast<Instruction>(V))
1073 if (I->getOpcode() == Instruction::FPExt)
1074 return LookThroughFPExtensions(I->getOperand(0));
1075
1076 // If this value is a constant, return the constant in the smallest FP type
1077 // that can accurately represent it. This allows us to turn
1078 // (float)((double)X+2.0) into x+2.0f.
1079 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
1080 if (CFP->getType() == Type::getPPC_FP128Ty(V->getContext()))
1081 return V; // No constant folding of this.
1082 // See if the value can be truncated to float and then reextended.
1083 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
1084 return V;
Benjamin Kramerf0127052010-01-05 13:12:22 +00001085 if (CFP->getType()->isDoubleTy())
Chris Lattner80f43d32010-01-04 07:53:58 +00001086 return V; // Won't shrink.
1087 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
1088 return V;
1089 // Don't try to shrink to various long double types.
1090 }
1091
1092 return V;
1093}
1094
1095Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
1096 if (Instruction *I = commonCastTransforms(CI))
1097 return I;
1098
1099 // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
1100 // smaller than the destination type, we can eliminate the truncate by doing
1101 // the add as the smaller type. This applies to fadd/fsub/fmul/fdiv as well
1102 // as many builtins (sqrt, etc).
1103 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
1104 if (OpI && OpI->hasOneUse()) {
1105 switch (OpI->getOpcode()) {
1106 default: break;
1107 case Instruction::FAdd:
1108 case Instruction::FSub:
1109 case Instruction::FMul:
1110 case Instruction::FDiv:
1111 case Instruction::FRem:
1112 const Type *SrcTy = OpI->getType();
1113 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
1114 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
1115 if (LHSTrunc->getType() != SrcTy &&
1116 RHSTrunc->getType() != SrcTy) {
1117 unsigned DstSize = CI.getType()->getScalarSizeInBits();
1118 // If the source types were both smaller than the destination type of
1119 // the cast, do this xform.
1120 if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
1121 RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
1122 LHSTrunc = Builder->CreateFPExt(LHSTrunc, CI.getType());
1123 RHSTrunc = Builder->CreateFPExt(RHSTrunc, CI.getType());
1124 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
1125 }
1126 }
1127 break;
1128 }
1129 }
1130 return 0;
1131}
1132
1133Instruction *InstCombiner::visitFPExt(CastInst &CI) {
1134 return commonCastTransforms(CI);
1135}
1136
1137Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
1138 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
1139 if (OpI == 0)
1140 return commonCastTransforms(FI);
1141
1142 // fptoui(uitofp(X)) --> X
1143 // fptoui(sitofp(X)) --> X
1144 // This is safe if the intermediate type has enough bits in its mantissa to
1145 // accurately represent all values of X. For example, do not do this with
1146 // i64->float->i64. This is also safe for sitofp case, because any negative
1147 // 'X' value would cause an undefined result for the fptoui.
1148 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
1149 OpI->getOperand(0)->getType() == FI.getType() &&
1150 (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
1151 OpI->getType()->getFPMantissaWidth())
1152 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
1153
1154 return commonCastTransforms(FI);
1155}
1156
1157Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
1158 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
1159 if (OpI == 0)
1160 return commonCastTransforms(FI);
1161
1162 // fptosi(sitofp(X)) --> X
1163 // fptosi(uitofp(X)) --> X
1164 // This is safe if the intermediate type has enough bits in its mantissa to
1165 // accurately represent all values of X. For example, do not do this with
1166 // i64->float->i64. This is also safe for sitofp case, because any negative
1167 // 'X' value would cause an undefined result for the fptoui.
1168 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
1169 OpI->getOperand(0)->getType() == FI.getType() &&
1170 (int)FI.getType()->getScalarSizeInBits() <=
1171 OpI->getType()->getFPMantissaWidth())
1172 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
1173
1174 return commonCastTransforms(FI);
1175}
1176
1177Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
1178 return commonCastTransforms(CI);
1179}
1180
1181Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
1182 return commonCastTransforms(CI);
1183}
1184
Chris Lattner80f43d32010-01-04 07:53:58 +00001185Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
1186 // If the source integer type is larger than the intptr_t type for
1187 // this target, do a trunc to the intptr_t type, then inttoptr of it. This
1188 // allows the trunc to be exposed to other transforms. Don't do this for
1189 // extending inttoptr's, because we don't know if the target sign or zero
1190 // extends to pointers.
1191 if (TD && CI.getOperand(0)->getType()->getScalarSizeInBits() >
1192 TD->getPointerSizeInBits()) {
1193 Value *P = Builder->CreateTrunc(CI.getOperand(0),
1194 TD->getIntPtrType(CI.getContext()), "tmp");
1195 return new IntToPtrInst(P, CI.getType());
1196 }
1197
1198 if (Instruction *I = commonCastTransforms(CI))
1199 return I;
1200
1201 return 0;
1202}
1203
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001204/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
1205Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
1206 Value *Src = CI.getOperand(0);
1207
1208 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
1209 // If casting the result of a getelementptr instruction with no offset, turn
1210 // this into a cast of the original pointer!
1211 if (GEP->hasAllZeroIndices()) {
1212 // Changing the cast operand is usually not a good idea but it is safe
1213 // here because the pointer operand is being replaced with another
1214 // pointer operand so the opcode doesn't need to change.
1215 Worklist.Add(GEP);
1216 CI.setOperand(0, GEP->getOperand(0));
1217 return &CI;
1218 }
1219
1220 // If the GEP has a single use, and the base pointer is a bitcast, and the
1221 // GEP computes a constant offset, see if we can convert these three
1222 // instructions into fewer. This typically happens with unions and other
1223 // non-type-safe code.
1224 if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0)) &&
1225 GEP->hasAllConstantIndices()) {
1226 // We are guaranteed to get a constant from EmitGEPOffset.
1227 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP));
1228 int64_t Offset = OffsetV->getSExtValue();
1229
1230 // Get the base pointer input of the bitcast, and the type it points to.
1231 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
1232 const Type *GEPIdxTy =
1233 cast<PointerType>(OrigBase->getType())->getElementType();
1234 SmallVector<Value*, 8> NewIndices;
1235 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices)) {
1236 // If we were able to index down into an element, create the GEP
1237 // and bitcast the result. This eliminates one bitcast, potentially
1238 // two.
1239 Value *NGEP = cast<GEPOperator>(GEP)->isInBounds() ?
1240 Builder->CreateInBoundsGEP(OrigBase,
1241 NewIndices.begin(), NewIndices.end()) :
1242 Builder->CreateGEP(OrigBase, NewIndices.begin(), NewIndices.end());
1243 NGEP->takeName(GEP);
1244
1245 if (isa<BitCastInst>(CI))
1246 return new BitCastInst(NGEP, CI.getType());
1247 assert(isa<PtrToIntInst>(CI));
1248 return new PtrToIntInst(NGEP, CI.getType());
1249 }
1250 }
1251 }
1252
1253 return commonCastTransforms(CI);
1254}
1255
1256Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
1257 // If the destination integer type is smaller than the intptr_t type for
1258 // this target, do a ptrtoint to intptr_t then do a trunc. This allows the
1259 // trunc to be exposed to other transforms. Don't do this for extending
1260 // ptrtoint's, because we don't know if the target sign or zero extends its
1261 // pointers.
1262 if (TD &&
1263 CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
1264 Value *P = Builder->CreatePtrToInt(CI.getOperand(0),
1265 TD->getIntPtrType(CI.getContext()),
1266 "tmp");
1267 return new TruncInst(P, CI.getType());
1268 }
1269
1270 return commonPointerCastTransforms(CI);
1271}
1272
Chris Lattner80f43d32010-01-04 07:53:58 +00001273Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
1274 // If the operands are integer typed then apply the integer transforms,
1275 // otherwise just apply the common ones.
1276 Value *Src = CI.getOperand(0);
1277 const Type *SrcTy = Src->getType();
1278 const Type *DestTy = CI.getType();
1279
Chris Lattner80f43d32010-01-04 07:53:58 +00001280 // Get rid of casts from one type to the same type. These are useless and can
1281 // be replaced by the operand.
1282 if (DestTy == Src->getType())
1283 return ReplaceInstUsesWith(CI, Src);
1284
1285 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
1286 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
1287 const Type *DstElTy = DstPTy->getElementType();
1288 const Type *SrcElTy = SrcPTy->getElementType();
1289
1290 // If the address spaces don't match, don't eliminate the bitcast, which is
1291 // required for changing types.
1292 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
1293 return 0;
1294
1295 // If we are casting a alloca to a pointer to a type of the same
1296 // size, rewrite the allocation instruction to allocate the "right" type.
1297 // There is no need to modify malloc calls because it is their bitcast that
1298 // needs to be cleaned up.
1299 if (AllocaInst *AI = dyn_cast<AllocaInst>(Src))
1300 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
1301 return V;
1302
1303 // If the source and destination are pointers, and this cast is equivalent
1304 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
1305 // This can enhance SROA and other transforms that want type-safe pointers.
1306 Constant *ZeroUInt =
1307 Constant::getNullValue(Type::getInt32Ty(CI.getContext()));
1308 unsigned NumZeros = 0;
1309 while (SrcElTy != DstElTy &&
1310 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
1311 SrcElTy->getNumContainedTypes() /* not "{}" */) {
1312 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
1313 ++NumZeros;
1314 }
1315
1316 // If we found a path from the src to dest, create the getelementptr now.
1317 if (SrcElTy == DstElTy) {
1318 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
1319 return GetElementPtrInst::CreateInBounds(Src, Idxs.begin(), Idxs.end(),"",
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001320 ((Instruction*)NULL));
Chris Lattner80f43d32010-01-04 07:53:58 +00001321 }
1322 }
1323
1324 if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001325 if (DestVTy->getNumElements() == 1 && !isa<VectorType>(SrcTy)) {
1326 Value *Elem = Builder->CreateBitCast(Src, DestVTy->getElementType());
1327 return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
Chris Lattner80f43d32010-01-04 07:53:58 +00001328 Constant::getNullValue(Type::getInt32Ty(CI.getContext())));
Chris Lattner80f43d32010-01-04 07:53:58 +00001329 // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
1330 }
1331 }
1332
1333 if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001334 if (SrcVTy->getNumElements() == 1 && !isa<VectorType>(DestTy)) {
1335 Value *Elem =
1336 Builder->CreateExtractElement(Src,
1337 Constant::getNullValue(Type::getInt32Ty(CI.getContext())));
1338 return CastInst::Create(Instruction::BitCast, Elem, DestTy);
Chris Lattner80f43d32010-01-04 07:53:58 +00001339 }
1340 }
1341
1342 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001343 // Okay, we have (bitcast (shuffle ..)). Check to see if this is
1344 // a bitconvert to a vector with the same # elts.
1345 if (SVI->hasOneUse() && isa<VectorType>(DestTy) &&
1346 cast<VectorType>(DestTy)->getNumElements() ==
1347 SVI->getType()->getNumElements() &&
1348 SVI->getType()->getNumElements() ==
1349 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
1350 BitCastInst *Tmp;
1351 // If either of the operands is a cast from CI.getType(), then
1352 // evaluating the shuffle in the casted destination's type will allow
1353 // us to eliminate at least one cast.
1354 if (((Tmp = dyn_cast<BitCastInst>(SVI->getOperand(0))) &&
1355 Tmp->getOperand(0)->getType() == DestTy) ||
1356 ((Tmp = dyn_cast<BitCastInst>(SVI->getOperand(1))) &&
1357 Tmp->getOperand(0)->getType() == DestTy)) {
1358 Value *LHS = Builder->CreateBitCast(SVI->getOperand(0), DestTy);
1359 Value *RHS = Builder->CreateBitCast(SVI->getOperand(1), DestTy);
1360 // Return a new shuffle vector. Use the same element ID's, as we
1361 // know the vector types match #elts.
1362 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner80f43d32010-01-04 07:53:58 +00001363 }
1364 }
1365 }
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001366
1367 if (isa<PointerType>(SrcTy))
1368 return commonPointerCastTransforms(CI);
1369 return commonCastTransforms(CI);
Chris Lattner80f43d32010-01-04 07:53:58 +00001370}