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/Support/PatternMatch.h"
19 using namespace PatternMatch;
21 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
22 /// expression. If so, decompose it, returning some value X, such that Val is
25 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
27 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
28 Offset = CI->getZExtValue();
30 return ConstantInt::get(Val->getType(), 0);
33 if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
34 // Cannot look past anything that might overflow.
35 OverflowingBinaryOperator *OBI = dyn_cast<OverflowingBinaryOperator>(Val);
36 if (OBI && !OBI->hasNoUnsignedWrap()) {
42 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
43 if (I->getOpcode() == Instruction::Shl) {
44 // This is a value scaled by '1 << the shift amt'.
45 Scale = UINT64_C(1) << RHS->getZExtValue();
47 return I->getOperand(0);
50 if (I->getOpcode() == Instruction::Mul) {
51 // This value is scaled by 'RHS'.
52 Scale = RHS->getZExtValue();
54 return I->getOperand(0);
57 if (I->getOpcode() == Instruction::Add) {
58 // We have X+C. Check to see if we really have (X*C2)+C1,
59 // where C1 is divisible by C2.
62 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
63 Offset += RHS->getZExtValue();
70 // Otherwise, we can't look past this.
76 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
77 /// try to eliminate the cast by moving the type information into the alloc.
78 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
80 // This requires TargetData to get the alloca alignment and size information.
83 PointerType *PTy = cast<PointerType>(CI.getType());
85 BuilderTy AllocaBuilder(*Builder);
86 AllocaBuilder.SetInsertPoint(AI.getParent(), &AI);
88 // Get the type really allocated and the type casted to.
89 Type *AllocElTy = AI.getAllocatedType();
90 Type *CastElTy = PTy->getElementType();
91 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
93 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
94 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
95 if (CastElTyAlign < AllocElTyAlign) return 0;
97 // If the allocation has multiple uses, only promote it if we are strictly
98 // increasing the alignment of the resultant allocation. If we keep it the
99 // same, we open the door to infinite loops of various kinds.
100 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
102 uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
103 uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
104 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
106 // See if we can satisfy the modulus by pulling a scale out of the array
108 unsigned ArraySizeScale;
109 uint64_t ArrayOffset;
110 Value *NumElements = // See if the array size is a decomposable linear expr.
111 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
113 // If we can now satisfy the modulus, by using a non-1 scale, we really can
115 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
116 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
118 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
123 Amt = ConstantInt::get(AI.getArraySize()->getType(), Scale);
124 // Insert before the alloca, not before the cast.
125 Amt = AllocaBuilder.CreateMul(Amt, NumElements, "tmp");
128 if (uint64_t Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
129 Value *Off = ConstantInt::get(AI.getArraySize()->getType(),
131 Amt = AllocaBuilder.CreateAdd(Amt, Off, "tmp");
134 AllocaInst *New = AllocaBuilder.CreateAlloca(CastElTy, Amt);
135 New->setAlignment(AI.getAlignment());
138 // If the allocation has multiple real uses, insert a cast and change all
139 // things that used it to use the new cast. This will also hack on CI, but it
141 if (!AI.hasOneUse()) {
142 // New is the allocation instruction, pointer typed. AI is the original
143 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
144 Value *NewCast = AllocaBuilder.CreateBitCast(New, AI.getType(), "tmpcast");
145 ReplaceInstUsesWith(AI, NewCast);
147 return ReplaceInstUsesWith(CI, New);
152 /// EvaluateInDifferentType - Given an expression that
153 /// CanEvaluateTruncated or CanEvaluateSExtd returns true for, actually
154 /// insert the code to evaluate the expression.
155 Value *InstCombiner::EvaluateInDifferentType(Value *V, Type *Ty,
157 if (Constant *C = dyn_cast<Constant>(V)) {
158 C = ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
159 // If we got a constantexpr back, try to simplify it with TD info.
160 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
161 C = ConstantFoldConstantExpression(CE, TD);
165 // Otherwise, it must be an instruction.
166 Instruction *I = cast<Instruction>(V);
167 Instruction *Res = 0;
168 unsigned Opc = I->getOpcode();
170 case Instruction::Add:
171 case Instruction::Sub:
172 case Instruction::Mul:
173 case Instruction::And:
174 case Instruction::Or:
175 case Instruction::Xor:
176 case Instruction::AShr:
177 case Instruction::LShr:
178 case Instruction::Shl:
179 case Instruction::UDiv:
180 case Instruction::URem: {
181 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
182 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
183 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
186 case Instruction::Trunc:
187 case Instruction::ZExt:
188 case Instruction::SExt:
189 // If the source type of the cast is the type we're trying for then we can
190 // just return the source. There's no need to insert it because it is not
192 if (I->getOperand(0)->getType() == Ty)
193 return I->getOperand(0);
195 // Otherwise, must be the same type of cast, so just reinsert a new one.
196 // This also handles the case of zext(trunc(x)) -> zext(x).
197 Res = CastInst::CreateIntegerCast(I->getOperand(0), Ty,
198 Opc == Instruction::SExt);
200 case Instruction::Select: {
201 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
202 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
203 Res = SelectInst::Create(I->getOperand(0), True, False);
206 case Instruction::PHI: {
207 PHINode *OPN = cast<PHINode>(I);
208 PHINode *NPN = PHINode::Create(Ty, OPN->getNumIncomingValues());
209 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
210 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
211 NPN->addIncoming(V, OPN->getIncomingBlock(i));
217 // TODO: Can handle more cases here.
218 llvm_unreachable("Unreachable!");
223 return InsertNewInstWith(Res, *I);
227 /// This function is a wrapper around CastInst::isEliminableCastPair. It
228 /// simply extracts arguments and returns what that function returns.
229 static Instruction::CastOps
230 isEliminableCastPair(
231 const CastInst *CI, ///< The first cast instruction
232 unsigned opcode, ///< The opcode of the second cast instruction
233 Type *DstTy, ///< The target type for the second cast instruction
234 TargetData *TD ///< The target data for pointer size
237 Type *SrcTy = CI->getOperand(0)->getType(); // A from above
238 Type *MidTy = CI->getType(); // B from above
240 // Get the opcodes of the two Cast instructions
241 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
242 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
244 unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
246 TD ? TD->getIntPtrType(CI->getContext()) : 0);
248 // We don't want to form an inttoptr or ptrtoint that converts to an integer
249 // type that differs from the pointer size.
250 if ((Res == Instruction::IntToPtr &&
251 (!TD || SrcTy != TD->getIntPtrType(CI->getContext()))) ||
252 (Res == Instruction::PtrToInt &&
253 (!TD || DstTy != TD->getIntPtrType(CI->getContext()))))
256 return Instruction::CastOps(Res);
259 /// ShouldOptimizeCast - Return true if the cast from "V to Ty" actually
260 /// results in any code being generated and is interesting to optimize out. If
261 /// the cast can be eliminated by some other simple transformation, we prefer
262 /// to do the simplification first.
263 bool InstCombiner::ShouldOptimizeCast(Instruction::CastOps opc, const Value *V,
265 // Noop casts and casts of constants should be eliminated trivially.
266 if (V->getType() == Ty || isa<Constant>(V)) return false;
268 // If this is another cast that can be eliminated, we prefer to have it
270 if (const CastInst *CI = dyn_cast<CastInst>(V))
271 if (isEliminableCastPair(CI, opc, Ty, TD))
274 // If this is a vector sext from a compare, then we don't want to break the
275 // idiom where each element of the extended vector is either zero or all ones.
276 if (opc == Instruction::SExt && isa<CmpInst>(V) && Ty->isVectorTy())
283 /// @brief Implement the transforms common to all CastInst visitors.
284 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
285 Value *Src = CI.getOperand(0);
287 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
289 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
290 if (Instruction::CastOps opc =
291 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
292 // The first cast (CSrc) is eliminable so we need to fix up or replace
293 // the second cast (CI). CSrc will then have a good chance of being dead.
294 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
298 // If we are casting a select then fold the cast into the select
299 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
300 if (Instruction *NV = FoldOpIntoSelect(CI, SI))
303 // If we are casting a PHI then fold the cast into the PHI
304 if (isa<PHINode>(Src)) {
305 // We don't do this if this would create a PHI node with an illegal type if
306 // it is currently legal.
307 if (!Src->getType()->isIntegerTy() ||
308 !CI.getType()->isIntegerTy() ||
309 ShouldChangeType(CI.getType(), Src->getType()))
310 if (Instruction *NV = FoldOpIntoPhi(CI))
317 /// CanEvaluateTruncated - Return true if we can evaluate the specified
318 /// expression tree as type Ty instead of its larger type, and arrive with the
319 /// same value. This is used by code that tries to eliminate truncates.
321 /// Ty will always be a type smaller than V. We should return true if trunc(V)
322 /// can be computed by computing V in the smaller type. If V is an instruction,
323 /// then trunc(inst(x,y)) can be computed as inst(trunc(x),trunc(y)), which only
324 /// makes sense if x and y can be efficiently truncated.
326 /// This function works on both vectors and scalars.
328 static bool CanEvaluateTruncated(Value *V, Type *Ty) {
329 // We can always evaluate constants in another type.
330 if (isa<Constant>(V))
333 Instruction *I = dyn_cast<Instruction>(V);
334 if (!I) return false;
336 Type *OrigTy = V->getType();
338 // If this is an extension from the dest type, we can eliminate it, even if it
339 // has multiple uses.
340 if ((isa<ZExtInst>(I) || isa<SExtInst>(I)) &&
341 I->getOperand(0)->getType() == Ty)
344 // We can't extend or shrink something that has multiple uses: doing so would
345 // require duplicating the instruction in general, which isn't profitable.
346 if (!I->hasOneUse()) return false;
348 unsigned Opc = I->getOpcode();
350 case Instruction::Add:
351 case Instruction::Sub:
352 case Instruction::Mul:
353 case Instruction::And:
354 case Instruction::Or:
355 case Instruction::Xor:
356 // These operators can all arbitrarily be extended or truncated.
357 return CanEvaluateTruncated(I->getOperand(0), Ty) &&
358 CanEvaluateTruncated(I->getOperand(1), Ty);
360 case Instruction::UDiv:
361 case Instruction::URem: {
362 // UDiv and URem can be truncated if all the truncated bits are zero.
363 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
364 uint32_t BitWidth = Ty->getScalarSizeInBits();
365 if (BitWidth < OrigBitWidth) {
366 APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
367 if (MaskedValueIsZero(I->getOperand(0), Mask) &&
368 MaskedValueIsZero(I->getOperand(1), Mask)) {
369 return CanEvaluateTruncated(I->getOperand(0), Ty) &&
370 CanEvaluateTruncated(I->getOperand(1), Ty);
375 case Instruction::Shl:
376 // If we are truncating the result of this SHL, and if it's a shift of a
377 // constant amount, we can always perform a SHL in a smaller type.
378 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
379 uint32_t BitWidth = Ty->getScalarSizeInBits();
380 if (CI->getLimitedValue(BitWidth) < BitWidth)
381 return CanEvaluateTruncated(I->getOperand(0), Ty);
384 case Instruction::LShr:
385 // If this is a truncate of a logical shr, we can truncate it to a smaller
386 // lshr iff we know that the bits we would otherwise be shifting in are
388 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
389 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
390 uint32_t BitWidth = Ty->getScalarSizeInBits();
391 if (MaskedValueIsZero(I->getOperand(0),
392 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
393 CI->getLimitedValue(BitWidth) < BitWidth) {
394 return CanEvaluateTruncated(I->getOperand(0), Ty);
398 case Instruction::Trunc:
399 // trunc(trunc(x)) -> trunc(x)
401 case Instruction::ZExt:
402 case Instruction::SExt:
403 // trunc(ext(x)) -> ext(x) if the source type is smaller than the new dest
404 // trunc(ext(x)) -> trunc(x) if the source type is larger than the new dest
406 case Instruction::Select: {
407 SelectInst *SI = cast<SelectInst>(I);
408 return CanEvaluateTruncated(SI->getTrueValue(), Ty) &&
409 CanEvaluateTruncated(SI->getFalseValue(), Ty);
411 case Instruction::PHI: {
412 // We can change a phi if we can change all operands. Note that we never
413 // get into trouble with cyclic PHIs here because we only consider
414 // instructions with a single use.
415 PHINode *PN = cast<PHINode>(I);
416 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
417 if (!CanEvaluateTruncated(PN->getIncomingValue(i), Ty))
422 // TODO: Can handle more cases here.
429 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
430 if (Instruction *Result = commonCastTransforms(CI))
433 // See if we can simplify any instructions used by the input whose sole
434 // purpose is to compute bits we don't care about.
435 if (SimplifyDemandedInstructionBits(CI))
438 Value *Src = CI.getOperand(0);
439 Type *DestTy = CI.getType(), *SrcTy = Src->getType();
441 // Attempt to truncate the entire input expression tree to the destination
442 // type. Only do this if the dest type is a simple type, don't convert the
443 // expression tree to something weird like i93 unless the source is also
445 if ((DestTy->isVectorTy() || ShouldChangeType(SrcTy, DestTy)) &&
446 CanEvaluateTruncated(Src, DestTy)) {
448 // If this cast is a truncate, evaluting in a different type always
449 // eliminates the cast, so it is always a win.
450 DEBUG(dbgs() << "ICE: EvaluateInDifferentType converting expression type"
451 " to avoid cast: " << CI << '\n');
452 Value *Res = EvaluateInDifferentType(Src, DestTy, false);
453 assert(Res->getType() == DestTy);
454 return ReplaceInstUsesWith(CI, Res);
457 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0), likewise for vector.
458 if (DestTy->getScalarSizeInBits() == 1) {
459 Constant *One = ConstantInt::get(Src->getType(), 1);
460 Src = Builder->CreateAnd(Src, One, "tmp");
461 Value *Zero = Constant::getNullValue(Src->getType());
462 return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
465 // Transform trunc(lshr (zext A), Cst) to eliminate one type conversion.
466 Value *A = 0; ConstantInt *Cst = 0;
467 if (Src->hasOneUse() &&
468 match(Src, m_LShr(m_ZExt(m_Value(A)), m_ConstantInt(Cst)))) {
469 // We have three types to worry about here, the type of A, the source of
470 // the truncate (MidSize), and the destination of the truncate. We know that
471 // ASize < MidSize and MidSize > ResultSize, but don't know the relation
472 // between ASize and ResultSize.
473 unsigned ASize = A->getType()->getPrimitiveSizeInBits();
475 // If the shift amount is larger than the size of A, then the result is
476 // known to be zero because all the input bits got shifted out.
477 if (Cst->getZExtValue() >= ASize)
478 return ReplaceInstUsesWith(CI, Constant::getNullValue(CI.getType()));
480 // Since we're doing an lshr and a zero extend, and know that the shift
481 // amount is smaller than ASize, it is always safe to do the shift in A's
482 // type, then zero extend or truncate to the result.
483 Value *Shift = Builder->CreateLShr(A, Cst->getZExtValue());
484 Shift->takeName(Src);
485 return CastInst::CreateIntegerCast(Shift, CI.getType(), false);
488 // Transform "trunc (and X, cst)" -> "and (trunc X), cst" so long as the dest
489 // type isn't non-native.
490 if (Src->hasOneUse() && isa<IntegerType>(Src->getType()) &&
491 ShouldChangeType(Src->getType(), CI.getType()) &&
492 match(Src, m_And(m_Value(A), m_ConstantInt(Cst)))) {
493 Value *NewTrunc = Builder->CreateTrunc(A, CI.getType(), A->getName()+".tr");
494 return BinaryOperator::CreateAnd(NewTrunc,
495 ConstantExpr::getTrunc(Cst, CI.getType()));
501 /// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
502 /// in order to eliminate the icmp.
503 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
505 // If we are just checking for a icmp eq of a single bit and zext'ing it
506 // to an integer, then shift the bit to the appropriate place and then
507 // cast to integer to avoid the comparison.
508 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
509 const APInt &Op1CV = Op1C->getValue();
511 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
512 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
513 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
514 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
515 if (!DoXform) return ICI;
517 Value *In = ICI->getOperand(0);
518 Value *Sh = ConstantInt::get(In->getType(),
519 In->getType()->getScalarSizeInBits()-1);
520 In = Builder->CreateLShr(In, Sh, In->getName()+".lobit");
521 if (In->getType() != CI.getType())
522 In = Builder->CreateIntCast(In, CI.getType(), false/*ZExt*/, "tmp");
524 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
525 Constant *One = ConstantInt::get(In->getType(), 1);
526 In = Builder->CreateXor(In, One, In->getName()+".not");
529 return ReplaceInstUsesWith(CI, In);
534 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
535 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
536 // zext (X == 1) to i32 --> X iff X has only the low bit set.
537 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
538 // zext (X != 0) to i32 --> X iff X has only the low bit set.
539 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
540 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
541 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
542 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
543 // This only works for EQ and NE
545 // If Op1C some other power of two, convert:
546 uint32_t BitWidth = Op1C->getType()->getBitWidth();
547 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
548 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
549 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
551 APInt KnownZeroMask(~KnownZero);
552 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
553 if (!DoXform) return ICI;
555 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
556 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
557 // (X&4) == 2 --> false
558 // (X&4) != 2 --> true
559 Constant *Res = ConstantInt::get(Type::getInt1Ty(CI.getContext()),
561 Res = ConstantExpr::getZExt(Res, CI.getType());
562 return ReplaceInstUsesWith(CI, Res);
565 uint32_t ShiftAmt = KnownZeroMask.logBase2();
566 Value *In = ICI->getOperand(0);
568 // Perform a logical shr by shiftamt.
569 // Insert the shift to put the result in the low bit.
570 In = Builder->CreateLShr(In, ConstantInt::get(In->getType(),ShiftAmt),
571 In->getName()+".lobit");
574 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
575 Constant *One = ConstantInt::get(In->getType(), 1);
576 In = Builder->CreateXor(In, One, "tmp");
579 if (CI.getType() == In->getType())
580 return ReplaceInstUsesWith(CI, In);
581 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
586 // icmp ne A, B is equal to xor A, B when A and B only really have one bit.
587 // It is also profitable to transform icmp eq into not(xor(A, B)) because that
588 // may lead to additional simplifications.
589 if (ICI->isEquality() && CI.getType() == ICI->getOperand(0)->getType()) {
590 if (IntegerType *ITy = dyn_cast<IntegerType>(CI.getType())) {
591 uint32_t BitWidth = ITy->getBitWidth();
592 Value *LHS = ICI->getOperand(0);
593 Value *RHS = ICI->getOperand(1);
595 APInt KnownZeroLHS(BitWidth, 0), KnownOneLHS(BitWidth, 0);
596 APInt KnownZeroRHS(BitWidth, 0), KnownOneRHS(BitWidth, 0);
597 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
598 ComputeMaskedBits(LHS, TypeMask, KnownZeroLHS, KnownOneLHS);
599 ComputeMaskedBits(RHS, TypeMask, KnownZeroRHS, KnownOneRHS);
601 if (KnownZeroLHS == KnownZeroRHS && KnownOneLHS == KnownOneRHS) {
602 APInt KnownBits = KnownZeroLHS | KnownOneLHS;
603 APInt UnknownBit = ~KnownBits;
604 if (UnknownBit.countPopulation() == 1) {
605 if (!DoXform) return ICI;
607 Value *Result = Builder->CreateXor(LHS, RHS);
609 // Mask off any bits that are set and won't be shifted away.
610 if (KnownOneLHS.uge(UnknownBit))
611 Result = Builder->CreateAnd(Result,
612 ConstantInt::get(ITy, UnknownBit));
614 // Shift the bit we're testing down to the lsb.
615 Result = Builder->CreateLShr(
616 Result, ConstantInt::get(ITy, UnknownBit.countTrailingZeros()));
618 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
619 Result = Builder->CreateXor(Result, ConstantInt::get(ITy, 1));
620 Result->takeName(ICI);
621 return ReplaceInstUsesWith(CI, Result);
630 /// CanEvaluateZExtd - Determine if the specified value can be computed in the
631 /// specified wider type and produce the same low bits. If not, return false.
633 /// If this function returns true, it can also return a non-zero number of bits
634 /// (in BitsToClear) which indicates that the value it computes is correct for
635 /// the zero extend, but that the additional BitsToClear bits need to be zero'd
636 /// out. For example, to promote something like:
638 /// %B = trunc i64 %A to i32
639 /// %C = lshr i32 %B, 8
640 /// %E = zext i32 %C to i64
642 /// CanEvaluateZExtd for the 'lshr' will return true, and BitsToClear will be
643 /// set to 8 to indicate that the promoted value needs to have bits 24-31
644 /// cleared in addition to bits 32-63. Since an 'and' will be generated to
645 /// clear the top bits anyway, doing this has no extra cost.
647 /// This function works on both vectors and scalars.
648 static bool CanEvaluateZExtd(Value *V, Type *Ty, unsigned &BitsToClear) {
650 if (isa<Constant>(V))
653 Instruction *I = dyn_cast<Instruction>(V);
654 if (!I) return false;
656 // If the input is a truncate from the destination type, we can trivially
657 // eliminate it, even if it has multiple uses.
658 // FIXME: This is currently disabled until codegen can handle this without
659 // pessimizing code, PR5997.
660 if (0 && isa<TruncInst>(I) && I->getOperand(0)->getType() == Ty)
663 // We can't extend or shrink something that has multiple uses: doing so would
664 // require duplicating the instruction in general, which isn't profitable.
665 if (!I->hasOneUse()) return false;
667 unsigned Opc = I->getOpcode(), Tmp;
669 case Instruction::ZExt: // zext(zext(x)) -> zext(x).
670 case Instruction::SExt: // zext(sext(x)) -> sext(x).
671 case Instruction::Trunc: // zext(trunc(x)) -> trunc(x) or zext(x)
673 case Instruction::And:
674 case Instruction::Or:
675 case Instruction::Xor:
676 case Instruction::Add:
677 case Instruction::Sub:
678 case Instruction::Mul:
679 case Instruction::Shl:
680 if (!CanEvaluateZExtd(I->getOperand(0), Ty, BitsToClear) ||
681 !CanEvaluateZExtd(I->getOperand(1), Ty, Tmp))
683 // These can all be promoted if neither operand has 'bits to clear'.
684 if (BitsToClear == 0 && Tmp == 0)
687 // If the operation is an AND/OR/XOR and the bits to clear are zero in the
688 // other side, BitsToClear is ok.
690 (Opc == Instruction::And || Opc == Instruction::Or ||
691 Opc == Instruction::Xor)) {
692 // We use MaskedValueIsZero here for generality, but the case we care
693 // about the most is constant RHS.
694 unsigned VSize = V->getType()->getScalarSizeInBits();
695 if (MaskedValueIsZero(I->getOperand(1),
696 APInt::getHighBitsSet(VSize, BitsToClear)))
700 // Otherwise, we don't know how to analyze this BitsToClear case yet.
703 case Instruction::LShr:
704 // We can promote lshr(x, cst) if we can promote x. This requires the
705 // ultimate 'and' to clear out the high zero bits we're clearing out though.
706 if (ConstantInt *Amt = dyn_cast<ConstantInt>(I->getOperand(1))) {
707 if (!CanEvaluateZExtd(I->getOperand(0), Ty, BitsToClear))
709 BitsToClear += Amt->getZExtValue();
710 if (BitsToClear > V->getType()->getScalarSizeInBits())
711 BitsToClear = V->getType()->getScalarSizeInBits();
714 // Cannot promote variable LSHR.
716 case Instruction::Select:
717 if (!CanEvaluateZExtd(I->getOperand(1), Ty, Tmp) ||
718 !CanEvaluateZExtd(I->getOperand(2), Ty, BitsToClear) ||
719 // TODO: If important, we could handle the case when the BitsToClear are
720 // known zero in the disagreeing side.
725 case Instruction::PHI: {
726 // We can change a phi if we can change all operands. Note that we never
727 // get into trouble with cyclic PHIs here because we only consider
728 // instructions with a single use.
729 PHINode *PN = cast<PHINode>(I);
730 if (!CanEvaluateZExtd(PN->getIncomingValue(0), Ty, BitsToClear))
732 for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i)
733 if (!CanEvaluateZExtd(PN->getIncomingValue(i), Ty, Tmp) ||
734 // TODO: If important, we could handle the case when the BitsToClear
735 // are known zero in the disagreeing input.
741 // TODO: Can handle more cases here.
746 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
747 // If this zero extend is only used by a truncate, let the truncate by
748 // eliminated before we try to optimize this zext.
749 if (CI.hasOneUse() && isa<TruncInst>(CI.use_back()))
752 // If one of the common conversion will work, do it.
753 if (Instruction *Result = commonCastTransforms(CI))
756 // See if we can simplify any instructions used by the input whose sole
757 // purpose is to compute bits we don't care about.
758 if (SimplifyDemandedInstructionBits(CI))
761 Value *Src = CI.getOperand(0);
762 Type *SrcTy = Src->getType(), *DestTy = CI.getType();
764 // Attempt to extend the entire input expression tree to the destination
765 // type. Only do this if the dest type is a simple type, don't convert the
766 // expression tree to something weird like i93 unless the source is also
768 unsigned BitsToClear;
769 if ((DestTy->isVectorTy() || ShouldChangeType(SrcTy, DestTy)) &&
770 CanEvaluateZExtd(Src, DestTy, BitsToClear)) {
771 assert(BitsToClear < SrcTy->getScalarSizeInBits() &&
772 "Unreasonable BitsToClear");
774 // Okay, we can transform this! Insert the new expression now.
775 DEBUG(dbgs() << "ICE: EvaluateInDifferentType converting expression type"
776 " to avoid zero extend: " << CI);
777 Value *Res = EvaluateInDifferentType(Src, DestTy, false);
778 assert(Res->getType() == DestTy);
780 uint32_t SrcBitsKept = SrcTy->getScalarSizeInBits()-BitsToClear;
781 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
783 // If the high bits are already filled with zeros, just replace this
784 // cast with the result.
785 if (MaskedValueIsZero(Res, APInt::getHighBitsSet(DestBitSize,
786 DestBitSize-SrcBitsKept)))
787 return ReplaceInstUsesWith(CI, Res);
789 // We need to emit an AND to clear the high bits.
790 Constant *C = ConstantInt::get(Res->getType(),
791 APInt::getLowBitsSet(DestBitSize, SrcBitsKept));
792 return BinaryOperator::CreateAnd(Res, C);
795 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
796 // types and if the sizes are just right we can convert this into a logical
797 // 'and' which will be much cheaper than the pair of casts.
798 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
799 // TODO: Subsume this into EvaluateInDifferentType.
801 // Get the sizes of the types involved. We know that the intermediate type
802 // will be smaller than A or C, but don't know the relation between A and C.
803 Value *A = CSrc->getOperand(0);
804 unsigned SrcSize = A->getType()->getScalarSizeInBits();
805 unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
806 unsigned DstSize = CI.getType()->getScalarSizeInBits();
807 // If we're actually extending zero bits, then if
808 // SrcSize < DstSize: zext(a & mask)
809 // SrcSize == DstSize: a & mask
810 // SrcSize > DstSize: trunc(a) & mask
811 if (SrcSize < DstSize) {
812 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
813 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
814 Value *And = Builder->CreateAnd(A, AndConst, CSrc->getName()+".mask");
815 return new ZExtInst(And, CI.getType());
818 if (SrcSize == DstSize) {
819 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
820 return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
823 if (SrcSize > DstSize) {
824 Value *Trunc = Builder->CreateTrunc(A, CI.getType(), "tmp");
825 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
826 return BinaryOperator::CreateAnd(Trunc,
827 ConstantInt::get(Trunc->getType(),
832 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
833 return transformZExtICmp(ICI, CI);
835 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
836 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
837 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
838 // of the (zext icmp) will be transformed.
839 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
840 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
841 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
842 (transformZExtICmp(LHS, CI, false) ||
843 transformZExtICmp(RHS, CI, false))) {
844 Value *LCast = Builder->CreateZExt(LHS, CI.getType(), LHS->getName());
845 Value *RCast = Builder->CreateZExt(RHS, CI.getType(), RHS->getName());
846 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
850 // zext(trunc(t) & C) -> (t & zext(C)).
851 if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
852 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
853 if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
854 Value *TI0 = TI->getOperand(0);
855 if (TI0->getType() == CI.getType())
857 BinaryOperator::CreateAnd(TI0,
858 ConstantExpr::getZExt(C, CI.getType()));
861 // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
862 if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
863 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
864 if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
865 if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
866 And->getOperand(1) == C)
867 if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
868 Value *TI0 = TI->getOperand(0);
869 if (TI0->getType() == CI.getType()) {
870 Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
871 Value *NewAnd = Builder->CreateAnd(TI0, ZC, "tmp");
872 return BinaryOperator::CreateXor(NewAnd, ZC);
876 // zext (xor i1 X, true) to i32 --> xor (zext i1 X to i32), 1
878 if (SrcI && SrcI->hasOneUse() && SrcI->getType()->isIntegerTy(1) &&
879 match(SrcI, m_Not(m_Value(X))) &&
880 (!X->hasOneUse() || !isa<CmpInst>(X))) {
881 Value *New = Builder->CreateZExt(X, CI.getType());
882 return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
888 /// transformSExtICmp - Transform (sext icmp) to bitwise / integer operations
889 /// in order to eliminate the icmp.
890 Instruction *InstCombiner::transformSExtICmp(ICmpInst *ICI, Instruction &CI) {
891 Value *Op0 = ICI->getOperand(0), *Op1 = ICI->getOperand(1);
892 ICmpInst::Predicate Pred = ICI->getPredicate();
894 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
895 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if negative
896 // (x >s -1) ? -1 : 0 -> not (ashr x, 31) -> all ones if positive
897 if ((Pred == ICmpInst::ICMP_SLT && Op1C->isZero()) ||
898 (Pred == ICmpInst::ICMP_SGT && Op1C->isAllOnesValue())) {
900 Value *Sh = ConstantInt::get(Op0->getType(),
901 Op0->getType()->getScalarSizeInBits()-1);
902 Value *In = Builder->CreateAShr(Op0, Sh, Op0->getName()+".lobit");
903 if (In->getType() != CI.getType())
904 In = Builder->CreateIntCast(In, CI.getType(), true/*SExt*/, "tmp");
906 if (Pred == ICmpInst::ICMP_SGT)
907 In = Builder->CreateNot(In, In->getName()+".not");
908 return ReplaceInstUsesWith(CI, In);
911 // If we know that only one bit of the LHS of the icmp can be set and we
912 // have an equality comparison with zero or a power of 2, we can transform
913 // the icmp and sext into bitwise/integer operations.
914 if (ICI->hasOneUse() &&
915 ICI->isEquality() && (Op1C->isZero() || Op1C->getValue().isPowerOf2())){
916 unsigned BitWidth = Op1C->getType()->getBitWidth();
917 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
918 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
919 ComputeMaskedBits(Op0, TypeMask, KnownZero, KnownOne);
921 APInt KnownZeroMask(~KnownZero);
922 if (KnownZeroMask.isPowerOf2()) {
923 Value *In = ICI->getOperand(0);
925 // If the icmp tests for a known zero bit we can constant fold it.
926 if (!Op1C->isZero() && Op1C->getValue() != KnownZeroMask) {
927 Value *V = Pred == ICmpInst::ICMP_NE ?
928 ConstantInt::getAllOnesValue(CI.getType()) :
929 ConstantInt::getNullValue(CI.getType());
930 return ReplaceInstUsesWith(CI, V);
933 if (!Op1C->isZero() == (Pred == ICmpInst::ICMP_NE)) {
934 // sext ((x & 2^n) == 0) -> (x >> n) - 1
935 // sext ((x & 2^n) != 2^n) -> (x >> n) - 1
936 unsigned ShiftAmt = KnownZeroMask.countTrailingZeros();
937 // Perform a right shift to place the desired bit in the LSB.
939 In = Builder->CreateLShr(In,
940 ConstantInt::get(In->getType(), ShiftAmt));
942 // At this point "In" is either 1 or 0. Subtract 1 to turn
943 // {1, 0} -> {0, -1}.
944 In = Builder->CreateAdd(In,
945 ConstantInt::getAllOnesValue(In->getType()),
948 // sext ((x & 2^n) != 0) -> (x << bitwidth-n) a>> bitwidth-1
949 // sext ((x & 2^n) == 2^n) -> (x << bitwidth-n) a>> bitwidth-1
950 unsigned ShiftAmt = KnownZeroMask.countLeadingZeros();
951 // Perform a left shift to place the desired bit in the MSB.
953 In = Builder->CreateShl(In,
954 ConstantInt::get(In->getType(), ShiftAmt));
956 // Distribute the bit over the whole bit width.
957 In = Builder->CreateAShr(In, ConstantInt::get(In->getType(),
958 BitWidth - 1), "sext");
961 if (CI.getType() == In->getType())
962 return ReplaceInstUsesWith(CI, In);
963 return CastInst::CreateIntegerCast(In, CI.getType(), true/*SExt*/);
968 // vector (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed.
969 if (VectorType *VTy = dyn_cast<VectorType>(CI.getType())) {
970 if (Pred == ICmpInst::ICMP_SLT && match(Op1, m_Zero()) &&
971 Op0->getType() == CI.getType()) {
972 Type *EltTy = VTy->getElementType();
974 // splat the shift constant to a constant vector.
975 Constant *VSh = ConstantInt::get(VTy, EltTy->getScalarSizeInBits()-1);
976 Value *In = Builder->CreateAShr(Op0, VSh, Op0->getName()+".lobit");
977 return ReplaceInstUsesWith(CI, In);
984 /// CanEvaluateSExtd - Return true if we can take the specified value
985 /// and return it as type Ty without inserting any new casts and without
986 /// changing the value of the common low bits. This is used by code that tries
987 /// to promote integer operations to a wider types will allow us to eliminate
990 /// This function works on both vectors and scalars.
992 static bool CanEvaluateSExtd(Value *V, Type *Ty) {
993 assert(V->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits() &&
994 "Can't sign extend type to a smaller type");
995 // If this is a constant, it can be trivially promoted.
996 if (isa<Constant>(V))
999 Instruction *I = dyn_cast<Instruction>(V);
1000 if (!I) return false;
1002 // If this is a truncate from the dest type, we can trivially eliminate it,
1003 // even if it has multiple uses.
1004 // FIXME: This is currently disabled until codegen can handle this without
1005 // pessimizing code, PR5997.
1006 if (0 && isa<TruncInst>(I) && I->getOperand(0)->getType() == Ty)
1009 // We can't extend or shrink something that has multiple uses: doing so would
1010 // require duplicating the instruction in general, which isn't profitable.
1011 if (!I->hasOneUse()) return false;
1013 switch (I->getOpcode()) {
1014 case Instruction::SExt: // sext(sext(x)) -> sext(x)
1015 case Instruction::ZExt: // sext(zext(x)) -> zext(x)
1016 case Instruction::Trunc: // sext(trunc(x)) -> trunc(x) or sext(x)
1018 case Instruction::And:
1019 case Instruction::Or:
1020 case Instruction::Xor:
1021 case Instruction::Add:
1022 case Instruction::Sub:
1023 case Instruction::Mul:
1024 // These operators can all arbitrarily be extended if their inputs can.
1025 return CanEvaluateSExtd(I->getOperand(0), Ty) &&
1026 CanEvaluateSExtd(I->getOperand(1), Ty);
1028 //case Instruction::Shl: TODO
1029 //case Instruction::LShr: TODO
1031 case Instruction::Select:
1032 return CanEvaluateSExtd(I->getOperand(1), Ty) &&
1033 CanEvaluateSExtd(I->getOperand(2), Ty);
1035 case Instruction::PHI: {
1036 // We can change a phi if we can change all operands. Note that we never
1037 // get into trouble with cyclic PHIs here because we only consider
1038 // instructions with a single use.
1039 PHINode *PN = cast<PHINode>(I);
1040 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1041 if (!CanEvaluateSExtd(PN->getIncomingValue(i), Ty)) return false;
1045 // TODO: Can handle more cases here.
1052 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
1053 // If this sign extend is only used by a truncate, let the truncate by
1054 // eliminated before we try to optimize this zext.
1055 if (CI.hasOneUse() && isa<TruncInst>(CI.use_back()))
1058 if (Instruction *I = commonCastTransforms(CI))
1061 // See if we can simplify any instructions used by the input whose sole
1062 // purpose is to compute bits we don't care about.
1063 if (SimplifyDemandedInstructionBits(CI))
1066 Value *Src = CI.getOperand(0);
1067 Type *SrcTy = Src->getType(), *DestTy = CI.getType();
1069 // Attempt to extend the entire input expression tree to the destination
1070 // type. Only do this if the dest type is a simple type, don't convert the
1071 // expression tree to something weird like i93 unless the source is also
1073 if ((DestTy->isVectorTy() || ShouldChangeType(SrcTy, DestTy)) &&
1074 CanEvaluateSExtd(Src, DestTy)) {
1075 // Okay, we can transform this! Insert the new expression now.
1076 DEBUG(dbgs() << "ICE: EvaluateInDifferentType converting expression type"
1077 " to avoid sign extend: " << CI);
1078 Value *Res = EvaluateInDifferentType(Src, DestTy, true);
1079 assert(Res->getType() == DestTy);
1081 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
1082 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
1084 // If the high bits are already filled with sign bit, just replace this
1085 // cast with the result.
1086 if (ComputeNumSignBits(Res) > DestBitSize - SrcBitSize)
1087 return ReplaceInstUsesWith(CI, Res);
1089 // We need to emit a shl + ashr to do the sign extend.
1090 Value *ShAmt = ConstantInt::get(DestTy, DestBitSize-SrcBitSize);
1091 return BinaryOperator::CreateAShr(Builder->CreateShl(Res, ShAmt, "sext"),
1095 // If this input is a trunc from our destination, then turn sext(trunc(x))
1097 if (TruncInst *TI = dyn_cast<TruncInst>(Src))
1098 if (TI->hasOneUse() && TI->getOperand(0)->getType() == DestTy) {
1099 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
1100 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
1102 // We need to emit a shl + ashr to do the sign extend.
1103 Value *ShAmt = ConstantInt::get(DestTy, DestBitSize-SrcBitSize);
1104 Value *Res = Builder->CreateShl(TI->getOperand(0), ShAmt, "sext");
1105 return BinaryOperator::CreateAShr(Res, ShAmt);
1108 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
1109 return transformSExtICmp(ICI, CI);
1111 // If the input is a shl/ashr pair of a same constant, then this is a sign
1112 // extension from a smaller value. If we could trust arbitrary bitwidth
1113 // integers, we could turn this into a truncate to the smaller bit and then
1114 // use a sext for the whole extension. Since we don't, look deeper and check
1115 // for a truncate. If the source and dest are the same type, eliminate the
1116 // trunc and extend and just do shifts. For example, turn:
1117 // %a = trunc i32 %i to i8
1118 // %b = shl i8 %a, 6
1119 // %c = ashr i8 %b, 6
1120 // %d = sext i8 %c to i32
1122 // %a = shl i32 %i, 30
1123 // %d = ashr i32 %a, 30
1125 // TODO: Eventually this could be subsumed by EvaluateInDifferentType.
1126 ConstantInt *BA = 0, *CA = 0;
1127 if (match(Src, m_AShr(m_Shl(m_Trunc(m_Value(A)), m_ConstantInt(BA)),
1128 m_ConstantInt(CA))) &&
1129 BA == CA && A->getType() == CI.getType()) {
1130 unsigned MidSize = Src->getType()->getScalarSizeInBits();
1131 unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
1132 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
1133 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
1134 A = Builder->CreateShl(A, ShAmtV, CI.getName());
1135 return BinaryOperator::CreateAShr(A, ShAmtV);
1142 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
1143 /// in the specified FP type without changing its value.
1144 static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
1146 APFloat F = CFP->getValueAPF();
1147 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
1149 return ConstantFP::get(CFP->getContext(), F);
1153 /// LookThroughFPExtensions - If this is an fp extension instruction, look
1154 /// through it until we get the source value.
1155 static Value *LookThroughFPExtensions(Value *V) {
1156 if (Instruction *I = dyn_cast<Instruction>(V))
1157 if (I->getOpcode() == Instruction::FPExt)
1158 return LookThroughFPExtensions(I->getOperand(0));
1160 // If this value is a constant, return the constant in the smallest FP type
1161 // that can accurately represent it. This allows us to turn
1162 // (float)((double)X+2.0) into x+2.0f.
1163 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
1164 if (CFP->getType() == Type::getPPC_FP128Ty(V->getContext()))
1165 return V; // No constant folding of this.
1166 // See if the value can be truncated to float and then reextended.
1167 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
1169 if (CFP->getType()->isDoubleTy())
1170 return V; // Won't shrink.
1171 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
1173 // Don't try to shrink to various long double types.
1179 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
1180 if (Instruction *I = commonCastTransforms(CI))
1183 // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
1184 // smaller than the destination type, we can eliminate the truncate by doing
1185 // the add as the smaller type. This applies to fadd/fsub/fmul/fdiv as well
1186 // as many builtins (sqrt, etc).
1187 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
1188 if (OpI && OpI->hasOneUse()) {
1189 switch (OpI->getOpcode()) {
1191 case Instruction::FAdd:
1192 case Instruction::FSub:
1193 case Instruction::FMul:
1194 case Instruction::FDiv:
1195 case Instruction::FRem:
1196 Type *SrcTy = OpI->getType();
1197 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
1198 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
1199 if (LHSTrunc->getType() != SrcTy &&
1200 RHSTrunc->getType() != SrcTy) {
1201 unsigned DstSize = CI.getType()->getScalarSizeInBits();
1202 // If the source types were both smaller than the destination type of
1203 // the cast, do this xform.
1204 if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
1205 RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
1206 LHSTrunc = Builder->CreateFPExt(LHSTrunc, CI.getType());
1207 RHSTrunc = Builder->CreateFPExt(RHSTrunc, CI.getType());
1208 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
1215 // Fold (fptrunc (sqrt (fpext x))) -> (sqrtf x)
1216 // NOTE: This should be disabled by -fno-builtin-sqrt if we ever support it.
1217 CallInst *Call = dyn_cast<CallInst>(CI.getOperand(0));
1218 if (Call && Call->getCalledFunction() &&
1219 Call->getCalledFunction()->getName() == "sqrt" &&
1220 Call->getNumArgOperands() == 1 &&
1221 Call->hasOneUse()) {
1222 CastInst *Arg = dyn_cast<CastInst>(Call->getArgOperand(0));
1223 if (Arg && Arg->getOpcode() == Instruction::FPExt &&
1224 CI.getType()->isFloatTy() &&
1225 Call->getType()->isDoubleTy() &&
1226 Arg->getType()->isDoubleTy() &&
1227 Arg->getOperand(0)->getType()->isFloatTy()) {
1228 Function *Callee = Call->getCalledFunction();
1229 Module *M = CI.getParent()->getParent()->getParent();
1230 Constant *SqrtfFunc = M->getOrInsertFunction("sqrtf",
1231 Callee->getAttributes(),
1232 Builder->getFloatTy(),
1233 Builder->getFloatTy(),
1235 CallInst *ret = CallInst::Create(SqrtfFunc, Arg->getOperand(0),
1237 ret->setAttributes(Callee->getAttributes());
1240 // Remove the old Call. With -fmath-errno, it won't get marked readnone.
1241 ReplaceInstUsesWith(*Call, UndefValue::get(Call->getType()));
1242 EraseInstFromFunction(*Call);
1250 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
1251 return commonCastTransforms(CI);
1254 Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
1255 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
1257 return commonCastTransforms(FI);
1259 // fptoui(uitofp(X)) --> X
1260 // fptoui(sitofp(X)) --> X
1261 // This is safe if the intermediate type has enough bits in its mantissa to
1262 // accurately represent all values of X. For example, do not do this with
1263 // i64->float->i64. This is also safe for sitofp case, because any negative
1264 // 'X' value would cause an undefined result for the fptoui.
1265 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
1266 OpI->getOperand(0)->getType() == FI.getType() &&
1267 (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
1268 OpI->getType()->getFPMantissaWidth())
1269 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
1271 return commonCastTransforms(FI);
1274 Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
1275 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
1277 return commonCastTransforms(FI);
1279 // fptosi(sitofp(X)) --> X
1280 // fptosi(uitofp(X)) --> X
1281 // This is safe if the intermediate type has enough bits in its mantissa to
1282 // accurately represent all values of X. For example, do not do this with
1283 // i64->float->i64. This is also safe for sitofp case, because any negative
1284 // 'X' value would cause an undefined result for the fptoui.
1285 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
1286 OpI->getOperand(0)->getType() == FI.getType() &&
1287 (int)FI.getType()->getScalarSizeInBits() <=
1288 OpI->getType()->getFPMantissaWidth())
1289 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
1291 return commonCastTransforms(FI);
1294 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
1295 return commonCastTransforms(CI);
1298 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
1299 return commonCastTransforms(CI);
1302 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
1303 // If the source integer type is not the intptr_t type for this target, do a
1304 // trunc or zext to the intptr_t type, then inttoptr of it. This allows the
1305 // cast to be exposed to other transforms.
1307 if (CI.getOperand(0)->getType()->getScalarSizeInBits() >
1308 TD->getPointerSizeInBits()) {
1309 Value *P = Builder->CreateTrunc(CI.getOperand(0),
1310 TD->getIntPtrType(CI.getContext()), "tmp");
1311 return new IntToPtrInst(P, CI.getType());
1313 if (CI.getOperand(0)->getType()->getScalarSizeInBits() <
1314 TD->getPointerSizeInBits()) {
1315 Value *P = Builder->CreateZExt(CI.getOperand(0),
1316 TD->getIntPtrType(CI.getContext()), "tmp");
1317 return new IntToPtrInst(P, CI.getType());
1321 if (Instruction *I = commonCastTransforms(CI))
1327 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
1328 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
1329 Value *Src = CI.getOperand(0);
1331 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
1332 // If casting the result of a getelementptr instruction with no offset, turn
1333 // this into a cast of the original pointer!
1334 if (GEP->hasAllZeroIndices()) {
1335 // Changing the cast operand is usually not a good idea but it is safe
1336 // here because the pointer operand is being replaced with another
1337 // pointer operand so the opcode doesn't need to change.
1339 CI.setOperand(0, GEP->getOperand(0));
1343 // If the GEP has a single use, and the base pointer is a bitcast, and the
1344 // GEP computes a constant offset, see if we can convert these three
1345 // instructions into fewer. This typically happens with unions and other
1346 // non-type-safe code.
1347 if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0)) &&
1348 GEP->hasAllConstantIndices()) {
1349 // We are guaranteed to get a constant from EmitGEPOffset.
1350 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP));
1351 int64_t Offset = OffsetV->getSExtValue();
1353 // Get the base pointer input of the bitcast, and the type it points to.
1354 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
1356 cast<PointerType>(OrigBase->getType())->getElementType();
1357 SmallVector<Value*, 8> NewIndices;
1358 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices)) {
1359 // If we were able to index down into an element, create the GEP
1360 // and bitcast the result. This eliminates one bitcast, potentially
1362 Value *NGEP = cast<GEPOperator>(GEP)->isInBounds() ?
1363 Builder->CreateInBoundsGEP(OrigBase, NewIndices) :
1364 Builder->CreateGEP(OrigBase, NewIndices);
1365 NGEP->takeName(GEP);
1367 if (isa<BitCastInst>(CI))
1368 return new BitCastInst(NGEP, CI.getType());
1369 assert(isa<PtrToIntInst>(CI));
1370 return new PtrToIntInst(NGEP, CI.getType());
1375 return commonCastTransforms(CI);
1378 Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
1379 // If the destination integer type is not the intptr_t type for this target,
1380 // do a ptrtoint to intptr_t then do a trunc or zext. This allows the cast
1381 // to be exposed to other transforms.
1383 if (CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
1384 Value *P = Builder->CreatePtrToInt(CI.getOperand(0),
1385 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()),
1393 return new ZExtInst(P, CI.getType());
1397 return commonPointerCastTransforms(CI);
1400 /// OptimizeVectorResize - This input value (which is known to have vector type)
1401 /// is being zero extended or truncated to the specified vector type. Try to
1402 /// replace it with a shuffle (and vector/vector bitcast) if possible.
1404 /// The source and destination vector types may have different element types.
1405 static Instruction *OptimizeVectorResize(Value *InVal, VectorType *DestTy,
1407 // We can only do this optimization if the output is a multiple of the input
1408 // element size, or the input is a multiple of the output element size.
1409 // Convert the input type to have the same element type as the output.
1410 VectorType *SrcTy = cast<VectorType>(InVal->getType());
1412 if (SrcTy->getElementType() != DestTy->getElementType()) {
1413 // The input types don't need to be identical, but for now they must be the
1414 // same size. There is no specific reason we couldn't handle things like
1415 // <4 x i16> -> <4 x i32> by bitcasting to <2 x i32> but haven't gotten
1417 if (SrcTy->getElementType()->getPrimitiveSizeInBits() !=
1418 DestTy->getElementType()->getPrimitiveSizeInBits())
1421 SrcTy = VectorType::get(DestTy->getElementType(), SrcTy->getNumElements());
1422 InVal = IC.Builder->CreateBitCast(InVal, SrcTy);
1425 // Now that the element types match, get the shuffle mask and RHS of the
1426 // shuffle to use, which depends on whether we're increasing or decreasing the
1427 // size of the input.
1428 SmallVector<Constant*, 16> ShuffleMask;
1430 IntegerType *Int32Ty = Type::getInt32Ty(SrcTy->getContext());
1432 if (SrcTy->getNumElements() > DestTy->getNumElements()) {
1433 // If we're shrinking the number of elements, just shuffle in the low
1434 // elements from the input and use undef as the second shuffle input.
1435 V2 = UndefValue::get(SrcTy);
1436 for (unsigned i = 0, e = DestTy->getNumElements(); i != e; ++i)
1437 ShuffleMask.push_back(ConstantInt::get(Int32Ty, i));
1440 // If we're increasing the number of elements, shuffle in all of the
1441 // elements from InVal and fill the rest of the result elements with zeros
1442 // from a constant zero.
1443 V2 = Constant::getNullValue(SrcTy);
1444 unsigned SrcElts = SrcTy->getNumElements();
1445 for (unsigned i = 0, e = SrcElts; i != e; ++i)
1446 ShuffleMask.push_back(ConstantInt::get(Int32Ty, i));
1448 // The excess elements reference the first element of the zero input.
1449 ShuffleMask.append(DestTy->getNumElements()-SrcElts,
1450 ConstantInt::get(Int32Ty, SrcElts));
1453 return new ShuffleVectorInst(InVal, V2, ConstantVector::get(ShuffleMask));
1456 static bool isMultipleOfTypeSize(unsigned Value, Type *Ty) {
1457 return Value % Ty->getPrimitiveSizeInBits() == 0;
1460 static unsigned getTypeSizeIndex(unsigned Value, Type *Ty) {
1461 return Value / Ty->getPrimitiveSizeInBits();
1464 /// CollectInsertionElements - V is a value which is inserted into a vector of
1465 /// VecEltTy. Look through the value to see if we can decompose it into
1466 /// insertions into the vector. See the example in the comment for
1467 /// OptimizeIntegerToVectorInsertions for the pattern this handles.
1468 /// The type of V is always a non-zero multiple of VecEltTy's size.
1470 /// This returns false if the pattern can't be matched or true if it can,
1471 /// filling in Elements with the elements found here.
1472 static bool CollectInsertionElements(Value *V, unsigned ElementIndex,
1473 SmallVectorImpl<Value*> &Elements,
1475 // Undef values never contribute useful bits to the result.
1476 if (isa<UndefValue>(V)) return true;
1478 // If we got down to a value of the right type, we win, try inserting into the
1480 if (V->getType() == VecEltTy) {
1481 // Inserting null doesn't actually insert any elements.
1482 if (Constant *C = dyn_cast<Constant>(V))
1483 if (C->isNullValue())
1486 // Fail if multiple elements are inserted into this slot.
1487 if (ElementIndex >= Elements.size() || Elements[ElementIndex] != 0)
1490 Elements[ElementIndex] = V;
1494 if (Constant *C = dyn_cast<Constant>(V)) {
1495 // Figure out the # elements this provides, and bitcast it or slice it up
1497 unsigned NumElts = getTypeSizeIndex(C->getType()->getPrimitiveSizeInBits(),
1499 // If the constant is the size of a vector element, we just need to bitcast
1500 // it to the right type so it gets properly inserted.
1502 return CollectInsertionElements(ConstantExpr::getBitCast(C, VecEltTy),
1503 ElementIndex, Elements, VecEltTy);
1505 // Okay, this is a constant that covers multiple elements. Slice it up into
1506 // pieces and insert each element-sized piece into the vector.
1507 if (!isa<IntegerType>(C->getType()))
1508 C = ConstantExpr::getBitCast(C, IntegerType::get(V->getContext(),
1509 C->getType()->getPrimitiveSizeInBits()));
1510 unsigned ElementSize = VecEltTy->getPrimitiveSizeInBits();
1511 Type *ElementIntTy = IntegerType::get(C->getContext(), ElementSize);
1513 for (unsigned i = 0; i != NumElts; ++i) {
1514 Constant *Piece = ConstantExpr::getLShr(C, ConstantInt::get(C->getType(),
1516 Piece = ConstantExpr::getTrunc(Piece, ElementIntTy);
1517 if (!CollectInsertionElements(Piece, ElementIndex+i, Elements, VecEltTy))
1523 if (!V->hasOneUse()) return false;
1525 Instruction *I = dyn_cast<Instruction>(V);
1526 if (I == 0) return false;
1527 switch (I->getOpcode()) {
1528 default: return false; // Unhandled case.
1529 case Instruction::BitCast:
1530 return CollectInsertionElements(I->getOperand(0), ElementIndex,
1531 Elements, VecEltTy);
1532 case Instruction::ZExt:
1533 if (!isMultipleOfTypeSize(
1534 I->getOperand(0)->getType()->getPrimitiveSizeInBits(),
1537 return CollectInsertionElements(I->getOperand(0), ElementIndex,
1538 Elements, VecEltTy);
1539 case Instruction::Or:
1540 return CollectInsertionElements(I->getOperand(0), ElementIndex,
1541 Elements, VecEltTy) &&
1542 CollectInsertionElements(I->getOperand(1), ElementIndex,
1543 Elements, VecEltTy);
1544 case Instruction::Shl: {
1545 // Must be shifting by a constant that is a multiple of the element size.
1546 ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1));
1547 if (CI == 0) return false;
1548 if (!isMultipleOfTypeSize(CI->getZExtValue(), VecEltTy)) return false;
1549 unsigned IndexShift = getTypeSizeIndex(CI->getZExtValue(), VecEltTy);
1551 return CollectInsertionElements(I->getOperand(0), ElementIndex+IndexShift,
1552 Elements, VecEltTy);
1559 /// OptimizeIntegerToVectorInsertions - If the input is an 'or' instruction, we
1560 /// may be doing shifts and ors to assemble the elements of the vector manually.
1561 /// Try to rip the code out and replace it with insertelements. This is to
1562 /// optimize code like this:
1564 /// %tmp37 = bitcast float %inc to i32
1565 /// %tmp38 = zext i32 %tmp37 to i64
1566 /// %tmp31 = bitcast float %inc5 to i32
1567 /// %tmp32 = zext i32 %tmp31 to i64
1568 /// %tmp33 = shl i64 %tmp32, 32
1569 /// %ins35 = or i64 %tmp33, %tmp38
1570 /// %tmp43 = bitcast i64 %ins35 to <2 x float>
1572 /// Into two insertelements that do "buildvector{%inc, %inc5}".
1573 static Value *OptimizeIntegerToVectorInsertions(BitCastInst &CI,
1575 VectorType *DestVecTy = cast<VectorType>(CI.getType());
1576 Value *IntInput = CI.getOperand(0);
1578 SmallVector<Value*, 8> Elements(DestVecTy->getNumElements());
1579 if (!CollectInsertionElements(IntInput, 0, Elements,
1580 DestVecTy->getElementType()))
1583 // If we succeeded, we know that all of the element are specified by Elements
1584 // or are zero if Elements has a null entry. Recast this as a set of
1586 Value *Result = Constant::getNullValue(CI.getType());
1587 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
1588 if (Elements[i] == 0) continue; // Unset element.
1590 Result = IC.Builder->CreateInsertElement(Result, Elements[i],
1591 IC.Builder->getInt32(i));
1598 /// OptimizeIntToFloatBitCast - See if we can optimize an integer->float/double
1599 /// bitcast. The various long double bitcasts can't get in here.
1600 static Instruction *OptimizeIntToFloatBitCast(BitCastInst &CI,InstCombiner &IC){
1601 Value *Src = CI.getOperand(0);
1602 Type *DestTy = CI.getType();
1604 // If this is a bitcast from int to float, check to see if the int is an
1605 // extraction from a vector.
1606 Value *VecInput = 0;
1607 // bitcast(trunc(bitcast(somevector)))
1608 if (match(Src, m_Trunc(m_BitCast(m_Value(VecInput)))) &&
1609 isa<VectorType>(VecInput->getType())) {
1610 VectorType *VecTy = cast<VectorType>(VecInput->getType());
1611 unsigned DestWidth = DestTy->getPrimitiveSizeInBits();
1613 if (VecTy->getPrimitiveSizeInBits() % DestWidth == 0) {
1614 // If the element type of the vector doesn't match the result type,
1615 // bitcast it to be a vector type we can extract from.
1616 if (VecTy->getElementType() != DestTy) {
1617 VecTy = VectorType::get(DestTy,
1618 VecTy->getPrimitiveSizeInBits() / DestWidth);
1619 VecInput = IC.Builder->CreateBitCast(VecInput, VecTy);
1622 return ExtractElementInst::Create(VecInput, IC.Builder->getInt32(0));
1626 // bitcast(trunc(lshr(bitcast(somevector), cst))
1627 ConstantInt *ShAmt = 0;
1628 if (match(Src, m_Trunc(m_LShr(m_BitCast(m_Value(VecInput)),
1629 m_ConstantInt(ShAmt)))) &&
1630 isa<VectorType>(VecInput->getType())) {
1631 VectorType *VecTy = cast<VectorType>(VecInput->getType());
1632 unsigned DestWidth = DestTy->getPrimitiveSizeInBits();
1633 if (VecTy->getPrimitiveSizeInBits() % DestWidth == 0 &&
1634 ShAmt->getZExtValue() % DestWidth == 0) {
1635 // If the element type of the vector doesn't match the result type,
1636 // bitcast it to be a vector type we can extract from.
1637 if (VecTy->getElementType() != DestTy) {
1638 VecTy = VectorType::get(DestTy,
1639 VecTy->getPrimitiveSizeInBits() / DestWidth);
1640 VecInput = IC.Builder->CreateBitCast(VecInput, VecTy);
1643 unsigned Elt = ShAmt->getZExtValue() / DestWidth;
1644 return ExtractElementInst::Create(VecInput, IC.Builder->getInt32(Elt));
1650 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
1651 // If the operands are integer typed then apply the integer transforms,
1652 // otherwise just apply the common ones.
1653 Value *Src = CI.getOperand(0);
1654 Type *SrcTy = Src->getType();
1655 Type *DestTy = CI.getType();
1657 // Get rid of casts from one type to the same type. These are useless and can
1658 // be replaced by the operand.
1659 if (DestTy == Src->getType())
1660 return ReplaceInstUsesWith(CI, Src);
1662 // Bitcasts are transitive.
1663 if (BitCastInst* BSrc = dyn_cast<BitCastInst>(Src)) {
1664 return CastInst::Create(Instruction::BitCast, BSrc->getOperand(0), DestTy);
1667 if (PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
1668 PointerType *SrcPTy = cast<PointerType>(SrcTy);
1669 Type *DstElTy = DstPTy->getElementType();
1670 Type *SrcElTy = SrcPTy->getElementType();
1672 // If the address spaces don't match, don't eliminate the bitcast, which is
1673 // required for changing types.
1674 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
1677 // If we are casting a alloca to a pointer to a type of the same
1678 // size, rewrite the allocation instruction to allocate the "right" type.
1679 // There is no need to modify malloc calls because it is their bitcast that
1680 // needs to be cleaned up.
1681 if (AllocaInst *AI = dyn_cast<AllocaInst>(Src))
1682 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
1685 // If the source and destination are pointers, and this cast is equivalent
1686 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
1687 // This can enhance SROA and other transforms that want type-safe pointers.
1688 Constant *ZeroUInt =
1689 Constant::getNullValue(Type::getInt32Ty(CI.getContext()));
1690 unsigned NumZeros = 0;
1691 while (SrcElTy != DstElTy &&
1692 isa<CompositeType>(SrcElTy) && !SrcElTy->isPointerTy() &&
1693 SrcElTy->getNumContainedTypes() /* not "{}" */) {
1694 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
1698 // If we found a path from the src to dest, create the getelementptr now.
1699 if (SrcElTy == DstElTy) {
1700 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
1701 return GetElementPtrInst::CreateInBounds(Src, Idxs);
1705 // Try to optimize int -> float bitcasts.
1706 if ((DestTy->isFloatTy() || DestTy->isDoubleTy()) && isa<IntegerType>(SrcTy))
1707 if (Instruction *I = OptimizeIntToFloatBitCast(CI, *this))
1710 if (VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
1711 if (DestVTy->getNumElements() == 1 && !SrcTy->isVectorTy()) {
1712 Value *Elem = Builder->CreateBitCast(Src, DestVTy->getElementType());
1713 return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
1714 Constant::getNullValue(Type::getInt32Ty(CI.getContext())));
1715 // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
1718 if (isa<IntegerType>(SrcTy)) {
1719 // If this is a cast from an integer to vector, check to see if the input
1720 // is a trunc or zext of a bitcast from vector. If so, we can replace all
1721 // the casts with a shuffle and (potentially) a bitcast.
1722 if (isa<TruncInst>(Src) || isa<ZExtInst>(Src)) {
1723 CastInst *SrcCast = cast<CastInst>(Src);
1724 if (BitCastInst *BCIn = dyn_cast<BitCastInst>(SrcCast->getOperand(0)))
1725 if (isa<VectorType>(BCIn->getOperand(0)->getType()))
1726 if (Instruction *I = OptimizeVectorResize(BCIn->getOperand(0),
1727 cast<VectorType>(DestTy), *this))
1731 // If the input is an 'or' instruction, we may be doing shifts and ors to
1732 // assemble the elements of the vector manually. Try to rip the code out
1733 // and replace it with insertelements.
1734 if (Value *V = OptimizeIntegerToVectorInsertions(CI, *this))
1735 return ReplaceInstUsesWith(CI, V);
1739 if (VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
1740 if (SrcVTy->getNumElements() == 1 && !DestTy->isVectorTy()) {
1742 Builder->CreateExtractElement(Src,
1743 Constant::getNullValue(Type::getInt32Ty(CI.getContext())));
1744 return CastInst::Create(Instruction::BitCast, Elem, DestTy);
1748 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
1749 // Okay, we have (bitcast (shuffle ..)). Check to see if this is
1750 // a bitcast to a vector with the same # elts.
1751 if (SVI->hasOneUse() && DestTy->isVectorTy() &&
1752 cast<VectorType>(DestTy)->getNumElements() ==
1753 SVI->getType()->getNumElements() &&
1754 SVI->getType()->getNumElements() ==
1755 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
1757 // If either of the operands is a cast from CI.getType(), then
1758 // evaluating the shuffle in the casted destination's type will allow
1759 // us to eliminate at least one cast.
1760 if (((Tmp = dyn_cast<BitCastInst>(SVI->getOperand(0))) &&
1761 Tmp->getOperand(0)->getType() == DestTy) ||
1762 ((Tmp = dyn_cast<BitCastInst>(SVI->getOperand(1))) &&
1763 Tmp->getOperand(0)->getType() == DestTy)) {
1764 Value *LHS = Builder->CreateBitCast(SVI->getOperand(0), DestTy);
1765 Value *RHS = Builder->CreateBitCast(SVI->getOperand(1), DestTy);
1766 // Return a new shuffle vector. Use the same element ID's, as we
1767 // know the vector types match #elts.
1768 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
1773 if (SrcTy->isPointerTy())
1774 return commonPointerCastTransforms(CI);
1775 return commonCastTransforms(CI);