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