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   if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
00904     // (x <s  0) ? -1 : 0 -> ashr x, 31        -> all ones if negative
00905     // (x >s -1) ? -1 : 0 -> not (ashr x, 31)  -> all ones if positive
00906     if ((Pred == ICmpInst::ICMP_SLT && Op1C->isNullValue()) ||
00907         (Pred == ICmpInst::ICMP_SGT && Op1C->isAllOnesValue())) {
00908 
00909       Value *Sh = ConstantInt::get(Op0->getType(),
00910                                    Op0->getType()->getScalarSizeInBits()-1);
00911       Value *In = Builder->CreateAShr(Op0, Sh, Op0->getName()+".lobit");
00912       if (In->getType() != CI.getType())
00913         In = Builder->CreateIntCast(In, CI.getType(), true/*SExt*/);
00914 
00915       if (Pred == ICmpInst::ICMP_SGT)
00916         In = Builder->CreateNot(In, In->getName()+".not");
00917       return ReplaceInstUsesWith(CI, In);
00918     }
00919   }
00920 
00921   if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
00922     // If we know that only one bit of the LHS of the icmp can be set and we
00923     // have an equality comparison with zero or a power of 2, we can transform
00924     // the icmp and sext into bitwise/integer operations.
00925     if (ICI->hasOneUse() &&
00926         ICI->isEquality() && (Op1C->isZero() || Op1C->getValue().isPowerOf2())){
00927       unsigned BitWidth = Op1C->getType()->getBitWidth();
00928       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
00929       computeKnownBits(Op0, KnownZero, KnownOne, 0, &CI);
00930 
00931       APInt KnownZeroMask(~KnownZero);
00932       if (KnownZeroMask.isPowerOf2()) {
00933         Value *In = ICI->getOperand(0);
00934 
00935         // If the icmp tests for a known zero bit we can constant fold it.
00936         if (!Op1C->isZero() && Op1C->getValue() != KnownZeroMask) {
00937           Value *V = Pred == ICmpInst::ICMP_NE ?
00938                        ConstantInt::getAllOnesValue(CI.getType()) :
00939                        ConstantInt::getNullValue(CI.getType());
00940           return ReplaceInstUsesWith(CI, V);
00941         }
00942 
00943         if (!Op1C->isZero() == (Pred == ICmpInst::ICMP_NE)) {
00944           // sext ((x & 2^n) == 0)   -> (x >> n) - 1
00945           // sext ((x & 2^n) != 2^n) -> (x >> n) - 1
00946           unsigned ShiftAmt = KnownZeroMask.countTrailingZeros();
00947           // Perform a right shift to place the desired bit in the LSB.
00948           if (ShiftAmt)
00949             In = Builder->CreateLShr(In,
00950                                      ConstantInt::get(In->getType(), ShiftAmt));
00951 
00952           // At this point "In" is either 1 or 0. Subtract 1 to turn
00953           // {1, 0} -> {0, -1}.
00954           In = Builder->CreateAdd(In,
00955                                   ConstantInt::getAllOnesValue(In->getType()),
00956                                   "sext");
00957         } else {
00958           // sext ((x & 2^n) != 0)   -> (x << bitwidth-n) a>> bitwidth-1
00959           // sext ((x & 2^n) == 2^n) -> (x << bitwidth-n) a>> bitwidth-1
00960           unsigned ShiftAmt = KnownZeroMask.countLeadingZeros();
00961           // Perform a left shift to place the desired bit in the MSB.
00962           if (ShiftAmt)
00963             In = Builder->CreateShl(In,
00964                                     ConstantInt::get(In->getType(), ShiftAmt));
00965 
00966           // Distribute the bit over the whole bit width.
00967           In = Builder->CreateAShr(In, ConstantInt::get(In->getType(),
00968                                                         BitWidth - 1), "sext");
00969         }
00970 
00971         if (CI.getType() == In->getType())
00972           return ReplaceInstUsesWith(CI, In);
00973         return CastInst::CreateIntegerCast(In, CI.getType(), true/*SExt*/);
00974       }
00975     }
00976   }
00977 
00978   return nullptr;
00979 }
00980 
00981 /// CanEvaluateSExtd - Return true if we can take the specified value
00982 /// and return it as type Ty without inserting any new casts and without
00983 /// changing the value of the common low bits.  This is used by code that tries
00984 /// to promote integer operations to a wider types will allow us to eliminate
00985 /// the extension.
00986 ///
00987 /// This function works on both vectors and scalars.
00988 ///
00989 static bool CanEvaluateSExtd(Value *V, Type *Ty) {
00990   assert(V->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits() &&
00991          "Can't sign extend type to a smaller type");
00992   // If this is a constant, it can be trivially promoted.
00993   if (isa<Constant>(V))
00994     return true;
00995 
00996   Instruction *I = dyn_cast<Instruction>(V);
00997   if (!I) return false;
00998 
00999   // If this is a truncate from the dest type, we can trivially eliminate it.
01000   if (isa<TruncInst>(I) && I->getOperand(0)->getType() == Ty)
01001     return true;
01002 
01003   // We can't extend or shrink something that has multiple uses: doing so would
01004   // require duplicating the instruction in general, which isn't profitable.
01005   if (!I->hasOneUse()) return false;
01006 
01007   switch (I->getOpcode()) {
01008   case Instruction::SExt:  // sext(sext(x)) -> sext(x)
01009   case Instruction::ZExt:  // sext(zext(x)) -> zext(x)
01010   case Instruction::Trunc: // sext(trunc(x)) -> trunc(x) or sext(x)
01011     return true;
01012   case Instruction::And:
01013   case Instruction::Or:
01014   case Instruction::Xor:
01015   case Instruction::Add:
01016   case Instruction::Sub:
01017   case Instruction::Mul:
01018     // These operators can all arbitrarily be extended if their inputs can.
01019     return CanEvaluateSExtd(I->getOperand(0), Ty) &&
01020            CanEvaluateSExtd(I->getOperand(1), Ty);
01021 
01022   //case Instruction::Shl:   TODO
01023   //case Instruction::LShr:  TODO
01024 
01025   case Instruction::Select:
01026     return CanEvaluateSExtd(I->getOperand(1), Ty) &&
01027            CanEvaluateSExtd(I->getOperand(2), Ty);
01028 
01029   case Instruction::PHI: {
01030     // We can change a phi if we can change all operands.  Note that we never
01031     // get into trouble with cyclic PHIs here because we only consider
01032     // instructions with a single use.
01033     PHINode *PN = cast<PHINode>(I);
01034     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
01035       if (!CanEvaluateSExtd(PN->getIncomingValue(i), Ty)) return false;
01036     return true;
01037   }
01038   default:
01039     // TODO: Can handle more cases here.
01040     break;
01041   }
01042 
01043   return false;
01044 }
01045 
01046 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
01047   // If this sign extend is only used by a truncate, let the truncate be
01048   // eliminated before we try to optimize this sext.
01049   if (CI.hasOneUse() && isa<TruncInst>(CI.user_back()))
01050     return nullptr;
01051 
01052   if (Instruction *I = commonCastTransforms(CI))
01053     return I;
01054 
01055   // See if we can simplify any instructions used by the input whose sole
01056   // purpose is to compute bits we don't care about.
01057   if (SimplifyDemandedInstructionBits(CI))
01058     return &CI;
01059 
01060   Value *Src = CI.getOperand(0);
01061   Type *SrcTy = Src->getType(), *DestTy = CI.getType();
01062 
01063   // Attempt to extend the entire input expression tree to the destination
01064   // type.   Only do this if the dest type is a simple type, don't convert the
01065   // expression tree to something weird like i93 unless the source is also
01066   // strange.
01067   if ((DestTy->isVectorTy() || ShouldChangeType(SrcTy, DestTy)) &&
01068       CanEvaluateSExtd(Src, DestTy)) {
01069     // Okay, we can transform this!  Insert the new expression now.
01070     DEBUG(dbgs() << "ICE: EvaluateInDifferentType converting expression type"
01071           " to avoid sign extend: " << CI);
01072     Value *Res = EvaluateInDifferentType(Src, DestTy, true);
01073     assert(Res->getType() == DestTy);
01074 
01075     uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
01076     uint32_t DestBitSize = DestTy->getScalarSizeInBits();
01077 
01078     // If the high bits are already filled with sign bit, just replace this
01079     // cast with the result.
01080     if (ComputeNumSignBits(Res, 0, &CI) > DestBitSize - SrcBitSize)
01081       return ReplaceInstUsesWith(CI, Res);
01082 
01083     // We need to emit a shl + ashr to do the sign extend.
01084     Value *ShAmt = ConstantInt::get(DestTy, DestBitSize-SrcBitSize);
01085     return BinaryOperator::CreateAShr(Builder->CreateShl(Res, ShAmt, "sext"),
01086                                       ShAmt);
01087   }
01088 
01089   // If this input is a trunc from our destination, then turn sext(trunc(x))
01090   // into shifts.
01091   if (TruncInst *TI = dyn_cast<TruncInst>(Src))
01092     if (TI->hasOneUse() && TI->getOperand(0)->getType() == DestTy) {
01093       uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
01094       uint32_t DestBitSize = DestTy->getScalarSizeInBits();
01095 
01096       // We need to emit a shl + ashr to do the sign extend.
01097       Value *ShAmt = ConstantInt::get(DestTy, DestBitSize-SrcBitSize);
01098       Value *Res = Builder->CreateShl(TI->getOperand(0), ShAmt, "sext");
01099       return BinaryOperator::CreateAShr(Res, ShAmt);
01100     }
01101 
01102   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
01103     return transformSExtICmp(ICI, CI);
01104 
01105   // If the input is a shl/ashr pair of a same constant, then this is a sign
01106   // extension from a smaller value.  If we could trust arbitrary bitwidth
01107   // integers, we could turn this into a truncate to the smaller bit and then
01108   // use a sext for the whole extension.  Since we don't, look deeper and check
01109   // for a truncate.  If the source and dest are the same type, eliminate the
01110   // trunc and extend and just do shifts.  For example, turn:
01111   //   %a = trunc i32 %i to i8
01112   //   %b = shl i8 %a, 6
01113   //   %c = ashr i8 %b, 6
01114   //   %d = sext i8 %c to i32
01115   // into:
01116   //   %a = shl i32 %i, 30
01117   //   %d = ashr i32 %a, 30
01118   Value *A = nullptr;
01119   // TODO: Eventually this could be subsumed by EvaluateInDifferentType.
01120   ConstantInt *BA = nullptr, *CA = nullptr;
01121   if (match(Src, m_AShr(m_Shl(m_Trunc(m_Value(A)), m_ConstantInt(BA)),
01122                         m_ConstantInt(CA))) &&
01123       BA == CA && A->getType() == CI.getType()) {
01124     unsigned MidSize = Src->getType()->getScalarSizeInBits();
01125     unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
01126     unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
01127     Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
01128     A = Builder->CreateShl(A, ShAmtV, CI.getName());
01129     return BinaryOperator::CreateAShr(A, ShAmtV);
01130   }
01131 
01132   return nullptr;
01133 }
01134 
01135 
01136 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
01137 /// in the specified FP type without changing its value.
01138 static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
01139   bool losesInfo;
01140   APFloat F = CFP->getValueAPF();
01141   (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
01142   if (!losesInfo)
01143     return ConstantFP::get(CFP->getContext(), F);
01144   return nullptr;
01145 }
01146 
01147 /// LookThroughFPExtensions - If this is an fp extension instruction, look
01148 /// through it until we get the source value.
01149 static Value *LookThroughFPExtensions(Value *V) {
01150   if (Instruction *I = dyn_cast<Instruction>(V))
01151     if (I->getOpcode() == Instruction::FPExt)
01152       return LookThroughFPExtensions(I->getOperand(0));
01153 
01154   // If this value is a constant, return the constant in the smallest FP type
01155   // that can accurately represent it.  This allows us to turn
01156   // (float)((double)X+2.0) into x+2.0f.
01157   if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
01158     if (CFP->getType() == Type::getPPC_FP128Ty(V->getContext()))
01159       return V;  // No constant folding of this.
01160     // See if the value can be truncated to half and then reextended.
01161     if (Value *V = FitsInFPType(CFP, APFloat::IEEEhalf))
01162       return V;
01163     // See if the value can be truncated to float and then reextended.
01164     if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
01165       return V;
01166     if (CFP->getType()->isDoubleTy())
01167       return V;  // Won't shrink.
01168     if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
01169       return V;
01170     // Don't try to shrink to various long double types.
01171   }
01172 
01173   return V;
01174 }
01175 
01176 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
01177   if (Instruction *I = commonCastTransforms(CI))
01178     return I;
01179   // If we have fptrunc(OpI (fpextend x), (fpextend y)), we would like to
01180   // simpilify this expression to avoid one or more of the trunc/extend
01181   // operations if we can do so without changing the numerical results.
01182   //
01183   // The exact manner in which the widths of the operands interact to limit
01184   // what we can and cannot do safely varies from operation to operation, and
01185   // is explained below in the various case statements.
01186   BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
01187   if (OpI && OpI->hasOneUse()) {
01188     Value *LHSOrig = LookThroughFPExtensions(OpI->getOperand(0));
01189     Value *RHSOrig = LookThroughFPExtensions(OpI->getOperand(1));
01190     unsigned OpWidth = OpI->getType()->getFPMantissaWidth();
01191     unsigned LHSWidth = LHSOrig->getType()->getFPMantissaWidth();
01192     unsigned RHSWidth = RHSOrig->getType()->getFPMantissaWidth();
01193     unsigned SrcWidth = std::max(LHSWidth, RHSWidth);
01194     unsigned DstWidth = CI.getType()->getFPMantissaWidth();
01195     switch (OpI->getOpcode()) {
01196       default: break;
01197       case Instruction::FAdd:
01198       case Instruction::FSub:
01199         // For addition and subtraction, the infinitely precise result can
01200         // essentially be arbitrarily wide; proving that double rounding
01201         // will not occur because the result of OpI is exact (as we will for
01202         // FMul, for example) is hopeless.  However, we *can* nonetheless
01203         // frequently know that double rounding cannot occur (or that it is
01204         // innocuous) by taking advantage of the specific structure of
01205         // infinitely-precise results that admit double rounding.
01206         //
01207         // Specifically, if OpWidth >= 2*DstWdith+1 and DstWidth is sufficient
01208         // to represent both sources, we can guarantee that the double
01209         // rounding is innocuous (See p50 of Figueroa's 2000 PhD thesis,
01210         // "A Rigorous Framework for Fully Supporting the IEEE Standard ..."
01211         // for proof of this fact).
01212         //
01213         // Note: Figueroa does not consider the case where DstFormat !=
01214         // SrcFormat.  It's possible (likely even!) that this analysis
01215         // could be tightened for those cases, but they are rare (the main
01216         // case of interest here is (float)((double)float + float)).
01217         if (OpWidth >= 2*DstWidth+1 && DstWidth >= SrcWidth) {
01218           if (LHSOrig->getType() != CI.getType())
01219             LHSOrig = Builder->CreateFPExt(LHSOrig, CI.getType());
01220           if (RHSOrig->getType() != CI.getType())
01221             RHSOrig = Builder->CreateFPExt(RHSOrig, CI.getType());
01222           Instruction *RI =
01223             BinaryOperator::Create(OpI->getOpcode(), LHSOrig, RHSOrig);
01224           RI->copyFastMathFlags(OpI);
01225           return RI;
01226         }
01227         break;
01228       case Instruction::FMul:
01229         // For multiplication, the infinitely precise result has at most
01230         // LHSWidth + RHSWidth significant bits; if OpWidth is sufficient
01231         // that such a value can be exactly represented, then no double
01232         // rounding can possibly occur; we can safely perform the operation
01233         // in the destination format if it can represent both sources.
01234         if (OpWidth >= LHSWidth + RHSWidth && DstWidth >= SrcWidth) {
01235           if (LHSOrig->getType() != CI.getType())
01236             LHSOrig = Builder->CreateFPExt(LHSOrig, CI.getType());
01237           if (RHSOrig->getType() != CI.getType())
01238             RHSOrig = Builder->CreateFPExt(RHSOrig, CI.getType());
01239           Instruction *RI =
01240             BinaryOperator::CreateFMul(LHSOrig, RHSOrig);
01241           RI->copyFastMathFlags(OpI);
01242           return RI;
01243         }
01244         break;
01245       case Instruction::FDiv:
01246         // For division, we use again use the bound from Figueroa's
01247         // dissertation.  I am entirely certain that this bound can be
01248         // tightened in the unbalanced operand case by an analysis based on
01249         // the diophantine rational approximation bound, but the well-known
01250         // condition used here is a good conservative first pass.
01251         // TODO: Tighten bound via rigorous analysis of the unbalanced case.
01252         if (OpWidth >= 2*DstWidth && DstWidth >= SrcWidth) {
01253           if (LHSOrig->getType() != CI.getType())
01254             LHSOrig = Builder->CreateFPExt(LHSOrig, CI.getType());
01255           if (RHSOrig->getType() != CI.getType())
01256             RHSOrig = Builder->CreateFPExt(RHSOrig, CI.getType());
01257           Instruction *RI =
01258             BinaryOperator::CreateFDiv(LHSOrig, RHSOrig);
01259           RI->copyFastMathFlags(OpI);
01260           return RI;
01261         }
01262         break;
01263       case Instruction::FRem:
01264         // Remainder is straightforward.  Remainder is always exact, so the
01265         // type of OpI doesn't enter into things at all.  We simply evaluate
01266         // in whichever source type is larger, then convert to the
01267         // destination type.
01268         if (LHSWidth < SrcWidth)
01269           LHSOrig = Builder->CreateFPExt(LHSOrig, RHSOrig->getType());
01270         else if (RHSWidth <= SrcWidth)
01271           RHSOrig = Builder->CreateFPExt(RHSOrig, LHSOrig->getType());
01272         Value *ExactResult = Builder->CreateFRem(LHSOrig, RHSOrig);
01273         if (Instruction *RI = dyn_cast<Instruction>(ExactResult))
01274           RI->copyFastMathFlags(OpI);
01275         return CastInst::CreateFPCast(ExactResult, CI.getType());
01276     }
01277 
01278     // (fptrunc (fneg x)) -> (fneg (fptrunc x))
01279     if (BinaryOperator::isFNeg(OpI)) {
01280       Value *InnerTrunc = Builder->CreateFPTrunc(OpI->getOperand(1),
01281                                                  CI.getType());
01282       Instruction *RI = BinaryOperator::CreateFNeg(InnerTrunc);
01283       RI->copyFastMathFlags(OpI);
01284       return RI;
01285     }
01286   }
01287 
01288   // (fptrunc (select cond, R1, Cst)) -->
01289   // (select cond, (fptrunc R1), (fptrunc Cst))
01290   SelectInst *SI = dyn_cast<SelectInst>(CI.getOperand(0));
01291   if (SI &&
01292       (isa<ConstantFP>(SI->getOperand(1)) ||
01293        isa<ConstantFP>(SI->getOperand(2)))) {
01294     Value *LHSTrunc = Builder->CreateFPTrunc(SI->getOperand(1),
01295                                              CI.getType());
01296     Value *RHSTrunc = Builder->CreateFPTrunc(SI->getOperand(2),
01297                                              CI.getType());
01298     return SelectInst::Create(SI->getOperand(0), LHSTrunc, RHSTrunc);
01299   }
01300 
01301   IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI.getOperand(0));
01302   if (II) {
01303     switch (II->getIntrinsicID()) {
01304       default: break;
01305       case Intrinsic::fabs: {
01306         // (fptrunc (fabs x)) -> (fabs (fptrunc x))
01307         Value *InnerTrunc = Builder->CreateFPTrunc(II->getArgOperand(0),
01308                                                    CI.getType());
01309         Type *IntrinsicType[] = { CI.getType() };
01310         Function *Overload =
01311           Intrinsic::getDeclaration(CI.getParent()->getParent()->getParent(),
01312                                     II->getIntrinsicID(), IntrinsicType);
01313 
01314         Value *Args[] = { InnerTrunc };
01315         return CallInst::Create(Overload, Args, II->getName());
01316       }
01317     }
01318   }
01319 
01320   // Fold (fptrunc (sqrt (fpext x))) -> (sqrtf x)
01321   // Note that we restrict this transformation based on
01322   // TLI->has(LibFunc::sqrtf), even for the sqrt intrinsic, because
01323   // TLI->has(LibFunc::sqrtf) is sufficient to guarantee that the
01324   // single-precision intrinsic can be expanded in the backend.
01325   CallInst *Call = dyn_cast<CallInst>(CI.getOperand(0));
01326   if (Call && Call->getCalledFunction() && TLI->has(LibFunc::sqrtf) &&
01327       (Call->getCalledFunction()->getName() == TLI->getName(LibFunc::sqrt) ||
01328        Call->getCalledFunction()->getIntrinsicID() == Intrinsic::sqrt) &&
01329       Call->getNumArgOperands() == 1 &&
01330       Call->hasOneUse()) {
01331     CastInst *Arg = dyn_cast<CastInst>(Call->getArgOperand(0));
01332     if (Arg && Arg->getOpcode() == Instruction::FPExt &&
01333         CI.getType()->isFloatTy() &&
01334         Call->getType()->isDoubleTy() &&
01335         Arg->getType()->isDoubleTy() &&
01336         Arg->getOperand(0)->getType()->isFloatTy()) {
01337       Function *Callee = Call->getCalledFunction();
01338       Module *M = CI.getParent()->getParent()->getParent();
01339       Constant *SqrtfFunc = (Callee->getIntrinsicID() == Intrinsic::sqrt) ?
01340         Intrinsic::getDeclaration(M, Intrinsic::sqrt, Builder->getFloatTy()) :
01341         M->getOrInsertFunction("sqrtf", Callee->getAttributes(),
01342                                Builder->getFloatTy(), Builder->getFloatTy(),
01343                                NULL);
01344       CallInst *ret = CallInst::Create(SqrtfFunc, Arg->getOperand(0),
01345                                        "sqrtfcall");
01346       ret->setAttributes(Callee->getAttributes());
01347 
01348 
01349       // Remove the old Call.  With -fmath-errno, it won't get marked readnone.
01350       ReplaceInstUsesWith(*Call, UndefValue::get(Call->getType()));
01351       EraseInstFromFunction(*Call);
01352       return ret;
01353     }
01354   }
01355 
01356   return nullptr;
01357 }
01358 
01359 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
01360   return commonCastTransforms(CI);
01361 }
01362 
01363 Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
01364   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
01365   if (!OpI)
01366     return commonCastTransforms(FI);
01367 
01368   // fptoui(uitofp(X)) --> X
01369   // fptoui(sitofp(X)) --> X
01370   // This is safe if the intermediate type has enough bits in its mantissa to
01371   // accurately represent all values of X.  For example, do not do this with
01372   // i64->float->i64.  This is also safe for sitofp case, because any negative
01373   // 'X' value would cause an undefined result for the fptoui.
01374   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
01375       OpI->getOperand(0)->getType() == FI.getType() &&
01376       (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
01377                     OpI->getType()->getFPMantissaWidth())
01378     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
01379 
01380   return commonCastTransforms(FI);
01381 }
01382 
01383 Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
01384   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
01385   if (!OpI)
01386     return commonCastTransforms(FI);
01387 
01388   // fptosi(sitofp(X)) --> X
01389   // fptosi(uitofp(X)) --> X
01390   // This is safe if the intermediate type has enough bits in its mantissa to
01391   // accurately represent all values of X.  For example, do not do this with
01392   // i64->float->i64.  This is also safe for sitofp case, because any negative
01393   // 'X' value would cause an undefined result for the fptoui.
01394   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
01395       OpI->getOperand(0)->getType() == FI.getType() &&
01396       (int)FI.getType()->getScalarSizeInBits() <=
01397                     OpI->getType()->getFPMantissaWidth())
01398     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
01399 
01400   return commonCastTransforms(FI);
01401 }
01402 
01403 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
01404   return commonCastTransforms(CI);
01405 }
01406 
01407 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
01408   return commonCastTransforms(CI);
01409 }
01410 
01411 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
01412   // If the source integer type is not the intptr_t type for this target, do a
01413   // trunc or zext to the intptr_t type, then inttoptr of it.  This allows the
01414   // cast to be exposed to other transforms.
01415 
01416   if (DL) {
01417     unsigned AS = CI.getAddressSpace();
01418     if (CI.getOperand(0)->getType()->getScalarSizeInBits() !=
01419         DL->getPointerSizeInBits(AS)) {
01420       Type *Ty = DL->getIntPtrType(CI.getContext(), AS);
01421       if (CI.getType()->isVectorTy()) // Handle vectors of pointers.
01422         Ty = VectorType::get(Ty, CI.getType()->getVectorNumElements());
01423 
01424       Value *P = Builder->CreateZExtOrTrunc(CI.getOperand(0), Ty);
01425       return new IntToPtrInst(P, CI.getType());
01426     }
01427   }
01428 
01429   if (Instruction *I = commonCastTransforms(CI))
01430     return I;
01431 
01432   return nullptr;
01433 }
01434 
01435 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
01436 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
01437   Value *Src = CI.getOperand(0);
01438 
01439   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
01440     // If casting the result of a getelementptr instruction with no offset, turn
01441     // this into a cast of the original pointer!
01442     if (GEP->hasAllZeroIndices() &&
01443         // If CI is an addrspacecast and GEP changes the poiner type, merging
01444         // GEP into CI would undo canonicalizing addrspacecast with different
01445         // pointer types, causing infinite loops.
01446         (!isa<AddrSpaceCastInst>(CI) ||
01447           GEP->getType() == GEP->getPointerOperand()->getType())) {
01448       // Changing the cast operand is usually not a good idea but it is safe
01449       // here because the pointer operand is being replaced with another
01450       // pointer operand so the opcode doesn't need to change.
01451       Worklist.Add(GEP);
01452       CI.setOperand(0, GEP->getOperand(0));
01453       return &CI;
01454     }
01455 
01456     if (!DL)
01457       return commonCastTransforms(CI);
01458 
01459     // If the GEP has a single use, and the base pointer is a bitcast, and the
01460     // GEP computes a constant offset, see if we can convert these three
01461     // instructions into fewer.  This typically happens with unions and other
01462     // non-type-safe code.
01463     unsigned AS = GEP->getPointerAddressSpace();
01464     unsigned OffsetBits = DL->getPointerSizeInBits(AS);
01465     APInt Offset(OffsetBits, 0);
01466     BitCastInst *BCI = dyn_cast<BitCastInst>(GEP->getOperand(0));
01467     if (GEP->hasOneUse() &&
01468         BCI &&
01469         GEP->accumulateConstantOffset(*DL, Offset)) {
01470       // Get the base pointer input of the bitcast, and the type it points to.
01471       Value *OrigBase = BCI->getOperand(0);
01472       SmallVector<Value*, 8> NewIndices;
01473       if (FindElementAtOffset(OrigBase->getType(),
01474                               Offset.getSExtValue(),
01475                               NewIndices)) {
01476         // If we were able to index down into an element, create the GEP
01477         // and bitcast the result.  This eliminates one bitcast, potentially
01478         // two.
01479         Value *NGEP = cast<GEPOperator>(GEP)->isInBounds() ?
01480           Builder->CreateInBoundsGEP(OrigBase, NewIndices) :
01481           Builder->CreateGEP(OrigBase, NewIndices);
01482         NGEP->takeName(GEP);
01483 
01484         if (isa<BitCastInst>(CI))
01485           return new BitCastInst(NGEP, CI.getType());
01486         assert(isa<PtrToIntInst>(CI));
01487         return new PtrToIntInst(NGEP, CI.getType());
01488       }
01489     }
01490   }
01491 
01492   return commonCastTransforms(CI);
01493 }
01494 
01495 Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
01496   // If the destination integer type is not the intptr_t type for this target,
01497   // do a ptrtoint to intptr_t then do a trunc or zext.  This allows the cast
01498   // to be exposed to other transforms.
01499 
01500   if (!DL)
01501     return commonPointerCastTransforms(CI);
01502 
01503   Type *Ty = CI.getType();
01504   unsigned AS = CI.getPointerAddressSpace();
01505 
01506   if (Ty->getScalarSizeInBits() == DL->getPointerSizeInBits(AS))
01507     return commonPointerCastTransforms(CI);
01508 
01509   Type *PtrTy = DL->getIntPtrType(CI.getContext(), AS);
01510   if (Ty->isVectorTy()) // Handle vectors of pointers.
01511     PtrTy = VectorType::get(PtrTy, Ty->getVectorNumElements());
01512 
01513   Value *P = Builder->CreatePtrToInt(CI.getOperand(0), PtrTy);
01514   return CastInst::CreateIntegerCast(P, Ty, /*isSigned=*/false);
01515 }
01516 
01517 /// OptimizeVectorResize - This input value (which is known to have vector type)
01518 /// is being zero extended or truncated to the specified vector type.  Try to
01519 /// replace it with a shuffle (and vector/vector bitcast) if possible.
01520 ///
01521 /// The source and destination vector types may have different element types.
01522 static Instruction *OptimizeVectorResize(Value *InVal, VectorType *DestTy,
01523                                          InstCombiner &IC) {
01524   // We can only do this optimization if the output is a multiple of the input
01525   // element size, or the input is a multiple of the output element size.
01526   // Convert the input type to have the same element type as the output.
01527   VectorType *SrcTy = cast<VectorType>(InVal->getType());
01528 
01529   if (SrcTy->getElementType() != DestTy->getElementType()) {
01530     // The input types don't need to be identical, but for now they must be the
01531     // same size.  There is no specific reason we couldn't handle things like
01532     // <4 x i16> -> <4 x i32> by bitcasting to <2 x i32> but haven't gotten
01533     // there yet.
01534     if (SrcTy->getElementType()->getPrimitiveSizeInBits() !=
01535         DestTy->getElementType()->getPrimitiveSizeInBits())
01536       return nullptr;
01537 
01538     SrcTy = VectorType::get(DestTy->getElementType(), SrcTy->getNumElements());
01539     InVal = IC.Builder->CreateBitCast(InVal, SrcTy);
01540   }
01541 
01542   // Now that the element types match, get the shuffle mask and RHS of the
01543   // shuffle to use, which depends on whether we're increasing or decreasing the
01544   // size of the input.
01545   SmallVector<uint32_t, 16> ShuffleMask;
01546   Value *V2;
01547 
01548   if (SrcTy->getNumElements() > DestTy->getNumElements()) {
01549     // If we're shrinking the number of elements, just shuffle in the low
01550     // elements from the input and use undef as the second shuffle input.
01551     V2 = UndefValue::get(SrcTy);
01552     for (unsigned i = 0, e = DestTy->getNumElements(); i != e; ++i)
01553       ShuffleMask.push_back(i);
01554 
01555   } else {
01556     // If we're increasing the number of elements, shuffle in all of the
01557     // elements from InVal and fill the rest of the result elements with zeros
01558     // from a constant zero.
01559     V2 = Constant::getNullValue(SrcTy);
01560     unsigned SrcElts = SrcTy->getNumElements();
01561     for (unsigned i = 0, e = SrcElts; i != e; ++i)
01562       ShuffleMask.push_back(i);
01563 
01564     // The excess elements reference the first element of the zero input.
01565     for (unsigned i = 0, e = DestTy->getNumElements()-SrcElts; i != e; ++i)
01566       ShuffleMask.push_back(SrcElts);
01567   }
01568 
01569   return new ShuffleVectorInst(InVal, V2,
01570                                ConstantDataVector::get(V2->getContext(),
01571                                                        ShuffleMask));
01572 }
01573 
01574 static bool isMultipleOfTypeSize(unsigned Value, Type *Ty) {
01575   return Value % Ty->getPrimitiveSizeInBits() == 0;
01576 }
01577 
01578 static unsigned getTypeSizeIndex(unsigned Value, Type *Ty) {
01579   return Value / Ty->getPrimitiveSizeInBits();
01580 }
01581 
01582 /// CollectInsertionElements - V is a value which is inserted into a vector of
01583 /// VecEltTy.  Look through the value to see if we can decompose it into
01584 /// insertions into the vector.  See the example in the comment for
01585 /// OptimizeIntegerToVectorInsertions for the pattern this handles.
01586 /// The type of V is always a non-zero multiple of VecEltTy's size.
01587 /// Shift is the number of bits between the lsb of V and the lsb of
01588 /// the vector.
01589 ///
01590 /// This returns false if the pattern can't be matched or true if it can,
01591 /// filling in Elements with the elements found here.
01592 static bool CollectInsertionElements(Value *V, unsigned Shift,
01593                                      SmallVectorImpl<Value*> &Elements,
01594                                      Type *VecEltTy, InstCombiner &IC) {
01595   assert(isMultipleOfTypeSize(Shift, VecEltTy) &&
01596          "Shift should be a multiple of the element type size");
01597 
01598   // Undef values never contribute useful bits to the result.
01599   if (isa<UndefValue>(V)) return true;
01600 
01601   // If we got down to a value of the right type, we win, try inserting into the
01602   // right element.
01603   if (V->getType() == VecEltTy) {
01604     // Inserting null doesn't actually insert any elements.
01605     if (Constant *C = dyn_cast<Constant>(V))
01606       if (C->isNullValue())
01607         return true;
01608 
01609     unsigned ElementIndex = getTypeSizeIndex(Shift, VecEltTy);
01610     if (IC.getDataLayout()->isBigEndian())
01611       ElementIndex = Elements.size() - ElementIndex - 1;
01612 
01613     // Fail if multiple elements are inserted into this slot.
01614     if (Elements[ElementIndex])
01615       return false;
01616 
01617     Elements[ElementIndex] = V;
01618     return true;
01619   }
01620 
01621   if (Constant *C = dyn_cast<Constant>(V)) {
01622     // Figure out the # elements this provides, and bitcast it or slice it up
01623     // as required.
01624     unsigned NumElts = getTypeSizeIndex(C->getType()->getPrimitiveSizeInBits(),
01625                                         VecEltTy);
01626     // If the constant is the size of a vector element, we just need to bitcast
01627     // it to the right type so it gets properly inserted.
01628     if (NumElts == 1)
01629       return CollectInsertionElements(ConstantExpr::getBitCast(C, VecEltTy),
01630                                       Shift, Elements, VecEltTy, IC);
01631 
01632     // Okay, this is a constant that covers multiple elements.  Slice it up into
01633     // pieces and insert each element-sized piece into the vector.
01634     if (!isa<IntegerType>(C->getType()))
01635       C = ConstantExpr::getBitCast(C, IntegerType::get(V->getContext(),
01636                                        C->getType()->getPrimitiveSizeInBits()));
01637     unsigned ElementSize = VecEltTy->getPrimitiveSizeInBits();
01638     Type *ElementIntTy = IntegerType::get(C->getContext(), ElementSize);
01639 
01640     for (unsigned i = 0; i != NumElts; ++i) {
01641       unsigned ShiftI = Shift+i*ElementSize;
01642       Constant *Piece = ConstantExpr::getLShr(C, ConstantInt::get(C->getType(),
01643                                                                   ShiftI));
01644       Piece = ConstantExpr::getTrunc(Piece, ElementIntTy);
01645       if (!CollectInsertionElements(Piece, ShiftI, Elements, VecEltTy, IC))
01646         return false;
01647     }
01648     return true;
01649   }
01650 
01651   if (!V->hasOneUse()) return false;
01652 
01653   Instruction *I = dyn_cast<Instruction>(V);
01654   if (!I) return false;
01655   switch (I->getOpcode()) {
01656   default: return false; // Unhandled case.
01657   case Instruction::BitCast:
01658     return CollectInsertionElements(I->getOperand(0), Shift,
01659                                     Elements, VecEltTy, IC);
01660   case Instruction::ZExt:
01661     if (!isMultipleOfTypeSize(
01662                           I->getOperand(0)->getType()->getPrimitiveSizeInBits(),
01663                               VecEltTy))
01664       return false;
01665     return CollectInsertionElements(I->getOperand(0), Shift,
01666                                     Elements, VecEltTy, IC);
01667   case Instruction::Or:
01668     return CollectInsertionElements(I->getOperand(0), Shift,
01669                                     Elements, VecEltTy, IC) &&
01670            CollectInsertionElements(I->getOperand(1), Shift,
01671                                     Elements, VecEltTy, IC);
01672   case Instruction::Shl: {
01673     // Must be shifting by a constant that is a multiple of the element size.
01674     ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1));
01675     if (!CI) return false;
01676     Shift += CI->getZExtValue();
01677     if (!isMultipleOfTypeSize(Shift, VecEltTy)) return false;
01678     return CollectInsertionElements(I->getOperand(0), Shift,
01679                                     Elements, VecEltTy, IC);
01680   }
01681 
01682   }
01683 }
01684 
01685 
01686 /// OptimizeIntegerToVectorInsertions - If the input is an 'or' instruction, we
01687 /// may be doing shifts and ors to assemble the elements of the vector manually.
01688 /// Try to rip the code out and replace it with insertelements.  This is to
01689 /// optimize code like this:
01690 ///
01691 ///    %tmp37 = bitcast float %inc to i32
01692 ///    %tmp38 = zext i32 %tmp37 to i64
01693 ///    %tmp31 = bitcast float %inc5 to i32
01694 ///    %tmp32 = zext i32 %tmp31 to i64
01695 ///    %tmp33 = shl i64 %tmp32, 32
01696 ///    %ins35 = or i64 %tmp33, %tmp38
01697 ///    %tmp43 = bitcast i64 %ins35 to <2 x float>
01698 ///
01699 /// Into two insertelements that do "buildvector{%inc, %inc5}".
01700 static Value *OptimizeIntegerToVectorInsertions(BitCastInst &CI,
01701                                                 InstCombiner &IC) {
01702   // We need to know the target byte order to perform this optimization.
01703   if (!IC.getDataLayout()) return nullptr;
01704 
01705   VectorType *DestVecTy = cast<VectorType>(CI.getType());
01706   Value *IntInput = CI.getOperand(0);
01707 
01708   SmallVector<Value*, 8> Elements(DestVecTy->getNumElements());
01709   if (!CollectInsertionElements(IntInput, 0, Elements,
01710                                 DestVecTy->getElementType(), IC))
01711     return nullptr;
01712 
01713   // If we succeeded, we know that all of the element are specified by Elements
01714   // or are zero if Elements has a null entry.  Recast this as a set of
01715   // insertions.
01716   Value *Result = Constant::getNullValue(CI.getType());
01717   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
01718     if (!Elements[i]) continue;  // Unset element.
01719 
01720     Result = IC.Builder->CreateInsertElement(Result, Elements[i],
01721                                              IC.Builder->getInt32(i));
01722   }
01723 
01724   return Result;
01725 }
01726 
01727 
01728 /// OptimizeIntToFloatBitCast - See if we can optimize an integer->float/double
01729 /// bitcast.  The various long double bitcasts can't get in here.
01730 static Instruction *OptimizeIntToFloatBitCast(BitCastInst &CI,InstCombiner &IC){
01731   // We need to know the target byte order to perform this optimization.
01732   if (!IC.getDataLayout()) return nullptr;
01733 
01734   Value *Src = CI.getOperand(0);
01735   Type *DestTy = CI.getType();
01736 
01737   // If this is a bitcast from int to float, check to see if the int is an
01738   // extraction from a vector.
01739   Value *VecInput = nullptr;
01740   // bitcast(trunc(bitcast(somevector)))
01741   if (match(Src, m_Trunc(m_BitCast(m_Value(VecInput)))) &&
01742       isa<VectorType>(VecInput->getType())) {
01743     VectorType *VecTy = cast<VectorType>(VecInput->getType());
01744     unsigned DestWidth = DestTy->getPrimitiveSizeInBits();
01745 
01746     if (VecTy->getPrimitiveSizeInBits() % DestWidth == 0) {
01747       // If the element type of the vector doesn't match the result type,
01748       // bitcast it to be a vector type we can extract from.
01749       if (VecTy->getElementType() != DestTy) {
01750         VecTy = VectorType::get(DestTy,
01751                                 VecTy->getPrimitiveSizeInBits() / DestWidth);
01752         VecInput = IC.Builder->CreateBitCast(VecInput, VecTy);
01753       }
01754 
01755       unsigned Elt = 0;
01756       if (IC.getDataLayout()->isBigEndian())
01757         Elt = VecTy->getPrimitiveSizeInBits() / DestWidth - 1;
01758       return ExtractElementInst::Create(VecInput, IC.Builder->getInt32(Elt));
01759     }
01760   }
01761 
01762   // bitcast(trunc(lshr(bitcast(somevector), cst))
01763   ConstantInt *ShAmt = nullptr;
01764   if (match(Src, m_Trunc(m_LShr(m_BitCast(m_Value(VecInput)),
01765                                 m_ConstantInt(ShAmt)))) &&
01766       isa<VectorType>(VecInput->getType())) {
01767     VectorType *VecTy = cast<VectorType>(VecInput->getType());
01768     unsigned DestWidth = DestTy->getPrimitiveSizeInBits();
01769     if (VecTy->getPrimitiveSizeInBits() % DestWidth == 0 &&
01770         ShAmt->getZExtValue() % DestWidth == 0) {
01771       // If the element type of the vector doesn't match the result type,
01772       // bitcast it to be a vector type we can extract from.
01773       if (VecTy->getElementType() != DestTy) {
01774         VecTy = VectorType::get(DestTy,
01775                                 VecTy->getPrimitiveSizeInBits() / DestWidth);
01776         VecInput = IC.Builder->CreateBitCast(VecInput, VecTy);
01777       }
01778 
01779       unsigned Elt = ShAmt->getZExtValue() / DestWidth;
01780       if (IC.getDataLayout()->isBigEndian())
01781         Elt = VecTy->getPrimitiveSizeInBits() / DestWidth - 1 - Elt;
01782       return ExtractElementInst::Create(VecInput, IC.Builder->getInt32(Elt));
01783     }
01784   }
01785   return nullptr;
01786 }
01787 
01788 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
01789   // If the operands are integer typed then apply the integer transforms,
01790   // otherwise just apply the common ones.
01791   Value *Src = CI.getOperand(0);
01792   Type *SrcTy = Src->getType();
01793   Type *DestTy = CI.getType();
01794 
01795   // Get rid of casts from one type to the same type. These are useless and can
01796   // be replaced by the operand.
01797   if (DestTy == Src->getType())
01798     return ReplaceInstUsesWith(CI, Src);
01799 
01800   if (PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
01801     PointerType *SrcPTy = cast<PointerType>(SrcTy);
01802     Type *DstElTy = DstPTy->getElementType();
01803     Type *SrcElTy = SrcPTy->getElementType();
01804 
01805     // If we are casting a alloca to a pointer to a type of the same
01806     // size, rewrite the allocation instruction to allocate the "right" type.
01807     // There is no need to modify malloc calls because it is their bitcast that
01808     // needs to be cleaned up.
01809     if (AllocaInst *AI = dyn_cast<AllocaInst>(Src))
01810       if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
01811         return V;
01812 
01813     // If the source and destination are pointers, and this cast is equivalent
01814     // to a getelementptr X, 0, 0, 0...  turn it into the appropriate gep.
01815     // This can enhance SROA and other transforms that want type-safe pointers.
01816     Constant *ZeroUInt =
01817       Constant::getNullValue(Type::getInt32Ty(CI.getContext()));
01818     unsigned NumZeros = 0;
01819     while (SrcElTy != DstElTy &&
01820            isa<CompositeType>(SrcElTy) && !SrcElTy->isPointerTy() &&
01821            SrcElTy->getNumContainedTypes() /* not "{}" */) {
01822       SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
01823       ++NumZeros;
01824     }
01825 
01826     // If we found a path from the src to dest, create the getelementptr now.
01827     if (SrcElTy == DstElTy) {
01828       SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
01829       return GetElementPtrInst::CreateInBounds(Src, Idxs);
01830     }
01831   }
01832 
01833   // Try to optimize int -> float bitcasts.
01834   if ((DestTy->isFloatTy() || DestTy->isDoubleTy()) && isa<IntegerType>(SrcTy))
01835     if (Instruction *I = OptimizeIntToFloatBitCast(CI, *this))
01836       return I;
01837 
01838   if (VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
01839     if (DestVTy->getNumElements() == 1 && !SrcTy->isVectorTy()) {
01840       Value *Elem = Builder->CreateBitCast(Src, DestVTy->getElementType());
01841       return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
01842                      Constant::getNullValue(Type::getInt32Ty(CI.getContext())));
01843       // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
01844     }
01845 
01846     if (isa<IntegerType>(SrcTy)) {
01847       // If this is a cast from an integer to vector, check to see if the input
01848       // is a trunc or zext of a bitcast from vector.  If so, we can replace all
01849       // the casts with a shuffle and (potentially) a bitcast.
01850       if (isa<TruncInst>(Src) || isa<ZExtInst>(Src)) {
01851         CastInst *SrcCast = cast<CastInst>(Src);
01852         if (BitCastInst *BCIn = dyn_cast<BitCastInst>(SrcCast->getOperand(0)))
01853           if (isa<VectorType>(BCIn->getOperand(0)->getType()))
01854             if (Instruction *I = OptimizeVectorResize(BCIn->getOperand(0),
01855                                                cast<VectorType>(DestTy), *this))
01856               return I;
01857       }
01858 
01859       // If the input is an 'or' instruction, we may be doing shifts and ors to
01860       // assemble the elements of the vector manually.  Try to rip the code out
01861       // and replace it with insertelements.
01862       if (Value *V = OptimizeIntegerToVectorInsertions(CI, *this))
01863         return ReplaceInstUsesWith(CI, V);
01864     }
01865   }
01866 
01867   if (VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
01868     if (SrcVTy->getNumElements() == 1) {
01869       // If our destination is not a vector, then make this a straight
01870       // scalar-scalar cast.
01871       if (!DestTy->isVectorTy()) {
01872         Value *Elem =
01873           Builder->CreateExtractElement(Src,
01874                      Constant::getNullValue(Type::getInt32Ty(CI.getContext())));
01875         return CastInst::Create(Instruction::BitCast, Elem, DestTy);
01876       }
01877 
01878       // Otherwise, see if our source is an insert. If so, then use the scalar
01879       // component directly.
01880       if (InsertElementInst *IEI =
01881             dyn_cast<InsertElementInst>(CI.getOperand(0)))
01882         return CastInst::Create(Instruction::BitCast, IEI->getOperand(1),
01883                                 DestTy);
01884     }
01885   }
01886 
01887   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
01888     // Okay, we have (bitcast (shuffle ..)).  Check to see if this is
01889     // a bitcast to a vector with the same # elts.
01890     if (SVI->hasOneUse() && DestTy->isVectorTy() &&
01891         DestTy->getVectorNumElements() == SVI->getType()->getNumElements() &&
01892         SVI->getType()->getNumElements() ==
01893         SVI->getOperand(0)->getType()->getVectorNumElements()) {
01894       BitCastInst *Tmp;
01895       // If either of the operands is a cast from CI.getType(), then
01896       // evaluating the shuffle in the casted destination's type will allow
01897       // us to eliminate at least one cast.
01898       if (((Tmp = dyn_cast<BitCastInst>(SVI->getOperand(0))) &&
01899            Tmp->getOperand(0)->getType() == DestTy) ||
01900           ((Tmp = dyn_cast<BitCastInst>(SVI->getOperand(1))) &&
01901            Tmp->getOperand(0)->getType() == DestTy)) {
01902         Value *LHS = Builder->CreateBitCast(SVI->getOperand(0), DestTy);
01903         Value *RHS = Builder->CreateBitCast(SVI->getOperand(1), DestTy);
01904         // Return a new shuffle vector.  Use the same element ID's, as we
01905         // know the vector types match #elts.
01906         return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
01907       }
01908     }
01909   }
01910 
01911   if (SrcTy->isPointerTy())
01912     return commonPointerCastTransforms(CI);
01913   return commonCastTransforms(CI);
01914 }
01915 
01916 Instruction *InstCombiner::visitAddrSpaceCast(AddrSpaceCastInst &CI) {
01917   // If the destination pointer element type is not the same as the source's
01918   // first do a bitcast to the destination type, and then the addrspacecast.
01919   // This allows the cast to be exposed to other transforms.
01920   Value *Src = CI.getOperand(0);
01921   PointerType *SrcTy = cast<PointerType>(Src->getType()->getScalarType());
01922   PointerType *DestTy = cast<PointerType>(CI.getType()->getScalarType());
01923 
01924   Type *DestElemTy = DestTy->getElementType();
01925   if (SrcTy->getElementType() != DestElemTy) {
01926     Type *MidTy = PointerType::get(DestElemTy, SrcTy->getAddressSpace());
01927     if (VectorType *VT = dyn_cast<VectorType>(CI.getType())) {
01928       // Handle vectors of pointers.
01929       MidTy = VectorType::get(MidTy, VT->getNumElements());
01930     }
01931 
01932     Value *NewBitCast = Builder->CreateBitCast(Src, MidTy);
01933     return new AddrSpaceCastInst(NewBitCast, CI.getType());
01934   }
01935 
01936   return commonPointerCastTransforms(CI);
01937 }