d49c5a10c83dbc09cd40401ce1db93ed72f8fe6c
[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 /// CanEvaluateInDifferentType - Return true if we can take the specified value
151 /// and return it as type Ty without inserting any new casts and without
152 /// changing the computed value.  This is used by code that tries to decide
153 /// whether promoting or shrinking integer operations to wider or smaller types
154 /// will allow us to eliminate a truncate or extend.
155 ///
156 /// This is a truncation operation if Ty is smaller than V->getType(), or a zero
157 /// extension operation if Ty is larger.
158 ///
159 /// If CastOpc is a truncation, then Ty will be a type smaller than V.  We
160 /// should return true if trunc(V) can be computed by computing V in the smaller
161 /// type.  If V is an instruction, then trunc(inst(x,y)) can be computed as
162 /// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
163 /// efficiently truncated.
164 ///
165 /// If CastOpc is zext, we are asking if the low bits of the value can be
166 /// computed in a larger type, which is then and'd to get the final result.
167 static bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
168                                        unsigned CastOpc,
169                                        unsigned &NumCastsRemoved) {
170   assert(CastOpc == Instruction::ZExt || CastOpc == Instruction::Trunc);
171   
172   // We can always evaluate constants in another type.
173   if (isa<Constant>(V))
174     return true;
175   
176   Instruction *I = dyn_cast<Instruction>(V);
177   if (!I) return false;
178   
179   const Type *OrigTy = V->getType();
180   
181   // If this is an extension or truncate, we can often eliminate it.
182   if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
183     // If this is a cast from the destination type, we can trivially eliminate
184     // it, and this will remove a cast overall.
185     if (I->getOperand(0)->getType() == Ty) {
186       // If the first operand is itself a cast, and is eliminable, do not count
187       // this as an eliminable cast.  We would prefer to eliminate those two
188       // casts first.
189       if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
190         ++NumCastsRemoved;
191       return true;
192     }
193   }
194
195   // We can't extend or shrink something that has multiple uses: doing so would
196   // require duplicating the instruction in general, which isn't profitable.
197   if (!I->hasOneUse()) return false;
198
199   unsigned Opc = I->getOpcode();
200   switch (Opc) {
201   case Instruction::Add:
202   case Instruction::Sub:
203   case Instruction::Mul:
204   case Instruction::And:
205   case Instruction::Or:
206   case Instruction::Xor:
207     // These operators can all arbitrarily be extended or truncated.
208     return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
209                                       NumCastsRemoved) &&
210            CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
211                                       NumCastsRemoved);
212
213   case Instruction::UDiv:
214   case Instruction::URem: {
215     // UDiv and URem can be truncated if all the truncated bits are zero.
216     uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
217     uint32_t BitWidth = Ty->getScalarSizeInBits();
218     if (BitWidth < OrigBitWidth) {
219       APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
220       if (MaskedValueIsZero(I->getOperand(0), Mask) &&
221           MaskedValueIsZero(I->getOperand(1), Mask)) {
222         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
223                                           NumCastsRemoved) &&
224                CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
225                                           NumCastsRemoved);
226       }
227     }
228     break;
229   }
230   case Instruction::Shl:
231     // If we are truncating the result of this SHL, and if it's a shift of a
232     // constant amount, we can always perform a SHL in a smaller type.
233     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
234       uint32_t BitWidth = Ty->getScalarSizeInBits();
235       if (BitWidth < OrigTy->getScalarSizeInBits() &&
236           CI->getLimitedValue(BitWidth) < BitWidth)
237         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
238                                           NumCastsRemoved);
239     }
240     break;
241   case Instruction::LShr:
242     // If this is a truncate of a logical shr, we can truncate it to a smaller
243     // lshr iff we know that the bits we would otherwise be shifting in are
244     // already zeros.
245     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
246       uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
247       uint32_t BitWidth = Ty->getScalarSizeInBits();
248       if (BitWidth < OrigBitWidth &&
249           MaskedValueIsZero(I->getOperand(0),
250             APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
251           CI->getLimitedValue(BitWidth) < BitWidth) {
252         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
253                                           NumCastsRemoved);
254       }
255     }
256     break;
257   case Instruction::ZExt:
258   case Instruction::SExt:
259   case Instruction::Trunc:
260     // If this is the same kind of case as our original (e.g. zext+zext), we
261     // can safely replace it.  Note that replacing it does not reduce the number
262     // of casts in the input.
263     if (Opc == CastOpc)
264       return true;
265
266     // sext (zext ty1), ty2 -> zext ty2
267     if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
268       return true;
269     break;
270   case Instruction::Select: {
271     SelectInst *SI = cast<SelectInst>(I);
272     return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
273                                       NumCastsRemoved) &&
274            CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
275                                       NumCastsRemoved);
276   }
277   case Instruction::PHI: {
278     // We can change a phi if we can change all operands.  Note that we never
279     // get into trouble with cyclic PHIs here because we only consider
280     // instructions with a single use.
281     PHINode *PN = cast<PHINode>(I);
282     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
283       if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
284                                       NumCastsRemoved))
285         return false;
286     return true;
287   }
288   default:
289     // TODO: Can handle more cases here.
290     break;
291   }
292   
293   return false;
294 }
295
296 /// CanEvaluateSExtd - Return true if we can take the specified value
297 /// and return it as type Ty without inserting any new casts and without
298 /// changing the value of the common low bits.  This is used by code that tries
299 /// to promote integer operations to a wider types will allow us to eliminate
300 /// the extension.
301 ///
302 /// This returns 0 if we can't do this or the number of sign bits that would be
303 /// set if we can.  For example, CanEvaluateSExtd(i16 1, i64) would return 63,
304 /// because the computation can be extended (to "i64 1") and the resulting
305 /// computation has 63 equal sign bits.
306 ///
307 /// This function works on both vectors and scalars.  For vectors, the result is
308 /// the number of bits known sign extended in each element.
309 ///
310 static unsigned CanEvaluateSExtd(Value *V, const Type *Ty,
311                                  unsigned &NumCastsRemoved, TargetData *TD) {
312   assert(V->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits() &&
313          "Can't sign extend type to a smaller type");
314   // If this is a constant, return the number of sign bits the extended version
315   // of it would have.
316   if (Constant *C = dyn_cast<Constant>(V))
317     return ComputeNumSignBits(ConstantExpr::getSExt(C, Ty), TD);
318   
319   Instruction *I = dyn_cast<Instruction>(V);
320   if (!I) return 0;
321   
322   // If this is a truncate from the destination type, we can trivially eliminate
323   // it, and this will remove a cast overall.
324   if (isa<TruncInst>(I) && I->getOperand(0)->getType() == Ty) {
325     // If the operand of the truncate is itself a cast, and is eliminable, do
326     // not count this as an eliminable cast.  We would prefer to eliminate those
327     // two casts first.
328     if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
329       ++NumCastsRemoved;
330     return ComputeNumSignBits(I->getOperand(0), TD);
331   }
332   
333   // We can't extend or shrink something that has multiple uses: doing so would
334   // require duplicating the instruction in general, which isn't profitable.
335   if (!I->hasOneUse()) return 0;
336
337   const Type *OrigTy = V->getType();
338
339   unsigned Opc = I->getOpcode();
340   unsigned Tmp1, Tmp2;
341   switch (Opc) {
342   case Instruction::And:
343   case Instruction::Or:
344   case Instruction::Xor:
345     // These operators can all arbitrarily be extended or truncated.
346     Tmp1 = CanEvaluateSExtd(I->getOperand(0), Ty, NumCastsRemoved, TD);
347     if (Tmp1 == 0) return 0;
348     Tmp2 = CanEvaluateSExtd(I->getOperand(1), Ty, NumCastsRemoved, TD);
349     return std::min(Tmp1, Tmp2);
350   case Instruction::Add:
351   case Instruction::Sub:
352     // Add/Sub can have at most one carry/borrow bit.
353     Tmp1 = CanEvaluateSExtd(I->getOperand(0), Ty, NumCastsRemoved, TD);
354     if (Tmp1 == 0) return 0;
355     Tmp2 = CanEvaluateSExtd(I->getOperand(1), Ty, NumCastsRemoved, TD);
356     if (Tmp2 == 0) return 0;
357     return std::min(Tmp1, Tmp2)-1;
358   case Instruction::Mul:
359     // These operators can all arbitrarily be extended or truncated.
360     if (!CanEvaluateSExtd(I->getOperand(0), Ty, NumCastsRemoved, TD))
361       return 0;
362     if (!CanEvaluateSExtd(I->getOperand(1), Ty, NumCastsRemoved, TD))
363       return 0;
364     return 1; // IMPROVE?
365       
366   //case Instruction::Shl:   TODO
367   //case Instruction::LShr:  TODO
368   //case Instruction::Trunc: TODO
369       
370   case Instruction::SExt:
371   case Instruction::ZExt: {
372     // sext(sext(x)) -> sext(x)
373     // sext(zext(x)) -> zext(x)
374     // Note that replacing a cast does not reduce the number of casts in the
375     // input.
376     unsigned InSignBits = ComputeNumSignBits(I, TD);
377     unsigned ExtBits = Ty->getScalarSizeInBits()-OrigTy->getScalarSizeInBits();
378     // We'll end up extending it all the way out.
379     return InSignBits+ExtBits;
380   }
381   case Instruction::Select: {
382     SelectInst *SI = cast<SelectInst>(I);
383     Tmp1 = CanEvaluateSExtd(SI->getTrueValue(), Ty, NumCastsRemoved, TD);
384     if (Tmp1 == 0) return 0;
385     Tmp2 = CanEvaluateSExtd(SI->getFalseValue(), Ty, NumCastsRemoved,TD);
386     return std::min(Tmp1, Tmp2);
387   }
388   case Instruction::PHI: {
389     // We can change a phi if we can change all operands.  Note that we never
390     // get into trouble with cyclic PHIs here because we only consider
391     // instructions with a single use.
392     PHINode *PN = cast<PHINode>(I);
393     unsigned Result = ~0U;
394     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
395       Result = std::min(Result,
396                         CanEvaluateSExtd(PN->getIncomingValue(i), Ty,
397                                          NumCastsRemoved, TD));
398       if (Result == 0) return 0;
399     }
400     return Result;
401   }
402   default:
403     // TODO: Can handle more cases here.
404     break;
405   }
406   
407   return 0;
408 }
409
410
411 /// EvaluateInDifferentType - Given an expression that 
412 /// CanEvaluateInDifferentType or CanEvaluateSExtd returns true for, actually
413 /// insert the code to evaluate the expression.
414 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty, 
415                                              bool isSigned) {
416   if (Constant *C = dyn_cast<Constant>(V))
417     return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
418
419   // Otherwise, it must be an instruction.
420   Instruction *I = cast<Instruction>(V);
421   Instruction *Res = 0;
422   unsigned Opc = I->getOpcode();
423   switch (Opc) {
424   case Instruction::Add:
425   case Instruction::Sub:
426   case Instruction::Mul:
427   case Instruction::And:
428   case Instruction::Or:
429   case Instruction::Xor:
430   case Instruction::AShr:
431   case Instruction::LShr:
432   case Instruction::Shl:
433   case Instruction::UDiv:
434   case Instruction::URem: {
435     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
436     Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
437     Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
438     break;
439   }    
440   case Instruction::Trunc:
441   case Instruction::ZExt:
442   case Instruction::SExt:
443     // If the source type of the cast is the type we're trying for then we can
444     // just return the source.  There's no need to insert it because it is not
445     // new.
446     if (I->getOperand(0)->getType() == Ty)
447       return I->getOperand(0);
448     
449     // Otherwise, must be the same type of cast, so just reinsert a new one.
450     Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),Ty);
451     break;
452   case Instruction::Select: {
453     Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
454     Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
455     Res = SelectInst::Create(I->getOperand(0), True, False);
456     break;
457   }
458   case Instruction::PHI: {
459     PHINode *OPN = cast<PHINode>(I);
460     PHINode *NPN = PHINode::Create(Ty);
461     for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
462       Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
463       NPN->addIncoming(V, OPN->getIncomingBlock(i));
464     }
465     Res = NPN;
466     break;
467   }
468   default: 
469     // TODO: Can handle more cases here.
470     llvm_unreachable("Unreachable!");
471     break;
472   }
473   
474   Res->takeName(I);
475   return InsertNewInstBefore(Res, *I);
476 }
477
478
479 /// This function is a wrapper around CastInst::isEliminableCastPair. It
480 /// simply extracts arguments and returns what that function returns.
481 static Instruction::CastOps 
482 isEliminableCastPair(
483   const CastInst *CI, ///< The first cast instruction
484   unsigned opcode,       ///< The opcode of the second cast instruction
485   const Type *DstTy,     ///< The target type for the second cast instruction
486   TargetData *TD         ///< The target data for pointer size
487 ) {
488
489   const Type *SrcTy = CI->getOperand(0)->getType();   // A from above
490   const Type *MidTy = CI->getType();                  // B from above
491
492   // Get the opcodes of the two Cast instructions
493   Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
494   Instruction::CastOps secondOp = Instruction::CastOps(opcode);
495
496   unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
497                                                 DstTy,
498                                   TD ? TD->getIntPtrType(CI->getContext()) : 0);
499   
500   // We don't want to form an inttoptr or ptrtoint that converts to an integer
501   // type that differs from the pointer size.
502   if ((Res == Instruction::IntToPtr &&
503           (!TD || SrcTy != TD->getIntPtrType(CI->getContext()))) ||
504       (Res == Instruction::PtrToInt &&
505           (!TD || DstTy != TD->getIntPtrType(CI->getContext()))))
506     Res = 0;
507   
508   return Instruction::CastOps(Res);
509 }
510
511 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
512 /// in any code being generated.  It does not require codegen if V is simple
513 /// enough or if the cast can be folded into other casts.
514 bool InstCombiner::ValueRequiresCast(Instruction::CastOps opcode,const Value *V,
515                                      const Type *Ty) {
516   if (V->getType() == Ty || isa<Constant>(V)) return false;
517   
518   // If this is another cast that can be eliminated, it isn't codegen either.
519   if (const CastInst *CI = dyn_cast<CastInst>(V))
520     if (isEliminableCastPair(CI, opcode, Ty, TD))
521       return false;
522   return true;
523 }
524
525
526 /// @brief Implement the transforms common to all CastInst visitors.
527 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
528   Value *Src = CI.getOperand(0);
529
530   // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
531   // eliminate it now.
532   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
533     if (Instruction::CastOps opc = 
534         isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
535       // The first cast (CSrc) is eliminable so we need to fix up or replace
536       // the second cast (CI). CSrc will then have a good chance of being dead.
537       return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
538     }
539   }
540
541   // If we are casting a select then fold the cast into the select
542   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
543     if (Instruction *NV = FoldOpIntoSelect(CI, SI))
544       return NV;
545
546   // If we are casting a PHI then fold the cast into the PHI
547   if (isa<PHINode>(Src)) {
548     // We don't do this if this would create a PHI node with an illegal type if
549     // it is currently legal.
550     if (!isa<IntegerType>(Src->getType()) ||
551         !isa<IntegerType>(CI.getType()) ||
552         ShouldChangeType(CI.getType(), Src->getType()))
553       if (Instruction *NV = FoldOpIntoPhi(CI))
554         return NV;
555   }
556   
557   return 0;
558 }
559
560 /// commonIntCastTransforms - This function implements the common transforms
561 /// for trunc, zext, and sext.
562 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
563   if (Instruction *Result = commonCastTransforms(CI))
564     return Result;
565
566   // See if we can simplify any instructions used by the LHS whose sole 
567   // purpose is to compute bits we don't care about.
568   if (SimplifyDemandedInstructionBits(CI))
569     return &CI;
570   
571   // If the source isn't an instruction or has more than one use then we
572   // can't do anything more. 
573   Instruction *Src = dyn_cast<Instruction>(CI.getOperand(0));
574   if (!Src || !Src->hasOneUse())
575     return 0;
576
577   // Check to see if we can eliminate the cast by changing the entire
578   // computation chain to do the computation in the result type.
579   const Type *SrcTy = Src->getType();
580   const Type *DestTy = CI.getType();
581   
582   // Only do this if the dest type is a simple type, don't convert the
583   // expression tree to something weird like i93 unless the source is also
584   // strange.
585   if (!isa<VectorType>(DestTy) && !ShouldChangeType(SrcTy, DestTy))
586     return 0;
587   
588   // Attempt to propagate the cast into the instruction for int->int casts.
589   unsigned NumCastsRemoved = 0;
590   switch (CI.getOpcode()) {
591   default: assert(0 && "not an integer cast");
592   case Instruction::Trunc:
593     if (!CanEvaluateInDifferentType(Src, DestTy,
594                                     Instruction::Trunc, NumCastsRemoved))
595       return 0;
596       
597     // If this cast is a truncate, evaluting in a different type always
598     // eliminates the cast, so it is always a win.
599     break;
600   case Instruction::ZExt:
601     if (!CanEvaluateInDifferentType(Src, DestTy,
602                                     Instruction::ZExt, NumCastsRemoved))
603       return 0;
604       
605     // If this is a zero-extension, we need to do an AND to maintain the clear
606     // top-part of the computation, so we require that the input have eliminated
607     // at least one cast.  
608     if (NumCastsRemoved < 1)
609       return 0;
610     break;
611   case Instruction::SExt: {
612     // Check to see if we can do this transformation, and if so, how many bits
613     // of the promoted expression will be known copies of the sign bit in the
614     // result.
615     unsigned NumBitsSExt = CanEvaluateSExtd(Src, DestTy, NumCastsRemoved, TD);
616     if (NumBitsSExt == 0)
617       return 0;
618
619     uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
620     uint32_t DestBitSize = DestTy->getScalarSizeInBits();
621
622     // Because this is a sign extension, we can always transform it by inserting
623     // two new shifts (to do the extension).  However, this is only profitable
624     // if we've eliminated two or more casts from the input.  If we know the
625     // result will be sign-extended enough to not require these shifts, we can
626     // always do the transformation.
627     if (NumCastsRemoved < 2 &&
628         NumBitsSExt <= DestBitSize-SrcBitSize)
629       return 0;
630     
631     // Okay, we can transform this!  Insert the new expression now.
632     DEBUG(dbgs() << "ICE: EvaluateInDifferentType converting expression type"
633           " to avoid sign extend: " << CI);
634     Value *Res = EvaluateInDifferentType(Src, DestTy, true);
635     assert(Res->getType() == DestTy);
636     
637     // If the high bits are already filled with sign bit, just replace this
638     // cast with the result.
639     if (NumBitsSExt > DestBitSize - SrcBitSize ||
640         ComputeNumSignBits(Res) > DestBitSize - SrcBitSize)
641       return ReplaceInstUsesWith(CI, Res);
642     
643     // We need to emit a cast to truncate, then a cast to sext.
644     return new SExtInst(Builder->CreateTrunc(Res, Src->getType()), DestTy);
645   }
646   }
647   
648   DEBUG(dbgs() << "ICE: EvaluateInDifferentType converting expression type"
649         " to avoid cast: " << CI);
650   Value *Res = EvaluateInDifferentType(Src, DestTy, false);
651   assert(Res->getType() == DestTy);
652
653   uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
654   uint32_t DestBitSize = DestTy->getScalarSizeInBits();
655   switch (CI.getOpcode()) {
656   default: assert(0 && "Unknown cast type!");
657   case Instruction::Trunc:
658     // Just replace this cast with the result.
659     return ReplaceInstUsesWith(CI, Res);
660   case Instruction::ZExt: {
661     // If the high bits are already zero, just replace this cast with the
662     // result.
663     APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
664     if (MaskedValueIsZero(Res, Mask))
665       return ReplaceInstUsesWith(CI, Res);
666
667     // We need to emit an AND to clear the high bits.
668     Constant *C = ConstantInt::get(CI.getContext(), 
669                              APInt::getLowBitsSet(DestBitSize, SrcBitSize));
670     return BinaryOperator::CreateAnd(Res, C);
671   }
672   case Instruction::SExt: {
673     // If the high bits are already filled with sign bit, just replace this
674     // cast with the result.
675     unsigned NumSignBits = ComputeNumSignBits(Res);
676     if (NumSignBits > (DestBitSize - SrcBitSize))
677       return ReplaceInstUsesWith(CI, Res);
678
679     // We need to emit a cast to truncate, then a cast to sext.
680     return new SExtInst(Builder->CreateTrunc(Res, Src->getType()), DestTy);
681   }
682   }
683 }
684
685 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
686   if (Instruction *Result = commonIntCastTransforms(CI))
687     return Result;
688   
689   Value *Src = CI.getOperand(0);
690   const Type *DestTy = CI.getType();
691
692   // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0), likewise for vector.
693   if (DestTy->getScalarSizeInBits() == 1) {
694     Constant *One = ConstantInt::get(Src->getType(), 1);
695     Src = Builder->CreateAnd(Src, One, "tmp");
696     Value *Zero = Constant::getNullValue(Src->getType());
697     return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
698   }
699
700   return 0;
701 }
702
703 /// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
704 /// in order to eliminate the icmp.
705 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
706                                              bool DoXform) {
707   // If we are just checking for a icmp eq of a single bit and zext'ing it
708   // to an integer, then shift the bit to the appropriate place and then
709   // cast to integer to avoid the comparison.
710   if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
711     const APInt &Op1CV = Op1C->getValue();
712       
713     // zext (x <s  0) to i32 --> x>>u31      true if signbit set.
714     // zext (x >s -1) to i32 --> (x>>u31)^1  true if signbit clear.
715     if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
716         (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
717       if (!DoXform) return ICI;
718
719       Value *In = ICI->getOperand(0);
720       Value *Sh = ConstantInt::get(In->getType(),
721                                    In->getType()->getScalarSizeInBits()-1);
722       In = Builder->CreateLShr(In, Sh, In->getName()+".lobit");
723       if (In->getType() != CI.getType())
724         In = Builder->CreateIntCast(In, CI.getType(), false/*ZExt*/, "tmp");
725
726       if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
727         Constant *One = ConstantInt::get(In->getType(), 1);
728         In = Builder->CreateXor(In, One, In->getName()+".not");
729       }
730
731       return ReplaceInstUsesWith(CI, In);
732     }
733       
734       
735       
736     // zext (X == 0) to i32 --> X^1      iff X has only the low bit set.
737     // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
738     // zext (X == 1) to i32 --> X        iff X has only the low bit set.
739     // zext (X == 2) to i32 --> X>>1     iff X has only the 2nd bit set.
740     // zext (X != 0) to i32 --> X        iff X has only the low bit set.
741     // zext (X != 0) to i32 --> X>>1     iff X has only the 2nd bit set.
742     // zext (X != 1) to i32 --> X^1      iff X has only the low bit set.
743     // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
744     if ((Op1CV == 0 || Op1CV.isPowerOf2()) && 
745         // This only works for EQ and NE
746         ICI->isEquality()) {
747       // If Op1C some other power of two, convert:
748       uint32_t BitWidth = Op1C->getType()->getBitWidth();
749       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
750       APInt TypeMask(APInt::getAllOnesValue(BitWidth));
751       ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
752         
753       APInt KnownZeroMask(~KnownZero);
754       if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
755         if (!DoXform) return ICI;
756
757         bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
758         if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
759           // (X&4) == 2 --> false
760           // (X&4) != 2 --> true
761           Constant *Res = ConstantInt::get(Type::getInt1Ty(CI.getContext()),
762                                            isNE);
763           Res = ConstantExpr::getZExt(Res, CI.getType());
764           return ReplaceInstUsesWith(CI, Res);
765         }
766           
767         uint32_t ShiftAmt = KnownZeroMask.logBase2();
768         Value *In = ICI->getOperand(0);
769         if (ShiftAmt) {
770           // Perform a logical shr by shiftamt.
771           // Insert the shift to put the result in the low bit.
772           In = Builder->CreateLShr(In, ConstantInt::get(In->getType(),ShiftAmt),
773                                    In->getName()+".lobit");
774         }
775           
776         if ((Op1CV != 0) == isNE) { // Toggle the low bit.
777           Constant *One = ConstantInt::get(In->getType(), 1);
778           In = Builder->CreateXor(In, One, "tmp");
779         }
780           
781         if (CI.getType() == In->getType())
782           return ReplaceInstUsesWith(CI, In);
783         else
784           return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
785       }
786     }
787   }
788
789   // icmp ne A, B is equal to xor A, B when A and B only really have one bit.
790   // It is also profitable to transform icmp eq into not(xor(A, B)) because that
791   // may lead to additional simplifications.
792   if (ICI->isEquality() && CI.getType() == ICI->getOperand(0)->getType()) {
793     if (const IntegerType *ITy = dyn_cast<IntegerType>(CI.getType())) {
794       uint32_t BitWidth = ITy->getBitWidth();
795       Value *LHS = ICI->getOperand(0);
796       Value *RHS = ICI->getOperand(1);
797
798       APInt KnownZeroLHS(BitWidth, 0), KnownOneLHS(BitWidth, 0);
799       APInt KnownZeroRHS(BitWidth, 0), KnownOneRHS(BitWidth, 0);
800       APInt TypeMask(APInt::getAllOnesValue(BitWidth));
801       ComputeMaskedBits(LHS, TypeMask, KnownZeroLHS, KnownOneLHS);
802       ComputeMaskedBits(RHS, TypeMask, KnownZeroRHS, KnownOneRHS);
803
804       if (KnownZeroLHS == KnownZeroRHS && KnownOneLHS == KnownOneRHS) {
805         APInt KnownBits = KnownZeroLHS | KnownOneLHS;
806         APInt UnknownBit = ~KnownBits;
807         if (UnknownBit.countPopulation() == 1) {
808           if (!DoXform) return ICI;
809
810           Value *Result = Builder->CreateXor(LHS, RHS);
811
812           // Mask off any bits that are set and won't be shifted away.
813           if (KnownOneLHS.uge(UnknownBit))
814             Result = Builder->CreateAnd(Result,
815                                         ConstantInt::get(ITy, UnknownBit));
816
817           // Shift the bit we're testing down to the lsb.
818           Result = Builder->CreateLShr(
819                Result, ConstantInt::get(ITy, UnknownBit.countTrailingZeros()));
820
821           if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
822             Result = Builder->CreateXor(Result, ConstantInt::get(ITy, 1));
823           Result->takeName(ICI);
824           return ReplaceInstUsesWith(CI, Result);
825         }
826       }
827     }
828   }
829
830   return 0;
831 }
832
833 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
834   // If one of the common conversion will work, do it.
835   if (Instruction *Result = commonIntCastTransforms(CI))
836     return Result;
837
838   Value *Src = CI.getOperand(0);
839
840   // If this is a TRUNC followed by a ZEXT then we are dealing with integral
841   // types and if the sizes are just right we can convert this into a logical
842   // 'and' which will be much cheaper than the pair of casts.
843   if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) {   // A->B->C cast
844     // Get the sizes of the types involved.  We know that the intermediate type
845     // will be smaller than A or C, but don't know the relation between A and C.
846     Value *A = CSrc->getOperand(0);
847     unsigned SrcSize = A->getType()->getScalarSizeInBits();
848     unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
849     unsigned DstSize = CI.getType()->getScalarSizeInBits();
850     // If we're actually extending zero bits, then if
851     // SrcSize <  DstSize: zext(a & mask)
852     // SrcSize == DstSize: a & mask
853     // SrcSize  > DstSize: trunc(a) & mask
854     if (SrcSize < DstSize) {
855       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
856       Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
857       Value *And = Builder->CreateAnd(A, AndConst, CSrc->getName()+".mask");
858       return new ZExtInst(And, CI.getType());
859     }
860     
861     if (SrcSize == DstSize) {
862       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
863       return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
864                                                            AndValue));
865     }
866     if (SrcSize > DstSize) {
867       Value *Trunc = Builder->CreateTrunc(A, CI.getType(), "tmp");
868       APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
869       return BinaryOperator::CreateAnd(Trunc, 
870                                        ConstantInt::get(Trunc->getType(),
871                                                                AndValue));
872     }
873   }
874
875   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
876     return transformZExtICmp(ICI, CI);
877
878   BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
879   if (SrcI && SrcI->getOpcode() == Instruction::Or) {
880     // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
881     // of the (zext icmp) will be transformed.
882     ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
883     ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
884     if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
885         (transformZExtICmp(LHS, CI, false) ||
886          transformZExtICmp(RHS, CI, false))) {
887       Value *LCast = Builder->CreateZExt(LHS, CI.getType(), LHS->getName());
888       Value *RCast = Builder->CreateZExt(RHS, CI.getType(), RHS->getName());
889       return BinaryOperator::Create(Instruction::Or, LCast, RCast);
890     }
891   }
892
893   // zext(trunc(t) & C) -> (t & zext(C)).
894   if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
895     if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
896       if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
897         Value *TI0 = TI->getOperand(0);
898         if (TI0->getType() == CI.getType())
899           return
900             BinaryOperator::CreateAnd(TI0,
901                                 ConstantExpr::getZExt(C, CI.getType()));
902       }
903
904   // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
905   if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
906     if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
907       if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
908         if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
909             And->getOperand(1) == C)
910           if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
911             Value *TI0 = TI->getOperand(0);
912             if (TI0->getType() == CI.getType()) {
913               Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
914               Value *NewAnd = Builder->CreateAnd(TI0, ZC, "tmp");
915               return BinaryOperator::CreateXor(NewAnd, ZC);
916             }
917           }
918
919   // zext (xor i1 X, true) to i32  --> xor (zext i1 X to i32), 1
920   Value *X;
921   if (SrcI && SrcI->hasOneUse() && SrcI->getType()->isInteger(1) &&
922       match(SrcI, m_Not(m_Value(X))) &&
923       (!X->hasOneUse() || !isa<CmpInst>(X))) {
924     Value *New = Builder->CreateZExt(X, CI.getType());
925     return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
926   }
927   
928   return 0;
929 }
930
931 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
932   if (Instruction *I = commonIntCastTransforms(CI))
933     return I;
934   
935   Value *Src = CI.getOperand(0);
936   
937   // Canonicalize sign-extend from i1 to a select.
938   if (Src->getType()->isInteger(1))
939     return SelectInst::Create(Src,
940                               Constant::getAllOnesValue(CI.getType()),
941                               Constant::getNullValue(CI.getType()));
942
943   // See if the value being truncated is already sign extended.  If so, just
944   // eliminate the trunc/sext pair.
945   if (Operator::getOpcode(Src) == Instruction::Trunc) {
946     Value *Op = cast<User>(Src)->getOperand(0);
947     unsigned OpBits   = Op->getType()->getScalarSizeInBits();
948     unsigned MidBits  = Src->getType()->getScalarSizeInBits();
949     unsigned DestBits = CI.getType()->getScalarSizeInBits();
950     unsigned NumSignBits = ComputeNumSignBits(Op);
951
952     if (OpBits == DestBits) {
953       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
954       // bits, it is already ready.
955       if (NumSignBits > DestBits-MidBits)
956         return ReplaceInstUsesWith(CI, Op);
957     } else if (OpBits < DestBits) {
958       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
959       // bits, just sext from i32.
960       if (NumSignBits > OpBits-MidBits)
961         return new SExtInst(Op, CI.getType(), "tmp");
962     } else {
963       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
964       // bits, just truncate to i32.
965       if (NumSignBits > OpBits-MidBits)
966         return new TruncInst(Op, CI.getType(), "tmp");
967     }
968   }
969
970   // If the input is a shl/ashr pair of a same constant, then this is a sign
971   // extension from a smaller value.  If we could trust arbitrary bitwidth
972   // integers, we could turn this into a truncate to the smaller bit and then
973   // use a sext for the whole extension.  Since we don't, look deeper and check
974   // for a truncate.  If the source and dest are the same type, eliminate the
975   // trunc and extend and just do shifts.  For example, turn:
976   //   %a = trunc i32 %i to i8
977   //   %b = shl i8 %a, 6
978   //   %c = ashr i8 %b, 6
979   //   %d = sext i8 %c to i32
980   // into:
981   //   %a = shl i32 %i, 30
982   //   %d = ashr i32 %a, 30
983   Value *A = 0;
984   ConstantInt *BA = 0, *CA = 0;
985   if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
986                         m_ConstantInt(CA))) &&
987       BA == CA && isa<TruncInst>(A)) {
988     Value *I = cast<TruncInst>(A)->getOperand(0);
989     if (I->getType() == CI.getType()) {
990       unsigned MidSize = Src->getType()->getScalarSizeInBits();
991       unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
992       unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
993       Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
994       I = Builder->CreateShl(I, ShAmtV, CI.getName());
995       return BinaryOperator::CreateAShr(I, ShAmtV);
996     }
997   }
998   
999   return 0;
1000 }
1001
1002
1003 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
1004 /// in the specified FP type without changing its value.
1005 static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
1006   bool losesInfo;
1007   APFloat F = CFP->getValueAPF();
1008   (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
1009   if (!losesInfo)
1010     return ConstantFP::get(CFP->getContext(), F);
1011   return 0;
1012 }
1013
1014 /// LookThroughFPExtensions - If this is an fp extension instruction, look
1015 /// through it until we get the source value.
1016 static Value *LookThroughFPExtensions(Value *V) {
1017   if (Instruction *I = dyn_cast<Instruction>(V))
1018     if (I->getOpcode() == Instruction::FPExt)
1019       return LookThroughFPExtensions(I->getOperand(0));
1020   
1021   // If this value is a constant, return the constant in the smallest FP type
1022   // that can accurately represent it.  This allows us to turn
1023   // (float)((double)X+2.0) into x+2.0f.
1024   if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
1025     if (CFP->getType() == Type::getPPC_FP128Ty(V->getContext()))
1026       return V;  // No constant folding of this.
1027     // See if the value can be truncated to float and then reextended.
1028     if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
1029       return V;
1030     if (CFP->getType()->isDoubleTy())
1031       return V;  // Won't shrink.
1032     if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
1033       return V;
1034     // Don't try to shrink to various long double types.
1035   }
1036   
1037   return V;
1038 }
1039
1040 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
1041   if (Instruction *I = commonCastTransforms(CI))
1042     return I;
1043   
1044   // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
1045   // smaller than the destination type, we can eliminate the truncate by doing
1046   // the add as the smaller type.  This applies to fadd/fsub/fmul/fdiv as well
1047   // as many builtins (sqrt, etc).
1048   BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
1049   if (OpI && OpI->hasOneUse()) {
1050     switch (OpI->getOpcode()) {
1051     default: break;
1052     case Instruction::FAdd:
1053     case Instruction::FSub:
1054     case Instruction::FMul:
1055     case Instruction::FDiv:
1056     case Instruction::FRem:
1057       const Type *SrcTy = OpI->getType();
1058       Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
1059       Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
1060       if (LHSTrunc->getType() != SrcTy && 
1061           RHSTrunc->getType() != SrcTy) {
1062         unsigned DstSize = CI.getType()->getScalarSizeInBits();
1063         // If the source types were both smaller than the destination type of
1064         // the cast, do this xform.
1065         if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
1066             RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
1067           LHSTrunc = Builder->CreateFPExt(LHSTrunc, CI.getType());
1068           RHSTrunc = Builder->CreateFPExt(RHSTrunc, CI.getType());
1069           return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
1070         }
1071       }
1072       break;  
1073     }
1074   }
1075   return 0;
1076 }
1077
1078 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
1079   return commonCastTransforms(CI);
1080 }
1081
1082 Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
1083   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
1084   if (OpI == 0)
1085     return commonCastTransforms(FI);
1086
1087   // fptoui(uitofp(X)) --> X
1088   // fptoui(sitofp(X)) --> X
1089   // This is safe if the intermediate type has enough bits in its mantissa to
1090   // accurately represent all values of X.  For example, do not do this with
1091   // i64->float->i64.  This is also safe for sitofp case, because any negative
1092   // 'X' value would cause an undefined result for the fptoui. 
1093   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
1094       OpI->getOperand(0)->getType() == FI.getType() &&
1095       (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
1096                     OpI->getType()->getFPMantissaWidth())
1097     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
1098
1099   return commonCastTransforms(FI);
1100 }
1101
1102 Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
1103   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
1104   if (OpI == 0)
1105     return commonCastTransforms(FI);
1106   
1107   // fptosi(sitofp(X)) --> X
1108   // fptosi(uitofp(X)) --> X
1109   // This is safe if the intermediate type has enough bits in its mantissa to
1110   // accurately represent all values of X.  For example, do not do this with
1111   // i64->float->i64.  This is also safe for sitofp case, because any negative
1112   // 'X' value would cause an undefined result for the fptoui. 
1113   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
1114       OpI->getOperand(0)->getType() == FI.getType() &&
1115       (int)FI.getType()->getScalarSizeInBits() <=
1116                     OpI->getType()->getFPMantissaWidth())
1117     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
1118   
1119   return commonCastTransforms(FI);
1120 }
1121
1122 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
1123   return commonCastTransforms(CI);
1124 }
1125
1126 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
1127   return commonCastTransforms(CI);
1128 }
1129
1130 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
1131   // If the source integer type is larger than the intptr_t type for
1132   // this target, do a trunc to the intptr_t type, then inttoptr of it.  This
1133   // allows the trunc to be exposed to other transforms.  Don't do this for
1134   // extending inttoptr's, because we don't know if the target sign or zero
1135   // extends to pointers.
1136   if (TD && CI.getOperand(0)->getType()->getScalarSizeInBits() >
1137       TD->getPointerSizeInBits()) {
1138     Value *P = Builder->CreateTrunc(CI.getOperand(0),
1139                                     TD->getIntPtrType(CI.getContext()), "tmp");
1140     return new IntToPtrInst(P, CI.getType());
1141   }
1142   
1143   if (Instruction *I = commonCastTransforms(CI))
1144     return I;
1145
1146   return 0;
1147 }
1148
1149 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
1150 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
1151   Value *Src = CI.getOperand(0);
1152   
1153   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
1154     // If casting the result of a getelementptr instruction with no offset, turn
1155     // this into a cast of the original pointer!
1156     if (GEP->hasAllZeroIndices()) {
1157       // Changing the cast operand is usually not a good idea but it is safe
1158       // here because the pointer operand is being replaced with another 
1159       // pointer operand so the opcode doesn't need to change.
1160       Worklist.Add(GEP);
1161       CI.setOperand(0, GEP->getOperand(0));
1162       return &CI;
1163     }
1164     
1165     // If the GEP has a single use, and the base pointer is a bitcast, and the
1166     // GEP computes a constant offset, see if we can convert these three
1167     // instructions into fewer.  This typically happens with unions and other
1168     // non-type-safe code.
1169     if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0)) &&
1170         GEP->hasAllConstantIndices()) {
1171       // We are guaranteed to get a constant from EmitGEPOffset.
1172       ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP));
1173       int64_t Offset = OffsetV->getSExtValue();
1174       
1175       // Get the base pointer input of the bitcast, and the type it points to.
1176       Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
1177       const Type *GEPIdxTy =
1178       cast<PointerType>(OrigBase->getType())->getElementType();
1179       SmallVector<Value*, 8> NewIndices;
1180       if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices)) {
1181         // If we were able to index down into an element, create the GEP
1182         // and bitcast the result.  This eliminates one bitcast, potentially
1183         // two.
1184         Value *NGEP = cast<GEPOperator>(GEP)->isInBounds() ?
1185         Builder->CreateInBoundsGEP(OrigBase,
1186                                    NewIndices.begin(), NewIndices.end()) :
1187         Builder->CreateGEP(OrigBase, NewIndices.begin(), NewIndices.end());
1188         NGEP->takeName(GEP);
1189         
1190         if (isa<BitCastInst>(CI))
1191           return new BitCastInst(NGEP, CI.getType());
1192         assert(isa<PtrToIntInst>(CI));
1193         return new PtrToIntInst(NGEP, CI.getType());
1194       }      
1195     }
1196   }
1197   
1198   return commonCastTransforms(CI);
1199 }
1200
1201 Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
1202   // If the destination integer type is smaller than the intptr_t type for
1203   // this target, do a ptrtoint to intptr_t then do a trunc.  This allows the
1204   // trunc to be exposed to other transforms.  Don't do this for extending
1205   // ptrtoint's, because we don't know if the target sign or zero extends its
1206   // pointers.
1207   if (TD &&
1208       CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
1209     Value *P = Builder->CreatePtrToInt(CI.getOperand(0),
1210                                        TD->getIntPtrType(CI.getContext()),
1211                                        "tmp");
1212     return new TruncInst(P, CI.getType());
1213   }
1214   
1215   return commonPointerCastTransforms(CI);
1216 }
1217
1218 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
1219   // If the operands are integer typed then apply the integer transforms,
1220   // otherwise just apply the common ones.
1221   Value *Src = CI.getOperand(0);
1222   const Type *SrcTy = Src->getType();
1223   const Type *DestTy = CI.getType();
1224
1225   // Get rid of casts from one type to the same type. These are useless and can
1226   // be replaced by the operand.
1227   if (DestTy == Src->getType())
1228     return ReplaceInstUsesWith(CI, Src);
1229
1230   if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
1231     const PointerType *SrcPTy = cast<PointerType>(SrcTy);
1232     const Type *DstElTy = DstPTy->getElementType();
1233     const Type *SrcElTy = SrcPTy->getElementType();
1234     
1235     // If the address spaces don't match, don't eliminate the bitcast, which is
1236     // required for changing types.
1237     if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
1238       return 0;
1239     
1240     // If we are casting a alloca to a pointer to a type of the same
1241     // size, rewrite the allocation instruction to allocate the "right" type.
1242     // There is no need to modify malloc calls because it is their bitcast that
1243     // needs to be cleaned up.
1244     if (AllocaInst *AI = dyn_cast<AllocaInst>(Src))
1245       if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
1246         return V;
1247     
1248     // If the source and destination are pointers, and this cast is equivalent
1249     // to a getelementptr X, 0, 0, 0...  turn it into the appropriate gep.
1250     // This can enhance SROA and other transforms that want type-safe pointers.
1251     Constant *ZeroUInt =
1252       Constant::getNullValue(Type::getInt32Ty(CI.getContext()));
1253     unsigned NumZeros = 0;
1254     while (SrcElTy != DstElTy && 
1255            isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
1256            SrcElTy->getNumContainedTypes() /* not "{}" */) {
1257       SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
1258       ++NumZeros;
1259     }
1260
1261     // If we found a path from the src to dest, create the getelementptr now.
1262     if (SrcElTy == DstElTy) {
1263       SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
1264       return GetElementPtrInst::CreateInBounds(Src, Idxs.begin(), Idxs.end(),"",
1265                                                ((Instruction*)NULL));
1266     }
1267   }
1268
1269   if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
1270     if (DestVTy->getNumElements() == 1 && !isa<VectorType>(SrcTy)) {
1271       Value *Elem = Builder->CreateBitCast(Src, DestVTy->getElementType());
1272       return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
1273                      Constant::getNullValue(Type::getInt32Ty(CI.getContext())));
1274       // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
1275     }
1276   }
1277
1278   if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
1279     if (SrcVTy->getNumElements() == 1 && !isa<VectorType>(DestTy)) {
1280       Value *Elem = 
1281         Builder->CreateExtractElement(Src,
1282                    Constant::getNullValue(Type::getInt32Ty(CI.getContext())));
1283       return CastInst::Create(Instruction::BitCast, Elem, DestTy);
1284     }
1285   }
1286
1287   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
1288     // Okay, we have (bitcast (shuffle ..)).  Check to see if this is
1289     // a bitconvert to a vector with the same # elts.
1290     if (SVI->hasOneUse() && isa<VectorType>(DestTy) && 
1291         cast<VectorType>(DestTy)->getNumElements() ==
1292               SVI->getType()->getNumElements() &&
1293         SVI->getType()->getNumElements() ==
1294           cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
1295       BitCastInst *Tmp;
1296       // If either of the operands is a cast from CI.getType(), then
1297       // evaluating the shuffle in the casted destination's type will allow
1298       // us to eliminate at least one cast.
1299       if (((Tmp = dyn_cast<BitCastInst>(SVI->getOperand(0))) && 
1300            Tmp->getOperand(0)->getType() == DestTy) ||
1301           ((Tmp = dyn_cast<BitCastInst>(SVI->getOperand(1))) && 
1302            Tmp->getOperand(0)->getType() == DestTy)) {
1303         Value *LHS = Builder->CreateBitCast(SVI->getOperand(0), DestTy);
1304         Value *RHS = Builder->CreateBitCast(SVI->getOperand(1), DestTy);
1305         // Return a new shuffle vector.  Use the same element ID's, as we
1306         // know the vector types match #elts.
1307         return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
1308       }
1309     }
1310   }
1311   
1312   if (isa<PointerType>(SrcTy))
1313     return commonPointerCastTransforms(CI);
1314   return commonCastTransforms(CI);
1315 }