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