1 //===- InstCombineCasts.cpp -----------------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the visit functions for cast operations.
12 //===----------------------------------------------------------------------===//
14 #include "InstCombine.h"
15 #include "llvm/Target/TargetData.h"
16 #include "llvm/Support/PatternMatch.h"
18 using namespace PatternMatch;
20 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
21 /// expression. If so, decompose it, returning some value X, such that Val is
24 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
26 assert(Val->getType()->isInteger(32) && "Unexpected allocation size type!");
27 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
28 Offset = CI->getZExtValue();
30 return ConstantInt::get(Type::getInt32Ty(Val->getContext()), 0);
33 if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
34 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();
39 return I->getOperand(0);
42 if (I->getOpcode() == Instruction::Mul) {
43 // This value is scaled by 'RHS'.
44 Scale = RHS->getZExtValue();
46 return I->getOperand(0);
49 if (I->getOpcode() == Instruction::Add) {
50 // We have X+C. Check to see if we really have (X*C2)+C1,
51 // where C1 is divisible by C2.
54 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
55 Offset += RHS->getZExtValue();
62 // Otherwise, we can't look past this.
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.
70 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
72 // This requires TargetData to get the alloca alignment and size information.
75 const PointerType *PTy = cast<PointerType>(CI.getType());
77 BuilderTy AllocaBuilder(*Builder);
78 AllocaBuilder.SetInsertPoint(AI.getParent(), &AI);
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;
85 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
86 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
87 if (CastElTyAlign < AllocElTyAlign) return 0;
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;
96 uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
97 uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
98 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
100 // See if we can satisfy the modulus by pulling a scale out of the array
102 unsigned ArraySizeScale;
104 Value *NumElements = // See if the array size is a decomposable linear expr.
105 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
107 // If we can now satisfy the modulus, by using a non-1 scale, we really can
109 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
110 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
112 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
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");
122 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
123 Value *Off = ConstantInt::get(Type::getInt32Ty(CI.getContext()),
125 Amt = AllocaBuilder.CreateAdd(Amt, Off, "tmp");
128 AllocaInst *New = AllocaBuilder.CreateAlloca(CastElTy, Amt);
129 New->setAlignment(AI.getAlignment());
132 // If the allocation has one real use plus a dbg.declare, just remove the
134 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
135 EraseInstFromFunction(*(Instruction*)DI);
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
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);
146 return ReplaceInstUsesWith(CI, New);
151 /// EvaluateInDifferentType - Given an expression that
152 /// CanEvaluateTruncated or CanEvaluateSExtd returns true for, actually
153 /// insert the code to evaluate the expression.
154 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
156 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);
164 // Otherwise, it must be an instruction.
165 Instruction *I = cast<Instruction>(V);
166 Instruction *Res = 0;
167 unsigned Opc = I->getOpcode();
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);
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
191 if (I->getOperand(0)->getType() == Ty)
192 return I->getOperand(0);
194 // Otherwise, must be the same type of cast, so just reinsert a new one.
195 // This also handles the case of zext(trunc(x)) -> zext(x).
196 Res = CastInst::CreateIntegerCast(I->getOperand(0), Ty,
197 Opc == Instruction::SExt);
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);
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));
216 // TODO: Can handle more cases here.
217 llvm_unreachable("Unreachable!");
222 return InsertNewInstBefore(Res, *I);
226 /// This function is a wrapper around CastInst::isEliminableCastPair. It
227 /// simply extracts arguments and returns what that function returns.
228 static Instruction::CastOps
229 isEliminableCastPair(
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
236 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
237 const Type *MidTy = CI->getType(); // B from above
239 // Get the opcodes of the two Cast instructions
240 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
241 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
243 unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
245 TD ? TD->getIntPtrType(CI->getContext()) : 0);
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()))))
255 return Instruction::CastOps(Res);
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.
261 bool InstCombiner::ValueRequiresCast(Instruction::CastOps opcode,const Value *V,
263 if (V->getType() == Ty || isa<Constant>(V)) return false;
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))
273 /// @brief Implement the transforms common to all CastInst visitors.
274 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
275 Value *Src = CI.getOperand(0);
277 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
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());
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))
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))
307 /// 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.
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.
316 /// This function works on both vectors and scalars.
318 static bool CanEvaluateTruncated(Value *V, const Type *Ty) {
319 // We can always evaluate constants in another type.
320 if (isa<Constant>(V))
323 Instruction *I = dyn_cast<Instruction>(V);
324 if (!I) return false;
326 const Type *OrigTy = V->getType();
328 // If this is an extension from the dest type, we can eliminate it, even if it
329 // has multiple uses.
330 if ((isa<ZExtInst>(I) || isa<SExtInst>(I)) &&
331 I->getOperand(0)->getType() == Ty)
334 // We can't extend or shrink something that has multiple uses: doing so would
335 // require duplicating the instruction in general, which isn't profitable.
336 if (!I->hasOneUse()) return false;
338 unsigned Opc = I->getOpcode();
340 case Instruction::Add:
341 case Instruction::Sub:
342 case Instruction::Mul:
343 case Instruction::And:
344 case Instruction::Or:
345 case Instruction::Xor:
346 // These operators can all arbitrarily be extended or truncated.
347 return CanEvaluateTruncated(I->getOperand(0), Ty) &&
348 CanEvaluateTruncated(I->getOperand(1), Ty);
350 case Instruction::UDiv:
351 case Instruction::URem: {
352 // UDiv and URem can be truncated if all the truncated bits are zero.
353 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
354 uint32_t BitWidth = Ty->getScalarSizeInBits();
355 if (BitWidth < OrigBitWidth) {
356 APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
357 if (MaskedValueIsZero(I->getOperand(0), Mask) &&
358 MaskedValueIsZero(I->getOperand(1), Mask)) {
359 return CanEvaluateTruncated(I->getOperand(0), Ty) &&
360 CanEvaluateTruncated(I->getOperand(1), Ty);
365 case Instruction::Shl:
366 // If we are truncating the result of this SHL, and if it's a shift of a
367 // constant amount, we can always perform a SHL in a smaller type.
368 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
369 uint32_t BitWidth = Ty->getScalarSizeInBits();
370 if (CI->getLimitedValue(BitWidth) < BitWidth)
371 return CanEvaluateTruncated(I->getOperand(0), Ty);
374 case Instruction::LShr:
375 // If this is a truncate of a logical shr, we can truncate it to a smaller
376 // lshr iff we know that the bits we would otherwise be shifting in are
378 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
379 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
380 uint32_t BitWidth = Ty->getScalarSizeInBits();
381 if (MaskedValueIsZero(I->getOperand(0),
382 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
383 CI->getLimitedValue(BitWidth) < BitWidth) {
384 return CanEvaluateTruncated(I->getOperand(0), Ty);
388 case Instruction::Trunc:
389 // trunc(trunc(x)) -> trunc(x)
391 case Instruction::Select: {
392 SelectInst *SI = cast<SelectInst>(I);
393 return CanEvaluateTruncated(SI->getTrueValue(), Ty) &&
394 CanEvaluateTruncated(SI->getFalseValue(), Ty);
396 case Instruction::PHI: {
397 // We can change a phi if we can change all operands. Note that we never
398 // get into trouble with cyclic PHIs here because we only consider
399 // instructions with a single use.
400 PHINode *PN = cast<PHINode>(I);
401 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
402 if (!CanEvaluateTruncated(PN->getIncomingValue(i), Ty))
407 // TODO: Can handle more cases here.
414 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
415 if (Instruction *Result = commonCastTransforms(CI))
418 // See if we can simplify any instructions used by the input whose sole
419 // purpose is to compute bits we don't care about.
420 if (SimplifyDemandedInstructionBits(CI))
423 Value *Src = CI.getOperand(0);
424 const Type *DestTy = CI.getType(), *SrcTy = Src->getType();
426 // Attempt to truncate the entire input expression tree to the destination
427 // type. Only do this if the dest type is a simple type, don't convert the
428 // expression tree to something weird like i93 unless the source is also
430 if ((isa<VectorType>(DestTy) || ShouldChangeType(SrcTy, DestTy)) &&
431 CanEvaluateTruncated(Src, DestTy)) {
433 // If this cast is a truncate, evaluting in a different type always
434 // eliminates the cast, so it is always a win.
435 DEBUG(dbgs() << "ICE: EvaluateInDifferentType converting expression type"
436 " to avoid cast: " << CI);
437 Value *Res = EvaluateInDifferentType(Src, DestTy, false);
438 assert(Res->getType() == DestTy);
439 return ReplaceInstUsesWith(CI, Res);
442 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0), likewise for vector.
443 if (DestTy->getScalarSizeInBits() == 1) {
444 Constant *One = ConstantInt::get(Src->getType(), 1);
445 Src = Builder->CreateAnd(Src, One, "tmp");
446 Value *Zero = Constant::getNullValue(Src->getType());
447 return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
453 /// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
454 /// in order to eliminate the icmp.
455 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
457 // If we are just checking for a icmp eq of a single bit and zext'ing it
458 // to an integer, then shift the bit to the appropriate place and then
459 // cast to integer to avoid the comparison.
460 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
461 const APInt &Op1CV = Op1C->getValue();
463 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
464 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
465 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
466 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
467 if (!DoXform) return ICI;
469 Value *In = ICI->getOperand(0);
470 Value *Sh = ConstantInt::get(In->getType(),
471 In->getType()->getScalarSizeInBits()-1);
472 In = Builder->CreateLShr(In, Sh, In->getName()+".lobit");
473 if (In->getType() != CI.getType())
474 In = Builder->CreateIntCast(In, CI.getType(), false/*ZExt*/, "tmp");
476 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
477 Constant *One = ConstantInt::get(In->getType(), 1);
478 In = Builder->CreateXor(In, One, In->getName()+".not");
481 return ReplaceInstUsesWith(CI, In);
486 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
487 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
488 // zext (X == 1) to i32 --> X iff X has only the low bit set.
489 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
490 // zext (X != 0) to i32 --> X iff X has only the low bit set.
491 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
492 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
493 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
494 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
495 // This only works for EQ and NE
497 // If Op1C some other power of two, convert:
498 uint32_t BitWidth = Op1C->getType()->getBitWidth();
499 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
500 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
501 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
503 APInt KnownZeroMask(~KnownZero);
504 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
505 if (!DoXform) return ICI;
507 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
508 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
509 // (X&4) == 2 --> false
510 // (X&4) != 2 --> true
511 Constant *Res = ConstantInt::get(Type::getInt1Ty(CI.getContext()),
513 Res = ConstantExpr::getZExt(Res, CI.getType());
514 return ReplaceInstUsesWith(CI, Res);
517 uint32_t ShiftAmt = KnownZeroMask.logBase2();
518 Value *In = ICI->getOperand(0);
520 // Perform a logical shr by shiftamt.
521 // Insert the shift to put the result in the low bit.
522 In = Builder->CreateLShr(In, ConstantInt::get(In->getType(),ShiftAmt),
523 In->getName()+".lobit");
526 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
527 Constant *One = ConstantInt::get(In->getType(), 1);
528 In = Builder->CreateXor(In, One, "tmp");
531 if (CI.getType() == In->getType())
532 return ReplaceInstUsesWith(CI, In);
534 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
539 // icmp ne A, B is equal to xor A, B when A and B only really have one bit.
540 // It is also profitable to transform icmp eq into not(xor(A, B)) because that
541 // may lead to additional simplifications.
542 if (ICI->isEquality() && CI.getType() == ICI->getOperand(0)->getType()) {
543 if (const IntegerType *ITy = dyn_cast<IntegerType>(CI.getType())) {
544 uint32_t BitWidth = ITy->getBitWidth();
545 Value *LHS = ICI->getOperand(0);
546 Value *RHS = ICI->getOperand(1);
548 APInt KnownZeroLHS(BitWidth, 0), KnownOneLHS(BitWidth, 0);
549 APInt KnownZeroRHS(BitWidth, 0), KnownOneRHS(BitWidth, 0);
550 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
551 ComputeMaskedBits(LHS, TypeMask, KnownZeroLHS, KnownOneLHS);
552 ComputeMaskedBits(RHS, TypeMask, KnownZeroRHS, KnownOneRHS);
554 if (KnownZeroLHS == KnownZeroRHS && KnownOneLHS == KnownOneRHS) {
555 APInt KnownBits = KnownZeroLHS | KnownOneLHS;
556 APInt UnknownBit = ~KnownBits;
557 if (UnknownBit.countPopulation() == 1) {
558 if (!DoXform) return ICI;
560 Value *Result = Builder->CreateXor(LHS, RHS);
562 // Mask off any bits that are set and won't be shifted away.
563 if (KnownOneLHS.uge(UnknownBit))
564 Result = Builder->CreateAnd(Result,
565 ConstantInt::get(ITy, UnknownBit));
567 // Shift the bit we're testing down to the lsb.
568 Result = Builder->CreateLShr(
569 Result, ConstantInt::get(ITy, UnknownBit.countTrailingZeros()));
571 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
572 Result = Builder->CreateXor(Result, ConstantInt::get(ITy, 1));
573 Result->takeName(ICI);
574 return ReplaceInstUsesWith(CI, Result);
583 /// CanEvaluateZExtd - Determine if the specified value can be computed in the
584 /// specified wider type and produce the same low bits. If not, return false.
586 /// If this function returns true, it can also return a non-zero number of bits
587 /// (in BitsToClear) which indicates that the value it computes is correct for
588 /// the zero extend, but that the additional BitsToClear bits need to be zero'd
589 /// out. For example, to promote something like:
591 /// %B = trunc i64 %A to i32
592 /// %C = lshr i32 %B, 8
593 /// %E = zext i32 %C to i64
595 /// CanEvaluateZExtd for the 'lshr' will return true, and BitsToClear will be
596 /// set to 8 to indicate that the promoted value needs to have bits 24-31
597 /// cleared in addition to bits 32-63. Since an 'and' will be generated to
598 /// clear the top bits anyway, doing this has no extra cost.
600 /// This function works on both vectors and scalars.
601 static bool CanEvaluateZExtd(Value *V, const Type *Ty, unsigned &BitsToClear) {
603 if (isa<Constant>(V))
606 Instruction *I = dyn_cast<Instruction>(V);
607 if (!I) return false;
609 // If the input is a truncate from the destination type, we can trivially
610 // eliminate it, even if it has multiple uses.
611 // FIXME: This is currently disabled until codegen can handle this without
612 // pessimizing code, PR5997.
613 if (0 && isa<TruncInst>(I) && I->getOperand(0)->getType() == Ty)
616 // We can't extend or shrink something that has multiple uses: doing so would
617 // require duplicating the instruction in general, which isn't profitable.
618 if (!I->hasOneUse()) return false;
620 unsigned Opc = I->getOpcode(), Tmp;
622 case Instruction::ZExt: // zext(zext(x)) -> zext(x).
623 case Instruction::SExt: // zext(sext(x)) -> sext(x).
624 case Instruction::Trunc: // zext(trunc(x)) -> trunc(x) or zext(x)
626 case Instruction::And:
627 case Instruction::Or:
628 case Instruction::Xor:
629 case Instruction::Add:
630 case Instruction::Sub:
631 case Instruction::Mul:
632 case Instruction::Shl:
633 if (!CanEvaluateZExtd(I->getOperand(0), Ty, BitsToClear) ||
634 !CanEvaluateZExtd(I->getOperand(1), Ty, Tmp))
636 // These can all be promoted if neither operand has 'bits to clear'.
637 if (BitsToClear == 0 && Tmp == 0)
640 // If the operation is an AND/OR/XOR and the bits to clear are zero in the
641 // other side, BitsToClear is ok.
643 (Opc == Instruction::And || Opc == Instruction::Or ||
644 Opc == Instruction::Xor)) {
645 // We use MaskedValueIsZero here for generality, but the case we care
646 // about the most is constant RHS.
647 unsigned VSize = V->getType()->getScalarSizeInBits();
648 if (MaskedValueIsZero(I->getOperand(1),
649 APInt::getHighBitsSet(VSize, BitsToClear)))
653 // Otherwise, we don't know how to analyze this BitsToClear case yet.
656 case Instruction::LShr:
657 // We can promote lshr(x, cst) if we can promote x. This requires the
658 // ultimate 'and' to clear out the high zero bits we're clearing out though.
659 if (ConstantInt *Amt = dyn_cast<ConstantInt>(I->getOperand(1))) {
660 if (!CanEvaluateZExtd(I->getOperand(0), Ty, BitsToClear))
662 BitsToClear += Amt->getZExtValue();
663 if (BitsToClear > V->getType()->getScalarSizeInBits())
664 BitsToClear = V->getType()->getScalarSizeInBits();
667 // Cannot promote variable LSHR.
669 case Instruction::Select:
670 if (!CanEvaluateZExtd(I->getOperand(1), Ty, Tmp) ||
671 !CanEvaluateZExtd(I->getOperand(2), Ty, BitsToClear) ||
672 // TODO: If important, we could handle the case when the BitsToClear are
673 // known zero in the disagreeing side.
678 case Instruction::PHI: {
679 // We can change a phi if we can change all operands. Note that we never
680 // get into trouble with cyclic PHIs here because we only consider
681 // instructions with a single use.
682 PHINode *PN = cast<PHINode>(I);
683 if (!CanEvaluateZExtd(PN->getIncomingValue(0), Ty, BitsToClear))
685 for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i)
686 if (!CanEvaluateZExtd(PN->getIncomingValue(i), Ty, Tmp) ||
687 // TODO: If important, we could handle the case when the BitsToClear
688 // are known zero in the disagreeing input.
694 // TODO: Can handle more cases here.
699 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
700 // If this zero extend is only used by a truncate, let the truncate by
701 // eliminated before we try to optimize this zext.
702 if (CI.hasOneUse() && isa<TruncInst>(CI.use_back()))
705 // If one of the common conversion will work, do it.
706 if (Instruction *Result = commonCastTransforms(CI))
709 // See if we can simplify any instructions used by the input whose sole
710 // purpose is to compute bits we don't care about.
711 if (SimplifyDemandedInstructionBits(CI))
714 Value *Src = CI.getOperand(0);
715 const Type *SrcTy = Src->getType(), *DestTy = CI.getType();
717 // Attempt to extend the entire input expression tree to the destination
718 // type. Only do this if the dest type is a simple type, don't convert the
719 // expression tree to something weird like i93 unless the source is also
721 unsigned BitsToClear;
722 if ((isa<VectorType>(DestTy) || ShouldChangeType(SrcTy, DestTy)) &&
723 CanEvaluateZExtd(Src, DestTy, BitsToClear)) {
724 assert(BitsToClear < SrcTy->getScalarSizeInBits() &&
725 "Unreasonable BitsToClear");
727 // Okay, we can transform this! Insert the new expression now.
728 DEBUG(dbgs() << "ICE: EvaluateInDifferentType converting expression type"
729 " to avoid zero extend: " << CI);
730 Value *Res = EvaluateInDifferentType(Src, DestTy, false);
731 assert(Res->getType() == DestTy);
733 uint32_t SrcBitsKept = SrcTy->getScalarSizeInBits()-BitsToClear;
734 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
736 // If the high bits are already filled with zeros, just replace this
737 // cast with the result.
738 if (MaskedValueIsZero(Res, APInt::getHighBitsSet(DestBitSize,
739 DestBitSize-SrcBitsKept)))
740 return ReplaceInstUsesWith(CI, Res);
742 // We need to emit an AND to clear the high bits.
743 Constant *C = ConstantInt::get(Res->getType(),
744 APInt::getLowBitsSet(DestBitSize, SrcBitsKept));
745 return BinaryOperator::CreateAnd(Res, C);
748 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
749 // types and if the sizes are just right we can convert this into a logical
750 // 'and' which will be much cheaper than the pair of casts.
751 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
752 // TODO: Subsume this into EvaluateInDifferentType.
754 // Get the sizes of the types involved. We know that the intermediate type
755 // will be smaller than A or C, but don't know the relation between A and C.
756 Value *A = CSrc->getOperand(0);
757 unsigned SrcSize = A->getType()->getScalarSizeInBits();
758 unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
759 unsigned DstSize = CI.getType()->getScalarSizeInBits();
760 // If we're actually extending zero bits, then if
761 // SrcSize < DstSize: zext(a & mask)
762 // SrcSize == DstSize: a & mask
763 // SrcSize > DstSize: trunc(a) & mask
764 if (SrcSize < DstSize) {
765 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
766 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
767 Value *And = Builder->CreateAnd(A, AndConst, CSrc->getName()+".mask");
768 return new ZExtInst(And, CI.getType());
771 if (SrcSize == DstSize) {
772 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
773 return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
776 if (SrcSize > DstSize) {
777 Value *Trunc = Builder->CreateTrunc(A, CI.getType(), "tmp");
778 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
779 return BinaryOperator::CreateAnd(Trunc,
780 ConstantInt::get(Trunc->getType(),
785 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
786 return transformZExtICmp(ICI, CI);
788 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
789 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
790 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
791 // of the (zext icmp) will be transformed.
792 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
793 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
794 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
795 (transformZExtICmp(LHS, CI, false) ||
796 transformZExtICmp(RHS, CI, false))) {
797 Value *LCast = Builder->CreateZExt(LHS, CI.getType(), LHS->getName());
798 Value *RCast = Builder->CreateZExt(RHS, CI.getType(), RHS->getName());
799 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
803 // zext(trunc(t) & C) -> (t & zext(C)).
804 if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
805 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
806 if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
807 Value *TI0 = TI->getOperand(0);
808 if (TI0->getType() == CI.getType())
810 BinaryOperator::CreateAnd(TI0,
811 ConstantExpr::getZExt(C, CI.getType()));
814 // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
815 if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
816 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
817 if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
818 if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
819 And->getOperand(1) == C)
820 if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
821 Value *TI0 = TI->getOperand(0);
822 if (TI0->getType() == CI.getType()) {
823 Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
824 Value *NewAnd = Builder->CreateAnd(TI0, ZC, "tmp");
825 return BinaryOperator::CreateXor(NewAnd, ZC);
829 // zext (xor i1 X, true) to i32 --> xor (zext i1 X to i32), 1
831 if (SrcI && SrcI->hasOneUse() && SrcI->getType()->isInteger(1) &&
832 match(SrcI, m_Not(m_Value(X))) &&
833 (!X->hasOneUse() || !isa<CmpInst>(X))) {
834 Value *New = Builder->CreateZExt(X, CI.getType());
835 return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
841 /// CanEvaluateSExtd - Return true if we can take the specified value
842 /// and return it as type Ty without inserting any new casts and without
843 /// changing the value of the common low bits. This is used by code that tries
844 /// to promote integer operations to a wider types will allow us to eliminate
847 /// This function works on both vectors and scalars.
849 static bool CanEvaluateSExtd(Value *V, const Type *Ty) {
850 assert(V->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits() &&
851 "Can't sign extend type to a smaller type");
852 // If this is a constant, it can be trivially promoted.
853 if (isa<Constant>(V))
856 Instruction *I = dyn_cast<Instruction>(V);
857 if (!I) return false;
859 // If this is a truncate from the dest type, we can trivially eliminate it,
860 // even if it has multiple uses.
861 // FIXME: This is currently disabled until codegen can handle this without
862 // pessimizing code, PR5997.
863 if (0 && isa<TruncInst>(I) && I->getOperand(0)->getType() == Ty)
866 // We can't extend or shrink something that has multiple uses: doing so would
867 // require duplicating the instruction in general, which isn't profitable.
868 if (!I->hasOneUse()) return false;
870 switch (I->getOpcode()) {
871 case Instruction::SExt: // sext(sext(x)) -> sext(x)
872 case Instruction::ZExt: // sext(zext(x)) -> zext(x)
873 case Instruction::Trunc: // sext(trunc(x)) -> trunc(x) or sext(x)
875 case Instruction::And:
876 case Instruction::Or:
877 case Instruction::Xor:
878 case Instruction::Add:
879 case Instruction::Sub:
880 case Instruction::Mul:
881 // These operators can all arbitrarily be extended if their inputs can.
882 return CanEvaluateSExtd(I->getOperand(0), Ty) &&
883 CanEvaluateSExtd(I->getOperand(1), Ty);
885 //case Instruction::Shl: TODO
886 //case Instruction::LShr: TODO
888 case Instruction::Select:
889 return CanEvaluateSExtd(I->getOperand(1), Ty) &&
890 CanEvaluateSExtd(I->getOperand(2), Ty);
892 case Instruction::PHI: {
893 // We can change a phi if we can change all operands. Note that we never
894 // get into trouble with cyclic PHIs here because we only consider
895 // instructions with a single use.
896 PHINode *PN = cast<PHINode>(I);
897 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
898 if (!CanEvaluateSExtd(PN->getIncomingValue(i), Ty)) return false;
902 // TODO: Can handle more cases here.
909 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
910 // If this sign extend is only used by a truncate, let the truncate by
911 // eliminated before we try to optimize this zext.
912 if (CI.hasOneUse() && isa<TruncInst>(CI.use_back()))
915 if (Instruction *I = commonCastTransforms(CI))
918 // See if we can simplify any instructions used by the input whose sole
919 // purpose is to compute bits we don't care about.
920 if (SimplifyDemandedInstructionBits(CI))
923 Value *Src = CI.getOperand(0);
924 const Type *SrcTy = Src->getType(), *DestTy = CI.getType();
926 // Canonicalize sign-extend from i1 to a select.
927 if (Src->getType()->isInteger(1))
928 return SelectInst::Create(Src,
929 Constant::getAllOnesValue(CI.getType()),
930 Constant::getNullValue(CI.getType()));
932 // Attempt to extend the entire input expression tree to the destination
933 // type. Only do this if the dest type is a simple type, don't convert the
934 // expression tree to something weird like i93 unless the source is also
936 if ((isa<VectorType>(DestTy) || ShouldChangeType(SrcTy, DestTy)) &&
937 CanEvaluateSExtd(Src, DestTy)) {
938 // Okay, we can transform this! Insert the new expression now.
939 DEBUG(dbgs() << "ICE: EvaluateInDifferentType converting expression type"
940 " to avoid sign extend: " << CI);
941 Value *Res = EvaluateInDifferentType(Src, DestTy, true);
942 assert(Res->getType() == DestTy);
944 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
945 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
947 // If the high bits are already filled with sign bit, just replace this
948 // cast with the result.
949 if (ComputeNumSignBits(Res) > DestBitSize - SrcBitSize)
950 return ReplaceInstUsesWith(CI, Res);
952 // We need to emit a shl + ashr to do the sign extend.
953 Value *ShAmt = ConstantInt::get(DestTy, DestBitSize-SrcBitSize);
954 return BinaryOperator::CreateAShr(Builder->CreateShl(Res, ShAmt, "sext"),
958 // If this input is a trunc from our destination, then turn sext(trunc(x))
960 if (TruncInst *TI = dyn_cast<TruncInst>(Src))
961 if (TI->hasOneUse() && TI->getOperand(0)->getType() == DestTy) {
962 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
963 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
965 // We need to emit a shl + ashr to do the sign extend.
966 Value *ShAmt = ConstantInt::get(DestTy, DestBitSize-SrcBitSize);
967 Value *Res = Builder->CreateShl(TI->getOperand(0), ShAmt, "sext");
968 return BinaryOperator::CreateAShr(Res, ShAmt);
971 // If the input is a shl/ashr pair of a same constant, then this is a sign
972 // extension from a smaller value. If we could trust arbitrary bitwidth
973 // integers, we could turn this into a truncate to the smaller bit and then
974 // use a sext for the whole extension. Since we don't, look deeper and check
975 // for a truncate. If the source and dest are the same type, eliminate the
976 // trunc and extend and just do shifts. For example, turn:
977 // %a = trunc i32 %i to i8
979 // %c = ashr i8 %b, 6
980 // %d = sext i8 %c to i32
982 // %a = shl i32 %i, 30
983 // %d = ashr i32 %a, 30
985 // TODO: Eventually this could be subsumed by EvaluateInDifferentType.
986 ConstantInt *BA = 0, *CA = 0;
987 if (match(Src, m_AShr(m_Shl(m_Trunc(m_Value(A)), m_ConstantInt(BA)),
988 m_ConstantInt(CA))) &&
989 BA == CA && A->getType() == CI.getType()) {
990 unsigned MidSize = Src->getType()->getScalarSizeInBits();
991 unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
992 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
993 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
994 A = Builder->CreateShl(A, ShAmtV, CI.getName());
995 return BinaryOperator::CreateAShr(A, ShAmtV);
1002 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
1003 /// in the specified FP type without changing its value.
1004 static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
1006 APFloat F = CFP->getValueAPF();
1007 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
1009 return ConstantFP::get(CFP->getContext(), F);
1013 /// LookThroughFPExtensions - If this is an fp extension instruction, look
1014 /// through it until we get the source value.
1015 static Value *LookThroughFPExtensions(Value *V) {
1016 if (Instruction *I = dyn_cast<Instruction>(V))
1017 if (I->getOpcode() == Instruction::FPExt)
1018 return LookThroughFPExtensions(I->getOperand(0));
1020 // If this value is a constant, return the constant in the smallest FP type
1021 // that can accurately represent it. This allows us to turn
1022 // (float)((double)X+2.0) into x+2.0f.
1023 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
1024 if (CFP->getType() == Type::getPPC_FP128Ty(V->getContext()))
1025 return V; // No constant folding of this.
1026 // See if the value can be truncated to float and then reextended.
1027 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
1029 if (CFP->getType()->isDoubleTy())
1030 return V; // Won't shrink.
1031 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
1033 // Don't try to shrink to various long double types.
1039 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
1040 if (Instruction *I = commonCastTransforms(CI))
1043 // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
1044 // smaller than the destination type, we can eliminate the truncate by doing
1045 // the add as the smaller type. This applies to fadd/fsub/fmul/fdiv as well
1046 // as many builtins (sqrt, etc).
1047 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
1048 if (OpI && OpI->hasOneUse()) {
1049 switch (OpI->getOpcode()) {
1051 case Instruction::FAdd:
1052 case Instruction::FSub:
1053 case Instruction::FMul:
1054 case Instruction::FDiv:
1055 case Instruction::FRem:
1056 const Type *SrcTy = OpI->getType();
1057 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
1058 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
1059 if (LHSTrunc->getType() != SrcTy &&
1060 RHSTrunc->getType() != SrcTy) {
1061 unsigned DstSize = CI.getType()->getScalarSizeInBits();
1062 // If the source types were both smaller than the destination type of
1063 // the cast, do this xform.
1064 if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
1065 RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
1066 LHSTrunc = Builder->CreateFPExt(LHSTrunc, CI.getType());
1067 RHSTrunc = Builder->CreateFPExt(RHSTrunc, CI.getType());
1068 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
1077 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
1078 return commonCastTransforms(CI);
1081 Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
1082 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
1084 return commonCastTransforms(FI);
1086 // fptoui(uitofp(X)) --> X
1087 // fptoui(sitofp(X)) --> X
1088 // This is safe if the intermediate type has enough bits in its mantissa to
1089 // accurately represent all values of X. For example, do not do this with
1090 // i64->float->i64. This is also safe for sitofp case, because any negative
1091 // 'X' value would cause an undefined result for the fptoui.
1092 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
1093 OpI->getOperand(0)->getType() == FI.getType() &&
1094 (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
1095 OpI->getType()->getFPMantissaWidth())
1096 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
1098 return commonCastTransforms(FI);
1101 Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
1102 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
1104 return commonCastTransforms(FI);
1106 // fptosi(sitofp(X)) --> X
1107 // fptosi(uitofp(X)) --> X
1108 // This is safe if the intermediate type has enough bits in its mantissa to
1109 // accurately represent all values of X. For example, do not do this with
1110 // i64->float->i64. This is also safe for sitofp case, because any negative
1111 // 'X' value would cause an undefined result for the fptoui.
1112 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
1113 OpI->getOperand(0)->getType() == FI.getType() &&
1114 (int)FI.getType()->getScalarSizeInBits() <=
1115 OpI->getType()->getFPMantissaWidth())
1116 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
1118 return commonCastTransforms(FI);
1121 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
1122 return commonCastTransforms(CI);
1125 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
1126 return commonCastTransforms(CI);
1129 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
1130 // If the source integer type is larger than the intptr_t type for
1131 // this target, do a trunc to the intptr_t type, then inttoptr of it. This
1132 // allows the trunc to be exposed to other transforms. Don't do this for
1133 // extending inttoptr's, because we don't know if the target sign or zero
1134 // extends to pointers.
1135 if (TD && CI.getOperand(0)->getType()->getScalarSizeInBits() >
1136 TD->getPointerSizeInBits()) {
1137 Value *P = Builder->CreateTrunc(CI.getOperand(0),
1138 TD->getIntPtrType(CI.getContext()), "tmp");
1139 return new IntToPtrInst(P, CI.getType());
1142 if (Instruction *I = commonCastTransforms(CI))
1148 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
1149 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
1150 Value *Src = CI.getOperand(0);
1152 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
1153 // If casting the result of a getelementptr instruction with no offset, turn
1154 // this into a cast of the original pointer!
1155 if (GEP->hasAllZeroIndices()) {
1156 // Changing the cast operand is usually not a good idea but it is safe
1157 // here because the pointer operand is being replaced with another
1158 // pointer operand so the opcode doesn't need to change.
1160 CI.setOperand(0, GEP->getOperand(0));
1164 // If the GEP has a single use, and the base pointer is a bitcast, and the
1165 // GEP computes a constant offset, see if we can convert these three
1166 // instructions into fewer. This typically happens with unions and other
1167 // non-type-safe code.
1168 if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0)) &&
1169 GEP->hasAllConstantIndices()) {
1170 // We are guaranteed to get a constant from EmitGEPOffset.
1171 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP));
1172 int64_t Offset = OffsetV->getSExtValue();
1174 // Get the base pointer input of the bitcast, and the type it points to.
1175 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
1176 const Type *GEPIdxTy =
1177 cast<PointerType>(OrigBase->getType())->getElementType();
1178 SmallVector<Value*, 8> NewIndices;
1179 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices)) {
1180 // If we were able to index down into an element, create the GEP
1181 // and bitcast the result. This eliminates one bitcast, potentially
1183 Value *NGEP = cast<GEPOperator>(GEP)->isInBounds() ?
1184 Builder->CreateInBoundsGEP(OrigBase,
1185 NewIndices.begin(), NewIndices.end()) :
1186 Builder->CreateGEP(OrigBase, NewIndices.begin(), NewIndices.end());
1187 NGEP->takeName(GEP);
1189 if (isa<BitCastInst>(CI))
1190 return new BitCastInst(NGEP, CI.getType());
1191 assert(isa<PtrToIntInst>(CI));
1192 return new PtrToIntInst(NGEP, CI.getType());
1197 return commonCastTransforms(CI);
1200 Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
1201 // If the destination integer type is smaller than the intptr_t type for
1202 // this target, do a ptrtoint to intptr_t then do a trunc. This allows the
1203 // trunc to be exposed to other transforms. Don't do this for extending
1204 // ptrtoint's, because we don't know if the target sign or zero extends its
1207 CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
1208 Value *P = Builder->CreatePtrToInt(CI.getOperand(0),
1209 TD->getIntPtrType(CI.getContext()),
1211 return new TruncInst(P, CI.getType());
1214 return commonPointerCastTransforms(CI);
1217 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
1218 // If the operands are integer typed then apply the integer transforms,
1219 // otherwise just apply the common ones.
1220 Value *Src = CI.getOperand(0);
1221 const Type *SrcTy = Src->getType();
1222 const Type *DestTy = CI.getType();
1224 // Get rid of casts from one type to the same type. These are useless and can
1225 // be replaced by the operand.
1226 if (DestTy == Src->getType())
1227 return ReplaceInstUsesWith(CI, Src);
1229 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
1230 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
1231 const Type *DstElTy = DstPTy->getElementType();
1232 const Type *SrcElTy = SrcPTy->getElementType();
1234 // If the address spaces don't match, don't eliminate the bitcast, which is
1235 // required for changing types.
1236 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
1239 // If we are casting a alloca to a pointer to a type of the same
1240 // size, rewrite the allocation instruction to allocate the "right" type.
1241 // There is no need to modify malloc calls because it is their bitcast that
1242 // needs to be cleaned up.
1243 if (AllocaInst *AI = dyn_cast<AllocaInst>(Src))
1244 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
1247 // If the source and destination are pointers, and this cast is equivalent
1248 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
1249 // This can enhance SROA and other transforms that want type-safe pointers.
1250 Constant *ZeroUInt =
1251 Constant::getNullValue(Type::getInt32Ty(CI.getContext()));
1252 unsigned NumZeros = 0;
1253 while (SrcElTy != DstElTy &&
1254 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
1255 SrcElTy->getNumContainedTypes() /* not "{}" */) {
1256 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
1260 // If we found a path from the src to dest, create the getelementptr now.
1261 if (SrcElTy == DstElTy) {
1262 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
1263 return GetElementPtrInst::CreateInBounds(Src, Idxs.begin(), Idxs.end(),"",
1264 ((Instruction*)NULL));
1268 if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
1269 if (DestVTy->getNumElements() == 1 && !isa<VectorType>(SrcTy)) {
1270 Value *Elem = Builder->CreateBitCast(Src, DestVTy->getElementType());
1271 return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
1272 Constant::getNullValue(Type::getInt32Ty(CI.getContext())));
1273 // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
1277 if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
1278 if (SrcVTy->getNumElements() == 1 && !isa<VectorType>(DestTy)) {
1280 Builder->CreateExtractElement(Src,
1281 Constant::getNullValue(Type::getInt32Ty(CI.getContext())));
1282 return CastInst::Create(Instruction::BitCast, Elem, DestTy);
1286 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
1287 // Okay, we have (bitcast (shuffle ..)). Check to see if this is
1288 // a bitconvert to a vector with the same # elts.
1289 if (SVI->hasOneUse() && isa<VectorType>(DestTy) &&
1290 cast<VectorType>(DestTy)->getNumElements() ==
1291 SVI->getType()->getNumElements() &&
1292 SVI->getType()->getNumElements() ==
1293 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
1295 // If either of the operands is a cast from CI.getType(), then
1296 // evaluating the shuffle in the casted destination's type will allow
1297 // us to eliminate at least one cast.
1298 if (((Tmp = dyn_cast<BitCastInst>(SVI->getOperand(0))) &&
1299 Tmp->getOperand(0)->getType() == DestTy) ||
1300 ((Tmp = dyn_cast<BitCastInst>(SVI->getOperand(1))) &&
1301 Tmp->getOperand(0)->getType() == DestTy)) {
1302 Value *LHS = Builder->CreateBitCast(SVI->getOperand(0), DestTy);
1303 Value *RHS = Builder->CreateBitCast(SVI->getOperand(1), DestTy);
1304 // Return a new shuffle vector. Use the same element ID's, as we
1305 // know the vector types match #elts.
1306 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
1311 if (isa<PointerType>(SrcTy))
1312 return commonPointerCastTransforms(CI);
1313 return commonCastTransforms(CI);