1//===- InstCombineCasts.cpp -----------------------------------------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the visit functions for cast operations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "InstCombine.h"
15#include "llvm/Analysis/ConstantFolding.h"
16#include "llvm/Target/TargetData.h"
17#include "llvm/Target/TargetLibraryInfo.h"
18#include "llvm/Support/PatternMatch.h"
19using namespace llvm;
20using namespace PatternMatch;
21
22/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
23/// expression.  If so, decompose it, returning some value X, such that Val is
24/// X*Scale+Offset.
25///
26static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
27                                        uint64_t &Offset) {
28  if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
29    Offset = CI->getZExtValue();
30    Scale  = 0;
31    return ConstantInt::get(Val->getType(), 0);
32  }
33
34  if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
35    // Cannot look past anything that might overflow.
36    OverflowingBinaryOperator *OBI = dyn_cast<OverflowingBinaryOperator>(Val);
37    if (OBI && !OBI->hasNoUnsignedWrap() && !OBI->hasNoSignedWrap()) {
38      Scale = 1;
39      Offset = 0;
40      return Val;
41    }
42
43    if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
44      if (I->getOpcode() == Instruction::Shl) {
45        // This is a value scaled by '1 << the shift amt'.
46        Scale = UINT64_C(1) << RHS->getZExtValue();
47        Offset = 0;
48        return I->getOperand(0);
49      }
50
51      if (I->getOpcode() == Instruction::Mul) {
52        // This value is scaled by 'RHS'.
53        Scale = RHS->getZExtValue();
54        Offset = 0;
55        return I->getOperand(0);
56      }
57
58      if (I->getOpcode() == Instruction::Add) {
59        // We have X+C.  Check to see if we really have (X*C2)+C1,
60        // where C1 is divisible by C2.
61        unsigned SubScale;
62        Value *SubVal =
63          DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
64        Offset += RHS->getZExtValue();
65        Scale = SubScale;
66        return SubVal;
67      }
68    }
69  }
70
71  // Otherwise, we can't look past this.
72  Scale = 1;
73  Offset = 0;
74  return Val;
75}
76
77/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
78/// try to eliminate the cast by moving the type information into the alloc.
79Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
80                                                   AllocaInst &AI) {
81  // This requires TargetData to get the alloca alignment and size information.
82  if (!TD) return 0;
83
84  PointerType *PTy = cast<PointerType>(CI.getType());
85
86  BuilderTy AllocaBuilder(*Builder);
87  AllocaBuilder.SetInsertPoint(AI.getParent(), &AI);
88
89  // Get the type really allocated and the type casted to.
90  Type *AllocElTy = AI.getAllocatedType();
91  Type *CastElTy = PTy->getElementType();
92  if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
93
94  unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
95  unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
96  if (CastElTyAlign < AllocElTyAlign) return 0;
97
98  // If the allocation has multiple uses, only promote it if we are strictly
99  // increasing the alignment of the resultant allocation.  If we keep it the
100  // same, we open the door to infinite loops of various kinds.
101  if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
102
103  uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
104  uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
105  if (CastElTySize == 0 || AllocElTySize == 0) return 0;
106
107  // See if we can satisfy the modulus by pulling a scale out of the array
108  // size argument.
109  unsigned ArraySizeScale;
110  uint64_t ArrayOffset;
111  Value *NumElements = // See if the array size is a decomposable linear expr.
112    DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
113
114  // If we can now satisfy the modulus, by using a non-1 scale, we really can
115  // do the xform.
116  if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
117      (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return 0;
118
119  unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
120  Value *Amt = 0;
121  if (Scale == 1) {
122    Amt = NumElements;
123  } else {
124    Amt = ConstantInt::get(AI.getArraySize()->getType(), Scale);
125    // Insert before the alloca, not before the cast.
126    Amt = AllocaBuilder.CreateMul(Amt, NumElements);
127  }
128
129  if (uint64_t Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
130    Value *Off = ConstantInt::get(AI.getArraySize()->getType(),
131                                  Offset, true);
132    Amt = AllocaBuilder.CreateAdd(Amt, Off);
133  }
134
135  AllocaInst *New = AllocaBuilder.CreateAlloca(CastElTy, Amt);
136  New->setAlignment(AI.getAlignment());
137  New->takeName(&AI);
138
139  // If the allocation has multiple real uses, insert a cast and change all
140  // things that used it to use the new cast.  This will also hack on CI, but it
141  // will die soon.
142  if (!AI.hasOneUse()) {
143    // New is the allocation instruction, pointer typed. AI is the original
144    // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
145    Value *NewCast = AllocaBuilder.CreateBitCast(New, AI.getType(), "tmpcast");
146    ReplaceInstUsesWith(AI, NewCast);
147  }
148  return ReplaceInstUsesWith(CI, New);
149}
150
151/// EvaluateInDifferentType - Given an expression that
152/// CanEvaluateTruncated or CanEvaluateSExtd returns true for, actually
153/// insert the code to evaluate the expression.
154Value *InstCombiner::EvaluateInDifferentType(Value *V, Type *Ty,
155                                             bool isSigned) {
156  if (Constant *C = dyn_cast<Constant>(V)) {
157    C = ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
158    // If we got a constantexpr back, try to simplify it with TD info.
159    if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
160      C = ConstantFoldConstantExpression(CE, TD, TLI);
161    return C;
162  }
163
164  // Otherwise, it must be an instruction.
165  Instruction *I = cast<Instruction>(V);
166  Instruction *Res = 0;
167  unsigned Opc = I->getOpcode();
168  switch (Opc) {
169  case Instruction::Add:
170  case Instruction::Sub:
171  case Instruction::Mul:
172  case Instruction::And:
173  case Instruction::Or:
174  case Instruction::Xor:
175  case Instruction::AShr:
176  case Instruction::LShr:
177  case Instruction::Shl:
178  case Instruction::UDiv:
179  case Instruction::URem: {
180    Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
181    Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
182    Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
183    break;
184  }
185  case Instruction::Trunc:
186  case Instruction::ZExt:
187  case Instruction::SExt:
188    // If the source type of the cast is the type we're trying for then we can
189    // just return the source.  There's no need to insert it because it is not
190    // new.
191    if (I->getOperand(0)->getType() == Ty)
192      return I->getOperand(0);
193
194    // Otherwise, must be the same type of cast, so just reinsert a new one.
195    // This also handles the case of zext(trunc(x)) -> zext(x).
196    Res = CastInst::CreateIntegerCast(I->getOperand(0), Ty,
197                                      Opc == Instruction::SExt);
198    break;
199  case Instruction::Select: {
200    Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
201    Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
202    Res = SelectInst::Create(I->getOperand(0), True, False);
203    break;
204  }
205  case Instruction::PHI: {
206    PHINode *OPN = cast<PHINode>(I);
207    PHINode *NPN = PHINode::Create(Ty, OPN->getNumIncomingValues());
208    for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
209      Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
210      NPN->addIncoming(V, OPN->getIncomingBlock(i));
211    }
212    Res = NPN;
213    break;
214  }
215  default:
216    // TODO: Can handle more cases here.
217    llvm_unreachable("Unreachable!");
218  }
219
220  Res->takeName(I);
221  return InsertNewInstWith(Res, *I);
222}
223
224
225/// This function is a wrapper around CastInst::isEliminableCastPair. It
226/// simply extracts arguments and returns what that function returns.
227static Instruction::CastOps
228isEliminableCastPair(
229  const CastInst *CI, ///< The first cast instruction
230  unsigned opcode,       ///< The opcode of the second cast instruction
231  Type *DstTy,     ///< The target type for the second cast instruction
232  TargetData *TD         ///< The target data for pointer size
233) {
234
235  Type *SrcTy = CI->getOperand(0)->getType();   // A from above
236  Type *MidTy = CI->getType();                  // B from above
237
238  // Get the opcodes of the two Cast instructions
239  Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
240  Instruction::CastOps secondOp = Instruction::CastOps(opcode);
241
242  unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
243                                                DstTy,
244                                  TD ? TD->getIntPtrType(CI->getContext()) : 0);
245
246  // We don't want to form an inttoptr or ptrtoint that converts to an integer
247  // type that differs from the pointer size.
248  if ((Res == Instruction::IntToPtr &&
249          (!TD || SrcTy != TD->getIntPtrType(CI->getContext()))) ||
250      (Res == Instruction::PtrToInt &&
251          (!TD || DstTy != TD->getIntPtrType(CI->getContext()))))
252    Res = 0;
253
254  return Instruction::CastOps(Res);
255}
256
257/// ShouldOptimizeCast - Return true if the cast from "V to Ty" actually
258/// results in any code being generated and is interesting to optimize out. If
259/// the cast can be eliminated by some other simple transformation, we prefer
260/// to do the simplification first.
261bool InstCombiner::ShouldOptimizeCast(Instruction::CastOps opc, const Value *V,
262                                      Type *Ty) {
263  // Noop casts and casts of constants should be eliminated trivially.
264  if (V->getType() == Ty || isa<Constant>(V)) return false;
265
266  // If this is another cast that can be eliminated, we prefer to have it
267  // eliminated.
268  if (const CastInst *CI = dyn_cast<CastInst>(V))
269    if (isEliminableCastPair(CI, opc, Ty, TD))
270      return false;
271
272  // If this is a vector sext from a compare, then we don't want to break the
273  // idiom where each element of the extended vector is either zero or all ones.
274  if (opc == Instruction::SExt && isa<CmpInst>(V) && Ty->isVectorTy())
275    return false;
276
277  return true;
278}
279
280
281/// @brief Implement the transforms common to all CastInst visitors.
282Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
283  Value *Src = CI.getOperand(0);
284
285  // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
286  // eliminate it now.
287  if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
288    if (Instruction::CastOps opc =
289        isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
290      // The first cast (CSrc) is eliminable so we need to fix up or replace
291      // the second cast (CI). CSrc will then have a good chance of being dead.
292      return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
293    }
294  }
295
296  // If we are casting a select then fold the cast into the select
297  if (SelectInst *SI = dyn_cast<SelectInst>(Src))
298    if (Instruction *NV = FoldOpIntoSelect(CI, SI))
299      return NV;
300
301  // If we are casting a PHI then fold the cast into the PHI
302  if (isa<PHINode>(Src)) {
303    // We don't do this if this would create a PHI node with an illegal type if
304    // it is currently legal.
305    if (!Src->getType()->isIntegerTy() ||
306        !CI.getType()->isIntegerTy() ||
307        ShouldChangeType(CI.getType(), Src->getType()))
308      if (Instruction *NV = FoldOpIntoPhi(CI))
309        return NV;
310  }
311
312  return 0;
313}
314
315/// CanEvaluateTruncated - Return true if we can evaluate the specified
316/// expression tree as type Ty instead of its larger type, and arrive with the
317/// same value.  This is used by code that tries to eliminate truncates.
318///
319/// Ty will always be a type smaller than V.  We should return true if trunc(V)
320/// can be computed by computing V in the smaller type.  If V is an instruction,
321/// then trunc(inst(x,y)) can be computed as inst(trunc(x),trunc(y)), which only
322/// makes sense if x and y can be efficiently truncated.
323///
324/// This function works on both vectors and scalars.
325///
326static bool CanEvaluateTruncated(Value *V, Type *Ty) {
327  // We can always evaluate constants in another type.
328  if (isa<Constant>(V))
329    return true;
330
331  Instruction *I = dyn_cast<Instruction>(V);
332  if (!I) return false;
333
334  Type *OrigTy = V->getType();
335
336  // If this is an extension from the dest type, we can eliminate it, even if it
337  // has multiple uses.
338  if ((isa<ZExtInst>(I) || isa<SExtInst>(I)) &&
339      I->getOperand(0)->getType() == Ty)
340    return true;
341
342  // We can't extend or shrink something that has multiple uses: doing so would
343  // require duplicating the instruction in general, which isn't profitable.
344  if (!I->hasOneUse()) return false;
345
346  unsigned Opc = I->getOpcode();
347  switch (Opc) {
348  case Instruction::Add:
349  case Instruction::Sub:
350  case Instruction::Mul:
351  case Instruction::And:
352  case Instruction::Or:
353  case Instruction::Xor:
354    // These operators can all arbitrarily be extended or truncated.
355    return CanEvaluateTruncated(I->getOperand(0), Ty) &&
356           CanEvaluateTruncated(I->getOperand(1), Ty);
357
358  case Instruction::UDiv:
359  case Instruction::URem: {
360    // UDiv and URem can be truncated if all the truncated bits are zero.
361    uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
362    uint32_t BitWidth = Ty->getScalarSizeInBits();
363    if (BitWidth < OrigBitWidth) {
364      APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
365      if (MaskedValueIsZero(I->getOperand(0), Mask) &&
366          MaskedValueIsZero(I->getOperand(1), Mask)) {
367        return CanEvaluateTruncated(I->getOperand(0), Ty) &&
368               CanEvaluateTruncated(I->getOperand(1), Ty);
369      }
370    }
371    break;
372  }
373  case Instruction::Shl:
374    // If we are truncating the result of this SHL, and if it's a shift of a
375    // constant amount, we can always perform a SHL in a smaller type.
376    if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
377      uint32_t BitWidth = Ty->getScalarSizeInBits();
378      if (CI->getLimitedValue(BitWidth) < BitWidth)
379        return CanEvaluateTruncated(I->getOperand(0), Ty);
380    }
381    break;
382  case Instruction::LShr:
383    // If this is a truncate of a logical shr, we can truncate it to a smaller
384    // lshr iff we know that the bits we would otherwise be shifting in are
385    // already zeros.
386    if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
387      uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
388      uint32_t BitWidth = Ty->getScalarSizeInBits();
389      if (MaskedValueIsZero(I->getOperand(0),
390            APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
391          CI->getLimitedValue(BitWidth) < BitWidth) {
392        return CanEvaluateTruncated(I->getOperand(0), Ty);
393      }
394    }
395    break;
396  case Instruction::Trunc:
397    // trunc(trunc(x)) -> trunc(x)
398    return true;
399  case Instruction::ZExt:
400  case Instruction::SExt:
401    // trunc(ext(x)) -> ext(x) if the source type is smaller than the new dest
402    // trunc(ext(x)) -> trunc(x) if the source type is larger than the new dest
403    return true;
404  case Instruction::Select: {
405    SelectInst *SI = cast<SelectInst>(I);
406    return CanEvaluateTruncated(SI->getTrueValue(), Ty) &&
407           CanEvaluateTruncated(SI->getFalseValue(), Ty);
408  }
409  case Instruction::PHI: {
410    // We can change a phi if we can change all operands.  Note that we never
411    // get into trouble with cyclic PHIs here because we only consider
412    // instructions with a single use.
413    PHINode *PN = cast<PHINode>(I);
414    for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
415      if (!CanEvaluateTruncated(PN->getIncomingValue(i), Ty))
416        return false;
417    return true;
418  }
419  default:
420    // TODO: Can handle more cases here.
421    break;
422  }
423
424  return false;
425}
426
427Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
428  if (Instruction *Result = commonCastTransforms(CI))
429    return Result;
430
431  // See if we can simplify any instructions used by the input whose sole
432  // purpose is to compute bits we don't care about.
433  if (SimplifyDemandedInstructionBits(CI))
434    return &CI;
435
436  Value *Src = CI.getOperand(0);
437  Type *DestTy = CI.getType(), *SrcTy = Src->getType();
438
439  // Attempt to truncate the entire input expression tree to the destination
440  // type.   Only do this if the dest type is a simple type, don't convert the
441  // expression tree to something weird like i93 unless the source is also
442  // strange.
443  if ((DestTy->isVectorTy() || ShouldChangeType(SrcTy, DestTy)) &&
444      CanEvaluateTruncated(Src, DestTy)) {
445
446    // If this cast is a truncate, evaluting in a different type always
447    // eliminates the cast, so it is always a win.
448    DEBUG(dbgs() << "ICE: EvaluateInDifferentType converting expression type"
449          " to avoid cast: " << CI << '\n');
450    Value *Res = EvaluateInDifferentType(Src, DestTy, false);
451    assert(Res->getType() == DestTy);
452    return ReplaceInstUsesWith(CI, Res);
453  }
454
455  // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0), likewise for vector.
456  if (DestTy->getScalarSizeInBits() == 1) {
457    Constant *One = ConstantInt::get(Src->getType(), 1);
458    Src = Builder->CreateAnd(Src, One);
459    Value *Zero = Constant::getNullValue(Src->getType());
460    return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
461  }
462
463  // Transform trunc(lshr (zext A), Cst) to eliminate one type conversion.
464  Value *A = 0; ConstantInt *Cst = 0;
465  if (Src->hasOneUse() &&
466      match(Src, m_LShr(m_ZExt(m_Value(A)), m_ConstantInt(Cst)))) {
467    // We have three types to worry about here, the type of A, the source of
468    // the truncate (MidSize), and the destination of the truncate. We know that
469    // ASize < MidSize   and MidSize > ResultSize, but don't know the relation
470    // between ASize and ResultSize.
471    unsigned ASize = A->getType()->getPrimitiveSizeInBits();
472
473    // If the shift amount is larger than the size of A, then the result is
474    // known to be zero because all the input bits got shifted out.
475    if (Cst->getZExtValue() >= ASize)
476      return ReplaceInstUsesWith(CI, Constant::getNullValue(CI.getType()));
477
478    // Since we're doing an lshr and a zero extend, and know that the shift
479    // amount is smaller than ASize, it is always safe to do the shift in A's
480    // type, then zero extend or truncate to the result.
481    Value *Shift = Builder->CreateLShr(A, Cst->getZExtValue());
482    Shift->takeName(Src);
483    return CastInst::CreateIntegerCast(Shift, CI.getType(), false);
484  }
485
486  // Transform "trunc (and X, cst)" -> "and (trunc X), cst" so long as the dest
487  // type isn't non-native.
488  if (Src->hasOneUse() && isa<IntegerType>(Src->getType()) &&
489      ShouldChangeType(Src->getType(), CI.getType()) &&
490      match(Src, m_And(m_Value(A), m_ConstantInt(Cst)))) {
491    Value *NewTrunc = Builder->CreateTrunc(A, CI.getType(), A->getName()+".tr");
492    return BinaryOperator::CreateAnd(NewTrunc,
493                                     ConstantExpr::getTrunc(Cst, CI.getType()));
494  }
495
496  return 0;
497}
498
499/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
500/// in order to eliminate the icmp.
501Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
502                                             bool DoXform) {
503  // If we are just checking for a icmp eq of a single bit and zext'ing it
504  // to an integer, then shift the bit to the appropriate place and then
505  // cast to integer to avoid the comparison.
506  if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
507    const APInt &Op1CV = Op1C->getValue();
508
509    // zext (x <s  0) to i32 --> x>>u31      true if signbit set.
510    // zext (x >s -1) to i32 --> (x>>u31)^1  true if signbit clear.
511    if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
512        (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
513      if (!DoXform) return ICI;
514
515      Value *In = ICI->getOperand(0);
516      Value *Sh = ConstantInt::get(In->getType(),
517                                   In->getType()->getScalarSizeInBits()-1);
518      In = Builder->CreateLShr(In, Sh, In->getName()+".lobit");
519      if (In->getType() != CI.getType())
520        In = Builder->CreateIntCast(In, CI.getType(), false/*ZExt*/);
521
522      if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
523        Constant *One = ConstantInt::get(In->getType(), 1);
524        In = Builder->CreateXor(In, One, In->getName()+".not");
525      }
526
527      return ReplaceInstUsesWith(CI, In);
528    }
529
530    // zext (X == 0) to i32 --> X^1      iff X has only the low bit set.
531    // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
532    // zext (X == 1) to i32 --> X        iff X has only the low bit set.
533    // zext (X == 2) to i32 --> X>>1     iff X has only the 2nd bit set.
534    // zext (X != 0) to i32 --> X        iff X has only the low bit set.
535    // zext (X != 0) to i32 --> X>>1     iff X has only the 2nd bit set.
536    // zext (X != 1) to i32 --> X^1      iff X has only the low bit set.
537    // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
538    if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
539        // This only works for EQ and NE
540        ICI->isEquality()) {
541      // If Op1C some other power of two, convert:
542      uint32_t BitWidth = Op1C->getType()->getBitWidth();
543      APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
544      ComputeMaskedBits(ICI->getOperand(0), KnownZero, KnownOne);
545
546      APInt KnownZeroMask(~KnownZero);
547      if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
548        if (!DoXform) return ICI;
549
550        bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
551        if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
552          // (X&4) == 2 --> false
553          // (X&4) != 2 --> true
554          Constant *Res = ConstantInt::get(Type::getInt1Ty(CI.getContext()),
555                                           isNE);
556          Res = ConstantExpr::getZExt(Res, CI.getType());
557          return ReplaceInstUsesWith(CI, Res);
558        }
559
560        uint32_t ShiftAmt = KnownZeroMask.logBase2();
561        Value *In = ICI->getOperand(0);
562        if (ShiftAmt) {
563          // Perform a logical shr by shiftamt.
564          // Insert the shift to put the result in the low bit.
565          In = Builder->CreateLShr(In, ConstantInt::get(In->getType(),ShiftAmt),
566                                   In->getName()+".lobit");
567        }
568
569        if ((Op1CV != 0) == isNE) { // Toggle the low bit.
570          Constant *One = ConstantInt::get(In->getType(), 1);
571          In = Builder->CreateXor(In, One);
572        }
573
574        if (CI.getType() == In->getType())
575          return ReplaceInstUsesWith(CI, In);
576        return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
577      }
578    }
579  }
580
581  // icmp ne A, B is equal to xor A, B when A and B only really have one bit.
582  // It is also profitable to transform icmp eq into not(xor(A, B)) because that
583  // may lead to additional simplifications.
584  if (ICI->isEquality() && CI.getType() == ICI->getOperand(0)->getType()) {
585    if (IntegerType *ITy = dyn_cast<IntegerType>(CI.getType())) {
586      uint32_t BitWidth = ITy->getBitWidth();
587      Value *LHS = ICI->getOperand(0);
588      Value *RHS = ICI->getOperand(1);
589
590      APInt KnownZeroLHS(BitWidth, 0), KnownOneLHS(BitWidth, 0);
591      APInt KnownZeroRHS(BitWidth, 0), KnownOneRHS(BitWidth, 0);
592      ComputeMaskedBits(LHS, KnownZeroLHS, KnownOneLHS);
593      ComputeMaskedBits(RHS, KnownZeroRHS, KnownOneRHS);
594
595      if (KnownZeroLHS == KnownZeroRHS && KnownOneLHS == KnownOneRHS) {
596        APInt KnownBits = KnownZeroLHS | KnownOneLHS;
597        APInt UnknownBit = ~KnownBits;
598        if (UnknownBit.countPopulation() == 1) {
599          if (!DoXform) return ICI;
600
601          Value *Result = Builder->CreateXor(LHS, RHS);
602
603          // Mask off any bits that are set and won't be shifted away.
604          if (KnownOneLHS.uge(UnknownBit))
605            Result = Builder->CreateAnd(Result,
606                                        ConstantInt::get(ITy, UnknownBit));
607
608          // Shift the bit we're testing down to the lsb.
609          Result = Builder->CreateLShr(
610               Result, ConstantInt::get(ITy, UnknownBit.countTrailingZeros()));
611
612          if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
613            Result = Builder->CreateXor(Result, ConstantInt::get(ITy, 1));
614          Result->takeName(ICI);
615          return ReplaceInstUsesWith(CI, Result);
616        }
617      }
618    }
619  }
620
621  return 0;
622}
623
624/// CanEvaluateZExtd - Determine if the specified value can be computed in the
625/// specified wider type and produce the same low bits.  If not, return false.
626///
627/// If this function returns true, it can also return a non-zero number of bits
628/// (in BitsToClear) which indicates that the value it computes is correct for
629/// the zero extend, but that the additional BitsToClear bits need to be zero'd
630/// out.  For example, to promote something like:
631///
632///   %B = trunc i64 %A to i32
633///   %C = lshr i32 %B, 8
634///   %E = zext i32 %C to i64
635///
636/// CanEvaluateZExtd for the 'lshr' will return true, and BitsToClear will be
637/// set to 8 to indicate that the promoted value needs to have bits 24-31
638/// cleared in addition to bits 32-63.  Since an 'and' will be generated to
639/// clear the top bits anyway, doing this has no extra cost.
640///
641/// This function works on both vectors and scalars.
642static bool CanEvaluateZExtd(Value *V, Type *Ty, unsigned &BitsToClear) {
643  BitsToClear = 0;
644  if (isa<Constant>(V))
645    return true;
646
647  Instruction *I = dyn_cast<Instruction>(V);
648  if (!I) return false;
649
650  // If the input is a truncate from the destination type, we can trivially
651  // eliminate it.
652  if (isa<TruncInst>(I) && I->getOperand(0)->getType() == Ty)
653    return true;
654
655  // We can't extend or shrink something that has multiple uses: doing so would
656  // require duplicating the instruction in general, which isn't profitable.
657  if (!I->hasOneUse()) return false;
658
659  unsigned Opc = I->getOpcode(), Tmp;
660  switch (Opc) {
661  case Instruction::ZExt:  // zext(zext(x)) -> zext(x).
662  case Instruction::SExt:  // zext(sext(x)) -> sext(x).
663  case Instruction::Trunc: // zext(trunc(x)) -> trunc(x) or zext(x)
664    return true;
665  case Instruction::And:
666  case Instruction::Or:
667  case Instruction::Xor:
668  case Instruction::Add:
669  case Instruction::Sub:
670  case Instruction::Mul:
671  case Instruction::Shl:
672    if (!CanEvaluateZExtd(I->getOperand(0), Ty, BitsToClear) ||
673        !CanEvaluateZExtd(I->getOperand(1), Ty, Tmp))
674      return false;
675    // These can all be promoted if neither operand has 'bits to clear'.
676    if (BitsToClear == 0 && Tmp == 0)
677      return true;
678
679    // If the operation is an AND/OR/XOR and the bits to clear are zero in the
680    // other side, BitsToClear is ok.
681    if (Tmp == 0 &&
682        (Opc == Instruction::And || Opc == Instruction::Or ||
683         Opc == Instruction::Xor)) {
684      // We use MaskedValueIsZero here for generality, but the case we care
685      // about the most is constant RHS.
686      unsigned VSize = V->getType()->getScalarSizeInBits();
687      if (MaskedValueIsZero(I->getOperand(1),
688                            APInt::getHighBitsSet(VSize, BitsToClear)))
689        return true;
690    }
691
692    // Otherwise, we don't know how to analyze this BitsToClear case yet.
693    return false;
694
695  case Instruction::LShr:
696    // We can promote lshr(x, cst) if we can promote x.  This requires the
697    // ultimate 'and' to clear out the high zero bits we're clearing out though.
698    if (ConstantInt *Amt = dyn_cast<ConstantInt>(I->getOperand(1))) {
699      if (!CanEvaluateZExtd(I->getOperand(0), Ty, BitsToClear))
700        return false;
701      BitsToClear += Amt->getZExtValue();
702      if (BitsToClear > V->getType()->getScalarSizeInBits())
703        BitsToClear = V->getType()->getScalarSizeInBits();
704      return true;
705    }
706    // Cannot promote variable LSHR.
707    return false;
708  case Instruction::Select:
709    if (!CanEvaluateZExtd(I->getOperand(1), Ty, Tmp) ||
710        !CanEvaluateZExtd(I->getOperand(2), Ty, BitsToClear) ||
711        // TODO: If important, we could handle the case when the BitsToClear are
712        // known zero in the disagreeing side.
713        Tmp != BitsToClear)
714      return false;
715    return true;
716
717  case Instruction::PHI: {
718    // We can change a phi if we can change all operands.  Note that we never
719    // get into trouble with cyclic PHIs here because we only consider
720    // instructions with a single use.
721    PHINode *PN = cast<PHINode>(I);
722    if (!CanEvaluateZExtd(PN->getIncomingValue(0), Ty, BitsToClear))
723      return false;
724    for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i)
725      if (!CanEvaluateZExtd(PN->getIncomingValue(i), Ty, Tmp) ||
726          // TODO: If important, we could handle the case when the BitsToClear
727          // are known zero in the disagreeing input.
728          Tmp != BitsToClear)
729        return false;
730    return true;
731  }
732  default:
733    // TODO: Can handle more cases here.
734    return false;
735  }
736}
737
738Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
739  // If this zero extend is only used by a truncate, let the truncate by
740  // eliminated before we try to optimize this zext.
741  if (CI.hasOneUse() && isa<TruncInst>(CI.use_back()))
742    return 0;
743
744  // If one of the common conversion will work, do it.
745  if (Instruction *Result = commonCastTransforms(CI))
746    return Result;
747
748  // See if we can simplify any instructions used by the input whose sole
749  // purpose is to compute bits we don't care about.
750  if (SimplifyDemandedInstructionBits(CI))
751    return &CI;
752
753  Value *Src = CI.getOperand(0);
754  Type *SrcTy = Src->getType(), *DestTy = CI.getType();
755
756  // Attempt to extend the entire input expression tree to the destination
757  // type.   Only do this if the dest type is a simple type, don't convert the
758  // expression tree to something weird like i93 unless the source is also
759  // strange.
760  unsigned BitsToClear;
761  if ((DestTy->isVectorTy() || ShouldChangeType(SrcTy, DestTy)) &&
762      CanEvaluateZExtd(Src, DestTy, BitsToClear)) {
763    assert(BitsToClear < SrcTy->getScalarSizeInBits() &&
764           "Unreasonable BitsToClear");
765
766    // Okay, we can transform this!  Insert the new expression now.
767    DEBUG(dbgs() << "ICE: EvaluateInDifferentType converting expression type"
768          " to avoid zero extend: " << CI);
769    Value *Res = EvaluateInDifferentType(Src, DestTy, false);
770    assert(Res->getType() == DestTy);
771
772    uint32_t SrcBitsKept = SrcTy->getScalarSizeInBits()-BitsToClear;
773    uint32_t DestBitSize = DestTy->getScalarSizeInBits();
774
775    // If the high bits are already filled with zeros, just replace this
776    // cast with the result.
777    if (MaskedValueIsZero(Res, APInt::getHighBitsSet(DestBitSize,
778                                                     DestBitSize-SrcBitsKept)))
779      return ReplaceInstUsesWith(CI, Res);
780
781    // We need to emit an AND to clear the high bits.
782    Constant *C = ConstantInt::get(Res->getType(),
783                               APInt::getLowBitsSet(DestBitSize, SrcBitsKept));
784    return BinaryOperator::CreateAnd(Res, C);
785  }
786
787  // If this is a TRUNC followed by a ZEXT then we are dealing with integral
788  // types and if the sizes are just right we can convert this into a logical
789  // 'and' which will be much cheaper than the pair of casts.
790  if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) {   // A->B->C cast
791    // TODO: Subsume this into EvaluateInDifferentType.
792
793    // Get the sizes of the types involved.  We know that the intermediate type
794    // will be smaller than A or C, but don't know the relation between A and C.
795    Value *A = CSrc->getOperand(0);
796    unsigned SrcSize = A->getType()->getScalarSizeInBits();
797    unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
798    unsigned DstSize = CI.getType()->getScalarSizeInBits();
799    // If we're actually extending zero bits, then if
800    // SrcSize <  DstSize: zext(a & mask)
801    // SrcSize == DstSize: a & mask
802    // SrcSize  > DstSize: trunc(a) & mask
803    if (SrcSize < DstSize) {
804      APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
805      Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
806      Value *And = Builder->CreateAnd(A, AndConst, CSrc->getName()+".mask");
807      return new ZExtInst(And, CI.getType());
808    }
809
810    if (SrcSize == DstSize) {
811      APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
812      return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
813                                                           AndValue));
814    }
815    if (SrcSize > DstSize) {
816      Value *Trunc = Builder->CreateTrunc(A, CI.getType());
817      APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
818      return BinaryOperator::CreateAnd(Trunc,
819                                       ConstantInt::get(Trunc->getType(),
820                                                        AndValue));
821    }
822  }
823
824  if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
825    return transformZExtICmp(ICI, CI);
826
827  BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
828  if (SrcI && SrcI->getOpcode() == Instruction::Or) {
829    // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
830    // of the (zext icmp) will be transformed.
831    ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
832    ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
833    if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
834        (transformZExtICmp(LHS, CI, false) ||
835         transformZExtICmp(RHS, CI, false))) {
836      Value *LCast = Builder->CreateZExt(LHS, CI.getType(), LHS->getName());
837      Value *RCast = Builder->CreateZExt(RHS, CI.getType(), RHS->getName());
838      return BinaryOperator::Create(Instruction::Or, LCast, RCast);
839    }
840  }
841
842  // zext(trunc(t) & C) -> (t & zext(C)).
843  if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
844    if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
845      if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
846        Value *TI0 = TI->getOperand(0);
847        if (TI0->getType() == CI.getType())
848          return
849            BinaryOperator::CreateAnd(TI0,
850                                ConstantExpr::getZExt(C, CI.getType()));
851      }
852
853  // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
854  if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
855    if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
856      if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
857        if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
858            And->getOperand(1) == C)
859          if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
860            Value *TI0 = TI->getOperand(0);
861            if (TI0->getType() == CI.getType()) {
862              Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
863              Value *NewAnd = Builder->CreateAnd(TI0, ZC);
864              return BinaryOperator::CreateXor(NewAnd, ZC);
865            }
866          }
867
868  // zext (xor i1 X, true) to i32  --> xor (zext i1 X to i32), 1
869  Value *X;
870  if (SrcI && SrcI->hasOneUse() && SrcI->getType()->isIntegerTy(1) &&
871      match(SrcI, m_Not(m_Value(X))) &&
872      (!X->hasOneUse() || !isa<CmpInst>(X))) {
873    Value *New = Builder->CreateZExt(X, CI.getType());
874    return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
875  }
876
877  return 0;
878}
879
880/// transformSExtICmp - Transform (sext icmp) to bitwise / integer operations
881/// in order to eliminate the icmp.
882Instruction *InstCombiner::transformSExtICmp(ICmpInst *ICI, Instruction &CI) {
883  Value *Op0 = ICI->getOperand(0), *Op1 = ICI->getOperand(1);
884  ICmpInst::Predicate Pred = ICI->getPredicate();
885
886  if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
887    // (x <s  0) ? -1 : 0 -> ashr x, 31        -> all ones if negative
888    // (x >s -1) ? -1 : 0 -> not (ashr x, 31)  -> all ones if positive
889    if ((Pred == ICmpInst::ICMP_SLT && Op1C->isZero()) ||
890        (Pred == ICmpInst::ICMP_SGT && Op1C->isAllOnesValue())) {
891
892      Value *Sh = ConstantInt::get(Op0->getType(),
893                                   Op0->getType()->getScalarSizeInBits()-1);
894      Value *In = Builder->CreateAShr(Op0, Sh, Op0->getName()+".lobit");
895      if (In->getType() != CI.getType())
896        In = Builder->CreateIntCast(In, CI.getType(), true/*SExt*/);
897
898      if (Pred == ICmpInst::ICMP_SGT)
899        In = Builder->CreateNot(In, In->getName()+".not");
900      return ReplaceInstUsesWith(CI, In);
901    }
902
903    // If we know that only one bit of the LHS of the icmp can be set and we
904    // have an equality comparison with zero or a power of 2, we can transform
905    // the icmp and sext into bitwise/integer operations.
906    if (ICI->hasOneUse() &&
907        ICI->isEquality() && (Op1C->isZero() || Op1C->getValue().isPowerOf2())){
908      unsigned BitWidth = Op1C->getType()->getBitWidth();
909      APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
910      ComputeMaskedBits(Op0, KnownZero, KnownOne);
911
912      APInt KnownZeroMask(~KnownZero);
913      if (KnownZeroMask.isPowerOf2()) {
914        Value *In = ICI->getOperand(0);
915
916        // If the icmp tests for a known zero bit we can constant fold it.
917        if (!Op1C->isZero() && Op1C->getValue() != KnownZeroMask) {
918          Value *V = Pred == ICmpInst::ICMP_NE ?
919                       ConstantInt::getAllOnesValue(CI.getType()) :
920                       ConstantInt::getNullValue(CI.getType());
921          return ReplaceInstUsesWith(CI, V);
922        }
923
924        if (!Op1C->isZero() == (Pred == ICmpInst::ICMP_NE)) {
925          // sext ((x & 2^n) == 0)   -> (x >> n) - 1
926          // sext ((x & 2^n) != 2^n) -> (x >> n) - 1
927          unsigned ShiftAmt = KnownZeroMask.countTrailingZeros();
928          // Perform a right shift to place the desired bit in the LSB.
929          if (ShiftAmt)
930            In = Builder->CreateLShr(In,
931                                     ConstantInt::get(In->getType(), ShiftAmt));
932
933          // At this point "In" is either 1 or 0. Subtract 1 to turn
934          // {1, 0} -> {0, -1}.
935          In = Builder->CreateAdd(In,
936                                  ConstantInt::getAllOnesValue(In->getType()),
937                                  "sext");
938        } else {
939          // sext ((x & 2^n) != 0)   -> (x << bitwidth-n) a>> bitwidth-1
940          // sext ((x & 2^n) == 2^n) -> (x << bitwidth-n) a>> bitwidth-1
941          unsigned ShiftAmt = KnownZeroMask.countLeadingZeros();
942          // Perform a left shift to place the desired bit in the MSB.
943          if (ShiftAmt)
944            In = Builder->CreateShl(In,
945                                    ConstantInt::get(In->getType(), ShiftAmt));
946
947          // Distribute the bit over the whole bit width.
948          In = Builder->CreateAShr(In, ConstantInt::get(In->getType(),
949                                                        BitWidth - 1), "sext");
950        }
951
952        if (CI.getType() == In->getType())
953          return ReplaceInstUsesWith(CI, In);
954        return CastInst::CreateIntegerCast(In, CI.getType(), true/*SExt*/);
955      }
956    }
957  }
958
959  // vector (x <s 0) ? -1 : 0 -> ashr x, 31   -> all ones if signed.
960  if (VectorType *VTy = dyn_cast<VectorType>(CI.getType())) {
961    if (Pred == ICmpInst::ICMP_SLT && match(Op1, m_Zero()) &&
962        Op0->getType() == CI.getType()) {
963      Type *EltTy = VTy->getElementType();
964
965      // splat the shift constant to a constant vector.
966      Constant *VSh = ConstantInt::get(VTy, EltTy->getScalarSizeInBits()-1);
967      Value *In = Builder->CreateAShr(Op0, VSh, Op0->getName()+".lobit");
968      return ReplaceInstUsesWith(CI, In);
969    }
970  }
971
972  return 0;
973}
974
975/// CanEvaluateSExtd - Return true if we can take the specified value
976/// and return it as type Ty without inserting any new casts and without
977/// changing the value of the common low bits.  This is used by code that tries
978/// to promote integer operations to a wider types will allow us to eliminate
979/// the extension.
980///
981/// This function works on both vectors and scalars.
982///
983static bool CanEvaluateSExtd(Value *V, Type *Ty) {
984  assert(V->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits() &&
985         "Can't sign extend type to a smaller type");
986  // If this is a constant, it can be trivially promoted.
987  if (isa<Constant>(V))
988    return true;
989
990  Instruction *I = dyn_cast<Instruction>(V);
991  if (!I) return false;
992
993  // If this is a truncate from the dest type, we can trivially eliminate it.
994  if (isa<TruncInst>(I) && I->getOperand(0)->getType() == Ty)
995    return true;
996
997  // We can't extend or shrink something that has multiple uses: doing so would
998  // require duplicating the instruction in general, which isn't profitable.
999  if (!I->hasOneUse()) return false;
1000
1001  switch (I->getOpcode()) {
1002  case Instruction::SExt:  // sext(sext(x)) -> sext(x)
1003  case Instruction::ZExt:  // sext(zext(x)) -> zext(x)
1004  case Instruction::Trunc: // sext(trunc(x)) -> trunc(x) or sext(x)
1005    return true;
1006  case Instruction::And:
1007  case Instruction::Or:
1008  case Instruction::Xor:
1009  case Instruction::Add:
1010  case Instruction::Sub:
1011  case Instruction::Mul:
1012    // These operators can all arbitrarily be extended if their inputs can.
1013    return CanEvaluateSExtd(I->getOperand(0), Ty) &&
1014           CanEvaluateSExtd(I->getOperand(1), Ty);
1015
1016  //case Instruction::Shl:   TODO
1017  //case Instruction::LShr:  TODO
1018
1019  case Instruction::Select:
1020    return CanEvaluateSExtd(I->getOperand(1), Ty) &&
1021           CanEvaluateSExtd(I->getOperand(2), Ty);
1022
1023  case Instruction::PHI: {
1024    // We can change a phi if we can change all operands.  Note that we never
1025    // get into trouble with cyclic PHIs here because we only consider
1026    // instructions with a single use.
1027    PHINode *PN = cast<PHINode>(I);
1028    for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1029      if (!CanEvaluateSExtd(PN->getIncomingValue(i), Ty)) return false;
1030    return true;
1031  }
1032  default:
1033    // TODO: Can handle more cases here.
1034    break;
1035  }
1036
1037  return false;
1038}
1039
1040Instruction *InstCombiner::visitSExt(SExtInst &CI) {
1041  // If this sign extend is only used by a truncate, let the truncate by
1042  // eliminated before we try to optimize this zext.
1043  if (CI.hasOneUse() && isa<TruncInst>(CI.use_back()))
1044    return 0;
1045
1046  if (Instruction *I = commonCastTransforms(CI))
1047    return I;
1048
1049  // See if we can simplify any instructions used by the input whose sole
1050  // purpose is to compute bits we don't care about.
1051  if (SimplifyDemandedInstructionBits(CI))
1052    return &CI;
1053
1054  Value *Src = CI.getOperand(0);
1055  Type *SrcTy = Src->getType(), *DestTy = CI.getType();
1056
1057  // Attempt to extend the entire input expression tree to the destination
1058  // type.   Only do this if the dest type is a simple type, don't convert the
1059  // expression tree to something weird like i93 unless the source is also
1060  // strange.
1061  if ((DestTy->isVectorTy() || ShouldChangeType(SrcTy, DestTy)) &&
1062      CanEvaluateSExtd(Src, DestTy)) {
1063    // Okay, we can transform this!  Insert the new expression now.
1064    DEBUG(dbgs() << "ICE: EvaluateInDifferentType converting expression type"
1065          " to avoid sign extend: " << CI);
1066    Value *Res = EvaluateInDifferentType(Src, DestTy, true);
1067    assert(Res->getType() == DestTy);
1068
1069    uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
1070    uint32_t DestBitSize = DestTy->getScalarSizeInBits();
1071
1072    // If the high bits are already filled with sign bit, just replace this
1073    // cast with the result.
1074    if (ComputeNumSignBits(Res) > DestBitSize - SrcBitSize)
1075      return ReplaceInstUsesWith(CI, Res);
1076
1077    // We need to emit a shl + ashr to do the sign extend.
1078    Value *ShAmt = ConstantInt::get(DestTy, DestBitSize-SrcBitSize);
1079    return BinaryOperator::CreateAShr(Builder->CreateShl(Res, ShAmt, "sext"),
1080                                      ShAmt);
1081  }
1082
1083  // If this input is a trunc from our destination, then turn sext(trunc(x))
1084  // into shifts.
1085  if (TruncInst *TI = dyn_cast<TruncInst>(Src))
1086    if (TI->hasOneUse() && TI->getOperand(0)->getType() == DestTy) {
1087      uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
1088      uint32_t DestBitSize = DestTy->getScalarSizeInBits();
1089
1090      // We need to emit a shl + ashr to do the sign extend.
1091      Value *ShAmt = ConstantInt::get(DestTy, DestBitSize-SrcBitSize);
1092      Value *Res = Builder->CreateShl(TI->getOperand(0), ShAmt, "sext");
1093      return BinaryOperator::CreateAShr(Res, ShAmt);
1094    }
1095
1096  if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
1097    return transformSExtICmp(ICI, CI);
1098
1099  // If the input is a shl/ashr pair of a same constant, then this is a sign
1100  // extension from a smaller value.  If we could trust arbitrary bitwidth
1101  // integers, we could turn this into a truncate to the smaller bit and then
1102  // use a sext for the whole extension.  Since we don't, look deeper and check
1103  // for a truncate.  If the source and dest are the same type, eliminate the
1104  // trunc and extend and just do shifts.  For example, turn:
1105  //   %a = trunc i32 %i to i8
1106  //   %b = shl i8 %a, 6
1107  //   %c = ashr i8 %b, 6
1108  //   %d = sext i8 %c to i32
1109  // into:
1110  //   %a = shl i32 %i, 30
1111  //   %d = ashr i32 %a, 30
1112  Value *A = 0;
1113  // TODO: Eventually this could be subsumed by EvaluateInDifferentType.
1114  ConstantInt *BA = 0, *CA = 0;
1115  if (match(Src, m_AShr(m_Shl(m_Trunc(m_Value(A)), m_ConstantInt(BA)),
1116                        m_ConstantInt(CA))) &&
1117      BA == CA && A->getType() == CI.getType()) {
1118    unsigned MidSize = Src->getType()->getScalarSizeInBits();
1119    unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
1120    unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
1121    Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
1122    A = Builder->CreateShl(A, ShAmtV, CI.getName());
1123    return BinaryOperator::CreateAShr(A, ShAmtV);
1124  }
1125
1126  return 0;
1127}
1128
1129
1130/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
1131/// in the specified FP type without changing its value.
1132static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
1133  bool losesInfo;
1134  APFloat F = CFP->getValueAPF();
1135  (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
1136  if (!losesInfo)
1137    return ConstantFP::get(CFP->getContext(), F);
1138  return 0;
1139}
1140
1141/// LookThroughFPExtensions - If this is an fp extension instruction, look
1142/// through it until we get the source value.
1143static Value *LookThroughFPExtensions(Value *V) {
1144  if (Instruction *I = dyn_cast<Instruction>(V))
1145    if (I->getOpcode() == Instruction::FPExt)
1146      return LookThroughFPExtensions(I->getOperand(0));
1147
1148  // If this value is a constant, return the constant in the smallest FP type
1149  // that can accurately represent it.  This allows us to turn
1150  // (float)((double)X+2.0) into x+2.0f.
1151  if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
1152    if (CFP->getType() == Type::getPPC_FP128Ty(V->getContext()))
1153      return V;  // No constant folding of this.
1154    // See if the value can be truncated to half and then reextended.
1155    if (Value *V = FitsInFPType(CFP, APFloat::IEEEhalf))
1156      return V;
1157    // See if the value can be truncated to float and then reextended.
1158    if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
1159      return V;
1160    if (CFP->getType()->isDoubleTy())
1161      return V;  // Won't shrink.
1162    if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
1163      return V;
1164    // Don't try to shrink to various long double types.
1165  }
1166
1167  return V;
1168}
1169
1170Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
1171  if (Instruction *I = commonCastTransforms(CI))
1172    return I;
1173
1174  // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
1175  // smaller than the destination type, we can eliminate the truncate by doing
1176  // the add as the smaller type.  This applies to fadd/fsub/fmul/fdiv as well
1177  // as many builtins (sqrt, etc).
1178  BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
1179  if (OpI && OpI->hasOneUse()) {
1180    switch (OpI->getOpcode()) {
1181    default: break;
1182    case Instruction::FAdd:
1183    case Instruction::FSub:
1184    case Instruction::FMul:
1185    case Instruction::FDiv:
1186    case Instruction::FRem:
1187      Type *SrcTy = OpI->getType();
1188      Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
1189      Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
1190      if (LHSTrunc->getType() != SrcTy &&
1191          RHSTrunc->getType() != SrcTy) {
1192        unsigned DstSize = CI.getType()->getScalarSizeInBits();
1193        // If the source types were both smaller than the destination type of
1194        // the cast, do this xform.
1195        if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
1196            RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
1197          LHSTrunc = Builder->CreateFPExt(LHSTrunc, CI.getType());
1198          RHSTrunc = Builder->CreateFPExt(RHSTrunc, CI.getType());
1199          return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
1200        }
1201      }
1202      break;
1203    }
1204  }
1205
1206  // Fold (fptrunc (sqrt (fpext x))) -> (sqrtf x)
1207  CallInst *Call = dyn_cast<CallInst>(CI.getOperand(0));
1208  if (Call && Call->getCalledFunction() && TLI->has(LibFunc::sqrtf) &&
1209      Call->getCalledFunction()->getName() == TLI->getName(LibFunc::sqrt) &&
1210      Call->getNumArgOperands() == 1 &&
1211      Call->hasOneUse()) {
1212    CastInst *Arg = dyn_cast<CastInst>(Call->getArgOperand(0));
1213    if (Arg && Arg->getOpcode() == Instruction::FPExt &&
1214        CI.getType()->isFloatTy() &&
1215        Call->getType()->isDoubleTy() &&
1216        Arg->getType()->isDoubleTy() &&
1217        Arg->getOperand(0)->getType()->isFloatTy()) {
1218      Function *Callee = Call->getCalledFunction();
1219      Module *M = CI.getParent()->getParent()->getParent();
1220      Constant *SqrtfFunc = M->getOrInsertFunction("sqrtf",
1221                                                   Callee->getAttributes(),
1222                                                   Builder->getFloatTy(),
1223                                                   Builder->getFloatTy(),
1224                                                   NULL);
1225      CallInst *ret = CallInst::Create(SqrtfFunc, Arg->getOperand(0),
1226                                       "sqrtfcall");
1227      ret->setAttributes(Callee->getAttributes());
1228
1229
1230      // Remove the old Call.  With -fmath-errno, it won't get marked readnone.
1231      ReplaceInstUsesWith(*Call, UndefValue::get(Call->getType()));
1232      EraseInstFromFunction(*Call);
1233      return ret;
1234    }
1235  }
1236
1237  return 0;
1238}
1239
1240Instruction *InstCombiner::visitFPExt(CastInst &CI) {
1241  return commonCastTransforms(CI);
1242}
1243
1244Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
1245  Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
1246  if (OpI == 0)
1247    return commonCastTransforms(FI);
1248
1249  // fptoui(uitofp(X)) --> X
1250  // fptoui(sitofp(X)) --> X
1251  // This is safe if the intermediate type has enough bits in its mantissa to
1252  // accurately represent all values of X.  For example, do not do this with
1253  // i64->float->i64.  This is also safe for sitofp case, because any negative
1254  // 'X' value would cause an undefined result for the fptoui.
1255  if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
1256      OpI->getOperand(0)->getType() == FI.getType() &&
1257      (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
1258                    OpI->getType()->getFPMantissaWidth())
1259    return ReplaceInstUsesWith(FI, OpI->getOperand(0));
1260
1261  return commonCastTransforms(FI);
1262}
1263
1264Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
1265  Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
1266  if (OpI == 0)
1267    return commonCastTransforms(FI);
1268
1269  // fptosi(sitofp(X)) --> X
1270  // fptosi(uitofp(X)) --> X
1271  // This is safe if the intermediate type has enough bits in its mantissa to
1272  // accurately represent all values of X.  For example, do not do this with
1273  // i64->float->i64.  This is also safe for sitofp case, because any negative
1274  // 'X' value would cause an undefined result for the fptoui.
1275  if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
1276      OpI->getOperand(0)->getType() == FI.getType() &&
1277      (int)FI.getType()->getScalarSizeInBits() <=
1278                    OpI->getType()->getFPMantissaWidth())
1279    return ReplaceInstUsesWith(FI, OpI->getOperand(0));
1280
1281  return commonCastTransforms(FI);
1282}
1283
1284Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
1285  return commonCastTransforms(CI);
1286}
1287
1288Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
1289  return commonCastTransforms(CI);
1290}
1291
1292Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
1293  // If the source integer type is not the intptr_t type for this target, do a
1294  // trunc or zext to the intptr_t type, then inttoptr of it.  This allows the
1295  // cast to be exposed to other transforms.
1296  if (TD) {
1297    if (CI.getOperand(0)->getType()->getScalarSizeInBits() >
1298        TD->getPointerSizeInBits()) {
1299      Value *P = Builder->CreateTrunc(CI.getOperand(0),
1300                                      TD->getIntPtrType(CI.getContext()));
1301      return new IntToPtrInst(P, CI.getType());
1302    }
1303    if (CI.getOperand(0)->getType()->getScalarSizeInBits() <
1304        TD->getPointerSizeInBits()) {
1305      Value *P = Builder->CreateZExt(CI.getOperand(0),
1306                                     TD->getIntPtrType(CI.getContext()));
1307      return new IntToPtrInst(P, CI.getType());
1308    }
1309  }
1310
1311  if (Instruction *I = commonCastTransforms(CI))
1312    return I;
1313
1314  return 0;
1315}
1316
1317/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
1318Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
1319  Value *Src = CI.getOperand(0);
1320
1321  if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
1322    // If casting the result of a getelementptr instruction with no offset, turn
1323    // this into a cast of the original pointer!
1324    if (GEP->hasAllZeroIndices()) {
1325      // Changing the cast operand is usually not a good idea but it is safe
1326      // here because the pointer operand is being replaced with another
1327      // pointer operand so the opcode doesn't need to change.
1328      Worklist.Add(GEP);
1329      CI.setOperand(0, GEP->getOperand(0));
1330      return &CI;
1331    }
1332
1333    // If the GEP has a single use, and the base pointer is a bitcast, and the
1334    // GEP computes a constant offset, see if we can convert these three
1335    // instructions into fewer.  This typically happens with unions and other
1336    // non-type-safe code.
1337    if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0)) &&
1338        GEP->hasAllConstantIndices()) {
1339      SmallVector<Value*, 8> Ops(GEP->idx_begin(), GEP->idx_end());
1340      int64_t Offset = TD->getIndexedOffset(GEP->getPointerOperandType(), Ops);
1341
1342      // Get the base pointer input of the bitcast, and the type it points to.
1343      Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
1344      Type *GEPIdxTy =
1345      cast<PointerType>(OrigBase->getType())->getElementType();
1346      SmallVector<Value*, 8> NewIndices;
1347      if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices)) {
1348        // If we were able to index down into an element, create the GEP
1349        // and bitcast the result.  This eliminates one bitcast, potentially
1350        // two.
1351        Value *NGEP = cast<GEPOperator>(GEP)->isInBounds() ?
1352        Builder->CreateInBoundsGEP(OrigBase, NewIndices) :
1353        Builder->CreateGEP(OrigBase, NewIndices);
1354        NGEP->takeName(GEP);
1355
1356        if (isa<BitCastInst>(CI))
1357          return new BitCastInst(NGEP, CI.getType());
1358        assert(isa<PtrToIntInst>(CI));
1359        return new PtrToIntInst(NGEP, CI.getType());
1360      }
1361    }
1362  }
1363
1364  return commonCastTransforms(CI);
1365}
1366
1367Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
1368  // If the destination integer type is not the intptr_t type for this target,
1369  // do a ptrtoint to intptr_t then do a trunc or zext.  This allows the cast
1370  // to be exposed to other transforms.
1371  if (TD) {
1372    if (CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
1373      Value *P = Builder->CreatePtrToInt(CI.getOperand(0),
1374                                         TD->getIntPtrType(CI.getContext()));
1375      return new TruncInst(P, CI.getType());
1376    }
1377    if (CI.getType()->getScalarSizeInBits() > TD->getPointerSizeInBits()) {
1378      Value *P = Builder->CreatePtrToInt(CI.getOperand(0),
1379                                         TD->getIntPtrType(CI.getContext()));
1380      return new ZExtInst(P, CI.getType());
1381    }
1382  }
1383
1384  return commonPointerCastTransforms(CI);
1385}
1386
1387/// OptimizeVectorResize - This input value (which is known to have vector type)
1388/// is being zero extended or truncated to the specified vector type.  Try to
1389/// replace it with a shuffle (and vector/vector bitcast) if possible.
1390///
1391/// The source and destination vector types may have different element types.
1392static Instruction *OptimizeVectorResize(Value *InVal, VectorType *DestTy,
1393                                         InstCombiner &IC) {
1394  // We can only do this optimization if the output is a multiple of the input
1395  // element size, or the input is a multiple of the output element size.
1396  // Convert the input type to have the same element type as the output.
1397  VectorType *SrcTy = cast<VectorType>(InVal->getType());
1398
1399  if (SrcTy->getElementType() != DestTy->getElementType()) {
1400    // The input types don't need to be identical, but for now they must be the
1401    // same size.  There is no specific reason we couldn't handle things like
1402    // <4 x i16> -> <4 x i32> by bitcasting to <2 x i32> but haven't gotten
1403    // there yet.
1404    if (SrcTy->getElementType()->getPrimitiveSizeInBits() !=
1405        DestTy->getElementType()->getPrimitiveSizeInBits())
1406      return 0;
1407
1408    SrcTy = VectorType::get(DestTy->getElementType(), SrcTy->getNumElements());
1409    InVal = IC.Builder->CreateBitCast(InVal, SrcTy);
1410  }
1411
1412  // Now that the element types match, get the shuffle mask and RHS of the
1413  // shuffle to use, which depends on whether we're increasing or decreasing the
1414  // size of the input.
1415  SmallVector<uint32_t, 16> ShuffleMask;
1416  Value *V2;
1417
1418  if (SrcTy->getNumElements() > DestTy->getNumElements()) {
1419    // If we're shrinking the number of elements, just shuffle in the low
1420    // elements from the input and use undef as the second shuffle input.
1421    V2 = UndefValue::get(SrcTy);
1422    for (unsigned i = 0, e = DestTy->getNumElements(); i != e; ++i)
1423      ShuffleMask.push_back(i);
1424
1425  } else {
1426    // If we're increasing the number of elements, shuffle in all of the
1427    // elements from InVal and fill the rest of the result elements with zeros
1428    // from a constant zero.
1429    V2 = Constant::getNullValue(SrcTy);
1430    unsigned SrcElts = SrcTy->getNumElements();
1431    for (unsigned i = 0, e = SrcElts; i != e; ++i)
1432      ShuffleMask.push_back(i);
1433
1434    // The excess elements reference the first element of the zero input.
1435    for (unsigned i = 0, e = DestTy->getNumElements()-SrcElts; i != e; ++i)
1436      ShuffleMask.push_back(SrcElts);
1437  }
1438
1439  return new ShuffleVectorInst(InVal, V2,
1440                               ConstantDataVector::get(V2->getContext(),
1441                                                       ShuffleMask));
1442}
1443
1444static bool isMultipleOfTypeSize(unsigned Value, Type *Ty) {
1445  return Value % Ty->getPrimitiveSizeInBits() == 0;
1446}
1447
1448static unsigned getTypeSizeIndex(unsigned Value, Type *Ty) {
1449  return Value / Ty->getPrimitiveSizeInBits();
1450}
1451
1452/// CollectInsertionElements - V is a value which is inserted into a vector of
1453/// VecEltTy.  Look through the value to see if we can decompose it into
1454/// insertions into the vector.  See the example in the comment for
1455/// OptimizeIntegerToVectorInsertions for the pattern this handles.
1456/// The type of V is always a non-zero multiple of VecEltTy's size.
1457///
1458/// This returns false if the pattern can't be matched or true if it can,
1459/// filling in Elements with the elements found here.
1460static bool CollectInsertionElements(Value *V, unsigned ElementIndex,
1461                                     SmallVectorImpl<Value*> &Elements,
1462                                     Type *VecEltTy) {
1463  // Undef values never contribute useful bits to the result.
1464  if (isa<UndefValue>(V)) return true;
1465
1466  // If we got down to a value of the right type, we win, try inserting into the
1467  // right element.
1468  if (V->getType() == VecEltTy) {
1469    // Inserting null doesn't actually insert any elements.
1470    if (Constant *C = dyn_cast<Constant>(V))
1471      if (C->isNullValue())
1472        return true;
1473
1474    // Fail if multiple elements are inserted into this slot.
1475    if (ElementIndex >= Elements.size() || Elements[ElementIndex] != 0)
1476      return false;
1477
1478    Elements[ElementIndex] = V;
1479    return true;
1480  }
1481
1482  if (Constant *C = dyn_cast<Constant>(V)) {
1483    // Figure out the # elements this provides, and bitcast it or slice it up
1484    // as required.
1485    unsigned NumElts = getTypeSizeIndex(C->getType()->getPrimitiveSizeInBits(),
1486                                        VecEltTy);
1487    // If the constant is the size of a vector element, we just need to bitcast
1488    // it to the right type so it gets properly inserted.
1489    if (NumElts == 1)
1490      return CollectInsertionElements(ConstantExpr::getBitCast(C, VecEltTy),
1491                                      ElementIndex, Elements, VecEltTy);
1492
1493    // Okay, this is a constant that covers multiple elements.  Slice it up into
1494    // pieces and insert each element-sized piece into the vector.
1495    if (!isa<IntegerType>(C->getType()))
1496      C = ConstantExpr::getBitCast(C, IntegerType::get(V->getContext(),
1497                                       C->getType()->getPrimitiveSizeInBits()));
1498    unsigned ElementSize = VecEltTy->getPrimitiveSizeInBits();
1499    Type *ElementIntTy = IntegerType::get(C->getContext(), ElementSize);
1500
1501    for (unsigned i = 0; i != NumElts; ++i) {
1502      Constant *Piece = ConstantExpr::getLShr(C, ConstantInt::get(C->getType(),
1503                                                               i*ElementSize));
1504      Piece = ConstantExpr::getTrunc(Piece, ElementIntTy);
1505      if (!CollectInsertionElements(Piece, ElementIndex+i, Elements, VecEltTy))
1506        return false;
1507    }
1508    return true;
1509  }
1510
1511  if (!V->hasOneUse()) return false;
1512
1513  Instruction *I = dyn_cast<Instruction>(V);
1514  if (I == 0) return false;
1515  switch (I->getOpcode()) {
1516  default: return false; // Unhandled case.
1517  case Instruction::BitCast:
1518    return CollectInsertionElements(I->getOperand(0), ElementIndex,
1519                                    Elements, VecEltTy);
1520  case Instruction::ZExt:
1521    if (!isMultipleOfTypeSize(
1522                          I->getOperand(0)->getType()->getPrimitiveSizeInBits(),
1523                              VecEltTy))
1524      return false;
1525    return CollectInsertionElements(I->getOperand(0), ElementIndex,
1526                                    Elements, VecEltTy);
1527  case Instruction::Or:
1528    return CollectInsertionElements(I->getOperand(0), ElementIndex,
1529                                    Elements, VecEltTy) &&
1530           CollectInsertionElements(I->getOperand(1), ElementIndex,
1531                                    Elements, VecEltTy);
1532  case Instruction::Shl: {
1533    // Must be shifting by a constant that is a multiple of the element size.
1534    ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1));
1535    if (CI == 0) return false;
1536    if (!isMultipleOfTypeSize(CI->getZExtValue(), VecEltTy)) return false;
1537    unsigned IndexShift = getTypeSizeIndex(CI->getZExtValue(), VecEltTy);
1538
1539    return CollectInsertionElements(I->getOperand(0), ElementIndex+IndexShift,
1540                                    Elements, VecEltTy);
1541  }
1542
1543  }
1544}
1545
1546
1547/// OptimizeIntegerToVectorInsertions - If the input is an 'or' instruction, we
1548/// may be doing shifts and ors to assemble the elements of the vector manually.
1549/// Try to rip the code out and replace it with insertelements.  This is to
1550/// optimize code like this:
1551///
1552///    %tmp37 = bitcast float %inc to i32
1553///    %tmp38 = zext i32 %tmp37 to i64
1554///    %tmp31 = bitcast float %inc5 to i32
1555///    %tmp32 = zext i32 %tmp31 to i64
1556///    %tmp33 = shl i64 %tmp32, 32
1557///    %ins35 = or i64 %tmp33, %tmp38
1558///    %tmp43 = bitcast i64 %ins35 to <2 x float>
1559///
1560/// Into two insertelements that do "buildvector{%inc, %inc5}".
1561static Value *OptimizeIntegerToVectorInsertions(BitCastInst &CI,
1562                                                InstCombiner &IC) {
1563  VectorType *DestVecTy = cast<VectorType>(CI.getType());
1564  Value *IntInput = CI.getOperand(0);
1565
1566  SmallVector<Value*, 8> Elements(DestVecTy->getNumElements());
1567  if (!CollectInsertionElements(IntInput, 0, Elements,
1568                                DestVecTy->getElementType()))
1569    return 0;
1570
1571  // If we succeeded, we know that all of the element are specified by Elements
1572  // or are zero if Elements has a null entry.  Recast this as a set of
1573  // insertions.
1574  Value *Result = Constant::getNullValue(CI.getType());
1575  for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
1576    if (Elements[i] == 0) continue;  // Unset element.
1577
1578    Result = IC.Builder->CreateInsertElement(Result, Elements[i],
1579                                             IC.Builder->getInt32(i));
1580  }
1581
1582  return Result;
1583}
1584
1585
1586/// OptimizeIntToFloatBitCast - See if we can optimize an integer->float/double
1587/// bitcast.  The various long double bitcasts can't get in here.
1588static Instruction *OptimizeIntToFloatBitCast(BitCastInst &CI,InstCombiner &IC){
1589  Value *Src = CI.getOperand(0);
1590  Type *DestTy = CI.getType();
1591
1592  // If this is a bitcast from int to float, check to see if the int is an
1593  // extraction from a vector.
1594  Value *VecInput = 0;
1595  // bitcast(trunc(bitcast(somevector)))
1596  if (match(Src, m_Trunc(m_BitCast(m_Value(VecInput)))) &&
1597      isa<VectorType>(VecInput->getType())) {
1598    VectorType *VecTy = cast<VectorType>(VecInput->getType());
1599    unsigned DestWidth = DestTy->getPrimitiveSizeInBits();
1600
1601    if (VecTy->getPrimitiveSizeInBits() % DestWidth == 0) {
1602      // If the element type of the vector doesn't match the result type,
1603      // bitcast it to be a vector type we can extract from.
1604      if (VecTy->getElementType() != DestTy) {
1605        VecTy = VectorType::get(DestTy,
1606                                VecTy->getPrimitiveSizeInBits() / DestWidth);
1607        VecInput = IC.Builder->CreateBitCast(VecInput, VecTy);
1608      }
1609
1610      return ExtractElementInst::Create(VecInput, IC.Builder->getInt32(0));
1611    }
1612  }
1613
1614  // bitcast(trunc(lshr(bitcast(somevector), cst))
1615  ConstantInt *ShAmt = 0;
1616  if (match(Src, m_Trunc(m_LShr(m_BitCast(m_Value(VecInput)),
1617                                m_ConstantInt(ShAmt)))) &&
1618      isa<VectorType>(VecInput->getType())) {
1619    VectorType *VecTy = cast<VectorType>(VecInput->getType());
1620    unsigned DestWidth = DestTy->getPrimitiveSizeInBits();
1621    if (VecTy->getPrimitiveSizeInBits() % DestWidth == 0 &&
1622        ShAmt->getZExtValue() % DestWidth == 0) {
1623      // If the element type of the vector doesn't match the result type,
1624      // bitcast it to be a vector type we can extract from.
1625      if (VecTy->getElementType() != DestTy) {
1626        VecTy = VectorType::get(DestTy,
1627                                VecTy->getPrimitiveSizeInBits() / DestWidth);
1628        VecInput = IC.Builder->CreateBitCast(VecInput, VecTy);
1629      }
1630
1631      unsigned Elt = ShAmt->getZExtValue() / DestWidth;
1632      return ExtractElementInst::Create(VecInput, IC.Builder->getInt32(Elt));
1633    }
1634  }
1635  return 0;
1636}
1637
1638Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
1639  // If the operands are integer typed then apply the integer transforms,
1640  // otherwise just apply the common ones.
1641  Value *Src = CI.getOperand(0);
1642  Type *SrcTy = Src->getType();
1643  Type *DestTy = CI.getType();
1644
1645  // Get rid of casts from one type to the same type. These are useless and can
1646  // be replaced by the operand.
1647  if (DestTy == Src->getType())
1648    return ReplaceInstUsesWith(CI, Src);
1649
1650  if (PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
1651    PointerType *SrcPTy = cast<PointerType>(SrcTy);
1652    Type *DstElTy = DstPTy->getElementType();
1653    Type *SrcElTy = SrcPTy->getElementType();
1654
1655    // If the address spaces don't match, don't eliminate the bitcast, which is
1656    // required for changing types.
1657    if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
1658      return 0;
1659
1660    // If we are casting a alloca to a pointer to a type of the same
1661    // size, rewrite the allocation instruction to allocate the "right" type.
1662    // There is no need to modify malloc calls because it is their bitcast that
1663    // needs to be cleaned up.
1664    if (AllocaInst *AI = dyn_cast<AllocaInst>(Src))
1665      if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
1666        return V;
1667
1668    // If the source and destination are pointers, and this cast is equivalent
1669    // to a getelementptr X, 0, 0, 0...  turn it into the appropriate gep.
1670    // This can enhance SROA and other transforms that want type-safe pointers.
1671    Constant *ZeroUInt =
1672      Constant::getNullValue(Type::getInt32Ty(CI.getContext()));
1673    unsigned NumZeros = 0;
1674    while (SrcElTy != DstElTy &&
1675           isa<CompositeType>(SrcElTy) && !SrcElTy->isPointerTy() &&
1676           SrcElTy->getNumContainedTypes() /* not "{}" */) {
1677      SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
1678      ++NumZeros;
1679    }
1680
1681    // If we found a path from the src to dest, create the getelementptr now.
1682    if (SrcElTy == DstElTy) {
1683      SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
1684      return GetElementPtrInst::CreateInBounds(Src, Idxs);
1685    }
1686  }
1687
1688  // Try to optimize int -> float bitcasts.
1689  if ((DestTy->isFloatTy() || DestTy->isDoubleTy()) && isa<IntegerType>(SrcTy))
1690    if (Instruction *I = OptimizeIntToFloatBitCast(CI, *this))
1691      return I;
1692
1693  if (VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
1694    if (DestVTy->getNumElements() == 1 && !SrcTy->isVectorTy()) {
1695      Value *Elem = Builder->CreateBitCast(Src, DestVTy->getElementType());
1696      return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
1697                     Constant::getNullValue(Type::getInt32Ty(CI.getContext())));
1698      // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
1699    }
1700
1701    if (isa<IntegerType>(SrcTy)) {
1702      // If this is a cast from an integer to vector, check to see if the input
1703      // is a trunc or zext of a bitcast from vector.  If so, we can replace all
1704      // the casts with a shuffle and (potentially) a bitcast.
1705      if (isa<TruncInst>(Src) || isa<ZExtInst>(Src)) {
1706        CastInst *SrcCast = cast<CastInst>(Src);
1707        if (BitCastInst *BCIn = dyn_cast<BitCastInst>(SrcCast->getOperand(0)))
1708          if (isa<VectorType>(BCIn->getOperand(0)->getType()))
1709            if (Instruction *I = OptimizeVectorResize(BCIn->getOperand(0),
1710                                               cast<VectorType>(DestTy), *this))
1711              return I;
1712      }
1713
1714      // If the input is an 'or' instruction, we may be doing shifts and ors to
1715      // assemble the elements of the vector manually.  Try to rip the code out
1716      // and replace it with insertelements.
1717      if (Value *V = OptimizeIntegerToVectorInsertions(CI, *this))
1718        return ReplaceInstUsesWith(CI, V);
1719    }
1720  }
1721
1722  if (VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
1723    if (SrcVTy->getNumElements() == 1 && !DestTy->isVectorTy()) {
1724      Value *Elem =
1725        Builder->CreateExtractElement(Src,
1726                   Constant::getNullValue(Type::getInt32Ty(CI.getContext())));
1727      return CastInst::Create(Instruction::BitCast, Elem, DestTy);
1728    }
1729  }
1730
1731  if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
1732    // Okay, we have (bitcast (shuffle ..)).  Check to see if this is
1733    // a bitcast to a vector with the same # elts.
1734    if (SVI->hasOneUse() && DestTy->isVectorTy() &&
1735        cast<VectorType>(DestTy)->getNumElements() ==
1736              SVI->getType()->getNumElements() &&
1737        SVI->getType()->getNumElements() ==
1738          cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
1739      BitCastInst *Tmp;
1740      // If either of the operands is a cast from CI.getType(), then
1741      // evaluating the shuffle in the casted destination's type will allow
1742      // us to eliminate at least one cast.
1743      if (((Tmp = dyn_cast<BitCastInst>(SVI->getOperand(0))) &&
1744           Tmp->getOperand(0)->getType() == DestTy) ||
1745          ((Tmp = dyn_cast<BitCastInst>(SVI->getOperand(1))) &&
1746           Tmp->getOperand(0)->getType() == DestTy)) {
1747        Value *LHS = Builder->CreateBitCast(SVI->getOperand(0), DestTy);
1748        Value *RHS = Builder->CreateBitCast(SVI->getOperand(1), DestTy);
1749        // Return a new shuffle vector.  Use the same element ID's, as we
1750        // know the vector types match #elts.
1751        return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
1752      }
1753    }
1754  }
1755
1756  if (SrcTy->isPointerTy())
1757    return commonPointerCastTransforms(CI);
1758  return commonCastTransforms(CI);
1759}
1760