LLVM API Documentation

InstCombineCasts.cpp
Go to the documentation of this file.
00001 //===- InstCombineCasts.cpp -----------------------------------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements the visit functions for cast operations.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "InstCombine.h"
00015 #include "llvm/Analysis/ConstantFolding.h"
00016 #include "llvm/IR/DataLayout.h"
00017 #include "llvm/IR/PatternMatch.h"
00018 #include "llvm/Target/TargetLibraryInfo.h"
00019 using namespace llvm;
00020 using namespace PatternMatch;
00021 
00022 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
00023 /// expression.  If so, decompose it, returning some value X, such that Val is
00024 /// X*Scale+Offset.
00025 ///
00026 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
00027                                         uint64_t &Offset) {
00028   if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
00029     Offset = CI->getZExtValue();
00030     Scale  = 0;
00031     return ConstantInt::get(Val->getType(), 0);
00032   }
00033 
00034   if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
00035     // Cannot look past anything that might overflow.
00036     OverflowingBinaryOperator *OBI = dyn_cast<OverflowingBinaryOperator>(Val);
00037     if (OBI && !OBI->hasNoUnsignedWrap() && !OBI->hasNoSignedWrap()) {
00038       Scale = 1;
00039       Offset = 0;
00040       return Val;
00041     }
00042 
00043     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
00044       if (I->getOpcode() == Instruction::Shl) {
00045         // This is a value scaled by '1 << the shift amt'.
00046         Scale = UINT64_C(1) << RHS->getZExtValue();
00047         Offset = 0;
00048         return I->getOperand(0);
00049       }
00050 
00051       if (I->getOpcode() == Instruction::Mul) {
00052         // This value is scaled by 'RHS'.
00053         Scale = RHS->getZExtValue();
00054         Offset = 0;
00055         return I->getOperand(0);
00056       }
00057 
00058       if (I->getOpcode() == Instruction::Add) {
00059         // We have X+C.  Check to see if we really have (X*C2)+C1,
00060         // where C1 is divisible by C2.
00061         unsigned SubScale;
00062         Value *SubVal =
00063           DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
00064         Offset += RHS->getZExtValue();
00065         Scale = SubScale;
00066         return SubVal;
00067       }
00068     }
00069   }
00070 
00071   // Otherwise, we can't look past this.
00072   Scale = 1;
00073   Offset = 0;
00074   return Val;
00075 }
00076 
00077 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
00078 /// try to eliminate the cast by moving the type information into the alloc.
00079 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
00080                                                    AllocaInst &AI) {
00081   // This requires DataLayout to get the alloca alignment and size information.
00082   if (!DL) return 0;
00083 
00084   PointerType *PTy = cast<PointerType>(CI.getType());
00085 
00086   BuilderTy AllocaBuilder(*Builder);
00087   AllocaBuilder.SetInsertPoint(AI.getParent(), &AI);
00088 
00089   // Get the type really allocated and the type casted to.
00090   Type *AllocElTy = AI.getAllocatedType();
00091   Type *CastElTy = PTy->getElementType();
00092   if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
00093 
00094   unsigned AllocElTyAlign = DL->getABITypeAlignment(AllocElTy);
00095   unsigned CastElTyAlign = DL->getABITypeAlignment(CastElTy);
00096   if (CastElTyAlign < AllocElTyAlign) return 0;
00097 
00098   // If the allocation has multiple uses, only promote it if we are strictly
00099   // increasing the alignment of the resultant allocation.  If we keep it the
00100   // same, we open the door to infinite loops of various kinds.
00101   if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
00102 
00103   uint64_t AllocElTySize = DL->getTypeAllocSize(AllocElTy);
00104   uint64_t CastElTySize = DL->getTypeAllocSize(CastElTy);
00105   if (CastElTySize == 0 || AllocElTySize == 0) return 0;
00106 
00107   // If the allocation has multiple uses, only promote it if we're not
00108   // shrinking the amount of memory being allocated.
00109   uint64_t AllocElTyStoreSize = DL->getTypeStoreSize(AllocElTy);
00110   uint64_t CastElTyStoreSize = DL->getTypeStoreSize(CastElTy);
00111   if (!AI.hasOneUse() && CastElTyStoreSize < AllocElTyStoreSize) return 0;
00112 
00113   // See if we can satisfy the modulus by pulling a scale out of the array
00114   // size argument.
00115   unsigned ArraySizeScale;
00116   uint64_t ArrayOffset;
00117   Value *NumElements = // See if the array size is a decomposable linear expr.
00118     DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
00119 
00120   // If we can now satisfy the modulus, by using a non-1 scale, we really can
00121   // do the xform.
00122   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
00123       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return 0;
00124 
00125   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
00126   Value *Amt = 0;
00127   if (Scale == 1) {
00128     Amt = NumElements;
00129   } else {
00130     Amt = ConstantInt::get(AI.getArraySize()->getType(), Scale);
00131     // Insert before the alloca, not before the cast.
00132     Amt = AllocaBuilder.CreateMul(Amt, NumElements);
00133   }
00134 
00135   if (uint64_t Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
00136     Value *Off = ConstantInt::get(AI.getArraySize()->getType(),
00137                                   Offset, true);
00138     Amt = AllocaBuilder.CreateAdd(Amt, Off);
00139   }
00140 
00141   AllocaInst *New = AllocaBuilder.CreateAlloca(CastElTy, Amt);
00142   New->setAlignment(AI.getAlignment());
00143   New->takeName(&AI);
00144 
00145   // If the allocation has multiple real uses, insert a cast and change all
00146   // things that used it to use the new cast.  This will also hack on CI, but it
00147   // will die soon.
00148   if (!AI.hasOneUse()) {
00149     // New is the allocation instruction, pointer typed. AI is the original
00150     // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
00151     Value *NewCast = AllocaBuilder.CreateBitCast(New, AI.getType(), "tmpcast");
00152     ReplaceInstUsesWith(AI, NewCast);
00153   }
00154   return ReplaceInstUsesWith(CI, New);
00155 }
00156 
00157 /// EvaluateInDifferentType - Given an expression that
00158 /// CanEvaluateTruncated or CanEvaluateSExtd returns true for, actually
00159 /// insert the code to evaluate the expression.
00160 Value *InstCombiner::EvaluateInDifferentType(Value *V, Type *Ty,
00161                                              bool isSigned) {
00162   if (Constant *C = dyn_cast<Constant>(V)) {
00163     C = ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
00164     // If we got a constantexpr back, try to simplify it with DL info.
00165     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
00166       C = ConstantFoldConstantExpression(CE, DL, TLI);
00167     return C;
00168   }
00169 
00170   // Otherwise, it must be an instruction.
00171   Instruction *I = cast<Instruction>(V);
00172   Instruction *Res = 0;
00173   unsigned Opc = I->getOpcode();
00174   switch (Opc) {
00175   case Instruction::Add:
00176   case Instruction::Sub:
00177   case Instruction::Mul:
00178   case Instruction::And:
00179   case Instruction::Or:
00180   case Instruction::Xor:
00181   case Instruction::AShr:
00182   case Instruction::LShr:
00183   case Instruction::Shl:
00184   case Instruction::UDiv:
00185   case Instruction::URem: {
00186     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
00187     Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
00188     Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
00189     break;
00190   }
00191   case Instruction::Trunc:
00192   case Instruction::ZExt:
00193   case Instruction::SExt:
00194     // If the source type of the cast is the type we're trying for then we can
00195     // just return the source.  There's no need to insert it because it is not
00196     // new.
00197     if (I->getOperand(0)->getType() == Ty)
00198       return I->getOperand(0);
00199 
00200     // Otherwise, must be the same type of cast, so just reinsert a new one.
00201     // This also handles the case of zext(trunc(x)) -> zext(x).
00202     Res = CastInst::CreateIntegerCast(I->getOperand(0), Ty,
00203                                       Opc == Instruction::SExt);
00204     break;
00205   case Instruction::Select: {
00206     Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
00207     Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
00208     Res = SelectInst::Create(I->getOperand(0), True, False);
00209     break;
00210   }
00211   case Instruction::PHI: {
00212     PHINode *OPN = cast<PHINode>(I);
00213     PHINode *NPN = PHINode::Create(Ty, OPN->getNumIncomingValues());
00214     for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
00215       Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
00216       NPN->addIncoming(V, OPN->getIncomingBlock(i));
00217     }
00218     Res = NPN;
00219     break;
00220   }
00221   default:
00222     // TODO: Can handle more cases here.
00223     llvm_unreachable("Unreachable!");
00224   }
00225 
00226   Res->takeName(I);
00227   return InsertNewInstWith(Res, *I);
00228 }
00229 
00230 
00231 /// This function is a wrapper around CastInst::isEliminableCastPair. It
00232 /// simply extracts arguments and returns what that function returns.
00233 static Instruction::CastOps
00234 isEliminableCastPair(
00235   const CastInst *CI, ///< The first cast instruction
00236   unsigned opcode,       ///< The opcode of the second cast instruction
00237   Type *DstTy,     ///< The target type for the second cast instruction
00238   const DataLayout *DL ///< The target data for pointer size
00239 ) {
00240 
00241   Type *SrcTy = CI->getOperand(0)->getType();   // A from above
00242   Type *MidTy = CI->getType();                  // B from above
00243 
00244   // Get the opcodes of the two Cast instructions
00245   Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
00246   Instruction::CastOps secondOp = Instruction::CastOps(opcode);
00247   Type *SrcIntPtrTy = DL && SrcTy->isPtrOrPtrVectorTy() ?
00248     DL->getIntPtrType(SrcTy) : 0;
00249   Type *MidIntPtrTy = DL && MidTy->isPtrOrPtrVectorTy() ?
00250     DL->getIntPtrType(MidTy) : 0;
00251   Type *DstIntPtrTy = DL && DstTy->isPtrOrPtrVectorTy() ?
00252     DL->getIntPtrType(DstTy) : 0;
00253   unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
00254                                                 DstTy, SrcIntPtrTy, MidIntPtrTy,
00255                                                 DstIntPtrTy);
00256 
00257   // We don't want to form an inttoptr or ptrtoint that converts to an integer
00258   // type that differs from the pointer size.
00259   if ((Res == Instruction::IntToPtr && SrcTy != DstIntPtrTy) ||
00260       (Res == Instruction::PtrToInt && DstTy != SrcIntPtrTy))
00261     Res = 0;
00262 
00263   return Instruction::CastOps(Res);
00264 }
00265 
00266 /// ShouldOptimizeCast - Return true if the cast from "V to Ty" actually
00267 /// results in any code being generated and is interesting to optimize out. If
00268 /// the cast can be eliminated by some other simple transformation, we prefer
00269 /// to do the simplification first.
00270 bool InstCombiner::ShouldOptimizeCast(Instruction::CastOps opc, const Value *V,
00271                                       Type *Ty) {
00272   // Noop casts and casts of constants should be eliminated trivially.
00273   if (V->getType() == Ty || isa<Constant>(V)) return false;
00274 
00275   // If this is another cast that can be eliminated, we prefer to have it
00276   // eliminated.
00277   if (const CastInst *CI = dyn_cast<CastInst>(V))
00278     if (isEliminableCastPair(CI, opc, Ty, DL))
00279       return false;
00280 
00281   // If this is a vector sext from a compare, then we don't want to break the
00282   // idiom where each element of the extended vector is either zero or all ones.
00283   if (opc == Instruction::SExt && isa<CmpInst>(V) && Ty->isVectorTy())
00284     return false;
00285 
00286   return true;
00287 }
00288 
00289 
00290 /// @brief Implement the transforms common to all CastInst visitors.
00291 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
00292   Value *Src = CI.getOperand(0);
00293 
00294   // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
00295   // eliminate it now.
00296   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
00297     if (Instruction::CastOps opc =
00298         isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), DL)) {
00299       // The first cast (CSrc) is eliminable so we need to fix up or replace
00300       // the second cast (CI). CSrc will then have a good chance of being dead.
00301       return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
00302     }
00303   }
00304 
00305   // If we are casting a select then fold the cast into the select
00306   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
00307     if (Instruction *NV = FoldOpIntoSelect(CI, SI))
00308       return NV;
00309 
00310   // If we are casting a PHI then fold the cast into the PHI
00311   if (isa<PHINode>(Src)) {
00312     // We don't do this if this would create a PHI node with an illegal type if
00313     // it is currently legal.
00314     if (!Src->getType()->isIntegerTy() ||
00315         !CI.getType()->isIntegerTy() ||
00316         ShouldChangeType(CI.getType(), Src->getType()))
00317       if (Instruction *NV = FoldOpIntoPhi(CI))
00318         return NV;
00319   }
00320 
00321   return 0;
00322 }
00323 
00324 /// CanEvaluateTruncated - Return true if we can evaluate the specified
00325 /// expression tree as type Ty instead of its larger type, and arrive with the
00326 /// same value.  This is used by code that tries to eliminate truncates.
00327 ///
00328 /// Ty will always be a type smaller than V.  We should return true if trunc(V)
00329 /// can be computed by computing V in the smaller type.  If V is an instruction,
00330 /// then trunc(inst(x,y)) can be computed as inst(trunc(x),trunc(y)), which only
00331 /// makes sense if x and y can be efficiently truncated.
00332 ///
00333 /// This function works on both vectors and scalars.
00334 ///
00335 static bool CanEvaluateTruncated(Value *V, Type *Ty) {
00336   // We can always evaluate constants in another type.
00337   if (isa<Constant>(V))
00338     return true;
00339 
00340   Instruction *I = dyn_cast<Instruction>(V);
00341   if (!I) return false;
00342 
00343   Type *OrigTy = V->getType();
00344 
00345   // If this is an extension from the dest type, we can eliminate it, even if it
00346   // has multiple uses.
00347   if ((isa<ZExtInst>(I) || isa<SExtInst>(I)) &&
00348       I->getOperand(0)->getType() == Ty)
00349     return true;
00350 
00351   // We can't extend or shrink something that has multiple uses: doing so would
00352   // require duplicating the instruction in general, which isn't profitable.
00353   if (!I->hasOneUse()) return false;
00354 
00355   unsigned Opc = I->getOpcode();
00356   switch (Opc) {
00357   case Instruction::Add:
00358   case Instruction::Sub:
00359   case Instruction::Mul:
00360   case Instruction::And:
00361   case Instruction::Or:
00362   case Instruction::Xor:
00363     // These operators can all arbitrarily be extended or truncated.
00364     return CanEvaluateTruncated(I->getOperand(0), Ty) &&
00365            CanEvaluateTruncated(I->getOperand(1), Ty);
00366 
00367   case Instruction::UDiv:
00368   case Instruction::URem: {
00369     // UDiv and URem can be truncated if all the truncated bits are zero.
00370     uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
00371     uint32_t BitWidth = Ty->getScalarSizeInBits();
00372     if (BitWidth < OrigBitWidth) {
00373       APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
00374       if (MaskedValueIsZero(I->getOperand(0), Mask) &&
00375           MaskedValueIsZero(I->getOperand(1), Mask)) {
00376         return CanEvaluateTruncated(I->getOperand(0), Ty) &&
00377                CanEvaluateTruncated(I->getOperand(1), Ty);
00378       }
00379     }
00380     break;
00381   }
00382   case Instruction::Shl:
00383     // If we are truncating the result of this SHL, and if it's a shift of a
00384     // constant amount, we can always perform a SHL in a smaller type.
00385     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
00386       uint32_t BitWidth = Ty->getScalarSizeInBits();
00387       if (CI->getLimitedValue(BitWidth) < BitWidth)
00388         return CanEvaluateTruncated(I->getOperand(0), Ty);
00389     }
00390     break;
00391   case Instruction::LShr:
00392     // If this is a truncate of a logical shr, we can truncate it to a smaller
00393     // lshr iff we know that the bits we would otherwise be shifting in are
00394     // already zeros.
00395     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
00396       uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
00397       uint32_t BitWidth = Ty->getScalarSizeInBits();
00398       if (MaskedValueIsZero(I->getOperand(0),
00399             APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
00400           CI->getLimitedValue(BitWidth) < BitWidth) {
00401         return CanEvaluateTruncated(I->getOperand(0), Ty);
00402       }
00403     }
00404     break;
00405   case Instruction::Trunc:
00406     // trunc(trunc(x)) -> trunc(x)
00407     return true;
00408   case Instruction::ZExt:
00409   case Instruction::SExt:
00410     // trunc(ext(x)) -> ext(x) if the source type is smaller than the new dest
00411     // trunc(ext(x)) -> trunc(x) if the source type is larger than the new dest
00412     return true;
00413   case Instruction::Select: {
00414     SelectInst *SI = cast<SelectInst>(I);
00415     return CanEvaluateTruncated(SI->getTrueValue(), Ty) &&
00416            CanEvaluateTruncated(SI->getFalseValue(), Ty);
00417   }
00418   case Instruction::PHI: {
00419     // We can change a phi if we can change all operands.  Note that we never
00420     // get into trouble with cyclic PHIs here because we only consider
00421     // instructions with a single use.
00422     PHINode *PN = cast<PHINode>(I);
00423     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
00424       if (!CanEvaluateTruncated(PN->getIncomingValue(i), Ty))
00425         return false;
00426     return true;
00427   }
00428   default:
00429     // TODO: Can handle more cases here.
00430     break;
00431   }
00432 
00433   return false;
00434 }
00435 
00436 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
00437   if (Instruction *Result = commonCastTransforms(CI))
00438     return Result;
00439 
00440   // See if we can simplify any instructions used by the input whose sole
00441   // purpose is to compute bits we don't care about.
00442   if (SimplifyDemandedInstructionBits(CI))
00443     return &CI;
00444 
00445   Value *Src = CI.getOperand(0);
00446   Type *DestTy = CI.getType(), *SrcTy = Src->getType();
00447 
00448   // Attempt to truncate the entire input expression tree to the destination
00449   // type.   Only do this if the dest type is a simple type, don't convert the
00450   // expression tree to something weird like i93 unless the source is also
00451   // strange.
00452   if ((DestTy->isVectorTy() || ShouldChangeType(SrcTy, DestTy)) &&
00453       CanEvaluateTruncated(Src, DestTy)) {
00454 
00455     // If this cast is a truncate, evaluting in a different type always
00456     // eliminates the cast, so it is always a win.
00457     DEBUG(dbgs() << "ICE: EvaluateInDifferentType converting expression type"
00458           " to avoid cast: " << CI << '\n');
00459     Value *Res = EvaluateInDifferentType(Src, DestTy, false);
00460     assert(Res->getType() == DestTy);
00461     return ReplaceInstUsesWith(CI, Res);
00462   }
00463 
00464   // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0), likewise for vector.
00465   if (DestTy->getScalarSizeInBits() == 1) {
00466     Constant *One = ConstantInt::get(Src->getType(), 1);
00467     Src = Builder->CreateAnd(Src, One);
00468     Value *Zero = Constant::getNullValue(Src->getType());
00469     return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
00470   }
00471 
00472   // Transform trunc(lshr (zext A), Cst) to eliminate one type conversion.
00473   Value *A = 0; ConstantInt *Cst = 0;
00474   if (Src->hasOneUse() &&
00475       match(Src, m_LShr(m_ZExt(m_Value(A)), m_ConstantInt(Cst)))) {
00476     // We have three types to worry about here, the type of A, the source of
00477     // the truncate (MidSize), and the destination of the truncate. We know that
00478     // ASize < MidSize   and MidSize > ResultSize, but don't know the relation
00479     // between ASize and ResultSize.
00480     unsigned ASize = A->getType()->getPrimitiveSizeInBits();
00481 
00482     // If the shift amount is larger than the size of A, then the result is
00483     // known to be zero because all the input bits got shifted out.
00484     if (Cst->getZExtValue() >= ASize)
00485       return ReplaceInstUsesWith(CI, Constant::getNullValue(CI.getType()));
00486 
00487     // Since we're doing an lshr and a zero extend, and know that the shift
00488     // amount is smaller than ASize, it is always safe to do the shift in A's
00489     // type, then zero extend or truncate to the result.
00490     Value *Shift = Builder->CreateLShr(A, Cst->getZExtValue());
00491     Shift->takeName(Src);
00492     return CastInst::CreateIntegerCast(Shift, CI.getType(), false);
00493   }
00494 
00495   // Transform "trunc (and X, cst)" -> "and (trunc X), cst" so long as the dest
00496   // type isn't non-native.
00497   if (Src->hasOneUse() && isa<IntegerType>(Src->getType()) &&
00498       ShouldChangeType(Src->getType(), CI.getType()) &&
00499       match(Src, m_And(m_Value(A), m_ConstantInt(Cst)))) {
00500     Value *NewTrunc = Builder->CreateTrunc(A, CI.getType(), A->getName()+".tr");
00501     return BinaryOperator::CreateAnd(NewTrunc,
00502                                      ConstantExpr::getTrunc(Cst, CI.getType()));
00503   }
00504 
00505   return 0;
00506 }
00507 
00508 /// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
00509 /// in order to eliminate the icmp.
00510 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
00511                                              bool DoXform) {
00512   // If we are just checking for a icmp eq of a single bit and zext'ing it
00513   // to an integer, then shift the bit to the appropriate place and then
00514   // cast to integer to avoid the comparison.
00515   if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
00516     const APInt &Op1CV = Op1C->getValue();
00517 
00518     // zext (x <s  0) to i32 --> x>>u31      true if signbit set.
00519     // zext (x >s -1) to i32 --> (x>>u31)^1  true if signbit clear.
00520     if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
00521         (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
00522       if (!DoXform) return ICI;
00523 
00524       Value *In = ICI->getOperand(0);
00525       Value *Sh = ConstantInt::get(In->getType(),
00526                                    In->getType()->getScalarSizeInBits()-1);
00527       In = Builder->CreateLShr(In, Sh, In->getName()+".lobit");
00528       if (In->getType() != CI.getType())
00529         In = Builder->CreateIntCast(In, CI.getType(), false/*ZExt*/);
00530 
00531       if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
00532         Constant *One = ConstantInt::get(In->getType(), 1);
00533         In = Builder->CreateXor(In, One, In->getName()+".not");
00534       }
00535 
00536       return ReplaceInstUsesWith(CI, In);
00537     }
00538 
00539     // zext (X == 0) to i32 --> X^1      iff X has only the low bit set.
00540     // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
00541     // zext (X == 1) to i32 --> X        iff X has only the low bit set.
00542     // zext (X == 2) to i32 --> X>>1     iff X has only the 2nd bit set.
00543     // zext (X != 0) to i32 --> X        iff X has only the low bit set.
00544     // zext (X != 0) to i32 --> X>>1     iff X has only the 2nd bit set.
00545     // zext (X != 1) to i32 --> X^1      iff X has only the low bit set.
00546     // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
00547     if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
00548         // This only works for EQ and NE
00549         ICI->isEquality()) {
00550       // If Op1C some other power of two, convert:
00551       uint32_t BitWidth = Op1C->getType()->getBitWidth();
00552       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
00553       ComputeMaskedBits(ICI->getOperand(0), KnownZero, KnownOne);
00554 
00555       APInt KnownZeroMask(~KnownZero);
00556       if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
00557         if (!DoXform) return ICI;
00558 
00559         bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
00560         if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
00561           // (X&4) == 2 --> false
00562           // (X&4) != 2 --> true
00563           Constant *Res = ConstantInt::get(Type::getInt1Ty(CI.getContext()),
00564                                            isNE);
00565           Res = ConstantExpr::getZExt(Res, CI.getType());
00566           return ReplaceInstUsesWith(CI, Res);
00567         }
00568 
00569         uint32_t ShiftAmt = KnownZeroMask.logBase2();
00570         Value *In = ICI->getOperand(0);
00571         if (ShiftAmt) {
00572           // Perform a logical shr by shiftamt.
00573           // Insert the shift to put the result in the low bit.
00574           In = Builder->CreateLShr(In, ConstantInt::get(In->getType(),ShiftAmt),
00575                                    In->getName()+".lobit");
00576         }
00577 
00578         if ((Op1CV != 0) == isNE) { // Toggle the low bit.
00579           Constant *One = ConstantInt::get(In->getType(), 1);
00580           In = Builder->CreateXor(In, One);
00581         }
00582 
00583         if (CI.getType() == In->getType())
00584           return ReplaceInstUsesWith(CI, In);
00585         return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
00586       }
00587     }
00588   }
00589 
00590   // icmp ne A, B is equal to xor A, B when A and B only really have one bit.
00591   // It is also profitable to transform icmp eq into not(xor(A, B)) because that
00592   // may lead to additional simplifications.
00593   if (ICI->isEquality() && CI.getType() == ICI->getOperand(0)->getType()) {
00594     if (IntegerType *ITy = dyn_cast<IntegerType>(CI.getType())) {
00595       uint32_t BitWidth = ITy->getBitWidth();
00596       Value *LHS = ICI->getOperand(0);
00597       Value *RHS = ICI->getOperand(1);
00598 
00599       APInt KnownZeroLHS(BitWidth, 0), KnownOneLHS(BitWidth, 0);
00600       APInt KnownZeroRHS(BitWidth, 0), KnownOneRHS(BitWidth, 0);
00601       ComputeMaskedBits(LHS, KnownZeroLHS, KnownOneLHS);
00602       ComputeMaskedBits(RHS, KnownZeroRHS, KnownOneRHS);
00603 
00604       if (KnownZeroLHS == KnownZeroRHS && KnownOneLHS == KnownOneRHS) {
00605         APInt KnownBits = KnownZeroLHS | KnownOneLHS;
00606         APInt UnknownBit = ~KnownBits;
00607         if (UnknownBit.countPopulation() == 1) {
00608           if (!DoXform) return ICI;
00609 
00610           Value *Result = Builder->CreateXor(LHS, RHS);
00611 
00612           // Mask off any bits that are set and won't be shifted away.
00613           if (KnownOneLHS.uge(UnknownBit))
00614             Result = Builder->CreateAnd(Result,
00615                                         ConstantInt::get(ITy, UnknownBit));
00616 
00617           // Shift the bit we're testing down to the lsb.
00618           Result = Builder->CreateLShr(
00619                Result, ConstantInt::get(ITy, UnknownBit.countTrailingZeros()));
00620 
00621           if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
00622             Result = Builder->CreateXor(Result, ConstantInt::get(ITy, 1));
00623           Result->takeName(ICI);
00624           return ReplaceInstUsesWith(CI, Result);
00625         }
00626       }
00627     }
00628   }
00629 
00630   return 0;
00631 }
00632 
00633 /// CanEvaluateZExtd - Determine if the specified value can be computed in the
00634 /// specified wider type and produce the same low bits.  If not, return false.
00635 ///
00636 /// If this function returns true, it can also return a non-zero number of bits
00637 /// (in BitsToClear) which indicates that the value it computes is correct for
00638 /// the zero extend, but that the additional BitsToClear bits need to be zero'd
00639 /// out.  For example, to promote something like:
00640 ///
00641 ///   %B = trunc i64 %A to i32
00642 ///   %C = lshr i32 %B, 8
00643 ///   %E = zext i32 %C to i64
00644 ///
00645 /// CanEvaluateZExtd for the 'lshr' will return true, and BitsToClear will be
00646 /// set to 8 to indicate that the promoted value needs to have bits 24-31
00647 /// cleared in addition to bits 32-63.  Since an 'and' will be generated to
00648 /// clear the top bits anyway, doing this has no extra cost.
00649 ///
00650 /// This function works on both vectors and scalars.
00651 static bool CanEvaluateZExtd(Value *V, Type *Ty, unsigned &BitsToClear) {
00652   BitsToClear = 0;
00653   if (isa<Constant>(V))
00654     return true;
00655 
00656   Instruction *I = dyn_cast<Instruction>(V);
00657   if (!I) return false;
00658 
00659   // If the input is a truncate from the destination type, we can trivially
00660   // eliminate it.
00661   if (isa<TruncInst>(I) && I->getOperand(0)->getType() == Ty)
00662     return true;
00663 
00664   // We can't extend or shrink something that has multiple uses: doing so would
00665   // require duplicating the instruction in general, which isn't profitable.
00666   if (!I->hasOneUse()) return false;
00667 
00668   unsigned Opc = I->getOpcode(), Tmp;
00669   switch (Opc) {
00670   case Instruction::ZExt:  // zext(zext(x)) -> zext(x).
00671   case Instruction::SExt:  // zext(sext(x)) -> sext(x).
00672   case Instruction::Trunc: // zext(trunc(x)) -> trunc(x) or zext(x)
00673     return true;
00674   case Instruction::And:
00675   case Instruction::Or:
00676   case Instruction::Xor:
00677   case Instruction::Add:
00678   case Instruction::Sub:
00679   case Instruction::Mul:
00680     if (!CanEvaluateZExtd(I->getOperand(0), Ty, BitsToClear) ||
00681         !CanEvaluateZExtd(I->getOperand(1), Ty, Tmp))
00682       return false;
00683     // These can all be promoted if neither operand has 'bits to clear'.
00684     if (BitsToClear == 0 && Tmp == 0)
00685       return true;
00686 
00687     // If the operation is an AND/OR/XOR and the bits to clear are zero in the
00688     // other side, BitsToClear is ok.
00689     if (Tmp == 0 &&
00690         (Opc == Instruction::And || Opc == Instruction::Or ||
00691          Opc == Instruction::Xor)) {
00692       // We use MaskedValueIsZero here for generality, but the case we care
00693       // about the most is constant RHS.
00694       unsigned VSize = V->getType()->getScalarSizeInBits();
00695       if (MaskedValueIsZero(I->getOperand(1),
00696                             APInt::getHighBitsSet(VSize, BitsToClear)))
00697         return true;
00698     }
00699 
00700     // Otherwise, we don't know how to analyze this BitsToClear case yet.
00701     return false;
00702 
00703   case Instruction::Shl:
00704     // We can promote shl(x, cst) if we can promote x.  Since shl overwrites the
00705     // upper bits we can reduce BitsToClear by the shift amount.
00706     if (ConstantInt *Amt = dyn_cast<ConstantInt>(I->getOperand(1))) {
00707       if (!CanEvaluateZExtd(I->getOperand(0), Ty, BitsToClear))
00708         return false;
00709       uint64_t ShiftAmt = Amt->getZExtValue();
00710       BitsToClear = ShiftAmt < BitsToClear ? BitsToClear - ShiftAmt : 0;
00711       return true;
00712     }
00713     return false;
00714   case Instruction::LShr:
00715     // We can promote lshr(x, cst) if we can promote x.  This requires the
00716     // ultimate 'and' to clear out the high zero bits we're clearing out though.
00717     if (ConstantInt *Amt = dyn_cast<ConstantInt>(I->getOperand(1))) {
00718       if (!CanEvaluateZExtd(I->getOperand(0), Ty, BitsToClear))
00719         return false;
00720       BitsToClear += Amt->getZExtValue();
00721       if (BitsToClear > V->getType()->getScalarSizeInBits())
00722         BitsToClear = V->getType()->getScalarSizeInBits();
00723       return true;
00724     }
00725     // Cannot promote variable LSHR.
00726     return false;
00727   case Instruction::Select:
00728     if (!CanEvaluateZExtd(I->getOperand(1), Ty, Tmp) ||
00729         !CanEvaluateZExtd(I->getOperand(2), Ty, BitsToClear) ||
00730         // TODO: If important, we could handle the case when the BitsToClear are
00731         // known zero in the disagreeing side.
00732         Tmp != BitsToClear)
00733       return false;
00734     return true;
00735 
00736   case Instruction::PHI: {
00737     // We can change a phi if we can change all operands.  Note that we never
00738     // get into trouble with cyclic PHIs here because we only consider
00739     // instructions with a single use.
00740     PHINode *PN = cast<PHINode>(I);
00741     if (!CanEvaluateZExtd(PN->getIncomingValue(0), Ty, BitsToClear))
00742       return false;
00743     for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i)
00744       if (!CanEvaluateZExtd(PN->getIncomingValue(i), Ty, Tmp) ||
00745           // TODO: If important, we could handle the case when the BitsToClear
00746           // are known zero in the disagreeing input.
00747           Tmp != BitsToClear)
00748         return false;
00749     return true;
00750   }
00751   default:
00752     // TODO: Can handle more cases here.
00753     return false;
00754   }
00755 }
00756 
00757 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
00758   // If this zero extend is only used by a truncate, let the truncate be
00759   // eliminated before we try to optimize this zext.
00760   if (CI.hasOneUse() && isa<TruncInst>(CI.user_back()))
00761     return 0;
00762 
00763   // If one of the common conversion will work, do it.
00764   if (Instruction *Result = commonCastTransforms(CI))
00765     return Result;
00766 
00767   // See if we can simplify any instructions used by the input whose sole
00768   // purpose is to compute bits we don't care about.
00769   if (SimplifyDemandedInstructionBits(CI))
00770     return &CI;
00771 
00772   Value *Src = CI.getOperand(0);
00773   Type *SrcTy = Src->getType(), *DestTy = CI.getType();
00774 
00775   // Attempt to extend the entire input expression tree to the destination
00776   // type.   Only do this if the dest type is a simple type, don't convert the
00777   // expression tree to something weird like i93 unless the source is also
00778   // strange.
00779   unsigned BitsToClear;
00780   if ((DestTy->isVectorTy() || ShouldChangeType(SrcTy, DestTy)) &&
00781       CanEvaluateZExtd(Src, DestTy, BitsToClear)) {
00782     assert(BitsToClear < SrcTy->getScalarSizeInBits() &&
00783            "Unreasonable BitsToClear");
00784 
00785     // Okay, we can transform this!  Insert the new expression now.
00786     DEBUG(dbgs() << "ICE: EvaluateInDifferentType converting expression type"
00787           " to avoid zero extend: " << CI);
00788     Value *Res = EvaluateInDifferentType(Src, DestTy, false);
00789     assert(Res->getType() == DestTy);
00790 
00791     uint32_t SrcBitsKept = SrcTy->getScalarSizeInBits()-BitsToClear;
00792     uint32_t DestBitSize = DestTy->getScalarSizeInBits();
00793 
00794     // If the high bits are already filled with zeros, just replace this
00795     // cast with the result.
00796     if (MaskedValueIsZero(Res, APInt::getHighBitsSet(DestBitSize,
00797                                                      DestBitSize-SrcBitsKept)))
00798       return ReplaceInstUsesWith(CI, Res);
00799 
00800     // We need to emit an AND to clear the high bits.
00801     Constant *C = ConstantInt::get(Res->getType(),
00802                                APInt::getLowBitsSet(DestBitSize, SrcBitsKept));
00803     return BinaryOperator::CreateAnd(Res, C);
00804   }
00805 
00806   // If this is a TRUNC followed by a ZEXT then we are dealing with integral
00807   // types and if the sizes are just right we can convert this into a logical
00808   // 'and' which will be much cheaper than the pair of casts.
00809   if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) {   // A->B->C cast
00810     // TODO: Subsume this into EvaluateInDifferentType.
00811 
00812     // Get the sizes of the types involved.  We know that the intermediate type
00813     // will be smaller than A or C, but don't know the relation between A and C.
00814     Value *A = CSrc->getOperand(0);
00815     unsigned SrcSize = A->getType()->getScalarSizeInBits();
00816     unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
00817     unsigned DstSize = CI.getType()->getScalarSizeInBits();
00818     // If we're actually extending zero bits, then if
00819     // SrcSize <  DstSize: zext(a & mask)
00820     // SrcSize == DstSize: a & mask
00821     // SrcSize  > DstSize: trunc(a) & mask
00822     if (SrcSize < DstSize) {
00823       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
00824       Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
00825       Value *And = Builder->CreateAnd(A, AndConst, CSrc->getName()+".mask");
00826       return new ZExtInst(And, CI.getType());
00827     }
00828 
00829     if (SrcSize == DstSize) {
00830       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
00831       return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
00832                                                            AndValue));
00833     }
00834     if (SrcSize > DstSize) {
00835       Value *Trunc = Builder->CreateTrunc(A, CI.getType());
00836       APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
00837       return BinaryOperator::CreateAnd(Trunc,
00838                                        ConstantInt::get(Trunc->getType(),
00839                                                         AndValue));
00840     }
00841   }
00842 
00843   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
00844     return transformZExtICmp(ICI, CI);
00845 
00846   BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
00847   if (SrcI && SrcI->getOpcode() == Instruction::Or) {
00848     // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
00849     // of the (zext icmp) will be transformed.
00850     ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
00851     ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
00852     if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
00853         (transformZExtICmp(LHS, CI, false) ||
00854          transformZExtICmp(RHS, CI, false))) {
00855       Value *LCast = Builder->CreateZExt(LHS, CI.getType(), LHS->getName());
00856       Value *RCast = Builder->CreateZExt(RHS, CI.getType(), RHS->getName());
00857       return BinaryOperator::Create(Instruction::Or, LCast, RCast);
00858     }
00859   }
00860 
00861   // zext(trunc(X) & C) -> (X & zext(C)).
00862   Constant *C;
00863   Value *X;
00864   if (SrcI &&
00865       match(SrcI, m_OneUse(m_And(m_Trunc(m_Value(X)), m_Constant(C)))) &&
00866       X->getType() == CI.getType())
00867     return BinaryOperator::CreateAnd(X, ConstantExpr::getZExt(C, CI.getType()));
00868 
00869   // zext((trunc(X) & C) ^ C) -> ((X & zext(C)) ^ zext(C)).
00870   Value *And;
00871   if (SrcI && match(SrcI, m_OneUse(m_Xor(m_Value(And), m_Constant(C)))) &&
00872       match(And, m_OneUse(m_And(m_Trunc(m_Value(X)), m_Specific(C)))) &&
00873       X->getType() == CI.getType()) {
00874     Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
00875     return BinaryOperator::CreateXor(Builder->CreateAnd(X, ZC), ZC);
00876   }
00877 
00878   // zext (xor i1 X, true) to i32  --> xor (zext i1 X to i32), 1
00879   if (SrcI && SrcI->hasOneUse() &&
00880       SrcI->getType()->getScalarType()->isIntegerTy(1) &&
00881       match(SrcI, m_Not(m_Value(X))) && (!X->hasOneUse() || !isa<CmpInst>(X))) {
00882     Value *New = Builder->CreateZExt(X, CI.getType());
00883     return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
00884   }
00885 
00886   return 0;
00887 }
00888 
00889 /// transformSExtICmp - Transform (sext icmp) to bitwise / integer operations
00890 /// in order to eliminate the icmp.
00891 Instruction *InstCombiner::transformSExtICmp(ICmpInst *ICI, Instruction &CI) {
00892   Value *Op0 = ICI->getOperand(0), *Op1 = ICI->getOperand(1);
00893   ICmpInst::Predicate Pred = ICI->getPredicate();
00894 
00895   if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
00896     // (x <s  0) ? -1 : 0 -> ashr x, 31        -> all ones if negative
00897     // (x >s -1) ? -1 : 0 -> not (ashr x, 31)  -> all ones if positive
00898     if ((Pred == ICmpInst::ICMP_SLT && Op1C->isNullValue()) ||
00899         (Pred == ICmpInst::ICMP_SGT && Op1C->isAllOnesValue())) {
00900 
00901       Value *Sh = ConstantInt::get(Op0->getType(),
00902                                    Op0->getType()->getScalarSizeInBits()-1);
00903       Value *In = Builder->CreateAShr(Op0, Sh, Op0->getName()+".lobit");
00904       if (In->getType() != CI.getType())
00905         In = Builder->CreateIntCast(In, CI.getType(), true/*SExt*/);
00906 
00907       if (Pred == ICmpInst::ICMP_SGT)
00908         In = Builder->CreateNot(In, In->getName()+".not");
00909       return ReplaceInstUsesWith(CI, In);
00910     }
00911   }
00912 
00913   if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
00914     // If we know that only one bit of the LHS of the icmp can be set and we
00915     // have an equality comparison with zero or a power of 2, we can transform
00916     // the icmp and sext into bitwise/integer operations.
00917     if (ICI->hasOneUse() &&
00918         ICI->isEquality() && (Op1C->isZero() || Op1C->getValue().isPowerOf2())){
00919       unsigned BitWidth = Op1C->getType()->getBitWidth();
00920       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
00921       ComputeMaskedBits(Op0, KnownZero, KnownOne);
00922 
00923       APInt KnownZeroMask(~KnownZero);
00924       if (KnownZeroMask.isPowerOf2()) {
00925         Value *In = ICI->getOperand(0);
00926 
00927         // If the icmp tests for a known zero bit we can constant fold it.
00928         if (!Op1C->isZero() && Op1C->getValue() != KnownZeroMask) {
00929           Value *V = Pred == ICmpInst::ICMP_NE ?
00930                        ConstantInt::getAllOnesValue(CI.getType()) :
00931                        ConstantInt::getNullValue(CI.getType());
00932           return ReplaceInstUsesWith(CI, V);
00933         }
00934 
00935         if (!Op1C->isZero() == (Pred == ICmpInst::ICMP_NE)) {
00936           // sext ((x & 2^n) == 0)   -> (x >> n) - 1
00937           // sext ((x & 2^n) != 2^n) -> (x >> n) - 1
00938           unsigned ShiftAmt = KnownZeroMask.countTrailingZeros();
00939           // Perform a right shift to place the desired bit in the LSB.
00940           if (ShiftAmt)
00941             In = Builder->CreateLShr(In,
00942                                      ConstantInt::get(In->getType(), ShiftAmt));
00943 
00944           // At this point "In" is either 1 or 0. Subtract 1 to turn
00945           // {1, 0} -> {0, -1}.
00946           In = Builder->CreateAdd(In,
00947                                   ConstantInt::getAllOnesValue(In->getType()),
00948                                   "sext");
00949         } else {
00950           // sext ((x & 2^n) != 0)   -> (x << bitwidth-n) a>> bitwidth-1
00951           // sext ((x & 2^n) == 2^n) -> (x << bitwidth-n) a>> bitwidth-1
00952           unsigned ShiftAmt = KnownZeroMask.countLeadingZeros();
00953           // Perform a left shift to place the desired bit in the MSB.
00954           if (ShiftAmt)
00955             In = Builder->CreateShl(In,
00956                                     ConstantInt::get(In->getType(), ShiftAmt));
00957 
00958           // Distribute the bit over the whole bit width.
00959           In = Builder->CreateAShr(In, ConstantInt::get(In->getType(),
00960                                                         BitWidth - 1), "sext");
00961         }
00962 
00963         if (CI.getType() == In->getType())
00964           return ReplaceInstUsesWith(CI, In);
00965         return CastInst::CreateIntegerCast(In, CI.getType(), true/*SExt*/);
00966       }
00967     }
00968   }
00969 
00970   return 0;
00971 }
00972 
00973 /// CanEvaluateSExtd - Return true if we can take the specified value
00974 /// and return it as type Ty without inserting any new casts and without
00975 /// changing the value of the common low bits.  This is used by code that tries
00976 /// to promote integer operations to a wider types will allow us to eliminate
00977 /// the extension.
00978 ///
00979 /// This function works on both vectors and scalars.
00980 ///
00981 static bool CanEvaluateSExtd(Value *V, Type *Ty) {
00982   assert(V->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits() &&
00983          "Can't sign extend type to a smaller type");
00984   // If this is a constant, it can be trivially promoted.
00985   if (isa<Constant>(V))
00986     return true;
00987 
00988   Instruction *I = dyn_cast<Instruction>(V);
00989   if (!I) return false;
00990 
00991   // If this is a truncate from the dest type, we can trivially eliminate it.
00992   if (isa<TruncInst>(I) && I->getOperand(0)->getType() == Ty)
00993     return true;
00994 
00995   // We can't extend or shrink something that has multiple uses: doing so would
00996   // require duplicating the instruction in general, which isn't profitable.
00997   if (!I->hasOneUse()) return false;
00998 
00999   switch (I->getOpcode()) {
01000   case Instruction::SExt:  // sext(sext(x)) -> sext(x)
01001   case Instruction::ZExt:  // sext(zext(x)) -> zext(x)
01002   case Instruction::Trunc: // sext(trunc(x)) -> trunc(x) or sext(x)
01003     return true;
01004   case Instruction::And:
01005   case Instruction::Or:
01006   case Instruction::Xor:
01007   case Instruction::Add:
01008   case Instruction::Sub:
01009   case Instruction::Mul:
01010     // These operators can all arbitrarily be extended if their inputs can.
01011     return CanEvaluateSExtd(I->getOperand(0), Ty) &&
01012            CanEvaluateSExtd(I->getOperand(1), Ty);
01013 
01014   //case Instruction::Shl:   TODO
01015   //case Instruction::LShr:  TODO
01016 
01017   case Instruction::Select:
01018     return CanEvaluateSExtd(I->getOperand(1), Ty) &&
01019            CanEvaluateSExtd(I->getOperand(2), Ty);
01020 
01021   case Instruction::PHI: {
01022     // We can change a phi if we can change all operands.  Note that we never
01023     // get into trouble with cyclic PHIs here because we only consider
01024     // instructions with a single use.
01025     PHINode *PN = cast<PHINode>(I);
01026     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
01027       if (!CanEvaluateSExtd(PN->getIncomingValue(i), Ty)) return false;
01028     return true;
01029   }
01030   default:
01031     // TODO: Can handle more cases here.
01032     break;
01033   }
01034 
01035   return false;
01036 }
01037 
01038 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
01039   // If this sign extend is only used by a truncate, let the truncate be
01040   // eliminated before we try to optimize this sext.
01041   if (CI.hasOneUse() && isa<TruncInst>(CI.user_back()))
01042     return 0;
01043 
01044   if (Instruction *I = commonCastTransforms(CI))
01045     return I;
01046 
01047   // See if we can simplify any instructions used by the input whose sole
01048   // purpose is to compute bits we don't care about.
01049   if (SimplifyDemandedInstructionBits(CI))
01050     return &CI;
01051 
01052   Value *Src = CI.getOperand(0);
01053   Type *SrcTy = Src->getType(), *DestTy = CI.getType();
01054 
01055   // Attempt to extend the entire input expression tree to the destination
01056   // type.   Only do this if the dest type is a simple type, don't convert the
01057   // expression tree to something weird like i93 unless the source is also
01058   // strange.
01059   if ((DestTy->isVectorTy() || ShouldChangeType(SrcTy, DestTy)) &&
01060       CanEvaluateSExtd(Src, DestTy)) {
01061     // Okay, we can transform this!  Insert the new expression now.
01062     DEBUG(dbgs() << "ICE: EvaluateInDifferentType converting expression type"
01063           " to avoid sign extend: " << CI);
01064     Value *Res = EvaluateInDifferentType(Src, DestTy, true);
01065     assert(Res->getType() == DestTy);
01066 
01067     uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
01068     uint32_t DestBitSize = DestTy->getScalarSizeInBits();
01069 
01070     // If the high bits are already filled with sign bit, just replace this
01071     // cast with the result.
01072     if (ComputeNumSignBits(Res) > DestBitSize - SrcBitSize)
01073       return ReplaceInstUsesWith(CI, Res);
01074 
01075     // We need to emit a shl + ashr to do the sign extend.
01076     Value *ShAmt = ConstantInt::get(DestTy, DestBitSize-SrcBitSize);
01077     return BinaryOperator::CreateAShr(Builder->CreateShl(Res, ShAmt, "sext"),
01078                                       ShAmt);
01079   }
01080 
01081   // If this input is a trunc from our destination, then turn sext(trunc(x))
01082   // into shifts.
01083   if (TruncInst *TI = dyn_cast<TruncInst>(Src))
01084     if (TI->hasOneUse() && TI->getOperand(0)->getType() == DestTy) {
01085       uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
01086       uint32_t DestBitSize = DestTy->getScalarSizeInBits();
01087 
01088       // We need to emit a shl + ashr to do the sign extend.
01089       Value *ShAmt = ConstantInt::get(DestTy, DestBitSize-SrcBitSize);
01090       Value *Res = Builder->CreateShl(TI->getOperand(0), ShAmt, "sext");
01091       return BinaryOperator::CreateAShr(Res, ShAmt);
01092     }
01093 
01094   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
01095     return transformSExtICmp(ICI, CI);
01096 
01097   // If the input is a shl/ashr pair of a same constant, then this is a sign
01098   // extension from a smaller value.  If we could trust arbitrary bitwidth
01099   // integers, we could turn this into a truncate to the smaller bit and then
01100   // use a sext for the whole extension.  Since we don't, look deeper and check
01101   // for a truncate.  If the source and dest are the same type, eliminate the
01102   // trunc and extend and just do shifts.  For example, turn:
01103   //   %a = trunc i32 %i to i8
01104   //   %b = shl i8 %a, 6
01105   //   %c = ashr i8 %b, 6
01106   //   %d = sext i8 %c to i32
01107   // into:
01108   //   %a = shl i32 %i, 30
01109   //   %d = ashr i32 %a, 30
01110   Value *A = 0;
01111   // TODO: Eventually this could be subsumed by EvaluateInDifferentType.
01112   ConstantInt *BA = 0, *CA = 0;
01113   if (match(Src, m_AShr(m_Shl(m_Trunc(m_Value(A)), m_ConstantInt(BA)),
01114                         m_ConstantInt(CA))) &&
01115       BA == CA && A->getType() == CI.getType()) {
01116     unsigned MidSize = Src->getType()->getScalarSizeInBits();
01117     unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
01118     unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
01119     Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
01120     A = Builder->CreateShl(A, ShAmtV, CI.getName());
01121     return BinaryOperator::CreateAShr(A, ShAmtV);
01122   }
01123 
01124   return 0;
01125 }
01126 
01127 
01128 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
01129 /// in the specified FP type without changing its value.
01130 static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
01131   bool losesInfo;
01132   APFloat F = CFP->getValueAPF();
01133   (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
01134   if (!losesInfo)
01135     return ConstantFP::get(CFP->getContext(), F);
01136   return 0;
01137 }
01138 
01139 /// LookThroughFPExtensions - If this is an fp extension instruction, look
01140 /// through it until we get the source value.
01141 static Value *LookThroughFPExtensions(Value *V) {
01142   if (Instruction *I = dyn_cast<Instruction>(V))
01143     if (I->getOpcode() == Instruction::FPExt)
01144       return LookThroughFPExtensions(I->getOperand(0));
01145 
01146   // If this value is a constant, return the constant in the smallest FP type
01147   // that can accurately represent it.  This allows us to turn
01148   // (float)((double)X+2.0) into x+2.0f.
01149   if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
01150     if (CFP->getType() == Type::getPPC_FP128Ty(V->getContext()))
01151       return V;  // No constant folding of this.
01152     // See if the value can be truncated to half and then reextended.
01153     if (Value *V = FitsInFPType(CFP, APFloat::IEEEhalf))
01154       return V;
01155     // See if the value can be truncated to float and then reextended.
01156     if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
01157       return V;
01158     if (CFP->getType()->isDoubleTy())
01159       return V;  // Won't shrink.
01160     if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
01161       return V;
01162     // Don't try to shrink to various long double types.
01163   }
01164 
01165   return V;
01166 }
01167 
01168 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
01169   if (Instruction *I = commonCastTransforms(CI))
01170     return I;
01171   // If we have fptrunc(OpI (fpextend x), (fpextend y)), we would like to
01172   // simpilify this expression to avoid one or more of the trunc/extend
01173   // operations if we can do so without changing the numerical results.
01174   //
01175   // The exact manner in which the widths of the operands interact to limit
01176   // what we can and cannot do safely varies from operation to operation, and
01177   // is explained below in the various case statements.
01178   BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
01179   if (OpI && OpI->hasOneUse()) {
01180     Value *LHSOrig = LookThroughFPExtensions(OpI->getOperand(0));
01181     Value *RHSOrig = LookThroughFPExtensions(OpI->getOperand(1));
01182     unsigned OpWidth = OpI->getType()->getFPMantissaWidth();
01183     unsigned LHSWidth = LHSOrig->getType()->getFPMantissaWidth();
01184     unsigned RHSWidth = RHSOrig->getType()->getFPMantissaWidth();
01185     unsigned SrcWidth = std::max(LHSWidth, RHSWidth);
01186     unsigned DstWidth = CI.getType()->getFPMantissaWidth();
01187     switch (OpI->getOpcode()) {
01188       default: break;
01189       case Instruction::FAdd:
01190       case Instruction::FSub:
01191         // For addition and subtraction, the infinitely precise result can
01192         // essentially be arbitrarily wide; proving that double rounding
01193         // will not occur because the result of OpI is exact (as we will for
01194         // FMul, for example) is hopeless.  However, we *can* nonetheless
01195         // frequently know that double rounding cannot occur (or that it is
01196         // innocuous) by taking advantage of the specific structure of
01197         // infinitely-precise results that admit double rounding.
01198         //
01199         // Specifically, if OpWidth >= 2*DstWdith+1 and DstWidth is sufficient
01200         // to represent both sources, we can guarantee that the double
01201         // rounding is innocuous (See p50 of Figueroa's 2000 PhD thesis,
01202         // "A Rigorous Framework for Fully Supporting the IEEE Standard ..."
01203         // for proof of this fact).
01204         //
01205         // Note: Figueroa does not consider the case where DstFormat !=
01206         // SrcFormat.  It's possible (likely even!) that this analysis
01207         // could be tightened for those cases, but they are rare (the main
01208         // case of interest here is (float)((double)float + float)).
01209         if (OpWidth >= 2*DstWidth+1 && DstWidth >= SrcWidth) {
01210           if (LHSOrig->getType() != CI.getType())
01211             LHSOrig = Builder->CreateFPExt(LHSOrig, CI.getType());
01212           if (RHSOrig->getType() != CI.getType())
01213             RHSOrig = Builder->CreateFPExt(RHSOrig, CI.getType());
01214           Instruction *RI =
01215             BinaryOperator::Create(OpI->getOpcode(), LHSOrig, RHSOrig);
01216           RI->copyFastMathFlags(OpI);
01217           return RI;
01218         }
01219         break;
01220       case Instruction::FMul:
01221         // For multiplication, the infinitely precise result has at most
01222         // LHSWidth + RHSWidth significant bits; if OpWidth is sufficient
01223         // that such a value can be exactly represented, then no double
01224         // rounding can possibly occur; we can safely perform the operation
01225         // in the destination format if it can represent both sources.
01226         if (OpWidth >= LHSWidth + RHSWidth && DstWidth >= SrcWidth) {
01227           if (LHSOrig->getType() != CI.getType())
01228             LHSOrig = Builder->CreateFPExt(LHSOrig, CI.getType());
01229           if (RHSOrig->getType() != CI.getType())
01230             RHSOrig = Builder->CreateFPExt(RHSOrig, CI.getType());
01231           Instruction *RI =
01232             BinaryOperator::CreateFMul(LHSOrig, RHSOrig);
01233           RI->copyFastMathFlags(OpI);
01234           return RI;
01235         }
01236         break;
01237       case Instruction::FDiv:
01238         // For division, we use again use the bound from Figueroa's
01239         // dissertation.  I am entirely certain that this bound can be
01240         // tightened in the unbalanced operand case by an analysis based on
01241         // the diophantine rational approximation bound, but the well-known
01242         // condition used here is a good conservative first pass.
01243         // TODO: Tighten bound via rigorous analysis of the unbalanced case.
01244         if (OpWidth >= 2*DstWidth && DstWidth >= SrcWidth) {
01245           if (LHSOrig->getType() != CI.getType())
01246             LHSOrig = Builder->CreateFPExt(LHSOrig, CI.getType());
01247           if (RHSOrig->getType() != CI.getType())
01248             RHSOrig = Builder->CreateFPExt(RHSOrig, CI.getType());
01249           Instruction *RI =
01250             BinaryOperator::CreateFDiv(LHSOrig, RHSOrig);
01251           RI->copyFastMathFlags(OpI);
01252           return RI;
01253         }
01254         break;
01255       case Instruction::FRem:
01256         // Remainder is straightforward.  Remainder is always exact, so the
01257         // type of OpI doesn't enter into things at all.  We simply evaluate
01258         // in whichever source type is larger, then convert to the
01259         // destination type.
01260         if (LHSWidth < SrcWidth)
01261           LHSOrig = Builder->CreateFPExt(LHSOrig, RHSOrig->getType());
01262         else if (RHSWidth <= SrcWidth)
01263           RHSOrig = Builder->CreateFPExt(RHSOrig, LHSOrig->getType());
01264         Value *ExactResult = Builder->CreateFRem(LHSOrig, RHSOrig);
01265         if (Instruction *RI = dyn_cast<Instruction>(ExactResult))
01266           RI->copyFastMathFlags(OpI);
01267         return CastInst::CreateFPCast(ExactResult, CI.getType());
01268     }
01269 
01270     // (fptrunc (fneg x)) -> (fneg (fptrunc x))
01271     if (BinaryOperator::isFNeg(OpI)) {
01272       Value *InnerTrunc = Builder->CreateFPTrunc(OpI->getOperand(1),
01273                                                  CI.getType());
01274       Instruction *RI = BinaryOperator::CreateFNeg(InnerTrunc);
01275       RI->copyFastMathFlags(OpI);
01276       return RI;
01277     }
01278   }
01279 
01280   // (fptrunc (select cond, R1, Cst)) -->
01281   // (select cond, (fptrunc R1), (fptrunc Cst))
01282   SelectInst *SI = dyn_cast<SelectInst>(CI.getOperand(0));
01283   if (SI &&
01284       (isa<ConstantFP>(SI->getOperand(1)) ||
01285        isa<ConstantFP>(SI->getOperand(2)))) {
01286     Value *LHSTrunc = Builder->CreateFPTrunc(SI->getOperand(1),
01287                                              CI.getType());
01288     Value *RHSTrunc = Builder->CreateFPTrunc(SI->getOperand(2),
01289                                              CI.getType());
01290     return SelectInst::Create(SI->getOperand(0), LHSTrunc, RHSTrunc);
01291   }
01292 
01293   IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI.getOperand(0));
01294   if (II) {
01295     switch (II->getIntrinsicID()) {
01296       default: break;
01297       case Intrinsic::fabs: {
01298         // (fptrunc (fabs x)) -> (fabs (fptrunc x))
01299         Value *InnerTrunc = Builder->CreateFPTrunc(II->getArgOperand(0),
01300                                                    CI.getType());
01301         Type *IntrinsicType[] = { CI.getType() };
01302         Function *Overload =
01303           Intrinsic::getDeclaration(CI.getParent()->getParent()->getParent(),
01304                                     II->getIntrinsicID(), IntrinsicType);
01305 
01306         Value *Args[] = { InnerTrunc };
01307         return CallInst::Create(Overload, Args, II->getName());
01308       }
01309     }
01310   }
01311 
01312   // Fold (fptrunc (sqrt (fpext x))) -> (sqrtf x)
01313   // Note that we restrict this transformation based on
01314   // TLI->has(LibFunc::sqrtf), even for the sqrt intrinsic, because
01315   // TLI->has(LibFunc::sqrtf) is sufficient to guarantee that the
01316   // single-precision intrinsic can be expanded in the backend.
01317   CallInst *Call = dyn_cast<CallInst>(CI.getOperand(0));
01318   if (Call && Call->getCalledFunction() && TLI->has(LibFunc::sqrtf) &&
01319       (Call->getCalledFunction()->getName() == TLI->getName(LibFunc::sqrt) ||
01320        Call->getCalledFunction()->getIntrinsicID() == Intrinsic::sqrt) &&
01321       Call->getNumArgOperands() == 1 &&
01322       Call->hasOneUse()) {
01323     CastInst *Arg = dyn_cast<CastInst>(Call->getArgOperand(0));
01324     if (Arg && Arg->getOpcode() == Instruction::FPExt &&
01325         CI.getType()->isFloatTy() &&
01326         Call->getType()->isDoubleTy() &&
01327         Arg->getType()->isDoubleTy() &&
01328         Arg->getOperand(0)->getType()->isFloatTy()) {
01329       Function *Callee = Call->getCalledFunction();
01330       Module *M = CI.getParent()->getParent()->getParent();
01331       Constant *SqrtfFunc = (Callee->getIntrinsicID() == Intrinsic::sqrt) ?
01332         Intrinsic::getDeclaration(M, Intrinsic::sqrt, Builder->getFloatTy()) :
01333         M->getOrInsertFunction("sqrtf", Callee->getAttributes(),
01334                                Builder->getFloatTy(), Builder->getFloatTy(),
01335                                NULL);
01336       CallInst *ret = CallInst::Create(SqrtfFunc, Arg->getOperand(0),
01337                                        "sqrtfcall");
01338       ret->setAttributes(Callee->getAttributes());
01339 
01340 
01341       // Remove the old Call.  With -fmath-errno, it won't get marked readnone.
01342       ReplaceInstUsesWith(*Call, UndefValue::get(Call->getType()));
01343       EraseInstFromFunction(*Call);
01344       return ret;
01345     }
01346   }
01347 
01348   return 0;
01349 }
01350 
01351 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
01352   return commonCastTransforms(CI);
01353 }
01354 
01355 Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
01356   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
01357   if (OpI == 0)
01358     return commonCastTransforms(FI);
01359 
01360   // fptoui(uitofp(X)) --> X
01361   // fptoui(sitofp(X)) --> X
01362   // This is safe if the intermediate type has enough bits in its mantissa to
01363   // accurately represent all values of X.  For example, do not do this with
01364   // i64->float->i64.  This is also safe for sitofp case, because any negative
01365   // 'X' value would cause an undefined result for the fptoui.
01366   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
01367       OpI->getOperand(0)->getType() == FI.getType() &&
01368       (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
01369                     OpI->getType()->getFPMantissaWidth())
01370     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
01371 
01372   return commonCastTransforms(FI);
01373 }
01374 
01375 Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
01376   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
01377   if (OpI == 0)
01378     return commonCastTransforms(FI);
01379 
01380   // fptosi(sitofp(X)) --> X
01381   // fptosi(uitofp(X)) --> X
01382   // This is safe if the intermediate type has enough bits in its mantissa to
01383   // accurately represent all values of X.  For example, do not do this with
01384   // i64->float->i64.  This is also safe for sitofp case, because any negative
01385   // 'X' value would cause an undefined result for the fptoui.
01386   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
01387       OpI->getOperand(0)->getType() == FI.getType() &&
01388       (int)FI.getType()->getScalarSizeInBits() <=
01389                     OpI->getType()->getFPMantissaWidth())
01390     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
01391 
01392   return commonCastTransforms(FI);
01393 }
01394 
01395 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
01396   return commonCastTransforms(CI);
01397 }
01398 
01399 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
01400   return commonCastTransforms(CI);
01401 }
01402 
01403 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
01404   // If the source integer type is not the intptr_t type for this target, do a
01405   // trunc or zext to the intptr_t type, then inttoptr of it.  This allows the
01406   // cast to be exposed to other transforms.
01407 
01408   if (DL) {
01409     unsigned AS = CI.getAddressSpace();
01410     if (CI.getOperand(0)->getType()->getScalarSizeInBits() !=
01411         DL->getPointerSizeInBits(AS)) {
01412       Type *Ty = DL->getIntPtrType(CI.getContext(), AS);
01413       if (CI.getType()->isVectorTy()) // Handle vectors of pointers.
01414         Ty = VectorType::get(Ty, CI.getType()->getVectorNumElements());
01415 
01416       Value *P = Builder->CreateZExtOrTrunc(CI.getOperand(0), Ty);
01417       return new IntToPtrInst(P, CI.getType());
01418     }
01419   }
01420 
01421   if (Instruction *I = commonCastTransforms(CI))
01422     return I;
01423 
01424   return 0;
01425 }
01426 
01427 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
01428 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
01429   Value *Src = CI.getOperand(0);
01430 
01431   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
01432     // If casting the result of a getelementptr instruction with no offset, turn
01433     // this into a cast of the original pointer!
01434     if (GEP->hasAllZeroIndices()) {
01435       // Changing the cast operand is usually not a good idea but it is safe
01436       // here because the pointer operand is being replaced with another
01437       // pointer operand so the opcode doesn't need to change.
01438       Worklist.Add(GEP);
01439       CI.setOperand(0, GEP->getOperand(0));
01440       return &CI;
01441     }
01442 
01443     if (!DL)
01444       return commonCastTransforms(CI);
01445 
01446     // If the GEP has a single use, and the base pointer is a bitcast, and the
01447     // GEP computes a constant offset, see if we can convert these three
01448     // instructions into fewer.  This typically happens with unions and other
01449     // non-type-safe code.
01450     unsigned AS = GEP->getPointerAddressSpace();
01451     unsigned OffsetBits = DL->getPointerSizeInBits(AS);
01452     APInt Offset(OffsetBits, 0);
01453     BitCastInst *BCI = dyn_cast<BitCastInst>(GEP->getOperand(0));
01454     if (GEP->hasOneUse() &&
01455         BCI &&
01456         GEP->accumulateConstantOffset(*DL, Offset)) {
01457       // Get the base pointer input of the bitcast, and the type it points to.
01458       Value *OrigBase = BCI->getOperand(0);
01459       SmallVector<Value*, 8> NewIndices;
01460       if (FindElementAtOffset(OrigBase->getType(),
01461                               Offset.getSExtValue(),
01462                               NewIndices)) {
01463         // If we were able to index down into an element, create the GEP
01464         // and bitcast the result.  This eliminates one bitcast, potentially
01465         // two.
01466         Value *NGEP = cast<GEPOperator>(GEP)->isInBounds() ?
01467           Builder->CreateInBoundsGEP(OrigBase, NewIndices) :
01468           Builder->CreateGEP(OrigBase, NewIndices);
01469         NGEP->takeName(GEP);
01470 
01471         if (isa<BitCastInst>(CI))
01472           return new BitCastInst(NGEP, CI.getType());
01473         assert(isa<PtrToIntInst>(CI));
01474         return new PtrToIntInst(NGEP, CI.getType());
01475       }
01476     }
01477   }
01478 
01479   return commonCastTransforms(CI);
01480 }
01481 
01482 Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
01483   // If the destination integer type is not the intptr_t type for this target,
01484   // do a ptrtoint to intptr_t then do a trunc or zext.  This allows the cast
01485   // to be exposed to other transforms.
01486 
01487   if (!DL)
01488     return commonPointerCastTransforms(CI);
01489 
01490   Type *Ty = CI.getType();
01491   unsigned AS = CI.getPointerAddressSpace();
01492 
01493   if (Ty->getScalarSizeInBits() == DL->getPointerSizeInBits(AS))
01494     return commonPointerCastTransforms(CI);
01495 
01496   Type *PtrTy = DL->getIntPtrType(CI.getContext(), AS);
01497   if (Ty->isVectorTy()) // Handle vectors of pointers.
01498     PtrTy = VectorType::get(PtrTy, Ty->getVectorNumElements());
01499 
01500   Value *P = Builder->CreatePtrToInt(CI.getOperand(0), PtrTy);
01501   return CastInst::CreateIntegerCast(P, Ty, /*isSigned=*/false);
01502 }
01503 
01504 /// OptimizeVectorResize - This input value (which is known to have vector type)
01505 /// is being zero extended or truncated to the specified vector type.  Try to
01506 /// replace it with a shuffle (and vector/vector bitcast) if possible.
01507 ///
01508 /// The source and destination vector types may have different element types.
01509 static Instruction *OptimizeVectorResize(Value *InVal, VectorType *DestTy,
01510                                          InstCombiner &IC) {
01511   // We can only do this optimization if the output is a multiple of the input
01512   // element size, or the input is a multiple of the output element size.
01513   // Convert the input type to have the same element type as the output.
01514   VectorType *SrcTy = cast<VectorType>(InVal->getType());
01515 
01516   if (SrcTy->getElementType() != DestTy->getElementType()) {
01517     // The input types don't need to be identical, but for now they must be the
01518     // same size.  There is no specific reason we couldn't handle things like
01519     // <4 x i16> -> <4 x i32> by bitcasting to <2 x i32> but haven't gotten
01520     // there yet.
01521     if (SrcTy->getElementType()->getPrimitiveSizeInBits() !=
01522         DestTy->getElementType()->getPrimitiveSizeInBits())
01523       return 0;
01524 
01525     SrcTy = VectorType::get(DestTy->getElementType(), SrcTy->getNumElements());
01526     InVal = IC.Builder->CreateBitCast(InVal, SrcTy);
01527   }
01528 
01529   // Now that the element types match, get the shuffle mask and RHS of the
01530   // shuffle to use, which depends on whether we're increasing or decreasing the
01531   // size of the input.
01532   SmallVector<uint32_t, 16> ShuffleMask;
01533   Value *V2;
01534 
01535   if (SrcTy->getNumElements() > DestTy->getNumElements()) {
01536     // If we're shrinking the number of elements, just shuffle in the low
01537     // elements from the input and use undef as the second shuffle input.
01538     V2 = UndefValue::get(SrcTy);
01539     for (unsigned i = 0, e = DestTy->getNumElements(); i != e; ++i)
01540       ShuffleMask.push_back(i);
01541 
01542   } else {
01543     // If we're increasing the number of elements, shuffle in all of the
01544     // elements from InVal and fill the rest of the result elements with zeros
01545     // from a constant zero.
01546     V2 = Constant::getNullValue(SrcTy);
01547     unsigned SrcElts = SrcTy->getNumElements();
01548     for (unsigned i = 0, e = SrcElts; i != e; ++i)
01549       ShuffleMask.push_back(i);
01550 
01551     // The excess elements reference the first element of the zero input.
01552     for (unsigned i = 0, e = DestTy->getNumElements()-SrcElts; i != e; ++i)
01553       ShuffleMask.push_back(SrcElts);
01554   }
01555 
01556   return new ShuffleVectorInst(InVal, V2,
01557                                ConstantDataVector::get(V2->getContext(),
01558                                                        ShuffleMask));
01559 }
01560 
01561 static bool isMultipleOfTypeSize(unsigned Value, Type *Ty) {
01562   return Value % Ty->getPrimitiveSizeInBits() == 0;
01563 }
01564 
01565 static unsigned getTypeSizeIndex(unsigned Value, Type *Ty) {
01566   return Value / Ty->getPrimitiveSizeInBits();
01567 }
01568 
01569 /// CollectInsertionElements - V is a value which is inserted into a vector of
01570 /// VecEltTy.  Look through the value to see if we can decompose it into
01571 /// insertions into the vector.  See the example in the comment for
01572 /// OptimizeIntegerToVectorInsertions for the pattern this handles.
01573 /// The type of V is always a non-zero multiple of VecEltTy's size.
01574 /// Shift is the number of bits between the lsb of V and the lsb of
01575 /// the vector.
01576 ///
01577 /// This returns false if the pattern can't be matched or true if it can,
01578 /// filling in Elements with the elements found here.
01579 static bool CollectInsertionElements(Value *V, unsigned Shift,
01580                                      SmallVectorImpl<Value*> &Elements,
01581                                      Type *VecEltTy, InstCombiner &IC) {
01582   assert(isMultipleOfTypeSize(Shift, VecEltTy) &&
01583          "Shift should be a multiple of the element type size");
01584 
01585   // Undef values never contribute useful bits to the result.
01586   if (isa<UndefValue>(V)) return true;
01587 
01588   // If we got down to a value of the right type, we win, try inserting into the
01589   // right element.
01590   if (V->getType() == VecEltTy) {
01591     // Inserting null doesn't actually insert any elements.
01592     if (Constant *C = dyn_cast<Constant>(V))
01593       if (C->isNullValue())
01594         return true;
01595 
01596     unsigned ElementIndex = getTypeSizeIndex(Shift, VecEltTy);
01597     if (IC.getDataLayout()->isBigEndian())
01598       ElementIndex = Elements.size() - ElementIndex - 1;
01599 
01600     // Fail if multiple elements are inserted into this slot.
01601     if (Elements[ElementIndex] != 0)
01602       return false;
01603 
01604     Elements[ElementIndex] = V;
01605     return true;
01606   }
01607 
01608   if (Constant *C = dyn_cast<Constant>(V)) {
01609     // Figure out the # elements this provides, and bitcast it or slice it up
01610     // as required.
01611     unsigned NumElts = getTypeSizeIndex(C->getType()->getPrimitiveSizeInBits(),
01612                                         VecEltTy);
01613     // If the constant is the size of a vector element, we just need to bitcast
01614     // it to the right type so it gets properly inserted.
01615     if (NumElts == 1)
01616       return CollectInsertionElements(ConstantExpr::getBitCast(C, VecEltTy),
01617                                       Shift, Elements, VecEltTy, IC);
01618 
01619     // Okay, this is a constant that covers multiple elements.  Slice it up into
01620     // pieces and insert each element-sized piece into the vector.
01621     if (!isa<IntegerType>(C->getType()))
01622       C = ConstantExpr::getBitCast(C, IntegerType::get(V->getContext(),
01623                                        C->getType()->getPrimitiveSizeInBits()));
01624     unsigned ElementSize = VecEltTy->getPrimitiveSizeInBits();
01625     Type *ElementIntTy = IntegerType::get(C->getContext(), ElementSize);
01626 
01627     for (unsigned i = 0; i != NumElts; ++i) {
01628       unsigned ShiftI = Shift+i*ElementSize;
01629       Constant *Piece = ConstantExpr::getLShr(C, ConstantInt::get(C->getType(),
01630                                                                   ShiftI));
01631       Piece = ConstantExpr::getTrunc(Piece, ElementIntTy);
01632       if (!CollectInsertionElements(Piece, ShiftI, Elements, VecEltTy, IC))
01633         return false;
01634     }
01635     return true;
01636   }
01637 
01638   if (!V->hasOneUse()) return false;
01639 
01640   Instruction *I = dyn_cast<Instruction>(V);
01641   if (I == 0) return false;
01642   switch (I->getOpcode()) {
01643   default: return false; // Unhandled case.
01644   case Instruction::BitCast:
01645     return CollectInsertionElements(I->getOperand(0), Shift,
01646                                     Elements, VecEltTy, IC);
01647   case Instruction::ZExt:
01648     if (!isMultipleOfTypeSize(
01649                           I->getOperand(0)->getType()->getPrimitiveSizeInBits(),
01650                               VecEltTy))
01651       return false;
01652     return CollectInsertionElements(I->getOperand(0), Shift,
01653                                     Elements, VecEltTy, IC);
01654   case Instruction::Or:
01655     return CollectInsertionElements(I->getOperand(0), Shift,
01656                                     Elements, VecEltTy, IC) &&
01657            CollectInsertionElements(I->getOperand(1), Shift,
01658                                     Elements, VecEltTy, IC);
01659   case Instruction::Shl: {
01660     // Must be shifting by a constant that is a multiple of the element size.
01661     ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1));
01662     if (CI == 0) return false;
01663     Shift += CI->getZExtValue();
01664     if (!isMultipleOfTypeSize(Shift, VecEltTy)) return false;
01665     return CollectInsertionElements(I->getOperand(0), Shift,
01666                                     Elements, VecEltTy, IC);
01667   }
01668 
01669   }
01670 }
01671 
01672 
01673 /// OptimizeIntegerToVectorInsertions - If the input is an 'or' instruction, we
01674 /// may be doing shifts and ors to assemble the elements of the vector manually.
01675 /// Try to rip the code out and replace it with insertelements.  This is to
01676 /// optimize code like this:
01677 ///
01678 ///    %tmp37 = bitcast float %inc to i32
01679 ///    %tmp38 = zext i32 %tmp37 to i64
01680 ///    %tmp31 = bitcast float %inc5 to i32
01681 ///    %tmp32 = zext i32 %tmp31 to i64
01682 ///    %tmp33 = shl i64 %tmp32, 32
01683 ///    %ins35 = or i64 %tmp33, %tmp38
01684 ///    %tmp43 = bitcast i64 %ins35 to <2 x float>
01685 ///
01686 /// Into two insertelements that do "buildvector{%inc, %inc5}".
01687 static Value *OptimizeIntegerToVectorInsertions(BitCastInst &CI,
01688                                                 InstCombiner &IC) {
01689   // We need to know the target byte order to perform this optimization.
01690   if (!IC.getDataLayout()) return 0;
01691 
01692   VectorType *DestVecTy = cast<VectorType>(CI.getType());
01693   Value *IntInput = CI.getOperand(0);
01694 
01695   SmallVector<Value*, 8> Elements(DestVecTy->getNumElements());
01696   if (!CollectInsertionElements(IntInput, 0, Elements,
01697                                 DestVecTy->getElementType(), IC))
01698     return 0;
01699 
01700   // If we succeeded, we know that all of the element are specified by Elements
01701   // or are zero if Elements has a null entry.  Recast this as a set of
01702   // insertions.
01703   Value *Result = Constant::getNullValue(CI.getType());
01704   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
01705     if (Elements[i] == 0) continue;  // Unset element.
01706 
01707     Result = IC.Builder->CreateInsertElement(Result, Elements[i],
01708                                              IC.Builder->getInt32(i));
01709   }
01710 
01711   return Result;
01712 }
01713 
01714 
01715 /// OptimizeIntToFloatBitCast - See if we can optimize an integer->float/double
01716 /// bitcast.  The various long double bitcasts can't get in here.
01717 static Instruction *OptimizeIntToFloatBitCast(BitCastInst &CI,InstCombiner &IC){
01718   // We need to know the target byte order to perform this optimization.
01719   if (!IC.getDataLayout()) return 0;
01720 
01721   Value *Src = CI.getOperand(0);
01722   Type *DestTy = CI.getType();
01723 
01724   // If this is a bitcast from int to float, check to see if the int is an
01725   // extraction from a vector.
01726   Value *VecInput = 0;
01727   // bitcast(trunc(bitcast(somevector)))
01728   if (match(Src, m_Trunc(m_BitCast(m_Value(VecInput)))) &&
01729       isa<VectorType>(VecInput->getType())) {
01730     VectorType *VecTy = cast<VectorType>(VecInput->getType());
01731     unsigned DestWidth = DestTy->getPrimitiveSizeInBits();
01732 
01733     if (VecTy->getPrimitiveSizeInBits() % DestWidth == 0) {
01734       // If the element type of the vector doesn't match the result type,
01735       // bitcast it to be a vector type we can extract from.
01736       if (VecTy->getElementType() != DestTy) {
01737         VecTy = VectorType::get(DestTy,
01738                                 VecTy->getPrimitiveSizeInBits() / DestWidth);
01739         VecInput = IC.Builder->CreateBitCast(VecInput, VecTy);
01740       }
01741 
01742       unsigned Elt = 0;
01743       if (IC.getDataLayout()->isBigEndian())
01744         Elt = VecTy->getPrimitiveSizeInBits() / DestWidth - 1;
01745       return ExtractElementInst::Create(VecInput, IC.Builder->getInt32(Elt));
01746     }
01747   }
01748 
01749   // bitcast(trunc(lshr(bitcast(somevector), cst))
01750   ConstantInt *ShAmt = 0;
01751   if (match(Src, m_Trunc(m_LShr(m_BitCast(m_Value(VecInput)),
01752                                 m_ConstantInt(ShAmt)))) &&
01753       isa<VectorType>(VecInput->getType())) {
01754     VectorType *VecTy = cast<VectorType>(VecInput->getType());
01755     unsigned DestWidth = DestTy->getPrimitiveSizeInBits();
01756     if (VecTy->getPrimitiveSizeInBits() % DestWidth == 0 &&
01757         ShAmt->getZExtValue() % DestWidth == 0) {
01758       // If the element type of the vector doesn't match the result type,
01759       // bitcast it to be a vector type we can extract from.
01760       if (VecTy->getElementType() != DestTy) {
01761         VecTy = VectorType::get(DestTy,
01762                                 VecTy->getPrimitiveSizeInBits() / DestWidth);
01763         VecInput = IC.Builder->CreateBitCast(VecInput, VecTy);
01764       }
01765 
01766       unsigned Elt = ShAmt->getZExtValue() / DestWidth;
01767       if (IC.getDataLayout()->isBigEndian())
01768         Elt = VecTy->getPrimitiveSizeInBits() / DestWidth - 1 - Elt;
01769       return ExtractElementInst::Create(VecInput, IC.Builder->getInt32(Elt));
01770     }
01771   }
01772   return 0;
01773 }
01774 
01775 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
01776   // If the operands are integer typed then apply the integer transforms,
01777   // otherwise just apply the common ones.
01778   Value *Src = CI.getOperand(0);
01779   Type *SrcTy = Src->getType();
01780   Type *DestTy = CI.getType();
01781 
01782   // Get rid of casts from one type to the same type. These are useless and can
01783   // be replaced by the operand.
01784   if (DestTy == Src->getType())
01785     return ReplaceInstUsesWith(CI, Src);
01786 
01787   if (PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
01788     PointerType *SrcPTy = cast<PointerType>(SrcTy);
01789     Type *DstElTy = DstPTy->getElementType();
01790     Type *SrcElTy = SrcPTy->getElementType();
01791 
01792     // If we are casting a alloca to a pointer to a type of the same
01793     // size, rewrite the allocation instruction to allocate the "right" type.
01794     // There is no need to modify malloc calls because it is their bitcast that
01795     // needs to be cleaned up.
01796     if (AllocaInst *AI = dyn_cast<AllocaInst>(Src))
01797       if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
01798         return V;
01799 
01800     // If the source and destination are pointers, and this cast is equivalent
01801     // to a getelementptr X, 0, 0, 0...  turn it into the appropriate gep.
01802     // This can enhance SROA and other transforms that want type-safe pointers.
01803     Constant *ZeroUInt =
01804       Constant::getNullValue(Type::getInt32Ty(CI.getContext()));
01805     unsigned NumZeros = 0;
01806     while (SrcElTy != DstElTy &&
01807            isa<CompositeType>(SrcElTy) && !SrcElTy->isPointerTy() &&
01808            SrcElTy->getNumContainedTypes() /* not "{}" */) {
01809       SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
01810       ++NumZeros;
01811     }
01812 
01813     // If we found a path from the src to dest, create the getelementptr now.
01814     if (SrcElTy == DstElTy) {
01815       SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
01816       return GetElementPtrInst::CreateInBounds(Src, Idxs);
01817     }
01818   }
01819 
01820   // Try to optimize int -> float bitcasts.
01821   if ((DestTy->isFloatTy() || DestTy->isDoubleTy()) && isa<IntegerType>(SrcTy))
01822     if (Instruction *I = OptimizeIntToFloatBitCast(CI, *this))
01823       return I;
01824 
01825   if (VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
01826     if (DestVTy->getNumElements() == 1 && !SrcTy->isVectorTy()) {
01827       Value *Elem = Builder->CreateBitCast(Src, DestVTy->getElementType());
01828       return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
01829                      Constant::getNullValue(Type::getInt32Ty(CI.getContext())));
01830       // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
01831     }
01832 
01833     if (isa<IntegerType>(SrcTy)) {
01834       // If this is a cast from an integer to vector, check to see if the input
01835       // is a trunc or zext of a bitcast from vector.  If so, we can replace all
01836       // the casts with a shuffle and (potentially) a bitcast.
01837       if (isa<TruncInst>(Src) || isa<ZExtInst>(Src)) {
01838         CastInst *SrcCast = cast<CastInst>(Src);
01839         if (BitCastInst *BCIn = dyn_cast<BitCastInst>(SrcCast->getOperand(0)))
01840           if (isa<VectorType>(BCIn->getOperand(0)->getType()))
01841             if (Instruction *I = OptimizeVectorResize(BCIn->getOperand(0),
01842                                                cast<VectorType>(DestTy), *this))
01843               return I;
01844       }
01845 
01846       // If the input is an 'or' instruction, we may be doing shifts and ors to
01847       // assemble the elements of the vector manually.  Try to rip the code out
01848       // and replace it with insertelements.
01849       if (Value *V = OptimizeIntegerToVectorInsertions(CI, *this))
01850         return ReplaceInstUsesWith(CI, V);
01851     }
01852   }
01853 
01854   if (VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
01855     if (SrcVTy->getNumElements() == 1) {
01856       // If our destination is not a vector, then make this a straight
01857       // scalar-scalar cast.
01858       if (!DestTy->isVectorTy()) {
01859         Value *Elem =
01860           Builder->CreateExtractElement(Src,
01861                      Constant::getNullValue(Type::getInt32Ty(CI.getContext())));
01862         return CastInst::Create(Instruction::BitCast, Elem, DestTy);
01863       }
01864 
01865       // Otherwise, see if our source is an insert. If so, then use the scalar
01866       // component directly.
01867       if (InsertElementInst *IEI =
01868             dyn_cast<InsertElementInst>(CI.getOperand(0)))
01869         return CastInst::Create(Instruction::BitCast, IEI->getOperand(1),
01870                                 DestTy);
01871     }
01872   }
01873 
01874   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
01875     // Okay, we have (bitcast (shuffle ..)).  Check to see if this is
01876     // a bitcast to a vector with the same # elts.
01877     if (SVI->hasOneUse() && DestTy->isVectorTy() &&
01878         DestTy->getVectorNumElements() == SVI->getType()->getNumElements() &&
01879         SVI->getType()->getNumElements() ==
01880         SVI->getOperand(0)->getType()->getVectorNumElements()) {
01881       BitCastInst *Tmp;
01882       // If either of the operands is a cast from CI.getType(), then
01883       // evaluating the shuffle in the casted destination's type will allow
01884       // us to eliminate at least one cast.
01885       if (((Tmp = dyn_cast<BitCastInst>(SVI->getOperand(0))) &&
01886            Tmp->getOperand(0)->getType() == DestTy) ||
01887           ((Tmp = dyn_cast<BitCastInst>(SVI->getOperand(1))) &&
01888            Tmp->getOperand(0)->getType() == DestTy)) {
01889         Value *LHS = Builder->CreateBitCast(SVI->getOperand(0), DestTy);
01890         Value *RHS = Builder->CreateBitCast(SVI->getOperand(1), DestTy);
01891         // Return a new shuffle vector.  Use the same element ID's, as we
01892         // know the vector types match #elts.
01893         return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
01894       }
01895     }
01896   }
01897 
01898   if (SrcTy->isPointerTy())
01899     return commonPointerCastTransforms(CI);
01900   return commonCastTransforms(CI);
01901 }
01902 
01903 Instruction *InstCombiner::visitAddrSpaceCast(AddrSpaceCastInst &CI) {
01904   return commonPointerCastTransforms(CI);
01905 }