LLVM API Documentation

InstCombineCalls.cpp
Go to the documentation of this file.
00001 //===- InstCombineCalls.cpp -----------------------------------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements the visitCall and visitInvoke functions.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "InstCombineInternal.h"
00015 #include "llvm/ADT/Statistic.h"
00016 #include "llvm/Analysis/MemoryBuiltins.h"
00017 #include "llvm/IR/CallSite.h"
00018 #include "llvm/IR/DataLayout.h"
00019 #include "llvm/IR/Dominators.h"
00020 #include "llvm/IR/PatternMatch.h"
00021 #include "llvm/IR/Statepoint.h"
00022 #include "llvm/Transforms/Utils/BuildLibCalls.h"
00023 #include "llvm/Transforms/Utils/Local.h"
00024 #include "llvm/Transforms/Utils/SimplifyLibCalls.h"
00025 using namespace llvm;
00026 using namespace PatternMatch;
00027 
00028 #define DEBUG_TYPE "instcombine"
00029 
00030 STATISTIC(NumSimplified, "Number of library calls simplified");
00031 
00032 /// getPromotedType - Return the specified type promoted as it would be to pass
00033 /// though a va_arg area.
00034 static Type *getPromotedType(Type *Ty) {
00035   if (IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
00036     if (ITy->getBitWidth() < 32)
00037       return Type::getInt32Ty(Ty->getContext());
00038   }
00039   return Ty;
00040 }
00041 
00042 /// reduceToSingleValueType - Given an aggregate type which ultimately holds a
00043 /// single scalar element, like {{{type}}} or [1 x type], return type.
00044 static Type *reduceToSingleValueType(Type *T) {
00045   while (!T->isSingleValueType()) {
00046     if (StructType *STy = dyn_cast<StructType>(T)) {
00047       if (STy->getNumElements() == 1)
00048         T = STy->getElementType(0);
00049       else
00050         break;
00051     } else if (ArrayType *ATy = dyn_cast<ArrayType>(T)) {
00052       if (ATy->getNumElements() == 1)
00053         T = ATy->getElementType();
00054       else
00055         break;
00056     } else
00057       break;
00058   }
00059 
00060   return T;
00061 }
00062 
00063 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
00064   unsigned DstAlign = getKnownAlignment(MI->getArgOperand(0), DL, AC, MI, DT);
00065   unsigned SrcAlign = getKnownAlignment(MI->getArgOperand(1), DL, AC, MI, DT);
00066   unsigned MinAlign = std::min(DstAlign, SrcAlign);
00067   unsigned CopyAlign = MI->getAlignment();
00068 
00069   if (CopyAlign < MinAlign) {
00070     MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
00071                                              MinAlign, false));
00072     return MI;
00073   }
00074 
00075   // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
00076   // load/store.
00077   ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getArgOperand(2));
00078   if (!MemOpLength) return nullptr;
00079 
00080   // Source and destination pointer types are always "i8*" for intrinsic.  See
00081   // if the size is something we can handle with a single primitive load/store.
00082   // A single load+store correctly handles overlapping memory in the memmove
00083   // case.
00084   uint64_t Size = MemOpLength->getLimitedValue();
00085   assert(Size && "0-sized memory transferring should be removed already.");
00086 
00087   if (Size > 8 || (Size&(Size-1)))
00088     return nullptr;  // If not 1/2/4/8 bytes, exit.
00089 
00090   // Use an integer load+store unless we can find something better.
00091   unsigned SrcAddrSp =
00092     cast<PointerType>(MI->getArgOperand(1)->getType())->getAddressSpace();
00093   unsigned DstAddrSp =
00094     cast<PointerType>(MI->getArgOperand(0)->getType())->getAddressSpace();
00095 
00096   IntegerType* IntType = IntegerType::get(MI->getContext(), Size<<3);
00097   Type *NewSrcPtrTy = PointerType::get(IntType, SrcAddrSp);
00098   Type *NewDstPtrTy = PointerType::get(IntType, DstAddrSp);
00099 
00100   // Memcpy forces the use of i8* for the source and destination.  That means
00101   // that if you're using memcpy to move one double around, you'll get a cast
00102   // from double* to i8*.  We'd much rather use a double load+store rather than
00103   // an i64 load+store, here because this improves the odds that the source or
00104   // dest address will be promotable.  See if we can find a better type than the
00105   // integer datatype.
00106   Value *StrippedDest = MI->getArgOperand(0)->stripPointerCasts();
00107   MDNode *CopyMD = nullptr;
00108   if (StrippedDest != MI->getArgOperand(0)) {
00109     Type *SrcETy = cast<PointerType>(StrippedDest->getType())
00110                                     ->getElementType();
00111     if (DL && SrcETy->isSized() && DL->getTypeStoreSize(SrcETy) == Size) {
00112       // The SrcETy might be something like {{{double}}} or [1 x double].  Rip
00113       // down through these levels if so.
00114       SrcETy = reduceToSingleValueType(SrcETy);
00115 
00116       if (SrcETy->isSingleValueType()) {
00117         NewSrcPtrTy = PointerType::get(SrcETy, SrcAddrSp);
00118         NewDstPtrTy = PointerType::get(SrcETy, DstAddrSp);
00119 
00120         // If the memcpy has metadata describing the members, see if we can
00121         // get the TBAA tag describing our copy.
00122         if (MDNode *M = MI->getMetadata(LLVMContext::MD_tbaa_struct)) {
00123           if (M->getNumOperands() == 3 && M->getOperand(0) &&
00124               mdconst::hasa<ConstantInt>(M->getOperand(0)) &&
00125               mdconst::extract<ConstantInt>(M->getOperand(0))->isNullValue() &&
00126               M->getOperand(1) &&
00127               mdconst::hasa<ConstantInt>(M->getOperand(1)) &&
00128               mdconst::extract<ConstantInt>(M->getOperand(1))->getValue() ==
00129                   Size &&
00130               M->getOperand(2) && isa<MDNode>(M->getOperand(2)))
00131             CopyMD = cast<MDNode>(M->getOperand(2));
00132         }
00133       }
00134     }
00135   }
00136 
00137   // If the memcpy/memmove provides better alignment info than we can
00138   // infer, use it.
00139   SrcAlign = std::max(SrcAlign, CopyAlign);
00140   DstAlign = std::max(DstAlign, CopyAlign);
00141 
00142   Value *Src = Builder->CreateBitCast(MI->getArgOperand(1), NewSrcPtrTy);
00143   Value *Dest = Builder->CreateBitCast(MI->getArgOperand(0), NewDstPtrTy);
00144   LoadInst *L = Builder->CreateLoad(Src, MI->isVolatile());
00145   L->setAlignment(SrcAlign);
00146   if (CopyMD)
00147     L->setMetadata(LLVMContext::MD_tbaa, CopyMD);
00148   StoreInst *S = Builder->CreateStore(L, Dest, MI->isVolatile());
00149   S->setAlignment(DstAlign);
00150   if (CopyMD)
00151     S->setMetadata(LLVMContext::MD_tbaa, CopyMD);
00152 
00153   // Set the size of the copy to 0, it will be deleted on the next iteration.
00154   MI->setArgOperand(2, Constant::getNullValue(MemOpLength->getType()));
00155   return MI;
00156 }
00157 
00158 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
00159   unsigned Alignment = getKnownAlignment(MI->getDest(), DL, AC, MI, DT);
00160   if (MI->getAlignment() < Alignment) {
00161     MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
00162                                              Alignment, false));
00163     return MI;
00164   }
00165 
00166   // Extract the length and alignment and fill if they are constant.
00167   ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
00168   ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
00169   if (!LenC || !FillC || !FillC->getType()->isIntegerTy(8))
00170     return nullptr;
00171   uint64_t Len = LenC->getLimitedValue();
00172   Alignment = MI->getAlignment();
00173   assert(Len && "0-sized memory setting should be removed already.");
00174 
00175   // memset(s,c,n) -> store s, c (for n=1,2,4,8)
00176   if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
00177     Type *ITy = IntegerType::get(MI->getContext(), Len*8);  // n=1 -> i8.
00178 
00179     Value *Dest = MI->getDest();
00180     unsigned DstAddrSp = cast<PointerType>(Dest->getType())->getAddressSpace();
00181     Type *NewDstPtrTy = PointerType::get(ITy, DstAddrSp);
00182     Dest = Builder->CreateBitCast(Dest, NewDstPtrTy);
00183 
00184     // Alignment 0 is identity for alignment 1 for memset, but not store.
00185     if (Alignment == 0) Alignment = 1;
00186 
00187     // Extract the fill value and store.
00188     uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
00189     StoreInst *S = Builder->CreateStore(ConstantInt::get(ITy, Fill), Dest,
00190                                         MI->isVolatile());
00191     S->setAlignment(Alignment);
00192 
00193     // Set the size of the copy to 0, it will be deleted on the next iteration.
00194     MI->setLength(Constant::getNullValue(LenC->getType()));
00195     return MI;
00196   }
00197 
00198   return nullptr;
00199 }
00200 
00201 /// visitCallInst - CallInst simplification.  This mostly only handles folding
00202 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
00203 /// the heavy lifting.
00204 ///
00205 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
00206   if (isFreeCall(&CI, TLI))
00207     return visitFree(CI);
00208 
00209   // If the caller function is nounwind, mark the call as nounwind, even if the
00210   // callee isn't.
00211   if (CI.getParent()->getParent()->doesNotThrow() &&
00212       !CI.doesNotThrow()) {
00213     CI.setDoesNotThrow();
00214     return &CI;
00215   }
00216 
00217   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
00218   if (!II) return visitCallSite(&CI);
00219 
00220   // Intrinsics cannot occur in an invoke, so handle them here instead of in
00221   // visitCallSite.
00222   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
00223     bool Changed = false;
00224 
00225     // memmove/cpy/set of zero bytes is a noop.
00226     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
00227       if (NumBytes->isNullValue())
00228         return EraseInstFromFunction(CI);
00229 
00230       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
00231         if (CI->getZExtValue() == 1) {
00232           // Replace the instruction with just byte operations.  We would
00233           // transform other cases to loads/stores, but we don't know if
00234           // alignment is sufficient.
00235         }
00236     }
00237 
00238     // No other transformations apply to volatile transfers.
00239     if (MI->isVolatile())
00240       return nullptr;
00241 
00242     // If we have a memmove and the source operation is a constant global,
00243     // then the source and dest pointers can't alias, so we can change this
00244     // into a call to memcpy.
00245     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
00246       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
00247         if (GVSrc->isConstant()) {
00248           Module *M = CI.getParent()->getParent()->getParent();
00249           Intrinsic::ID MemCpyID = Intrinsic::memcpy;
00250           Type *Tys[3] = { CI.getArgOperand(0)->getType(),
00251                            CI.getArgOperand(1)->getType(),
00252                            CI.getArgOperand(2)->getType() };
00253           CI.setCalledFunction(Intrinsic::getDeclaration(M, MemCpyID, Tys));
00254           Changed = true;
00255         }
00256     }
00257 
00258     if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) {
00259       // memmove(x,x,size) -> noop.
00260       if (MTI->getSource() == MTI->getDest())
00261         return EraseInstFromFunction(CI);
00262     }
00263 
00264     // If we can determine a pointer alignment that is bigger than currently
00265     // set, update the alignment.
00266     if (isa<MemTransferInst>(MI)) {
00267       if (Instruction *I = SimplifyMemTransfer(MI))
00268         return I;
00269     } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
00270       if (Instruction *I = SimplifyMemSet(MSI))
00271         return I;
00272     }
00273 
00274     if (Changed) return II;
00275   }
00276 
00277   switch (II->getIntrinsicID()) {
00278   default: break;
00279   case Intrinsic::objectsize: {
00280     uint64_t Size;
00281     if (getObjectSize(II->getArgOperand(0), Size, DL, TLI))
00282       return ReplaceInstUsesWith(CI, ConstantInt::get(CI.getType(), Size));
00283     return nullptr;
00284   }
00285   case Intrinsic::bswap: {
00286     Value *IIOperand = II->getArgOperand(0);
00287     Value *X = nullptr;
00288 
00289     // bswap(bswap(x)) -> x
00290     if (match(IIOperand, m_BSwap(m_Value(X))))
00291         return ReplaceInstUsesWith(CI, X);
00292 
00293     // bswap(trunc(bswap(x))) -> trunc(lshr(x, c))
00294     if (match(IIOperand, m_Trunc(m_BSwap(m_Value(X))))) {
00295       unsigned C = X->getType()->getPrimitiveSizeInBits() -
00296         IIOperand->getType()->getPrimitiveSizeInBits();
00297       Value *CV = ConstantInt::get(X->getType(), C);
00298       Value *V = Builder->CreateLShr(X, CV);
00299       return new TruncInst(V, IIOperand->getType());
00300     }
00301     break;
00302   }
00303 
00304   case Intrinsic::powi:
00305     if (ConstantInt *Power = dyn_cast<ConstantInt>(II->getArgOperand(1))) {
00306       // powi(x, 0) -> 1.0
00307       if (Power->isZero())
00308         return ReplaceInstUsesWith(CI, ConstantFP::get(CI.getType(), 1.0));
00309       // powi(x, 1) -> x
00310       if (Power->isOne())
00311         return ReplaceInstUsesWith(CI, II->getArgOperand(0));
00312       // powi(x, -1) -> 1/x
00313       if (Power->isAllOnesValue())
00314         return BinaryOperator::CreateFDiv(ConstantFP::get(CI.getType(), 1.0),
00315                                           II->getArgOperand(0));
00316     }
00317     break;
00318   case Intrinsic::cttz: {
00319     // If all bits below the first known one are known zero,
00320     // this value is constant.
00321     IntegerType *IT = dyn_cast<IntegerType>(II->getArgOperand(0)->getType());
00322     // FIXME: Try to simplify vectors of integers.
00323     if (!IT) break;
00324     uint32_t BitWidth = IT->getBitWidth();
00325     APInt KnownZero(BitWidth, 0);
00326     APInt KnownOne(BitWidth, 0);
00327     computeKnownBits(II->getArgOperand(0), KnownZero, KnownOne, 0, II);
00328     unsigned TrailingZeros = KnownOne.countTrailingZeros();
00329     APInt Mask(APInt::getLowBitsSet(BitWidth, TrailingZeros));
00330     if ((Mask & KnownZero) == Mask)
00331       return ReplaceInstUsesWith(CI, ConstantInt::get(IT,
00332                                  APInt(BitWidth, TrailingZeros)));
00333 
00334     }
00335     break;
00336   case Intrinsic::ctlz: {
00337     // If all bits above the first known one are known zero,
00338     // this value is constant.
00339     IntegerType *IT = dyn_cast<IntegerType>(II->getArgOperand(0)->getType());
00340     // FIXME: Try to simplify vectors of integers.
00341     if (!IT) break;
00342     uint32_t BitWidth = IT->getBitWidth();
00343     APInt KnownZero(BitWidth, 0);
00344     APInt KnownOne(BitWidth, 0);
00345     computeKnownBits(II->getArgOperand(0), KnownZero, KnownOne, 0, II);
00346     unsigned LeadingZeros = KnownOne.countLeadingZeros();
00347     APInt Mask(APInt::getHighBitsSet(BitWidth, LeadingZeros));
00348     if ((Mask & KnownZero) == Mask)
00349       return ReplaceInstUsesWith(CI, ConstantInt::get(IT,
00350                                  APInt(BitWidth, LeadingZeros)));
00351 
00352     }
00353     break;
00354   case Intrinsic::uadd_with_overflow: {
00355     Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
00356     OverflowResult OR = computeOverflowForUnsignedAdd(LHS, RHS, II);
00357     if (OR == OverflowResult::NeverOverflows)
00358       return CreateOverflowTuple(II, Builder->CreateNUWAdd(LHS, RHS), false);
00359     if (OR == OverflowResult::AlwaysOverflows)
00360       return CreateOverflowTuple(II, Builder->CreateAdd(LHS, RHS), true);
00361   }
00362   // FALL THROUGH uadd into sadd
00363   case Intrinsic::sadd_with_overflow:
00364     // Canonicalize constants into the RHS.
00365     if (isa<Constant>(II->getArgOperand(0)) &&
00366         !isa<Constant>(II->getArgOperand(1))) {
00367       Value *LHS = II->getArgOperand(0);
00368       II->setArgOperand(0, II->getArgOperand(1));
00369       II->setArgOperand(1, LHS);
00370       return II;
00371     }
00372 
00373     // X + undef -> undef
00374     if (isa<UndefValue>(II->getArgOperand(1)))
00375       return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
00376 
00377     if (ConstantInt *RHS = dyn_cast<ConstantInt>(II->getArgOperand(1))) {
00378       // X + 0 -> {X, false}
00379       if (RHS->isZero()) {
00380         return CreateOverflowTuple(II, II->getArgOperand(0), false,
00381                                     /*ReUseName*/false);
00382       }
00383     }
00384 
00385     // We can strength reduce reduce this signed add into a regular add if we
00386     // can prove that it will never overflow.
00387     if (II->getIntrinsicID() == Intrinsic::sadd_with_overflow) {
00388       Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
00389       if (WillNotOverflowSignedAdd(LHS, RHS, II)) {
00390         return CreateOverflowTuple(II, Builder->CreateNSWAdd(LHS, RHS), false);
00391       }
00392     }
00393 
00394     break;
00395   case Intrinsic::usub_with_overflow:
00396   case Intrinsic::ssub_with_overflow: {
00397     Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
00398     // undef - X -> undef
00399     // X - undef -> undef
00400     if (isa<UndefValue>(LHS) || isa<UndefValue>(RHS))
00401       return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
00402 
00403     if (ConstantInt *ConstRHS = dyn_cast<ConstantInt>(RHS)) {
00404       // X - 0 -> {X, false}
00405       if (ConstRHS->isZero()) {
00406         return CreateOverflowTuple(II, LHS, false, /*ReUseName*/false);
00407       }
00408     }
00409     if (II->getIntrinsicID() == Intrinsic::ssub_with_overflow) {
00410       if (WillNotOverflowSignedSub(LHS, RHS, II)) {
00411         return CreateOverflowTuple(II, Builder->CreateNSWSub(LHS, RHS), false);
00412       }
00413     } else {
00414       if (WillNotOverflowUnsignedSub(LHS, RHS, II)) {
00415         return CreateOverflowTuple(II, Builder->CreateNUWSub(LHS, RHS), false);
00416       }
00417     }
00418     break;
00419   }
00420   case Intrinsic::umul_with_overflow: {
00421     Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
00422     OverflowResult OR = computeOverflowForUnsignedMul(LHS, RHS, II);
00423     if (OR == OverflowResult::NeverOverflows)
00424       return CreateOverflowTuple(II, Builder->CreateNUWMul(LHS, RHS), false);
00425     if (OR == OverflowResult::AlwaysOverflows)
00426       return CreateOverflowTuple(II, Builder->CreateMul(LHS, RHS), true);
00427   } // FALL THROUGH
00428   case Intrinsic::smul_with_overflow:
00429     // Canonicalize constants into the RHS.
00430     if (isa<Constant>(II->getArgOperand(0)) &&
00431         !isa<Constant>(II->getArgOperand(1))) {
00432       Value *LHS = II->getArgOperand(0);
00433       II->setArgOperand(0, II->getArgOperand(1));
00434       II->setArgOperand(1, LHS);
00435       return II;
00436     }
00437 
00438     // X * undef -> undef
00439     if (isa<UndefValue>(II->getArgOperand(1)))
00440       return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
00441 
00442     if (ConstantInt *RHSI = dyn_cast<ConstantInt>(II->getArgOperand(1))) {
00443       // X*0 -> {0, false}
00444       if (RHSI->isZero())
00445         return ReplaceInstUsesWith(CI, Constant::getNullValue(II->getType()));
00446 
00447       // X * 1 -> {X, false}
00448       if (RHSI->equalsInt(1)) {
00449         return CreateOverflowTuple(II, II->getArgOperand(0), false,
00450                                     /*ReUseName*/false);
00451       }
00452     }
00453     if (II->getIntrinsicID() == Intrinsic::smul_with_overflow) {
00454       Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
00455       if (WillNotOverflowSignedMul(LHS, RHS, II)) {
00456         return CreateOverflowTuple(II, Builder->CreateNSWMul(LHS, RHS), false);
00457       }
00458     }
00459     break;
00460   case Intrinsic::minnum:
00461   case Intrinsic::maxnum: {
00462     Value *Arg0 = II->getArgOperand(0);
00463     Value *Arg1 = II->getArgOperand(1);
00464 
00465     // fmin(x, x) -> x
00466     if (Arg0 == Arg1)
00467       return ReplaceInstUsesWith(CI, Arg0);
00468 
00469     const ConstantFP *C0 = dyn_cast<ConstantFP>(Arg0);
00470     const ConstantFP *C1 = dyn_cast<ConstantFP>(Arg1);
00471 
00472     // Canonicalize constants into the RHS.
00473     if (C0 && !C1) {
00474       II->setArgOperand(0, Arg1);
00475       II->setArgOperand(1, Arg0);
00476       return II;
00477     }
00478 
00479     // fmin(x, nan) -> x
00480     if (C1 && C1->isNaN())
00481       return ReplaceInstUsesWith(CI, Arg0);
00482 
00483     // This is the value because if undef were NaN, we would return the other
00484     // value and cannot return a NaN unless both operands are.
00485     //
00486     // fmin(undef, x) -> x
00487     if (isa<UndefValue>(Arg0))
00488       return ReplaceInstUsesWith(CI, Arg1);
00489 
00490     // fmin(x, undef) -> x
00491     if (isa<UndefValue>(Arg1))
00492       return ReplaceInstUsesWith(CI, Arg0);
00493 
00494     Value *X = nullptr;
00495     Value *Y = nullptr;
00496     if (II->getIntrinsicID() == Intrinsic::minnum) {
00497       // fmin(x, fmin(x, y)) -> fmin(x, y)
00498       // fmin(y, fmin(x, y)) -> fmin(x, y)
00499       if (match(Arg1, m_FMin(m_Value(X), m_Value(Y)))) {
00500         if (Arg0 == X || Arg0 == Y)
00501           return ReplaceInstUsesWith(CI, Arg1);
00502       }
00503 
00504       // fmin(fmin(x, y), x) -> fmin(x, y)
00505       // fmin(fmin(x, y), y) -> fmin(x, y)
00506       if (match(Arg0, m_FMin(m_Value(X), m_Value(Y)))) {
00507         if (Arg1 == X || Arg1 == Y)
00508           return ReplaceInstUsesWith(CI, Arg0);
00509       }
00510 
00511       // TODO: fmin(nnan x, inf) -> x
00512       // TODO: fmin(nnan ninf x, flt_max) -> x
00513       if (C1 && C1->isInfinity()) {
00514         // fmin(x, -inf) -> -inf
00515         if (C1->isNegative())
00516           return ReplaceInstUsesWith(CI, Arg1);
00517       }
00518     } else {
00519       assert(II->getIntrinsicID() == Intrinsic::maxnum);
00520       // fmax(x, fmax(x, y)) -> fmax(x, y)
00521       // fmax(y, fmax(x, y)) -> fmax(x, y)
00522       if (match(Arg1, m_FMax(m_Value(X), m_Value(Y)))) {
00523         if (Arg0 == X || Arg0 == Y)
00524           return ReplaceInstUsesWith(CI, Arg1);
00525       }
00526 
00527       // fmax(fmax(x, y), x) -> fmax(x, y)
00528       // fmax(fmax(x, y), y) -> fmax(x, y)
00529       if (match(Arg0, m_FMax(m_Value(X), m_Value(Y)))) {
00530         if (Arg1 == X || Arg1 == Y)
00531           return ReplaceInstUsesWith(CI, Arg0);
00532       }
00533 
00534       // TODO: fmax(nnan x, -inf) -> x
00535       // TODO: fmax(nnan ninf x, -flt_max) -> x
00536       if (C1 && C1->isInfinity()) {
00537         // fmax(x, inf) -> inf
00538         if (!C1->isNegative())
00539           return ReplaceInstUsesWith(CI, Arg1);
00540       }
00541     }
00542     break;
00543   }
00544   case Intrinsic::ppc_altivec_lvx:
00545   case Intrinsic::ppc_altivec_lvxl:
00546     // Turn PPC lvx -> load if the pointer is known aligned.
00547     if (getOrEnforceKnownAlignment(II->getArgOperand(0), 16, DL, AC, II, DT) >=
00548         16) {
00549       Value *Ptr = Builder->CreateBitCast(II->getArgOperand(0),
00550                                          PointerType::getUnqual(II->getType()));
00551       return new LoadInst(Ptr);
00552     }
00553     break;
00554   case Intrinsic::ppc_vsx_lxvw4x:
00555   case Intrinsic::ppc_vsx_lxvd2x: {
00556     // Turn PPC VSX loads into normal loads.
00557     Value *Ptr = Builder->CreateBitCast(II->getArgOperand(0),
00558                                         PointerType::getUnqual(II->getType()));
00559     return new LoadInst(Ptr, Twine(""), false, 1);
00560   }
00561   case Intrinsic::ppc_altivec_stvx:
00562   case Intrinsic::ppc_altivec_stvxl:
00563     // Turn stvx -> store if the pointer is known aligned.
00564     if (getOrEnforceKnownAlignment(II->getArgOperand(1), 16, DL, AC, II, DT) >=
00565         16) {
00566       Type *OpPtrTy =
00567         PointerType::getUnqual(II->getArgOperand(0)->getType());
00568       Value *Ptr = Builder->CreateBitCast(II->getArgOperand(1), OpPtrTy);
00569       return new StoreInst(II->getArgOperand(0), Ptr);
00570     }
00571     break;
00572   case Intrinsic::ppc_vsx_stxvw4x:
00573   case Intrinsic::ppc_vsx_stxvd2x: {
00574     // Turn PPC VSX stores into normal stores.
00575     Type *OpPtrTy = PointerType::getUnqual(II->getArgOperand(0)->getType());
00576     Value *Ptr = Builder->CreateBitCast(II->getArgOperand(1), OpPtrTy);
00577     return new StoreInst(II->getArgOperand(0), Ptr, false, 1);
00578   }
00579   case Intrinsic::x86_sse_storeu_ps:
00580   case Intrinsic::x86_sse2_storeu_pd:
00581   case Intrinsic::x86_sse2_storeu_dq:
00582     // Turn X86 storeu -> store if the pointer is known aligned.
00583     if (getOrEnforceKnownAlignment(II->getArgOperand(0), 16, DL, AC, II, DT) >=
00584         16) {
00585       Type *OpPtrTy =
00586         PointerType::getUnqual(II->getArgOperand(1)->getType());
00587       Value *Ptr = Builder->CreateBitCast(II->getArgOperand(0), OpPtrTy);
00588       return new StoreInst(II->getArgOperand(1), Ptr);
00589     }
00590     break;
00591 
00592   case Intrinsic::x86_sse_cvtss2si:
00593   case Intrinsic::x86_sse_cvtss2si64:
00594   case Intrinsic::x86_sse_cvttss2si:
00595   case Intrinsic::x86_sse_cvttss2si64:
00596   case Intrinsic::x86_sse2_cvtsd2si:
00597   case Intrinsic::x86_sse2_cvtsd2si64:
00598   case Intrinsic::x86_sse2_cvttsd2si:
00599   case Intrinsic::x86_sse2_cvttsd2si64: {
00600     // These intrinsics only demand the 0th element of their input vectors. If
00601     // we can simplify the input based on that, do so now.
00602     unsigned VWidth =
00603       cast<VectorType>(II->getArgOperand(0)->getType())->getNumElements();
00604     APInt DemandedElts(VWidth, 1);
00605     APInt UndefElts(VWidth, 0);
00606     if (Value *V = SimplifyDemandedVectorElts(II->getArgOperand(0),
00607                                               DemandedElts, UndefElts)) {
00608       II->setArgOperand(0, V);
00609       return II;
00610     }
00611     break;
00612   }
00613 
00614   // Constant fold <A x Bi> << Ci.
00615   // FIXME: We don't handle _dq because it's a shift of an i128, but is
00616   // represented in the IR as <2 x i64>. A per element shift is wrong.
00617   case Intrinsic::x86_sse2_psll_d:
00618   case Intrinsic::x86_sse2_psll_q:
00619   case Intrinsic::x86_sse2_psll_w:
00620   case Intrinsic::x86_sse2_pslli_d:
00621   case Intrinsic::x86_sse2_pslli_q:
00622   case Intrinsic::x86_sse2_pslli_w:
00623   case Intrinsic::x86_avx2_psll_d:
00624   case Intrinsic::x86_avx2_psll_q:
00625   case Intrinsic::x86_avx2_psll_w:
00626   case Intrinsic::x86_avx2_pslli_d:
00627   case Intrinsic::x86_avx2_pslli_q:
00628   case Intrinsic::x86_avx2_pslli_w:
00629   case Intrinsic::x86_sse2_psrl_d:
00630   case Intrinsic::x86_sse2_psrl_q:
00631   case Intrinsic::x86_sse2_psrl_w:
00632   case Intrinsic::x86_sse2_psrli_d:
00633   case Intrinsic::x86_sse2_psrli_q:
00634   case Intrinsic::x86_sse2_psrli_w:
00635   case Intrinsic::x86_avx2_psrl_d:
00636   case Intrinsic::x86_avx2_psrl_q:
00637   case Intrinsic::x86_avx2_psrl_w:
00638   case Intrinsic::x86_avx2_psrli_d:
00639   case Intrinsic::x86_avx2_psrli_q:
00640   case Intrinsic::x86_avx2_psrli_w: {
00641     // Simplify if count is constant. To 0 if >= BitWidth,
00642     // otherwise to shl/lshr.
00643     auto CDV = dyn_cast<ConstantDataVector>(II->getArgOperand(1));
00644     auto CInt = dyn_cast<ConstantInt>(II->getArgOperand(1));
00645     if (!CDV && !CInt)
00646       break;
00647     ConstantInt *Count;
00648     if (CDV)
00649       Count = cast<ConstantInt>(CDV->getElementAsConstant(0));
00650     else
00651       Count = CInt;
00652 
00653     auto Vec = II->getArgOperand(0);
00654     auto VT = cast<VectorType>(Vec->getType());
00655     if (Count->getZExtValue() >
00656         VT->getElementType()->getPrimitiveSizeInBits() - 1)
00657       return ReplaceInstUsesWith(
00658           CI, ConstantAggregateZero::get(Vec->getType()));
00659 
00660     bool isPackedShiftLeft = true;
00661     switch (II->getIntrinsicID()) {
00662     default : break;
00663     case Intrinsic::x86_sse2_psrl_d:
00664     case Intrinsic::x86_sse2_psrl_q:
00665     case Intrinsic::x86_sse2_psrl_w:
00666     case Intrinsic::x86_sse2_psrli_d:
00667     case Intrinsic::x86_sse2_psrli_q:
00668     case Intrinsic::x86_sse2_psrli_w:
00669     case Intrinsic::x86_avx2_psrl_d:
00670     case Intrinsic::x86_avx2_psrl_q:
00671     case Intrinsic::x86_avx2_psrl_w:
00672     case Intrinsic::x86_avx2_psrli_d:
00673     case Intrinsic::x86_avx2_psrli_q:
00674     case Intrinsic::x86_avx2_psrli_w: isPackedShiftLeft = false; break;
00675     }
00676 
00677     unsigned VWidth = VT->getNumElements();
00678     // Get a constant vector of the same type as the first operand.
00679     auto VTCI = ConstantInt::get(VT->getElementType(), Count->getZExtValue());
00680     if (isPackedShiftLeft)
00681       return BinaryOperator::CreateShl(Vec,
00682           Builder->CreateVectorSplat(VWidth, VTCI));
00683 
00684     return BinaryOperator::CreateLShr(Vec,
00685         Builder->CreateVectorSplat(VWidth, VTCI));
00686   }
00687 
00688   case Intrinsic::x86_sse41_pmovsxbw:
00689   case Intrinsic::x86_sse41_pmovsxwd:
00690   case Intrinsic::x86_sse41_pmovsxdq:
00691   case Intrinsic::x86_sse41_pmovzxbw:
00692   case Intrinsic::x86_sse41_pmovzxwd:
00693   case Intrinsic::x86_sse41_pmovzxdq: {
00694     // pmov{s|z}x ignores the upper half of their input vectors.
00695     unsigned VWidth =
00696       cast<VectorType>(II->getArgOperand(0)->getType())->getNumElements();
00697     unsigned LowHalfElts = VWidth / 2;
00698     APInt InputDemandedElts(APInt::getBitsSet(VWidth, 0, LowHalfElts));
00699     APInt UndefElts(VWidth, 0);
00700     if (Value *TmpV = SimplifyDemandedVectorElts(II->getArgOperand(0),
00701                                                  InputDemandedElts,
00702                                                  UndefElts)) {
00703       II->setArgOperand(0, TmpV);
00704       return II;
00705     }
00706     break;
00707   }
00708 
00709   case Intrinsic::x86_sse4a_insertqi: {
00710     // insertqi x, y, 64, 0 can just copy y's lower bits and leave the top
00711     // ones undef
00712     // TODO: eventually we should lower this intrinsic to IR
00713     if (auto CIWidth = dyn_cast<ConstantInt>(II->getArgOperand(2))) {
00714       if (auto CIStart = dyn_cast<ConstantInt>(II->getArgOperand(3))) {
00715         unsigned Index = CIStart->getZExtValue();
00716         // From AMD documentation: "a value of zero in the field length is
00717         // defined as length of 64".
00718         unsigned Length = CIWidth->equalsInt(0) ? 64 : CIWidth->getZExtValue();
00719 
00720         // From AMD documentation: "If the sum of the bit index + length field
00721         // is greater than 64, the results are undefined".
00722 
00723         // Note that both field index and field length are 8-bit quantities.
00724         // Since variables 'Index' and 'Length' are unsigned values
00725         // obtained from zero-extending field index and field length
00726         // respectively, their sum should never wrap around.
00727         if ((Index + Length) > 64)
00728           return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
00729 
00730         if (Length == 64 && Index == 0) {
00731           Value *Vec = II->getArgOperand(1);
00732           Value *Undef = UndefValue::get(Vec->getType());
00733           const uint32_t Mask[] = { 0, 2 };
00734           return ReplaceInstUsesWith(
00735               CI,
00736               Builder->CreateShuffleVector(
00737                   Vec, Undef, ConstantDataVector::get(
00738                                   II->getContext(), makeArrayRef(Mask))));
00739 
00740         } else if (auto Source =
00741                        dyn_cast<IntrinsicInst>(II->getArgOperand(0))) {
00742           if (Source->hasOneUse() &&
00743               Source->getArgOperand(1) == II->getArgOperand(1)) {
00744             // If the source of the insert has only one use and it's another
00745             // insert (and they're both inserting from the same vector), try to
00746             // bundle both together.
00747             auto CISourceWidth =
00748                 dyn_cast<ConstantInt>(Source->getArgOperand(2));
00749             auto CISourceStart =
00750                 dyn_cast<ConstantInt>(Source->getArgOperand(3));
00751             if (CISourceStart && CISourceWidth) {
00752               unsigned Start = CIStart->getZExtValue();
00753               unsigned Width = CIWidth->getZExtValue();
00754               unsigned End = Start + Width;
00755               unsigned SourceStart = CISourceStart->getZExtValue();
00756               unsigned SourceWidth = CISourceWidth->getZExtValue();
00757               unsigned SourceEnd = SourceStart + SourceWidth;
00758               unsigned NewStart, NewWidth;
00759               bool ShouldReplace = false;
00760               if (Start <= SourceStart && SourceStart <= End) {
00761                 NewStart = Start;
00762                 NewWidth = std::max(End, SourceEnd) - NewStart;
00763                 ShouldReplace = true;
00764               } else if (SourceStart <= Start && Start <= SourceEnd) {
00765                 NewStart = SourceStart;
00766                 NewWidth = std::max(SourceEnd, End) - NewStart;
00767                 ShouldReplace = true;
00768               }
00769 
00770               if (ShouldReplace) {
00771                 Constant *ConstantWidth = ConstantInt::get(
00772                     II->getArgOperand(2)->getType(), NewWidth, false);
00773                 Constant *ConstantStart = ConstantInt::get(
00774                     II->getArgOperand(3)->getType(), NewStart, false);
00775                 Value *Args[4] = { Source->getArgOperand(0),
00776                                    II->getArgOperand(1), ConstantWidth,
00777                                    ConstantStart };
00778                 Module *M = CI.getParent()->getParent()->getParent();
00779                 Value *F =
00780                     Intrinsic::getDeclaration(M, Intrinsic::x86_sse4a_insertqi);
00781                 return ReplaceInstUsesWith(CI, Builder->CreateCall(F, Args));
00782               }
00783             }
00784           }
00785         }
00786       }
00787     }
00788     break;
00789   }
00790 
00791   case Intrinsic::x86_sse41_pblendvb:
00792   case Intrinsic::x86_sse41_blendvps:
00793   case Intrinsic::x86_sse41_blendvpd:
00794   case Intrinsic::x86_avx_blendv_ps_256:
00795   case Intrinsic::x86_avx_blendv_pd_256:
00796   case Intrinsic::x86_avx2_pblendvb: {
00797     // Convert blendv* to vector selects if the mask is constant.
00798     // This optimization is convoluted because the intrinsic is defined as
00799     // getting a vector of floats or doubles for the ps and pd versions.
00800     // FIXME: That should be changed.
00801     Value *Mask = II->getArgOperand(2);
00802     if (auto C = dyn_cast<ConstantDataVector>(Mask)) {
00803       auto Tyi1 = Builder->getInt1Ty();
00804       auto SelectorType = cast<VectorType>(Mask->getType());
00805       auto EltTy = SelectorType->getElementType();
00806       unsigned Size = SelectorType->getNumElements();
00807       unsigned BitWidth =
00808           EltTy->isFloatTy()
00809               ? 32
00810               : (EltTy->isDoubleTy() ? 64 : EltTy->getIntegerBitWidth());
00811       assert((BitWidth == 64 || BitWidth == 32 || BitWidth == 8) &&
00812              "Wrong arguments for variable blend intrinsic");
00813       SmallVector<Constant *, 32> Selectors;
00814       for (unsigned I = 0; I < Size; ++I) {
00815         // The intrinsics only read the top bit
00816         uint64_t Selector;
00817         if (BitWidth == 8)
00818           Selector = C->getElementAsInteger(I);
00819         else
00820           Selector = C->getElementAsAPFloat(I).bitcastToAPInt().getZExtValue();
00821         Selectors.push_back(ConstantInt::get(Tyi1, Selector >> (BitWidth - 1)));
00822       }
00823       auto NewSelector = ConstantVector::get(Selectors);
00824       return SelectInst::Create(NewSelector, II->getArgOperand(1),
00825                                 II->getArgOperand(0), "blendv");
00826     } else {
00827       break;
00828     }
00829   }
00830 
00831   case Intrinsic::x86_avx_vpermilvar_ps:
00832   case Intrinsic::x86_avx_vpermilvar_ps_256:
00833   case Intrinsic::x86_avx_vpermilvar_pd:
00834   case Intrinsic::x86_avx_vpermilvar_pd_256: {
00835     // Convert vpermil* to shufflevector if the mask is constant.
00836     Value *V = II->getArgOperand(1);
00837     unsigned Size = cast<VectorType>(V->getType())->getNumElements();
00838     assert(Size == 8 || Size == 4 || Size == 2);
00839     uint32_t Indexes[8];
00840     if (auto C = dyn_cast<ConstantDataVector>(V)) {
00841       // The intrinsics only read one or two bits, clear the rest.
00842       for (unsigned I = 0; I < Size; ++I) {
00843         uint32_t Index = C->getElementAsInteger(I) & 0x3;
00844         if (II->getIntrinsicID() == Intrinsic::x86_avx_vpermilvar_pd ||
00845             II->getIntrinsicID() == Intrinsic::x86_avx_vpermilvar_pd_256)
00846           Index >>= 1;
00847         Indexes[I] = Index;
00848       }
00849     } else if (isa<ConstantAggregateZero>(V)) {
00850       for (unsigned I = 0; I < Size; ++I)
00851         Indexes[I] = 0;
00852     } else {
00853       break;
00854     }
00855     // The _256 variants are a bit trickier since the mask bits always index
00856     // into the corresponding 128 half. In order to convert to a generic
00857     // shuffle, we have to make that explicit.
00858     if (II->getIntrinsicID() == Intrinsic::x86_avx_vpermilvar_ps_256 ||
00859         II->getIntrinsicID() == Intrinsic::x86_avx_vpermilvar_pd_256) {
00860       for (unsigned I = Size / 2; I < Size; ++I)
00861         Indexes[I] += Size / 2;
00862     }
00863     auto NewC =
00864         ConstantDataVector::get(V->getContext(), makeArrayRef(Indexes, Size));
00865     auto V1 = II->getArgOperand(0);
00866     auto V2 = UndefValue::get(V1->getType());
00867     auto Shuffle = Builder->CreateShuffleVector(V1, V2, NewC);
00868     return ReplaceInstUsesWith(CI, Shuffle);
00869   }
00870 
00871   case Intrinsic::ppc_altivec_vperm:
00872     // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
00873     // Note that ppc_altivec_vperm has a big-endian bias, so when creating
00874     // a vectorshuffle for little endian, we must undo the transformation
00875     // performed on vec_perm in altivec.h.  That is, we must complement
00876     // the permutation mask with respect to 31 and reverse the order of
00877     // V1 and V2.
00878     if (Constant *Mask = dyn_cast<Constant>(II->getArgOperand(2))) {
00879       assert(Mask->getType()->getVectorNumElements() == 16 &&
00880              "Bad type for intrinsic!");
00881 
00882       // Check that all of the elements are integer constants or undefs.
00883       bool AllEltsOk = true;
00884       for (unsigned i = 0; i != 16; ++i) {
00885         Constant *Elt = Mask->getAggregateElement(i);
00886         if (!Elt || !(isa<ConstantInt>(Elt) || isa<UndefValue>(Elt))) {
00887           AllEltsOk = false;
00888           break;
00889         }
00890       }
00891 
00892       if (AllEltsOk) {
00893         // Cast the input vectors to byte vectors.
00894         Value *Op0 = Builder->CreateBitCast(II->getArgOperand(0),
00895                                             Mask->getType());
00896         Value *Op1 = Builder->CreateBitCast(II->getArgOperand(1),
00897                                             Mask->getType());
00898         Value *Result = UndefValue::get(Op0->getType());
00899 
00900         // Only extract each element once.
00901         Value *ExtractedElts[32];
00902         memset(ExtractedElts, 0, sizeof(ExtractedElts));
00903 
00904         for (unsigned i = 0; i != 16; ++i) {
00905           if (isa<UndefValue>(Mask->getAggregateElement(i)))
00906             continue;
00907           unsigned Idx =
00908             cast<ConstantInt>(Mask->getAggregateElement(i))->getZExtValue();
00909           Idx &= 31;  // Match the hardware behavior.
00910           if (DL && DL->isLittleEndian())
00911             Idx = 31 - Idx;
00912 
00913           if (!ExtractedElts[Idx]) {
00914             Value *Op0ToUse = (DL && DL->isLittleEndian()) ? Op1 : Op0;
00915             Value *Op1ToUse = (DL && DL->isLittleEndian()) ? Op0 : Op1;
00916             ExtractedElts[Idx] =
00917               Builder->CreateExtractElement(Idx < 16 ? Op0ToUse : Op1ToUse,
00918                                             Builder->getInt32(Idx&15));
00919           }
00920 
00921           // Insert this value into the result vector.
00922           Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
00923                                                 Builder->getInt32(i));
00924         }
00925         return CastInst::Create(Instruction::BitCast, Result, CI.getType());
00926       }
00927     }
00928     break;
00929 
00930   case Intrinsic::arm_neon_vld1:
00931   case Intrinsic::arm_neon_vld2:
00932   case Intrinsic::arm_neon_vld3:
00933   case Intrinsic::arm_neon_vld4:
00934   case Intrinsic::arm_neon_vld2lane:
00935   case Intrinsic::arm_neon_vld3lane:
00936   case Intrinsic::arm_neon_vld4lane:
00937   case Intrinsic::arm_neon_vst1:
00938   case Intrinsic::arm_neon_vst2:
00939   case Intrinsic::arm_neon_vst3:
00940   case Intrinsic::arm_neon_vst4:
00941   case Intrinsic::arm_neon_vst2lane:
00942   case Intrinsic::arm_neon_vst3lane:
00943   case Intrinsic::arm_neon_vst4lane: {
00944     unsigned MemAlign = getKnownAlignment(II->getArgOperand(0), DL, AC, II, DT);
00945     unsigned AlignArg = II->getNumArgOperands() - 1;
00946     ConstantInt *IntrAlign = dyn_cast<ConstantInt>(II->getArgOperand(AlignArg));
00947     if (IntrAlign && IntrAlign->getZExtValue() < MemAlign) {
00948       II->setArgOperand(AlignArg,
00949                         ConstantInt::get(Type::getInt32Ty(II->getContext()),
00950                                          MemAlign, false));
00951       return II;
00952     }
00953     break;
00954   }
00955 
00956   case Intrinsic::arm_neon_vmulls:
00957   case Intrinsic::arm_neon_vmullu:
00958   case Intrinsic::aarch64_neon_smull:
00959   case Intrinsic::aarch64_neon_umull: {
00960     Value *Arg0 = II->getArgOperand(0);
00961     Value *Arg1 = II->getArgOperand(1);
00962 
00963     // Handle mul by zero first:
00964     if (isa<ConstantAggregateZero>(Arg0) || isa<ConstantAggregateZero>(Arg1)) {
00965       return ReplaceInstUsesWith(CI, ConstantAggregateZero::get(II->getType()));
00966     }
00967 
00968     // Check for constant LHS & RHS - in this case we just simplify.
00969     bool Zext = (II->getIntrinsicID() == Intrinsic::arm_neon_vmullu ||
00970                  II->getIntrinsicID() == Intrinsic::aarch64_neon_umull);
00971     VectorType *NewVT = cast<VectorType>(II->getType());
00972     if (Constant *CV0 = dyn_cast<Constant>(Arg0)) {
00973       if (Constant *CV1 = dyn_cast<Constant>(Arg1)) {
00974         CV0 = ConstantExpr::getIntegerCast(CV0, NewVT, /*isSigned=*/!Zext);
00975         CV1 = ConstantExpr::getIntegerCast(CV1, NewVT, /*isSigned=*/!Zext);
00976 
00977         return ReplaceInstUsesWith(CI, ConstantExpr::getMul(CV0, CV1));
00978       }
00979 
00980       // Couldn't simplify - canonicalize constant to the RHS.
00981       std::swap(Arg0, Arg1);
00982     }
00983 
00984     // Handle mul by one:
00985     if (Constant *CV1 = dyn_cast<Constant>(Arg1))
00986       if (ConstantInt *Splat =
00987               dyn_cast_or_null<ConstantInt>(CV1->getSplatValue()))
00988         if (Splat->isOne())
00989           return CastInst::CreateIntegerCast(Arg0, II->getType(),
00990                                              /*isSigned=*/!Zext);
00991 
00992     break;
00993   }
00994 
00995   case Intrinsic::AMDGPU_rcp: {
00996     if (const ConstantFP *C = dyn_cast<ConstantFP>(II->getArgOperand(0))) {
00997       const APFloat &ArgVal = C->getValueAPF();
00998       APFloat Val(ArgVal.getSemantics(), 1.0);
00999       APFloat::opStatus Status = Val.divide(ArgVal,
01000                                             APFloat::rmNearestTiesToEven);
01001       // Only do this if it was exact and therefore not dependent on the
01002       // rounding mode.
01003       if (Status == APFloat::opOK)
01004         return ReplaceInstUsesWith(CI, ConstantFP::get(II->getContext(), Val));
01005     }
01006 
01007     break;
01008   }
01009   case Intrinsic::stackrestore: {
01010     // If the save is right next to the restore, remove the restore.  This can
01011     // happen when variable allocas are DCE'd.
01012     if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getArgOperand(0))) {
01013       if (SS->getIntrinsicID() == Intrinsic::stacksave) {
01014         BasicBlock::iterator BI = SS;
01015         if (&*++BI == II)
01016           return EraseInstFromFunction(CI);
01017       }
01018     }
01019 
01020     // Scan down this block to see if there is another stack restore in the
01021     // same block without an intervening call/alloca.
01022     BasicBlock::iterator BI = II;
01023     TerminatorInst *TI = II->getParent()->getTerminator();
01024     bool CannotRemove = false;
01025     for (++BI; &*BI != TI; ++BI) {
01026       if (isa<AllocaInst>(BI)) {
01027         CannotRemove = true;
01028         break;
01029       }
01030       if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
01031         if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
01032           // If there is a stackrestore below this one, remove this one.
01033           if (II->getIntrinsicID() == Intrinsic::stackrestore)
01034             return EraseInstFromFunction(CI);
01035           // Otherwise, ignore the intrinsic.
01036         } else {
01037           // If we found a non-intrinsic call, we can't remove the stack
01038           // restore.
01039           CannotRemove = true;
01040           break;
01041         }
01042       }
01043     }
01044 
01045     // If the stack restore is in a return, resume, or unwind block and if there
01046     // are no allocas or calls between the restore and the return, nuke the
01047     // restore.
01048     if (!CannotRemove && (isa<ReturnInst>(TI) || isa<ResumeInst>(TI)))
01049       return EraseInstFromFunction(CI);
01050     break;
01051   }
01052   case Intrinsic::assume: {
01053     // Canonicalize assume(a && b) -> assume(a); assume(b);
01054     // Note: New assumption intrinsics created here are registered by
01055     // the InstCombineIRInserter object.
01056     Value *IIOperand = II->getArgOperand(0), *A, *B,
01057           *AssumeIntrinsic = II->getCalledValue();
01058     if (match(IIOperand, m_And(m_Value(A), m_Value(B)))) {
01059       Builder->CreateCall(AssumeIntrinsic, A, II->getName());
01060       Builder->CreateCall(AssumeIntrinsic, B, II->getName());
01061       return EraseInstFromFunction(*II);
01062     }
01063     // assume(!(a || b)) -> assume(!a); assume(!b);
01064     if (match(IIOperand, m_Not(m_Or(m_Value(A), m_Value(B))))) {
01065       Builder->CreateCall(AssumeIntrinsic, Builder->CreateNot(A),
01066                           II->getName());
01067       Builder->CreateCall(AssumeIntrinsic, Builder->CreateNot(B),
01068                           II->getName());
01069       return EraseInstFromFunction(*II);
01070     }
01071 
01072     // assume( (load addr) != null ) -> add 'nonnull' metadata to load
01073     // (if assume is valid at the load)
01074     if (ICmpInst* ICmp = dyn_cast<ICmpInst>(IIOperand)) {
01075       Value *LHS = ICmp->getOperand(0);
01076       Value *RHS = ICmp->getOperand(1);
01077       if (ICmpInst::ICMP_NE == ICmp->getPredicate() &&
01078           isa<LoadInst>(LHS) &&
01079           isa<Constant>(RHS) &&
01080           RHS->getType()->isPointerTy() &&
01081           cast<Constant>(RHS)->isNullValue()) {
01082         LoadInst* LI = cast<LoadInst>(LHS);
01083         if (isValidAssumeForContext(II, LI, DL, DT)) {
01084           MDNode *MD = MDNode::get(II->getContext(), None);
01085           LI->setMetadata(LLVMContext::MD_nonnull, MD);
01086           return EraseInstFromFunction(*II);
01087         }
01088       }
01089       // TODO: apply nonnull return attributes to calls and invokes
01090       // TODO: apply range metadata for range check patterns?
01091     }
01092     // If there is a dominating assume with the same condition as this one,
01093     // then this one is redundant, and should be removed.
01094     APInt KnownZero(1, 0), KnownOne(1, 0);
01095     computeKnownBits(IIOperand, KnownZero, KnownOne, 0, II);
01096     if (KnownOne.isAllOnesValue())
01097       return EraseInstFromFunction(*II);
01098 
01099     break;
01100   }
01101   case Intrinsic::experimental_gc_relocate: {
01102     // Translate facts known about a pointer before relocating into
01103     // facts about the relocate value, while being careful to
01104     // preserve relocation semantics.
01105     GCRelocateOperands Operands(II);
01106     Value *DerivedPtr = Operands.derivedPtr();
01107 
01108     // Remove the relocation if unused, note that this check is required
01109     // to prevent the cases below from looping forever.
01110     if (II->use_empty())
01111       return EraseInstFromFunction(*II);
01112 
01113     // Undef is undef, even after relocation.
01114     // TODO: provide a hook for this in GCStrategy.  This is clearly legal for
01115     // most practical collectors, but there was discussion in the review thread
01116     // about whether it was legal for all possible collectors.
01117     if (isa<UndefValue>(DerivedPtr))
01118       return ReplaceInstUsesWith(*II, DerivedPtr);
01119 
01120     // The relocation of null will be null for most any collector.
01121     // TODO: provide a hook for this in GCStrategy.  There might be some weird
01122     // collector this property does not hold for.
01123     if (isa<ConstantPointerNull>(DerivedPtr))
01124       return ReplaceInstUsesWith(*II, DerivedPtr);
01125 
01126     // isKnownNonNull -> nonnull attribute
01127     if (isKnownNonNull(DerivedPtr))
01128       II->addAttribute(AttributeSet::ReturnIndex, Attribute::NonNull);
01129 
01130     // TODO: dereferenceable -> deref attribute
01131 
01132     // TODO: bitcast(relocate(p)) -> relocate(bitcast(p))
01133     // Canonicalize on the type from the uses to the defs
01134     
01135     // TODO: relocate((gep p, C, C2, ...)) -> gep(relocate(p), C, C2, ...)
01136   }
01137   }
01138 
01139   return visitCallSite(II);
01140 }
01141 
01142 // InvokeInst simplification
01143 //
01144 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
01145   return visitCallSite(&II);
01146 }
01147 
01148 /// isSafeToEliminateVarargsCast - If this cast does not affect the value
01149 /// passed through the varargs area, we can eliminate the use of the cast.
01150 static bool isSafeToEliminateVarargsCast(const CallSite CS,
01151                                          const CastInst * const CI,
01152                                          const DataLayout * const DL,
01153                                          const int ix) {
01154   if (!CI->isLosslessCast())
01155     return false;
01156 
01157   // If this is a GC intrinsic, avoid munging types.  We need types for
01158   // statepoint reconstruction in SelectionDAG.
01159   // TODO: This is probably something which should be expanded to all
01160   // intrinsics since the entire point of intrinsics is that
01161   // they are understandable by the optimizer.
01162   if (isStatepoint(CS) || isGCRelocate(CS) || isGCResult(CS))
01163     return false;
01164 
01165   // The size of ByVal or InAlloca arguments is derived from the type, so we
01166   // can't change to a type with a different size.  If the size were
01167   // passed explicitly we could avoid this check.
01168   if (!CS.isByValOrInAllocaArgument(ix))
01169     return true;
01170 
01171   Type* SrcTy =
01172             cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
01173   Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
01174   if (!SrcTy->isSized() || !DstTy->isSized())
01175     return false;
01176   if (!DL || DL->getTypeAllocSize(SrcTy) != DL->getTypeAllocSize(DstTy))
01177     return false;
01178   return true;
01179 }
01180 
01181 // Try to fold some different type of calls here.
01182 // Currently we're only working with the checking functions, memcpy_chk,
01183 // mempcpy_chk, memmove_chk, memset_chk, strcpy_chk, stpcpy_chk, strncpy_chk,
01184 // strcat_chk and strncat_chk.
01185 Instruction *InstCombiner::tryOptimizeCall(CallInst *CI, const DataLayout *DL) {
01186   if (!CI->getCalledFunction()) return nullptr;
01187 
01188   auto InstCombineRAUW = [this](Instruction *From, Value *With) {
01189     ReplaceInstUsesWith(*From, With);
01190   };
01191   LibCallSimplifier Simplifier(DL, TLI, InstCombineRAUW);
01192   if (Value *With = Simplifier.optimizeCall(CI)) {
01193     ++NumSimplified;
01194     return CI->use_empty() ? CI : ReplaceInstUsesWith(*CI, With);
01195   }
01196 
01197   return nullptr;
01198 }
01199 
01200 static IntrinsicInst *FindInitTrampolineFromAlloca(Value *TrampMem) {
01201   // Strip off at most one level of pointer casts, looking for an alloca.  This
01202   // is good enough in practice and simpler than handling any number of casts.
01203   Value *Underlying = TrampMem->stripPointerCasts();
01204   if (Underlying != TrampMem &&
01205       (!Underlying->hasOneUse() || Underlying->user_back() != TrampMem))
01206     return nullptr;
01207   if (!isa<AllocaInst>(Underlying))
01208     return nullptr;
01209 
01210   IntrinsicInst *InitTrampoline = nullptr;
01211   for (User *U : TrampMem->users()) {
01212     IntrinsicInst *II = dyn_cast<IntrinsicInst>(U);
01213     if (!II)
01214       return nullptr;
01215     if (II->getIntrinsicID() == Intrinsic::init_trampoline) {
01216       if (InitTrampoline)
01217         // More than one init_trampoline writes to this value.  Give up.
01218         return nullptr;
01219       InitTrampoline = II;
01220       continue;
01221     }
01222     if (II->getIntrinsicID() == Intrinsic::adjust_trampoline)
01223       // Allow any number of calls to adjust.trampoline.
01224       continue;
01225     return nullptr;
01226   }
01227 
01228   // No call to init.trampoline found.
01229   if (!InitTrampoline)
01230     return nullptr;
01231 
01232   // Check that the alloca is being used in the expected way.
01233   if (InitTrampoline->getOperand(0) != TrampMem)
01234     return nullptr;
01235 
01236   return InitTrampoline;
01237 }
01238 
01239 static IntrinsicInst *FindInitTrampolineFromBB(IntrinsicInst *AdjustTramp,
01240                                                Value *TrampMem) {
01241   // Visit all the previous instructions in the basic block, and try to find a
01242   // init.trampoline which has a direct path to the adjust.trampoline.
01243   for (BasicBlock::iterator I = AdjustTramp,
01244        E = AdjustTramp->getParent()->begin(); I != E; ) {
01245     Instruction *Inst = --I;
01246     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
01247       if (II->getIntrinsicID() == Intrinsic::init_trampoline &&
01248           II->getOperand(0) == TrampMem)
01249         return II;
01250     if (Inst->mayWriteToMemory())
01251       return nullptr;
01252   }
01253   return nullptr;
01254 }
01255 
01256 // Given a call to llvm.adjust.trampoline, find and return the corresponding
01257 // call to llvm.init.trampoline if the call to the trampoline can be optimized
01258 // to a direct call to a function.  Otherwise return NULL.
01259 //
01260 static IntrinsicInst *FindInitTrampoline(Value *Callee) {
01261   Callee = Callee->stripPointerCasts();
01262   IntrinsicInst *AdjustTramp = dyn_cast<IntrinsicInst>(Callee);
01263   if (!AdjustTramp ||
01264       AdjustTramp->getIntrinsicID() != Intrinsic::adjust_trampoline)
01265     return nullptr;
01266 
01267   Value *TrampMem = AdjustTramp->getOperand(0);
01268 
01269   if (IntrinsicInst *IT = FindInitTrampolineFromAlloca(TrampMem))
01270     return IT;
01271   if (IntrinsicInst *IT = FindInitTrampolineFromBB(AdjustTramp, TrampMem))
01272     return IT;
01273   return nullptr;
01274 }
01275 
01276 // visitCallSite - Improvements for call and invoke instructions.
01277 //
01278 Instruction *InstCombiner::visitCallSite(CallSite CS) {
01279   if (isAllocLikeFn(CS.getInstruction(), TLI))
01280     return visitAllocSite(*CS.getInstruction());
01281 
01282   bool Changed = false;
01283 
01284   // If the callee is a pointer to a function, attempt to move any casts to the
01285   // arguments of the call/invoke.
01286   Value *Callee = CS.getCalledValue();
01287   if (!isa<Function>(Callee) && transformConstExprCastCall(CS))
01288     return nullptr;
01289 
01290   if (Function *CalleeF = dyn_cast<Function>(Callee))
01291     // If the call and callee calling conventions don't match, this call must
01292     // be unreachable, as the call is undefined.
01293     if (CalleeF->getCallingConv() != CS.getCallingConv() &&
01294         // Only do this for calls to a function with a body.  A prototype may
01295         // not actually end up matching the implementation's calling conv for a
01296         // variety of reasons (e.g. it may be written in assembly).
01297         !CalleeF->isDeclaration()) {
01298       Instruction *OldCall = CS.getInstruction();
01299       new StoreInst(ConstantInt::getTrue(Callee->getContext()),
01300                 UndefValue::get(Type::getInt1PtrTy(Callee->getContext())),
01301                                   OldCall);
01302       // If OldCall does not return void then replaceAllUsesWith undef.
01303       // This allows ValueHandlers and custom metadata to adjust itself.
01304       if (!OldCall->getType()->isVoidTy())
01305         ReplaceInstUsesWith(*OldCall, UndefValue::get(OldCall->getType()));
01306       if (isa<CallInst>(OldCall))
01307         return EraseInstFromFunction(*OldCall);
01308 
01309       // We cannot remove an invoke, because it would change the CFG, just
01310       // change the callee to a null pointer.
01311       cast<InvokeInst>(OldCall)->setCalledFunction(
01312                                     Constant::getNullValue(CalleeF->getType()));
01313       return nullptr;
01314     }
01315 
01316   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
01317     // If CS does not return void then replaceAllUsesWith undef.
01318     // This allows ValueHandlers and custom metadata to adjust itself.
01319     if (!CS.getInstruction()->getType()->isVoidTy())
01320       ReplaceInstUsesWith(*CS.getInstruction(),
01321                           UndefValue::get(CS.getInstruction()->getType()));
01322 
01323     if (isa<InvokeInst>(CS.getInstruction())) {
01324       // Can't remove an invoke because we cannot change the CFG.
01325       return nullptr;
01326     }
01327 
01328     // This instruction is not reachable, just remove it.  We insert a store to
01329     // undef so that we know that this code is not reachable, despite the fact
01330     // that we can't modify the CFG here.
01331     new StoreInst(ConstantInt::getTrue(Callee->getContext()),
01332                   UndefValue::get(Type::getInt1PtrTy(Callee->getContext())),
01333                   CS.getInstruction());
01334 
01335     return EraseInstFromFunction(*CS.getInstruction());
01336   }
01337 
01338   if (IntrinsicInst *II = FindInitTrampoline(Callee))
01339     return transformCallThroughTrampoline(CS, II);
01340 
01341   PointerType *PTy = cast<PointerType>(Callee->getType());
01342   FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
01343   if (FTy->isVarArg()) {
01344     int ix = FTy->getNumParams();
01345     // See if we can optimize any arguments passed through the varargs area of
01346     // the call.
01347     for (CallSite::arg_iterator I = CS.arg_begin() + FTy->getNumParams(),
01348            E = CS.arg_end(); I != E; ++I, ++ix) {
01349       CastInst *CI = dyn_cast<CastInst>(*I);
01350       if (CI && isSafeToEliminateVarargsCast(CS, CI, DL, ix)) {
01351         *I = CI->getOperand(0);
01352         Changed = true;
01353       }
01354     }
01355   }
01356 
01357   if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
01358     // Inline asm calls cannot throw - mark them 'nounwind'.
01359     CS.setDoesNotThrow();
01360     Changed = true;
01361   }
01362 
01363   // Try to optimize the call if possible, we require DataLayout for most of
01364   // this.  None of these calls are seen as possibly dead so go ahead and
01365   // delete the instruction now.
01366   if (CallInst *CI = dyn_cast<CallInst>(CS.getInstruction())) {
01367     Instruction *I = tryOptimizeCall(CI, DL);
01368     // If we changed something return the result, etc. Otherwise let
01369     // the fallthrough check.
01370     if (I) return EraseInstFromFunction(*I);
01371   }
01372 
01373   return Changed ? CS.getInstruction() : nullptr;
01374 }
01375 
01376 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
01377 // attempt to move the cast to the arguments of the call/invoke.
01378 //
01379 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
01380   Function *Callee =
01381     dyn_cast<Function>(CS.getCalledValue()->stripPointerCasts());
01382   if (!Callee)
01383     return false;
01384   // The prototype of thunks are a lie, don't try to directly call such
01385   // functions.
01386   if (Callee->hasFnAttribute("thunk"))
01387     return false;
01388   Instruction *Caller = CS.getInstruction();
01389   const AttributeSet &CallerPAL = CS.getAttributes();
01390 
01391   // Okay, this is a cast from a function to a different type.  Unless doing so
01392   // would cause a type conversion of one of our arguments, change this call to
01393   // be a direct call with arguments casted to the appropriate types.
01394   //
01395   FunctionType *FT = Callee->getFunctionType();
01396   Type *OldRetTy = Caller->getType();
01397   Type *NewRetTy = FT->getReturnType();
01398 
01399   // Check to see if we are changing the return type...
01400   if (OldRetTy != NewRetTy) {
01401 
01402     if (NewRetTy->isStructTy())
01403       return false; // TODO: Handle multiple return values.
01404 
01405     if (!CastInst::isBitOrNoopPointerCastable(NewRetTy, OldRetTy, DL)) {
01406       if (Callee->isDeclaration())
01407         return false;   // Cannot transform this return value.
01408 
01409       if (!Caller->use_empty() &&
01410           // void -> non-void is handled specially
01411           !NewRetTy->isVoidTy())
01412         return false;   // Cannot transform this return value.
01413     }
01414 
01415     if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
01416       AttrBuilder RAttrs(CallerPAL, AttributeSet::ReturnIndex);
01417       if (RAttrs.
01418           hasAttributes(AttributeFuncs::
01419                         typeIncompatible(NewRetTy, AttributeSet::ReturnIndex),
01420                         AttributeSet::ReturnIndex))
01421         return false;   // Attribute not compatible with transformed value.
01422     }
01423 
01424     // If the callsite is an invoke instruction, and the return value is used by
01425     // a PHI node in a successor, we cannot change the return type of the call
01426     // because there is no place to put the cast instruction (without breaking
01427     // the critical edge).  Bail out in this case.
01428     if (!Caller->use_empty())
01429       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
01430         for (User *U : II->users())
01431           if (PHINode *PN = dyn_cast<PHINode>(U))
01432             if (PN->getParent() == II->getNormalDest() ||
01433                 PN->getParent() == II->getUnwindDest())
01434               return false;
01435   }
01436 
01437   unsigned NumActualArgs = CS.arg_size();
01438   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
01439 
01440   // Prevent us turning:
01441   // declare void @takes_i32_inalloca(i32* inalloca)
01442   //  call void bitcast (void (i32*)* @takes_i32_inalloca to void (i32)*)(i32 0)
01443   //
01444   // into:
01445   //  call void @takes_i32_inalloca(i32* null)
01446   if (Callee->getAttributes().hasAttrSomewhere(Attribute::InAlloca))
01447     return false;
01448 
01449   CallSite::arg_iterator AI = CS.arg_begin();
01450   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
01451     Type *ParamTy = FT->getParamType(i);
01452     Type *ActTy = (*AI)->getType();
01453 
01454     if (!CastInst::isBitOrNoopPointerCastable(ActTy, ParamTy, DL))
01455       return false;   // Cannot transform this parameter value.
01456 
01457     if (AttrBuilder(CallerPAL.getParamAttributes(i + 1), i + 1).
01458           hasAttributes(AttributeFuncs::
01459                         typeIncompatible(ParamTy, i + 1), i + 1))
01460       return false;   // Attribute not compatible with transformed value.
01461 
01462     if (CS.isInAllocaArgument(i))
01463       return false;   // Cannot transform to and from inalloca.
01464 
01465     // If the parameter is passed as a byval argument, then we have to have a
01466     // sized type and the sized type has to have the same size as the old type.
01467     if (ParamTy != ActTy &&
01468         CallerPAL.getParamAttributes(i + 1).hasAttribute(i + 1,
01469                                                          Attribute::ByVal)) {
01470       PointerType *ParamPTy = dyn_cast<PointerType>(ParamTy);
01471       if (!ParamPTy || !ParamPTy->getElementType()->isSized() || !DL)
01472         return false;
01473 
01474       Type *CurElTy = ActTy->getPointerElementType();
01475       if (DL->getTypeAllocSize(CurElTy) !=
01476           DL->getTypeAllocSize(ParamPTy->getElementType()))
01477         return false;
01478     }
01479   }
01480 
01481   if (Callee->isDeclaration()) {
01482     // Do not delete arguments unless we have a function body.
01483     if (FT->getNumParams() < NumActualArgs && !FT->isVarArg())
01484       return false;
01485 
01486     // If the callee is just a declaration, don't change the varargsness of the
01487     // call.  We don't want to introduce a varargs call where one doesn't
01488     // already exist.
01489     PointerType *APTy = cast<PointerType>(CS.getCalledValue()->getType());
01490     if (FT->isVarArg()!=cast<FunctionType>(APTy->getElementType())->isVarArg())
01491       return false;
01492 
01493     // If both the callee and the cast type are varargs, we still have to make
01494     // sure the number of fixed parameters are the same or we have the same
01495     // ABI issues as if we introduce a varargs call.
01496     if (FT->isVarArg() &&
01497         cast<FunctionType>(APTy->getElementType())->isVarArg() &&
01498         FT->getNumParams() !=
01499         cast<FunctionType>(APTy->getElementType())->getNumParams())
01500       return false;
01501   }
01502 
01503   if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
01504       !CallerPAL.isEmpty())
01505     // In this case we have more arguments than the new function type, but we
01506     // won't be dropping them.  Check that these extra arguments have attributes
01507     // that are compatible with being a vararg call argument.
01508     for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
01509       unsigned Index = CallerPAL.getSlotIndex(i - 1);
01510       if (Index <= FT->getNumParams())
01511         break;
01512 
01513       // Check if it has an attribute that's incompatible with varargs.
01514       AttributeSet PAttrs = CallerPAL.getSlotAttributes(i - 1);
01515       if (PAttrs.hasAttribute(Index, Attribute::StructRet))
01516         return false;
01517     }
01518 
01519 
01520   // Okay, we decided that this is a safe thing to do: go ahead and start
01521   // inserting cast instructions as necessary.
01522   std::vector<Value*> Args;
01523   Args.reserve(NumActualArgs);
01524   SmallVector<AttributeSet, 8> attrVec;
01525   attrVec.reserve(NumCommonArgs);
01526 
01527   // Get any return attributes.
01528   AttrBuilder RAttrs(CallerPAL, AttributeSet::ReturnIndex);
01529 
01530   // If the return value is not being used, the type may not be compatible
01531   // with the existing attributes.  Wipe out any problematic attributes.
01532   RAttrs.
01533     removeAttributes(AttributeFuncs::
01534                      typeIncompatible(NewRetTy, AttributeSet::ReturnIndex),
01535                      AttributeSet::ReturnIndex);
01536 
01537   // Add the new return attributes.
01538   if (RAttrs.hasAttributes())
01539     attrVec.push_back(AttributeSet::get(Caller->getContext(),
01540                                         AttributeSet::ReturnIndex, RAttrs));
01541 
01542   AI = CS.arg_begin();
01543   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
01544     Type *ParamTy = FT->getParamType(i);
01545 
01546     if ((*AI)->getType() == ParamTy) {
01547       Args.push_back(*AI);
01548     } else {
01549       Args.push_back(Builder->CreateBitOrPointerCast(*AI, ParamTy));
01550     }
01551 
01552     // Add any parameter attributes.
01553     AttrBuilder PAttrs(CallerPAL.getParamAttributes(i + 1), i + 1);
01554     if (PAttrs.hasAttributes())
01555       attrVec.push_back(AttributeSet::get(Caller->getContext(), i + 1,
01556                                           PAttrs));
01557   }
01558 
01559   // If the function takes more arguments than the call was taking, add them
01560   // now.
01561   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
01562     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
01563 
01564   // If we are removing arguments to the function, emit an obnoxious warning.
01565   if (FT->getNumParams() < NumActualArgs) {
01566     // TODO: if (!FT->isVarArg()) this call may be unreachable. PR14722
01567     if (FT->isVarArg()) {
01568       // Add all of the arguments in their promoted form to the arg list.
01569       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
01570         Type *PTy = getPromotedType((*AI)->getType());
01571         if (PTy != (*AI)->getType()) {
01572           // Must promote to pass through va_arg area!
01573           Instruction::CastOps opcode =
01574             CastInst::getCastOpcode(*AI, false, PTy, false);
01575           Args.push_back(Builder->CreateCast(opcode, *AI, PTy));
01576         } else {
01577           Args.push_back(*AI);
01578         }
01579 
01580         // Add any parameter attributes.
01581         AttrBuilder PAttrs(CallerPAL.getParamAttributes(i + 1), i + 1);
01582         if (PAttrs.hasAttributes())
01583           attrVec.push_back(AttributeSet::get(FT->getContext(), i + 1,
01584                                               PAttrs));
01585       }
01586     }
01587   }
01588 
01589   AttributeSet FnAttrs = CallerPAL.getFnAttributes();
01590   if (CallerPAL.hasAttributes(AttributeSet::FunctionIndex))
01591     attrVec.push_back(AttributeSet::get(Callee->getContext(), FnAttrs));
01592 
01593   if (NewRetTy->isVoidTy())
01594     Caller->setName("");   // Void type should not have a name.
01595 
01596   const AttributeSet &NewCallerPAL = AttributeSet::get(Callee->getContext(),
01597                                                        attrVec);
01598 
01599   Instruction *NC;
01600   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
01601     NC = Builder->CreateInvoke(Callee, II->getNormalDest(),
01602                                II->getUnwindDest(), Args);
01603     NC->takeName(II);
01604     cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
01605     cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
01606   } else {
01607     CallInst *CI = cast<CallInst>(Caller);
01608     NC = Builder->CreateCall(Callee, Args);
01609     NC->takeName(CI);
01610     if (CI->isTailCall())
01611       cast<CallInst>(NC)->setTailCall();
01612     cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
01613     cast<CallInst>(NC)->setAttributes(NewCallerPAL);
01614   }
01615 
01616   // Insert a cast of the return type as necessary.
01617   Value *NV = NC;
01618   if (OldRetTy != NV->getType() && !Caller->use_empty()) {
01619     if (!NV->getType()->isVoidTy()) {
01620       NV = NC = CastInst::CreateBitOrPointerCast(NC, OldRetTy);
01621       NC->setDebugLoc(Caller->getDebugLoc());
01622 
01623       // If this is an invoke instruction, we should insert it after the first
01624       // non-phi, instruction in the normal successor block.
01625       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
01626         BasicBlock::iterator I = II->getNormalDest()->getFirstInsertionPt();
01627         InsertNewInstBefore(NC, *I);
01628       } else {
01629         // Otherwise, it's a call, just insert cast right after the call.
01630         InsertNewInstBefore(NC, *Caller);
01631       }
01632       Worklist.AddUsersToWorkList(*Caller);
01633     } else {
01634       NV = UndefValue::get(Caller->getType());
01635     }
01636   }
01637 
01638   if (!Caller->use_empty())
01639     ReplaceInstUsesWith(*Caller, NV);
01640   else if (Caller->hasValueHandle()) {
01641     if (OldRetTy == NV->getType())
01642       ValueHandleBase::ValueIsRAUWd(Caller, NV);
01643     else
01644       // We cannot call ValueIsRAUWd with a different type, and the
01645       // actual tracked value will disappear.
01646       ValueHandleBase::ValueIsDeleted(Caller);
01647   }
01648 
01649   EraseInstFromFunction(*Caller);
01650   return true;
01651 }
01652 
01653 // transformCallThroughTrampoline - Turn a call to a function created by
01654 // init_trampoline / adjust_trampoline intrinsic pair into a direct call to the
01655 // underlying function.
01656 //
01657 Instruction *
01658 InstCombiner::transformCallThroughTrampoline(CallSite CS,
01659                                              IntrinsicInst *Tramp) {
01660   Value *Callee = CS.getCalledValue();
01661   PointerType *PTy = cast<PointerType>(Callee->getType());
01662   FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
01663   const AttributeSet &Attrs = CS.getAttributes();
01664 
01665   // If the call already has the 'nest' attribute somewhere then give up -
01666   // otherwise 'nest' would occur twice after splicing in the chain.
01667   if (Attrs.hasAttrSomewhere(Attribute::Nest))
01668     return nullptr;
01669 
01670   assert(Tramp &&
01671          "transformCallThroughTrampoline called with incorrect CallSite.");
01672 
01673   Function *NestF =cast<Function>(Tramp->getArgOperand(1)->stripPointerCasts());
01674   PointerType *NestFPTy = cast<PointerType>(NestF->getType());
01675   FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
01676 
01677   const AttributeSet &NestAttrs = NestF->getAttributes();
01678   if (!NestAttrs.isEmpty()) {
01679     unsigned NestIdx = 1;
01680     Type *NestTy = nullptr;
01681     AttributeSet NestAttr;
01682 
01683     // Look for a parameter marked with the 'nest' attribute.
01684     for (FunctionType::param_iterator I = NestFTy->param_begin(),
01685          E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
01686       if (NestAttrs.hasAttribute(NestIdx, Attribute::Nest)) {
01687         // Record the parameter type and any other attributes.
01688         NestTy = *I;
01689         NestAttr = NestAttrs.getParamAttributes(NestIdx);
01690         break;
01691       }
01692 
01693     if (NestTy) {
01694       Instruction *Caller = CS.getInstruction();
01695       std::vector<Value*> NewArgs;
01696       NewArgs.reserve(CS.arg_size() + 1);
01697 
01698       SmallVector<AttributeSet, 8> NewAttrs;
01699       NewAttrs.reserve(Attrs.getNumSlots() + 1);
01700 
01701       // Insert the nest argument into the call argument list, which may
01702       // mean appending it.  Likewise for attributes.
01703 
01704       // Add any result attributes.
01705       if (Attrs.hasAttributes(AttributeSet::ReturnIndex))
01706         NewAttrs.push_back(AttributeSet::get(Caller->getContext(),
01707                                              Attrs.getRetAttributes()));
01708 
01709       {
01710         unsigned Idx = 1;
01711         CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
01712         do {
01713           if (Idx == NestIdx) {
01714             // Add the chain argument and attributes.
01715             Value *NestVal = Tramp->getArgOperand(2);
01716             if (NestVal->getType() != NestTy)
01717               NestVal = Builder->CreateBitCast(NestVal, NestTy, "nest");
01718             NewArgs.push_back(NestVal);
01719             NewAttrs.push_back(AttributeSet::get(Caller->getContext(),
01720                                                  NestAttr));
01721           }
01722 
01723           if (I == E)
01724             break;
01725 
01726           // Add the original argument and attributes.
01727           NewArgs.push_back(*I);
01728           AttributeSet Attr = Attrs.getParamAttributes(Idx);
01729           if (Attr.hasAttributes(Idx)) {
01730             AttrBuilder B(Attr, Idx);
01731             NewAttrs.push_back(AttributeSet::get(Caller->getContext(),
01732                                                  Idx + (Idx >= NestIdx), B));
01733           }
01734 
01735           ++Idx, ++I;
01736         } while (1);
01737       }
01738 
01739       // Add any function attributes.
01740       if (Attrs.hasAttributes(AttributeSet::FunctionIndex))
01741         NewAttrs.push_back(AttributeSet::get(FTy->getContext(),
01742                                              Attrs.getFnAttributes()));
01743 
01744       // The trampoline may have been bitcast to a bogus type (FTy).
01745       // Handle this by synthesizing a new function type, equal to FTy
01746       // with the chain parameter inserted.
01747 
01748       std::vector<Type*> NewTypes;
01749       NewTypes.reserve(FTy->getNumParams()+1);
01750 
01751       // Insert the chain's type into the list of parameter types, which may
01752       // mean appending it.
01753       {
01754         unsigned Idx = 1;
01755         FunctionType::param_iterator I = FTy->param_begin(),
01756           E = FTy->param_end();
01757 
01758         do {
01759           if (Idx == NestIdx)
01760             // Add the chain's type.
01761             NewTypes.push_back(NestTy);
01762 
01763           if (I == E)
01764             break;
01765 
01766           // Add the original type.
01767           NewTypes.push_back(*I);
01768 
01769           ++Idx, ++I;
01770         } while (1);
01771       }
01772 
01773       // Replace the trampoline call with a direct call.  Let the generic
01774       // code sort out any function type mismatches.
01775       FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
01776                                                 FTy->isVarArg());
01777       Constant *NewCallee =
01778         NestF->getType() == PointerType::getUnqual(NewFTy) ?
01779         NestF : ConstantExpr::getBitCast(NestF,
01780                                          PointerType::getUnqual(NewFTy));
01781       const AttributeSet &NewPAL =
01782           AttributeSet::get(FTy->getContext(), NewAttrs);
01783 
01784       Instruction *NewCaller;
01785       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
01786         NewCaller = InvokeInst::Create(NewCallee,
01787                                        II->getNormalDest(), II->getUnwindDest(),
01788                                        NewArgs);
01789         cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
01790         cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
01791       } else {
01792         NewCaller = CallInst::Create(NewCallee, NewArgs);
01793         if (cast<CallInst>(Caller)->isTailCall())
01794           cast<CallInst>(NewCaller)->setTailCall();
01795         cast<CallInst>(NewCaller)->
01796           setCallingConv(cast<CallInst>(Caller)->getCallingConv());
01797         cast<CallInst>(NewCaller)->setAttributes(NewPAL);
01798       }
01799 
01800       return NewCaller;
01801     }
01802   }
01803 
01804   // Replace the trampoline call with a direct call.  Since there is no 'nest'
01805   // parameter, there is no need to adjust the argument list.  Let the generic
01806   // code sort out any function type mismatches.
01807   Constant *NewCallee =
01808     NestF->getType() == PTy ? NestF :
01809                               ConstantExpr::getBitCast(NestF, PTy);
01810   CS.setCalledFunction(NewCallee);
01811   return CS.getInstruction();
01812 }