blob: b5da3e615be5be1f5503dd9daa2666fde627f8e8 [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.
Chris Lattner9ee947c2010-01-10 20:25:54 +0000195 // This also handles the case of zext(trunc(x)) -> zext(x).
196 Res = CastInst::CreateIntegerCast(I->getOperand(0), Ty,
197 Opc == Instruction::SExt);
Chris Lattner5f0290e2010-01-04 07:54:59 +0000198 break;
199 case Instruction::Select: {
200 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
201 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
202 Res = SelectInst::Create(I->getOperand(0), True, False);
203 break;
204 }
205 case Instruction::PHI: {
206 PHINode *OPN = cast<PHINode>(I);
207 PHINode *NPN = PHINode::Create(Ty);
208 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
209 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
210 NPN->addIncoming(V, OPN->getIncomingBlock(i));
211 }
212 Res = NPN;
213 break;
214 }
215 default:
216 // TODO: Can handle more cases here.
217 llvm_unreachable("Unreachable!");
218 break;
219 }
220
221 Res->takeName(I);
222 return InsertNewInstBefore(Res, *I);
223}
Chris Lattner80f43d32010-01-04 07:53:58 +0000224
225
226/// This function is a wrapper around CastInst::isEliminableCastPair. It
227/// simply extracts arguments and returns what that function returns.
228static Instruction::CastOps
229isEliminableCastPair(
230 const CastInst *CI, ///< The first cast instruction
231 unsigned opcode, ///< The opcode of the second cast instruction
232 const Type *DstTy, ///< The target type for the second cast instruction
233 TargetData *TD ///< The target data for pointer size
234) {
235
236 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
237 const Type *MidTy = CI->getType(); // B from above
238
239 // Get the opcodes of the two Cast instructions
240 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
241 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
242
243 unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
244 DstTy,
245 TD ? TD->getIntPtrType(CI->getContext()) : 0);
246
247 // We don't want to form an inttoptr or ptrtoint that converts to an integer
248 // type that differs from the pointer size.
249 if ((Res == Instruction::IntToPtr &&
250 (!TD || SrcTy != TD->getIntPtrType(CI->getContext()))) ||
251 (Res == Instruction::PtrToInt &&
252 (!TD || DstTy != TD->getIntPtrType(CI->getContext()))))
253 Res = 0;
254
255 return Instruction::CastOps(Res);
256}
257
258/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
259/// in any code being generated. It does not require codegen if V is simple
260/// enough or if the cast can be folded into other casts.
261bool InstCombiner::ValueRequiresCast(Instruction::CastOps opcode,const Value *V,
262 const Type *Ty) {
263 if (V->getType() == Ty || isa<Constant>(V)) return false;
264
265 // If this is another cast that can be eliminated, it isn't codegen either.
266 if (const CastInst *CI = dyn_cast<CastInst>(V))
267 if (isEliminableCastPair(CI, opcode, Ty, TD))
268 return false;
269 return true;
270}
271
272
273/// @brief Implement the transforms common to all CastInst visitors.
274Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
275 Value *Src = CI.getOperand(0);
276
277 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
278 // eliminate it now.
279 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
280 if (Instruction::CastOps opc =
281 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
282 // The first cast (CSrc) is eliminable so we need to fix up or replace
283 // the second cast (CI). CSrc will then have a good chance of being dead.
284 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
285 }
286 }
287
288 // If we are casting a select then fold the cast into the select
289 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
290 if (Instruction *NV = FoldOpIntoSelect(CI, SI))
291 return NV;
292
293 // If we are casting a PHI then fold the cast into the PHI
294 if (isa<PHINode>(Src)) {
295 // We don't do this if this would create a PHI node with an illegal type if
296 // it is currently legal.
297 if (!isa<IntegerType>(Src->getType()) ||
298 !isa<IntegerType>(CI.getType()) ||
299 ShouldChangeType(CI.getType(), Src->getType()))
300 if (Instruction *NV = FoldOpIntoPhi(CI))
301 return NV;
302 }
303
304 return 0;
305}
306
Chris Lattner75215c92010-01-10 00:58:42 +0000307/// CanEvaluateTruncated - Return true if we can evaluate the specified
308/// expression tree as type Ty instead of its larger type, and arrive with the
309/// same value. This is used by code that tries to eliminate truncates.
310///
311/// Ty will always be a type smaller than V. We should return true if trunc(V)
312/// can be computed by computing V in the smaller type. If V is an instruction,
313/// then trunc(inst(x,y)) can be computed as inst(trunc(x),trunc(y)), which only
314/// makes sense if x and y can be efficiently truncated.
315///
Chris Lattner8cf4f6f2010-01-11 02:43:35 +0000316/// This function works on both vectors and scalars.
317///
Chris Lattner75215c92010-01-10 00:58:42 +0000318static bool CanEvaluateTruncated(Value *V, const Type *Ty) {
319 // We can always evaluate constants in another type.
320 if (isa<Constant>(V))
321 return true;
Chris Lattner68c6e892010-01-05 23:00:30 +0000322
Chris Lattner75215c92010-01-10 00:58:42 +0000323 Instruction *I = dyn_cast<Instruction>(V);
324 if (!I) return false;
325
326 const Type *OrigTy = V->getType();
327
Chris Lattnera958cbf2010-01-11 22:45:25 +0000328 // If this is an extension from the dest type, we can eliminate it, even if it
329 // has multiple uses.
330 // FIXME: This is currently disabled until codegen can handle this without
331 // pessimizing code, PR5997.
332 if (0 && (isa<ZExtInst>(I) || isa<SExtInst>(I)) &&
Chris Lattner75215c92010-01-10 00:58:42 +0000333 I->getOperand(0)->getType() == Ty)
334 return true;
335
336 // We can't extend or shrink something that has multiple uses: doing so would
337 // require duplicating the instruction in general, which isn't profitable.
338 if (!I->hasOneUse()) return false;
339
340 unsigned Opc = I->getOpcode();
341 switch (Opc) {
342 case Instruction::Add:
343 case Instruction::Sub:
344 case Instruction::Mul:
345 case Instruction::And:
346 case Instruction::Or:
347 case Instruction::Xor:
348 // These operators can all arbitrarily be extended or truncated.
349 return CanEvaluateTruncated(I->getOperand(0), Ty) &&
350 CanEvaluateTruncated(I->getOperand(1), Ty);
351
352 case Instruction::UDiv:
353 case Instruction::URem: {
354 // UDiv and URem can be truncated if all the truncated bits are zero.
355 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
356 uint32_t BitWidth = Ty->getScalarSizeInBits();
357 if (BitWidth < OrigBitWidth) {
358 APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
359 if (MaskedValueIsZero(I->getOperand(0), Mask) &&
360 MaskedValueIsZero(I->getOperand(1), Mask)) {
361 return CanEvaluateTruncated(I->getOperand(0), Ty) &&
362 CanEvaluateTruncated(I->getOperand(1), Ty);
363 }
364 }
365 break;
366 }
367 case Instruction::Shl:
368 // If we are truncating the result of this SHL, and if it's a shift of a
369 // constant amount, we can always perform a SHL in a smaller type.
370 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
371 uint32_t BitWidth = Ty->getScalarSizeInBits();
372 if (CI->getLimitedValue(BitWidth) < BitWidth)
373 return CanEvaluateTruncated(I->getOperand(0), Ty);
374 }
375 break;
376 case Instruction::LShr:
377 // If this is a truncate of a logical shr, we can truncate it to a smaller
378 // lshr iff we know that the bits we would otherwise be shifting in are
379 // already zeros.
380 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
381 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
382 uint32_t BitWidth = Ty->getScalarSizeInBits();
383 if (MaskedValueIsZero(I->getOperand(0),
384 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
385 CI->getLimitedValue(BitWidth) < BitWidth) {
386 return CanEvaluateTruncated(I->getOperand(0), Ty);
387 }
388 }
389 break;
390 case Instruction::Trunc:
391 // trunc(trunc(x)) -> trunc(x)
392 return true;
393 case Instruction::Select: {
394 SelectInst *SI = cast<SelectInst>(I);
395 return CanEvaluateTruncated(SI->getTrueValue(), Ty) &&
396 CanEvaluateTruncated(SI->getFalseValue(), Ty);
397 }
398 case Instruction::PHI: {
399 // We can change a phi if we can change all operands. Note that we never
400 // get into trouble with cyclic PHIs here because we only consider
401 // instructions with a single use.
402 PHINode *PN = cast<PHINode>(I);
403 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
404 if (!CanEvaluateTruncated(PN->getIncomingValue(i), Ty))
405 return false;
406 return true;
407 }
408 default:
409 // TODO: Can handle more cases here.
410 break;
411 }
412
413 return false;
414}
415
416Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattnerd84dfa42010-01-10 01:00:46 +0000417 if (Instruction *Result = commonCastTransforms(CI))
Chris Lattner75215c92010-01-10 00:58:42 +0000418 return Result;
419
Chris Lattnerd84dfa42010-01-10 01:00:46 +0000420 // See if we can simplify any instructions used by the input whose sole
421 // purpose is to compute bits we don't care about.
422 if (SimplifyDemandedInstructionBits(CI))
423 return &CI;
424
Chris Lattner75215c92010-01-10 00:58:42 +0000425 Value *Src = CI.getOperand(0);
426 const Type *DestTy = CI.getType(), *SrcTy = Src->getType();
427
428 // Attempt to truncate the entire input expression tree to the destination
429 // type. Only do this if the dest type is a simple type, don't convert the
Chris Lattner80f43d32010-01-04 07:53:58 +0000430 // expression tree to something weird like i93 unless the source is also
431 // strange.
Chris Lattner75215c92010-01-10 00:58:42 +0000432 if ((isa<VectorType>(DestTy) || ShouldChangeType(SrcTy, DestTy)) &&
433 CanEvaluateTruncated(Src, DestTy)) {
Chris Lattnere0e4cc72010-01-06 01:56:21 +0000434
Chris Lattner80f43d32010-01-04 07:53:58 +0000435 // If this cast is a truncate, evaluting in a different type always
Chris Lattner68c6e892010-01-05 23:00:30 +0000436 // eliminates the cast, so it is always a win.
Chris Lattner075f6922010-01-07 23:41:00 +0000437 DEBUG(dbgs() << "ICE: EvaluateInDifferentType converting expression type"
438 " to avoid cast: " << CI);
439 Value *Res = EvaluateInDifferentType(Src, DestTy, false);
440 assert(Res->getType() == DestTy);
441 return ReplaceInstUsesWith(CI, Res);
442 }
Chris Lattner80f43d32010-01-04 07:53:58 +0000443
Chris Lattner7a34d6c2010-01-05 22:21:18 +0000444 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0), likewise for vector.
445 if (DestTy->getScalarSizeInBits() == 1) {
Chris Lattner80f43d32010-01-04 07:53:58 +0000446 Constant *One = ConstantInt::get(Src->getType(), 1);
447 Src = Builder->CreateAnd(Src, One, "tmp");
448 Value *Zero = Constant::getNullValue(Src->getType());
449 return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
450 }
451
Chris Lattner80f43d32010-01-04 07:53:58 +0000452 return 0;
453}
454
455/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
456/// in order to eliminate the icmp.
457Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
458 bool DoXform) {
459 // If we are just checking for a icmp eq of a single bit and zext'ing it
460 // to an integer, then shift the bit to the appropriate place and then
461 // cast to integer to avoid the comparison.
462 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
463 const APInt &Op1CV = Op1C->getValue();
464
465 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
466 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
467 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
468 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
469 if (!DoXform) return ICI;
470
471 Value *In = ICI->getOperand(0);
472 Value *Sh = ConstantInt::get(In->getType(),
473 In->getType()->getScalarSizeInBits()-1);
474 In = Builder->CreateLShr(In, Sh, In->getName()+".lobit");
475 if (In->getType() != CI.getType())
476 In = Builder->CreateIntCast(In, CI.getType(), false/*ZExt*/, "tmp");
477
478 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
479 Constant *One = ConstantInt::get(In->getType(), 1);
480 In = Builder->CreateXor(In, One, In->getName()+".not");
481 }
482
483 return ReplaceInstUsesWith(CI, In);
484 }
485
486
487
488 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
489 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
490 // zext (X == 1) to i32 --> X iff X has only the low bit set.
491 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
492 // zext (X != 0) to i32 --> X iff X has only the low bit set.
493 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
494 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
495 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
496 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
497 // This only works for EQ and NE
498 ICI->isEquality()) {
499 // If Op1C some other power of two, convert:
500 uint32_t BitWidth = Op1C->getType()->getBitWidth();
501 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
502 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
503 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
504
505 APInt KnownZeroMask(~KnownZero);
506 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
507 if (!DoXform) return ICI;
508
509 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
510 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
511 // (X&4) == 2 --> false
512 // (X&4) != 2 --> true
513 Constant *Res = ConstantInt::get(Type::getInt1Ty(CI.getContext()),
514 isNE);
515 Res = ConstantExpr::getZExt(Res, CI.getType());
516 return ReplaceInstUsesWith(CI, Res);
517 }
518
519 uint32_t ShiftAmt = KnownZeroMask.logBase2();
520 Value *In = ICI->getOperand(0);
521 if (ShiftAmt) {
522 // Perform a logical shr by shiftamt.
523 // Insert the shift to put the result in the low bit.
524 In = Builder->CreateLShr(In, ConstantInt::get(In->getType(),ShiftAmt),
525 In->getName()+".lobit");
526 }
527
528 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
529 Constant *One = ConstantInt::get(In->getType(), 1);
530 In = Builder->CreateXor(In, One, "tmp");
531 }
532
533 if (CI.getType() == In->getType())
534 return ReplaceInstUsesWith(CI, In);
535 else
536 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
537 }
538 }
539 }
540
541 // icmp ne A, B is equal to xor A, B when A and B only really have one bit.
542 // It is also profitable to transform icmp eq into not(xor(A, B)) because that
543 // may lead to additional simplifications.
544 if (ICI->isEquality() && CI.getType() == ICI->getOperand(0)->getType()) {
545 if (const IntegerType *ITy = dyn_cast<IntegerType>(CI.getType())) {
546 uint32_t BitWidth = ITy->getBitWidth();
547 Value *LHS = ICI->getOperand(0);
548 Value *RHS = ICI->getOperand(1);
549
550 APInt KnownZeroLHS(BitWidth, 0), KnownOneLHS(BitWidth, 0);
551 APInt KnownZeroRHS(BitWidth, 0), KnownOneRHS(BitWidth, 0);
552 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
553 ComputeMaskedBits(LHS, TypeMask, KnownZeroLHS, KnownOneLHS);
554 ComputeMaskedBits(RHS, TypeMask, KnownZeroRHS, KnownOneRHS);
555
556 if (KnownZeroLHS == KnownZeroRHS && KnownOneLHS == KnownOneRHS) {
557 APInt KnownBits = KnownZeroLHS | KnownOneLHS;
558 APInt UnknownBit = ~KnownBits;
559 if (UnknownBit.countPopulation() == 1) {
560 if (!DoXform) return ICI;
561
562 Value *Result = Builder->CreateXor(LHS, RHS);
563
564 // Mask off any bits that are set and won't be shifted away.
565 if (KnownOneLHS.uge(UnknownBit))
566 Result = Builder->CreateAnd(Result,
567 ConstantInt::get(ITy, UnknownBit));
568
569 // Shift the bit we're testing down to the lsb.
570 Result = Builder->CreateLShr(
571 Result, ConstantInt::get(ITy, UnknownBit.countTrailingZeros()));
572
573 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
574 Result = Builder->CreateXor(Result, ConstantInt::get(ITy, 1));
575 Result->takeName(ICI);
576 return ReplaceInstUsesWith(CI, Result);
577 }
578 }
579 }
580 }
581
582 return 0;
583}
584
Chris Lattner75215c92010-01-10 00:58:42 +0000585/// CanEvaluateZExtd - Determine if the specified value can be computed in the
Chris Lattner8cf4f6f2010-01-11 02:43:35 +0000586/// specified wider type and produce the same low bits. If not, return false.
587///
Chris Lattner789162a2010-01-11 03:32:00 +0000588/// If this function returns true, it can also return a non-zero number of bits
589/// (in BitsToClear) which indicates that the value it computes is correct for
590/// the zero extend, but that the additional BitsToClear bits need to be zero'd
591/// out. For example, to promote something like:
592///
593/// %B = trunc i64 %A to i32
594/// %C = lshr i32 %B, 8
595/// %E = zext i32 %C to i64
596///
597/// CanEvaluateZExtd for the 'lshr' will return true, and BitsToClear will be
598/// set to 8 to indicate that the promoted value needs to have bits 24-31
599/// cleared in addition to bits 32-63. Since an 'and' will be generated to
600/// clear the top bits anyway, doing this has no extra cost.
601///
Chris Lattner8cf4f6f2010-01-11 02:43:35 +0000602/// This function works on both vectors and scalars.
Chris Lattner789162a2010-01-11 03:32:00 +0000603static bool CanEvaluateZExtd(Value *V, const Type *Ty, unsigned &BitsToClear) {
604 BitsToClear = 0;
Chris Lattner9e390dd2010-01-10 02:50:04 +0000605 if (isa<Constant>(V))
606 return true;
Chris Lattner75215c92010-01-10 00:58:42 +0000607
608 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattner9e390dd2010-01-10 02:50:04 +0000609 if (!I) return false;
Chris Lattner75215c92010-01-10 00:58:42 +0000610
611 // If the input is a truncate from the destination type, we can trivially
Chris Lattnera958cbf2010-01-11 22:45:25 +0000612 // eliminate it, even if it has multiple uses.
613 // FIXME: This is currently disabled until codegen can handle this without
614 // pessimizing code, PR5997.
615 if (0 && isa<TruncInst>(I) && I->getOperand(0)->getType() == Ty)
Chris Lattner9e390dd2010-01-10 02:50:04 +0000616 return true;
Chris Lattner75215c92010-01-10 00:58:42 +0000617
618 // We can't extend or shrink something that has multiple uses: doing so would
619 // require duplicating the instruction in general, which isn't profitable.
Chris Lattner9e390dd2010-01-10 02:50:04 +0000620 if (!I->hasOneUse()) return false;
Chris Lattner75215c92010-01-10 00:58:42 +0000621
Chris Lattner789162a2010-01-11 03:32:00 +0000622 unsigned Opc = I->getOpcode(), Tmp;
Chris Lattner75215c92010-01-10 00:58:42 +0000623 switch (Opc) {
Chris Lattner9ee947c2010-01-10 20:25:54 +0000624 case Instruction::ZExt: // zext(zext(x)) -> zext(x).
625 case Instruction::SExt: // zext(sext(x)) -> sext(x).
626 case Instruction::Trunc: // zext(trunc(x)) -> trunc(x) or zext(x)
627 return true;
Chris Lattner75215c92010-01-10 00:58:42 +0000628 case Instruction::And:
Chris Lattner75215c92010-01-10 00:58:42 +0000629 case Instruction::Or:
630 case Instruction::Xor:
Chris Lattner75215c92010-01-10 00:58:42 +0000631 case Instruction::Add:
632 case Instruction::Sub:
633 case Instruction::Mul:
Chris Lattnerd26c9e12010-01-10 02:22:12 +0000634 case Instruction::Shl:
Chris Lattner789162a2010-01-11 03:32:00 +0000635 if (!CanEvaluateZExtd(I->getOperand(0), Ty, BitsToClear) ||
636 !CanEvaluateZExtd(I->getOperand(1), Ty, Tmp))
637 return false;
638 // These can all be promoted if neither operand has 'bits to clear'.
639 if (BitsToClear == 0 && Tmp == 0)
640 return true;
Chris Lattner75215c92010-01-10 00:58:42 +0000641
Chris Lattner7acc4b12010-01-11 04:05:13 +0000642 // If the operation is an AND/OR/XOR and the bits to clear are zero in the
643 // other side, BitsToClear is ok.
644 if (Tmp == 0 &&
645 (Opc == Instruction::And || Opc == Instruction::Or ||
646 Opc == Instruction::Xor)) {
647 // We use MaskedValueIsZero here for generality, but the case we care
648 // about the most is constant RHS.
649 unsigned VSize = V->getType()->getScalarSizeInBits();
650 if (MaskedValueIsZero(I->getOperand(1),
651 APInt::getHighBitsSet(VSize, BitsToClear)))
652 return true;
653 }
654
655 // Otherwise, we don't know how to analyze this BitsToClear case yet.
Chris Lattner789162a2010-01-11 03:32:00 +0000656 return false;
Chris Lattnerd26c9e12010-01-10 02:22:12 +0000657
Chris Lattner789162a2010-01-11 03:32:00 +0000658 case Instruction::LShr:
659 // We can promote lshr(x, cst) if we can promote x. This requires the
660 // ultimate 'and' to clear out the high zero bits we're clearing out though.
661 if (ConstantInt *Amt = dyn_cast<ConstantInt>(I->getOperand(1))) {
662 if (!CanEvaluateZExtd(I->getOperand(0), Ty, BitsToClear))
663 return false;
664 BitsToClear += Amt->getZExtValue();
665 if (BitsToClear > V->getType()->getScalarSizeInBits())
666 BitsToClear = V->getType()->getScalarSizeInBits();
667 return true;
668 }
669 // Cannot promote variable LSHR.
670 return false;
Chris Lattner75215c92010-01-10 00:58:42 +0000671 case Instruction::Select:
Chris Lattner789162a2010-01-11 03:32:00 +0000672 if (!CanEvaluateZExtd(I->getOperand(1), Ty, Tmp) ||
673 !CanEvaluateZExtd(I->getOperand(2), Ty, BitsToClear) ||
Chris Lattner7acc4b12010-01-11 04:05:13 +0000674 // TODO: If important, we could handle the case when the BitsToClear are
675 // known zero in the disagreeing side.
Chris Lattner789162a2010-01-11 03:32:00 +0000676 Tmp != BitsToClear)
677 return false;
678 return true;
Chris Lattner75215c92010-01-10 00:58:42 +0000679
680 case Instruction::PHI: {
681 // We can change a phi if we can change all operands. Note that we never
682 // get into trouble with cyclic PHIs here because we only consider
683 // instructions with a single use.
684 PHINode *PN = cast<PHINode>(I);
Chris Lattner789162a2010-01-11 03:32:00 +0000685 if (!CanEvaluateZExtd(PN->getIncomingValue(0), Ty, BitsToClear))
686 return false;
Chris Lattner9e390dd2010-01-10 02:50:04 +0000687 for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i)
Chris Lattner789162a2010-01-11 03:32:00 +0000688 if (!CanEvaluateZExtd(PN->getIncomingValue(i), Ty, Tmp) ||
Chris Lattner7acc4b12010-01-11 04:05:13 +0000689 // TODO: If important, we could handle the case when the BitsToClear
690 // are known zero in the disagreeing input.
Chris Lattner789162a2010-01-11 03:32:00 +0000691 Tmp != BitsToClear)
692 return false;
Chris Lattner9e390dd2010-01-10 02:50:04 +0000693 return true;
Chris Lattner75215c92010-01-10 00:58:42 +0000694 }
695 default:
696 // TODO: Can handle more cases here.
Chris Lattner9e390dd2010-01-10 02:50:04 +0000697 return false;
Chris Lattner75215c92010-01-10 00:58:42 +0000698 }
699}
700
Chris Lattner80f43d32010-01-04 07:53:58 +0000701Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Chris Lattner5324d802010-01-10 02:39:31 +0000702 // If this zero extend is only used by a truncate, let the truncate by
703 // eliminated before we try to optimize this zext.
704 if (CI.hasOneUse() && isa<TruncInst>(CI.use_back()))
705 return 0;
706
Chris Lattner80f43d32010-01-04 07:53:58 +0000707 // If one of the common conversion will work, do it.
Chris Lattnerd84dfa42010-01-10 01:00:46 +0000708 if (Instruction *Result = commonCastTransforms(CI))
Chris Lattner80f43d32010-01-04 07:53:58 +0000709 return Result;
710
Chris Lattnerd84dfa42010-01-10 01:00:46 +0000711 // See if we can simplify any instructions used by the input whose sole
712 // purpose is to compute bits we don't care about.
713 if (SimplifyDemandedInstructionBits(CI))
714 return &CI;
Chris Lattner75215c92010-01-10 00:58:42 +0000715
Chris Lattnerd84dfa42010-01-10 01:00:46 +0000716 Value *Src = CI.getOperand(0);
Chris Lattner75215c92010-01-10 00:58:42 +0000717 const Type *SrcTy = Src->getType(), *DestTy = CI.getType();
718
719 // Attempt to extend the entire input expression tree to the destination
720 // type. Only do this if the dest type is a simple type, don't convert the
721 // expression tree to something weird like i93 unless the source is also
722 // strange.
Chris Lattner789162a2010-01-11 03:32:00 +0000723 unsigned BitsToClear;
Chris Lattner9e390dd2010-01-10 02:50:04 +0000724 if ((isa<VectorType>(DestTy) || ShouldChangeType(SrcTy, DestTy)) &&
Chris Lattner789162a2010-01-11 03:32:00 +0000725 CanEvaluateZExtd(Src, DestTy, BitsToClear)) {
726 assert(BitsToClear < SrcTy->getScalarSizeInBits() &&
727 "Unreasonable BitsToClear");
728
Chris Lattner5324d802010-01-10 02:39:31 +0000729 // Okay, we can transform this! Insert the new expression now.
730 DEBUG(dbgs() << "ICE: EvaluateInDifferentType converting expression type"
731 " to avoid zero extend: " << CI);
732 Value *Res = EvaluateInDifferentType(Src, DestTy, false);
733 assert(Res->getType() == DestTy);
734
Chris Lattner789162a2010-01-11 03:32:00 +0000735 uint32_t SrcBitsKept = SrcTy->getScalarSizeInBits()-BitsToClear;
736 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
737
Chris Lattner5324d802010-01-10 02:39:31 +0000738 // If the high bits are already filled with zeros, just replace this
739 // cast with the result.
Chris Lattner9e390dd2010-01-10 02:50:04 +0000740 if (MaskedValueIsZero(Res, APInt::getHighBitsSet(DestBitSize,
Chris Lattner789162a2010-01-11 03:32:00 +0000741 DestBitSize-SrcBitsKept)))
Chris Lattner5324d802010-01-10 02:39:31 +0000742 return ReplaceInstUsesWith(CI, Res);
743
744 // We need to emit an AND to clear the high bits.
Chris Lattner9ee947c2010-01-10 20:25:54 +0000745 Constant *C = ConstantInt::get(Res->getType(),
Chris Lattner789162a2010-01-11 03:32:00 +0000746 APInt::getLowBitsSet(DestBitSize, SrcBitsKept));
Chris Lattner5324d802010-01-10 02:39:31 +0000747 return BinaryOperator::CreateAnd(Res, C);
Chris Lattner75215c92010-01-10 00:58:42 +0000748 }
Chris Lattner80f43d32010-01-04 07:53:58 +0000749
750 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
751 // types and if the sizes are just right we can convert this into a logical
752 // 'and' which will be much cheaper than the pair of casts.
753 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
Chris Lattnerf4fb9112010-01-10 07:08:30 +0000754 // TODO: Subsume this into EvaluateInDifferentType.
755
Chris Lattner80f43d32010-01-04 07:53:58 +0000756 // Get the sizes of the types involved. We know that the intermediate type
757 // will be smaller than A or C, but don't know the relation between A and C.
758 Value *A = CSrc->getOperand(0);
759 unsigned SrcSize = A->getType()->getScalarSizeInBits();
760 unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
761 unsigned DstSize = CI.getType()->getScalarSizeInBits();
762 // If we're actually extending zero bits, then if
763 // SrcSize < DstSize: zext(a & mask)
764 // SrcSize == DstSize: a & mask
765 // SrcSize > DstSize: trunc(a) & mask
766 if (SrcSize < DstSize) {
767 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
768 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
769 Value *And = Builder->CreateAnd(A, AndConst, CSrc->getName()+".mask");
770 return new ZExtInst(And, CI.getType());
771 }
772
773 if (SrcSize == DstSize) {
774 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
775 return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
776 AndValue));
777 }
778 if (SrcSize > DstSize) {
779 Value *Trunc = Builder->CreateTrunc(A, CI.getType(), "tmp");
780 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
781 return BinaryOperator::CreateAnd(Trunc,
782 ConstantInt::get(Trunc->getType(),
Chris Lattnerf4fb9112010-01-10 07:08:30 +0000783 AndValue));
Chris Lattner80f43d32010-01-04 07:53:58 +0000784 }
785 }
786
787 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
788 return transformZExtICmp(ICI, CI);
789
790 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
791 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
792 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
793 // of the (zext icmp) will be transformed.
794 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
795 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
796 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
797 (transformZExtICmp(LHS, CI, false) ||
798 transformZExtICmp(RHS, CI, false))) {
799 Value *LCast = Builder->CreateZExt(LHS, CI.getType(), LHS->getName());
800 Value *RCast = Builder->CreateZExt(RHS, CI.getType(), RHS->getName());
801 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
802 }
803 }
804
805 // zext(trunc(t) & C) -> (t & zext(C)).
806 if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
807 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
808 if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
809 Value *TI0 = TI->getOperand(0);
810 if (TI0->getType() == CI.getType())
811 return
812 BinaryOperator::CreateAnd(TI0,
813 ConstantExpr::getZExt(C, CI.getType()));
814 }
815
816 // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
817 if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
818 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
819 if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
820 if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
821 And->getOperand(1) == C)
822 if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
823 Value *TI0 = TI->getOperand(0);
824 if (TI0->getType() == CI.getType()) {
825 Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
826 Value *NewAnd = Builder->CreateAnd(TI0, ZC, "tmp");
827 return BinaryOperator::CreateXor(NewAnd, ZC);
828 }
829 }
830
Chris Lattner718bf3f2010-01-05 21:04:47 +0000831 // zext (xor i1 X, true) to i32 --> xor (zext i1 X to i32), 1
832 Value *X;
Chris Lattner49bdfef2010-01-05 21:11:17 +0000833 if (SrcI && SrcI->hasOneUse() && SrcI->getType()->isInteger(1) &&
834 match(SrcI, m_Not(m_Value(X))) &&
Chris Lattner718bf3f2010-01-05 21:04:47 +0000835 (!X->hasOneUse() || !isa<CmpInst>(X))) {
836 Value *New = Builder->CreateZExt(X, CI.getType());
837 return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
838 }
839
Chris Lattner80f43d32010-01-04 07:53:58 +0000840 return 0;
841}
842
Chris Lattner75215c92010-01-10 00:58:42 +0000843/// CanEvaluateSExtd - Return true if we can take the specified value
844/// and return it as type Ty without inserting any new casts and without
845/// changing the value of the common low bits. This is used by code that tries
846/// to promote integer operations to a wider types will allow us to eliminate
847/// the extension.
848///
Chris Lattneraa9c8942010-01-10 07:57:20 +0000849/// This function works on both vectors and scalars.
Chris Lattner75215c92010-01-10 00:58:42 +0000850///
Chris Lattner8cf4f6f2010-01-11 02:43:35 +0000851static bool CanEvaluateSExtd(Value *V, const Type *Ty) {
Chris Lattner75215c92010-01-10 00:58:42 +0000852 assert(V->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits() &&
853 "Can't sign extend type to a smaller type");
Chris Lattneraa9c8942010-01-10 07:57:20 +0000854 // If this is a constant, it can be trivially promoted.
855 if (isa<Constant>(V))
856 return true;
Chris Lattner75215c92010-01-10 00:58:42 +0000857
858 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattneraa9c8942010-01-10 07:57:20 +0000859 if (!I) return false;
Chris Lattner75215c92010-01-10 00:58:42 +0000860
Chris Lattnera958cbf2010-01-11 22:45:25 +0000861 // If this is a truncate from the dest type, we can trivially eliminate it,
862 // even if it has multiple uses.
863 // FIXME: This is currently disabled until codegen can handle this without
864 // pessimizing code, PR5997.
865 if (0 && isa<TruncInst>(I) && I->getOperand(0)->getType() == Ty)
Chris Lattneraa9c8942010-01-10 07:57:20 +0000866 return true;
Chris Lattner75215c92010-01-10 00:58:42 +0000867
868 // We can't extend or shrink something that has multiple uses: doing so would
869 // require duplicating the instruction in general, which isn't profitable.
Chris Lattneraa9c8942010-01-10 07:57:20 +0000870 if (!I->hasOneUse()) return false;
Chris Lattner75215c92010-01-10 00:58:42 +0000871
Chris Lattneraa9c8942010-01-10 07:57:20 +0000872 switch (I->getOpcode()) {
Chris Lattner11ea8122010-01-10 20:30:41 +0000873 case Instruction::SExt: // sext(sext(x)) -> sext(x)
874 case Instruction::ZExt: // sext(zext(x)) -> zext(x)
875 case Instruction::Trunc: // sext(trunc(x)) -> trunc(x) or sext(x)
876 return true;
Chris Lattner75215c92010-01-10 00:58:42 +0000877 case Instruction::And:
878 case Instruction::Or:
879 case Instruction::Xor:
Chris Lattner75215c92010-01-10 00:58:42 +0000880 case Instruction::Add:
881 case Instruction::Sub:
Chris Lattner75215c92010-01-10 00:58:42 +0000882 case Instruction::Mul:
Chris Lattneraa9c8942010-01-10 07:57:20 +0000883 // These operators can all arbitrarily be extended if their inputs can.
Chris Lattner8cf4f6f2010-01-11 02:43:35 +0000884 return CanEvaluateSExtd(I->getOperand(0), Ty) &&
885 CanEvaluateSExtd(I->getOperand(1), Ty);
Chris Lattner75215c92010-01-10 00:58:42 +0000886
887 //case Instruction::Shl: TODO
888 //case Instruction::LShr: TODO
Chris Lattner75215c92010-01-10 00:58:42 +0000889
Chris Lattneraa9c8942010-01-10 07:57:20 +0000890 case Instruction::Select:
Chris Lattner8cf4f6f2010-01-11 02:43:35 +0000891 return CanEvaluateSExtd(I->getOperand(1), Ty) &&
892 CanEvaluateSExtd(I->getOperand(2), Ty);
Chris Lattner9ee947c2010-01-10 20:25:54 +0000893
Chris Lattner75215c92010-01-10 00:58:42 +0000894 case Instruction::PHI: {
895 // We can change a phi if we can change all operands. Note that we never
896 // get into trouble with cyclic PHIs here because we only consider
897 // instructions with a single use.
898 PHINode *PN = cast<PHINode>(I);
Chris Lattner9ee947c2010-01-10 20:25:54 +0000899 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
Chris Lattner8cf4f6f2010-01-11 02:43:35 +0000900 if (!CanEvaluateSExtd(PN->getIncomingValue(i), Ty)) return false;
Chris Lattneraa9c8942010-01-10 07:57:20 +0000901 return true;
Chris Lattner75215c92010-01-10 00:58:42 +0000902 }
903 default:
904 // TODO: Can handle more cases here.
905 break;
906 }
907
Chris Lattneraa9c8942010-01-10 07:57:20 +0000908 return false;
Chris Lattner75215c92010-01-10 00:58:42 +0000909}
910
Chris Lattner80f43d32010-01-04 07:53:58 +0000911Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattner5324d802010-01-10 02:39:31 +0000912 // If this sign extend is only used by a truncate, let the truncate by
913 // eliminated before we try to optimize this zext.
914 if (CI.hasOneUse() && isa<TruncInst>(CI.use_back()))
915 return 0;
916
Chris Lattnerd84dfa42010-01-10 01:00:46 +0000917 if (Instruction *I = commonCastTransforms(CI))
Chris Lattner80f43d32010-01-04 07:53:58 +0000918 return I;
919
Chris Lattnerd84dfa42010-01-10 01:00:46 +0000920 // See if we can simplify any instructions used by the input whose sole
921 // purpose is to compute bits we don't care about.
922 if (SimplifyDemandedInstructionBits(CI))
923 return &CI;
924
Chris Lattner80f43d32010-01-04 07:53:58 +0000925 Value *Src = CI.getOperand(0);
Chris Lattner75215c92010-01-10 00:58:42 +0000926 const Type *SrcTy = Src->getType(), *DestTy = CI.getType();
927
Chris Lattner80f43d32010-01-04 07:53:58 +0000928 // Canonicalize sign-extend from i1 to a select.
Benjamin Kramer11acaa32010-01-05 20:07:06 +0000929 if (Src->getType()->isInteger(1))
Chris Lattner80f43d32010-01-04 07:53:58 +0000930 return SelectInst::Create(Src,
931 Constant::getAllOnesValue(CI.getType()),
932 Constant::getNullValue(CI.getType()));
Chris Lattner75215c92010-01-10 00:58:42 +0000933
934 // Attempt to extend the entire input expression tree to the destination
935 // type. Only do this if the dest type is a simple type, don't convert the
936 // expression tree to something weird like i93 unless the source is also
937 // strange.
Chris Lattneraa9c8942010-01-10 07:57:20 +0000938 if ((isa<VectorType>(DestTy) || ShouldChangeType(SrcTy, DestTy)) &&
Chris Lattner8cf4f6f2010-01-11 02:43:35 +0000939 CanEvaluateSExtd(Src, DestTy)) {
Chris Lattnerdde5ee52010-01-10 07:40:50 +0000940 // Okay, we can transform this! Insert the new expression now.
941 DEBUG(dbgs() << "ICE: EvaluateInDifferentType converting expression type"
942 " to avoid sign extend: " << CI);
943 Value *Res = EvaluateInDifferentType(Src, DestTy, true);
944 assert(Res->getType() == DestTy);
945
Chris Lattner75215c92010-01-10 00:58:42 +0000946 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
947 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
Chris Lattnerdde5ee52010-01-10 07:40:50 +0000948
949 // If the high bits are already filled with sign bit, just replace this
950 // cast with the result.
Chris Lattneraa9c8942010-01-10 07:57:20 +0000951 if (ComputeNumSignBits(Res) > DestBitSize - SrcBitSize)
Chris Lattnerdde5ee52010-01-10 07:40:50 +0000952 return ReplaceInstUsesWith(CI, Res);
Chris Lattner75215c92010-01-10 00:58:42 +0000953
Chris Lattnerdde5ee52010-01-10 07:40:50 +0000954 // We need to emit a shl + ashr to do the sign extend.
955 Value *ShAmt = ConstantInt::get(DestTy, DestBitSize-SrcBitSize);
956 return BinaryOperator::CreateAShr(Builder->CreateShl(Res, ShAmt, "sext"),
957 ShAmt);
Chris Lattner75215c92010-01-10 00:58:42 +0000958 }
Chris Lattner80f43d32010-01-04 07:53:58 +0000959
960 // If the input is a shl/ashr pair of a same constant, then this is a sign
961 // extension from a smaller value. If we could trust arbitrary bitwidth
962 // integers, we could turn this into a truncate to the smaller bit and then
963 // use a sext for the whole extension. Since we don't, look deeper and check
964 // for a truncate. If the source and dest are the same type, eliminate the
965 // trunc and extend and just do shifts. For example, turn:
966 // %a = trunc i32 %i to i8
967 // %b = shl i8 %a, 6
968 // %c = ashr i8 %b, 6
969 // %d = sext i8 %c to i32
970 // into:
971 // %a = shl i32 %i, 30
972 // %d = ashr i32 %a, 30
973 Value *A = 0;
Chris Lattner4f379782010-01-10 01:04:31 +0000974 // TODO: Eventually this could be subsumed by EvaluateInDifferentType.
Chris Lattner80f43d32010-01-04 07:53:58 +0000975 ConstantInt *BA = 0, *CA = 0;
Chris Lattner4f379782010-01-10 01:04:31 +0000976 if (match(Src, m_AShr(m_Shl(m_Trunc(m_Value(A)), m_ConstantInt(BA)),
Chris Lattner80f43d32010-01-04 07:53:58 +0000977 m_ConstantInt(CA))) &&
Chris Lattner4f379782010-01-10 01:04:31 +0000978 BA == CA && A->getType() == CI.getType()) {
979 unsigned MidSize = Src->getType()->getScalarSizeInBits();
980 unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
981 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
982 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
983 A = Builder->CreateShl(A, ShAmtV, CI.getName());
984 return BinaryOperator::CreateAShr(A, ShAmtV);
Chris Lattner80f43d32010-01-04 07:53:58 +0000985 }
986
987 return 0;
988}
989
990
991/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
992/// in the specified FP type without changing its value.
993static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
994 bool losesInfo;
995 APFloat F = CFP->getValueAPF();
996 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
997 if (!losesInfo)
998 return ConstantFP::get(CFP->getContext(), F);
999 return 0;
1000}
1001
1002/// LookThroughFPExtensions - If this is an fp extension instruction, look
1003/// through it until we get the source value.
1004static Value *LookThroughFPExtensions(Value *V) {
1005 if (Instruction *I = dyn_cast<Instruction>(V))
1006 if (I->getOpcode() == Instruction::FPExt)
1007 return LookThroughFPExtensions(I->getOperand(0));
1008
1009 // If this value is a constant, return the constant in the smallest FP type
1010 // that can accurately represent it. This allows us to turn
1011 // (float)((double)X+2.0) into x+2.0f.
1012 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
1013 if (CFP->getType() == Type::getPPC_FP128Ty(V->getContext()))
1014 return V; // No constant folding of this.
1015 // See if the value can be truncated to float and then reextended.
1016 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
1017 return V;
Benjamin Kramerf0127052010-01-05 13:12:22 +00001018 if (CFP->getType()->isDoubleTy())
Chris Lattner80f43d32010-01-04 07:53:58 +00001019 return V; // Won't shrink.
1020 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
1021 return V;
1022 // Don't try to shrink to various long double types.
1023 }
1024
1025 return V;
1026}
1027
1028Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
1029 if (Instruction *I = commonCastTransforms(CI))
1030 return I;
1031
1032 // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
1033 // smaller than the destination type, we can eliminate the truncate by doing
1034 // the add as the smaller type. This applies to fadd/fsub/fmul/fdiv as well
1035 // as many builtins (sqrt, etc).
1036 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
1037 if (OpI && OpI->hasOneUse()) {
1038 switch (OpI->getOpcode()) {
1039 default: break;
1040 case Instruction::FAdd:
1041 case Instruction::FSub:
1042 case Instruction::FMul:
1043 case Instruction::FDiv:
1044 case Instruction::FRem:
1045 const Type *SrcTy = OpI->getType();
1046 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
1047 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
1048 if (LHSTrunc->getType() != SrcTy &&
1049 RHSTrunc->getType() != SrcTy) {
1050 unsigned DstSize = CI.getType()->getScalarSizeInBits();
1051 // If the source types were both smaller than the destination type of
1052 // the cast, do this xform.
1053 if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
1054 RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
1055 LHSTrunc = Builder->CreateFPExt(LHSTrunc, CI.getType());
1056 RHSTrunc = Builder->CreateFPExt(RHSTrunc, CI.getType());
1057 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
1058 }
1059 }
1060 break;
1061 }
1062 }
1063 return 0;
1064}
1065
1066Instruction *InstCombiner::visitFPExt(CastInst &CI) {
1067 return commonCastTransforms(CI);
1068}
1069
1070Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
1071 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
1072 if (OpI == 0)
1073 return commonCastTransforms(FI);
1074
1075 // fptoui(uitofp(X)) --> X
1076 // fptoui(sitofp(X)) --> X
1077 // This is safe if the intermediate type has enough bits in its mantissa to
1078 // accurately represent all values of X. For example, do not do this with
1079 // i64->float->i64. This is also safe for sitofp case, because any negative
1080 // 'X' value would cause an undefined result for the fptoui.
1081 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
1082 OpI->getOperand(0)->getType() == FI.getType() &&
1083 (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
1084 OpI->getType()->getFPMantissaWidth())
1085 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
1086
1087 return commonCastTransforms(FI);
1088}
1089
1090Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
1091 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
1092 if (OpI == 0)
1093 return commonCastTransforms(FI);
1094
1095 // fptosi(sitofp(X)) --> X
1096 // fptosi(uitofp(X)) --> X
1097 // This is safe if the intermediate type has enough bits in its mantissa to
1098 // accurately represent all values of X. For example, do not do this with
1099 // i64->float->i64. This is also safe for sitofp case, because any negative
1100 // 'X' value would cause an undefined result for the fptoui.
1101 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
1102 OpI->getOperand(0)->getType() == FI.getType() &&
1103 (int)FI.getType()->getScalarSizeInBits() <=
1104 OpI->getType()->getFPMantissaWidth())
1105 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
1106
1107 return commonCastTransforms(FI);
1108}
1109
1110Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
1111 return commonCastTransforms(CI);
1112}
1113
1114Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
1115 return commonCastTransforms(CI);
1116}
1117
Chris Lattner80f43d32010-01-04 07:53:58 +00001118Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
1119 // If the source integer type is larger than the intptr_t type for
1120 // this target, do a trunc to the intptr_t type, then inttoptr of it. This
1121 // allows the trunc to be exposed to other transforms. Don't do this for
1122 // extending inttoptr's, because we don't know if the target sign or zero
1123 // extends to pointers.
1124 if (TD && CI.getOperand(0)->getType()->getScalarSizeInBits() >
1125 TD->getPointerSizeInBits()) {
1126 Value *P = Builder->CreateTrunc(CI.getOperand(0),
1127 TD->getIntPtrType(CI.getContext()), "tmp");
1128 return new IntToPtrInst(P, CI.getType());
1129 }
1130
1131 if (Instruction *I = commonCastTransforms(CI))
1132 return I;
1133
1134 return 0;
1135}
1136
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001137/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
1138Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
1139 Value *Src = CI.getOperand(0);
1140
1141 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
1142 // If casting the result of a getelementptr instruction with no offset, turn
1143 // this into a cast of the original pointer!
1144 if (GEP->hasAllZeroIndices()) {
1145 // Changing the cast operand is usually not a good idea but it is safe
1146 // here because the pointer operand is being replaced with another
1147 // pointer operand so the opcode doesn't need to change.
1148 Worklist.Add(GEP);
1149 CI.setOperand(0, GEP->getOperand(0));
1150 return &CI;
1151 }
1152
1153 // If the GEP has a single use, and the base pointer is a bitcast, and the
1154 // GEP computes a constant offset, see if we can convert these three
1155 // instructions into fewer. This typically happens with unions and other
1156 // non-type-safe code.
1157 if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0)) &&
1158 GEP->hasAllConstantIndices()) {
1159 // We are guaranteed to get a constant from EmitGEPOffset.
1160 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP));
1161 int64_t Offset = OffsetV->getSExtValue();
1162
1163 // Get the base pointer input of the bitcast, and the type it points to.
1164 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
1165 const Type *GEPIdxTy =
1166 cast<PointerType>(OrigBase->getType())->getElementType();
1167 SmallVector<Value*, 8> NewIndices;
1168 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices)) {
1169 // If we were able to index down into an element, create the GEP
1170 // and bitcast the result. This eliminates one bitcast, potentially
1171 // two.
1172 Value *NGEP = cast<GEPOperator>(GEP)->isInBounds() ?
1173 Builder->CreateInBoundsGEP(OrigBase,
1174 NewIndices.begin(), NewIndices.end()) :
1175 Builder->CreateGEP(OrigBase, NewIndices.begin(), NewIndices.end());
1176 NGEP->takeName(GEP);
1177
1178 if (isa<BitCastInst>(CI))
1179 return new BitCastInst(NGEP, CI.getType());
1180 assert(isa<PtrToIntInst>(CI));
1181 return new PtrToIntInst(NGEP, CI.getType());
1182 }
1183 }
1184 }
1185
1186 return commonCastTransforms(CI);
1187}
1188
1189Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
1190 // If the destination integer type is smaller than the intptr_t type for
1191 // this target, do a ptrtoint to intptr_t then do a trunc. This allows the
1192 // trunc to be exposed to other transforms. Don't do this for extending
1193 // ptrtoint's, because we don't know if the target sign or zero extends its
1194 // pointers.
1195 if (TD &&
1196 CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
1197 Value *P = Builder->CreatePtrToInt(CI.getOperand(0),
1198 TD->getIntPtrType(CI.getContext()),
1199 "tmp");
1200 return new TruncInst(P, CI.getType());
1201 }
1202
1203 return commonPointerCastTransforms(CI);
1204}
1205
Chris Lattner80f43d32010-01-04 07:53:58 +00001206Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
1207 // If the operands are integer typed then apply the integer transforms,
1208 // otherwise just apply the common ones.
1209 Value *Src = CI.getOperand(0);
1210 const Type *SrcTy = Src->getType();
1211 const Type *DestTy = CI.getType();
1212
Chris Lattner80f43d32010-01-04 07:53:58 +00001213 // Get rid of casts from one type to the same type. These are useless and can
1214 // be replaced by the operand.
1215 if (DestTy == Src->getType())
1216 return ReplaceInstUsesWith(CI, Src);
1217
1218 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
1219 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
1220 const Type *DstElTy = DstPTy->getElementType();
1221 const Type *SrcElTy = SrcPTy->getElementType();
1222
1223 // If the address spaces don't match, don't eliminate the bitcast, which is
1224 // required for changing types.
1225 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
1226 return 0;
1227
1228 // If we are casting a alloca to a pointer to a type of the same
1229 // size, rewrite the allocation instruction to allocate the "right" type.
1230 // There is no need to modify malloc calls because it is their bitcast that
1231 // needs to be cleaned up.
1232 if (AllocaInst *AI = dyn_cast<AllocaInst>(Src))
1233 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
1234 return V;
1235
1236 // If the source and destination are pointers, and this cast is equivalent
1237 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
1238 // This can enhance SROA and other transforms that want type-safe pointers.
1239 Constant *ZeroUInt =
1240 Constant::getNullValue(Type::getInt32Ty(CI.getContext()));
1241 unsigned NumZeros = 0;
1242 while (SrcElTy != DstElTy &&
1243 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
1244 SrcElTy->getNumContainedTypes() /* not "{}" */) {
1245 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
1246 ++NumZeros;
1247 }
1248
1249 // If we found a path from the src to dest, create the getelementptr now.
1250 if (SrcElTy == DstElTy) {
1251 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
1252 return GetElementPtrInst::CreateInBounds(Src, Idxs.begin(), Idxs.end(),"",
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001253 ((Instruction*)NULL));
Chris Lattner80f43d32010-01-04 07:53:58 +00001254 }
1255 }
1256
1257 if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001258 if (DestVTy->getNumElements() == 1 && !isa<VectorType>(SrcTy)) {
1259 Value *Elem = Builder->CreateBitCast(Src, DestVTy->getElementType());
1260 return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
Chris Lattner80f43d32010-01-04 07:53:58 +00001261 Constant::getNullValue(Type::getInt32Ty(CI.getContext())));
Chris Lattner80f43d32010-01-04 07:53:58 +00001262 // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
1263 }
1264 }
1265
1266 if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001267 if (SrcVTy->getNumElements() == 1 && !isa<VectorType>(DestTy)) {
1268 Value *Elem =
1269 Builder->CreateExtractElement(Src,
1270 Constant::getNullValue(Type::getInt32Ty(CI.getContext())));
1271 return CastInst::Create(Instruction::BitCast, Elem, DestTy);
Chris Lattner80f43d32010-01-04 07:53:58 +00001272 }
1273 }
1274
1275 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001276 // Okay, we have (bitcast (shuffle ..)). Check to see if this is
1277 // a bitconvert to a vector with the same # elts.
1278 if (SVI->hasOneUse() && isa<VectorType>(DestTy) &&
1279 cast<VectorType>(DestTy)->getNumElements() ==
1280 SVI->getType()->getNumElements() &&
1281 SVI->getType()->getNumElements() ==
1282 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
1283 BitCastInst *Tmp;
1284 // If either of the operands is a cast from CI.getType(), then
1285 // evaluating the shuffle in the casted destination's type will allow
1286 // us to eliminate at least one cast.
1287 if (((Tmp = dyn_cast<BitCastInst>(SVI->getOperand(0))) &&
1288 Tmp->getOperand(0)->getType() == DestTy) ||
1289 ((Tmp = dyn_cast<BitCastInst>(SVI->getOperand(1))) &&
1290 Tmp->getOperand(0)->getType() == DestTy)) {
1291 Value *LHS = Builder->CreateBitCast(SVI->getOperand(0), DestTy);
1292 Value *RHS = Builder->CreateBitCast(SVI->getOperand(1), DestTy);
1293 // Return a new shuffle vector. Use the same element ID's, as we
1294 // know the vector types match #elts.
1295 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner80f43d32010-01-04 07:53:58 +00001296 }
1297 }
1298 }
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001299
1300 if (isa<PointerType>(SrcTy))
1301 return commonPointerCastTransforms(CI);
1302 return commonCastTransforms(CI);
Chris Lattner80f43d32010-01-04 07:53:58 +00001303}