teach sext optimization to handle truncs from types that are not
[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                                         int &Offset) {
26   assert(Val->getType()->isInteger(32) && "Unexpected allocation size type!");
27   if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
28     Offset = CI->getZExtValue();
29     Scale  = 0;
30     return ConstantInt::get(Type::getInt32Ty(Val->getContext()), 0);
31   }
32   
33   if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
34     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
35       if (I->getOpcode() == Instruction::Shl) {
36         // This is a value scaled by '1 << the shift amt'.
37         Scale = 1U << RHS->getZExtValue();
38         Offset = 0;
39         return I->getOperand(0);
40       }
41       
42       if (I->getOpcode() == Instruction::Mul) {
43         // This value is scaled by 'RHS'.
44         Scale = RHS->getZExtValue();
45         Offset = 0;
46         return I->getOperand(0);
47       }
48       
49       if (I->getOpcode() == Instruction::Add) {
50         // We have X+C.  Check to see if we really have (X*C2)+C1, 
51         // where C1 is divisible by C2.
52         unsigned SubScale;
53         Value *SubVal = 
54           DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
55         Offset += RHS->getZExtValue();
56         Scale = SubScale;
57         return SubVal;
58       }
59     }
60   }
61
62   // Otherwise, we can't look past this.
63   Scale = 1;
64   Offset = 0;
65   return Val;
66 }
67
68 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
69 /// try to eliminate the cast by moving the type information into the alloc.
70 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
71                                                    AllocaInst &AI) {
72   // This requires TargetData to get the alloca alignment and size information.
73   if (!TD) return 0;
74
75   const PointerType *PTy = cast<PointerType>(CI.getType());
76   
77   BuilderTy AllocaBuilder(*Builder);
78   AllocaBuilder.SetInsertPoint(AI.getParent(), &AI);
79
80   // Get the type really allocated and the type casted to.
81   const Type *AllocElTy = AI.getAllocatedType();
82   const Type *CastElTy = PTy->getElementType();
83   if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
84
85   unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
86   unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
87   if (CastElTyAlign < AllocElTyAlign) return 0;
88
89   // If the allocation has multiple uses, only promote it if we are strictly
90   // increasing the alignment of the resultant allocation.  If we keep it the
91   // same, we open the door to infinite loops of various kinds.  (A reference
92   // from a dbg.declare doesn't count as a use for this purpose.)
93   if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
94       CastElTyAlign == AllocElTyAlign) return 0;
95
96   uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
97   uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
98   if (CastElTySize == 0 || AllocElTySize == 0) return 0;
99
100   // See if we can satisfy the modulus by pulling a scale out of the array
101   // size argument.
102   unsigned ArraySizeScale;
103   int ArrayOffset;
104   Value *NumElements = // See if the array size is a decomposable linear expr.
105     DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
106  
107   // If we can now satisfy the modulus, by using a non-1 scale, we really can
108   // do the xform.
109   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
110       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return 0;
111
112   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
113   Value *Amt = 0;
114   if (Scale == 1) {
115     Amt = NumElements;
116   } else {
117     Amt = ConstantInt::get(Type::getInt32Ty(CI.getContext()), Scale);
118     // Insert before the alloca, not before the cast.
119     Amt = AllocaBuilder.CreateMul(Amt, NumElements, "tmp");
120   }
121   
122   if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
123     Value *Off = ConstantInt::get(Type::getInt32Ty(CI.getContext()),
124                                   Offset, true);
125     Amt = AllocaBuilder.CreateAdd(Amt, Off, "tmp");
126   }
127   
128   AllocaInst *New = AllocaBuilder.CreateAlloca(CastElTy, Amt);
129   New->setAlignment(AI.getAlignment());
130   New->takeName(&AI);
131   
132   // If the allocation has one real use plus a dbg.declare, just remove the
133   // declare.
134   if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
135     EraseInstFromFunction(*(Instruction*)DI);
136   }
137   // If the allocation has multiple real uses, insert a cast and change all
138   // things that used it to use the new cast.  This will also hack on CI, but it
139   // will die soon.
140   else if (!AI.hasOneUse()) {
141     // New is the allocation instruction, pointer typed. AI is the original
142     // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
143     Value *NewCast = AllocaBuilder.CreateBitCast(New, AI.getType(), "tmpcast");
144     AI.replaceAllUsesWith(NewCast);
145   }
146   return ReplaceInstUsesWith(CI, New);
147 }
148
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, const 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);
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);
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     break;
219   }
220   
221   Res->takeName(I);
222   return InsertNewInstBefore(Res, *I);
223 }
224
225
226 /// This function is a wrapper around CastInst::isEliminableCastPair. It
227 /// simply extracts arguments and returns what that function returns.
228 static Instruction::CastOps 
229 isEliminableCastPair(
230   const CastInst *CI, ///< The first cast instruction
231   unsigned opcode,       ///< The opcode of the second cast instruction
232   const Type *DstTy,     ///< The target type for the second cast instruction
233   TargetData *TD         ///< The target data for pointer size
234 ) {
235
236   const Type *SrcTy = CI->getOperand(0)->getType();   // A from above
237   const Type *MidTy = CI->getType();                  // B from above
238
239   // Get the opcodes of the two Cast instructions
240   Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
241   Instruction::CastOps secondOp = Instruction::CastOps(opcode);
242
243   unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
244                                                 DstTy,
245                                   TD ? TD->getIntPtrType(CI->getContext()) : 0);
246   
247   // We don't want to form an inttoptr or ptrtoint that converts to an integer
248   // type that differs from the pointer size.
249   if ((Res == Instruction::IntToPtr &&
250           (!TD || SrcTy != TD->getIntPtrType(CI->getContext()))) ||
251       (Res == Instruction::PtrToInt &&
252           (!TD || DstTy != TD->getIntPtrType(CI->getContext()))))
253     Res = 0;
254   
255   return Instruction::CastOps(Res);
256 }
257
258 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
259 /// in any code being generated.  It does not require codegen if V is simple
260 /// enough or if the cast can be folded into other casts.
261 bool InstCombiner::ValueRequiresCast(Instruction::CastOps opcode,const Value *V,
262                                      const Type *Ty) {
263   if (V->getType() == Ty || isa<Constant>(V)) return false;
264   
265   // If this is another cast that can be eliminated, it isn't codegen either.
266   if (const CastInst *CI = dyn_cast<CastInst>(V))
267     if (isEliminableCastPair(CI, opcode, Ty, TD))
268       return false;
269   return true;
270 }
271
272
273 /// @brief Implement the transforms common to all CastInst visitors.
274 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
275   Value *Src = CI.getOperand(0);
276
277   // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
278   // eliminate it now.
279   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
280     if (Instruction::CastOps opc = 
281         isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
282       // The first cast (CSrc) is eliminable so we need to fix up or replace
283       // the second cast (CI). CSrc will then have a good chance of being dead.
284       return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
285     }
286   }
287
288   // If we are casting a select then fold the cast into the select
289   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
290     if (Instruction *NV = FoldOpIntoSelect(CI, SI))
291       return NV;
292
293   // If we are casting a PHI then fold the cast into the PHI
294   if (isa<PHINode>(Src)) {
295     // We don't do this if this would create a PHI node with an illegal type if
296     // it is currently legal.
297     if (!isa<IntegerType>(Src->getType()) ||
298         !isa<IntegerType>(CI.getType()) ||
299         ShouldChangeType(CI.getType(), Src->getType()))
300       if (Instruction *NV = FoldOpIntoPhi(CI))
301         return NV;
302   }
303   
304   return 0;
305 }
306
307 /// CanEvaluateTruncated - Return true if we can evaluate the specified
308 /// expression tree as type Ty instead of its larger type, and arrive with the
309 /// same value.  This is used by code that tries to eliminate truncates.
310 ///
311 /// Ty will always be a type smaller than V.  We should return true if trunc(V)
312 /// can be computed by computing V in the smaller type.  If V is an instruction,
313 /// then trunc(inst(x,y)) can be computed as inst(trunc(x),trunc(y)), which only
314 /// makes sense if x and y can be efficiently truncated.
315 ///
316 static bool CanEvaluateTruncated(Value *V, const Type *Ty) {
317   // We can always evaluate constants in another type.
318   if (isa<Constant>(V))
319     return true;
320   
321   Instruction *I = dyn_cast<Instruction>(V);
322   if (!I) return false;
323   
324   const Type *OrigTy = V->getType();
325   
326   // If this is an extension from the dest type, we can eliminate it.
327   if ((isa<ZExtInst>(I) || isa<SExtInst>(I)) && 
328       I->getOperand(0)->getType() == Ty)
329     return true;
330
331   // We can't extend or shrink something that has multiple uses: doing so would
332   // require duplicating the instruction in general, which isn't profitable.
333   if (!I->hasOneUse()) return false;
334
335   unsigned Opc = I->getOpcode();
336   switch (Opc) {
337   case Instruction::Add:
338   case Instruction::Sub:
339   case Instruction::Mul:
340   case Instruction::And:
341   case Instruction::Or:
342   case Instruction::Xor:
343     // These operators can all arbitrarily be extended or truncated.
344     return CanEvaluateTruncated(I->getOperand(0), Ty) &&
345            CanEvaluateTruncated(I->getOperand(1), Ty);
346
347   case Instruction::UDiv:
348   case Instruction::URem: {
349     // UDiv and URem can be truncated if all the truncated bits are zero.
350     uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
351     uint32_t BitWidth = Ty->getScalarSizeInBits();
352     if (BitWidth < OrigBitWidth) {
353       APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
354       if (MaskedValueIsZero(I->getOperand(0), Mask) &&
355           MaskedValueIsZero(I->getOperand(1), Mask)) {
356         return CanEvaluateTruncated(I->getOperand(0), Ty) &&
357                CanEvaluateTruncated(I->getOperand(1), Ty);
358       }
359     }
360     break;
361   }
362   case Instruction::Shl:
363     // If we are truncating the result of this SHL, and if it's a shift of a
364     // constant amount, we can always perform a SHL in a smaller type.
365     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
366       uint32_t BitWidth = Ty->getScalarSizeInBits();
367       if (CI->getLimitedValue(BitWidth) < BitWidth)
368         return CanEvaluateTruncated(I->getOperand(0), Ty);
369     }
370     break;
371   case Instruction::LShr:
372     // If this is a truncate of a logical shr, we can truncate it to a smaller
373     // lshr iff we know that the bits we would otherwise be shifting in are
374     // already zeros.
375     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
376       uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
377       uint32_t BitWidth = Ty->getScalarSizeInBits();
378       if (MaskedValueIsZero(I->getOperand(0),
379             APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
380           CI->getLimitedValue(BitWidth) < BitWidth) {
381         return CanEvaluateTruncated(I->getOperand(0), Ty);
382       }
383     }
384     break;
385   case Instruction::Trunc:
386     // trunc(trunc(x)) -> trunc(x)
387     return true;
388   case Instruction::Select: {
389     SelectInst *SI = cast<SelectInst>(I);
390     return CanEvaluateTruncated(SI->getTrueValue(), Ty) &&
391            CanEvaluateTruncated(SI->getFalseValue(), Ty);
392   }
393   case Instruction::PHI: {
394     // We can change a phi if we can change all operands.  Note that we never
395     // get into trouble with cyclic PHIs here because we only consider
396     // instructions with a single use.
397     PHINode *PN = cast<PHINode>(I);
398     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
399       if (!CanEvaluateTruncated(PN->getIncomingValue(i), Ty))
400         return false;
401     return true;
402   }
403   default:
404     // TODO: Can handle more cases here.
405     break;
406   }
407   
408   return false;
409 }
410
411 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
412   if (Instruction *Result = commonCastTransforms(CI))
413     return Result;
414   
415   // See if we can simplify any instructions used by the input whose sole 
416   // purpose is to compute bits we don't care about.
417   if (SimplifyDemandedInstructionBits(CI))
418     return &CI;
419   
420   Value *Src = CI.getOperand(0);
421   const Type *DestTy = CI.getType(), *SrcTy = Src->getType();
422   
423   // Attempt to truncate the entire input expression tree to the destination
424   // type.   Only do this if the dest type is a simple type, don't convert the
425   // expression tree to something weird like i93 unless the source is also
426   // strange.
427   if ((isa<VectorType>(DestTy) || ShouldChangeType(SrcTy, DestTy)) &&
428       CanEvaluateTruncated(Src, DestTy)) {
429       
430     // If this cast is a truncate, evaluting in a different type always
431     // eliminates the cast, so it is always a win.
432     DEBUG(dbgs() << "ICE: EvaluateInDifferentType converting expression type"
433           " to avoid cast: " << CI);
434     Value *Res = EvaluateInDifferentType(Src, DestTy, false);
435     assert(Res->getType() == DestTy);
436     return ReplaceInstUsesWith(CI, Res);
437   }
438
439   // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0), likewise for vector.
440   if (DestTy->getScalarSizeInBits() == 1) {
441     Constant *One = ConstantInt::get(Src->getType(), 1);
442     Src = Builder->CreateAnd(Src, One, "tmp");
443     Value *Zero = Constant::getNullValue(Src->getType());
444     return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
445   }
446
447   return 0;
448 }
449
450 /// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
451 /// in order to eliminate the icmp.
452 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
453                                              bool DoXform) {
454   // If we are just checking for a icmp eq of a single bit and zext'ing it
455   // to an integer, then shift the bit to the appropriate place and then
456   // cast to integer to avoid the comparison.
457   if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
458     const APInt &Op1CV = Op1C->getValue();
459       
460     // zext (x <s  0) to i32 --> x>>u31      true if signbit set.
461     // zext (x >s -1) to i32 --> (x>>u31)^1  true if signbit clear.
462     if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
463         (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
464       if (!DoXform) return ICI;
465
466       Value *In = ICI->getOperand(0);
467       Value *Sh = ConstantInt::get(In->getType(),
468                                    In->getType()->getScalarSizeInBits()-1);
469       In = Builder->CreateLShr(In, Sh, In->getName()+".lobit");
470       if (In->getType() != CI.getType())
471         In = Builder->CreateIntCast(In, CI.getType(), false/*ZExt*/, "tmp");
472
473       if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
474         Constant *One = ConstantInt::get(In->getType(), 1);
475         In = Builder->CreateXor(In, One, In->getName()+".not");
476       }
477
478       return ReplaceInstUsesWith(CI, In);
479     }
480       
481       
482       
483     // zext (X == 0) to i32 --> X^1      iff X has only the low bit set.
484     // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
485     // zext (X == 1) to i32 --> X        iff X has only the low bit set.
486     // zext (X == 2) to i32 --> X>>1     iff X has only the 2nd bit set.
487     // zext (X != 0) to i32 --> X        iff X has only the low bit set.
488     // zext (X != 0) to i32 --> X>>1     iff X has only the 2nd bit set.
489     // zext (X != 1) to i32 --> X^1      iff X has only the low bit set.
490     // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
491     if ((Op1CV == 0 || Op1CV.isPowerOf2()) && 
492         // This only works for EQ and NE
493         ICI->isEquality()) {
494       // If Op1C some other power of two, convert:
495       uint32_t BitWidth = Op1C->getType()->getBitWidth();
496       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
497       APInt TypeMask(APInt::getAllOnesValue(BitWidth));
498       ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
499         
500       APInt KnownZeroMask(~KnownZero);
501       if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
502         if (!DoXform) return ICI;
503
504         bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
505         if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
506           // (X&4) == 2 --> false
507           // (X&4) != 2 --> true
508           Constant *Res = ConstantInt::get(Type::getInt1Ty(CI.getContext()),
509                                            isNE);
510           Res = ConstantExpr::getZExt(Res, CI.getType());
511           return ReplaceInstUsesWith(CI, Res);
512         }
513           
514         uint32_t ShiftAmt = KnownZeroMask.logBase2();
515         Value *In = ICI->getOperand(0);
516         if (ShiftAmt) {
517           // Perform a logical shr by shiftamt.
518           // Insert the shift to put the result in the low bit.
519           In = Builder->CreateLShr(In, ConstantInt::get(In->getType(),ShiftAmt),
520                                    In->getName()+".lobit");
521         }
522           
523         if ((Op1CV != 0) == isNE) { // Toggle the low bit.
524           Constant *One = ConstantInt::get(In->getType(), 1);
525           In = Builder->CreateXor(In, One, "tmp");
526         }
527           
528         if (CI.getType() == In->getType())
529           return ReplaceInstUsesWith(CI, In);
530         else
531           return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
532       }
533     }
534   }
535
536   // icmp ne A, B is equal to xor A, B when A and B only really have one bit.
537   // It is also profitable to transform icmp eq into not(xor(A, B)) because that
538   // may lead to additional simplifications.
539   if (ICI->isEquality() && CI.getType() == ICI->getOperand(0)->getType()) {
540     if (const IntegerType *ITy = dyn_cast<IntegerType>(CI.getType())) {
541       uint32_t BitWidth = ITy->getBitWidth();
542       Value *LHS = ICI->getOperand(0);
543       Value *RHS = ICI->getOperand(1);
544
545       APInt KnownZeroLHS(BitWidth, 0), KnownOneLHS(BitWidth, 0);
546       APInt KnownZeroRHS(BitWidth, 0), KnownOneRHS(BitWidth, 0);
547       APInt TypeMask(APInt::getAllOnesValue(BitWidth));
548       ComputeMaskedBits(LHS, TypeMask, KnownZeroLHS, KnownOneLHS);
549       ComputeMaskedBits(RHS, TypeMask, KnownZeroRHS, KnownOneRHS);
550
551       if (KnownZeroLHS == KnownZeroRHS && KnownOneLHS == KnownOneRHS) {
552         APInt KnownBits = KnownZeroLHS | KnownOneLHS;
553         APInt UnknownBit = ~KnownBits;
554         if (UnknownBit.countPopulation() == 1) {
555           if (!DoXform) return ICI;
556
557           Value *Result = Builder->CreateXor(LHS, RHS);
558
559           // Mask off any bits that are set and won't be shifted away.
560           if (KnownOneLHS.uge(UnknownBit))
561             Result = Builder->CreateAnd(Result,
562                                         ConstantInt::get(ITy, UnknownBit));
563
564           // Shift the bit we're testing down to the lsb.
565           Result = Builder->CreateLShr(
566                Result, ConstantInt::get(ITy, UnknownBit.countTrailingZeros()));
567
568           if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
569             Result = Builder->CreateXor(Result, ConstantInt::get(ITy, 1));
570           Result->takeName(ICI);
571           return ReplaceInstUsesWith(CI, Result);
572         }
573       }
574     }
575   }
576
577   return 0;
578 }
579
580 /// CanEvaluateZExtd - Determine if the specified value can be computed in the
581 /// specified wider type and produce the same low bits.  If not, return -1.  If
582 /// it is possible, return the number of high bits that are known to be zero in
583 /// the promoted value.
584 static bool CanEvaluateZExtd(Value *V, const Type *Ty, const TargetData *TD) {
585   if (isa<Constant>(V))
586     return true;
587   
588   Instruction *I = dyn_cast<Instruction>(V);
589   if (!I) return false;
590   
591   // If the input is a truncate from the destination type, we can trivially
592   // eliminate it.
593   if (isa<TruncInst>(I) && I->getOperand(0)->getType() == Ty)
594     return true;
595   
596   // We can't extend or shrink something that has multiple uses: doing so would
597   // require duplicating the instruction in general, which isn't profitable.
598   if (!I->hasOneUse()) return false;
599   
600   unsigned Opc = I->getOpcode();
601   switch (Opc) {
602   case Instruction::ZExt:  // zext(zext(x)) -> zext(x).
603   case Instruction::SExt:  // zext(sext(x)) -> sext(x).
604   case Instruction::Trunc: // zext(trunc(x)) -> trunc(x) or zext(x)
605     return true;
606   case Instruction::And:
607   case Instruction::Or:
608   case Instruction::Xor:
609   case Instruction::Add:
610   case Instruction::Sub:
611   case Instruction::Mul:
612   case Instruction::Shl:
613     return CanEvaluateZExtd(I->getOperand(0), Ty, TD) &&
614            CanEvaluateZExtd(I->getOperand(1), Ty, TD);
615       
616   //case Instruction::LShr:
617       
618   case Instruction::Select:
619     return CanEvaluateZExtd(I->getOperand(1), Ty, TD) &&
620            CanEvaluateZExtd(I->getOperand(2), Ty, TD);
621       
622   case Instruction::PHI: {
623     // We can change a phi if we can change all operands.  Note that we never
624     // get into trouble with cyclic PHIs here because we only consider
625     // instructions with a single use.
626     PHINode *PN = cast<PHINode>(I);
627     if (!CanEvaluateZExtd(PN->getIncomingValue(0), Ty, TD)) return false;
628     for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i)
629       if (!CanEvaluateZExtd(PN->getIncomingValue(i), Ty, TD)) return false;
630     return true;
631   }
632   default:
633     // TODO: Can handle more cases here.
634     return false;
635   }
636 }
637
638 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
639   // If this zero extend is only used by a truncate, let the truncate by
640   // eliminated before we try to optimize this zext.
641   if (CI.hasOneUse() && isa<TruncInst>(CI.use_back()))
642     return 0;
643   
644   // If one of the common conversion will work, do it.
645   if (Instruction *Result = commonCastTransforms(CI))
646     return Result;
647
648   // See if we can simplify any instructions used by the input whose sole 
649   // purpose is to compute bits we don't care about.
650   if (SimplifyDemandedInstructionBits(CI))
651     return &CI;
652   
653   Value *Src = CI.getOperand(0);
654   const Type *SrcTy = Src->getType(), *DestTy = CI.getType();
655   
656   // Attempt to extend the entire input expression tree to the destination
657   // type.   Only do this if the dest type is a simple type, don't convert the
658   // expression tree to something weird like i93 unless the source is also
659   // strange.
660   if ((isa<VectorType>(DestTy) || ShouldChangeType(SrcTy, DestTy)) &&
661       CanEvaluateZExtd(Src, DestTy, TD)) { 
662     // Okay, we can transform this!  Insert the new expression now.
663     DEBUG(dbgs() << "ICE: EvaluateInDifferentType converting expression type"
664           " to avoid zero extend: " << CI);
665     Value *Res = EvaluateInDifferentType(Src, DestTy, false);
666     assert(Res->getType() == DestTy);
667     
668     // If the high bits are already filled with zeros, just replace this
669     // cast with the result.
670     uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
671     uint32_t DestBitSize = DestTy->getScalarSizeInBits();
672     if (MaskedValueIsZero(Res, APInt::getHighBitsSet(DestBitSize,
673                                                      DestBitSize-SrcBitSize)))
674       return ReplaceInstUsesWith(CI, Res);
675     
676     // We need to emit an AND to clear the high bits.
677     Constant *C = ConstantInt::get(Res->getType(),
678                                APInt::getLowBitsSet(DestBitSize, SrcBitSize));
679     return BinaryOperator::CreateAnd(Res, C);
680   }
681
682   // If this is a TRUNC followed by a ZEXT then we are dealing with integral
683   // types and if the sizes are just right we can convert this into a logical
684   // 'and' which will be much cheaper than the pair of casts.
685   if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) {   // A->B->C cast
686     // TODO: Subsume this into EvaluateInDifferentType.
687     
688     // Get the sizes of the types involved.  We know that the intermediate type
689     // will be smaller than A or C, but don't know the relation between A and C.
690     Value *A = CSrc->getOperand(0);
691     unsigned SrcSize = A->getType()->getScalarSizeInBits();
692     unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
693     unsigned DstSize = CI.getType()->getScalarSizeInBits();
694     // If we're actually extending zero bits, then if
695     // SrcSize <  DstSize: zext(a & mask)
696     // SrcSize == DstSize: a & mask
697     // SrcSize  > DstSize: trunc(a) & mask
698     if (SrcSize < DstSize) {
699       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
700       Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
701       Value *And = Builder->CreateAnd(A, AndConst, CSrc->getName()+".mask");
702       return new ZExtInst(And, CI.getType());
703     }
704     
705     if (SrcSize == DstSize) {
706       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
707       return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
708                                                            AndValue));
709     }
710     if (SrcSize > DstSize) {
711       Value *Trunc = Builder->CreateTrunc(A, CI.getType(), "tmp");
712       APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
713       return BinaryOperator::CreateAnd(Trunc, 
714                                        ConstantInt::get(Trunc->getType(),
715                                                         AndValue));
716     }
717   }
718
719   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
720     return transformZExtICmp(ICI, CI);
721
722   BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
723   if (SrcI && SrcI->getOpcode() == Instruction::Or) {
724     // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
725     // of the (zext icmp) will be transformed.
726     ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
727     ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
728     if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
729         (transformZExtICmp(LHS, CI, false) ||
730          transformZExtICmp(RHS, CI, false))) {
731       Value *LCast = Builder->CreateZExt(LHS, CI.getType(), LHS->getName());
732       Value *RCast = Builder->CreateZExt(RHS, CI.getType(), RHS->getName());
733       return BinaryOperator::Create(Instruction::Or, LCast, RCast);
734     }
735   }
736
737   // zext(trunc(t) & C) -> (t & zext(C)).
738   if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
739     if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
740       if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
741         Value *TI0 = TI->getOperand(0);
742         if (TI0->getType() == CI.getType())
743           return
744             BinaryOperator::CreateAnd(TI0,
745                                 ConstantExpr::getZExt(C, CI.getType()));
746       }
747
748   // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
749   if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
750     if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
751       if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
752         if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
753             And->getOperand(1) == C)
754           if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
755             Value *TI0 = TI->getOperand(0);
756             if (TI0->getType() == CI.getType()) {
757               Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
758               Value *NewAnd = Builder->CreateAnd(TI0, ZC, "tmp");
759               return BinaryOperator::CreateXor(NewAnd, ZC);
760             }
761           }
762
763   // zext (xor i1 X, true) to i32  --> xor (zext i1 X to i32), 1
764   Value *X;
765   if (SrcI && SrcI->hasOneUse() && SrcI->getType()->isInteger(1) &&
766       match(SrcI, m_Not(m_Value(X))) &&
767       (!X->hasOneUse() || !isa<CmpInst>(X))) {
768     Value *New = Builder->CreateZExt(X, CI.getType());
769     return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
770   }
771   
772   return 0;
773 }
774
775 /// CanEvaluateSExtd - Return true if we can take the specified value
776 /// and return it as type Ty without inserting any new casts and without
777 /// changing the value of the common low bits.  This is used by code that tries
778 /// to promote integer operations to a wider types will allow us to eliminate
779 /// the extension.
780 ///
781 /// This function works on both vectors and scalars.
782 ///
783 static bool CanEvaluateSExtd(Value *V, const Type *Ty, TargetData *TD) {
784   assert(V->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits() &&
785          "Can't sign extend type to a smaller type");
786   // If this is a constant, it can be trivially promoted.
787   if (isa<Constant>(V))
788     return true;
789   
790   Instruction *I = dyn_cast<Instruction>(V);
791   if (!I) return false;
792   
793   // If this is a truncate from the dest type, we can trivially eliminate it.
794   if (isa<TruncInst>(I) && I->getOperand(0)->getType() == Ty)
795     return true;
796   
797   // We can't extend or shrink something that has multiple uses: doing so would
798   // require duplicating the instruction in general, which isn't profitable.
799   if (!I->hasOneUse()) return false;
800
801   switch (I->getOpcode()) {
802   case Instruction::SExt:  // sext(sext(x)) -> sext(x)
803   case Instruction::ZExt:  // sext(zext(x)) -> zext(x)
804   case Instruction::Trunc: // sext(trunc(x)) -> trunc(x) or sext(x)
805     return true;
806   case Instruction::And:
807   case Instruction::Or:
808   case Instruction::Xor:
809   case Instruction::Add:
810   case Instruction::Sub:
811   case Instruction::Mul:
812     // These operators can all arbitrarily be extended if their inputs can.
813     return CanEvaluateSExtd(I->getOperand(0), Ty, TD) &&
814            CanEvaluateSExtd(I->getOperand(1), Ty, TD);
815       
816   //case Instruction::Shl:   TODO
817   //case Instruction::LShr:  TODO
818   //case Instruction::Trunc: TODO
819       
820   case Instruction::Select:
821     return CanEvaluateSExtd(I->getOperand(1), Ty, TD) &&
822            CanEvaluateSExtd(I->getOperand(2), Ty, TD);
823       
824   case Instruction::PHI: {
825     // We can change a phi if we can change all operands.  Note that we never
826     // get into trouble with cyclic PHIs here because we only consider
827     // instructions with a single use.
828     PHINode *PN = cast<PHINode>(I);
829     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
830       if (!CanEvaluateSExtd(PN->getIncomingValue(i), Ty, TD)) return false;
831     return true;
832   }
833   default:
834     // TODO: Can handle more cases here.
835     break;
836   }
837   
838   return false;
839 }
840
841 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
842   // If this sign extend is only used by a truncate, let the truncate by
843   // eliminated before we try to optimize this zext.
844   if (CI.hasOneUse() && isa<TruncInst>(CI.use_back()))
845     return 0;
846   
847   if (Instruction *I = commonCastTransforms(CI))
848     return I;
849   
850   // See if we can simplify any instructions used by the input whose sole 
851   // purpose is to compute bits we don't care about.
852   if (SimplifyDemandedInstructionBits(CI))
853     return &CI;
854   
855   Value *Src = CI.getOperand(0);
856   const Type *SrcTy = Src->getType(), *DestTy = CI.getType();
857
858   // Canonicalize sign-extend from i1 to a select.
859   if (Src->getType()->isInteger(1))
860     return SelectInst::Create(Src,
861                               Constant::getAllOnesValue(CI.getType()),
862                               Constant::getNullValue(CI.getType()));
863   
864   // Attempt to extend the entire input expression tree to the destination
865   // type.   Only do this if the dest type is a simple type, don't convert the
866   // expression tree to something weird like i93 unless the source is also
867   // strange.
868   if ((isa<VectorType>(DestTy) || ShouldChangeType(SrcTy, DestTy)) &&
869       CanEvaluateSExtd(Src, DestTy, TD)) {
870     // Okay, we can transform this!  Insert the new expression now.
871     DEBUG(dbgs() << "ICE: EvaluateInDifferentType converting expression type"
872           " to avoid sign extend: " << CI);
873     Value *Res = EvaluateInDifferentType(Src, DestTy, true);
874     assert(Res->getType() == DestTy);
875
876     uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
877     uint32_t DestBitSize = DestTy->getScalarSizeInBits();
878
879     // If the high bits are already filled with sign bit, just replace this
880     // cast with the result.
881     if (ComputeNumSignBits(Res) > DestBitSize - SrcBitSize)
882       return ReplaceInstUsesWith(CI, Res);
883     
884     // We need to emit a shl + ashr to do the sign extend.
885     Value *ShAmt = ConstantInt::get(DestTy, DestBitSize-SrcBitSize);
886     return BinaryOperator::CreateAShr(Builder->CreateShl(Res, ShAmt, "sext"),
887                                       ShAmt);
888   }
889
890   // If the input is a shl/ashr pair of a same constant, then this is a sign
891   // extension from a smaller value.  If we could trust arbitrary bitwidth
892   // integers, we could turn this into a truncate to the smaller bit and then
893   // use a sext for the whole extension.  Since we don't, look deeper and check
894   // for a truncate.  If the source and dest are the same type, eliminate the
895   // trunc and extend and just do shifts.  For example, turn:
896   //   %a = trunc i32 %i to i8
897   //   %b = shl i8 %a, 6
898   //   %c = ashr i8 %b, 6
899   //   %d = sext i8 %c to i32
900   // into:
901   //   %a = shl i32 %i, 30
902   //   %d = ashr i32 %a, 30
903   Value *A = 0;
904   // TODO: Eventually this could be subsumed by EvaluateInDifferentType.
905   ConstantInt *BA = 0, *CA = 0;
906   if (match(Src, m_AShr(m_Shl(m_Trunc(m_Value(A)), m_ConstantInt(BA)),
907                         m_ConstantInt(CA))) &&
908       BA == CA && A->getType() == CI.getType()) {
909     unsigned MidSize = Src->getType()->getScalarSizeInBits();
910     unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
911     unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
912     Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
913     A = Builder->CreateShl(A, ShAmtV, CI.getName());
914     return BinaryOperator::CreateAShr(A, ShAmtV);
915   }
916   
917   return 0;
918 }
919
920
921 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
922 /// in the specified FP type without changing its value.
923 static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
924   bool losesInfo;
925   APFloat F = CFP->getValueAPF();
926   (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
927   if (!losesInfo)
928     return ConstantFP::get(CFP->getContext(), F);
929   return 0;
930 }
931
932 /// LookThroughFPExtensions - If this is an fp extension instruction, look
933 /// through it until we get the source value.
934 static Value *LookThroughFPExtensions(Value *V) {
935   if (Instruction *I = dyn_cast<Instruction>(V))
936     if (I->getOpcode() == Instruction::FPExt)
937       return LookThroughFPExtensions(I->getOperand(0));
938   
939   // If this value is a constant, return the constant in the smallest FP type
940   // that can accurately represent it.  This allows us to turn
941   // (float)((double)X+2.0) into x+2.0f.
942   if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
943     if (CFP->getType() == Type::getPPC_FP128Ty(V->getContext()))
944       return V;  // No constant folding of this.
945     // See if the value can be truncated to float and then reextended.
946     if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
947       return V;
948     if (CFP->getType()->isDoubleTy())
949       return V;  // Won't shrink.
950     if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
951       return V;
952     // Don't try to shrink to various long double types.
953   }
954   
955   return V;
956 }
957
958 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
959   if (Instruction *I = commonCastTransforms(CI))
960     return I;
961   
962   // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
963   // smaller than the destination type, we can eliminate the truncate by doing
964   // the add as the smaller type.  This applies to fadd/fsub/fmul/fdiv as well
965   // as many builtins (sqrt, etc).
966   BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
967   if (OpI && OpI->hasOneUse()) {
968     switch (OpI->getOpcode()) {
969     default: break;
970     case Instruction::FAdd:
971     case Instruction::FSub:
972     case Instruction::FMul:
973     case Instruction::FDiv:
974     case Instruction::FRem:
975       const Type *SrcTy = OpI->getType();
976       Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
977       Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
978       if (LHSTrunc->getType() != SrcTy && 
979           RHSTrunc->getType() != SrcTy) {
980         unsigned DstSize = CI.getType()->getScalarSizeInBits();
981         // If the source types were both smaller than the destination type of
982         // the cast, do this xform.
983         if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
984             RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
985           LHSTrunc = Builder->CreateFPExt(LHSTrunc, CI.getType());
986           RHSTrunc = Builder->CreateFPExt(RHSTrunc, CI.getType());
987           return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
988         }
989       }
990       break;  
991     }
992   }
993   return 0;
994 }
995
996 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
997   return commonCastTransforms(CI);
998 }
999
1000 Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
1001   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
1002   if (OpI == 0)
1003     return commonCastTransforms(FI);
1004
1005   // fptoui(uitofp(X)) --> X
1006   // fptoui(sitofp(X)) --> X
1007   // This is safe if the intermediate type has enough bits in its mantissa to
1008   // accurately represent all values of X.  For example, do not do this with
1009   // i64->float->i64.  This is also safe for sitofp case, because any negative
1010   // 'X' value would cause an undefined result for the fptoui. 
1011   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
1012       OpI->getOperand(0)->getType() == FI.getType() &&
1013       (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
1014                     OpI->getType()->getFPMantissaWidth())
1015     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
1016
1017   return commonCastTransforms(FI);
1018 }
1019
1020 Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
1021   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
1022   if (OpI == 0)
1023     return commonCastTransforms(FI);
1024   
1025   // fptosi(sitofp(X)) --> X
1026   // fptosi(uitofp(X)) --> X
1027   // This is safe if the intermediate type has enough bits in its mantissa to
1028   // accurately represent all values of X.  For example, do not do this with
1029   // i64->float->i64.  This is also safe for sitofp case, because any negative
1030   // 'X' value would cause an undefined result for the fptoui. 
1031   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
1032       OpI->getOperand(0)->getType() == FI.getType() &&
1033       (int)FI.getType()->getScalarSizeInBits() <=
1034                     OpI->getType()->getFPMantissaWidth())
1035     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
1036   
1037   return commonCastTransforms(FI);
1038 }
1039
1040 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
1041   return commonCastTransforms(CI);
1042 }
1043
1044 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
1045   return commonCastTransforms(CI);
1046 }
1047
1048 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
1049   // If the source integer type is larger than the intptr_t type for
1050   // this target, do a trunc to the intptr_t type, then inttoptr of it.  This
1051   // allows the trunc to be exposed to other transforms.  Don't do this for
1052   // extending inttoptr's, because we don't know if the target sign or zero
1053   // extends to pointers.
1054   if (TD && CI.getOperand(0)->getType()->getScalarSizeInBits() >
1055       TD->getPointerSizeInBits()) {
1056     Value *P = Builder->CreateTrunc(CI.getOperand(0),
1057                                     TD->getIntPtrType(CI.getContext()), "tmp");
1058     return new IntToPtrInst(P, CI.getType());
1059   }
1060   
1061   if (Instruction *I = commonCastTransforms(CI))
1062     return I;
1063
1064   return 0;
1065 }
1066
1067 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
1068 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
1069   Value *Src = CI.getOperand(0);
1070   
1071   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
1072     // If casting the result of a getelementptr instruction with no offset, turn
1073     // this into a cast of the original pointer!
1074     if (GEP->hasAllZeroIndices()) {
1075       // Changing the cast operand is usually not a good idea but it is safe
1076       // here because the pointer operand is being replaced with another 
1077       // pointer operand so the opcode doesn't need to change.
1078       Worklist.Add(GEP);
1079       CI.setOperand(0, GEP->getOperand(0));
1080       return &CI;
1081     }
1082     
1083     // If the GEP has a single use, and the base pointer is a bitcast, and the
1084     // GEP computes a constant offset, see if we can convert these three
1085     // instructions into fewer.  This typically happens with unions and other
1086     // non-type-safe code.
1087     if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0)) &&
1088         GEP->hasAllConstantIndices()) {
1089       // We are guaranteed to get a constant from EmitGEPOffset.
1090       ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP));
1091       int64_t Offset = OffsetV->getSExtValue();
1092       
1093       // Get the base pointer input of the bitcast, and the type it points to.
1094       Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
1095       const Type *GEPIdxTy =
1096       cast<PointerType>(OrigBase->getType())->getElementType();
1097       SmallVector<Value*, 8> NewIndices;
1098       if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices)) {
1099         // If we were able to index down into an element, create the GEP
1100         // and bitcast the result.  This eliminates one bitcast, potentially
1101         // two.
1102         Value *NGEP = cast<GEPOperator>(GEP)->isInBounds() ?
1103         Builder->CreateInBoundsGEP(OrigBase,
1104                                    NewIndices.begin(), NewIndices.end()) :
1105         Builder->CreateGEP(OrigBase, NewIndices.begin(), NewIndices.end());
1106         NGEP->takeName(GEP);
1107         
1108         if (isa<BitCastInst>(CI))
1109           return new BitCastInst(NGEP, CI.getType());
1110         assert(isa<PtrToIntInst>(CI));
1111         return new PtrToIntInst(NGEP, CI.getType());
1112       }      
1113     }
1114   }
1115   
1116   return commonCastTransforms(CI);
1117 }
1118
1119 Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
1120   // If the destination integer type is smaller than the intptr_t type for
1121   // this target, do a ptrtoint to intptr_t then do a trunc.  This allows the
1122   // trunc to be exposed to other transforms.  Don't do this for extending
1123   // ptrtoint's, because we don't know if the target sign or zero extends its
1124   // pointers.
1125   if (TD &&
1126       CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
1127     Value *P = Builder->CreatePtrToInt(CI.getOperand(0),
1128                                        TD->getIntPtrType(CI.getContext()),
1129                                        "tmp");
1130     return new TruncInst(P, CI.getType());
1131   }
1132   
1133   return commonPointerCastTransforms(CI);
1134 }
1135
1136 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
1137   // If the operands are integer typed then apply the integer transforms,
1138   // otherwise just apply the common ones.
1139   Value *Src = CI.getOperand(0);
1140   const Type *SrcTy = Src->getType();
1141   const Type *DestTy = CI.getType();
1142
1143   // Get rid of casts from one type to the same type. These are useless and can
1144   // be replaced by the operand.
1145   if (DestTy == Src->getType())
1146     return ReplaceInstUsesWith(CI, Src);
1147
1148   if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
1149     const PointerType *SrcPTy = cast<PointerType>(SrcTy);
1150     const Type *DstElTy = DstPTy->getElementType();
1151     const Type *SrcElTy = SrcPTy->getElementType();
1152     
1153     // If the address spaces don't match, don't eliminate the bitcast, which is
1154     // required for changing types.
1155     if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
1156       return 0;
1157     
1158     // If we are casting a alloca to a pointer to a type of the same
1159     // size, rewrite the allocation instruction to allocate the "right" type.
1160     // There is no need to modify malloc calls because it is their bitcast that
1161     // needs to be cleaned up.
1162     if (AllocaInst *AI = dyn_cast<AllocaInst>(Src))
1163       if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
1164         return V;
1165     
1166     // If the source and destination are pointers, and this cast is equivalent
1167     // to a getelementptr X, 0, 0, 0...  turn it into the appropriate gep.
1168     // This can enhance SROA and other transforms that want type-safe pointers.
1169     Constant *ZeroUInt =
1170       Constant::getNullValue(Type::getInt32Ty(CI.getContext()));
1171     unsigned NumZeros = 0;
1172     while (SrcElTy != DstElTy && 
1173            isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
1174            SrcElTy->getNumContainedTypes() /* not "{}" */) {
1175       SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
1176       ++NumZeros;
1177     }
1178
1179     // If we found a path from the src to dest, create the getelementptr now.
1180     if (SrcElTy == DstElTy) {
1181       SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
1182       return GetElementPtrInst::CreateInBounds(Src, Idxs.begin(), Idxs.end(),"",
1183                                                ((Instruction*)NULL));
1184     }
1185   }
1186
1187   if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
1188     if (DestVTy->getNumElements() == 1 && !isa<VectorType>(SrcTy)) {
1189       Value *Elem = Builder->CreateBitCast(Src, DestVTy->getElementType());
1190       return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
1191                      Constant::getNullValue(Type::getInt32Ty(CI.getContext())));
1192       // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
1193     }
1194   }
1195
1196   if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
1197     if (SrcVTy->getNumElements() == 1 && !isa<VectorType>(DestTy)) {
1198       Value *Elem = 
1199         Builder->CreateExtractElement(Src,
1200                    Constant::getNullValue(Type::getInt32Ty(CI.getContext())));
1201       return CastInst::Create(Instruction::BitCast, Elem, DestTy);
1202     }
1203   }
1204
1205   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
1206     // Okay, we have (bitcast (shuffle ..)).  Check to see if this is
1207     // a bitconvert to a vector with the same # elts.
1208     if (SVI->hasOneUse() && isa<VectorType>(DestTy) && 
1209         cast<VectorType>(DestTy)->getNumElements() ==
1210               SVI->getType()->getNumElements() &&
1211         SVI->getType()->getNumElements() ==
1212           cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
1213       BitCastInst *Tmp;
1214       // If either of the operands is a cast from CI.getType(), then
1215       // evaluating the shuffle in the casted destination's type will allow
1216       // us to eliminate at least one cast.
1217       if (((Tmp = dyn_cast<BitCastInst>(SVI->getOperand(0))) && 
1218            Tmp->getOperand(0)->getType() == DestTy) ||
1219           ((Tmp = dyn_cast<BitCastInst>(SVI->getOperand(1))) && 
1220            Tmp->getOperand(0)->getType() == DestTy)) {
1221         Value *LHS = Builder->CreateBitCast(SVI->getOperand(0), DestTy);
1222         Value *RHS = Builder->CreateBitCast(SVI->getOperand(1), DestTy);
1223         // Return a new shuffle vector.  Use the same element ID's, as we
1224         // know the vector types match #elts.
1225         return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
1226       }
1227     }
1228   }
1229   
1230   if (isa<PointerType>(SrcTy))
1231     return commonPointerCastTransforms(CI);
1232   return commonCastTransforms(CI);
1233 }