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