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