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