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