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/Analysis/ConstantFolding.h"
16 #include "llvm/Target/TargetData.h"
17 #include "llvm/Target/TargetLibraryInfo.h"
18 #include "llvm/Support/PatternMatch.h"
20 using namespace PatternMatch;
22 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
23 /// expression. If so, decompose it, returning some value X, such that Val is
26 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
28 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
29 Offset = CI->getZExtValue();
31 return ConstantInt::get(Val->getType(), 0);
34 if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
35 // Cannot look past anything that might overflow.
36 OverflowingBinaryOperator *OBI = dyn_cast<OverflowingBinaryOperator>(Val);
37 if (OBI && !OBI->hasNoUnsignedWrap()) {
43 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
44 if (I->getOpcode() == Instruction::Shl) {
45 // This is a value scaled by '1 << the shift amt'.
46 Scale = UINT64_C(1) << RHS->getZExtValue();
48 return I->getOperand(0);
51 if (I->getOpcode() == Instruction::Mul) {
52 // This value is scaled by 'RHS'.
53 Scale = RHS->getZExtValue();
55 return I->getOperand(0);
58 if (I->getOpcode() == Instruction::Add) {
59 // We have X+C. Check to see if we really have (X*C2)+C1,
60 // where C1 is divisible by C2.
63 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
64 Offset += RHS->getZExtValue();
71 // Otherwise, we can't look past this.
77 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
78 /// try to eliminate the cast by moving the type information into the alloc.
79 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
81 // This requires TargetData to get the alloca alignment and size information.
84 PointerType *PTy = cast<PointerType>(CI.getType());
86 BuilderTy AllocaBuilder(*Builder);
87 AllocaBuilder.SetInsertPoint(AI.getParent(), &AI);
89 // Get the type really allocated and the type casted to.
90 Type *AllocElTy = AI.getAllocatedType();
91 Type *CastElTy = PTy->getElementType();
92 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
94 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
95 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
96 if (CastElTyAlign < AllocElTyAlign) return 0;
98 // If the allocation has multiple uses, only promote it if we are strictly
99 // increasing the alignment of the resultant allocation. If we keep it the
100 // same, we open the door to infinite loops of various kinds.
101 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
103 uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
104 uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
105 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
107 // See if we can satisfy the modulus by pulling a scale out of the array
109 unsigned ArraySizeScale;
110 uint64_t ArrayOffset;
111 Value *NumElements = // See if the array size is a decomposable linear expr.
112 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
114 // If we can now satisfy the modulus, by using a non-1 scale, we really can
116 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
117 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
119 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
124 Amt = ConstantInt::get(AI.getArraySize()->getType(), Scale);
125 // Insert before the alloca, not before the cast.
126 Amt = AllocaBuilder.CreateMul(Amt, NumElements);
129 if (uint64_t Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
130 Value *Off = ConstantInt::get(AI.getArraySize()->getType(),
132 Amt = AllocaBuilder.CreateAdd(Amt, Off);
135 AllocaInst *New = AllocaBuilder.CreateAlloca(CastElTy, Amt);
136 New->setAlignment(AI.getAlignment());
139 // If the allocation has multiple real uses, insert a cast and change all
140 // things that used it to use the new cast. This will also hack on CI, but it
142 if (!AI.hasOneUse()) {
143 // New is the allocation instruction, pointer typed. AI is the original
144 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
145 Value *NewCast = AllocaBuilder.CreateBitCast(New, AI.getType(), "tmpcast");
146 ReplaceInstUsesWith(AI, NewCast);
148 return ReplaceInstUsesWith(CI, New);
153 /// EvaluateInDifferentType - Given an expression that
154 /// CanEvaluateTruncated or CanEvaluateSExtd returns true for, actually
155 /// insert the code to evaluate the expression.
156 Value *InstCombiner::EvaluateInDifferentType(Value *V, Type *Ty,
158 if (Constant *C = dyn_cast<Constant>(V)) {
159 C = ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
160 // If we got a constantexpr back, try to simplify it with TD info.
161 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
162 C = ConstantFoldConstantExpression(CE, TD);
166 // Otherwise, it must be an instruction.
167 Instruction *I = cast<Instruction>(V);
168 Instruction *Res = 0;
169 unsigned Opc = I->getOpcode();
171 case Instruction::Add:
172 case Instruction::Sub:
173 case Instruction::Mul:
174 case Instruction::And:
175 case Instruction::Or:
176 case Instruction::Xor:
177 case Instruction::AShr:
178 case Instruction::LShr:
179 case Instruction::Shl:
180 case Instruction::UDiv:
181 case Instruction::URem: {
182 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
183 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
184 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
187 case Instruction::Trunc:
188 case Instruction::ZExt:
189 case Instruction::SExt:
190 // If the source type of the cast is the type we're trying for then we can
191 // just return the source. There's no need to insert it because it is not
193 if (I->getOperand(0)->getType() == Ty)
194 return I->getOperand(0);
196 // Otherwise, must be the same type of cast, so just reinsert a new one.
197 // This also handles the case of zext(trunc(x)) -> zext(x).
198 Res = CastInst::CreateIntegerCast(I->getOperand(0), Ty,
199 Opc == Instruction::SExt);
201 case Instruction::Select: {
202 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
203 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
204 Res = SelectInst::Create(I->getOperand(0), True, False);
207 case Instruction::PHI: {
208 PHINode *OPN = cast<PHINode>(I);
209 PHINode *NPN = PHINode::Create(Ty, OPN->getNumIncomingValues());
210 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
211 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
212 NPN->addIncoming(V, OPN->getIncomingBlock(i));
218 // TODO: Can handle more cases here.
219 llvm_unreachable("Unreachable!");
224 return InsertNewInstWith(Res, *I);
228 /// This function is a wrapper around CastInst::isEliminableCastPair. It
229 /// simply extracts arguments and returns what that function returns.
230 static Instruction::CastOps
231 isEliminableCastPair(
232 const CastInst *CI, ///< The first cast instruction
233 unsigned opcode, ///< The opcode of the second cast instruction
234 Type *DstTy, ///< The target type for the second cast instruction
235 TargetData *TD ///< The target data for pointer size
238 Type *SrcTy = CI->getOperand(0)->getType(); // A from above
239 Type *MidTy = CI->getType(); // B from above
241 // Get the opcodes of the two Cast instructions
242 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
243 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
245 unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
247 TD ? TD->getIntPtrType(CI->getContext()) : 0);
249 // We don't want to form an inttoptr or ptrtoint that converts to an integer
250 // type that differs from the pointer size.
251 if ((Res == Instruction::IntToPtr &&
252 (!TD || SrcTy != TD->getIntPtrType(CI->getContext()))) ||
253 (Res == Instruction::PtrToInt &&
254 (!TD || DstTy != TD->getIntPtrType(CI->getContext()))))
257 return Instruction::CastOps(Res);
260 /// ShouldOptimizeCast - Return true if the cast from "V to Ty" actually
261 /// results in any code being generated and is interesting to optimize out. If
262 /// the cast can be eliminated by some other simple transformation, we prefer
263 /// to do the simplification first.
264 bool InstCombiner::ShouldOptimizeCast(Instruction::CastOps opc, const Value *V,
266 // Noop casts and casts of constants should be eliminated trivially.
267 if (V->getType() == Ty || isa<Constant>(V)) return false;
269 // If this is another cast that can be eliminated, we prefer to have it
271 if (const CastInst *CI = dyn_cast<CastInst>(V))
272 if (isEliminableCastPair(CI, opc, Ty, TD))
275 // If this is a vector sext from a compare, then we don't want to break the
276 // idiom where each element of the extended vector is either zero or all ones.
277 if (opc == Instruction::SExt && isa<CmpInst>(V) && Ty->isVectorTy())
284 /// @brief Implement the transforms common to all CastInst visitors.
285 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
286 Value *Src = CI.getOperand(0);
288 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
290 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
291 if (Instruction::CastOps opc =
292 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
293 // The first cast (CSrc) is eliminable so we need to fix up or replace
294 // the second cast (CI). CSrc will then have a good chance of being dead.
295 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
299 // If we are casting a select then fold the cast into the select
300 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
301 if (Instruction *NV = FoldOpIntoSelect(CI, SI))
304 // If we are casting a PHI then fold the cast into the PHI
305 if (isa<PHINode>(Src)) {
306 // We don't do this if this would create a PHI node with an illegal type if
307 // it is currently legal.
308 if (!Src->getType()->isIntegerTy() ||
309 !CI.getType()->isIntegerTy() ||
310 ShouldChangeType(CI.getType(), Src->getType()))
311 if (Instruction *NV = FoldOpIntoPhi(CI))
318 /// CanEvaluateTruncated - Return true if we can evaluate the specified
319 /// expression tree as type Ty instead of its larger type, and arrive with the
320 /// same value. This is used by code that tries to eliminate truncates.
322 /// Ty will always be a type smaller than V. We should return true if trunc(V)
323 /// can be computed by computing V in the smaller type. If V is an instruction,
324 /// then trunc(inst(x,y)) can be computed as inst(trunc(x),trunc(y)), which only
325 /// makes sense if x and y can be efficiently truncated.
327 /// This function works on both vectors and scalars.
329 static bool CanEvaluateTruncated(Value *V, Type *Ty) {
330 // We can always evaluate constants in another type.
331 if (isa<Constant>(V))
334 Instruction *I = dyn_cast<Instruction>(V);
335 if (!I) return false;
337 Type *OrigTy = V->getType();
339 // If this is an extension from the dest type, we can eliminate it, even if it
340 // has multiple uses.
341 if ((isa<ZExtInst>(I) || isa<SExtInst>(I)) &&
342 I->getOperand(0)->getType() == Ty)
345 // We can't extend or shrink something that has multiple uses: doing so would
346 // require duplicating the instruction in general, which isn't profitable.
347 if (!I->hasOneUse()) return false;
349 unsigned Opc = I->getOpcode();
351 case Instruction::Add:
352 case Instruction::Sub:
353 case Instruction::Mul:
354 case Instruction::And:
355 case Instruction::Or:
356 case Instruction::Xor:
357 // These operators can all arbitrarily be extended or truncated.
358 return CanEvaluateTruncated(I->getOperand(0), Ty) &&
359 CanEvaluateTruncated(I->getOperand(1), Ty);
361 case Instruction::UDiv:
362 case Instruction::URem: {
363 // UDiv and URem can be truncated if all the truncated bits are zero.
364 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
365 uint32_t BitWidth = Ty->getScalarSizeInBits();
366 if (BitWidth < OrigBitWidth) {
367 APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
368 if (MaskedValueIsZero(I->getOperand(0), Mask) &&
369 MaskedValueIsZero(I->getOperand(1), Mask)) {
370 return CanEvaluateTruncated(I->getOperand(0), Ty) &&
371 CanEvaluateTruncated(I->getOperand(1), Ty);
376 case Instruction::Shl:
377 // If we are truncating the result of this SHL, and if it's a shift of a
378 // constant amount, we can always perform a SHL in a smaller type.
379 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
380 uint32_t BitWidth = Ty->getScalarSizeInBits();
381 if (CI->getLimitedValue(BitWidth) < BitWidth)
382 return CanEvaluateTruncated(I->getOperand(0), Ty);
385 case Instruction::LShr:
386 // If this is a truncate of a logical shr, we can truncate it to a smaller
387 // lshr iff we know that the bits we would otherwise be shifting in are
389 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
390 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
391 uint32_t BitWidth = Ty->getScalarSizeInBits();
392 if (MaskedValueIsZero(I->getOperand(0),
393 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
394 CI->getLimitedValue(BitWidth) < BitWidth) {
395 return CanEvaluateTruncated(I->getOperand(0), Ty);
399 case Instruction::Trunc:
400 // trunc(trunc(x)) -> trunc(x)
402 case Instruction::ZExt:
403 case Instruction::SExt:
404 // trunc(ext(x)) -> ext(x) if the source type is smaller than the new dest
405 // trunc(ext(x)) -> trunc(x) if the source type is larger than the new dest
407 case Instruction::Select: {
408 SelectInst *SI = cast<SelectInst>(I);
409 return CanEvaluateTruncated(SI->getTrueValue(), Ty) &&
410 CanEvaluateTruncated(SI->getFalseValue(), Ty);
412 case Instruction::PHI: {
413 // We can change a phi if we can change all operands. Note that we never
414 // get into trouble with cyclic PHIs here because we only consider
415 // instructions with a single use.
416 PHINode *PN = cast<PHINode>(I);
417 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
418 if (!CanEvaluateTruncated(PN->getIncomingValue(i), Ty))
423 // TODO: Can handle more cases here.
430 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
431 if (Instruction *Result = commonCastTransforms(CI))
434 // See if we can simplify any instructions used by the input whose sole
435 // purpose is to compute bits we don't care about.
436 if (SimplifyDemandedInstructionBits(CI))
439 Value *Src = CI.getOperand(0);
440 Type *DestTy = CI.getType(), *SrcTy = Src->getType();
442 // Attempt to truncate the entire input expression tree to the destination
443 // type. Only do this if the dest type is a simple type, don't convert the
444 // expression tree to something weird like i93 unless the source is also
446 if ((DestTy->isVectorTy() || ShouldChangeType(SrcTy, DestTy)) &&
447 CanEvaluateTruncated(Src, DestTy)) {
449 // If this cast is a truncate, evaluting in a different type always
450 // eliminates the cast, so it is always a win.
451 DEBUG(dbgs() << "ICE: EvaluateInDifferentType converting expression type"
452 " to avoid cast: " << CI << '\n');
453 Value *Res = EvaluateInDifferentType(Src, DestTy, false);
454 assert(Res->getType() == DestTy);
455 return ReplaceInstUsesWith(CI, Res);
458 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0), likewise for vector.
459 if (DestTy->getScalarSizeInBits() == 1) {
460 Constant *One = ConstantInt::get(Src->getType(), 1);
461 Src = Builder->CreateAnd(Src, One);
462 Value *Zero = Constant::getNullValue(Src->getType());
463 return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
466 // Transform trunc(lshr (zext A), Cst) to eliminate one type conversion.
467 Value *A = 0; ConstantInt *Cst = 0;
468 if (Src->hasOneUse() &&
469 match(Src, m_LShr(m_ZExt(m_Value(A)), m_ConstantInt(Cst)))) {
470 // We have three types to worry about here, the type of A, the source of
471 // the truncate (MidSize), and the destination of the truncate. We know that
472 // ASize < MidSize and MidSize > ResultSize, but don't know the relation
473 // between ASize and ResultSize.
474 unsigned ASize = A->getType()->getPrimitiveSizeInBits();
476 // If the shift amount is larger than the size of A, then the result is
477 // known to be zero because all the input bits got shifted out.
478 if (Cst->getZExtValue() >= ASize)
479 return ReplaceInstUsesWith(CI, Constant::getNullValue(CI.getType()));
481 // Since we're doing an lshr and a zero extend, and know that the shift
482 // amount is smaller than ASize, it is always safe to do the shift in A's
483 // type, then zero extend or truncate to the result.
484 Value *Shift = Builder->CreateLShr(A, Cst->getZExtValue());
485 Shift->takeName(Src);
486 return CastInst::CreateIntegerCast(Shift, CI.getType(), false);
489 // Transform "trunc (and X, cst)" -> "and (trunc X), cst" so long as the dest
490 // type isn't non-native.
491 if (Src->hasOneUse() && isa<IntegerType>(Src->getType()) &&
492 ShouldChangeType(Src->getType(), CI.getType()) &&
493 match(Src, m_And(m_Value(A), m_ConstantInt(Cst)))) {
494 Value *NewTrunc = Builder->CreateTrunc(A, CI.getType(), A->getName()+".tr");
495 return BinaryOperator::CreateAnd(NewTrunc,
496 ConstantExpr::getTrunc(Cst, CI.getType()));
502 /// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
503 /// in order to eliminate the icmp.
504 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
506 // If we are just checking for a icmp eq of a single bit and zext'ing it
507 // to an integer, then shift the bit to the appropriate place and then
508 // cast to integer to avoid the comparison.
509 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
510 const APInt &Op1CV = Op1C->getValue();
512 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
513 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
514 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
515 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
516 if (!DoXform) return ICI;
518 Value *In = ICI->getOperand(0);
519 Value *Sh = ConstantInt::get(In->getType(),
520 In->getType()->getScalarSizeInBits()-1);
521 In = Builder->CreateLShr(In, Sh, In->getName()+".lobit");
522 if (In->getType() != CI.getType())
523 In = Builder->CreateIntCast(In, CI.getType(), false/*ZExt*/);
525 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
526 Constant *One = ConstantInt::get(In->getType(), 1);
527 In = Builder->CreateXor(In, One, In->getName()+".not");
530 return ReplaceInstUsesWith(CI, In);
535 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
536 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
537 // zext (X == 1) to i32 --> X iff X has only the low bit set.
538 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
539 // zext (X != 0) to i32 --> X iff X has only the low bit set.
540 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
541 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
542 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
543 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
544 // This only works for EQ and NE
546 // If Op1C some other power of two, convert:
547 uint32_t BitWidth = Op1C->getType()->getBitWidth();
548 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
549 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
550 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
552 APInt KnownZeroMask(~KnownZero);
553 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
554 if (!DoXform) return ICI;
556 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
557 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
558 // (X&4) == 2 --> false
559 // (X&4) != 2 --> true
560 Constant *Res = ConstantInt::get(Type::getInt1Ty(CI.getContext()),
562 Res = ConstantExpr::getZExt(Res, CI.getType());
563 return ReplaceInstUsesWith(CI, Res);
566 uint32_t ShiftAmt = KnownZeroMask.logBase2();
567 Value *In = ICI->getOperand(0);
569 // Perform a logical shr by shiftamt.
570 // Insert the shift to put the result in the low bit.
571 In = Builder->CreateLShr(In, ConstantInt::get(In->getType(),ShiftAmt),
572 In->getName()+".lobit");
575 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
576 Constant *One = ConstantInt::get(In->getType(), 1);
577 In = Builder->CreateXor(In, One);
580 if (CI.getType() == In->getType())
581 return ReplaceInstUsesWith(CI, In);
582 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
587 // icmp ne A, B is equal to xor A, B when A and B only really have one bit.
588 // It is also profitable to transform icmp eq into not(xor(A, B)) because that
589 // may lead to additional simplifications.
590 if (ICI->isEquality() && CI.getType() == ICI->getOperand(0)->getType()) {
591 if (IntegerType *ITy = dyn_cast<IntegerType>(CI.getType())) {
592 uint32_t BitWidth = ITy->getBitWidth();
593 Value *LHS = ICI->getOperand(0);
594 Value *RHS = ICI->getOperand(1);
596 APInt KnownZeroLHS(BitWidth, 0), KnownOneLHS(BitWidth, 0);
597 APInt KnownZeroRHS(BitWidth, 0), KnownOneRHS(BitWidth, 0);
598 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
599 ComputeMaskedBits(LHS, TypeMask, KnownZeroLHS, KnownOneLHS);
600 ComputeMaskedBits(RHS, TypeMask, KnownZeroRHS, KnownOneRHS);
602 if (KnownZeroLHS == KnownZeroRHS && KnownOneLHS == KnownOneRHS) {
603 APInt KnownBits = KnownZeroLHS | KnownOneLHS;
604 APInt UnknownBit = ~KnownBits;
605 if (UnknownBit.countPopulation() == 1) {
606 if (!DoXform) return ICI;
608 Value *Result = Builder->CreateXor(LHS, RHS);
610 // Mask off any bits that are set and won't be shifted away.
611 if (KnownOneLHS.uge(UnknownBit))
612 Result = Builder->CreateAnd(Result,
613 ConstantInt::get(ITy, UnknownBit));
615 // Shift the bit we're testing down to the lsb.
616 Result = Builder->CreateLShr(
617 Result, ConstantInt::get(ITy, UnknownBit.countTrailingZeros()));
619 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
620 Result = Builder->CreateXor(Result, ConstantInt::get(ITy, 1));
621 Result->takeName(ICI);
622 return ReplaceInstUsesWith(CI, Result);
631 /// CanEvaluateZExtd - Determine if the specified value can be computed in the
632 /// specified wider type and produce the same low bits. If not, return false.
634 /// If this function returns true, it can also return a non-zero number of bits
635 /// (in BitsToClear) which indicates that the value it computes is correct for
636 /// the zero extend, but that the additional BitsToClear bits need to be zero'd
637 /// out. For example, to promote something like:
639 /// %B = trunc i64 %A to i32
640 /// %C = lshr i32 %B, 8
641 /// %E = zext i32 %C to i64
643 /// CanEvaluateZExtd for the 'lshr' will return true, and BitsToClear will be
644 /// set to 8 to indicate that the promoted value needs to have bits 24-31
645 /// cleared in addition to bits 32-63. Since an 'and' will be generated to
646 /// clear the top bits anyway, doing this has no extra cost.
648 /// This function works on both vectors and scalars.
649 static bool CanEvaluateZExtd(Value *V, Type *Ty, unsigned &BitsToClear) {
651 if (isa<Constant>(V))
654 Instruction *I = dyn_cast<Instruction>(V);
655 if (!I) return false;
657 // If the input is a truncate from the destination type, we can trivially
658 // eliminate it, even if it has multiple uses.
659 // FIXME: This is currently disabled until codegen can handle this without
660 // pessimizing code, PR5997.
661 if (0 && isa<TruncInst>(I) && I->getOperand(0)->getType() == Ty)
664 // We can't extend or shrink something that has multiple uses: doing so would
665 // require duplicating the instruction in general, which isn't profitable.
666 if (!I->hasOneUse()) return false;
668 unsigned Opc = I->getOpcode(), Tmp;
670 case Instruction::ZExt: // zext(zext(x)) -> zext(x).
671 case Instruction::SExt: // zext(sext(x)) -> sext(x).
672 case Instruction::Trunc: // zext(trunc(x)) -> trunc(x) or zext(x)
674 case Instruction::And:
675 case Instruction::Or:
676 case Instruction::Xor:
677 case Instruction::Add:
678 case Instruction::Sub:
679 case Instruction::Mul:
680 case Instruction::Shl:
681 if (!CanEvaluateZExtd(I->getOperand(0), Ty, BitsToClear) ||
682 !CanEvaluateZExtd(I->getOperand(1), Ty, Tmp))
684 // These can all be promoted if neither operand has 'bits to clear'.
685 if (BitsToClear == 0 && Tmp == 0)
688 // If the operation is an AND/OR/XOR and the bits to clear are zero in the
689 // other side, BitsToClear is ok.
691 (Opc == Instruction::And || Opc == Instruction::Or ||
692 Opc == Instruction::Xor)) {
693 // We use MaskedValueIsZero here for generality, but the case we care
694 // about the most is constant RHS.
695 unsigned VSize = V->getType()->getScalarSizeInBits();
696 if (MaskedValueIsZero(I->getOperand(1),
697 APInt::getHighBitsSet(VSize, BitsToClear)))
701 // Otherwise, we don't know how to analyze this BitsToClear case yet.
704 case Instruction::LShr:
705 // We can promote lshr(x, cst) if we can promote x. This requires the
706 // ultimate 'and' to clear out the high zero bits we're clearing out though.
707 if (ConstantInt *Amt = dyn_cast<ConstantInt>(I->getOperand(1))) {
708 if (!CanEvaluateZExtd(I->getOperand(0), Ty, BitsToClear))
710 BitsToClear += Amt->getZExtValue();
711 if (BitsToClear > V->getType()->getScalarSizeInBits())
712 BitsToClear = V->getType()->getScalarSizeInBits();
715 // Cannot promote variable LSHR.
717 case Instruction::Select:
718 if (!CanEvaluateZExtd(I->getOperand(1), Ty, Tmp) ||
719 !CanEvaluateZExtd(I->getOperand(2), Ty, BitsToClear) ||
720 // TODO: If important, we could handle the case when the BitsToClear are
721 // known zero in the disagreeing side.
726 case Instruction::PHI: {
727 // We can change a phi if we can change all operands. Note that we never
728 // get into trouble with cyclic PHIs here because we only consider
729 // instructions with a single use.
730 PHINode *PN = cast<PHINode>(I);
731 if (!CanEvaluateZExtd(PN->getIncomingValue(0), Ty, BitsToClear))
733 for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i)
734 if (!CanEvaluateZExtd(PN->getIncomingValue(i), Ty, Tmp) ||
735 // TODO: If important, we could handle the case when the BitsToClear
736 // are known zero in the disagreeing input.
742 // TODO: Can handle more cases here.
747 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
748 // If this zero extend is only used by a truncate, let the truncate by
749 // eliminated before we try to optimize this zext.
750 if (CI.hasOneUse() && isa<TruncInst>(CI.use_back()))
753 // If one of the common conversion will work, do it.
754 if (Instruction *Result = commonCastTransforms(CI))
757 // See if we can simplify any instructions used by the input whose sole
758 // purpose is to compute bits we don't care about.
759 if (SimplifyDemandedInstructionBits(CI))
762 Value *Src = CI.getOperand(0);
763 Type *SrcTy = Src->getType(), *DestTy = CI.getType();
765 // Attempt to extend the entire input expression tree to the destination
766 // type. Only do this if the dest type is a simple type, don't convert the
767 // expression tree to something weird like i93 unless the source is also
769 unsigned BitsToClear;
770 if ((DestTy->isVectorTy() || ShouldChangeType(SrcTy, DestTy)) &&
771 CanEvaluateZExtd(Src, DestTy, BitsToClear)) {
772 assert(BitsToClear < SrcTy->getScalarSizeInBits() &&
773 "Unreasonable BitsToClear");
775 // Okay, we can transform this! Insert the new expression now.
776 DEBUG(dbgs() << "ICE: EvaluateInDifferentType converting expression type"
777 " to avoid zero extend: " << CI);
778 Value *Res = EvaluateInDifferentType(Src, DestTy, false);
779 assert(Res->getType() == DestTy);
781 uint32_t SrcBitsKept = SrcTy->getScalarSizeInBits()-BitsToClear;
782 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
784 // If the high bits are already filled with zeros, just replace this
785 // cast with the result.
786 if (MaskedValueIsZero(Res, APInt::getHighBitsSet(DestBitSize,
787 DestBitSize-SrcBitsKept)))
788 return ReplaceInstUsesWith(CI, Res);
790 // We need to emit an AND to clear the high bits.
791 Constant *C = ConstantInt::get(Res->getType(),
792 APInt::getLowBitsSet(DestBitSize, SrcBitsKept));
793 return BinaryOperator::CreateAnd(Res, C);
796 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
797 // types and if the sizes are just right we can convert this into a logical
798 // 'and' which will be much cheaper than the pair of casts.
799 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
800 // TODO: Subsume this into EvaluateInDifferentType.
802 // Get the sizes of the types involved. We know that the intermediate type
803 // will be smaller than A or C, but don't know the relation between A and C.
804 Value *A = CSrc->getOperand(0);
805 unsigned SrcSize = A->getType()->getScalarSizeInBits();
806 unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
807 unsigned DstSize = CI.getType()->getScalarSizeInBits();
808 // If we're actually extending zero bits, then if
809 // SrcSize < DstSize: zext(a & mask)
810 // SrcSize == DstSize: a & mask
811 // SrcSize > DstSize: trunc(a) & mask
812 if (SrcSize < DstSize) {
813 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
814 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
815 Value *And = Builder->CreateAnd(A, AndConst, CSrc->getName()+".mask");
816 return new ZExtInst(And, CI.getType());
819 if (SrcSize == DstSize) {
820 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
821 return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
824 if (SrcSize > DstSize) {
825 Value *Trunc = Builder->CreateTrunc(A, CI.getType());
826 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
827 return BinaryOperator::CreateAnd(Trunc,
828 ConstantInt::get(Trunc->getType(),
833 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
834 return transformZExtICmp(ICI, CI);
836 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
837 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
838 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
839 // of the (zext icmp) will be transformed.
840 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
841 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
842 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
843 (transformZExtICmp(LHS, CI, false) ||
844 transformZExtICmp(RHS, CI, false))) {
845 Value *LCast = Builder->CreateZExt(LHS, CI.getType(), LHS->getName());
846 Value *RCast = Builder->CreateZExt(RHS, CI.getType(), RHS->getName());
847 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
851 // zext(trunc(t) & C) -> (t & zext(C)).
852 if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
853 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
854 if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
855 Value *TI0 = TI->getOperand(0);
856 if (TI0->getType() == CI.getType())
858 BinaryOperator::CreateAnd(TI0,
859 ConstantExpr::getZExt(C, CI.getType()));
862 // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
863 if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
864 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
865 if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
866 if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
867 And->getOperand(1) == C)
868 if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
869 Value *TI0 = TI->getOperand(0);
870 if (TI0->getType() == CI.getType()) {
871 Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
872 Value *NewAnd = Builder->CreateAnd(TI0, ZC);
873 return BinaryOperator::CreateXor(NewAnd, ZC);
877 // zext (xor i1 X, true) to i32 --> xor (zext i1 X to i32), 1
879 if (SrcI && SrcI->hasOneUse() && SrcI->getType()->isIntegerTy(1) &&
880 match(SrcI, m_Not(m_Value(X))) &&
881 (!X->hasOneUse() || !isa<CmpInst>(X))) {
882 Value *New = Builder->CreateZExt(X, CI.getType());
883 return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
889 /// transformSExtICmp - Transform (sext icmp) to bitwise / integer operations
890 /// in order to eliminate the icmp.
891 Instruction *InstCombiner::transformSExtICmp(ICmpInst *ICI, Instruction &CI) {
892 Value *Op0 = ICI->getOperand(0), *Op1 = ICI->getOperand(1);
893 ICmpInst::Predicate Pred = ICI->getPredicate();
895 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
896 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if negative
897 // (x >s -1) ? -1 : 0 -> not (ashr x, 31) -> all ones if positive
898 if ((Pred == ICmpInst::ICMP_SLT && Op1C->isZero()) ||
899 (Pred == ICmpInst::ICMP_SGT && Op1C->isAllOnesValue())) {
901 Value *Sh = ConstantInt::get(Op0->getType(),
902 Op0->getType()->getScalarSizeInBits()-1);
903 Value *In = Builder->CreateAShr(Op0, Sh, Op0->getName()+".lobit");
904 if (In->getType() != CI.getType())
905 In = Builder->CreateIntCast(In, CI.getType(), true/*SExt*/);
907 if (Pred == ICmpInst::ICMP_SGT)
908 In = Builder->CreateNot(In, In->getName()+".not");
909 return ReplaceInstUsesWith(CI, In);
912 // If we know that only one bit of the LHS of the icmp can be set and we
913 // have an equality comparison with zero or a power of 2, we can transform
914 // the icmp and sext into bitwise/integer operations.
915 if (ICI->hasOneUse() &&
916 ICI->isEquality() && (Op1C->isZero() || Op1C->getValue().isPowerOf2())){
917 unsigned BitWidth = Op1C->getType()->getBitWidth();
918 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
919 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
920 ComputeMaskedBits(Op0, TypeMask, KnownZero, KnownOne);
922 APInt KnownZeroMask(~KnownZero);
923 if (KnownZeroMask.isPowerOf2()) {
924 Value *In = ICI->getOperand(0);
926 // If the icmp tests for a known zero bit we can constant fold it.
927 if (!Op1C->isZero() && Op1C->getValue() != KnownZeroMask) {
928 Value *V = Pred == ICmpInst::ICMP_NE ?
929 ConstantInt::getAllOnesValue(CI.getType()) :
930 ConstantInt::getNullValue(CI.getType());
931 return ReplaceInstUsesWith(CI, V);
934 if (!Op1C->isZero() == (Pred == ICmpInst::ICMP_NE)) {
935 // sext ((x & 2^n) == 0) -> (x >> n) - 1
936 // sext ((x & 2^n) != 2^n) -> (x >> n) - 1
937 unsigned ShiftAmt = KnownZeroMask.countTrailingZeros();
938 // Perform a right shift to place the desired bit in the LSB.
940 In = Builder->CreateLShr(In,
941 ConstantInt::get(In->getType(), ShiftAmt));
943 // At this point "In" is either 1 or 0. Subtract 1 to turn
944 // {1, 0} -> {0, -1}.
945 In = Builder->CreateAdd(In,
946 ConstantInt::getAllOnesValue(In->getType()),
949 // sext ((x & 2^n) != 0) -> (x << bitwidth-n) a>> bitwidth-1
950 // sext ((x & 2^n) == 2^n) -> (x << bitwidth-n) a>> bitwidth-1
951 unsigned ShiftAmt = KnownZeroMask.countLeadingZeros();
952 // Perform a left shift to place the desired bit in the MSB.
954 In = Builder->CreateShl(In,
955 ConstantInt::get(In->getType(), ShiftAmt));
957 // Distribute the bit over the whole bit width.
958 In = Builder->CreateAShr(In, ConstantInt::get(In->getType(),
959 BitWidth - 1), "sext");
962 if (CI.getType() == In->getType())
963 return ReplaceInstUsesWith(CI, In);
964 return CastInst::CreateIntegerCast(In, CI.getType(), true/*SExt*/);
969 // vector (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed.
970 if (VectorType *VTy = dyn_cast<VectorType>(CI.getType())) {
971 if (Pred == ICmpInst::ICMP_SLT && match(Op1, m_Zero()) &&
972 Op0->getType() == CI.getType()) {
973 Type *EltTy = VTy->getElementType();
975 // splat the shift constant to a constant vector.
976 Constant *VSh = ConstantInt::get(VTy, EltTy->getScalarSizeInBits()-1);
977 Value *In = Builder->CreateAShr(Op0, VSh, Op0->getName()+".lobit");
978 return ReplaceInstUsesWith(CI, In);
985 /// CanEvaluateSExtd - Return true if we can take the specified value
986 /// and return it as type Ty without inserting any new casts and without
987 /// changing the value of the common low bits. This is used by code that tries
988 /// to promote integer operations to a wider types will allow us to eliminate
991 /// This function works on both vectors and scalars.
993 static bool CanEvaluateSExtd(Value *V, Type *Ty) {
994 assert(V->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits() &&
995 "Can't sign extend type to a smaller type");
996 // If this is a constant, it can be trivially promoted.
997 if (isa<Constant>(V))
1000 Instruction *I = dyn_cast<Instruction>(V);
1001 if (!I) return false;
1003 // If this is a truncate from the dest type, we can trivially eliminate it,
1004 // even if it has multiple uses.
1005 // FIXME: This is currently disabled until codegen can handle this without
1006 // pessimizing code, PR5997.
1007 if (0 && isa<TruncInst>(I) && I->getOperand(0)->getType() == Ty)
1010 // We can't extend or shrink something that has multiple uses: doing so would
1011 // require duplicating the instruction in general, which isn't profitable.
1012 if (!I->hasOneUse()) return false;
1014 switch (I->getOpcode()) {
1015 case Instruction::SExt: // sext(sext(x)) -> sext(x)
1016 case Instruction::ZExt: // sext(zext(x)) -> zext(x)
1017 case Instruction::Trunc: // sext(trunc(x)) -> trunc(x) or sext(x)
1019 case Instruction::And:
1020 case Instruction::Or:
1021 case Instruction::Xor:
1022 case Instruction::Add:
1023 case Instruction::Sub:
1024 case Instruction::Mul:
1025 // These operators can all arbitrarily be extended if their inputs can.
1026 return CanEvaluateSExtd(I->getOperand(0), Ty) &&
1027 CanEvaluateSExtd(I->getOperand(1), Ty);
1029 //case Instruction::Shl: TODO
1030 //case Instruction::LShr: TODO
1032 case Instruction::Select:
1033 return CanEvaluateSExtd(I->getOperand(1), Ty) &&
1034 CanEvaluateSExtd(I->getOperand(2), Ty);
1036 case Instruction::PHI: {
1037 // We can change a phi if we can change all operands. Note that we never
1038 // get into trouble with cyclic PHIs here because we only consider
1039 // instructions with a single use.
1040 PHINode *PN = cast<PHINode>(I);
1041 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1042 if (!CanEvaluateSExtd(PN->getIncomingValue(i), Ty)) return false;
1046 // TODO: Can handle more cases here.
1053 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
1054 // If this sign extend is only used by a truncate, let the truncate by
1055 // eliminated before we try to optimize this zext.
1056 if (CI.hasOneUse() && isa<TruncInst>(CI.use_back()))
1059 if (Instruction *I = commonCastTransforms(CI))
1062 // See if we can simplify any instructions used by the input whose sole
1063 // purpose is to compute bits we don't care about.
1064 if (SimplifyDemandedInstructionBits(CI))
1067 Value *Src = CI.getOperand(0);
1068 Type *SrcTy = Src->getType(), *DestTy = CI.getType();
1070 // Attempt to extend the entire input expression tree to the destination
1071 // type. Only do this if the dest type is a simple type, don't convert the
1072 // expression tree to something weird like i93 unless the source is also
1074 if ((DestTy->isVectorTy() || ShouldChangeType(SrcTy, DestTy)) &&
1075 CanEvaluateSExtd(Src, DestTy)) {
1076 // Okay, we can transform this! Insert the new expression now.
1077 DEBUG(dbgs() << "ICE: EvaluateInDifferentType converting expression type"
1078 " to avoid sign extend: " << CI);
1079 Value *Res = EvaluateInDifferentType(Src, DestTy, true);
1080 assert(Res->getType() == DestTy);
1082 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
1083 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
1085 // If the high bits are already filled with sign bit, just replace this
1086 // cast with the result.
1087 if (ComputeNumSignBits(Res) > DestBitSize - SrcBitSize)
1088 return ReplaceInstUsesWith(CI, Res);
1090 // We need to emit a shl + ashr to do the sign extend.
1091 Value *ShAmt = ConstantInt::get(DestTy, DestBitSize-SrcBitSize);
1092 return BinaryOperator::CreateAShr(Builder->CreateShl(Res, ShAmt, "sext"),
1096 // If this input is a trunc from our destination, then turn sext(trunc(x))
1098 if (TruncInst *TI = dyn_cast<TruncInst>(Src))
1099 if (TI->hasOneUse() && TI->getOperand(0)->getType() == DestTy) {
1100 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
1101 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
1103 // We need to emit a shl + ashr to do the sign extend.
1104 Value *ShAmt = ConstantInt::get(DestTy, DestBitSize-SrcBitSize);
1105 Value *Res = Builder->CreateShl(TI->getOperand(0), ShAmt, "sext");
1106 return BinaryOperator::CreateAShr(Res, ShAmt);
1109 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
1110 return transformSExtICmp(ICI, CI);
1112 // If the input is a shl/ashr pair of a same constant, then this is a sign
1113 // extension from a smaller value. If we could trust arbitrary bitwidth
1114 // integers, we could turn this into a truncate to the smaller bit and then
1115 // use a sext for the whole extension. Since we don't, look deeper and check
1116 // for a truncate. If the source and dest are the same type, eliminate the
1117 // trunc and extend and just do shifts. For example, turn:
1118 // %a = trunc i32 %i to i8
1119 // %b = shl i8 %a, 6
1120 // %c = ashr i8 %b, 6
1121 // %d = sext i8 %c to i32
1123 // %a = shl i32 %i, 30
1124 // %d = ashr i32 %a, 30
1126 // TODO: Eventually this could be subsumed by EvaluateInDifferentType.
1127 ConstantInt *BA = 0, *CA = 0;
1128 if (match(Src, m_AShr(m_Shl(m_Trunc(m_Value(A)), m_ConstantInt(BA)),
1129 m_ConstantInt(CA))) &&
1130 BA == CA && A->getType() == CI.getType()) {
1131 unsigned MidSize = Src->getType()->getScalarSizeInBits();
1132 unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
1133 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
1134 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
1135 A = Builder->CreateShl(A, ShAmtV, CI.getName());
1136 return BinaryOperator::CreateAShr(A, ShAmtV);
1143 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
1144 /// in the specified FP type without changing its value.
1145 static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
1147 APFloat F = CFP->getValueAPF();
1148 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
1150 return ConstantFP::get(CFP->getContext(), F);
1154 /// LookThroughFPExtensions - If this is an fp extension instruction, look
1155 /// through it until we get the source value.
1156 static Value *LookThroughFPExtensions(Value *V) {
1157 if (Instruction *I = dyn_cast<Instruction>(V))
1158 if (I->getOpcode() == Instruction::FPExt)
1159 return LookThroughFPExtensions(I->getOperand(0));
1161 // If this value is a constant, return the constant in the smallest FP type
1162 // that can accurately represent it. This allows us to turn
1163 // (float)((double)X+2.0) into x+2.0f.
1164 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
1165 if (CFP->getType() == Type::getPPC_FP128Ty(V->getContext()))
1166 return V; // No constant folding of this.
1167 // See if the value can be truncated to float and then reextended.
1168 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
1170 if (CFP->getType()->isDoubleTy())
1171 return V; // Won't shrink.
1172 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
1174 // Don't try to shrink to various long double types.
1180 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
1181 if (Instruction *I = commonCastTransforms(CI))
1184 // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
1185 // smaller than the destination type, we can eliminate the truncate by doing
1186 // the add as the smaller type. This applies to fadd/fsub/fmul/fdiv as well
1187 // as many builtins (sqrt, etc).
1188 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
1189 if (OpI && OpI->hasOneUse()) {
1190 switch (OpI->getOpcode()) {
1192 case Instruction::FAdd:
1193 case Instruction::FSub:
1194 case Instruction::FMul:
1195 case Instruction::FDiv:
1196 case Instruction::FRem:
1197 Type *SrcTy = OpI->getType();
1198 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
1199 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
1200 if (LHSTrunc->getType() != SrcTy &&
1201 RHSTrunc->getType() != SrcTy) {
1202 unsigned DstSize = CI.getType()->getScalarSizeInBits();
1203 // If the source types were both smaller than the destination type of
1204 // the cast, do this xform.
1205 if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
1206 RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
1207 LHSTrunc = Builder->CreateFPExt(LHSTrunc, CI.getType());
1208 RHSTrunc = Builder->CreateFPExt(RHSTrunc, CI.getType());
1209 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
1216 // Fold (fptrunc (sqrt (fpext x))) -> (sqrtf x)
1217 const TargetLibraryInfo &TLI = getAnalysis<TargetLibraryInfo>();
1218 CallInst *Call = dyn_cast<CallInst>(CI.getOperand(0));
1219 if (Call && Call->getCalledFunction() && TLI.has(LibFunc::sqrtf) &&
1220 Call->getCalledFunction()->getName() == TLI.getName(LibFunc::sqrt) &&
1221 Call->getNumArgOperands() == 1 &&
1222 Call->hasOneUse()) {
1223 CastInst *Arg = dyn_cast<CastInst>(Call->getArgOperand(0));
1224 if (Arg && Arg->getOpcode() == Instruction::FPExt &&
1225 CI.getType()->isFloatTy() &&
1226 Call->getType()->isDoubleTy() &&
1227 Arg->getType()->isDoubleTy() &&
1228 Arg->getOperand(0)->getType()->isFloatTy()) {
1229 Function *Callee = Call->getCalledFunction();
1230 Module *M = CI.getParent()->getParent()->getParent();
1231 Constant *SqrtfFunc = M->getOrInsertFunction("sqrtf",
1232 Callee->getAttributes(),
1233 Builder->getFloatTy(),
1234 Builder->getFloatTy(),
1236 CallInst *ret = CallInst::Create(SqrtfFunc, Arg->getOperand(0),
1238 ret->setAttributes(Callee->getAttributes());
1241 // Remove the old Call. With -fmath-errno, it won't get marked readnone.
1242 ReplaceInstUsesWith(*Call, UndefValue::get(Call->getType()));
1243 EraseInstFromFunction(*Call);
1251 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
1252 return commonCastTransforms(CI);
1255 Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
1256 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
1258 return commonCastTransforms(FI);
1260 // fptoui(uitofp(X)) --> X
1261 // fptoui(sitofp(X)) --> X
1262 // This is safe if the intermediate type has enough bits in its mantissa to
1263 // accurately represent all values of X. For example, do not do this with
1264 // i64->float->i64. This is also safe for sitofp case, because any negative
1265 // 'X' value would cause an undefined result for the fptoui.
1266 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
1267 OpI->getOperand(0)->getType() == FI.getType() &&
1268 (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
1269 OpI->getType()->getFPMantissaWidth())
1270 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
1272 return commonCastTransforms(FI);
1275 Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
1276 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
1278 return commonCastTransforms(FI);
1280 // fptosi(sitofp(X)) --> X
1281 // fptosi(uitofp(X)) --> X
1282 // This is safe if the intermediate type has enough bits in its mantissa to
1283 // accurately represent all values of X. For example, do not do this with
1284 // i64->float->i64. This is also safe for sitofp case, because any negative
1285 // 'X' value would cause an undefined result for the fptoui.
1286 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
1287 OpI->getOperand(0)->getType() == FI.getType() &&
1288 (int)FI.getType()->getScalarSizeInBits() <=
1289 OpI->getType()->getFPMantissaWidth())
1290 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
1292 return commonCastTransforms(FI);
1295 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
1296 return commonCastTransforms(CI);
1299 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
1300 return commonCastTransforms(CI);
1303 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
1304 // If the source integer type is not the intptr_t type for this target, do a
1305 // trunc or zext to the intptr_t type, then inttoptr of it. This allows the
1306 // cast to be exposed to other transforms.
1308 if (CI.getOperand(0)->getType()->getScalarSizeInBits() >
1309 TD->getPointerSizeInBits()) {
1310 Value *P = Builder->CreateTrunc(CI.getOperand(0),
1311 TD->getIntPtrType(CI.getContext()));
1312 return new IntToPtrInst(P, CI.getType());
1314 if (CI.getOperand(0)->getType()->getScalarSizeInBits() <
1315 TD->getPointerSizeInBits()) {
1316 Value *P = Builder->CreateZExt(CI.getOperand(0),
1317 TD->getIntPtrType(CI.getContext()));
1318 return new IntToPtrInst(P, CI.getType());
1322 if (Instruction *I = commonCastTransforms(CI))
1328 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
1329 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
1330 Value *Src = CI.getOperand(0);
1332 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
1333 // If casting the result of a getelementptr instruction with no offset, turn
1334 // this into a cast of the original pointer!
1335 if (GEP->hasAllZeroIndices()) {
1336 // Changing the cast operand is usually not a good idea but it is safe
1337 // here because the pointer operand is being replaced with another
1338 // pointer operand so the opcode doesn't need to change.
1340 CI.setOperand(0, GEP->getOperand(0));
1344 // If the GEP has a single use, and the base pointer is a bitcast, and the
1345 // GEP computes a constant offset, see if we can convert these three
1346 // instructions into fewer. This typically happens with unions and other
1347 // non-type-safe code.
1348 if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0)) &&
1349 GEP->hasAllConstantIndices()) {
1350 // We are guaranteed to get a constant from EmitGEPOffset.
1351 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP));
1352 int64_t Offset = OffsetV->getSExtValue();
1354 // Get the base pointer input of the bitcast, and the type it points to.
1355 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
1357 cast<PointerType>(OrigBase->getType())->getElementType();
1358 SmallVector<Value*, 8> NewIndices;
1359 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices)) {
1360 // If we were able to index down into an element, create the GEP
1361 // and bitcast the result. This eliminates one bitcast, potentially
1363 Value *NGEP = cast<GEPOperator>(GEP)->isInBounds() ?
1364 Builder->CreateInBoundsGEP(OrigBase, NewIndices) :
1365 Builder->CreateGEP(OrigBase, NewIndices);
1366 NGEP->takeName(GEP);
1368 if (isa<BitCastInst>(CI))
1369 return new BitCastInst(NGEP, CI.getType());
1370 assert(isa<PtrToIntInst>(CI));
1371 return new PtrToIntInst(NGEP, CI.getType());
1376 return commonCastTransforms(CI);
1379 Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
1380 // If the destination integer type is not the intptr_t type for this target,
1381 // do a ptrtoint to intptr_t then do a trunc or zext. This allows the cast
1382 // to be exposed to other transforms.
1384 if (CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
1385 Value *P = Builder->CreatePtrToInt(CI.getOperand(0),
1386 TD->getIntPtrType(CI.getContext()));
1387 return new TruncInst(P, CI.getType());
1389 if (CI.getType()->getScalarSizeInBits() > TD->getPointerSizeInBits()) {
1390 Value *P = Builder->CreatePtrToInt(CI.getOperand(0),
1391 TD->getIntPtrType(CI.getContext()));
1392 return new ZExtInst(P, CI.getType());
1396 return commonPointerCastTransforms(CI);
1399 /// OptimizeVectorResize - This input value (which is known to have vector type)
1400 /// is being zero extended or truncated to the specified vector type. Try to
1401 /// replace it with a shuffle (and vector/vector bitcast) if possible.
1403 /// The source and destination vector types may have different element types.
1404 static Instruction *OptimizeVectorResize(Value *InVal, VectorType *DestTy,
1406 // We can only do this optimization if the output is a multiple of the input
1407 // element size, or the input is a multiple of the output element size.
1408 // Convert the input type to have the same element type as the output.
1409 VectorType *SrcTy = cast<VectorType>(InVal->getType());
1411 if (SrcTy->getElementType() != DestTy->getElementType()) {
1412 // The input types don't need to be identical, but for now they must be the
1413 // same size. There is no specific reason we couldn't handle things like
1414 // <4 x i16> -> <4 x i32> by bitcasting to <2 x i32> but haven't gotten
1416 if (SrcTy->getElementType()->getPrimitiveSizeInBits() !=
1417 DestTy->getElementType()->getPrimitiveSizeInBits())
1420 SrcTy = VectorType::get(DestTy->getElementType(), SrcTy->getNumElements());
1421 InVal = IC.Builder->CreateBitCast(InVal, SrcTy);
1424 // Now that the element types match, get the shuffle mask and RHS of the
1425 // shuffle to use, which depends on whether we're increasing or decreasing the
1426 // size of the input.
1427 SmallVector<Constant*, 16> ShuffleMask;
1429 IntegerType *Int32Ty = Type::getInt32Ty(SrcTy->getContext());
1431 if (SrcTy->getNumElements() > DestTy->getNumElements()) {
1432 // If we're shrinking the number of elements, just shuffle in the low
1433 // elements from the input and use undef as the second shuffle input.
1434 V2 = UndefValue::get(SrcTy);
1435 for (unsigned i = 0, e = DestTy->getNumElements(); i != e; ++i)
1436 ShuffleMask.push_back(ConstantInt::get(Int32Ty, i));
1439 // If we're increasing the number of elements, shuffle in all of the
1440 // elements from InVal and fill the rest of the result elements with zeros
1441 // from a constant zero.
1442 V2 = Constant::getNullValue(SrcTy);
1443 unsigned SrcElts = SrcTy->getNumElements();
1444 for (unsigned i = 0, e = SrcElts; i != e; ++i)
1445 ShuffleMask.push_back(ConstantInt::get(Int32Ty, i));
1447 // The excess elements reference the first element of the zero input.
1448 ShuffleMask.append(DestTy->getNumElements()-SrcElts,
1449 ConstantInt::get(Int32Ty, SrcElts));
1452 return new ShuffleVectorInst(InVal, V2, ConstantVector::get(ShuffleMask));
1455 static bool isMultipleOfTypeSize(unsigned Value, Type *Ty) {
1456 return Value % Ty->getPrimitiveSizeInBits() == 0;
1459 static unsigned getTypeSizeIndex(unsigned Value, Type *Ty) {
1460 return Value / Ty->getPrimitiveSizeInBits();
1463 /// CollectInsertionElements - V is a value which is inserted into a vector of
1464 /// VecEltTy. Look through the value to see if we can decompose it into
1465 /// insertions into the vector. See the example in the comment for
1466 /// OptimizeIntegerToVectorInsertions for the pattern this handles.
1467 /// The type of V is always a non-zero multiple of VecEltTy's size.
1469 /// This returns false if the pattern can't be matched or true if it can,
1470 /// filling in Elements with the elements found here.
1471 static bool CollectInsertionElements(Value *V, unsigned ElementIndex,
1472 SmallVectorImpl<Value*> &Elements,
1474 // Undef values never contribute useful bits to the result.
1475 if (isa<UndefValue>(V)) return true;
1477 // If we got down to a value of the right type, we win, try inserting into the
1479 if (V->getType() == VecEltTy) {
1480 // Inserting null doesn't actually insert any elements.
1481 if (Constant *C = dyn_cast<Constant>(V))
1482 if (C->isNullValue())
1485 // Fail if multiple elements are inserted into this slot.
1486 if (ElementIndex >= Elements.size() || Elements[ElementIndex] != 0)
1489 Elements[ElementIndex] = V;
1493 if (Constant *C = dyn_cast<Constant>(V)) {
1494 // Figure out the # elements this provides, and bitcast it or slice it up
1496 unsigned NumElts = getTypeSizeIndex(C->getType()->getPrimitiveSizeInBits(),
1498 // If the constant is the size of a vector element, we just need to bitcast
1499 // it to the right type so it gets properly inserted.
1501 return CollectInsertionElements(ConstantExpr::getBitCast(C, VecEltTy),
1502 ElementIndex, Elements, VecEltTy);
1504 // Okay, this is a constant that covers multiple elements. Slice it up into
1505 // pieces and insert each element-sized piece into the vector.
1506 if (!isa<IntegerType>(C->getType()))
1507 C = ConstantExpr::getBitCast(C, IntegerType::get(V->getContext(),
1508 C->getType()->getPrimitiveSizeInBits()));
1509 unsigned ElementSize = VecEltTy->getPrimitiveSizeInBits();
1510 Type *ElementIntTy = IntegerType::get(C->getContext(), ElementSize);
1512 for (unsigned i = 0; i != NumElts; ++i) {
1513 Constant *Piece = ConstantExpr::getLShr(C, ConstantInt::get(C->getType(),
1515 Piece = ConstantExpr::getTrunc(Piece, ElementIntTy);
1516 if (!CollectInsertionElements(Piece, ElementIndex+i, Elements, VecEltTy))
1522 if (!V->hasOneUse()) return false;
1524 Instruction *I = dyn_cast<Instruction>(V);
1525 if (I == 0) return false;
1526 switch (I->getOpcode()) {
1527 default: return false; // Unhandled case.
1528 case Instruction::BitCast:
1529 return CollectInsertionElements(I->getOperand(0), ElementIndex,
1530 Elements, VecEltTy);
1531 case Instruction::ZExt:
1532 if (!isMultipleOfTypeSize(
1533 I->getOperand(0)->getType()->getPrimitiveSizeInBits(),
1536 return CollectInsertionElements(I->getOperand(0), ElementIndex,
1537 Elements, VecEltTy);
1538 case Instruction::Or:
1539 return CollectInsertionElements(I->getOperand(0), ElementIndex,
1540 Elements, VecEltTy) &&
1541 CollectInsertionElements(I->getOperand(1), ElementIndex,
1542 Elements, VecEltTy);
1543 case Instruction::Shl: {
1544 // Must be shifting by a constant that is a multiple of the element size.
1545 ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1));
1546 if (CI == 0) return false;
1547 if (!isMultipleOfTypeSize(CI->getZExtValue(), VecEltTy)) return false;
1548 unsigned IndexShift = getTypeSizeIndex(CI->getZExtValue(), VecEltTy);
1550 return CollectInsertionElements(I->getOperand(0), ElementIndex+IndexShift,
1551 Elements, VecEltTy);
1558 /// OptimizeIntegerToVectorInsertions - If the input is an 'or' instruction, we
1559 /// may be doing shifts and ors to assemble the elements of the vector manually.
1560 /// Try to rip the code out and replace it with insertelements. This is to
1561 /// optimize code like this:
1563 /// %tmp37 = bitcast float %inc to i32
1564 /// %tmp38 = zext i32 %tmp37 to i64
1565 /// %tmp31 = bitcast float %inc5 to i32
1566 /// %tmp32 = zext i32 %tmp31 to i64
1567 /// %tmp33 = shl i64 %tmp32, 32
1568 /// %ins35 = or i64 %tmp33, %tmp38
1569 /// %tmp43 = bitcast i64 %ins35 to <2 x float>
1571 /// Into two insertelements that do "buildvector{%inc, %inc5}".
1572 static Value *OptimizeIntegerToVectorInsertions(BitCastInst &CI,
1574 VectorType *DestVecTy = cast<VectorType>(CI.getType());
1575 Value *IntInput = CI.getOperand(0);
1577 SmallVector<Value*, 8> Elements(DestVecTy->getNumElements());
1578 if (!CollectInsertionElements(IntInput, 0, Elements,
1579 DestVecTy->getElementType()))
1582 // If we succeeded, we know that all of the element are specified by Elements
1583 // or are zero if Elements has a null entry. Recast this as a set of
1585 Value *Result = Constant::getNullValue(CI.getType());
1586 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
1587 if (Elements[i] == 0) continue; // Unset element.
1589 Result = IC.Builder->CreateInsertElement(Result, Elements[i],
1590 IC.Builder->getInt32(i));
1597 /// OptimizeIntToFloatBitCast - See if we can optimize an integer->float/double
1598 /// bitcast. The various long double bitcasts can't get in here.
1599 static Instruction *OptimizeIntToFloatBitCast(BitCastInst &CI,InstCombiner &IC){
1600 Value *Src = CI.getOperand(0);
1601 Type *DestTy = CI.getType();
1603 // If this is a bitcast from int to float, check to see if the int is an
1604 // extraction from a vector.
1605 Value *VecInput = 0;
1606 // bitcast(trunc(bitcast(somevector)))
1607 if (match(Src, m_Trunc(m_BitCast(m_Value(VecInput)))) &&
1608 isa<VectorType>(VecInput->getType())) {
1609 VectorType *VecTy = cast<VectorType>(VecInput->getType());
1610 unsigned DestWidth = DestTy->getPrimitiveSizeInBits();
1612 if (VecTy->getPrimitiveSizeInBits() % DestWidth == 0) {
1613 // If the element type of the vector doesn't match the result type,
1614 // bitcast it to be a vector type we can extract from.
1615 if (VecTy->getElementType() != DestTy) {
1616 VecTy = VectorType::get(DestTy,
1617 VecTy->getPrimitiveSizeInBits() / DestWidth);
1618 VecInput = IC.Builder->CreateBitCast(VecInput, VecTy);
1621 return ExtractElementInst::Create(VecInput, IC.Builder->getInt32(0));
1625 // bitcast(trunc(lshr(bitcast(somevector), cst))
1626 ConstantInt *ShAmt = 0;
1627 if (match(Src, m_Trunc(m_LShr(m_BitCast(m_Value(VecInput)),
1628 m_ConstantInt(ShAmt)))) &&
1629 isa<VectorType>(VecInput->getType())) {
1630 VectorType *VecTy = cast<VectorType>(VecInput->getType());
1631 unsigned DestWidth = DestTy->getPrimitiveSizeInBits();
1632 if (VecTy->getPrimitiveSizeInBits() % DestWidth == 0 &&
1633 ShAmt->getZExtValue() % DestWidth == 0) {
1634 // If the element type of the vector doesn't match the result type,
1635 // bitcast it to be a vector type we can extract from.
1636 if (VecTy->getElementType() != DestTy) {
1637 VecTy = VectorType::get(DestTy,
1638 VecTy->getPrimitiveSizeInBits() / DestWidth);
1639 VecInput = IC.Builder->CreateBitCast(VecInput, VecTy);
1642 unsigned Elt = ShAmt->getZExtValue() / DestWidth;
1643 return ExtractElementInst::Create(VecInput, IC.Builder->getInt32(Elt));
1649 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
1650 // If the operands are integer typed then apply the integer transforms,
1651 // otherwise just apply the common ones.
1652 Value *Src = CI.getOperand(0);
1653 Type *SrcTy = Src->getType();
1654 Type *DestTy = CI.getType();
1656 // Get rid of casts from one type to the same type. These are useless and can
1657 // be replaced by the operand.
1658 if (DestTy == Src->getType())
1659 return ReplaceInstUsesWith(CI, Src);
1661 if (PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
1662 PointerType *SrcPTy = cast<PointerType>(SrcTy);
1663 Type *DstElTy = DstPTy->getElementType();
1664 Type *SrcElTy = SrcPTy->getElementType();
1666 // If the address spaces don't match, don't eliminate the bitcast, which is
1667 // required for changing types.
1668 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
1671 // If we are casting a alloca to a pointer to a type of the same
1672 // size, rewrite the allocation instruction to allocate the "right" type.
1673 // There is no need to modify malloc calls because it is their bitcast that
1674 // needs to be cleaned up.
1675 if (AllocaInst *AI = dyn_cast<AllocaInst>(Src))
1676 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
1679 // If the source and destination are pointers, and this cast is equivalent
1680 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
1681 // This can enhance SROA and other transforms that want type-safe pointers.
1682 Constant *ZeroUInt =
1683 Constant::getNullValue(Type::getInt32Ty(CI.getContext()));
1684 unsigned NumZeros = 0;
1685 while (SrcElTy != DstElTy &&
1686 isa<CompositeType>(SrcElTy) && !SrcElTy->isPointerTy() &&
1687 SrcElTy->getNumContainedTypes() /* not "{}" */) {
1688 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
1692 // If we found a path from the src to dest, create the getelementptr now.
1693 if (SrcElTy == DstElTy) {
1694 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
1695 return GetElementPtrInst::CreateInBounds(Src, Idxs);
1699 // Try to optimize int -> float bitcasts.
1700 if ((DestTy->isFloatTy() || DestTy->isDoubleTy()) && isa<IntegerType>(SrcTy))
1701 if (Instruction *I = OptimizeIntToFloatBitCast(CI, *this))
1704 if (VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
1705 if (DestVTy->getNumElements() == 1 && !SrcTy->isVectorTy()) {
1706 Value *Elem = Builder->CreateBitCast(Src, DestVTy->getElementType());
1707 return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
1708 Constant::getNullValue(Type::getInt32Ty(CI.getContext())));
1709 // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
1712 if (isa<IntegerType>(SrcTy)) {
1713 // If this is a cast from an integer to vector, check to see if the input
1714 // is a trunc or zext of a bitcast from vector. If so, we can replace all
1715 // the casts with a shuffle and (potentially) a bitcast.
1716 if (isa<TruncInst>(Src) || isa<ZExtInst>(Src)) {
1717 CastInst *SrcCast = cast<CastInst>(Src);
1718 if (BitCastInst *BCIn = dyn_cast<BitCastInst>(SrcCast->getOperand(0)))
1719 if (isa<VectorType>(BCIn->getOperand(0)->getType()))
1720 if (Instruction *I = OptimizeVectorResize(BCIn->getOperand(0),
1721 cast<VectorType>(DestTy), *this))
1725 // If the input is an 'or' instruction, we may be doing shifts and ors to
1726 // assemble the elements of the vector manually. Try to rip the code out
1727 // and replace it with insertelements.
1728 if (Value *V = OptimizeIntegerToVectorInsertions(CI, *this))
1729 return ReplaceInstUsesWith(CI, V);
1733 if (VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
1734 if (SrcVTy->getNumElements() == 1 && !DestTy->isVectorTy()) {
1736 Builder->CreateExtractElement(Src,
1737 Constant::getNullValue(Type::getInt32Ty(CI.getContext())));
1738 return CastInst::Create(Instruction::BitCast, Elem, DestTy);
1742 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
1743 // Okay, we have (bitcast (shuffle ..)). Check to see if this is
1744 // a bitcast to a vector with the same # elts.
1745 if (SVI->hasOneUse() && DestTy->isVectorTy() &&
1746 cast<VectorType>(DestTy)->getNumElements() ==
1747 SVI->getType()->getNumElements() &&
1748 SVI->getType()->getNumElements() ==
1749 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
1751 // If either of the operands is a cast from CI.getType(), then
1752 // evaluating the shuffle in the casted destination's type will allow
1753 // us to eliminate at least one cast.
1754 if (((Tmp = dyn_cast<BitCastInst>(SVI->getOperand(0))) &&
1755 Tmp->getOperand(0)->getType() == DestTy) ||
1756 ((Tmp = dyn_cast<BitCastInst>(SVI->getOperand(1))) &&
1757 Tmp->getOperand(0)->getType() == DestTy)) {
1758 Value *LHS = Builder->CreateBitCast(SVI->getOperand(0), DestTy);
1759 Value *RHS = Builder->CreateBitCast(SVI->getOperand(1), DestTy);
1760 // Return a new shuffle vector. Use the same element ID's, as we
1761 // know the vector types match #elts.
1762 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
1767 if (SrcTy->isPointerTy())
1768 return commonPointerCastTransforms(CI);
1769 return commonCastTransforms(CI);