InstCombineCalls.cpp revision 973f72a29aeafb1fdc4f8dafc3f6c6651cbb0c99
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"
20using namespace llvm;
21
22/// getPromotedType - Return the specified type promoted as it would be to pass
23/// though a va_arg area.
24static 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
33Instruction *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
123Instruction *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///
172Instruction *InstCombiner::visitCallInst(CallInst &CI) {
173  if (isFreeCall(&CI))
174    return visitFree(CI);
175  if (isMalloc(&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    // We need target data for just about everything so depend on it.
250    if (!TD) break;
251
252    Type *ReturnTy = CI.getType();
253    uint64_t DontKnow = II->getArgOperand(1) == Builder->getTrue() ? 0 : -1ULL;
254
255    // Get to the real allocated thing and offset as fast as possible.
256    Value *Op1 = II->getArgOperand(0)->stripPointerCasts();
257
258    uint64_t Offset = 0;
259    uint64_t Size = -1ULL;
260
261    // Try to look through constant GEPs.
262    if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1)) {
263      if (!GEP->hasAllConstantIndices()) break;
264
265      // Get the current byte offset into the thing. Use the original
266      // operand in case we're looking through a bitcast.
267      SmallVector<Value*, 8> Ops(GEP->idx_begin(), GEP->idx_end());
268      if (!GEP->getPointerOperandType()->isPointerTy())
269        return 0;
270      Offset = TD->getIndexedOffset(GEP->getPointerOperandType(), Ops);
271
272      Op1 = GEP->getPointerOperand()->stripPointerCasts();
273
274      // Make sure we're not a constant offset from an external
275      // global.
276      if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op1))
277        if (!GV->hasDefinitiveInitializer()) break;
278    }
279
280    // If we've stripped down to a single global variable that we
281    // can know the size of then just return that.
282    if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op1)) {
283      if (GV->hasDefinitiveInitializer()) {
284        Constant *C = GV->getInitializer();
285        Size = TD->getTypeAllocSize(C->getType());
286      } else {
287        // Can't determine size of the GV.
288        Constant *RetVal = ConstantInt::get(ReturnTy, DontKnow);
289        return ReplaceInstUsesWith(CI, RetVal);
290      }
291    } else if (AllocaInst *AI = dyn_cast<AllocaInst>(Op1)) {
292      // Get alloca size.
293      if (AI->getAllocatedType()->isSized()) {
294        Size = TD->getTypeAllocSize(AI->getAllocatedType());
295        if (AI->isArrayAllocation()) {
296          const ConstantInt *C = dyn_cast<ConstantInt>(AI->getArraySize());
297          if (!C) break;
298          Size *= C->getZExtValue();
299        }
300      }
301    } else if (CallInst *MI = extractMallocCall(Op1)) {
302      // Get allocation size.
303      Type* MallocType = getMallocAllocatedType(MI);
304      if (MallocType && MallocType->isSized())
305        if (Value *NElems = getMallocArraySize(MI, TD, true))
306          if (ConstantInt *NElements = dyn_cast<ConstantInt>(NElems))
307            Size = NElements->getZExtValue() * TD->getTypeAllocSize(MallocType);
308    }
309
310    // Do not return "I don't know" here. Later optimization passes could
311    // make it possible to evaluate objectsize to a constant.
312    if (Size == -1ULL)
313      break;
314
315    if (Size < Offset) {
316      // Out of bound reference? Negative index normalized to large
317      // index? Just return "I don't know".
318      return ReplaceInstUsesWith(CI, ConstantInt::get(ReturnTy, DontKnow));
319    }
320    return ReplaceInstUsesWith(CI, ConstantInt::get(ReturnTy, Size-Offset));
321  }
322  case Intrinsic::bswap:
323    // bswap(bswap(x)) -> x
324    if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getArgOperand(0)))
325      if (Operand->getIntrinsicID() == Intrinsic::bswap)
326        return ReplaceInstUsesWith(CI, Operand->getArgOperand(0));
327
328    // bswap(trunc(bswap(x))) -> trunc(lshr(x, c))
329    if (TruncInst *TI = dyn_cast<TruncInst>(II->getArgOperand(0))) {
330      if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(TI->getOperand(0)))
331        if (Operand->getIntrinsicID() == Intrinsic::bswap) {
332          unsigned C = Operand->getType()->getPrimitiveSizeInBits() -
333                       TI->getType()->getPrimitiveSizeInBits();
334          Value *CV = ConstantInt::get(Operand->getType(), C);
335          Value *V = Builder->CreateLShr(Operand->getArgOperand(0), CV);
336          return new TruncInst(V, TI->getType());
337        }
338    }
339
340    break;
341  case Intrinsic::powi:
342    if (ConstantInt *Power = dyn_cast<ConstantInt>(II->getArgOperand(1))) {
343      // powi(x, 0) -> 1.0
344      if (Power->isZero())
345        return ReplaceInstUsesWith(CI, ConstantFP::get(CI.getType(), 1.0));
346      // powi(x, 1) -> x
347      if (Power->isOne())
348        return ReplaceInstUsesWith(CI, II->getArgOperand(0));
349      // powi(x, -1) -> 1/x
350      if (Power->isAllOnesValue())
351        return BinaryOperator::CreateFDiv(ConstantFP::get(CI.getType(), 1.0),
352                                          II->getArgOperand(0));
353    }
354    break;
355  case Intrinsic::cttz: {
356    // If all bits below the first known one are known zero,
357    // this value is constant.
358    IntegerType *IT = dyn_cast<IntegerType>(II->getArgOperand(0)->getType());
359    // FIXME: Try to simplify vectors of integers.
360    if (!IT) break;
361    uint32_t BitWidth = IT->getBitWidth();
362    APInt KnownZero(BitWidth, 0);
363    APInt KnownOne(BitWidth, 0);
364    ComputeMaskedBits(II->getArgOperand(0), KnownZero, KnownOne);
365    unsigned TrailingZeros = KnownOne.countTrailingZeros();
366    APInt Mask(APInt::getLowBitsSet(BitWidth, TrailingZeros));
367    if ((Mask & KnownZero) == Mask)
368      return ReplaceInstUsesWith(CI, ConstantInt::get(IT,
369                                 APInt(BitWidth, TrailingZeros)));
370
371    }
372    break;
373  case Intrinsic::ctlz: {
374    // If all bits above the first known one are known zero,
375    // this value is constant.
376    IntegerType *IT = dyn_cast<IntegerType>(II->getArgOperand(0)->getType());
377    // FIXME: Try to simplify vectors of integers.
378    if (!IT) break;
379    uint32_t BitWidth = IT->getBitWidth();
380    APInt KnownZero(BitWidth, 0);
381    APInt KnownOne(BitWidth, 0);
382    ComputeMaskedBits(II->getArgOperand(0), KnownZero, KnownOne);
383    unsigned LeadingZeros = KnownOne.countLeadingZeros();
384    APInt Mask(APInt::getHighBitsSet(BitWidth, LeadingZeros));
385    if ((Mask & KnownZero) == Mask)
386      return ReplaceInstUsesWith(CI, ConstantInt::get(IT,
387                                 APInt(BitWidth, LeadingZeros)));
388
389    }
390    break;
391  case Intrinsic::uadd_with_overflow: {
392    Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
393    IntegerType *IT = cast<IntegerType>(II->getArgOperand(0)->getType());
394    uint32_t BitWidth = IT->getBitWidth();
395    APInt LHSKnownZero(BitWidth, 0);
396    APInt LHSKnownOne(BitWidth, 0);
397    ComputeMaskedBits(LHS, LHSKnownZero, LHSKnownOne);
398    bool LHSKnownNegative = LHSKnownOne[BitWidth - 1];
399    bool LHSKnownPositive = LHSKnownZero[BitWidth - 1];
400
401    if (LHSKnownNegative || LHSKnownPositive) {
402      APInt RHSKnownZero(BitWidth, 0);
403      APInt RHSKnownOne(BitWidth, 0);
404      ComputeMaskedBits(RHS, RHSKnownZero, RHSKnownOne);
405      bool RHSKnownNegative = RHSKnownOne[BitWidth - 1];
406      bool RHSKnownPositive = RHSKnownZero[BitWidth - 1];
407      if (LHSKnownNegative && RHSKnownNegative) {
408        // The sign bit is set in both cases: this MUST overflow.
409        // Create a simple add instruction, and insert it into the struct.
410        Value *Add = Builder->CreateAdd(LHS, RHS);
411        Add->takeName(&CI);
412        Constant *V[] = {
413          UndefValue::get(LHS->getType()),
414          ConstantInt::getTrue(II->getContext())
415        };
416        StructType *ST = cast<StructType>(II->getType());
417        Constant *Struct = ConstantStruct::get(ST, V);
418        return InsertValueInst::Create(Struct, Add, 0);
419      }
420
421      if (LHSKnownPositive && RHSKnownPositive) {
422        // The sign bit is clear in both cases: this CANNOT overflow.
423        // Create a simple add instruction, and insert it into the struct.
424        Value *Add = Builder->CreateNUWAdd(LHS, RHS);
425        Add->takeName(&CI);
426        Constant *V[] = {
427          UndefValue::get(LHS->getType()),
428          ConstantInt::getFalse(II->getContext())
429        };
430        StructType *ST = cast<StructType>(II->getType());
431        Constant *Struct = ConstantStruct::get(ST, V);
432        return InsertValueInst::Create(Struct, Add, 0);
433      }
434    }
435  }
436  // FALL THROUGH uadd into sadd
437  case Intrinsic::sadd_with_overflow:
438    // Canonicalize constants into the RHS.
439    if (isa<Constant>(II->getArgOperand(0)) &&
440        !isa<Constant>(II->getArgOperand(1))) {
441      Value *LHS = II->getArgOperand(0);
442      II->setArgOperand(0, II->getArgOperand(1));
443      II->setArgOperand(1, LHS);
444      return II;
445    }
446
447    // X + undef -> undef
448    if (isa<UndefValue>(II->getArgOperand(1)))
449      return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
450
451    if (ConstantInt *RHS = dyn_cast<ConstantInt>(II->getArgOperand(1))) {
452      // X + 0 -> {X, false}
453      if (RHS->isZero()) {
454        Constant *V[] = {
455          UndefValue::get(II->getArgOperand(0)->getType()),
456          ConstantInt::getFalse(II->getContext())
457        };
458        Constant *Struct =
459          ConstantStruct::get(cast<StructType>(II->getType()), V);
460        return InsertValueInst::Create(Struct, II->getArgOperand(0), 0);
461      }
462    }
463    break;
464  case Intrinsic::usub_with_overflow:
465  case Intrinsic::ssub_with_overflow:
466    // undef - X -> undef
467    // X - undef -> undef
468    if (isa<UndefValue>(II->getArgOperand(0)) ||
469        isa<UndefValue>(II->getArgOperand(1)))
470      return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
471
472    if (ConstantInt *RHS = dyn_cast<ConstantInt>(II->getArgOperand(1))) {
473      // X - 0 -> {X, false}
474      if (RHS->isZero()) {
475        Constant *V[] = {
476          UndefValue::get(II->getArgOperand(0)->getType()),
477          ConstantInt::getFalse(II->getContext())
478        };
479        Constant *Struct =
480          ConstantStruct::get(cast<StructType>(II->getType()), V);
481        return InsertValueInst::Create(Struct, II->getArgOperand(0), 0);
482      }
483    }
484    break;
485  case Intrinsic::umul_with_overflow: {
486    Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
487    unsigned BitWidth = cast<IntegerType>(LHS->getType())->getBitWidth();
488
489    APInt LHSKnownZero(BitWidth, 0);
490    APInt LHSKnownOne(BitWidth, 0);
491    ComputeMaskedBits(LHS, LHSKnownZero, LHSKnownOne);
492    APInt RHSKnownZero(BitWidth, 0);
493    APInt RHSKnownOne(BitWidth, 0);
494    ComputeMaskedBits(RHS, RHSKnownZero, RHSKnownOne);
495
496    // Get the largest possible values for each operand.
497    APInt LHSMax = ~LHSKnownZero;
498    APInt RHSMax = ~RHSKnownZero;
499
500    // If multiplying the maximum values does not overflow then we can turn
501    // this into a plain NUW mul.
502    bool Overflow;
503    LHSMax.umul_ov(RHSMax, Overflow);
504    if (!Overflow) {
505      Value *Mul = Builder->CreateNUWMul(LHS, RHS, "umul_with_overflow");
506      Constant *V[] = {
507        UndefValue::get(LHS->getType()),
508        Builder->getFalse()
509      };
510      Constant *Struct = ConstantStruct::get(cast<StructType>(II->getType()),V);
511      return InsertValueInst::Create(Struct, Mul, 0);
512    }
513  } // FALL THROUGH
514  case Intrinsic::smul_with_overflow:
515    // Canonicalize constants into the RHS.
516    if (isa<Constant>(II->getArgOperand(0)) &&
517        !isa<Constant>(II->getArgOperand(1))) {
518      Value *LHS = II->getArgOperand(0);
519      II->setArgOperand(0, II->getArgOperand(1));
520      II->setArgOperand(1, LHS);
521      return II;
522    }
523
524    // X * undef -> undef
525    if (isa<UndefValue>(II->getArgOperand(1)))
526      return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
527
528    if (ConstantInt *RHSI = dyn_cast<ConstantInt>(II->getArgOperand(1))) {
529      // X*0 -> {0, false}
530      if (RHSI->isZero())
531        return ReplaceInstUsesWith(CI, Constant::getNullValue(II->getType()));
532
533      // X * 1 -> {X, false}
534      if (RHSI->equalsInt(1)) {
535        Constant *V[] = {
536          UndefValue::get(II->getArgOperand(0)->getType()),
537          ConstantInt::getFalse(II->getContext())
538        };
539        Constant *Struct =
540          ConstantStruct::get(cast<StructType>(II->getType()), V);
541        return InsertValueInst::Create(Struct, II->getArgOperand(0), 0);
542      }
543    }
544    break;
545  case Intrinsic::ppc_altivec_lvx:
546  case Intrinsic::ppc_altivec_lvxl:
547    // Turn PPC lvx -> load if the pointer is known aligned.
548    if (getOrEnforceKnownAlignment(II->getArgOperand(0), 16, TD) >= 16) {
549      Value *Ptr = Builder->CreateBitCast(II->getArgOperand(0),
550                                         PointerType::getUnqual(II->getType()));
551      return new LoadInst(Ptr);
552    }
553    break;
554  case Intrinsic::ppc_altivec_stvx:
555  case Intrinsic::ppc_altivec_stvxl:
556    // Turn stvx -> store if the pointer is known aligned.
557    if (getOrEnforceKnownAlignment(II->getArgOperand(1), 16, TD) >= 16) {
558      Type *OpPtrTy =
559        PointerType::getUnqual(II->getArgOperand(0)->getType());
560      Value *Ptr = Builder->CreateBitCast(II->getArgOperand(1), OpPtrTy);
561      return new StoreInst(II->getArgOperand(0), Ptr);
562    }
563    break;
564  case Intrinsic::x86_sse_storeu_ps:
565  case Intrinsic::x86_sse2_storeu_pd:
566  case Intrinsic::x86_sse2_storeu_dq:
567    // Turn X86 storeu -> store if the pointer is known aligned.
568    if (getOrEnforceKnownAlignment(II->getArgOperand(0), 16, TD) >= 16) {
569      Type *OpPtrTy =
570        PointerType::getUnqual(II->getArgOperand(1)->getType());
571      Value *Ptr = Builder->CreateBitCast(II->getArgOperand(0), OpPtrTy);
572      return new StoreInst(II->getArgOperand(1), Ptr);
573    }
574    break;
575
576  case Intrinsic::x86_sse_cvtss2si:
577  case Intrinsic::x86_sse_cvtss2si64:
578  case Intrinsic::x86_sse_cvttss2si:
579  case Intrinsic::x86_sse_cvttss2si64:
580  case Intrinsic::x86_sse2_cvtsd2si:
581  case Intrinsic::x86_sse2_cvtsd2si64:
582  case Intrinsic::x86_sse2_cvttsd2si:
583  case Intrinsic::x86_sse2_cvttsd2si64: {
584    // These intrinsics only demand the 0th element of their input vectors. If
585    // we can simplify the input based on that, do so now.
586    unsigned VWidth =
587      cast<VectorType>(II->getArgOperand(0)->getType())->getNumElements();
588    APInt DemandedElts(VWidth, 1);
589    APInt UndefElts(VWidth, 0);
590    if (Value *V = SimplifyDemandedVectorElts(II->getArgOperand(0),
591                                              DemandedElts, UndefElts)) {
592      II->setArgOperand(0, V);
593      return II;
594    }
595    break;
596  }
597
598
599  case Intrinsic::x86_sse41_pmovsxbw:
600  case Intrinsic::x86_sse41_pmovsxwd:
601  case Intrinsic::x86_sse41_pmovsxdq:
602  case Intrinsic::x86_sse41_pmovzxbw:
603  case Intrinsic::x86_sse41_pmovzxwd:
604  case Intrinsic::x86_sse41_pmovzxdq: {
605    // pmov{s|z}x ignores the upper half of their input vectors.
606    unsigned VWidth =
607      cast<VectorType>(II->getArgOperand(0)->getType())->getNumElements();
608    unsigned LowHalfElts = VWidth / 2;
609    APInt InputDemandedElts(APInt::getBitsSet(VWidth, 0, LowHalfElts));
610    APInt UndefElts(VWidth, 0);
611    if (Value *TmpV = SimplifyDemandedVectorElts(II->getArgOperand(0),
612                                                 InputDemandedElts,
613                                                 UndefElts)) {
614      II->setArgOperand(0, TmpV);
615      return II;
616    }
617    break;
618  }
619
620  case Intrinsic::ppc_altivec_vperm:
621    // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
622    if (Constant *Mask = dyn_cast<Constant>(II->getArgOperand(2))) {
623      assert(Mask->getType()->getVectorNumElements() == 16 &&
624             "Bad type for intrinsic!");
625
626      // Check that all of the elements are integer constants or undefs.
627      bool AllEltsOk = true;
628      for (unsigned i = 0; i != 16; ++i) {
629        Constant *Elt = Mask->getAggregateElement(i);
630        if (Elt == 0 ||
631            !(isa<ConstantInt>(Elt) || isa<UndefValue>(Elt))) {
632          AllEltsOk = false;
633          break;
634        }
635      }
636
637      if (AllEltsOk) {
638        // Cast the input vectors to byte vectors.
639        Value *Op0 = Builder->CreateBitCast(II->getArgOperand(0),
640                                            Mask->getType());
641        Value *Op1 = Builder->CreateBitCast(II->getArgOperand(1),
642                                            Mask->getType());
643        Value *Result = UndefValue::get(Op0->getType());
644
645        // Only extract each element once.
646        Value *ExtractedElts[32];
647        memset(ExtractedElts, 0, sizeof(ExtractedElts));
648
649        for (unsigned i = 0; i != 16; ++i) {
650          if (isa<UndefValue>(Mask->getAggregateElement(i)))
651            continue;
652          unsigned Idx =
653            cast<ConstantInt>(Mask->getAggregateElement(i))->getZExtValue();
654          Idx &= 31;  // Match the hardware behavior.
655
656          if (ExtractedElts[Idx] == 0) {
657            ExtractedElts[Idx] =
658              Builder->CreateExtractElement(Idx < 16 ? Op0 : Op1,
659                                            Builder->getInt32(Idx&15));
660          }
661
662          // Insert this value into the result vector.
663          Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
664                                                Builder->getInt32(i));
665        }
666        return CastInst::Create(Instruction::BitCast, Result, CI.getType());
667      }
668    }
669    break;
670
671  case Intrinsic::arm_neon_vld1:
672  case Intrinsic::arm_neon_vld2:
673  case Intrinsic::arm_neon_vld3:
674  case Intrinsic::arm_neon_vld4:
675  case Intrinsic::arm_neon_vld2lane:
676  case Intrinsic::arm_neon_vld3lane:
677  case Intrinsic::arm_neon_vld4lane:
678  case Intrinsic::arm_neon_vst1:
679  case Intrinsic::arm_neon_vst2:
680  case Intrinsic::arm_neon_vst3:
681  case Intrinsic::arm_neon_vst4:
682  case Intrinsic::arm_neon_vst2lane:
683  case Intrinsic::arm_neon_vst3lane:
684  case Intrinsic::arm_neon_vst4lane: {
685    unsigned MemAlign = getKnownAlignment(II->getArgOperand(0), TD);
686    unsigned AlignArg = II->getNumArgOperands() - 1;
687    ConstantInt *IntrAlign = dyn_cast<ConstantInt>(II->getArgOperand(AlignArg));
688    if (IntrAlign && IntrAlign->getZExtValue() < MemAlign) {
689      II->setArgOperand(AlignArg,
690                        ConstantInt::get(Type::getInt32Ty(II->getContext()),
691                                         MemAlign, false));
692      return II;
693    }
694    break;
695  }
696
697  case Intrinsic::arm_neon_vmulls:
698  case Intrinsic::arm_neon_vmullu: {
699    Value *Arg0 = II->getArgOperand(0);
700    Value *Arg1 = II->getArgOperand(1);
701
702    // Handle mul by zero first:
703    if (isa<ConstantAggregateZero>(Arg0) || isa<ConstantAggregateZero>(Arg1)) {
704      return ReplaceInstUsesWith(CI, ConstantAggregateZero::get(II->getType()));
705    }
706
707    // Check for constant LHS & RHS - in this case we just simplify.
708    bool Zext = (II->getIntrinsicID() == Intrinsic::arm_neon_vmullu);
709    VectorType *NewVT = cast<VectorType>(II->getType());
710    unsigned NewWidth = NewVT->getElementType()->getIntegerBitWidth();
711    if (ConstantDataVector *CV0 = dyn_cast<ConstantDataVector>(Arg0)) {
712      if (ConstantDataVector *CV1 = dyn_cast<ConstantDataVector>(Arg1)) {
713        VectorType* VT = cast<VectorType>(CV0->getType());
714        SmallVector<Constant*, 4> NewElems;
715        for (unsigned i = 0; i < VT->getNumElements(); ++i) {
716          APInt CV0E =
717            (cast<ConstantInt>(CV0->getAggregateElement(i)))->getValue();
718          CV0E = Zext ? CV0E.zext(NewWidth) : CV0E.sext(NewWidth);
719          APInt CV1E =
720            (cast<ConstantInt>(CV1->getAggregateElement(i)))->getValue();
721          CV1E = Zext ? CV1E.zext(NewWidth) : CV1E.sext(NewWidth);
722          NewElems.push_back(
723            ConstantInt::get(NewVT->getElementType(), CV0E * CV1E));
724        }
725        return ReplaceInstUsesWith(CI, ConstantVector::get(NewElems));
726      }
727
728      // Couldn't simplify - cannonicalize constant to the RHS.
729      std::swap(Arg0, Arg1);
730    }
731
732    // Handle mul by one:
733    if (ConstantDataVector *CV1 = dyn_cast<ConstantDataVector>(Arg1)) {
734      if (ConstantInt *Splat =
735            dyn_cast_or_null<ConstantInt>(CV1->getSplatValue())) {
736        if (Splat->isOne()) {
737          if (Zext)
738            return CastInst::CreateZExtOrBitCast(Arg0, II->getType());
739          // else
740          return CastInst::CreateSExtOrBitCast(Arg0, II->getType());
741        }
742      }
743    }
744
745    break;
746  }
747
748  case Intrinsic::stackrestore: {
749    // If the save is right next to the restore, remove the restore.  This can
750    // happen when variable allocas are DCE'd.
751    if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getArgOperand(0))) {
752      if (SS->getIntrinsicID() == Intrinsic::stacksave) {
753        BasicBlock::iterator BI = SS;
754        if (&*++BI == II)
755          return EraseInstFromFunction(CI);
756      }
757    }
758
759    // Scan down this block to see if there is another stack restore in the
760    // same block without an intervening call/alloca.
761    BasicBlock::iterator BI = II;
762    TerminatorInst *TI = II->getParent()->getTerminator();
763    bool CannotRemove = false;
764    for (++BI; &*BI != TI; ++BI) {
765      if (isa<AllocaInst>(BI) || isMalloc(BI)) {
766        CannotRemove = true;
767        break;
768      }
769      if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
770        if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
771          // If there is a stackrestore below this one, remove this one.
772          if (II->getIntrinsicID() == Intrinsic::stackrestore)
773            return EraseInstFromFunction(CI);
774          // Otherwise, ignore the intrinsic.
775        } else {
776          // If we found a non-intrinsic call, we can't remove the stack
777          // restore.
778          CannotRemove = true;
779          break;
780        }
781      }
782    }
783
784    // If the stack restore is in a return, resume, or unwind block and if there
785    // are no allocas or calls between the restore and the return, nuke the
786    // restore.
787    if (!CannotRemove && (isa<ReturnInst>(TI) || isa<ResumeInst>(TI)))
788      return EraseInstFromFunction(CI);
789    break;
790  }
791  }
792
793  return visitCallSite(II);
794}
795
796// InvokeInst simplification
797//
798Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
799  return visitCallSite(&II);
800}
801
802/// isSafeToEliminateVarargsCast - If this cast does not affect the value
803/// passed through the varargs area, we can eliminate the use of the cast.
804static bool isSafeToEliminateVarargsCast(const CallSite CS,
805                                         const CastInst * const CI,
806                                         const TargetData * const TD,
807                                         const int ix) {
808  if (!CI->isLosslessCast())
809    return false;
810
811  // The size of ByVal arguments is derived from the type, so we
812  // can't change to a type with a different size.  If the size were
813  // passed explicitly we could avoid this check.
814  if (!CS.isByValArgument(ix))
815    return true;
816
817  Type* SrcTy =
818            cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
819  Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
820  if (!SrcTy->isSized() || !DstTy->isSized())
821    return false;
822  if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
823    return false;
824  return true;
825}
826
827namespace {
828class InstCombineFortifiedLibCalls : public SimplifyFortifiedLibCalls {
829  InstCombiner *IC;
830protected:
831  void replaceCall(Value *With) {
832    NewInstruction = IC->ReplaceInstUsesWith(*CI, With);
833  }
834  bool isFoldable(unsigned SizeCIOp, unsigned SizeArgOp, bool isString) const {
835    if (CI->getArgOperand(SizeCIOp) == CI->getArgOperand(SizeArgOp))
836      return true;
837    if (ConstantInt *SizeCI =
838                           dyn_cast<ConstantInt>(CI->getArgOperand(SizeCIOp))) {
839      if (SizeCI->isAllOnesValue())
840        return true;
841      if (isString) {
842        uint64_t Len = GetStringLength(CI->getArgOperand(SizeArgOp));
843        // If the length is 0 we don't know how long it is and so we can't
844        // remove the check.
845        if (Len == 0) return false;
846        return SizeCI->getZExtValue() >= Len;
847      }
848      if (ConstantInt *Arg = dyn_cast<ConstantInt>(
849                                                  CI->getArgOperand(SizeArgOp)))
850        return SizeCI->getZExtValue() >= Arg->getZExtValue();
851    }
852    return false;
853  }
854public:
855  InstCombineFortifiedLibCalls(InstCombiner *IC) : IC(IC), NewInstruction(0) { }
856  Instruction *NewInstruction;
857};
858} // end anonymous namespace
859
860// Try to fold some different type of calls here.
861// Currently we're only working with the checking functions, memcpy_chk,
862// mempcpy_chk, memmove_chk, memset_chk, strcpy_chk, stpcpy_chk, strncpy_chk,
863// strcat_chk and strncat_chk.
864Instruction *InstCombiner::tryOptimizeCall(CallInst *CI, const TargetData *TD) {
865  if (CI->getCalledFunction() == 0) return 0;
866
867  InstCombineFortifiedLibCalls Simplifier(this);
868  Simplifier.fold(CI, TD);
869  return Simplifier.NewInstruction;
870}
871
872static IntrinsicInst *FindInitTrampolineFromAlloca(Value *TrampMem) {
873  // Strip off at most one level of pointer casts, looking for an alloca.  This
874  // is good enough in practice and simpler than handling any number of casts.
875  Value *Underlying = TrampMem->stripPointerCasts();
876  if (Underlying != TrampMem &&
877      (!Underlying->hasOneUse() || *Underlying->use_begin() != TrampMem))
878    return 0;
879  if (!isa<AllocaInst>(Underlying))
880    return 0;
881
882  IntrinsicInst *InitTrampoline = 0;
883  for (Value::use_iterator I = TrampMem->use_begin(), E = TrampMem->use_end();
884       I != E; I++) {
885    IntrinsicInst *II = dyn_cast<IntrinsicInst>(*I);
886    if (!II)
887      return 0;
888    if (II->getIntrinsicID() == Intrinsic::init_trampoline) {
889      if (InitTrampoline)
890        // More than one init_trampoline writes to this value.  Give up.
891        return 0;
892      InitTrampoline = II;
893      continue;
894    }
895    if (II->getIntrinsicID() == Intrinsic::adjust_trampoline)
896      // Allow any number of calls to adjust.trampoline.
897      continue;
898    return 0;
899  }
900
901  // No call to init.trampoline found.
902  if (!InitTrampoline)
903    return 0;
904
905  // Check that the alloca is being used in the expected way.
906  if (InitTrampoline->getOperand(0) != TrampMem)
907    return 0;
908
909  return InitTrampoline;
910}
911
912static IntrinsicInst *FindInitTrampolineFromBB(IntrinsicInst *AdjustTramp,
913                                               Value *TrampMem) {
914  // Visit all the previous instructions in the basic block, and try to find a
915  // init.trampoline which has a direct path to the adjust.trampoline.
916  for (BasicBlock::iterator I = AdjustTramp,
917       E = AdjustTramp->getParent()->begin(); I != E; ) {
918    Instruction *Inst = --I;
919    if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
920      if (II->getIntrinsicID() == Intrinsic::init_trampoline &&
921          II->getOperand(0) == TrampMem)
922        return II;
923    if (Inst->mayWriteToMemory())
924      return 0;
925  }
926  return 0;
927}
928
929// Given a call to llvm.adjust.trampoline, find and return the corresponding
930// call to llvm.init.trampoline if the call to the trampoline can be optimized
931// to a direct call to a function.  Otherwise return NULL.
932//
933static IntrinsicInst *FindInitTrampoline(Value *Callee) {
934  Callee = Callee->stripPointerCasts();
935  IntrinsicInst *AdjustTramp = dyn_cast<IntrinsicInst>(Callee);
936  if (!AdjustTramp ||
937      AdjustTramp->getIntrinsicID() != Intrinsic::adjust_trampoline)
938    return 0;
939
940  Value *TrampMem = AdjustTramp->getOperand(0);
941
942  if (IntrinsicInst *IT = FindInitTrampolineFromAlloca(TrampMem))
943    return IT;
944  if (IntrinsicInst *IT = FindInitTrampolineFromBB(AdjustTramp, TrampMem))
945    return IT;
946  return 0;
947}
948
949// visitCallSite - Improvements for call and invoke instructions.
950//
951Instruction *InstCombiner::visitCallSite(CallSite CS) {
952  bool Changed = false;
953
954  // If the callee is a pointer to a function, attempt to move any casts to the
955  // arguments of the call/invoke.
956  Value *Callee = CS.getCalledValue();
957  if (!isa<Function>(Callee) && transformConstExprCastCall(CS))
958    return 0;
959
960  if (Function *CalleeF = dyn_cast<Function>(Callee))
961    // If the call and callee calling conventions don't match, this call must
962    // be unreachable, as the call is undefined.
963    if (CalleeF->getCallingConv() != CS.getCallingConv() &&
964        // Only do this for calls to a function with a body.  A prototype may
965        // not actually end up matching the implementation's calling conv for a
966        // variety of reasons (e.g. it may be written in assembly).
967        !CalleeF->isDeclaration()) {
968      Instruction *OldCall = CS.getInstruction();
969      new StoreInst(ConstantInt::getTrue(Callee->getContext()),
970                UndefValue::get(Type::getInt1PtrTy(Callee->getContext())),
971                                  OldCall);
972      // If OldCall dues not return void then replaceAllUsesWith undef.
973      // This allows ValueHandlers and custom metadata to adjust itself.
974      if (!OldCall->getType()->isVoidTy())
975        ReplaceInstUsesWith(*OldCall, UndefValue::get(OldCall->getType()));
976      if (isa<CallInst>(OldCall))
977        return EraseInstFromFunction(*OldCall);
978
979      // We cannot remove an invoke, because it would change the CFG, just
980      // change the callee to a null pointer.
981      cast<InvokeInst>(OldCall)->setCalledFunction(
982                                    Constant::getNullValue(CalleeF->getType()));
983      return 0;
984    }
985
986  if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
987    // This instruction is not reachable, just remove it.  We insert a store to
988    // undef so that we know that this code is not reachable, despite the fact
989    // that we can't modify the CFG here.
990    new StoreInst(ConstantInt::getTrue(Callee->getContext()),
991               UndefValue::get(Type::getInt1PtrTy(Callee->getContext())),
992                  CS.getInstruction());
993
994    // If CS does not return void then replaceAllUsesWith undef.
995    // This allows ValueHandlers and custom metadata to adjust itself.
996    if (!CS.getInstruction()->getType()->isVoidTy())
997      ReplaceInstUsesWith(*CS.getInstruction(),
998                          UndefValue::get(CS.getInstruction()->getType()));
999
1000    if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
1001      // Don't break the CFG, insert a dummy cond branch.
1002      BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
1003                         ConstantInt::getTrue(Callee->getContext()), II);
1004    }
1005    return EraseInstFromFunction(*CS.getInstruction());
1006  }
1007
1008  if (IntrinsicInst *II = FindInitTrampoline(Callee))
1009    return transformCallThroughTrampoline(CS, II);
1010
1011  PointerType *PTy = cast<PointerType>(Callee->getType());
1012  FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1013  if (FTy->isVarArg()) {
1014    int ix = FTy->getNumParams();
1015    // See if we can optimize any arguments passed through the varargs area of
1016    // the call.
1017    for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
1018           E = CS.arg_end(); I != E; ++I, ++ix) {
1019      CastInst *CI = dyn_cast<CastInst>(*I);
1020      if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
1021        *I = CI->getOperand(0);
1022        Changed = true;
1023      }
1024    }
1025  }
1026
1027  if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
1028    // Inline asm calls cannot throw - mark them 'nounwind'.
1029    CS.setDoesNotThrow();
1030    Changed = true;
1031  }
1032
1033  // Try to optimize the call if possible, we require TargetData for most of
1034  // this.  None of these calls are seen as possibly dead so go ahead and
1035  // delete the instruction now.
1036  if (CallInst *CI = dyn_cast<CallInst>(CS.getInstruction())) {
1037    Instruction *I = tryOptimizeCall(CI, TD);
1038    // If we changed something return the result, etc. Otherwise let
1039    // the fallthrough check.
1040    if (I) return EraseInstFromFunction(*I);
1041  }
1042
1043  return Changed ? CS.getInstruction() : 0;
1044}
1045
1046// transformConstExprCastCall - If the callee is a constexpr cast of a function,
1047// attempt to move the cast to the arguments of the call/invoke.
1048//
1049bool InstCombiner::transformConstExprCastCall(CallSite CS) {
1050  Function *Callee =
1051    dyn_cast<Function>(CS.getCalledValue()->stripPointerCasts());
1052  if (Callee == 0)
1053    return false;
1054  Instruction *Caller = CS.getInstruction();
1055  const AttrListPtr &CallerPAL = CS.getAttributes();
1056
1057  // Okay, this is a cast from a function to a different type.  Unless doing so
1058  // would cause a type conversion of one of our arguments, change this call to
1059  // be a direct call with arguments casted to the appropriate types.
1060  //
1061  FunctionType *FT = Callee->getFunctionType();
1062  Type *OldRetTy = Caller->getType();
1063  Type *NewRetTy = FT->getReturnType();
1064
1065  if (NewRetTy->isStructTy())
1066    return false; // TODO: Handle multiple return values.
1067
1068  // Check to see if we are changing the return type...
1069  if (OldRetTy != NewRetTy) {
1070    if (Callee->isDeclaration() &&
1071        // Conversion is ok if changing from one pointer type to another or from
1072        // a pointer to an integer of the same size.
1073        !((OldRetTy->isPointerTy() || !TD ||
1074           OldRetTy == TD->getIntPtrType(Caller->getContext())) &&
1075          (NewRetTy->isPointerTy() || !TD ||
1076           NewRetTy == TD->getIntPtrType(Caller->getContext()))))
1077      return false;   // Cannot transform this return value.
1078
1079    if (!Caller->use_empty() &&
1080        // void -> non-void is handled specially
1081        !NewRetTy->isVoidTy() && !CastInst::isCastable(NewRetTy, OldRetTy))
1082      return false;   // Cannot transform this return value.
1083
1084    if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
1085      Attributes RAttrs = CallerPAL.getRetAttributes();
1086      if (RAttrs & Attribute::typeIncompatible(NewRetTy))
1087        return false;   // Attribute not compatible with transformed value.
1088    }
1089
1090    // If the callsite is an invoke instruction, and the return value is used by
1091    // a PHI node in a successor, we cannot change the return type of the call
1092    // because there is no place to put the cast instruction (without breaking
1093    // the critical edge).  Bail out in this case.
1094    if (!Caller->use_empty())
1095      if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
1096        for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
1097             UI != E; ++UI)
1098          if (PHINode *PN = dyn_cast<PHINode>(*UI))
1099            if (PN->getParent() == II->getNormalDest() ||
1100                PN->getParent() == II->getUnwindDest())
1101              return false;
1102  }
1103
1104  unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
1105  unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
1106
1107  CallSite::arg_iterator AI = CS.arg_begin();
1108  for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
1109    Type *ParamTy = FT->getParamType(i);
1110    Type *ActTy = (*AI)->getType();
1111
1112    if (!CastInst::isCastable(ActTy, ParamTy))
1113      return false;   // Cannot transform this parameter value.
1114
1115    Attributes Attrs = CallerPAL.getParamAttributes(i + 1);
1116    if (Attrs & Attribute::typeIncompatible(ParamTy))
1117      return false;   // Attribute not compatible with transformed value.
1118
1119    // If the parameter is passed as a byval argument, then we have to have a
1120    // sized type and the sized type has to have the same size as the old type.
1121    if (ParamTy != ActTy && (Attrs & Attribute::ByVal)) {
1122      PointerType *ParamPTy = dyn_cast<PointerType>(ParamTy);
1123      if (ParamPTy == 0 || !ParamPTy->getElementType()->isSized() || TD == 0)
1124        return false;
1125
1126      Type *CurElTy = cast<PointerType>(ActTy)->getElementType();
1127      if (TD->getTypeAllocSize(CurElTy) !=
1128          TD->getTypeAllocSize(ParamPTy->getElementType()))
1129        return false;
1130    }
1131
1132    // Converting from one pointer type to another or between a pointer and an
1133    // integer of the same size is safe even if we do not have a body.
1134    bool isConvertible = ActTy == ParamTy ||
1135      (TD && ((ParamTy->isPointerTy() ||
1136      ParamTy == TD->getIntPtrType(Caller->getContext())) &&
1137              (ActTy->isPointerTy() ||
1138              ActTy == TD->getIntPtrType(Caller->getContext()))));
1139    if (Callee->isDeclaration() && !isConvertible) return false;
1140  }
1141
1142  if (Callee->isDeclaration()) {
1143    // Do not delete arguments unless we have a function body.
1144    if (FT->getNumParams() < NumActualArgs && !FT->isVarArg())
1145      return false;
1146
1147    // If the callee is just a declaration, don't change the varargsness of the
1148    // call.  We don't want to introduce a varargs call where one doesn't
1149    // already exist.
1150    PointerType *APTy = cast<PointerType>(CS.getCalledValue()->getType());
1151    if (FT->isVarArg()!=cast<FunctionType>(APTy->getElementType())->isVarArg())
1152      return false;
1153
1154    // If both the callee and the cast type are varargs, we still have to make
1155    // sure the number of fixed parameters are the same or we have the same
1156    // ABI issues as if we introduce a varargs call.
1157    if (FT->isVarArg() &&
1158        cast<FunctionType>(APTy->getElementType())->isVarArg() &&
1159        FT->getNumParams() !=
1160        cast<FunctionType>(APTy->getElementType())->getNumParams())
1161      return false;
1162  }
1163
1164  if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
1165      !CallerPAL.isEmpty())
1166    // In this case we have more arguments than the new function type, but we
1167    // won't be dropping them.  Check that these extra arguments have attributes
1168    // that are compatible with being a vararg call argument.
1169    for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
1170      if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
1171        break;
1172      Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
1173      if (PAttrs & Attribute::VarArgsIncompatible)
1174        return false;
1175    }
1176
1177
1178  // Okay, we decided that this is a safe thing to do: go ahead and start
1179  // inserting cast instructions as necessary.
1180  std::vector<Value*> Args;
1181  Args.reserve(NumActualArgs);
1182  SmallVector<AttributeWithIndex, 8> attrVec;
1183  attrVec.reserve(NumCommonArgs);
1184
1185  // Get any return attributes.
1186  Attributes RAttrs = CallerPAL.getRetAttributes();
1187
1188  // If the return value is not being used, the type may not be compatible
1189  // with the existing attributes.  Wipe out any problematic attributes.
1190  RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
1191
1192  // Add the new return attributes.
1193  if (RAttrs)
1194    attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
1195
1196  AI = CS.arg_begin();
1197  for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
1198    Type *ParamTy = FT->getParamType(i);
1199    if ((*AI)->getType() == ParamTy) {
1200      Args.push_back(*AI);
1201    } else {
1202      Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
1203          false, ParamTy, false);
1204      Args.push_back(Builder->CreateCast(opcode, *AI, ParamTy));
1205    }
1206
1207    // Add any parameter attributes.
1208    if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
1209      attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
1210  }
1211
1212  // If the function takes more arguments than the call was taking, add them
1213  // now.
1214  for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
1215    Args.push_back(Constant::getNullValue(FT->getParamType(i)));
1216
1217  // If we are removing arguments to the function, emit an obnoxious warning.
1218  if (FT->getNumParams() < NumActualArgs) {
1219    if (!FT->isVarArg()) {
1220      errs() << "WARNING: While resolving call to function '"
1221             << Callee->getName() << "' arguments were dropped!\n";
1222    } else {
1223      // Add all of the arguments in their promoted form to the arg list.
1224      for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
1225        Type *PTy = getPromotedType((*AI)->getType());
1226        if (PTy != (*AI)->getType()) {
1227          // Must promote to pass through va_arg area!
1228          Instruction::CastOps opcode =
1229            CastInst::getCastOpcode(*AI, false, PTy, false);
1230          Args.push_back(Builder->CreateCast(opcode, *AI, PTy));
1231        } else {
1232          Args.push_back(*AI);
1233        }
1234
1235        // Add any parameter attributes.
1236        if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
1237          attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
1238      }
1239    }
1240  }
1241
1242  if (Attributes FnAttrs =  CallerPAL.getFnAttributes())
1243    attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
1244
1245  if (NewRetTy->isVoidTy())
1246    Caller->setName("");   // Void type should not have a name.
1247
1248  const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),
1249                                                     attrVec.end());
1250
1251  Instruction *NC;
1252  if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
1253    NC = Builder->CreateInvoke(Callee, II->getNormalDest(),
1254                               II->getUnwindDest(), Args);
1255    NC->takeName(II);
1256    cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
1257    cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
1258  } else {
1259    CallInst *CI = cast<CallInst>(Caller);
1260    NC = Builder->CreateCall(Callee, Args);
1261    NC->takeName(CI);
1262    if (CI->isTailCall())
1263      cast<CallInst>(NC)->setTailCall();
1264    cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
1265    cast<CallInst>(NC)->setAttributes(NewCallerPAL);
1266  }
1267
1268  // Insert a cast of the return type as necessary.
1269  Value *NV = NC;
1270  if (OldRetTy != NV->getType() && !Caller->use_empty()) {
1271    if (!NV->getType()->isVoidTy()) {
1272      Instruction::CastOps opcode =
1273        CastInst::getCastOpcode(NC, false, OldRetTy, false);
1274      NV = NC = CastInst::Create(opcode, NC, OldRetTy);
1275      NC->setDebugLoc(Caller->getDebugLoc());
1276
1277      // If this is an invoke instruction, we should insert it after the first
1278      // non-phi, instruction in the normal successor block.
1279      if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
1280        BasicBlock::iterator I = II->getNormalDest()->getFirstInsertionPt();
1281        InsertNewInstBefore(NC, *I);
1282      } else {
1283        // Otherwise, it's a call, just insert cast right after the call.
1284        InsertNewInstBefore(NC, *Caller);
1285      }
1286      Worklist.AddUsersToWorkList(*Caller);
1287    } else {
1288      NV = UndefValue::get(Caller->getType());
1289    }
1290  }
1291
1292  if (!Caller->use_empty())
1293    ReplaceInstUsesWith(*Caller, NV);
1294
1295  EraseInstFromFunction(*Caller);
1296  return true;
1297}
1298
1299// transformCallThroughTrampoline - Turn a call to a function created by
1300// init_trampoline / adjust_trampoline intrinsic pair into a direct call to the
1301// underlying function.
1302//
1303Instruction *
1304InstCombiner::transformCallThroughTrampoline(CallSite CS,
1305                                             IntrinsicInst *Tramp) {
1306  Value *Callee = CS.getCalledValue();
1307  PointerType *PTy = cast<PointerType>(Callee->getType());
1308  FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1309  const AttrListPtr &Attrs = CS.getAttributes();
1310
1311  // If the call already has the 'nest' attribute somewhere then give up -
1312  // otherwise 'nest' would occur twice after splicing in the chain.
1313  if (Attrs.hasAttrSomewhere(Attribute::Nest))
1314    return 0;
1315
1316  assert(Tramp &&
1317         "transformCallThroughTrampoline called with incorrect CallSite.");
1318
1319  Function *NestF =cast<Function>(Tramp->getArgOperand(1)->stripPointerCasts());
1320  PointerType *NestFPTy = cast<PointerType>(NestF->getType());
1321  FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
1322
1323  const AttrListPtr &NestAttrs = NestF->getAttributes();
1324  if (!NestAttrs.isEmpty()) {
1325    unsigned NestIdx = 1;
1326    Type *NestTy = 0;
1327    Attributes NestAttr = Attribute::None;
1328
1329    // Look for a parameter marked with the 'nest' attribute.
1330    for (FunctionType::param_iterator I = NestFTy->param_begin(),
1331         E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
1332      if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
1333        // Record the parameter type and any other attributes.
1334        NestTy = *I;
1335        NestAttr = NestAttrs.getParamAttributes(NestIdx);
1336        break;
1337      }
1338
1339    if (NestTy) {
1340      Instruction *Caller = CS.getInstruction();
1341      std::vector<Value*> NewArgs;
1342      NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
1343
1344      SmallVector<AttributeWithIndex, 8> NewAttrs;
1345      NewAttrs.reserve(Attrs.getNumSlots() + 1);
1346
1347      // Insert the nest argument into the call argument list, which may
1348      // mean appending it.  Likewise for attributes.
1349
1350      // Add any result attributes.
1351      if (Attributes Attr = Attrs.getRetAttributes())
1352        NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
1353
1354      {
1355        unsigned Idx = 1;
1356        CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
1357        do {
1358          if (Idx == NestIdx) {
1359            // Add the chain argument and attributes.
1360            Value *NestVal = Tramp->getArgOperand(2);
1361            if (NestVal->getType() != NestTy)
1362              NestVal = Builder->CreateBitCast(NestVal, NestTy, "nest");
1363            NewArgs.push_back(NestVal);
1364            NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
1365          }
1366
1367          if (I == E)
1368            break;
1369
1370          // Add the original argument and attributes.
1371          NewArgs.push_back(*I);
1372          if (Attributes Attr = Attrs.getParamAttributes(Idx))
1373            NewAttrs.push_back
1374              (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
1375
1376          ++Idx, ++I;
1377        } while (1);
1378      }
1379
1380      // Add any function attributes.
1381      if (Attributes Attr = Attrs.getFnAttributes())
1382        NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
1383
1384      // The trampoline may have been bitcast to a bogus type (FTy).
1385      // Handle this by synthesizing a new function type, equal to FTy
1386      // with the chain parameter inserted.
1387
1388      std::vector<Type*> NewTypes;
1389      NewTypes.reserve(FTy->getNumParams()+1);
1390
1391      // Insert the chain's type into the list of parameter types, which may
1392      // mean appending it.
1393      {
1394        unsigned Idx = 1;
1395        FunctionType::param_iterator I = FTy->param_begin(),
1396          E = FTy->param_end();
1397
1398        do {
1399          if (Idx == NestIdx)
1400            // Add the chain's type.
1401            NewTypes.push_back(NestTy);
1402
1403          if (I == E)
1404            break;
1405
1406          // Add the original type.
1407          NewTypes.push_back(*I);
1408
1409          ++Idx, ++I;
1410        } while (1);
1411      }
1412
1413      // Replace the trampoline call with a direct call.  Let the generic
1414      // code sort out any function type mismatches.
1415      FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
1416                                                FTy->isVarArg());
1417      Constant *NewCallee =
1418        NestF->getType() == PointerType::getUnqual(NewFTy) ?
1419        NestF : ConstantExpr::getBitCast(NestF,
1420                                         PointerType::getUnqual(NewFTy));
1421      const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),
1422                                                   NewAttrs.end());
1423
1424      Instruction *NewCaller;
1425      if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
1426        NewCaller = InvokeInst::Create(NewCallee,
1427                                       II->getNormalDest(), II->getUnwindDest(),
1428                                       NewArgs);
1429        cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
1430        cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
1431      } else {
1432        NewCaller = CallInst::Create(NewCallee, NewArgs);
1433        if (cast<CallInst>(Caller)->isTailCall())
1434          cast<CallInst>(NewCaller)->setTailCall();
1435        cast<CallInst>(NewCaller)->
1436          setCallingConv(cast<CallInst>(Caller)->getCallingConv());
1437        cast<CallInst>(NewCaller)->setAttributes(NewPAL);
1438      }
1439
1440      return NewCaller;
1441    }
1442  }
1443
1444  // Replace the trampoline call with a direct call.  Since there is no 'nest'
1445  // parameter, there is no need to adjust the argument list.  Let the generic
1446  // code sort out any function type mismatches.
1447  Constant *NewCallee =
1448    NestF->getType() == PTy ? NestF :
1449                              ConstantExpr::getBitCast(NestF, PTy);
1450  CS.setCalledFunction(NewCallee);
1451  return CS.getInstruction();
1452}
1453