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