404f3b64b5dd4b8cc6af4af8e1ef1908127f0b28
[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() == Type::getInt32Ty(Val->getContext()) && 
27          "Unexpected allocation size type!");
28   if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
29     Offset = CI->getZExtValue();
30     Scale  = 0;
31     return ConstantInt::get(Type::getInt32Ty(Val->getContext()), 0);
32   } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
33     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
34       if (I->getOpcode() == Instruction::Shl) {
35         // This is a value scaled by '1 << the shift amt'.
36         Scale = 1U << RHS->getZExtValue();
37         Offset = 0;
38         return I->getOperand(0);
39       } else if (I->getOpcode() == Instruction::Mul) {
40         // This value is scaled by 'RHS'.
41         Scale = RHS->getZExtValue();
42         Offset = 0;
43         return I->getOperand(0);
44       } else if (I->getOpcode() == Instruction::Add) {
45         // We have X+C.  Check to see if we really have (X*C2)+C1, 
46         // where C1 is divisible by C2.
47         unsigned SubScale;
48         Value *SubVal = 
49           DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
50         Offset += RHS->getZExtValue();
51         Scale = SubScale;
52         return SubVal;
53       }
54     }
55   }
56
57   // Otherwise, we can't look past this.
58   Scale = 1;
59   Offset = 0;
60   return Val;
61 }
62
63 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
64 /// try to eliminate the cast by moving the type information into the alloc.
65 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
66                                                    AllocaInst &AI) {
67   // This requires TargetData to get the alloca alignment and size information.
68   if (!TD) return 0;
69
70   const PointerType *PTy = cast<PointerType>(CI.getType());
71   
72   BuilderTy AllocaBuilder(*Builder);
73   AllocaBuilder.SetInsertPoint(AI.getParent(), &AI);
74
75   // Get the type really allocated and the type casted to.
76   const Type *AllocElTy = AI.getAllocatedType();
77   const Type *CastElTy = PTy->getElementType();
78   if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
79
80   unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
81   unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
82   if (CastElTyAlign < AllocElTyAlign) return 0;
83
84   // If the allocation has multiple uses, only promote it if we are strictly
85   // increasing the alignment of the resultant allocation.  If we keep it the
86   // same, we open the door to infinite loops of various kinds.  (A reference
87   // from a dbg.declare doesn't count as a use for this purpose.)
88   if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
89       CastElTyAlign == AllocElTyAlign) return 0;
90
91   uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
92   uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
93   if (CastElTySize == 0 || AllocElTySize == 0) return 0;
94
95   // See if we can satisfy the modulus by pulling a scale out of the array
96   // size argument.
97   unsigned ArraySizeScale;
98   int ArrayOffset;
99   Value *NumElements = // See if the array size is a decomposable linear expr.
100     DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
101  
102   // If we can now satisfy the modulus, by using a non-1 scale, we really can
103   // do the xform.
104   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
105       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return 0;
106
107   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
108   Value *Amt = 0;
109   if (Scale == 1) {
110     Amt = NumElements;
111   } else {
112     Amt = ConstantInt::get(Type::getInt32Ty(CI.getContext()), Scale);
113     // Insert before the alloca, not before the cast.
114     Amt = AllocaBuilder.CreateMul(Amt, NumElements, "tmp");
115   }
116   
117   if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
118     Value *Off = ConstantInt::get(Type::getInt32Ty(CI.getContext()),
119                                   Offset, true);
120     Amt = AllocaBuilder.CreateAdd(Amt, Off, "tmp");
121   }
122   
123   AllocaInst *New = AllocaBuilder.CreateAlloca(CastElTy, Amt);
124   New->setAlignment(AI.getAlignment());
125   New->takeName(&AI);
126   
127   // If the allocation has one real use plus a dbg.declare, just remove the
128   // declare.
129   if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
130     EraseInstFromFunction(*(Instruction*)DI);
131   }
132   // If the allocation has multiple real uses, insert a cast and change all
133   // things that used it to use the new cast.  This will also hack on CI, but it
134   // will die soon.
135   else if (!AI.hasOneUse()) {
136     // New is the allocation instruction, pointer typed. AI is the original
137     // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
138     Value *NewCast = AllocaBuilder.CreateBitCast(New, AI.getType(), "tmpcast");
139     AI.replaceAllUsesWith(NewCast);
140   }
141   return ReplaceInstUsesWith(CI, New);
142 }
143
144
145 /// CanEvaluateInDifferentType - Return true if we can take the specified value
146 /// and return it as type Ty without inserting any new casts and without
147 /// changing the computed value.  This is used by code that tries to decide
148 /// whether promoting or shrinking integer operations to wider or smaller types
149 /// will allow us to eliminate a truncate or extend.
150 ///
151 /// This is a truncation operation if Ty is smaller than V->getType(), or an
152 /// extension operation if Ty is larger.
153 ///
154 /// If CastOpc is a truncation, then Ty will be a type smaller than V.  We
155 /// should return true if trunc(V) can be computed by computing V in the smaller
156 /// type.  If V is an instruction, then trunc(inst(x,y)) can be computed as
157 /// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
158 /// efficiently truncated.
159 ///
160 /// If CastOpc is a sext or zext, we are asking if the low bits of the value can
161 /// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
162 /// the final result.
163 bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
164                                               unsigned CastOpc,
165                                               int &NumCastsRemoved){
166   // We can always evaluate constants in another type.
167   if (isa<Constant>(V))
168     return true;
169   
170   Instruction *I = dyn_cast<Instruction>(V);
171   if (!I) return false;
172   
173   const Type *OrigTy = V->getType();
174   
175   // If this is an extension or truncate, we can often eliminate it.
176   if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
177     // If this is a cast from the destination type, we can trivially eliminate
178     // it, and this will remove a cast overall.
179     if (I->getOperand(0)->getType() == Ty) {
180       // If the first operand is itself a cast, and is eliminable, do not count
181       // this as an eliminable cast.  We would prefer to eliminate those two
182       // casts first.
183       if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
184         ++NumCastsRemoved;
185       return true;
186     }
187   }
188
189   // We can't extend or shrink something that has multiple uses: doing so would
190   // require duplicating the instruction in general, which isn't profitable.
191   if (!I->hasOneUse()) return false;
192
193   unsigned Opc = I->getOpcode();
194   switch (Opc) {
195   case Instruction::Add:
196   case Instruction::Sub:
197   case Instruction::Mul:
198   case Instruction::And:
199   case Instruction::Or:
200   case Instruction::Xor:
201     // These operators can all arbitrarily be extended or truncated.
202     return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
203                                       NumCastsRemoved) &&
204            CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
205                                       NumCastsRemoved);
206
207   case Instruction::UDiv:
208   case Instruction::URem: {
209     // UDiv and URem can be truncated if all the truncated bits are zero.
210     uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
211     uint32_t BitWidth = Ty->getScalarSizeInBits();
212     if (BitWidth < OrigBitWidth) {
213       APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
214       if (MaskedValueIsZero(I->getOperand(0), Mask) &&
215           MaskedValueIsZero(I->getOperand(1), Mask)) {
216         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
217                                           NumCastsRemoved) &&
218                CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
219                                           NumCastsRemoved);
220       }
221     }
222     break;
223   }
224   case Instruction::Shl:
225     // If we are truncating the result of this SHL, and if it's a shift of a
226     // constant amount, we can always perform a SHL in a smaller type.
227     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
228       uint32_t BitWidth = Ty->getScalarSizeInBits();
229       if (BitWidth < OrigTy->getScalarSizeInBits() &&
230           CI->getLimitedValue(BitWidth) < BitWidth)
231         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
232                                           NumCastsRemoved);
233     }
234     break;
235   case Instruction::LShr:
236     // If this is a truncate of a logical shr, we can truncate it to a smaller
237     // lshr iff we know that the bits we would otherwise be shifting in are
238     // already zeros.
239     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
240       uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
241       uint32_t BitWidth = Ty->getScalarSizeInBits();
242       if (BitWidth < OrigBitWidth &&
243           MaskedValueIsZero(I->getOperand(0),
244             APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
245           CI->getLimitedValue(BitWidth) < BitWidth) {
246         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
247                                           NumCastsRemoved);
248       }
249     }
250     break;
251   case Instruction::ZExt:
252   case Instruction::SExt:
253   case Instruction::Trunc:
254     // If this is the same kind of case as our original (e.g. zext+zext), we
255     // can safely replace it.  Note that replacing it does not reduce the number
256     // of casts in the input.
257     if (Opc == CastOpc)
258       return true;
259
260     // sext (zext ty1), ty2 -> zext ty2
261     if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
262       return true;
263     break;
264   case Instruction::Select: {
265     SelectInst *SI = cast<SelectInst>(I);
266     return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
267                                       NumCastsRemoved) &&
268            CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
269                                       NumCastsRemoved);
270   }
271   case Instruction::PHI: {
272     // We can change a phi if we can change all operands.
273     PHINode *PN = cast<PHINode>(I);
274     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
275       if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
276                                       NumCastsRemoved))
277         return false;
278     return true;
279   }
280   default:
281     // TODO: Can handle more cases here.
282     break;
283   }
284   
285   return false;
286 }
287
288 /// EvaluateInDifferentType - Given an expression that 
289 /// CanEvaluateInDifferentType returns true for, actually insert the code to
290 /// evaluate the expression.
291 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty, 
292                                              bool isSigned) {
293   if (Constant *C = dyn_cast<Constant>(V))
294     return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
295
296   // Otherwise, it must be an instruction.
297   Instruction *I = cast<Instruction>(V);
298   Instruction *Res = 0;
299   unsigned Opc = I->getOpcode();
300   switch (Opc) {
301   case Instruction::Add:
302   case Instruction::Sub:
303   case Instruction::Mul:
304   case Instruction::And:
305   case Instruction::Or:
306   case Instruction::Xor:
307   case Instruction::AShr:
308   case Instruction::LShr:
309   case Instruction::Shl:
310   case Instruction::UDiv:
311   case Instruction::URem: {
312     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
313     Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
314     Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
315     break;
316   }    
317   case Instruction::Trunc:
318   case Instruction::ZExt:
319   case Instruction::SExt:
320     // If the source type of the cast is the type we're trying for then we can
321     // just return the source.  There's no need to insert it because it is not
322     // new.
323     if (I->getOperand(0)->getType() == Ty)
324       return I->getOperand(0);
325     
326     // Otherwise, must be the same type of cast, so just reinsert a new one.
327     Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),Ty);
328     break;
329   case Instruction::Select: {
330     Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
331     Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
332     Res = SelectInst::Create(I->getOperand(0), True, False);
333     break;
334   }
335   case Instruction::PHI: {
336     PHINode *OPN = cast<PHINode>(I);
337     PHINode *NPN = PHINode::Create(Ty);
338     for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
339       Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
340       NPN->addIncoming(V, OPN->getIncomingBlock(i));
341     }
342     Res = NPN;
343     break;
344   }
345   default: 
346     // TODO: Can handle more cases here.
347     llvm_unreachable("Unreachable!");
348     break;
349   }
350   
351   Res->takeName(I);
352   return InsertNewInstBefore(Res, *I);
353 }
354
355
356 /// This function is a wrapper around CastInst::isEliminableCastPair. It
357 /// simply extracts arguments and returns what that function returns.
358 static Instruction::CastOps 
359 isEliminableCastPair(
360   const CastInst *CI, ///< The first cast instruction
361   unsigned opcode,       ///< The opcode of the second cast instruction
362   const Type *DstTy,     ///< The target type for the second cast instruction
363   TargetData *TD         ///< The target data for pointer size
364 ) {
365
366   const Type *SrcTy = CI->getOperand(0)->getType();   // A from above
367   const Type *MidTy = CI->getType();                  // B from above
368
369   // Get the opcodes of the two Cast instructions
370   Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
371   Instruction::CastOps secondOp = Instruction::CastOps(opcode);
372
373   unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
374                                                 DstTy,
375                                   TD ? TD->getIntPtrType(CI->getContext()) : 0);
376   
377   // We don't want to form an inttoptr or ptrtoint that converts to an integer
378   // type that differs from the pointer size.
379   if ((Res == Instruction::IntToPtr &&
380           (!TD || SrcTy != TD->getIntPtrType(CI->getContext()))) ||
381       (Res == Instruction::PtrToInt &&
382           (!TD || DstTy != TD->getIntPtrType(CI->getContext()))))
383     Res = 0;
384   
385   return Instruction::CastOps(Res);
386 }
387
388 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
389 /// in any code being generated.  It does not require codegen if V is simple
390 /// enough or if the cast can be folded into other casts.
391 bool InstCombiner::ValueRequiresCast(Instruction::CastOps opcode,const Value *V,
392                                      const Type *Ty) {
393   if (V->getType() == Ty || isa<Constant>(V)) return false;
394   
395   // If this is another cast that can be eliminated, it isn't codegen either.
396   if (const CastInst *CI = dyn_cast<CastInst>(V))
397     if (isEliminableCastPair(CI, opcode, Ty, TD))
398       return false;
399   return true;
400 }
401
402
403 /// @brief Implement the transforms common to all CastInst visitors.
404 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
405   Value *Src = CI.getOperand(0);
406
407   // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
408   // eliminate it now.
409   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
410     if (Instruction::CastOps opc = 
411         isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
412       // The first cast (CSrc) is eliminable so we need to fix up or replace
413       // the second cast (CI). CSrc will then have a good chance of being dead.
414       return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
415     }
416   }
417
418   // If we are casting a select then fold the cast into the select
419   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
420     if (Instruction *NV = FoldOpIntoSelect(CI, SI))
421       return NV;
422
423   // If we are casting a PHI then fold the cast into the PHI
424   if (isa<PHINode>(Src)) {
425     // We don't do this if this would create a PHI node with an illegal type if
426     // it is currently legal.
427     if (!isa<IntegerType>(Src->getType()) ||
428         !isa<IntegerType>(CI.getType()) ||
429         ShouldChangeType(CI.getType(), Src->getType()))
430       if (Instruction *NV = FoldOpIntoPhi(CI))
431         return NV;
432   }
433   
434   return 0;
435 }
436
437 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
438 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
439   Value *Src = CI.getOperand(0);
440   
441   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
442     // If casting the result of a getelementptr instruction with no offset, turn
443     // this into a cast of the original pointer!
444     if (GEP->hasAllZeroIndices()) {
445       // Changing the cast operand is usually not a good idea but it is safe
446       // here because the pointer operand is being replaced with another 
447       // pointer operand so the opcode doesn't need to change.
448       Worklist.Add(GEP);
449       CI.setOperand(0, GEP->getOperand(0));
450       return &CI;
451     }
452     
453     // If the GEP has a single use, and the base pointer is a bitcast, and the
454     // GEP computes a constant offset, see if we can convert these three
455     // instructions into fewer.  This typically happens with unions and other
456     // non-type-safe code.
457     if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
458       if (GEP->hasAllConstantIndices()) {
459         // We are guaranteed to get a constant from EmitGEPOffset.
460         ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP));
461         int64_t Offset = OffsetV->getSExtValue();
462         
463         // Get the base pointer input of the bitcast, and the type it points to.
464         Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
465         const Type *GEPIdxTy =
466           cast<PointerType>(OrigBase->getType())->getElementType();
467         SmallVector<Value*, 8> NewIndices;
468         if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices)) {
469           // If we were able to index down into an element, create the GEP
470           // and bitcast the result.  This eliminates one bitcast, potentially
471           // two.
472           Value *NGEP = cast<GEPOperator>(GEP)->isInBounds() ?
473             Builder->CreateInBoundsGEP(OrigBase,
474                                        NewIndices.begin(), NewIndices.end()) :
475             Builder->CreateGEP(OrigBase, NewIndices.begin(), NewIndices.end());
476           NGEP->takeName(GEP);
477           
478           if (isa<BitCastInst>(CI))
479             return new BitCastInst(NGEP, CI.getType());
480           assert(isa<PtrToIntInst>(CI));
481           return new PtrToIntInst(NGEP, CI.getType());
482         }
483       }      
484     }
485   }
486     
487   return commonCastTransforms(CI);
488 }
489
490 /// commonIntCastTransforms - This function implements the common transforms
491 /// for trunc, zext, and sext.
492 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
493   if (Instruction *Result = commonCastTransforms(CI))
494     return Result;
495
496   Value *Src = CI.getOperand(0);
497   const Type *SrcTy = Src->getType();
498   const Type *DestTy = CI.getType();
499   uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
500   uint32_t DestBitSize = DestTy->getScalarSizeInBits();
501
502   // See if we can simplify any instructions used by the LHS whose sole 
503   // purpose is to compute bits we don't care about.
504   if (SimplifyDemandedInstructionBits(CI))
505     return &CI;
506
507   // If the source isn't an instruction or has more than one use then we
508   // can't do anything more. 
509   Instruction *SrcI = dyn_cast<Instruction>(Src);
510   if (!SrcI || !Src->hasOneUse())
511     return 0;
512
513   // Attempt to propagate the cast into the instruction for int->int casts.
514   int NumCastsRemoved = 0;
515   // Only do this if the dest type is a simple type, don't convert the
516   // expression tree to something weird like i93 unless the source is also
517   // strange.
518   if ((isa<VectorType>(DestTy) ||
519        ShouldChangeType(SrcI->getType(), DestTy)) &&
520       CanEvaluateInDifferentType(SrcI, DestTy,
521                                  CI.getOpcode(), NumCastsRemoved)) {
522     // If this cast is a truncate, evaluting in a different type always
523     // eliminates the cast, so it is always a win.  If this is a zero-extension,
524     // we need to do an AND to maintain the clear top-part of the computation,
525     // so we require that the input have eliminated at least one cast.  If this
526     // is a sign extension, we insert two new casts (to do the extension) so we
527     // require that two casts have been eliminated.
528     bool DoXForm = false;
529     bool JustReplace = false;
530     switch (CI.getOpcode()) {
531     default:
532       // All the others use floating point so we shouldn't actually 
533       // get here because of the check above.
534       llvm_unreachable("Unknown cast type");
535     case Instruction::Trunc:
536       DoXForm = true;
537       break;
538     case Instruction::ZExt: {
539       DoXForm = NumCastsRemoved >= 1;
540       
541       if (!DoXForm && 0) {
542         // If it's unnecessary to issue an AND to clear the high bits, it's
543         // always profitable to do this xform.
544         Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
545         APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
546         if (MaskedValueIsZero(TryRes, Mask))
547           return ReplaceInstUsesWith(CI, TryRes);
548         
549         if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
550           if (TryI->use_empty())
551             EraseInstFromFunction(*TryI);
552       }
553       break;
554     }
555     case Instruction::SExt: {
556       DoXForm = NumCastsRemoved >= 2;
557       if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
558         // If we do not have to emit the truncate + sext pair, then it's always
559         // profitable to do this xform.
560         //
561         // It's not safe to eliminate the trunc + sext pair if one of the
562         // eliminated cast is a truncate. e.g.
563         // t2 = trunc i32 t1 to i16
564         // t3 = sext i16 t2 to i32
565         // !=
566         // i32 t1
567         Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
568         unsigned NumSignBits = ComputeNumSignBits(TryRes);
569         if (NumSignBits > (DestBitSize - SrcBitSize))
570           return ReplaceInstUsesWith(CI, TryRes);
571         
572         if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
573           if (TryI->use_empty())
574             EraseInstFromFunction(*TryI);
575       }
576       break;
577     }
578     }
579     
580     if (DoXForm) {
581       DEBUG(errs() << "ICE: EvaluateInDifferentType converting expression type"
582             " to avoid cast: " << CI);
583       Value *Res = EvaluateInDifferentType(SrcI, DestTy, 
584                                            CI.getOpcode() == Instruction::SExt);
585       if (JustReplace)
586         // Just replace this cast with the result.
587         return ReplaceInstUsesWith(CI, Res);
588
589       assert(Res->getType() == DestTy);
590       switch (CI.getOpcode()) {
591       default: llvm_unreachable("Unknown cast type!");
592       case Instruction::Trunc:
593         // Just replace this cast with the result.
594         return ReplaceInstUsesWith(CI, Res);
595       case Instruction::ZExt: {
596         assert(SrcBitSize < DestBitSize && "Not a zext?");
597
598         // If the high bits are already zero, just replace this cast with the
599         // result.
600         APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
601         if (MaskedValueIsZero(Res, Mask))
602           return ReplaceInstUsesWith(CI, Res);
603
604         // We need to emit an AND to clear the high bits.
605         Constant *C = ConstantInt::get(CI.getContext(), 
606                                  APInt::getLowBitsSet(DestBitSize, SrcBitSize));
607         return BinaryOperator::CreateAnd(Res, C);
608       }
609       case Instruction::SExt: {
610         // If the high bits are already filled with sign bit, just replace this
611         // cast with the result.
612         unsigned NumSignBits = ComputeNumSignBits(Res);
613         if (NumSignBits > (DestBitSize - SrcBitSize))
614           return ReplaceInstUsesWith(CI, Res);
615
616         // We need to emit a cast to truncate, then a cast to sext.
617         return new SExtInst(Builder->CreateTrunc(Res, Src->getType()), DestTy);
618       }
619       }
620     }
621   }
622   
623   Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
624   Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
625
626   switch (SrcI->getOpcode()) {
627   case Instruction::Add:
628   case Instruction::Mul:
629   case Instruction::And:
630   case Instruction::Or:
631   case Instruction::Xor:
632     // If we are discarding information, rewrite.
633     if (DestBitSize < SrcBitSize && DestBitSize != 1) {
634       // Don't insert two casts unless at least one can be eliminated.
635       if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy) ||
636           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy)) {
637         Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
638         Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
639         return BinaryOperator::Create(
640             cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
641       }
642     }
643
644     // cast (xor bool X, true) to int  --> xor (cast bool X to int), 1
645     if (isa<ZExtInst>(CI) && SrcBitSize == 1 && 
646         SrcI->getOpcode() == Instruction::Xor &&
647         Op1 == ConstantInt::getTrue(CI.getContext()) &&
648         (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
649       Value *New = Builder->CreateZExt(Op0, DestTy, Op0->getName());
650       return BinaryOperator::CreateXor(New,
651                                       ConstantInt::get(CI.getType(), 1));
652     }
653     break;
654
655   case Instruction::Shl: {
656     // Canonicalize trunc inside shl, if we can.
657     ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
658     if (CI && DestBitSize < SrcBitSize &&
659         CI->getLimitedValue(DestBitSize) < DestBitSize) {
660       Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
661       Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
662       return BinaryOperator::CreateShl(Op0c, Op1c);
663     }
664     break;
665   }
666   }
667   return 0;
668 }
669
670
671 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
672   if (Instruction *Result = commonIntCastTransforms(CI))
673     return Result;
674   
675   Value *Src = CI.getOperand(0);
676   const Type *Ty = CI.getType();
677   uint32_t DestBitWidth = Ty->getScalarSizeInBits();
678   uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
679
680   // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
681   if (DestBitWidth == 1) {
682     Constant *One = ConstantInt::get(Src->getType(), 1);
683     Src = Builder->CreateAnd(Src, One, "tmp");
684     Value *Zero = Constant::getNullValue(Src->getType());
685     return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
686   }
687
688   // Optimize trunc(lshr(), c) to pull the shift through the truncate.
689   ConstantInt *ShAmtV = 0;
690   Value *ShiftOp = 0;
691   if (Src->hasOneUse() &&
692       match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)))) {
693     uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
694     
695     // Get a mask for the bits shifting in.
696     APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
697     if (MaskedValueIsZero(ShiftOp, Mask)) {
698       if (ShAmt >= DestBitWidth)        // All zeros.
699         return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
700       
701       // Okay, we can shrink this.  Truncate the input, then return a new
702       // shift.
703       Value *V1 = Builder->CreateTrunc(ShiftOp, Ty, ShiftOp->getName());
704       Value *V2 = ConstantExpr::getTrunc(ShAmtV, Ty);
705       return BinaryOperator::CreateLShr(V1, V2);
706     }
707   }
708  
709   return 0;
710 }
711
712 /// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
713 /// in order to eliminate the icmp.
714 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
715                                              bool DoXform) {
716   // If we are just checking for a icmp eq of a single bit and zext'ing it
717   // to an integer, then shift the bit to the appropriate place and then
718   // cast to integer to avoid the comparison.
719   if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
720     const APInt &Op1CV = Op1C->getValue();
721       
722     // zext (x <s  0) to i32 --> x>>u31      true if signbit set.
723     // zext (x >s -1) to i32 --> (x>>u31)^1  true if signbit clear.
724     if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
725         (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
726       if (!DoXform) return ICI;
727
728       Value *In = ICI->getOperand(0);
729       Value *Sh = ConstantInt::get(In->getType(),
730                                    In->getType()->getScalarSizeInBits()-1);
731       In = Builder->CreateLShr(In, Sh, In->getName()+".lobit");
732       if (In->getType() != CI.getType())
733         In = Builder->CreateIntCast(In, CI.getType(), false/*ZExt*/, "tmp");
734
735       if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
736         Constant *One = ConstantInt::get(In->getType(), 1);
737         In = Builder->CreateXor(In, One, In->getName()+".not");
738       }
739
740       return ReplaceInstUsesWith(CI, In);
741     }
742       
743       
744       
745     // zext (X == 0) to i32 --> X^1      iff X has only the low bit set.
746     // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
747     // zext (X == 1) to i32 --> X        iff X has only the low bit set.
748     // zext (X == 2) to i32 --> X>>1     iff X has only the 2nd bit set.
749     // zext (X != 0) to i32 --> X        iff X has only the low bit set.
750     // zext (X != 0) to i32 --> X>>1     iff X has only the 2nd bit set.
751     // zext (X != 1) to i32 --> X^1      iff X has only the low bit set.
752     // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
753     if ((Op1CV == 0 || Op1CV.isPowerOf2()) && 
754         // This only works for EQ and NE
755         ICI->isEquality()) {
756       // If Op1C some other power of two, convert:
757       uint32_t BitWidth = Op1C->getType()->getBitWidth();
758       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
759       APInt TypeMask(APInt::getAllOnesValue(BitWidth));
760       ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
761         
762       APInt KnownZeroMask(~KnownZero);
763       if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
764         if (!DoXform) return ICI;
765
766         bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
767         if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
768           // (X&4) == 2 --> false
769           // (X&4) != 2 --> true
770           Constant *Res = ConstantInt::get(Type::getInt1Ty(CI.getContext()),
771                                            isNE);
772           Res = ConstantExpr::getZExt(Res, CI.getType());
773           return ReplaceInstUsesWith(CI, Res);
774         }
775           
776         uint32_t ShiftAmt = KnownZeroMask.logBase2();
777         Value *In = ICI->getOperand(0);
778         if (ShiftAmt) {
779           // Perform a logical shr by shiftamt.
780           // Insert the shift to put the result in the low bit.
781           In = Builder->CreateLShr(In, ConstantInt::get(In->getType(),ShiftAmt),
782                                    In->getName()+".lobit");
783         }
784           
785         if ((Op1CV != 0) == isNE) { // Toggle the low bit.
786           Constant *One = ConstantInt::get(In->getType(), 1);
787           In = Builder->CreateXor(In, One, "tmp");
788         }
789           
790         if (CI.getType() == In->getType())
791           return ReplaceInstUsesWith(CI, In);
792         else
793           return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
794       }
795     }
796   }
797
798   // icmp ne A, B is equal to xor A, B when A and B only really have one bit.
799   // It is also profitable to transform icmp eq into not(xor(A, B)) because that
800   // may lead to additional simplifications.
801   if (ICI->isEquality() && CI.getType() == ICI->getOperand(0)->getType()) {
802     if (const IntegerType *ITy = dyn_cast<IntegerType>(CI.getType())) {
803       uint32_t BitWidth = ITy->getBitWidth();
804       Value *LHS = ICI->getOperand(0);
805       Value *RHS = ICI->getOperand(1);
806
807       APInt KnownZeroLHS(BitWidth, 0), KnownOneLHS(BitWidth, 0);
808       APInt KnownZeroRHS(BitWidth, 0), KnownOneRHS(BitWidth, 0);
809       APInt TypeMask(APInt::getAllOnesValue(BitWidth));
810       ComputeMaskedBits(LHS, TypeMask, KnownZeroLHS, KnownOneLHS);
811       ComputeMaskedBits(RHS, TypeMask, KnownZeroRHS, KnownOneRHS);
812
813       if (KnownZeroLHS == KnownZeroRHS && KnownOneLHS == KnownOneRHS) {
814         APInt KnownBits = KnownZeroLHS | KnownOneLHS;
815         APInt UnknownBit = ~KnownBits;
816         if (UnknownBit.countPopulation() == 1) {
817           if (!DoXform) return ICI;
818
819           Value *Result = Builder->CreateXor(LHS, RHS);
820
821           // Mask off any bits that are set and won't be shifted away.
822           if (KnownOneLHS.uge(UnknownBit))
823             Result = Builder->CreateAnd(Result,
824                                         ConstantInt::get(ITy, UnknownBit));
825
826           // Shift the bit we're testing down to the lsb.
827           Result = Builder->CreateLShr(
828                Result, ConstantInt::get(ITy, UnknownBit.countTrailingZeros()));
829
830           if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
831             Result = Builder->CreateXor(Result, ConstantInt::get(ITy, 1));
832           Result->takeName(ICI);
833           return ReplaceInstUsesWith(CI, Result);
834         }
835       }
836     }
837   }
838
839   return 0;
840 }
841
842 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
843   // If one of the common conversion will work, do it.
844   if (Instruction *Result = commonIntCastTransforms(CI))
845     return Result;
846
847   Value *Src = CI.getOperand(0);
848
849   // If this is a TRUNC followed by a ZEXT then we are dealing with integral
850   // types and if the sizes are just right we can convert this into a logical
851   // 'and' which will be much cheaper than the pair of casts.
852   if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) {   // A->B->C cast
853     // Get the sizes of the types involved.  We know that the intermediate type
854     // will be smaller than A or C, but don't know the relation between A and C.
855     Value *A = CSrc->getOperand(0);
856     unsigned SrcSize = A->getType()->getScalarSizeInBits();
857     unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
858     unsigned DstSize = CI.getType()->getScalarSizeInBits();
859     // If we're actually extending zero bits, then if
860     // SrcSize <  DstSize: zext(a & mask)
861     // SrcSize == DstSize: a & mask
862     // SrcSize  > DstSize: trunc(a) & mask
863     if (SrcSize < DstSize) {
864       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
865       Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
866       Value *And = Builder->CreateAnd(A, AndConst, CSrc->getName()+".mask");
867       return new ZExtInst(And, CI.getType());
868     }
869     
870     if (SrcSize == DstSize) {
871       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
872       return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
873                                                            AndValue));
874     }
875     if (SrcSize > DstSize) {
876       Value *Trunc = Builder->CreateTrunc(A, CI.getType(), "tmp");
877       APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
878       return BinaryOperator::CreateAnd(Trunc, 
879                                        ConstantInt::get(Trunc->getType(),
880                                                                AndValue));
881     }
882   }
883
884   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
885     return transformZExtICmp(ICI, CI);
886
887   BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
888   if (SrcI && SrcI->getOpcode() == Instruction::Or) {
889     // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
890     // of the (zext icmp) will be transformed.
891     ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
892     ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
893     if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
894         (transformZExtICmp(LHS, CI, false) ||
895          transformZExtICmp(RHS, CI, false))) {
896       Value *LCast = Builder->CreateZExt(LHS, CI.getType(), LHS->getName());
897       Value *RCast = Builder->CreateZExt(RHS, CI.getType(), RHS->getName());
898       return BinaryOperator::Create(Instruction::Or, LCast, RCast);
899     }
900   }
901
902   // zext(trunc(t) & C) -> (t & zext(C)).
903   if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
904     if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
905       if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
906         Value *TI0 = TI->getOperand(0);
907         if (TI0->getType() == CI.getType())
908           return
909             BinaryOperator::CreateAnd(TI0,
910                                 ConstantExpr::getZExt(C, CI.getType()));
911       }
912
913   // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
914   if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
915     if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
916       if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
917         if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
918             And->getOperand(1) == C)
919           if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
920             Value *TI0 = TI->getOperand(0);
921             if (TI0->getType() == CI.getType()) {
922               Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
923               Value *NewAnd = Builder->CreateAnd(TI0, ZC, "tmp");
924               return BinaryOperator::CreateXor(NewAnd, ZC);
925             }
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() == Type::getInt1Ty(CI.getContext()))
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() == Type::getDoubleTy(V->getContext()))
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::visitPtrToInt(PtrToIntInst &CI) {
1131   // If the destination integer type is smaller than the intptr_t type for
1132   // this target, do a ptrtoint to intptr_t then do a trunc.  This allows the
1133   // trunc to be exposed to other transforms.  Don't do this for extending
1134   // ptrtoint's, because we don't know if the target sign or zero extends its
1135   // pointers.
1136   if (TD &&
1137       CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
1138     Value *P = Builder->CreatePtrToInt(CI.getOperand(0),
1139                                        TD->getIntPtrType(CI.getContext()),
1140                                        "tmp");
1141     return new TruncInst(P, CI.getType());
1142   }
1143   
1144   return commonPointerCastTransforms(CI);
1145 }
1146
1147
1148 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
1149   // If the source integer type is larger than the intptr_t type for
1150   // this target, do a trunc to the intptr_t type, then inttoptr of it.  This
1151   // allows the trunc to be exposed to other transforms.  Don't do this for
1152   // extending inttoptr's, because we don't know if the target sign or zero
1153   // extends to pointers.
1154   if (TD && CI.getOperand(0)->getType()->getScalarSizeInBits() >
1155       TD->getPointerSizeInBits()) {
1156     Value *P = Builder->CreateTrunc(CI.getOperand(0),
1157                                     TD->getIntPtrType(CI.getContext()), "tmp");
1158     return new IntToPtrInst(P, CI.getType());
1159   }
1160   
1161   if (Instruction *I = commonCastTransforms(CI))
1162     return I;
1163
1164   return 0;
1165 }
1166
1167 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
1168   // If the operands are integer typed then apply the integer transforms,
1169   // otherwise just apply the common ones.
1170   Value *Src = CI.getOperand(0);
1171   const Type *SrcTy = Src->getType();
1172   const Type *DestTy = CI.getType();
1173
1174   if (isa<PointerType>(SrcTy)) {
1175     if (Instruction *I = commonPointerCastTransforms(CI))
1176       return I;
1177   } else {
1178     if (Instruction *Result = commonCastTransforms(CI))
1179       return Result;
1180   }
1181
1182
1183   // Get rid of casts from one type to the same type. These are useless and can
1184   // be replaced by the operand.
1185   if (DestTy == Src->getType())
1186     return ReplaceInstUsesWith(CI, Src);
1187
1188   if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
1189     const PointerType *SrcPTy = cast<PointerType>(SrcTy);
1190     const Type *DstElTy = DstPTy->getElementType();
1191     const Type *SrcElTy = SrcPTy->getElementType();
1192     
1193     // If the address spaces don't match, don't eliminate the bitcast, which is
1194     // required for changing types.
1195     if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
1196       return 0;
1197     
1198     // If we are casting a alloca to a pointer to a type of the same
1199     // size, rewrite the allocation instruction to allocate the "right" type.
1200     // There is no need to modify malloc calls because it is their bitcast that
1201     // needs to be cleaned up.
1202     if (AllocaInst *AI = dyn_cast<AllocaInst>(Src))
1203       if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
1204         return V;
1205     
1206     // If the source and destination are pointers, and this cast is equivalent
1207     // to a getelementptr X, 0, 0, 0...  turn it into the appropriate gep.
1208     // This can enhance SROA and other transforms that want type-safe pointers.
1209     Constant *ZeroUInt =
1210       Constant::getNullValue(Type::getInt32Ty(CI.getContext()));
1211     unsigned NumZeros = 0;
1212     while (SrcElTy != DstElTy && 
1213            isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
1214            SrcElTy->getNumContainedTypes() /* not "{}" */) {
1215       SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
1216       ++NumZeros;
1217     }
1218
1219     // If we found a path from the src to dest, create the getelementptr now.
1220     if (SrcElTy == DstElTy) {
1221       SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
1222       return GetElementPtrInst::CreateInBounds(Src, Idxs.begin(), Idxs.end(),"",
1223                                                ((Instruction*) NULL));
1224     }
1225   }
1226
1227   if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
1228     if (DestVTy->getNumElements() == 1) {
1229       if (!isa<VectorType>(SrcTy)) {
1230         Value *Elem = Builder->CreateBitCast(Src, DestVTy->getElementType());
1231         return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
1232                      Constant::getNullValue(Type::getInt32Ty(CI.getContext())));
1233       }
1234       // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
1235     }
1236   }
1237
1238   if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
1239     if (SrcVTy->getNumElements() == 1) {
1240       if (!isa<VectorType>(DestTy)) {
1241         Value *Elem = 
1242           Builder->CreateExtractElement(Src,
1243                      Constant::getNullValue(Type::getInt32Ty(CI.getContext())));
1244         return CastInst::Create(Instruction::BitCast, Elem, DestTy);
1245       }
1246     }
1247   }
1248
1249   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
1250     if (SVI->hasOneUse()) {
1251       // Okay, we have (bitconvert (shuffle ..)).  Check to see if this is
1252       // a bitconvert to a vector with the same # elts.
1253       if (isa<VectorType>(DestTy) && 
1254           cast<VectorType>(DestTy)->getNumElements() ==
1255                 SVI->getType()->getNumElements() &&
1256           SVI->getType()->getNumElements() ==
1257             cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
1258         CastInst *Tmp;
1259         // If either of the operands is a cast from CI.getType(), then
1260         // evaluating the shuffle in the casted destination's type will allow
1261         // us to eliminate at least one cast.
1262         if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) && 
1263              Tmp->getOperand(0)->getType() == DestTy) ||
1264             ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) && 
1265              Tmp->getOperand(0)->getType() == DestTy)) {
1266           Value *LHS = Builder->CreateBitCast(SVI->getOperand(0), DestTy);
1267           Value *RHS = Builder->CreateBitCast(SVI->getOperand(1), DestTy);
1268           // Return a new shuffle vector.  Use the same element ID's, as we
1269           // know the vector types match #elts.
1270           return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
1271         }
1272       }
1273     }
1274   }
1275   return 0;
1276 }