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