1 //===- InstCombineCasts.cpp -----------------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the visit functions for cast operations.
12 //===----------------------------------------------------------------------===//
14 #include "InstCombine.h"
15 #include "llvm/Target/TargetData.h"
16 #include "llvm/Support/PatternMatch.h"
18 using namespace PatternMatch;
20 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
21 /// expression. If so, decompose it, returning some value X, such that Val is
24 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
26 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
27 Offset = CI->getZExtValue();
29 return ConstantInt::get(Val->getType(), 0);
32 if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
33 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
34 if (I->getOpcode() == Instruction::Shl) {
35 // This is a value scaled by '1 << the shift amt'.
36 Scale = UINT64_C(1) << RHS->getZExtValue();
38 return I->getOperand(0);
41 if (I->getOpcode() == Instruction::Mul) {
42 // This value is scaled by 'RHS'.
43 Scale = RHS->getZExtValue();
45 return I->getOperand(0);
48 if (I->getOpcode() == Instruction::Add) {
49 // We have X+C. Check to see if we really have (X*C2)+C1,
50 // where C1 is divisible by C2.
53 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
54 Offset += RHS->getZExtValue();
61 // Otherwise, we can't look past this.
67 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
68 /// try to eliminate the cast by moving the type information into the alloc.
69 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
71 // This requires TargetData to get the alloca alignment and size information.
74 const PointerType *PTy = cast<PointerType>(CI.getType());
76 BuilderTy AllocaBuilder(*Builder);
77 AllocaBuilder.SetInsertPoint(AI.getParent(), &AI);
79 // Get the type really allocated and the type casted to.
80 const Type *AllocElTy = AI.getAllocatedType();
81 const Type *CastElTy = PTy->getElementType();
82 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
84 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
85 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
86 if (CastElTyAlign < AllocElTyAlign) return 0;
88 // If the allocation has multiple uses, only promote it if we are strictly
89 // increasing the alignment of the resultant allocation. If we keep it the
90 // same, we open the door to infinite loops of various kinds. (A reference
91 // from a dbg.declare doesn't count as a use for this purpose.)
92 if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
93 CastElTyAlign == AllocElTyAlign) return 0;
95 uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
96 uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
97 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
99 // See if we can satisfy the modulus by pulling a scale out of the array
101 unsigned ArraySizeScale;
102 uint64_t ArrayOffset;
103 Value *NumElements = // See if the array size is a decomposable linear expr.
104 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
106 // If we can now satisfy the modulus, by using a non-1 scale, we really can
108 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
109 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
111 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
116 Amt = ConstantInt::get(AI.getArraySize()->getType(), Scale);
117 // Insert before the alloca, not before the cast.
118 Amt = AllocaBuilder.CreateMul(Amt, NumElements, "tmp");
121 if (uint64_t Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
122 Value *Off = ConstantInt::get(AI.getArraySize()->getType(),
124 Amt = AllocaBuilder.CreateAdd(Amt, Off, "tmp");
127 AllocaInst *New = AllocaBuilder.CreateAlloca(CastElTy, Amt);
128 New->setAlignment(AI.getAlignment());
131 // If the allocation has one real use plus a dbg.declare, just remove the
133 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
134 EraseInstFromFunction(*(Instruction*)DI);
136 // If the allocation has multiple real uses, insert a cast and change all
137 // things that used it to use the new cast. This will also hack on CI, but it
139 else if (!AI.hasOneUse()) {
140 // New is the allocation instruction, pointer typed. AI is the original
141 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
142 Value *NewCast = AllocaBuilder.CreateBitCast(New, AI.getType(), "tmpcast");
143 AI.replaceAllUsesWith(NewCast);
145 return ReplaceInstUsesWith(CI, New);
150 /// EvaluateInDifferentType - Given an expression that
151 /// CanEvaluateTruncated or CanEvaluateSExtd returns true for, actually
152 /// insert the code to evaluate the expression.
153 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
155 if (Constant *C = dyn_cast<Constant>(V)) {
156 C = ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
157 // If we got a constantexpr back, try to simplify it with TD info.
158 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
159 C = ConstantFoldConstantExpression(CE, TD);
163 // Otherwise, it must be an instruction.
164 Instruction *I = cast<Instruction>(V);
165 Instruction *Res = 0;
166 unsigned Opc = I->getOpcode();
168 case Instruction::Add:
169 case Instruction::Sub:
170 case Instruction::Mul:
171 case Instruction::And:
172 case Instruction::Or:
173 case Instruction::Xor:
174 case Instruction::AShr:
175 case Instruction::LShr:
176 case Instruction::Shl:
177 case Instruction::UDiv:
178 case Instruction::URem: {
179 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
180 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
181 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
184 case Instruction::Trunc:
185 case Instruction::ZExt:
186 case Instruction::SExt:
187 // If the source type of the cast is the type we're trying for then we can
188 // just return the source. There's no need to insert it because it is not
190 if (I->getOperand(0)->getType() == Ty)
191 return I->getOperand(0);
193 // Otherwise, must be the same type of cast, so just reinsert a new one.
194 // This also handles the case of zext(trunc(x)) -> zext(x).
195 Res = CastInst::CreateIntegerCast(I->getOperand(0), Ty,
196 Opc == Instruction::SExt);
198 case Instruction::Select: {
199 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
200 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
201 Res = SelectInst::Create(I->getOperand(0), True, False);
204 case Instruction::PHI: {
205 PHINode *OPN = cast<PHINode>(I);
206 PHINode *NPN = PHINode::Create(Ty);
207 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
208 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
209 NPN->addIncoming(V, OPN->getIncomingBlock(i));
215 // TODO: Can handle more cases here.
216 llvm_unreachable("Unreachable!");
221 return InsertNewInstBefore(Res, *I);
225 /// This function is a wrapper around CastInst::isEliminableCastPair. It
226 /// simply extracts arguments and returns what that function returns.
227 static Instruction::CastOps
228 isEliminableCastPair(
229 const CastInst *CI, ///< The first cast instruction
230 unsigned opcode, ///< The opcode of the second cast instruction
231 const Type *DstTy, ///< The target type for the second cast instruction
232 TargetData *TD ///< The target data for pointer size
235 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
236 const Type *MidTy = CI->getType(); // B from above
238 // Get the opcodes of the two Cast instructions
239 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
240 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
242 unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
244 TD ? TD->getIntPtrType(CI->getContext()) : 0);
246 // We don't want to form an inttoptr or ptrtoint that converts to an integer
247 // type that differs from the pointer size.
248 if ((Res == Instruction::IntToPtr &&
249 (!TD || SrcTy != TD->getIntPtrType(CI->getContext()))) ||
250 (Res == Instruction::PtrToInt &&
251 (!TD || DstTy != TD->getIntPtrType(CI->getContext()))))
254 return Instruction::CastOps(Res);
257 /// ShouldOptimizeCast - Return true if the cast from "V to Ty" actually
258 /// results in any code being generated and is interesting to optimize out. If
259 /// the cast can be eliminated by some other simple transformation, we prefer
260 /// to do the simplification first.
261 bool InstCombiner::ShouldOptimizeCast(Instruction::CastOps opc, const Value *V,
263 // Noop casts and casts of constants should be eliminated trivially.
264 if (V->getType() == Ty || isa<Constant>(V)) return false;
266 // If this is another cast that can be eliminated, we prefer to have it
268 if (const CastInst *CI = dyn_cast<CastInst>(V))
269 if (isEliminableCastPair(CI, opc, Ty, TD))
272 // If this is a vector sext from a compare, then we don't want to break the
273 // idiom where each element of the extended vector is either zero or all ones.
274 if (opc == Instruction::SExt && isa<CmpInst>(V) && Ty->isVectorTy())
281 /// @brief Implement the transforms common to all CastInst visitors.
282 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
283 Value *Src = CI.getOperand(0);
285 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
287 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
288 if (Instruction::CastOps opc =
289 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
290 // The first cast (CSrc) is eliminable so we need to fix up or replace
291 // the second cast (CI). CSrc will then have a good chance of being dead.
292 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
296 // If we are casting a select then fold the cast into the select
297 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
298 if (Instruction *NV = FoldOpIntoSelect(CI, SI))
301 // If we are casting a PHI then fold the cast into the PHI
302 if (isa<PHINode>(Src)) {
303 // We don't do this if this would create a PHI node with an illegal type if
304 // it is currently legal.
305 if (!Src->getType()->isIntegerTy() ||
306 !CI.getType()->isIntegerTy() ||
307 ShouldChangeType(CI.getType(), Src->getType()))
308 if (Instruction *NV = FoldOpIntoPhi(CI))
315 /// CanEvaluateTruncated - Return true if we can evaluate the specified
316 /// expression tree as type Ty instead of its larger type, and arrive with the
317 /// same value. This is used by code that tries to eliminate truncates.
319 /// Ty will always be a type smaller than V. We should return true if trunc(V)
320 /// can be computed by computing V in the smaller type. If V is an instruction,
321 /// then trunc(inst(x,y)) can be computed as inst(trunc(x),trunc(y)), which only
322 /// makes sense if x and y can be efficiently truncated.
324 /// This function works on both vectors and scalars.
326 static bool CanEvaluateTruncated(Value *V, const Type *Ty) {
327 // We can always evaluate constants in another type.
328 if (isa<Constant>(V))
331 Instruction *I = dyn_cast<Instruction>(V);
332 if (!I) return false;
334 const Type *OrigTy = V->getType();
336 // If this is an extension from the dest type, we can eliminate it, even if it
337 // has multiple uses.
338 if ((isa<ZExtInst>(I) || isa<SExtInst>(I)) &&
339 I->getOperand(0)->getType() == Ty)
342 // We can't extend or shrink something that has multiple uses: doing so would
343 // require duplicating the instruction in general, which isn't profitable.
344 if (!I->hasOneUse()) return false;
346 unsigned Opc = I->getOpcode();
348 case Instruction::Add:
349 case Instruction::Sub:
350 case Instruction::Mul:
351 case Instruction::And:
352 case Instruction::Or:
353 case Instruction::Xor:
354 // These operators can all arbitrarily be extended or truncated.
355 return CanEvaluateTruncated(I->getOperand(0), Ty) &&
356 CanEvaluateTruncated(I->getOperand(1), Ty);
358 case Instruction::UDiv:
359 case Instruction::URem: {
360 // UDiv and URem can be truncated if all the truncated bits are zero.
361 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
362 uint32_t BitWidth = Ty->getScalarSizeInBits();
363 if (BitWidth < OrigBitWidth) {
364 APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
365 if (MaskedValueIsZero(I->getOperand(0), Mask) &&
366 MaskedValueIsZero(I->getOperand(1), Mask)) {
367 return CanEvaluateTruncated(I->getOperand(0), Ty) &&
368 CanEvaluateTruncated(I->getOperand(1), Ty);
373 case Instruction::Shl:
374 // If we are truncating the result of this SHL, and if it's a shift of a
375 // constant amount, we can always perform a SHL in a smaller type.
376 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
377 uint32_t BitWidth = Ty->getScalarSizeInBits();
378 if (CI->getLimitedValue(BitWidth) < BitWidth)
379 return CanEvaluateTruncated(I->getOperand(0), Ty);
382 case Instruction::LShr:
383 // If this is a truncate of a logical shr, we can truncate it to a smaller
384 // lshr iff we know that the bits we would otherwise be shifting in are
386 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
387 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
388 uint32_t BitWidth = Ty->getScalarSizeInBits();
389 if (MaskedValueIsZero(I->getOperand(0),
390 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
391 CI->getLimitedValue(BitWidth) < BitWidth) {
392 return CanEvaluateTruncated(I->getOperand(0), Ty);
396 case Instruction::Trunc:
397 // trunc(trunc(x)) -> trunc(x)
399 case Instruction::ZExt:
400 case Instruction::SExt:
401 // trunc(ext(x)) -> ext(x) if the source type is smaller than the new dest
402 // trunc(ext(x)) -> trunc(x) if the source type is larger than the new dest
404 case Instruction::Select: {
405 SelectInst *SI = cast<SelectInst>(I);
406 return CanEvaluateTruncated(SI->getTrueValue(), Ty) &&
407 CanEvaluateTruncated(SI->getFalseValue(), Ty);
409 case Instruction::PHI: {
410 // We can change a phi if we can change all operands. Note that we never
411 // get into trouble with cyclic PHIs here because we only consider
412 // instructions with a single use.
413 PHINode *PN = cast<PHINode>(I);
414 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
415 if (!CanEvaluateTruncated(PN->getIncomingValue(i), Ty))
420 // TODO: Can handle more cases here.
427 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
428 if (Instruction *Result = commonCastTransforms(CI))
431 // See if we can simplify any instructions used by the input whose sole
432 // purpose is to compute bits we don't care about.
433 if (SimplifyDemandedInstructionBits(CI))
436 Value *Src = CI.getOperand(0);
437 const Type *DestTy = CI.getType(), *SrcTy = Src->getType();
439 // Attempt to truncate the entire input expression tree to the destination
440 // type. Only do this if the dest type is a simple type, don't convert the
441 // expression tree to something weird like i93 unless the source is also
443 if ((DestTy->isVectorTy() || ShouldChangeType(SrcTy, DestTy)) &&
444 CanEvaluateTruncated(Src, DestTy)) {
446 // If this cast is a truncate, evaluting in a different type always
447 // eliminates the cast, so it is always a win.
448 DEBUG(dbgs() << "ICE: EvaluateInDifferentType converting expression type"
449 " to avoid cast: " << CI << '\n');
450 Value *Res = EvaluateInDifferentType(Src, DestTy, false);
451 assert(Res->getType() == DestTy);
452 return ReplaceInstUsesWith(CI, Res);
455 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0), likewise for vector.
456 if (DestTy->getScalarSizeInBits() == 1) {
457 Constant *One = ConstantInt::get(Src->getType(), 1);
458 Src = Builder->CreateAnd(Src, One, "tmp");
459 Value *Zero = Constant::getNullValue(Src->getType());
460 return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
463 // Transform trunc(lshr (zext A), Cst) to eliminate one type conversion.
464 Value *A = 0; ConstantInt *Cst = 0;
465 if (match(Src, m_LShr(m_ZExt(m_Value(A)), m_ConstantInt(Cst))) &&
467 // We have three types to worry about here, the type of A, the source of
468 // the truncate (MidSize), and the destination of the truncate. We know that
469 // ASize < MidSize and MidSize > ResultSize, but don't know the relation
470 // between ASize and ResultSize.
471 unsigned ASize = A->getType()->getPrimitiveSizeInBits();
473 // If the shift amount is larger than the size of A, then the result is
474 // known to be zero because all the input bits got shifted out.
475 if (Cst->getZExtValue() >= ASize)
476 return ReplaceInstUsesWith(CI, Constant::getNullValue(CI.getType()));
478 // Since we're doing an lshr and a zero extend, and know that the shift
479 // amount is smaller than ASize, it is always safe to do the shift in A's
480 // type, then zero extend or truncate to the result.
481 Value *Shift = Builder->CreateLShr(A, Cst->getZExtValue());
482 Shift->takeName(Src);
483 return CastInst::CreateIntegerCast(Shift, CI.getType(), false);
489 /// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
490 /// in order to eliminate the icmp.
491 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
493 // If we are just checking for a icmp eq of a single bit and zext'ing it
494 // to an integer, then shift the bit to the appropriate place and then
495 // cast to integer to avoid the comparison.
496 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
497 const APInt &Op1CV = Op1C->getValue();
499 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
500 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
501 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
502 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
503 if (!DoXform) return ICI;
505 Value *In = ICI->getOperand(0);
506 Value *Sh = ConstantInt::get(In->getType(),
507 In->getType()->getScalarSizeInBits()-1);
508 In = Builder->CreateLShr(In, Sh, In->getName()+".lobit");
509 if (In->getType() != CI.getType())
510 In = Builder->CreateIntCast(In, CI.getType(), false/*ZExt*/, "tmp");
512 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
513 Constant *One = ConstantInt::get(In->getType(), 1);
514 In = Builder->CreateXor(In, One, In->getName()+".not");
517 return ReplaceInstUsesWith(CI, In);
522 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
523 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
524 // zext (X == 1) to i32 --> X iff X has only the low bit set.
525 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
526 // zext (X != 0) to i32 --> X iff X has only the low bit set.
527 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
528 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
529 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
530 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
531 // This only works for EQ and NE
533 // If Op1C some other power of two, convert:
534 uint32_t BitWidth = Op1C->getType()->getBitWidth();
535 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
536 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
537 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
539 APInt KnownZeroMask(~KnownZero);
540 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
541 if (!DoXform) return ICI;
543 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
544 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
545 // (X&4) == 2 --> false
546 // (X&4) != 2 --> true
547 Constant *Res = ConstantInt::get(Type::getInt1Ty(CI.getContext()),
549 Res = ConstantExpr::getZExt(Res, CI.getType());
550 return ReplaceInstUsesWith(CI, Res);
553 uint32_t ShiftAmt = KnownZeroMask.logBase2();
554 Value *In = ICI->getOperand(0);
556 // Perform a logical shr by shiftamt.
557 // Insert the shift to put the result in the low bit.
558 In = Builder->CreateLShr(In, ConstantInt::get(In->getType(),ShiftAmt),
559 In->getName()+".lobit");
562 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
563 Constant *One = ConstantInt::get(In->getType(), 1);
564 In = Builder->CreateXor(In, One, "tmp");
567 if (CI.getType() == In->getType())
568 return ReplaceInstUsesWith(CI, In);
569 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
574 // icmp ne A, B is equal to xor A, B when A and B only really have one bit.
575 // It is also profitable to transform icmp eq into not(xor(A, B)) because that
576 // may lead to additional simplifications.
577 if (ICI->isEquality() && CI.getType() == ICI->getOperand(0)->getType()) {
578 if (const IntegerType *ITy = dyn_cast<IntegerType>(CI.getType())) {
579 uint32_t BitWidth = ITy->getBitWidth();
580 Value *LHS = ICI->getOperand(0);
581 Value *RHS = ICI->getOperand(1);
583 APInt KnownZeroLHS(BitWidth, 0), KnownOneLHS(BitWidth, 0);
584 APInt KnownZeroRHS(BitWidth, 0), KnownOneRHS(BitWidth, 0);
585 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
586 ComputeMaskedBits(LHS, TypeMask, KnownZeroLHS, KnownOneLHS);
587 ComputeMaskedBits(RHS, TypeMask, KnownZeroRHS, KnownOneRHS);
589 if (KnownZeroLHS == KnownZeroRHS && KnownOneLHS == KnownOneRHS) {
590 APInt KnownBits = KnownZeroLHS | KnownOneLHS;
591 APInt UnknownBit = ~KnownBits;
592 if (UnknownBit.countPopulation() == 1) {
593 if (!DoXform) return ICI;
595 Value *Result = Builder->CreateXor(LHS, RHS);
597 // Mask off any bits that are set and won't be shifted away.
598 if (KnownOneLHS.uge(UnknownBit))
599 Result = Builder->CreateAnd(Result,
600 ConstantInt::get(ITy, UnknownBit));
602 // Shift the bit we're testing down to the lsb.
603 Result = Builder->CreateLShr(
604 Result, ConstantInt::get(ITy, UnknownBit.countTrailingZeros()));
606 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
607 Result = Builder->CreateXor(Result, ConstantInt::get(ITy, 1));
608 Result->takeName(ICI);
609 return ReplaceInstUsesWith(CI, Result);
618 /// CanEvaluateZExtd - Determine if the specified value can be computed in the
619 /// specified wider type and produce the same low bits. If not, return false.
621 /// If this function returns true, it can also return a non-zero number of bits
622 /// (in BitsToClear) which indicates that the value it computes is correct for
623 /// the zero extend, but that the additional BitsToClear bits need to be zero'd
624 /// out. For example, to promote something like:
626 /// %B = trunc i64 %A to i32
627 /// %C = lshr i32 %B, 8
628 /// %E = zext i32 %C to i64
630 /// CanEvaluateZExtd for the 'lshr' will return true, and BitsToClear will be
631 /// set to 8 to indicate that the promoted value needs to have bits 24-31
632 /// cleared in addition to bits 32-63. Since an 'and' will be generated to
633 /// clear the top bits anyway, doing this has no extra cost.
635 /// This function works on both vectors and scalars.
636 static bool CanEvaluateZExtd(Value *V, const Type *Ty, unsigned &BitsToClear) {
638 if (isa<Constant>(V))
641 Instruction *I = dyn_cast<Instruction>(V);
642 if (!I) return false;
644 // If the input is a truncate from the destination type, we can trivially
645 // eliminate it, even if it has multiple uses.
646 // FIXME: This is currently disabled until codegen can handle this without
647 // pessimizing code, PR5997.
648 if (0 && isa<TruncInst>(I) && I->getOperand(0)->getType() == Ty)
651 // We can't extend or shrink something that has multiple uses: doing so would
652 // require duplicating the instruction in general, which isn't profitable.
653 if (!I->hasOneUse()) return false;
655 unsigned Opc = I->getOpcode(), Tmp;
657 case Instruction::ZExt: // zext(zext(x)) -> zext(x).
658 case Instruction::SExt: // zext(sext(x)) -> sext(x).
659 case Instruction::Trunc: // zext(trunc(x)) -> trunc(x) or zext(x)
661 case Instruction::And:
662 case Instruction::Or:
663 case Instruction::Xor:
664 case Instruction::Add:
665 case Instruction::Sub:
666 case Instruction::Mul:
667 case Instruction::Shl:
668 if (!CanEvaluateZExtd(I->getOperand(0), Ty, BitsToClear) ||
669 !CanEvaluateZExtd(I->getOperand(1), Ty, Tmp))
671 // These can all be promoted if neither operand has 'bits to clear'.
672 if (BitsToClear == 0 && Tmp == 0)
675 // If the operation is an AND/OR/XOR and the bits to clear are zero in the
676 // other side, BitsToClear is ok.
678 (Opc == Instruction::And || Opc == Instruction::Or ||
679 Opc == Instruction::Xor)) {
680 // We use MaskedValueIsZero here for generality, but the case we care
681 // about the most is constant RHS.
682 unsigned VSize = V->getType()->getScalarSizeInBits();
683 if (MaskedValueIsZero(I->getOperand(1),
684 APInt::getHighBitsSet(VSize, BitsToClear)))
688 // Otherwise, we don't know how to analyze this BitsToClear case yet.
691 case Instruction::LShr:
692 // We can promote lshr(x, cst) if we can promote x. This requires the
693 // ultimate 'and' to clear out the high zero bits we're clearing out though.
694 if (ConstantInt *Amt = dyn_cast<ConstantInt>(I->getOperand(1))) {
695 if (!CanEvaluateZExtd(I->getOperand(0), Ty, BitsToClear))
697 BitsToClear += Amt->getZExtValue();
698 if (BitsToClear > V->getType()->getScalarSizeInBits())
699 BitsToClear = V->getType()->getScalarSizeInBits();
702 // Cannot promote variable LSHR.
704 case Instruction::Select:
705 if (!CanEvaluateZExtd(I->getOperand(1), Ty, Tmp) ||
706 !CanEvaluateZExtd(I->getOperand(2), Ty, BitsToClear) ||
707 // TODO: If important, we could handle the case when the BitsToClear are
708 // known zero in the disagreeing side.
713 case Instruction::PHI: {
714 // We can change a phi if we can change all operands. Note that we never
715 // get into trouble with cyclic PHIs here because we only consider
716 // instructions with a single use.
717 PHINode *PN = cast<PHINode>(I);
718 if (!CanEvaluateZExtd(PN->getIncomingValue(0), Ty, BitsToClear))
720 for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i)
721 if (!CanEvaluateZExtd(PN->getIncomingValue(i), Ty, Tmp) ||
722 // TODO: If important, we could handle the case when the BitsToClear
723 // are known zero in the disagreeing input.
729 // TODO: Can handle more cases here.
734 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
735 // If this zero extend is only used by a truncate, let the truncate by
736 // eliminated before we try to optimize this zext.
737 if (CI.hasOneUse() && isa<TruncInst>(CI.use_back()))
740 // If one of the common conversion will work, do it.
741 if (Instruction *Result = commonCastTransforms(CI))
744 // See if we can simplify any instructions used by the input whose sole
745 // purpose is to compute bits we don't care about.
746 if (SimplifyDemandedInstructionBits(CI))
749 Value *Src = CI.getOperand(0);
750 const Type *SrcTy = Src->getType(), *DestTy = CI.getType();
752 // Attempt to extend the entire input expression tree to the destination
753 // type. Only do this if the dest type is a simple type, don't convert the
754 // expression tree to something weird like i93 unless the source is also
756 unsigned BitsToClear;
757 if ((DestTy->isVectorTy() || ShouldChangeType(SrcTy, DestTy)) &&
758 CanEvaluateZExtd(Src, DestTy, BitsToClear)) {
759 assert(BitsToClear < SrcTy->getScalarSizeInBits() &&
760 "Unreasonable BitsToClear");
762 // Okay, we can transform this! Insert the new expression now.
763 DEBUG(dbgs() << "ICE: EvaluateInDifferentType converting expression type"
764 " to avoid zero extend: " << CI);
765 Value *Res = EvaluateInDifferentType(Src, DestTy, false);
766 assert(Res->getType() == DestTy);
768 uint32_t SrcBitsKept = SrcTy->getScalarSizeInBits()-BitsToClear;
769 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
771 // If the high bits are already filled with zeros, just replace this
772 // cast with the result.
773 if (MaskedValueIsZero(Res, APInt::getHighBitsSet(DestBitSize,
774 DestBitSize-SrcBitsKept)))
775 return ReplaceInstUsesWith(CI, Res);
777 // We need to emit an AND to clear the high bits.
778 Constant *C = ConstantInt::get(Res->getType(),
779 APInt::getLowBitsSet(DestBitSize, SrcBitsKept));
780 return BinaryOperator::CreateAnd(Res, C);
783 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
784 // types and if the sizes are just right we can convert this into a logical
785 // 'and' which will be much cheaper than the pair of casts.
786 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
787 // TODO: Subsume this into EvaluateInDifferentType.
789 // Get the sizes of the types involved. We know that the intermediate type
790 // will be smaller than A or C, but don't know the relation between A and C.
791 Value *A = CSrc->getOperand(0);
792 unsigned SrcSize = A->getType()->getScalarSizeInBits();
793 unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
794 unsigned DstSize = CI.getType()->getScalarSizeInBits();
795 // If we're actually extending zero bits, then if
796 // SrcSize < DstSize: zext(a & mask)
797 // SrcSize == DstSize: a & mask
798 // SrcSize > DstSize: trunc(a) & mask
799 if (SrcSize < DstSize) {
800 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
801 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
802 Value *And = Builder->CreateAnd(A, AndConst, CSrc->getName()+".mask");
803 return new ZExtInst(And, CI.getType());
806 if (SrcSize == DstSize) {
807 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
808 return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
811 if (SrcSize > DstSize) {
812 Value *Trunc = Builder->CreateTrunc(A, CI.getType(), "tmp");
813 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
814 return BinaryOperator::CreateAnd(Trunc,
815 ConstantInt::get(Trunc->getType(),
820 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
821 return transformZExtICmp(ICI, CI);
823 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
824 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
825 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
826 // of the (zext icmp) will be transformed.
827 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
828 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
829 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
830 (transformZExtICmp(LHS, CI, false) ||
831 transformZExtICmp(RHS, CI, false))) {
832 Value *LCast = Builder->CreateZExt(LHS, CI.getType(), LHS->getName());
833 Value *RCast = Builder->CreateZExt(RHS, CI.getType(), RHS->getName());
834 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
838 // zext(trunc(t) & C) -> (t & zext(C)).
839 if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
840 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
841 if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
842 Value *TI0 = TI->getOperand(0);
843 if (TI0->getType() == CI.getType())
845 BinaryOperator::CreateAnd(TI0,
846 ConstantExpr::getZExt(C, CI.getType()));
849 // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
850 if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
851 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
852 if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
853 if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
854 And->getOperand(1) == C)
855 if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
856 Value *TI0 = TI->getOperand(0);
857 if (TI0->getType() == CI.getType()) {
858 Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
859 Value *NewAnd = Builder->CreateAnd(TI0, ZC, "tmp");
860 return BinaryOperator::CreateXor(NewAnd, ZC);
864 // zext (xor i1 X, true) to i32 --> xor (zext i1 X to i32), 1
866 if (SrcI && SrcI->hasOneUse() && SrcI->getType()->isIntegerTy(1) &&
867 match(SrcI, m_Not(m_Value(X))) &&
868 (!X->hasOneUse() || !isa<CmpInst>(X))) {
869 Value *New = Builder->CreateZExt(X, CI.getType());
870 return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
876 /// CanEvaluateSExtd - Return true if we can take the specified value
877 /// and return it as type Ty without inserting any new casts and without
878 /// changing the value of the common low bits. This is used by code that tries
879 /// to promote integer operations to a wider types will allow us to eliminate
882 /// This function works on both vectors and scalars.
884 static bool CanEvaluateSExtd(Value *V, const Type *Ty) {
885 assert(V->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits() &&
886 "Can't sign extend type to a smaller type");
887 // If this is a constant, it can be trivially promoted.
888 if (isa<Constant>(V))
891 Instruction *I = dyn_cast<Instruction>(V);
892 if (!I) return false;
894 // If this is a truncate from the dest type, we can trivially eliminate it,
895 // even if it has multiple uses.
896 // FIXME: This is currently disabled until codegen can handle this without
897 // pessimizing code, PR5997.
898 if (0 && isa<TruncInst>(I) && I->getOperand(0)->getType() == Ty)
901 // We can't extend or shrink something that has multiple uses: doing so would
902 // require duplicating the instruction in general, which isn't profitable.
903 if (!I->hasOneUse()) return false;
905 switch (I->getOpcode()) {
906 case Instruction::SExt: // sext(sext(x)) -> sext(x)
907 case Instruction::ZExt: // sext(zext(x)) -> zext(x)
908 case Instruction::Trunc: // sext(trunc(x)) -> trunc(x) or sext(x)
910 case Instruction::And:
911 case Instruction::Or:
912 case Instruction::Xor:
913 case Instruction::Add:
914 case Instruction::Sub:
915 case Instruction::Mul:
916 // These operators can all arbitrarily be extended if their inputs can.
917 return CanEvaluateSExtd(I->getOperand(0), Ty) &&
918 CanEvaluateSExtd(I->getOperand(1), Ty);
920 //case Instruction::Shl: TODO
921 //case Instruction::LShr: TODO
923 case Instruction::Select:
924 return CanEvaluateSExtd(I->getOperand(1), Ty) &&
925 CanEvaluateSExtd(I->getOperand(2), Ty);
927 case Instruction::PHI: {
928 // We can change a phi if we can change all operands. Note that we never
929 // get into trouble with cyclic PHIs here because we only consider
930 // instructions with a single use.
931 PHINode *PN = cast<PHINode>(I);
932 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
933 if (!CanEvaluateSExtd(PN->getIncomingValue(i), Ty)) return false;
937 // TODO: Can handle more cases here.
944 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
945 // If this sign extend is only used by a truncate, let the truncate by
946 // eliminated before we try to optimize this zext.
947 if (CI.hasOneUse() && isa<TruncInst>(CI.use_back()))
950 if (Instruction *I = commonCastTransforms(CI))
953 // See if we can simplify any instructions used by the input whose sole
954 // purpose is to compute bits we don't care about.
955 if (SimplifyDemandedInstructionBits(CI))
958 Value *Src = CI.getOperand(0);
959 const Type *SrcTy = Src->getType(), *DestTy = CI.getType();
961 // Attempt to extend the entire input expression tree to the destination
962 // type. Only do this if the dest type is a simple type, don't convert the
963 // expression tree to something weird like i93 unless the source is also
965 if ((DestTy->isVectorTy() || ShouldChangeType(SrcTy, DestTy)) &&
966 CanEvaluateSExtd(Src, DestTy)) {
967 // Okay, we can transform this! Insert the new expression now.
968 DEBUG(dbgs() << "ICE: EvaluateInDifferentType converting expression type"
969 " to avoid sign extend: " << CI);
970 Value *Res = EvaluateInDifferentType(Src, DestTy, true);
971 assert(Res->getType() == DestTy);
973 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
974 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
976 // If the high bits are already filled with sign bit, just replace this
977 // cast with the result.
978 if (ComputeNumSignBits(Res) > DestBitSize - SrcBitSize)
979 return ReplaceInstUsesWith(CI, Res);
981 // We need to emit a shl + ashr to do the sign extend.
982 Value *ShAmt = ConstantInt::get(DestTy, DestBitSize-SrcBitSize);
983 return BinaryOperator::CreateAShr(Builder->CreateShl(Res, ShAmt, "sext"),
987 // If this input is a trunc from our destination, then turn sext(trunc(x))
989 if (TruncInst *TI = dyn_cast<TruncInst>(Src))
990 if (TI->hasOneUse() && TI->getOperand(0)->getType() == DestTy) {
991 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
992 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
994 // We need to emit a shl + ashr to do the sign extend.
995 Value *ShAmt = ConstantInt::get(DestTy, DestBitSize-SrcBitSize);
996 Value *Res = Builder->CreateShl(TI->getOperand(0), ShAmt, "sext");
997 return BinaryOperator::CreateAShr(Res, ShAmt);
1001 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed
1002 // (x >s -1) ? -1 : 0 -> ashr x, 31 -> all ones if not signed
1004 ICmpInst::Predicate Pred; Value *CmpLHS; ConstantInt *CmpRHS;
1005 if (match(Src, m_ICmp(Pred, m_Value(CmpLHS), m_ConstantInt(CmpRHS)))) {
1006 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
1007 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
1008 if ((Pred == ICmpInst::ICMP_SLT && CmpRHS->isZero()) ||
1009 (Pred == ICmpInst::ICMP_SGT && CmpRHS->isAllOnesValue())) {
1010 Value *Sh = ConstantInt::get(CmpLHS->getType(),
1011 CmpLHS->getType()->getScalarSizeInBits()-1);
1012 Value *In = Builder->CreateAShr(CmpLHS, Sh, CmpLHS->getName()+".lobit");
1013 if (In->getType() != CI.getType())
1014 In = Builder->CreateIntCast(In, CI.getType(), true/*SExt*/, "tmp");
1016 if (Pred == ICmpInst::ICMP_SGT)
1017 In = Builder->CreateNot(In, In->getName()+".not");
1018 return ReplaceInstUsesWith(CI, In);
1024 // If the input is a shl/ashr pair of a same constant, then this is a sign
1025 // extension from a smaller value. If we could trust arbitrary bitwidth
1026 // integers, we could turn this into a truncate to the smaller bit and then
1027 // use a sext for the whole extension. Since we don't, look deeper and check
1028 // for a truncate. If the source and dest are the same type, eliminate the
1029 // trunc and extend and just do shifts. For example, turn:
1030 // %a = trunc i32 %i to i8
1031 // %b = shl i8 %a, 6
1032 // %c = ashr i8 %b, 6
1033 // %d = sext i8 %c to i32
1035 // %a = shl i32 %i, 30
1036 // %d = ashr i32 %a, 30
1038 // TODO: Eventually this could be subsumed by EvaluateInDifferentType.
1039 ConstantInt *BA = 0, *CA = 0;
1040 if (match(Src, m_AShr(m_Shl(m_Trunc(m_Value(A)), m_ConstantInt(BA)),
1041 m_ConstantInt(CA))) &&
1042 BA == CA && A->getType() == CI.getType()) {
1043 unsigned MidSize = Src->getType()->getScalarSizeInBits();
1044 unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
1045 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
1046 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
1047 A = Builder->CreateShl(A, ShAmtV, CI.getName());
1048 return BinaryOperator::CreateAShr(A, ShAmtV);
1055 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
1056 /// in the specified FP type without changing its value.
1057 static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
1059 APFloat F = CFP->getValueAPF();
1060 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
1062 return ConstantFP::get(CFP->getContext(), F);
1066 /// LookThroughFPExtensions - If this is an fp extension instruction, look
1067 /// through it until we get the source value.
1068 static Value *LookThroughFPExtensions(Value *V) {
1069 if (Instruction *I = dyn_cast<Instruction>(V))
1070 if (I->getOpcode() == Instruction::FPExt)
1071 return LookThroughFPExtensions(I->getOperand(0));
1073 // If this value is a constant, return the constant in the smallest FP type
1074 // that can accurately represent it. This allows us to turn
1075 // (float)((double)X+2.0) into x+2.0f.
1076 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
1077 if (CFP->getType() == Type::getPPC_FP128Ty(V->getContext()))
1078 return V; // No constant folding of this.
1079 // See if the value can be truncated to float and then reextended.
1080 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
1082 if (CFP->getType()->isDoubleTy())
1083 return V; // Won't shrink.
1084 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
1086 // Don't try to shrink to various long double types.
1092 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
1093 if (Instruction *I = commonCastTransforms(CI))
1096 // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
1097 // smaller than the destination type, we can eliminate the truncate by doing
1098 // the add as the smaller type. This applies to fadd/fsub/fmul/fdiv as well
1099 // as many builtins (sqrt, etc).
1100 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
1101 if (OpI && OpI->hasOneUse()) {
1102 switch (OpI->getOpcode()) {
1104 case Instruction::FAdd:
1105 case Instruction::FSub:
1106 case Instruction::FMul:
1107 case Instruction::FDiv:
1108 case Instruction::FRem:
1109 const Type *SrcTy = OpI->getType();
1110 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
1111 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
1112 if (LHSTrunc->getType() != SrcTy &&
1113 RHSTrunc->getType() != SrcTy) {
1114 unsigned DstSize = CI.getType()->getScalarSizeInBits();
1115 // If the source types were both smaller than the destination type of
1116 // the cast, do this xform.
1117 if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
1118 RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
1119 LHSTrunc = Builder->CreateFPExt(LHSTrunc, CI.getType());
1120 RHSTrunc = Builder->CreateFPExt(RHSTrunc, CI.getType());
1121 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
1128 // Fold (fptrunc (sqrt (fpext x))) -> (sqrtf x)
1129 // NOTE: This should be disabled by -fno-builtin-sqrt if we ever support it.
1130 CallInst *Call = dyn_cast<CallInst>(CI.getOperand(0));
1131 if (Call && Call->getCalledFunction() &&
1132 Call->getCalledFunction()->getName() == "sqrt" &&
1133 Call->getNumArgOperands() == 1) {
1134 CastInst *Arg = dyn_cast<CastInst>(Call->getArgOperand(0));
1135 if (Arg && Arg->getOpcode() == Instruction::FPExt &&
1136 CI.getType()->isFloatTy() &&
1137 Call->getType()->isDoubleTy() &&
1138 Arg->getType()->isDoubleTy() &&
1139 Arg->getOperand(0)->getType()->isFloatTy()) {
1140 Function *Callee = Call->getCalledFunction();
1141 Module *M = CI.getParent()->getParent()->getParent();
1142 Constant* SqrtfFunc = M->getOrInsertFunction("sqrtf",
1143 Callee->getAttributes(),
1144 Builder->getFloatTy(),
1145 Builder->getFloatTy(),
1147 CallInst *ret = CallInst::Create(SqrtfFunc, Arg->getOperand(0),
1149 ret->setAttributes(Callee->getAttributes());
1157 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
1158 return commonCastTransforms(CI);
1161 Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
1162 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
1164 return commonCastTransforms(FI);
1166 // fptoui(uitofp(X)) --> X
1167 // fptoui(sitofp(X)) --> X
1168 // This is safe if the intermediate type has enough bits in its mantissa to
1169 // accurately represent all values of X. For example, do not do this with
1170 // i64->float->i64. This is also safe for sitofp case, because any negative
1171 // 'X' value would cause an undefined result for the fptoui.
1172 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
1173 OpI->getOperand(0)->getType() == FI.getType() &&
1174 (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
1175 OpI->getType()->getFPMantissaWidth())
1176 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
1178 return commonCastTransforms(FI);
1181 Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
1182 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
1184 return commonCastTransforms(FI);
1186 // fptosi(sitofp(X)) --> X
1187 // fptosi(uitofp(X)) --> X
1188 // This is safe if the intermediate type has enough bits in its mantissa to
1189 // accurately represent all values of X. For example, do not do this with
1190 // i64->float->i64. This is also safe for sitofp case, because any negative
1191 // 'X' value would cause an undefined result for the fptoui.
1192 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
1193 OpI->getOperand(0)->getType() == FI.getType() &&
1194 (int)FI.getType()->getScalarSizeInBits() <=
1195 OpI->getType()->getFPMantissaWidth())
1196 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
1198 return commonCastTransforms(FI);
1201 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
1202 return commonCastTransforms(CI);
1205 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
1206 return commonCastTransforms(CI);
1209 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
1210 // If the source integer type is not the intptr_t type for this target, do a
1211 // trunc or zext to the intptr_t type, then inttoptr of it. This allows the
1212 // cast to be exposed to other transforms.
1214 if (CI.getOperand(0)->getType()->getScalarSizeInBits() >
1215 TD->getPointerSizeInBits()) {
1216 Value *P = Builder->CreateTrunc(CI.getOperand(0),
1217 TD->getIntPtrType(CI.getContext()), "tmp");
1218 return new IntToPtrInst(P, CI.getType());
1220 if (CI.getOperand(0)->getType()->getScalarSizeInBits() <
1221 TD->getPointerSizeInBits()) {
1222 Value *P = Builder->CreateZExt(CI.getOperand(0),
1223 TD->getIntPtrType(CI.getContext()), "tmp");
1224 return new IntToPtrInst(P, CI.getType());
1228 if (Instruction *I = commonCastTransforms(CI))
1234 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
1235 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
1236 Value *Src = CI.getOperand(0);
1238 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
1239 // If casting the result of a getelementptr instruction with no offset, turn
1240 // this into a cast of the original pointer!
1241 if (GEP->hasAllZeroIndices()) {
1242 // Changing the cast operand is usually not a good idea but it is safe
1243 // here because the pointer operand is being replaced with another
1244 // pointer operand so the opcode doesn't need to change.
1246 CI.setOperand(0, GEP->getOperand(0));
1250 // If the GEP has a single use, and the base pointer is a bitcast, and the
1251 // GEP computes a constant offset, see if we can convert these three
1252 // instructions into fewer. This typically happens with unions and other
1253 // non-type-safe code.
1254 if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0)) &&
1255 GEP->hasAllConstantIndices()) {
1256 // We are guaranteed to get a constant from EmitGEPOffset.
1257 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP));
1258 int64_t Offset = OffsetV->getSExtValue();
1260 // Get the base pointer input of the bitcast, and the type it points to.
1261 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
1262 const Type *GEPIdxTy =
1263 cast<PointerType>(OrigBase->getType())->getElementType();
1264 SmallVector<Value*, 8> NewIndices;
1265 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices)) {
1266 // If we were able to index down into an element, create the GEP
1267 // and bitcast the result. This eliminates one bitcast, potentially
1269 Value *NGEP = cast<GEPOperator>(GEP)->isInBounds() ?
1270 Builder->CreateInBoundsGEP(OrigBase,
1271 NewIndices.begin(), NewIndices.end()) :
1272 Builder->CreateGEP(OrigBase, NewIndices.begin(), NewIndices.end());
1273 NGEP->takeName(GEP);
1275 if (isa<BitCastInst>(CI))
1276 return new BitCastInst(NGEP, CI.getType());
1277 assert(isa<PtrToIntInst>(CI));
1278 return new PtrToIntInst(NGEP, CI.getType());
1283 return commonCastTransforms(CI);
1286 Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
1287 // If the destination integer type is not the intptr_t type for this target,
1288 // do a ptrtoint to intptr_t then do a trunc or zext. This allows the cast
1289 // to be exposed to other transforms.
1291 if (CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
1292 Value *P = Builder->CreatePtrToInt(CI.getOperand(0),
1293 TD->getIntPtrType(CI.getContext()),
1295 return new TruncInst(P, CI.getType());
1297 if (CI.getType()->getScalarSizeInBits() > TD->getPointerSizeInBits()) {
1298 Value *P = Builder->CreatePtrToInt(CI.getOperand(0),
1299 TD->getIntPtrType(CI.getContext()),
1301 return new ZExtInst(P, CI.getType());
1305 return commonPointerCastTransforms(CI);
1308 /// OptimizeVectorResize - This input value (which is known to have vector type)
1309 /// is being zero extended or truncated to the specified vector type. Try to
1310 /// replace it with a shuffle (and vector/vector bitcast) if possible.
1312 /// The source and destination vector types may have different element types.
1313 static Instruction *OptimizeVectorResize(Value *InVal, const VectorType *DestTy,
1315 // We can only do this optimization if the output is a multiple of the input
1316 // element size, or the input is a multiple of the output element size.
1317 // Convert the input type to have the same element type as the output.
1318 const VectorType *SrcTy = cast<VectorType>(InVal->getType());
1320 if (SrcTy->getElementType() != DestTy->getElementType()) {
1321 // The input types don't need to be identical, but for now they must be the
1322 // same size. There is no specific reason we couldn't handle things like
1323 // <4 x i16> -> <4 x i32> by bitcasting to <2 x i32> but haven't gotten
1325 if (SrcTy->getElementType()->getPrimitiveSizeInBits() !=
1326 DestTy->getElementType()->getPrimitiveSizeInBits())
1329 SrcTy = VectorType::get(DestTy->getElementType(), SrcTy->getNumElements());
1330 InVal = IC.Builder->CreateBitCast(InVal, SrcTy);
1333 // Now that the element types match, get the shuffle mask and RHS of the
1334 // shuffle to use, which depends on whether we're increasing or decreasing the
1335 // size of the input.
1336 SmallVector<Constant*, 16> ShuffleMask;
1338 const IntegerType *Int32Ty = Type::getInt32Ty(SrcTy->getContext());
1340 if (SrcTy->getNumElements() > DestTy->getNumElements()) {
1341 // If we're shrinking the number of elements, just shuffle in the low
1342 // elements from the input and use undef as the second shuffle input.
1343 V2 = UndefValue::get(SrcTy);
1344 for (unsigned i = 0, e = DestTy->getNumElements(); i != e; ++i)
1345 ShuffleMask.push_back(ConstantInt::get(Int32Ty, i));
1348 // If we're increasing the number of elements, shuffle in all of the
1349 // elements from InVal and fill the rest of the result elements with zeros
1350 // from a constant zero.
1351 V2 = Constant::getNullValue(SrcTy);
1352 unsigned SrcElts = SrcTy->getNumElements();
1353 for (unsigned i = 0, e = SrcElts; i != e; ++i)
1354 ShuffleMask.push_back(ConstantInt::get(Int32Ty, i));
1356 // The excess elements reference the first element of the zero input.
1357 ShuffleMask.append(DestTy->getNumElements()-SrcElts,
1358 ConstantInt::get(Int32Ty, SrcElts));
1361 Constant *Mask = ConstantVector::get(ShuffleMask.data(), ShuffleMask.size());
1362 return new ShuffleVectorInst(InVal, V2, Mask);
1365 /// OptimizeIntToFloatBitCast - See if we can optimize an integer->float/double
1366 /// bitcast. The various long double bitcasts can't get in here.
1367 static Instruction *OptimizeIntToFloatBitCast(BitCastInst &CI,InstCombiner &IC){
1368 Value *Src = CI.getOperand(0);
1369 const Type *DestTy = CI.getType();
1371 // If this is a bitcast from int to float, check to see if the int is an
1372 // extraction from a vector.
1373 Value *VecInput = 0;
1374 // bitcast(trunc(bitcast(somevector)))
1375 if (match(Src, m_Trunc(m_BitCast(m_Value(VecInput)))) &&
1376 isa<VectorType>(VecInput->getType())) {
1377 const VectorType *VecTy = cast<VectorType>(VecInput->getType());
1378 unsigned DestWidth = DestTy->getPrimitiveSizeInBits();
1380 if (VecTy->getPrimitiveSizeInBits() % DestWidth == 0) {
1381 // If the element type of the vector doesn't match the result type,
1382 // bitcast it to be a vector type we can extract from.
1383 if (VecTy->getElementType() != DestTy) {
1384 VecTy = VectorType::get(DestTy,
1385 VecTy->getPrimitiveSizeInBits() / DestWidth);
1386 VecInput = IC.Builder->CreateBitCast(VecInput, VecTy);
1389 return ExtractElementInst::Create(VecInput, IC.Builder->getInt32(0));
1393 // bitcast(trunc(lshr(bitcast(somevector), cst))
1394 ConstantInt *ShAmt = 0;
1395 if (match(Src, m_Trunc(m_LShr(m_BitCast(m_Value(VecInput)),
1396 m_ConstantInt(ShAmt)))) &&
1397 isa<VectorType>(VecInput->getType())) {
1398 const VectorType *VecTy = cast<VectorType>(VecInput->getType());
1399 unsigned DestWidth = DestTy->getPrimitiveSizeInBits();
1400 if (VecTy->getPrimitiveSizeInBits() % DestWidth == 0 &&
1401 ShAmt->getZExtValue() % DestWidth == 0) {
1402 // If the element type of the vector doesn't match the result type,
1403 // bitcast it to be a vector type we can extract from.
1404 if (VecTy->getElementType() != DestTy) {
1405 VecTy = VectorType::get(DestTy,
1406 VecTy->getPrimitiveSizeInBits() / DestWidth);
1407 VecInput = IC.Builder->CreateBitCast(VecInput, VecTy);
1410 unsigned Elt = ShAmt->getZExtValue() / DestWidth;
1411 return ExtractElementInst::Create(VecInput, IC.Builder->getInt32(Elt));
1417 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
1418 // If the operands are integer typed then apply the integer transforms,
1419 // otherwise just apply the common ones.
1420 Value *Src = CI.getOperand(0);
1421 const Type *SrcTy = Src->getType();
1422 const Type *DestTy = CI.getType();
1424 // Get rid of casts from one type to the same type. These are useless and can
1425 // be replaced by the operand.
1426 if (DestTy == Src->getType())
1427 return ReplaceInstUsesWith(CI, Src);
1429 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
1430 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
1431 const Type *DstElTy = DstPTy->getElementType();
1432 const Type *SrcElTy = SrcPTy->getElementType();
1434 // If the address spaces don't match, don't eliminate the bitcast, which is
1435 // required for changing types.
1436 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
1439 // If we are casting a alloca to a pointer to a type of the same
1440 // size, rewrite the allocation instruction to allocate the "right" type.
1441 // There is no need to modify malloc calls because it is their bitcast that
1442 // needs to be cleaned up.
1443 if (AllocaInst *AI = dyn_cast<AllocaInst>(Src))
1444 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
1447 // If the source and destination are pointers, and this cast is equivalent
1448 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
1449 // This can enhance SROA and other transforms that want type-safe pointers.
1450 Constant *ZeroUInt =
1451 Constant::getNullValue(Type::getInt32Ty(CI.getContext()));
1452 unsigned NumZeros = 0;
1453 while (SrcElTy != DstElTy &&
1454 isa<CompositeType>(SrcElTy) && !SrcElTy->isPointerTy() &&
1455 SrcElTy->getNumContainedTypes() /* not "{}" */) {
1456 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
1460 // If we found a path from the src to dest, create the getelementptr now.
1461 if (SrcElTy == DstElTy) {
1462 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
1463 return GetElementPtrInst::CreateInBounds(Src, Idxs.begin(), Idxs.end(),"",
1464 ((Instruction*)NULL));
1468 // Try to optimize int -> float bitcasts.
1469 if ((DestTy->isFloatTy() || DestTy->isDoubleTy()) && isa<IntegerType>(SrcTy))
1470 if (Instruction *I = OptimizeIntToFloatBitCast(CI, *this))
1473 if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
1474 if (DestVTy->getNumElements() == 1 && !SrcTy->isVectorTy()) {
1475 Value *Elem = Builder->CreateBitCast(Src, DestVTy->getElementType());
1476 return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
1477 Constant::getNullValue(Type::getInt32Ty(CI.getContext())));
1478 // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
1481 // If this is a cast from an integer to vector, check to see if the input
1482 // is a trunc or zext of a bitcast from vector. If so, we can replace all
1483 // the casts with a shuffle and (potentially) a bitcast.
1484 if (isa<IntegerType>(SrcTy) && (isa<TruncInst>(Src) || isa<ZExtInst>(Src))){
1485 CastInst *SrcCast = cast<CastInst>(Src);
1486 if (BitCastInst *BCIn = dyn_cast<BitCastInst>(SrcCast->getOperand(0)))
1487 if (isa<VectorType>(BCIn->getOperand(0)->getType()))
1488 if (Instruction *I = OptimizeVectorResize(BCIn->getOperand(0),
1489 cast<VectorType>(DestTy), *this))
1494 if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
1495 if (SrcVTy->getNumElements() == 1 && !DestTy->isVectorTy()) {
1497 Builder->CreateExtractElement(Src,
1498 Constant::getNullValue(Type::getInt32Ty(CI.getContext())));
1499 return CastInst::Create(Instruction::BitCast, Elem, DestTy);
1503 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
1504 // Okay, we have (bitcast (shuffle ..)). Check to see if this is
1505 // a bitcast to a vector with the same # elts.
1506 if (SVI->hasOneUse() && DestTy->isVectorTy() &&
1507 cast<VectorType>(DestTy)->getNumElements() ==
1508 SVI->getType()->getNumElements() &&
1509 SVI->getType()->getNumElements() ==
1510 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
1512 // If either of the operands is a cast from CI.getType(), then
1513 // evaluating the shuffle in the casted destination's type will allow
1514 // us to eliminate at least one cast.
1515 if (((Tmp = dyn_cast<BitCastInst>(SVI->getOperand(0))) &&
1516 Tmp->getOperand(0)->getType() == DestTy) ||
1517 ((Tmp = dyn_cast<BitCastInst>(SVI->getOperand(1))) &&
1518 Tmp->getOperand(0)->getType() == DestTy)) {
1519 Value *LHS = Builder->CreateBitCast(SVI->getOperand(0), DestTy);
1520 Value *RHS = Builder->CreateBitCast(SVI->getOperand(1), DestTy);
1521 // Return a new shuffle vector. Use the same element ID's, as we
1522 // know the vector types match #elts.
1523 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
1528 if (SrcTy->isPointerTy())
1529 return commonPointerCastTransforms(CI);
1530 return commonCastTransforms(CI);