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