08a6ff41ebb23b1c9b82c06de95046ac3da26f4e
[oota-llvm.git] / lib / Transforms / InstCombine / InstCombineCalls.cpp
1 //===- InstCombineCalls.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 visitCall and visitInvoke functions.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "InstCombine.h"
15 #include "llvm/IntrinsicInst.h"
16 #include "llvm/Support/CallSite.h"
17 #include "llvm/Target/TargetData.h"
18 #include "llvm/Analysis/MemoryBuiltins.h"
19 #include "llvm/Transforms/Utils/BuildLibCalls.h"
20 using namespace llvm;
21
22 /// getPromotedType - Return the specified type promoted as it would be to pass
23 /// though a va_arg area.
24 static const Type *getPromotedType(const Type *Ty) {
25   if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
26     if (ITy->getBitWidth() < 32)
27       return Type::getInt32Ty(Ty->getContext());
28   }
29   return Ty;
30 }
31
32 /// EnforceKnownAlignment - If the specified pointer points to an object that
33 /// we control, modify the object's alignment to PrefAlign. This isn't
34 /// often possible though. If alignment is important, a more reliable approach
35 /// is to simply align all global variables and allocation instructions to
36 /// their preferred alignment from the beginning.
37 ///
38 static unsigned EnforceKnownAlignment(Value *V,
39                                       unsigned Align, unsigned PrefAlign) {
40
41   User *U = dyn_cast<User>(V);
42   if (!U) return Align;
43
44   switch (Operator::getOpcode(U)) {
45   default: break;
46   case Instruction::BitCast:
47     return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
48   case Instruction::GetElementPtr: {
49     // If all indexes are zero, it is just the alignment of the base pointer.
50     bool AllZeroOperands = true;
51     for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
52       if (!isa<Constant>(*i) ||
53           !cast<Constant>(*i)->isNullValue()) {
54         AllZeroOperands = false;
55         break;
56       }
57
58     if (AllZeroOperands) {
59       // Treat this like a bitcast.
60       return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
61     }
62     return Align;
63   }
64   case Instruction::Alloca: {
65     AllocaInst *AI = cast<AllocaInst>(V);
66     // If there is a requested alignment and if this is an alloca, round up.
67     if (AI->getAlignment() >= PrefAlign)
68       return AI->getAlignment();
69     AI->setAlignment(PrefAlign);
70     return PrefAlign;
71   }
72   }
73
74   if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
75     // If there is a large requested alignment and we can, bump up the alignment
76     // of the global.
77     if (GV->isDeclaration()) return Align;
78     
79     if (GV->getAlignment() >= PrefAlign)
80       return GV->getAlignment();
81     // We can only increase the alignment of the global if it has no alignment
82     // specified or if it is not assigned a section.  If it is assigned a
83     // section, the global could be densely packed with other objects in the
84     // section, increasing the alignment could cause padding issues.
85     if (!GV->hasSection() || GV->getAlignment() == 0)
86       GV->setAlignment(PrefAlign);
87     return GV->getAlignment();
88   }
89
90   return Align;
91 }
92
93 /// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
94 /// we can determine, return it, otherwise return 0.  If PrefAlign is specified,
95 /// and it is more than the alignment of the ultimate object, see if we can
96 /// increase the alignment of the ultimate object, making this check succeed.
97 unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
98                                                   unsigned PrefAlign) {
99   unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
100                       sizeof(PrefAlign) * CHAR_BIT;
101   APInt Mask = APInt::getAllOnesValue(BitWidth);
102   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
103   ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
104   unsigned TrailZ = KnownZero.countTrailingOnes();
105   unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
106
107   if (PrefAlign > Align)
108     Align = EnforceKnownAlignment(V, Align, PrefAlign);
109   
110     // We don't need to make any adjustment.
111   return Align;
112 }
113
114 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
115   unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
116   unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
117   unsigned MinAlign = std::min(DstAlign, SrcAlign);
118   unsigned CopyAlign = MI->getAlignment();
119
120   if (CopyAlign < MinAlign) {
121     MI->setAlignment(ConstantInt::get(MI->getAlignmentType(), 
122                                              MinAlign, false));
123     return MI;
124   }
125   
126   // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
127   // load/store.
128   ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
129   if (MemOpLength == 0) return 0;
130   
131   // Source and destination pointer types are always "i8*" for intrinsic.  See
132   // if the size is something we can handle with a single primitive load/store.
133   // A single load+store correctly handles overlapping memory in the memmove
134   // case.
135   unsigned Size = MemOpLength->getZExtValue();
136   if (Size == 0) return MI;  // Delete this mem transfer.
137   
138   if (Size > 8 || (Size&(Size-1)))
139     return 0;  // If not 1/2/4/8 bytes, exit.
140   
141   // Use an integer load+store unless we can find something better.
142   unsigned SrcAddrSp =
143     cast<PointerType>(MI->getOperand(2)->getType())->getAddressSpace();
144   unsigned DstAddrSp =
145     cast<PointerType>(MI->getOperand(1)->getType())->getAddressSpace();
146
147   const IntegerType* IntType = IntegerType::get(MI->getContext(), Size<<3);
148   Type *NewSrcPtrTy = PointerType::get(IntType, SrcAddrSp);
149   Type *NewDstPtrTy = PointerType::get(IntType, DstAddrSp);
150   
151   // Memcpy forces the use of i8* for the source and destination.  That means
152   // that if you're using memcpy to move one double around, you'll get a cast
153   // from double* to i8*.  We'd much rather use a double load+store rather than
154   // an i64 load+store, here because this improves the odds that the source or
155   // dest address will be promotable.  See if we can find a better type than the
156   // integer datatype.
157   Value *StrippedDest = MI->getOperand(1)->stripPointerCasts();
158   if (StrippedDest != MI->getOperand(1)) {
159     const Type *SrcETy = cast<PointerType>(StrippedDest->getType())
160                                     ->getElementType();
161     if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
162       // The SrcETy might be something like {{{double}}} or [1 x double].  Rip
163       // down through these levels if so.
164       while (!SrcETy->isSingleValueType()) {
165         if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
166           if (STy->getNumElements() == 1)
167             SrcETy = STy->getElementType(0);
168           else
169             break;
170         } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
171           if (ATy->getNumElements() == 1)
172             SrcETy = ATy->getElementType();
173           else
174             break;
175         } else
176           break;
177       }
178       
179       if (SrcETy->isSingleValueType()) {
180         NewSrcPtrTy = PointerType::get(SrcETy, SrcAddrSp);
181         NewDstPtrTy = PointerType::get(SrcETy, DstAddrSp);
182       }
183     }
184   }
185   
186   
187   // If the memcpy/memmove provides better alignment info than we can
188   // infer, use it.
189   SrcAlign = std::max(SrcAlign, CopyAlign);
190   DstAlign = std::max(DstAlign, CopyAlign);
191   
192   Value *Src = Builder->CreateBitCast(MI->getOperand(2), NewSrcPtrTy);
193   Value *Dest = Builder->CreateBitCast(MI->getOperand(1), NewDstPtrTy);
194   Instruction *L = new LoadInst(Src, "tmp", MI->isVolatile(), SrcAlign);
195   InsertNewInstBefore(L, *MI);
196   InsertNewInstBefore(new StoreInst(L, Dest, MI->isVolatile(), DstAlign),
197                       *MI);
198
199   // Set the size of the copy to 0, it will be deleted on the next iteration.
200   MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
201   return MI;
202 }
203
204 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
205   unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
206   if (MI->getAlignment() < Alignment) {
207     MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
208                                              Alignment, false));
209     return MI;
210   }
211   
212   // Extract the length and alignment and fill if they are constant.
213   ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
214   ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
215   if (!LenC || !FillC || !FillC->getType()->isIntegerTy(8))
216     return 0;
217   uint64_t Len = LenC->getZExtValue();
218   Alignment = MI->getAlignment();
219   
220   // If the length is zero, this is a no-op
221   if (Len == 0) return MI; // memset(d,c,0,a) -> noop
222   
223   // memset(s,c,n) -> store s, c (for n=1,2,4,8)
224   if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
225     const Type *ITy = IntegerType::get(MI->getContext(), Len*8);  // n=1 -> i8.
226     
227     Value *Dest = MI->getDest();
228     Dest = Builder->CreateBitCast(Dest, PointerType::getUnqual(ITy));
229
230     // Alignment 0 is identity for alignment 1 for memset, but not store.
231     if (Alignment == 0) Alignment = 1;
232     
233     // Extract the fill value and store.
234     uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
235     InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill),
236                                       Dest, false, Alignment), *MI);
237     
238     // Set the size of the copy to 0, it will be deleted on the next iteration.
239     MI->setLength(Constant::getNullValue(LenC->getType()));
240     return MI;
241   }
242
243   return 0;
244 }
245
246 /// visitCallInst - CallInst simplification.  This mostly only handles folding 
247 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
248 /// the heavy lifting.
249 ///
250 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
251   if (isFreeCall(&CI))
252     return visitFree(CI);
253   if (isMalloc(&CI))
254     return visitMalloc(CI);
255
256   // If the caller function is nounwind, mark the call as nounwind, even if the
257   // callee isn't.
258   if (CI.getParent()->getParent()->doesNotThrow() &&
259       !CI.doesNotThrow()) {
260     CI.setDoesNotThrow();
261     return &CI;
262   }
263   
264   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
265   if (!II) return visitCallSite(&CI);
266   
267   // Intrinsics cannot occur in an invoke, so handle them here instead of in
268   // visitCallSite.
269   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
270     bool Changed = false;
271
272     // memmove/cpy/set of zero bytes is a noop.
273     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
274       if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
275
276       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
277         if (CI->getZExtValue() == 1) {
278           // Replace the instruction with just byte operations.  We would
279           // transform other cases to loads/stores, but we don't know if
280           // alignment is sufficient.
281         }
282     }
283
284     // If we have a memmove and the source operation is a constant global,
285     // then the source and dest pointers can't alias, so we can change this
286     // into a call to memcpy.
287     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
288       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
289         if (GVSrc->isConstant()) {
290           Module *M = CI.getParent()->getParent()->getParent();
291           Intrinsic::ID MemCpyID = Intrinsic::memcpy;
292           const Type *Tys[3] = { CI.getOperand(1)->getType(),
293                                  CI.getOperand(2)->getType(),
294                                  CI.getOperand(3)->getType() };
295           CI.setCalledFunction( 
296                         Intrinsic::getDeclaration(M, MemCpyID, Tys, 3));
297           Changed = true;
298         }
299     }
300
301     if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) {
302       // memmove(x,x,size) -> noop.
303       if (MTI->getSource() == MTI->getDest())
304         return EraseInstFromFunction(CI);
305     }
306
307     // If we can determine a pointer alignment that is bigger than currently
308     // set, update the alignment.
309     if (isa<MemTransferInst>(MI)) {
310       if (Instruction *I = SimplifyMemTransfer(MI))
311         return I;
312     } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
313       if (Instruction *I = SimplifyMemSet(MSI))
314         return I;
315     }
316           
317     if (Changed) return II;
318   }
319   
320   switch (II->getIntrinsicID()) {
321   default: break;
322   case Intrinsic::objectsize: {
323     // We need target data for just about everything so depend on it.
324     if (!TD) break;
325     
326     const Type *ReturnTy = CI.getType();
327     bool Min = (cast<ConstantInt>(II->getOperand(2))->getZExtValue() == 1);
328
329     // Get to the real allocated thing and offset as fast as possible.
330     Value *Op1 = II->getOperand(1)->stripPointerCasts();
331     
332     // If we've stripped down to a single global variable that we
333     // can know the size of then just return that.
334     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op1)) {
335       if (GV->hasDefinitiveInitializer()) {
336         Constant *C = GV->getInitializer();
337         uint64_t GlobalSize = TD->getTypeAllocSize(C->getType());
338         return ReplaceInstUsesWith(CI, ConstantInt::get(ReturnTy, GlobalSize));
339       } else {
340         // Can't determine size of the GV.
341         Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);
342         return ReplaceInstUsesWith(CI, RetVal);
343       }
344     } else if (AllocaInst *AI = dyn_cast<AllocaInst>(Op1)) {
345       // Get alloca size.
346       if (AI->getAllocatedType()->isSized()) {
347         uint64_t AllocaSize = TD->getTypeAllocSize(AI->getAllocatedType());
348         if (AI->isArrayAllocation()) {
349           const ConstantInt *C = dyn_cast<ConstantInt>(AI->getArraySize());
350           if (!C) break;
351           AllocaSize *= C->getZExtValue();
352         }
353         return ReplaceInstUsesWith(CI, ConstantInt::get(ReturnTy, AllocaSize));
354       }
355     } else if (CallInst *MI = extractMallocCall(Op1)) {
356       const Type* MallocType = getMallocAllocatedType(MI);
357       // Get alloca size.
358       if (MallocType && MallocType->isSized()) {
359         if (Value *NElems = getMallocArraySize(MI, TD, true)) {
360           if (ConstantInt *NElements = dyn_cast<ConstantInt>(NElems))
361         return ReplaceInstUsesWith(CI, ConstantInt::get(ReturnTy,
362                (NElements->getZExtValue() * TD->getTypeAllocSize(MallocType))));
363         }
364       }
365     } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op1)) {      
366       // Only handle constant GEPs here.
367       if (CE->getOpcode() != Instruction::GetElementPtr) break;
368       GEPOperator *GEP = cast<GEPOperator>(CE);
369       
370       // Make sure we're not a constant offset from an external
371       // global.
372       Value *Operand = GEP->getPointerOperand();
373       Operand = Operand->stripPointerCasts();
374       if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Operand))
375         if (!GV->hasDefinitiveInitializer()) break;
376         
377       // Get what we're pointing to and its size. 
378       const PointerType *BaseType = 
379         cast<PointerType>(Operand->getType());
380       uint64_t Size = TD->getTypeAllocSize(BaseType->getElementType());
381       
382       // Get the current byte offset into the thing. Use the original
383       // operand in case we're looking through a bitcast.
384       SmallVector<Value*, 8> Ops(CE->op_begin()+1, CE->op_end());
385       const PointerType *OffsetType =
386         cast<PointerType>(GEP->getPointerOperand()->getType());
387       uint64_t Offset = TD->getIndexedOffset(OffsetType, &Ops[0], Ops.size());
388
389       if (Size < Offset) {
390         // Out of bound reference? Negative index normalized to large
391         // index? Just return "I don't know".
392         Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);
393         return ReplaceInstUsesWith(CI, RetVal);
394       }
395       
396       Constant *RetVal = ConstantInt::get(ReturnTy, Size-Offset);
397       return ReplaceInstUsesWith(CI, RetVal);
398       
399     } 
400
401     // Do not return "I don't know" here. Later optimization passes could
402     // make it possible to evaluate objectsize to a constant.
403     break;
404   }
405   case Intrinsic::bswap:
406     // bswap(bswap(x)) -> x
407     if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
408       if (Operand->getIntrinsicID() == Intrinsic::bswap)
409         return ReplaceInstUsesWith(CI, Operand->getOperand(1));
410       
411     // bswap(trunc(bswap(x))) -> trunc(lshr(x, c))
412     if (TruncInst *TI = dyn_cast<TruncInst>(II->getOperand(1))) {
413       if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(TI->getOperand(0)))
414         if (Operand->getIntrinsicID() == Intrinsic::bswap) {
415           unsigned C = Operand->getType()->getPrimitiveSizeInBits() -
416                        TI->getType()->getPrimitiveSizeInBits();
417           Value *CV = ConstantInt::get(Operand->getType(), C);
418           Value *V = Builder->CreateLShr(Operand->getOperand(1), CV);
419           return new TruncInst(V, TI->getType());
420         }
421     }
422       
423     break;
424   case Intrinsic::powi:
425     if (ConstantInt *Power = dyn_cast<ConstantInt>(II->getOperand(2))) {
426       // powi(x, 0) -> 1.0
427       if (Power->isZero())
428         return ReplaceInstUsesWith(CI, ConstantFP::get(CI.getType(), 1.0));
429       // powi(x, 1) -> x
430       if (Power->isOne())
431         return ReplaceInstUsesWith(CI, II->getOperand(1));
432       // powi(x, -1) -> 1/x
433       if (Power->isAllOnesValue())
434         return BinaryOperator::CreateFDiv(ConstantFP::get(CI.getType(), 1.0),
435                                           II->getOperand(1));
436     }
437     break;
438   case Intrinsic::cttz: {
439     // If all bits below the first known one are known zero,
440     // this value is constant.
441     const IntegerType *IT = cast<IntegerType>(II->getOperand(1)->getType());
442     uint32_t BitWidth = IT->getBitWidth();
443     APInt KnownZero(BitWidth, 0);
444     APInt KnownOne(BitWidth, 0);
445     ComputeMaskedBits(II->getOperand(1), APInt::getAllOnesValue(BitWidth),
446                       KnownZero, KnownOne);
447     unsigned TrailingZeros = KnownOne.countTrailingZeros();
448     APInt Mask(APInt::getLowBitsSet(BitWidth, TrailingZeros));
449     if ((Mask & KnownZero) == Mask)
450       return ReplaceInstUsesWith(CI, ConstantInt::get(IT,
451                                  APInt(BitWidth, TrailingZeros)));
452     
453     }
454     break;
455   case Intrinsic::ctlz: {
456     // If all bits above the first known one are known zero,
457     // this value is constant.
458     const IntegerType *IT = cast<IntegerType>(II->getOperand(1)->getType());
459     uint32_t BitWidth = IT->getBitWidth();
460     APInt KnownZero(BitWidth, 0);
461     APInt KnownOne(BitWidth, 0);
462     ComputeMaskedBits(II->getOperand(1), APInt::getAllOnesValue(BitWidth),
463                       KnownZero, KnownOne);
464     unsigned LeadingZeros = KnownOne.countLeadingZeros();
465     APInt Mask(APInt::getHighBitsSet(BitWidth, LeadingZeros));
466     if ((Mask & KnownZero) == Mask)
467       return ReplaceInstUsesWith(CI, ConstantInt::get(IT,
468                                  APInt(BitWidth, LeadingZeros)));
469     
470     }
471     break;
472   case Intrinsic::uadd_with_overflow: {
473     Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
474     const IntegerType *IT = cast<IntegerType>(II->getOperand(1)->getType());
475     uint32_t BitWidth = IT->getBitWidth();
476     APInt Mask = APInt::getSignBit(BitWidth);
477     APInt LHSKnownZero(BitWidth, 0);
478     APInt LHSKnownOne(BitWidth, 0);
479     ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
480     bool LHSKnownNegative = LHSKnownOne[BitWidth - 1];
481     bool LHSKnownPositive = LHSKnownZero[BitWidth - 1];
482
483     if (LHSKnownNegative || LHSKnownPositive) {
484       APInt RHSKnownZero(BitWidth, 0);
485       APInt RHSKnownOne(BitWidth, 0);
486       ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
487       bool RHSKnownNegative = RHSKnownOne[BitWidth - 1];
488       bool RHSKnownPositive = RHSKnownZero[BitWidth - 1];
489       if (LHSKnownNegative && RHSKnownNegative) {
490         // The sign bit is set in both cases: this MUST overflow.
491         // Create a simple add instruction, and insert it into the struct.
492         Instruction *Add = BinaryOperator::CreateAdd(LHS, RHS, "", &CI);
493         Worklist.Add(Add);
494         Constant *V[] = {
495           UndefValue::get(LHS->getType()),ConstantInt::getTrue(II->getContext())
496         };
497         Constant *Struct = ConstantStruct::get(II->getContext(), V, 2, false);
498         return InsertValueInst::Create(Struct, Add, 0);
499       }
500       
501       if (LHSKnownPositive && RHSKnownPositive) {
502         // The sign bit is clear in both cases: this CANNOT overflow.
503         // Create a simple add instruction, and insert it into the struct.
504         Instruction *Add = BinaryOperator::CreateNUWAdd(LHS, RHS, "", &CI);
505         Worklist.Add(Add);
506         Constant *V[] = {
507           UndefValue::get(LHS->getType()),
508           ConstantInt::getFalse(II->getContext())
509         };
510         Constant *Struct = ConstantStruct::get(II->getContext(), V, 2, false);
511         return InsertValueInst::Create(Struct, Add, 0);
512       }
513     }
514   }
515   // FALL THROUGH uadd into sadd
516   case Intrinsic::sadd_with_overflow:
517     // Canonicalize constants into the RHS.
518     if (isa<Constant>(II->getOperand(1)) &&
519         !isa<Constant>(II->getOperand(2))) {
520       Value *LHS = II->getOperand(1);
521       II->setOperand(1, II->getOperand(2));
522       II->setOperand(2, LHS);
523       return II;
524     }
525
526     // X + undef -> undef
527     if (isa<UndefValue>(II->getOperand(2)))
528       return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
529       
530     if (ConstantInt *RHS = dyn_cast<ConstantInt>(II->getOperand(2))) {
531       // X + 0 -> {X, false}
532       if (RHS->isZero()) {
533         Constant *V[] = {
534           UndefValue::get(II->getCalledValue()->getType()),
535           ConstantInt::getFalse(II->getContext())
536         };
537         Constant *Struct = ConstantStruct::get(II->getContext(), V, 2, false);
538         return InsertValueInst::Create(Struct, II->getOperand(1), 0);
539       }
540     }
541     break;
542   case Intrinsic::usub_with_overflow:
543   case Intrinsic::ssub_with_overflow:
544     // undef - X -> undef
545     // X - undef -> undef
546     if (isa<UndefValue>(II->getOperand(1)) ||
547         isa<UndefValue>(II->getOperand(2)))
548       return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
549       
550     if (ConstantInt *RHS = dyn_cast<ConstantInt>(II->getOperand(2))) {
551       // X - 0 -> {X, false}
552       if (RHS->isZero()) {
553         Constant *V[] = {
554           UndefValue::get(II->getOperand(1)->getType()),
555           ConstantInt::getFalse(II->getContext())
556         };
557         Constant *Struct = ConstantStruct::get(II->getContext(), V, 2, false);
558         return InsertValueInst::Create(Struct, II->getOperand(1), 0);
559       }
560     }
561     break;
562   case Intrinsic::umul_with_overflow:
563   case Intrinsic::smul_with_overflow:
564     // Canonicalize constants into the RHS.
565     if (isa<Constant>(II->getOperand(1)) &&
566         !isa<Constant>(II->getOperand(2))) {
567       Value *LHS = II->getOperand(1);
568       II->setOperand(1, II->getOperand(2));
569       II->setOperand(2, LHS);
570       return II;
571     }
572
573     // X * undef -> undef
574     if (isa<UndefValue>(II->getOperand(2)))
575       return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
576       
577     if (ConstantInt *RHSI = dyn_cast<ConstantInt>(II->getOperand(2))) {
578       // X*0 -> {0, false}
579       if (RHSI->isZero())
580         return ReplaceInstUsesWith(CI, Constant::getNullValue(II->getType()));
581       
582       // X * 1 -> {X, false}
583       if (RHSI->equalsInt(1)) {
584         Constant *V[] = {
585           UndefValue::get(II->getOperand(1)->getType()),
586           ConstantInt::getFalse(II->getContext())
587         };
588         Constant *Struct = ConstantStruct::get(II->getContext(), V, 2, false);
589         return InsertValueInst::Create(Struct, II->getOperand(1), 0);
590       }
591     }
592     break;
593   case Intrinsic::ppc_altivec_lvx:
594   case Intrinsic::ppc_altivec_lvxl:
595   case Intrinsic::x86_sse_loadu_ps:
596   case Intrinsic::x86_sse2_loadu_pd:
597   case Intrinsic::x86_sse2_loadu_dq:
598     // Turn PPC lvx     -> load if the pointer is known aligned.
599     // Turn X86 loadups -> load if the pointer is known aligned.
600     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
601       Value *Ptr = Builder->CreateBitCast(II->getOperand(1),
602                                          PointerType::getUnqual(II->getType()));
603       return new LoadInst(Ptr);
604     }
605     break;
606   case Intrinsic::ppc_altivec_stvx:
607   case Intrinsic::ppc_altivec_stvxl:
608     // Turn stvx -> store if the pointer is known aligned.
609     if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
610       const Type *OpPtrTy = 
611         PointerType::getUnqual(II->getOperand(1)->getType());
612       Value *Ptr = Builder->CreateBitCast(II->getOperand(2), OpPtrTy);
613       return new StoreInst(II->getOperand(1), Ptr);
614     }
615     break;
616   case Intrinsic::x86_sse_storeu_ps:
617   case Intrinsic::x86_sse2_storeu_pd:
618   case Intrinsic::x86_sse2_storeu_dq:
619     // Turn X86 storeu -> store if the pointer is known aligned.
620     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
621       const Type *OpPtrTy = 
622         PointerType::getUnqual(II->getOperand(2)->getType());
623       Value *Ptr = Builder->CreateBitCast(II->getOperand(1), OpPtrTy);
624       return new StoreInst(II->getOperand(2), Ptr);
625     }
626     break;
627     
628   case Intrinsic::x86_sse_cvttss2si: {
629     // These intrinsics only demands the 0th element of its input vector.  If
630     // we can simplify the input based on that, do so now.
631     unsigned VWidth =
632       cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
633     APInt DemandedElts(VWidth, 1);
634     APInt UndefElts(VWidth, 0);
635     if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
636                                               UndefElts)) {
637       II->setOperand(1, V);
638       return II;
639     }
640     break;
641   }
642     
643   case Intrinsic::ppc_altivec_vperm:
644     // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
645     if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
646       assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
647       
648       // Check that all of the elements are integer constants or undefs.
649       bool AllEltsOk = true;
650       for (unsigned i = 0; i != 16; ++i) {
651         if (!isa<ConstantInt>(Mask->getOperand(i)) && 
652             !isa<UndefValue>(Mask->getOperand(i))) {
653           AllEltsOk = false;
654           break;
655         }
656       }
657       
658       if (AllEltsOk) {
659         // Cast the input vectors to byte vectors.
660         Value *Op0 = Builder->CreateBitCast(II->getOperand(1), Mask->getType());
661         Value *Op1 = Builder->CreateBitCast(II->getOperand(2), Mask->getType());
662         Value *Result = UndefValue::get(Op0->getType());
663         
664         // Only extract each element once.
665         Value *ExtractedElts[32];
666         memset(ExtractedElts, 0, sizeof(ExtractedElts));
667         
668         for (unsigned i = 0; i != 16; ++i) {
669           if (isa<UndefValue>(Mask->getOperand(i)))
670             continue;
671           unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
672           Idx &= 31;  // Match the hardware behavior.
673           
674           if (ExtractedElts[Idx] == 0) {
675             ExtractedElts[Idx] = 
676               Builder->CreateExtractElement(Idx < 16 ? Op0 : Op1, 
677                   ConstantInt::get(Type::getInt32Ty(II->getContext()),
678                                    Idx&15, false), "tmp");
679           }
680         
681           // Insert this value into the result vector.
682           Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
683                          ConstantInt::get(Type::getInt32Ty(II->getContext()),
684                                           i, false), "tmp");
685         }
686         return CastInst::Create(Instruction::BitCast, Result, CI.getType());
687       }
688     }
689     break;
690
691   case Intrinsic::stackrestore: {
692     // If the save is right next to the restore, remove the restore.  This can
693     // happen when variable allocas are DCE'd.
694     if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
695       if (SS->getIntrinsicID() == Intrinsic::stacksave) {
696         BasicBlock::iterator BI = SS;
697         if (&*++BI == II)
698           return EraseInstFromFunction(CI);
699       }
700     }
701     
702     // Scan down this block to see if there is another stack restore in the
703     // same block without an intervening call/alloca.
704     BasicBlock::iterator BI = II;
705     TerminatorInst *TI = II->getParent()->getTerminator();
706     bool CannotRemove = false;
707     for (++BI; &*BI != TI; ++BI) {
708       if (isa<AllocaInst>(BI) || isMalloc(BI)) {
709         CannotRemove = true;
710         break;
711       }
712       if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
713         if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
714           // If there is a stackrestore below this one, remove this one.
715           if (II->getIntrinsicID() == Intrinsic::stackrestore)
716             return EraseInstFromFunction(CI);
717           // Otherwise, ignore the intrinsic.
718         } else {
719           // If we found a non-intrinsic call, we can't remove the stack
720           // restore.
721           CannotRemove = true;
722           break;
723         }
724       }
725     }
726     
727     // If the stack restore is in a return/unwind block and if there are no
728     // allocas or calls between the restore and the return, nuke the restore.
729     if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
730       return EraseInstFromFunction(CI);
731     break;
732   }
733   }
734
735   return visitCallSite(II);
736 }
737
738 // InvokeInst simplification
739 //
740 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
741   return visitCallSite(&II);
742 }
743
744 /// isSafeToEliminateVarargsCast - If this cast does not affect the value 
745 /// passed through the varargs area, we can eliminate the use of the cast.
746 static bool isSafeToEliminateVarargsCast(const CallSite CS,
747                                          const CastInst * const CI,
748                                          const TargetData * const TD,
749                                          const int ix) {
750   if (!CI->isLosslessCast())
751     return false;
752
753   // The size of ByVal arguments is derived from the type, so we
754   // can't change to a type with a different size.  If the size were
755   // passed explicitly we could avoid this check.
756   if (!CS.paramHasAttr(ix, Attribute::ByVal))
757     return true;
758
759   const Type* SrcTy = 
760             cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
761   const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
762   if (!SrcTy->isSized() || !DstTy->isSized())
763     return false;
764   if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
765     return false;
766   return true;
767 }
768
769 namespace {
770 class InstCombineFortifiedLibCalls : public SimplifyFortifiedLibCalls {
771   InstCombiner *IC;
772 protected:
773   void replaceCall(Value *With) {
774     NewInstruction = IC->ReplaceInstUsesWith(*CI, With);
775   }
776   bool isFoldable(unsigned SizeCIOp, unsigned SizeArgOp, bool isString) const {
777     if (ConstantInt *SizeCI = dyn_cast<ConstantInt>(CI->getOperand(SizeCIOp))) {
778       if (SizeCI->isAllOnesValue())
779         return true;
780       if (isString)
781         return SizeCI->getZExtValue() >=
782                GetStringLength(CI->getOperand(SizeArgOp));
783       if (ConstantInt *Arg = dyn_cast<ConstantInt>(CI->getOperand(SizeArgOp)))
784         return SizeCI->getZExtValue() >= Arg->getZExtValue();
785     }
786     return false;
787   }
788 public:
789   InstCombineFortifiedLibCalls(InstCombiner *IC) : IC(IC), NewInstruction(0) { }
790   Instruction *NewInstruction;
791 };
792 } // end anonymous namespace
793
794 // Try to fold some different type of calls here.
795 // Currently we're only working with the checking functions, memcpy_chk, 
796 // mempcpy_chk, memmove_chk, memset_chk, strcpy_chk, stpcpy_chk, strncpy_chk,
797 // strcat_chk and strncat_chk.
798 Instruction *InstCombiner::tryOptimizeCall(CallInst *CI, const TargetData *TD) {
799   if (CI->getCalledFunction() == 0) return 0;
800
801   InstCombineFortifiedLibCalls Simplifier(this);
802   Simplifier.fold(CI, TD);
803   return Simplifier.NewInstruction;
804 }
805
806 // visitCallSite - Improvements for call and invoke instructions.
807 //
808 Instruction *InstCombiner::visitCallSite(CallSite CS) {
809   bool Changed = false;
810
811   // If the callee is a constexpr cast of a function, attempt to move the cast
812   // to the arguments of the call/invoke.
813   if (transformConstExprCastCall(CS)) return 0;
814
815   Value *Callee = CS.getCalledValue();
816
817   if (Function *CalleeF = dyn_cast<Function>(Callee))
818     // If the call and callee calling conventions don't match, this call must
819     // be unreachable, as the call is undefined.
820     if (CalleeF->getCallingConv() != CS.getCallingConv() &&
821         // Only do this for calls to a function with a body.  A prototype may
822         // not actually end up matching the implementation's calling conv for a
823         // variety of reasons (e.g. it may be written in assembly).
824         !CalleeF->isDeclaration()) {
825       Instruction *OldCall = CS.getInstruction();
826       new StoreInst(ConstantInt::getTrue(Callee->getContext()),
827                 UndefValue::get(Type::getInt1PtrTy(Callee->getContext())), 
828                                   OldCall);
829       // If OldCall dues not return void then replaceAllUsesWith undef.
830       // This allows ValueHandlers and custom metadata to adjust itself.
831       if (!OldCall->getType()->isVoidTy())
832         OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
833       if (isa<CallInst>(OldCall))
834         return EraseInstFromFunction(*OldCall);
835       
836       // We cannot remove an invoke, because it would change the CFG, just
837       // change the callee to a null pointer.
838       cast<InvokeInst>(OldCall)->setCalledFunction(
839                                     Constant::getNullValue(CalleeF->getType()));
840       return 0;
841     }
842
843   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
844     // This instruction is not reachable, just remove it.  We insert a store to
845     // undef so that we know that this code is not reachable, despite the fact
846     // that we can't modify the CFG here.
847     new StoreInst(ConstantInt::getTrue(Callee->getContext()),
848                UndefValue::get(Type::getInt1PtrTy(Callee->getContext())),
849                   CS.getInstruction());
850
851     // If CS dues not return void then replaceAllUsesWith undef.
852     // This allows ValueHandlers and custom metadata to adjust itself.
853     if (!CS.getInstruction()->getType()->isVoidTy())
854       CS.getInstruction()->
855         replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
856
857     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
858       // Don't break the CFG, insert a dummy cond branch.
859       BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
860                          ConstantInt::getTrue(Callee->getContext()), II);
861     }
862     return EraseInstFromFunction(*CS.getInstruction());
863   }
864
865   if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
866     if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
867       if (In->getIntrinsicID() == Intrinsic::init_trampoline)
868         return transformCallThroughTrampoline(CS);
869
870   const PointerType *PTy = cast<PointerType>(Callee->getType());
871   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
872   if (FTy->isVarArg()) {
873     int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
874     // See if we can optimize any arguments passed through the varargs area of
875     // the call.
876     for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
877            E = CS.arg_end(); I != E; ++I, ++ix) {
878       CastInst *CI = dyn_cast<CastInst>(*I);
879       if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
880         *I = CI->getOperand(0);
881         Changed = true;
882       }
883     }
884   }
885
886   if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
887     // Inline asm calls cannot throw - mark them 'nounwind'.
888     CS.setDoesNotThrow();
889     Changed = true;
890   }
891
892   // Try to optimize the call if possible, we require TargetData for most of
893   // this.  None of these calls are seen as possibly dead so go ahead and
894   // delete the instruction now.
895   if (CallInst *CI = dyn_cast<CallInst>(CS.getInstruction())) {
896     Instruction *I = tryOptimizeCall(CI, TD);
897     // If we changed something return the result, etc. Otherwise let
898     // the fallthrough check.
899     if (I) return EraseInstFromFunction(*I);
900   }
901
902   return Changed ? CS.getInstruction() : 0;
903 }
904
905 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
906 // attempt to move the cast to the arguments of the call/invoke.
907 //
908 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
909   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
910   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
911   if (CE->getOpcode() != Instruction::BitCast || 
912       !isa<Function>(CE->getOperand(0)))
913     return false;
914   Function *Callee = cast<Function>(CE->getOperand(0));
915   Instruction *Caller = CS.getInstruction();
916   const AttrListPtr &CallerPAL = CS.getAttributes();
917
918   // Okay, this is a cast from a function to a different type.  Unless doing so
919   // would cause a type conversion of one of our arguments, change this call to
920   // be a direct call with arguments casted to the appropriate types.
921   //
922   const FunctionType *FT = Callee->getFunctionType();
923   const Type *OldRetTy = Caller->getType();
924   const Type *NewRetTy = FT->getReturnType();
925
926   if (NewRetTy->isStructTy())
927     return false; // TODO: Handle multiple return values.
928
929   // Check to see if we are changing the return type...
930   if (OldRetTy != NewRetTy) {
931     if (Callee->isDeclaration() &&
932         // Conversion is ok if changing from one pointer type to another or from
933         // a pointer to an integer of the same size.
934         !((OldRetTy->isPointerTy() || !TD ||
935            OldRetTy == TD->getIntPtrType(Caller->getContext())) &&
936           (NewRetTy->isPointerTy() || !TD ||
937            NewRetTy == TD->getIntPtrType(Caller->getContext()))))
938       return false;   // Cannot transform this return value.
939
940     if (!Caller->use_empty() &&
941         // void -> non-void is handled specially
942         !NewRetTy->isVoidTy() && !CastInst::isCastable(NewRetTy, OldRetTy))
943       return false;   // Cannot transform this return value.
944
945     if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
946       Attributes RAttrs = CallerPAL.getRetAttributes();
947       if (RAttrs & Attribute::typeIncompatible(NewRetTy))
948         return false;   // Attribute not compatible with transformed value.
949     }
950
951     // If the callsite is an invoke instruction, and the return value is used by
952     // a PHI node in a successor, we cannot change the return type of the call
953     // because there is no place to put the cast instruction (without breaking
954     // the critical edge).  Bail out in this case.
955     if (!Caller->use_empty())
956       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
957         for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
958              UI != E; ++UI)
959           if (PHINode *PN = dyn_cast<PHINode>(*UI))
960             if (PN->getParent() == II->getNormalDest() ||
961                 PN->getParent() == II->getUnwindDest())
962               return false;
963   }
964
965   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
966   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
967
968   CallSite::arg_iterator AI = CS.arg_begin();
969   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
970     const Type *ParamTy = FT->getParamType(i);
971     const Type *ActTy = (*AI)->getType();
972
973     if (!CastInst::isCastable(ActTy, ParamTy))
974       return false;   // Cannot transform this parameter value.
975
976     if (CallerPAL.getParamAttributes(i + 1) 
977         & Attribute::typeIncompatible(ParamTy))
978       return false;   // Attribute not compatible with transformed value.
979
980     // Converting from one pointer type to another or between a pointer and an
981     // integer of the same size is safe even if we do not have a body.
982     bool isConvertible = ActTy == ParamTy ||
983       (TD && ((ParamTy->isPointerTy() ||
984       ParamTy == TD->getIntPtrType(Caller->getContext())) &&
985               (ActTy->isPointerTy() ||
986               ActTy == TD->getIntPtrType(Caller->getContext()))));
987     if (Callee->isDeclaration() && !isConvertible) return false;
988   }
989
990   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
991       Callee->isDeclaration())
992     return false;   // Do not delete arguments unless we have a function body.
993
994   if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
995       !CallerPAL.isEmpty())
996     // In this case we have more arguments than the new function type, but we
997     // won't be dropping them.  Check that these extra arguments have attributes
998     // that are compatible with being a vararg call argument.
999     for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
1000       if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
1001         break;
1002       Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
1003       if (PAttrs & Attribute::VarArgsIncompatible)
1004         return false;
1005     }
1006
1007   // Okay, we decided that this is a safe thing to do: go ahead and start
1008   // inserting cast instructions as necessary...
1009   std::vector<Value*> Args;
1010   Args.reserve(NumActualArgs);
1011   SmallVector<AttributeWithIndex, 8> attrVec;
1012   attrVec.reserve(NumCommonArgs);
1013
1014   // Get any return attributes.
1015   Attributes RAttrs = CallerPAL.getRetAttributes();
1016
1017   // If the return value is not being used, the type may not be compatible
1018   // with the existing attributes.  Wipe out any problematic attributes.
1019   RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
1020
1021   // Add the new return attributes.
1022   if (RAttrs)
1023     attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
1024
1025   AI = CS.arg_begin();
1026   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
1027     const Type *ParamTy = FT->getParamType(i);
1028     if ((*AI)->getType() == ParamTy) {
1029       Args.push_back(*AI);
1030     } else {
1031       Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
1032           false, ParamTy, false);
1033       Args.push_back(Builder->CreateCast(opcode, *AI, ParamTy, "tmp"));
1034     }
1035
1036     // Add any parameter attributes.
1037     if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
1038       attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
1039   }
1040
1041   // If the function takes more arguments than the call was taking, add them
1042   // now.
1043   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
1044     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
1045
1046   // If we are removing arguments to the function, emit an obnoxious warning.
1047   if (FT->getNumParams() < NumActualArgs) {
1048     if (!FT->isVarArg()) {
1049       errs() << "WARNING: While resolving call to function '"
1050              << Callee->getName() << "' arguments were dropped!\n";
1051     } else {
1052       // Add all of the arguments in their promoted form to the arg list.
1053       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
1054         const Type *PTy = getPromotedType((*AI)->getType());
1055         if (PTy != (*AI)->getType()) {
1056           // Must promote to pass through va_arg area!
1057           Instruction::CastOps opcode =
1058             CastInst::getCastOpcode(*AI, false, PTy, false);
1059           Args.push_back(Builder->CreateCast(opcode, *AI, PTy, "tmp"));
1060         } else {
1061           Args.push_back(*AI);
1062         }
1063
1064         // Add any parameter attributes.
1065         if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
1066           attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
1067       }
1068     }
1069   }
1070
1071   if (Attributes FnAttrs =  CallerPAL.getFnAttributes())
1072     attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
1073
1074   if (NewRetTy->isVoidTy())
1075     Caller->setName("");   // Void type should not have a name.
1076
1077   const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),
1078                                                      attrVec.end());
1079
1080   Instruction *NC;
1081   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
1082     NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
1083                             Args.begin(), Args.end(),
1084                             Caller->getName(), Caller);
1085     cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
1086     cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
1087   } else {
1088     NC = CallInst::Create(Callee, Args.begin(), Args.end(),
1089                           Caller->getName(), Caller);
1090     CallInst *CI = cast<CallInst>(Caller);
1091     if (CI->isTailCall())
1092       cast<CallInst>(NC)->setTailCall();
1093     cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
1094     cast<CallInst>(NC)->setAttributes(NewCallerPAL);
1095   }
1096
1097   // Insert a cast of the return type as necessary.
1098   Value *NV = NC;
1099   if (OldRetTy != NV->getType() && !Caller->use_empty()) {
1100     if (!NV->getType()->isVoidTy()) {
1101       Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false, 
1102                                                             OldRetTy, false);
1103       NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
1104
1105       // If this is an invoke instruction, we should insert it after the first
1106       // non-phi, instruction in the normal successor block.
1107       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
1108         BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
1109         InsertNewInstBefore(NC, *I);
1110       } else {
1111         // Otherwise, it's a call, just insert cast right after the call instr
1112         InsertNewInstBefore(NC, *Caller);
1113       }
1114       Worklist.AddUsersToWorkList(*Caller);
1115     } else {
1116       NV = UndefValue::get(Caller->getType());
1117     }
1118   }
1119
1120
1121   if (!Caller->use_empty())
1122     Caller->replaceAllUsesWith(NV);
1123   
1124   EraseInstFromFunction(*Caller);
1125   return true;
1126 }
1127
1128 // transformCallThroughTrampoline - Turn a call to a function created by the
1129 // init_trampoline intrinsic into a direct call to the underlying function.
1130 //
1131 Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
1132   Value *Callee = CS.getCalledValue();
1133   const PointerType *PTy = cast<PointerType>(Callee->getType());
1134   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1135   const AttrListPtr &Attrs = CS.getAttributes();
1136
1137   // If the call already has the 'nest' attribute somewhere then give up -
1138   // otherwise 'nest' would occur twice after splicing in the chain.
1139   if (Attrs.hasAttrSomewhere(Attribute::Nest))
1140     return 0;
1141
1142   IntrinsicInst *Tramp =
1143     cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
1144
1145   Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
1146   const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
1147   const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
1148
1149   const AttrListPtr &NestAttrs = NestF->getAttributes();
1150   if (!NestAttrs.isEmpty()) {
1151     unsigned NestIdx = 1;
1152     const Type *NestTy = 0;
1153     Attributes NestAttr = Attribute::None;
1154
1155     // Look for a parameter marked with the 'nest' attribute.
1156     for (FunctionType::param_iterator I = NestFTy->param_begin(),
1157          E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
1158       if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
1159         // Record the parameter type and any other attributes.
1160         NestTy = *I;
1161         NestAttr = NestAttrs.getParamAttributes(NestIdx);
1162         break;
1163       }
1164
1165     if (NestTy) {
1166       Instruction *Caller = CS.getInstruction();
1167       std::vector<Value*> NewArgs;
1168       NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
1169
1170       SmallVector<AttributeWithIndex, 8> NewAttrs;
1171       NewAttrs.reserve(Attrs.getNumSlots() + 1);
1172
1173       // Insert the nest argument into the call argument list, which may
1174       // mean appending it.  Likewise for attributes.
1175
1176       // Add any result attributes.
1177       if (Attributes Attr = Attrs.getRetAttributes())
1178         NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
1179
1180       {
1181         unsigned Idx = 1;
1182         CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
1183         do {
1184           if (Idx == NestIdx) {
1185             // Add the chain argument and attributes.
1186             Value *NestVal = Tramp->getOperand(3);
1187             if (NestVal->getType() != NestTy)
1188               NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
1189             NewArgs.push_back(NestVal);
1190             NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
1191           }
1192
1193           if (I == E)
1194             break;
1195
1196           // Add the original argument and attributes.
1197           NewArgs.push_back(*I);
1198           if (Attributes Attr = Attrs.getParamAttributes(Idx))
1199             NewAttrs.push_back
1200               (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
1201
1202           ++Idx, ++I;
1203         } while (1);
1204       }
1205
1206       // Add any function attributes.
1207       if (Attributes Attr = Attrs.getFnAttributes())
1208         NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
1209
1210       // The trampoline may have been bitcast to a bogus type (FTy).
1211       // Handle this by synthesizing a new function type, equal to FTy
1212       // with the chain parameter inserted.
1213
1214       std::vector<const Type*> NewTypes;
1215       NewTypes.reserve(FTy->getNumParams()+1);
1216
1217       // Insert the chain's type into the list of parameter types, which may
1218       // mean appending it.
1219       {
1220         unsigned Idx = 1;
1221         FunctionType::param_iterator I = FTy->param_begin(),
1222           E = FTy->param_end();
1223
1224         do {
1225           if (Idx == NestIdx)
1226             // Add the chain's type.
1227             NewTypes.push_back(NestTy);
1228
1229           if (I == E)
1230             break;
1231
1232           // Add the original type.
1233           NewTypes.push_back(*I);
1234
1235           ++Idx, ++I;
1236         } while (1);
1237       }
1238
1239       // Replace the trampoline call with a direct call.  Let the generic
1240       // code sort out any function type mismatches.
1241       FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes, 
1242                                                 FTy->isVarArg());
1243       Constant *NewCallee =
1244         NestF->getType() == PointerType::getUnqual(NewFTy) ?
1245         NestF : ConstantExpr::getBitCast(NestF, 
1246                                          PointerType::getUnqual(NewFTy));
1247       const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),
1248                                                    NewAttrs.end());
1249
1250       Instruction *NewCaller;
1251       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
1252         NewCaller = InvokeInst::Create(NewCallee,
1253                                        II->getNormalDest(), II->getUnwindDest(),
1254                                        NewArgs.begin(), NewArgs.end(),
1255                                        Caller->getName(), Caller);
1256         cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
1257         cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
1258       } else {
1259         NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
1260                                      Caller->getName(), Caller);
1261         if (cast<CallInst>(Caller)->isTailCall())
1262           cast<CallInst>(NewCaller)->setTailCall();
1263         cast<CallInst>(NewCaller)->
1264           setCallingConv(cast<CallInst>(Caller)->getCallingConv());
1265         cast<CallInst>(NewCaller)->setAttributes(NewPAL);
1266       }
1267       if (!Caller->getType()->isVoidTy())
1268         Caller->replaceAllUsesWith(NewCaller);
1269       Caller->eraseFromParent();
1270       Worklist.Remove(Caller);
1271       return 0;
1272     }
1273   }
1274
1275   // Replace the trampoline call with a direct call.  Since there is no 'nest'
1276   // parameter, there is no need to adjust the argument list.  Let the generic
1277   // code sort out any function type mismatches.
1278   Constant *NewCallee =
1279     NestF->getType() == PTy ? NestF : 
1280                               ConstantExpr::getBitCast(NestF, PTy);
1281   CS.setCalledFunction(NewCallee);
1282   return CS.getInstruction();
1283 }
1284