1 //===- InstCombineCalls.cpp -----------------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the visitCall and visitInvoke functions.
12 //===----------------------------------------------------------------------===//
14 #include "InstCombineInternal.h"
15 #include "llvm/ADT/Statistic.h"
16 #include "llvm/Analysis/InstructionSimplify.h"
17 #include "llvm/Analysis/MemoryBuiltins.h"
18 #include "llvm/IR/CallSite.h"
19 #include "llvm/IR/Dominators.h"
20 #include "llvm/IR/PatternMatch.h"
21 #include "llvm/IR/Statepoint.h"
22 #include "llvm/Transforms/Utils/BuildLibCalls.h"
23 #include "llvm/Transforms/Utils/Local.h"
24 #include "llvm/Transforms/Utils/SimplifyLibCalls.h"
26 using namespace PatternMatch;
28 #define DEBUG_TYPE "instcombine"
30 STATISTIC(NumSimplified, "Number of library calls simplified");
32 /// getPromotedType - Return the specified type promoted as it would be to pass
33 /// though a va_arg area.
34 static Type *getPromotedType(Type *Ty) {
35 if (IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
36 if (ITy->getBitWidth() < 32)
37 return Type::getInt32Ty(Ty->getContext());
42 /// reduceToSingleValueType - Given an aggregate type which ultimately holds a
43 /// single scalar element, like {{{type}}} or [1 x type], return type.
44 static Type *reduceToSingleValueType(Type *T) {
45 while (!T->isSingleValueType()) {
46 if (StructType *STy = dyn_cast<StructType>(T)) {
47 if (STy->getNumElements() == 1)
48 T = STy->getElementType(0);
51 } else if (ArrayType *ATy = dyn_cast<ArrayType>(T)) {
52 if (ATy->getNumElements() == 1)
53 T = ATy->getElementType();
63 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
64 unsigned DstAlign = getKnownAlignment(MI->getArgOperand(0), DL, MI, AC, DT);
65 unsigned SrcAlign = getKnownAlignment(MI->getArgOperand(1), DL, MI, AC, DT);
66 unsigned MinAlign = std::min(DstAlign, SrcAlign);
67 unsigned CopyAlign = MI->getAlignment();
69 if (CopyAlign < MinAlign) {
70 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(), MinAlign, false));
74 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
76 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getArgOperand(2));
77 if (!MemOpLength) return nullptr;
79 // Source and destination pointer types are always "i8*" for intrinsic. See
80 // if the size is something we can handle with a single primitive load/store.
81 // A single load+store correctly handles overlapping memory in the memmove
83 uint64_t Size = MemOpLength->getLimitedValue();
84 assert(Size && "0-sized memory transferring should be removed already.");
86 if (Size > 8 || (Size&(Size-1)))
87 return nullptr; // If not 1/2/4/8 bytes, exit.
89 // Use an integer load+store unless we can find something better.
91 cast<PointerType>(MI->getArgOperand(1)->getType())->getAddressSpace();
93 cast<PointerType>(MI->getArgOperand(0)->getType())->getAddressSpace();
95 IntegerType* IntType = IntegerType::get(MI->getContext(), Size<<3);
96 Type *NewSrcPtrTy = PointerType::get(IntType, SrcAddrSp);
97 Type *NewDstPtrTy = PointerType::get(IntType, DstAddrSp);
99 // Memcpy forces the use of i8* for the source and destination. That means
100 // that if you're using memcpy to move one double around, you'll get a cast
101 // from double* to i8*. We'd much rather use a double load+store rather than
102 // an i64 load+store, here because this improves the odds that the source or
103 // dest address will be promotable. See if we can find a better type than the
105 Value *StrippedDest = MI->getArgOperand(0)->stripPointerCasts();
106 MDNode *CopyMD = nullptr;
107 if (StrippedDest != MI->getArgOperand(0)) {
108 Type *SrcETy = cast<PointerType>(StrippedDest->getType())
110 if (SrcETy->isSized() && DL.getTypeStoreSize(SrcETy) == Size) {
111 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
112 // down through these levels if so.
113 SrcETy = reduceToSingleValueType(SrcETy);
115 if (SrcETy->isSingleValueType()) {
116 NewSrcPtrTy = PointerType::get(SrcETy, SrcAddrSp);
117 NewDstPtrTy = PointerType::get(SrcETy, DstAddrSp);
119 // If the memcpy has metadata describing the members, see if we can
120 // get the TBAA tag describing our copy.
121 if (MDNode *M = MI->getMetadata(LLVMContext::MD_tbaa_struct)) {
122 if (M->getNumOperands() == 3 && M->getOperand(0) &&
123 mdconst::hasa<ConstantInt>(M->getOperand(0)) &&
124 mdconst::extract<ConstantInt>(M->getOperand(0))->isNullValue() &&
126 mdconst::hasa<ConstantInt>(M->getOperand(1)) &&
127 mdconst::extract<ConstantInt>(M->getOperand(1))->getValue() ==
129 M->getOperand(2) && isa<MDNode>(M->getOperand(2)))
130 CopyMD = cast<MDNode>(M->getOperand(2));
136 // If the memcpy/memmove provides better alignment info than we can
138 SrcAlign = std::max(SrcAlign, CopyAlign);
139 DstAlign = std::max(DstAlign, CopyAlign);
141 Value *Src = Builder->CreateBitCast(MI->getArgOperand(1), NewSrcPtrTy);
142 Value *Dest = Builder->CreateBitCast(MI->getArgOperand(0), NewDstPtrTy);
143 LoadInst *L = Builder->CreateLoad(Src, MI->isVolatile());
144 L->setAlignment(SrcAlign);
146 L->setMetadata(LLVMContext::MD_tbaa, CopyMD);
147 StoreInst *S = Builder->CreateStore(L, Dest, MI->isVolatile());
148 S->setAlignment(DstAlign);
150 S->setMetadata(LLVMContext::MD_tbaa, CopyMD);
152 // Set the size of the copy to 0, it will be deleted on the next iteration.
153 MI->setArgOperand(2, Constant::getNullValue(MemOpLength->getType()));
157 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
158 unsigned Alignment = getKnownAlignment(MI->getDest(), DL, MI, AC, DT);
159 if (MI->getAlignment() < Alignment) {
160 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
165 // Extract the length and alignment and fill if they are constant.
166 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
167 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
168 if (!LenC || !FillC || !FillC->getType()->isIntegerTy(8))
170 uint64_t Len = LenC->getLimitedValue();
171 Alignment = MI->getAlignment();
172 assert(Len && "0-sized memory setting should be removed already.");
174 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
175 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
176 Type *ITy = IntegerType::get(MI->getContext(), Len*8); // n=1 -> i8.
178 Value *Dest = MI->getDest();
179 unsigned DstAddrSp = cast<PointerType>(Dest->getType())->getAddressSpace();
180 Type *NewDstPtrTy = PointerType::get(ITy, DstAddrSp);
181 Dest = Builder->CreateBitCast(Dest, NewDstPtrTy);
183 // Alignment 0 is identity for alignment 1 for memset, but not store.
184 if (Alignment == 0) Alignment = 1;
186 // Extract the fill value and store.
187 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
188 StoreInst *S = Builder->CreateStore(ConstantInt::get(ITy, Fill), Dest,
190 S->setAlignment(Alignment);
192 // Set the size of the copy to 0, it will be deleted on the next iteration.
193 MI->setLength(Constant::getNullValue(LenC->getType()));
200 static Value *SimplifyX86immshift(const IntrinsicInst &II,
201 InstCombiner::BuilderTy &Builder) {
202 bool LogicalShift = false;
203 bool ShiftLeft = false;
205 switch (II.getIntrinsicID()) {
208 case Intrinsic::x86_sse2_psra_d:
209 case Intrinsic::x86_sse2_psra_w:
210 case Intrinsic::x86_sse2_psrai_d:
211 case Intrinsic::x86_sse2_psrai_w:
212 case Intrinsic::x86_avx2_psra_d:
213 case Intrinsic::x86_avx2_psra_w:
214 case Intrinsic::x86_avx2_psrai_d:
215 case Intrinsic::x86_avx2_psrai_w:
216 LogicalShift = false; ShiftLeft = false;
218 case Intrinsic::x86_sse2_psrl_d:
219 case Intrinsic::x86_sse2_psrl_q:
220 case Intrinsic::x86_sse2_psrl_w:
221 case Intrinsic::x86_sse2_psrli_d:
222 case Intrinsic::x86_sse2_psrli_q:
223 case Intrinsic::x86_sse2_psrli_w:
224 case Intrinsic::x86_avx2_psrl_d:
225 case Intrinsic::x86_avx2_psrl_q:
226 case Intrinsic::x86_avx2_psrl_w:
227 case Intrinsic::x86_avx2_psrli_d:
228 case Intrinsic::x86_avx2_psrli_q:
229 case Intrinsic::x86_avx2_psrli_w:
230 LogicalShift = true; ShiftLeft = false;
232 case Intrinsic::x86_sse2_psll_d:
233 case Intrinsic::x86_sse2_psll_q:
234 case Intrinsic::x86_sse2_psll_w:
235 case Intrinsic::x86_sse2_pslli_d:
236 case Intrinsic::x86_sse2_pslli_q:
237 case Intrinsic::x86_sse2_pslli_w:
238 case Intrinsic::x86_avx2_psll_d:
239 case Intrinsic::x86_avx2_psll_q:
240 case Intrinsic::x86_avx2_psll_w:
241 case Intrinsic::x86_avx2_pslli_d:
242 case Intrinsic::x86_avx2_pslli_q:
243 case Intrinsic::x86_avx2_pslli_w:
244 LogicalShift = true; ShiftLeft = true;
247 assert((LogicalShift || !ShiftLeft) && "Only logical shifts can shift left");
249 // Simplify if count is constant.
250 auto Arg1 = II.getArgOperand(1);
251 auto CAZ = dyn_cast<ConstantAggregateZero>(Arg1);
252 auto CDV = dyn_cast<ConstantDataVector>(Arg1);
253 auto CInt = dyn_cast<ConstantInt>(Arg1);
254 if (!CAZ && !CDV && !CInt)
259 // SSE2/AVX2 uses all the first 64-bits of the 128-bit vector
260 // operand to compute the shift amount.
261 auto VT = cast<VectorType>(CDV->getType());
262 unsigned BitWidth = VT->getElementType()->getPrimitiveSizeInBits();
263 assert((64 % BitWidth) == 0 && "Unexpected packed shift size");
264 unsigned NumSubElts = 64 / BitWidth;
266 // Concatenate the sub-elements to create the 64-bit value.
267 for (unsigned i = 0; i != NumSubElts; ++i) {
268 unsigned SubEltIdx = (NumSubElts - 1) - i;
269 auto SubElt = cast<ConstantInt>(CDV->getElementAsConstant(SubEltIdx));
270 Count = Count.shl(BitWidth);
271 Count |= SubElt->getValue().zextOrTrunc(64);
275 Count = CInt->getValue();
277 auto Vec = II.getArgOperand(0);
278 auto VT = cast<VectorType>(Vec->getType());
279 auto SVT = VT->getElementType();
280 unsigned VWidth = VT->getNumElements();
281 unsigned BitWidth = SVT->getPrimitiveSizeInBits();
283 // If shift-by-zero then just return the original value.
287 // Handle cases when Shift >= BitWidth.
288 if (Count.uge(BitWidth)) {
289 // If LogicalShift - just return zero.
291 return ConstantAggregateZero::get(VT);
293 // If ArithmeticShift - clamp Shift to (BitWidth - 1).
294 Count = APInt(64, BitWidth - 1);
297 // Get a constant vector of the same type as the first operand.
298 auto ShiftAmt = ConstantInt::get(SVT, Count.zextOrTrunc(BitWidth));
299 auto ShiftVec = Builder.CreateVectorSplat(VWidth, ShiftAmt);
302 return Builder.CreateShl(Vec, ShiftVec);
305 return Builder.CreateLShr(Vec, ShiftVec);
307 return Builder.CreateAShr(Vec, ShiftVec);
310 static Value *SimplifyX86extend(const IntrinsicInst &II,
311 InstCombiner::BuilderTy &Builder,
313 VectorType *SrcTy = cast<VectorType>(II.getArgOperand(0)->getType());
314 VectorType *DstTy = cast<VectorType>(II.getType());
315 unsigned NumDstElts = DstTy->getNumElements();
317 // Extract a subvector of the first NumDstElts lanes and sign/zero extend.
318 SmallVector<int, 8> ShuffleMask;
319 for (int i = 0; i != (int)NumDstElts; ++i)
320 ShuffleMask.push_back(i);
322 Value *SV = Builder.CreateShuffleVector(II.getArgOperand(0),
323 UndefValue::get(SrcTy), ShuffleMask);
324 return SignExtend ? Builder.CreateSExt(SV, DstTy)
325 : Builder.CreateZExt(SV, DstTy);
328 static Value *SimplifyX86insertps(const IntrinsicInst &II,
329 InstCombiner::BuilderTy &Builder) {
330 if (auto *CInt = dyn_cast<ConstantInt>(II.getArgOperand(2))) {
331 VectorType *VecTy = cast<VectorType>(II.getType());
332 assert(VecTy->getNumElements() == 4 && "insertps with wrong vector type");
334 // The immediate permute control byte looks like this:
335 // [3:0] - zero mask for each 32-bit lane
336 // [5:4] - select one 32-bit destination lane
337 // [7:6] - select one 32-bit source lane
339 uint8_t Imm = CInt->getZExtValue();
340 uint8_t ZMask = Imm & 0xf;
341 uint8_t DestLane = (Imm >> 4) & 0x3;
342 uint8_t SourceLane = (Imm >> 6) & 0x3;
344 ConstantAggregateZero *ZeroVector = ConstantAggregateZero::get(VecTy);
346 // If all zero mask bits are set, this was just a weird way to
347 // generate a zero vector.
351 // Initialize by passing all of the first source bits through.
352 int ShuffleMask[4] = { 0, 1, 2, 3 };
354 // We may replace the second operand with the zero vector.
355 Value *V1 = II.getArgOperand(1);
358 // If the zero mask is being used with a single input or the zero mask
359 // overrides the destination lane, this is a shuffle with the zero vector.
360 if ((II.getArgOperand(0) == II.getArgOperand(1)) ||
361 (ZMask & (1 << DestLane))) {
363 // We may still move 32-bits of the first source vector from one lane
365 ShuffleMask[DestLane] = SourceLane;
366 // The zero mask may override the previous insert operation.
367 for (unsigned i = 0; i < 4; ++i)
368 if ((ZMask >> i) & 0x1)
369 ShuffleMask[i] = i + 4;
371 // TODO: Model this case as 2 shuffles or a 'logical and' plus shuffle?
375 // Replace the selected destination lane with the selected source lane.
376 ShuffleMask[DestLane] = SourceLane + 4;
379 return Builder.CreateShuffleVector(II.getArgOperand(0), V1, ShuffleMask);
384 /// Attempt to simplify SSE4A EXTRQ/EXTRQI instructions using constant folding
385 /// or conversion to a shuffle vector.
386 static Value *SimplifyX86extrq(IntrinsicInst &II, Value *Op0,
387 ConstantInt *CILength, ConstantInt *CIIndex,
388 InstCombiner::BuilderTy &Builder) {
389 auto LowConstantHighUndef = [&](uint64_t Val) {
390 Type *IntTy64 = Type::getInt64Ty(II.getContext());
391 Constant *Args[] = {ConstantInt::get(IntTy64, Val),
392 UndefValue::get(IntTy64)};
393 return ConstantVector::get(Args);
396 // See if we're dealing with constant values.
397 Constant *C0 = dyn_cast<Constant>(Op0);
399 C0 ? dyn_cast<ConstantInt>(C0->getAggregateElement((unsigned)0))
402 // Attempt to constant fold.
403 if (CILength && CIIndex) {
404 // From AMD documentation: "The bit index and field length are each six
405 // bits in length other bits of the field are ignored."
406 APInt APIndex = CIIndex->getValue().zextOrTrunc(6);
407 APInt APLength = CILength->getValue().zextOrTrunc(6);
409 unsigned Index = APIndex.getZExtValue();
411 // From AMD documentation: "a value of zero in the field length is
412 // defined as length of 64".
413 unsigned Length = APLength == 0 ? 64 : APLength.getZExtValue();
415 // From AMD documentation: "If the sum of the bit index + length field
416 // is greater than 64, the results are undefined".
417 unsigned End = Index + Length;
419 // Note that both field index and field length are 8-bit quantities.
420 // Since variables 'Index' and 'Length' are unsigned values
421 // obtained from zero-extending field index and field length
422 // respectively, their sum should never wrap around.
424 return UndefValue::get(II.getType());
426 // If we are inserting whole bytes, we can convert this to a shuffle.
427 // Lowering can recognize EXTRQI shuffle masks.
428 if ((Length % 8) == 0 && (Index % 8) == 0) {
429 // Convert bit indices to byte indices.
433 Type *IntTy8 = Type::getInt8Ty(II.getContext());
434 Type *IntTy32 = Type::getInt32Ty(II.getContext());
435 VectorType *ShufTy = VectorType::get(IntTy8, 16);
437 SmallVector<Constant *, 16> ShuffleMask;
438 for (int i = 0; i != (int)Length; ++i)
439 ShuffleMask.push_back(
440 Constant::getIntegerValue(IntTy32, APInt(32, i + Index)));
441 for (int i = Length; i != 8; ++i)
442 ShuffleMask.push_back(
443 Constant::getIntegerValue(IntTy32, APInt(32, i + 16)));
444 for (int i = 8; i != 16; ++i)
445 ShuffleMask.push_back(UndefValue::get(IntTy32));
447 Value *SV = Builder.CreateShuffleVector(
448 Builder.CreateBitCast(Op0, ShufTy),
449 ConstantAggregateZero::get(ShufTy), ConstantVector::get(ShuffleMask));
450 return Builder.CreateBitCast(SV, II.getType());
453 // Constant Fold - shift Index'th bit to lowest position and mask off
456 APInt Elt = CI0->getValue();
457 Elt = Elt.lshr(Index).zextOrTrunc(Length);
458 return LowConstantHighUndef(Elt.getZExtValue());
461 // If we were an EXTRQ call, we'll save registers if we convert to EXTRQI.
462 if (II.getIntrinsicID() == Intrinsic::x86_sse4a_extrq) {
463 Value *Args[] = {Op0, CILength, CIIndex};
464 Module *M = II.getParent()->getParent()->getParent();
465 Value *F = Intrinsic::getDeclaration(M, Intrinsic::x86_sse4a_extrqi);
466 return Builder.CreateCall(F, Args);
470 // Constant Fold - extraction from zero is always {zero, undef}.
471 if (CI0 && CI0->equalsInt(0))
472 return LowConstantHighUndef(0);
477 /// Attempt to simplify SSE4A INSERTQ/INSERTQI instructions using constant
478 /// folding or conversion to a shuffle vector.
479 static Value *SimplifyX86insertq(IntrinsicInst &II, Value *Op0, Value *Op1,
480 APInt APLength, APInt APIndex,
481 InstCombiner::BuilderTy &Builder) {
483 // From AMD documentation: "The bit index and field length are each six bits
484 // in length other bits of the field are ignored."
485 APIndex = APIndex.zextOrTrunc(6);
486 APLength = APLength.zextOrTrunc(6);
488 // Attempt to constant fold.
489 unsigned Index = APIndex.getZExtValue();
491 // From AMD documentation: "a value of zero in the field length is
492 // defined as length of 64".
493 unsigned Length = APLength == 0 ? 64 : APLength.getZExtValue();
495 // From AMD documentation: "If the sum of the bit index + length field
496 // is greater than 64, the results are undefined".
497 unsigned End = Index + Length;
499 // Note that both field index and field length are 8-bit quantities.
500 // Since variables 'Index' and 'Length' are unsigned values
501 // obtained from zero-extending field index and field length
502 // respectively, their sum should never wrap around.
504 return UndefValue::get(II.getType());
506 // If we are inserting whole bytes, we can convert this to a shuffle.
507 // Lowering can recognize INSERTQI shuffle masks.
508 if ((Length % 8) == 0 && (Index % 8) == 0) {
509 // Convert bit indices to byte indices.
513 Type *IntTy8 = Type::getInt8Ty(II.getContext());
514 Type *IntTy32 = Type::getInt32Ty(II.getContext());
515 VectorType *ShufTy = VectorType::get(IntTy8, 16);
517 SmallVector<Constant *, 16> ShuffleMask;
518 for (int i = 0; i != (int)Index; ++i)
519 ShuffleMask.push_back(Constant::getIntegerValue(IntTy32, APInt(32, i)));
520 for (int i = 0; i != (int)Length; ++i)
521 ShuffleMask.push_back(
522 Constant::getIntegerValue(IntTy32, APInt(32, i + 16)));
523 for (int i = Index + Length; i != 8; ++i)
524 ShuffleMask.push_back(Constant::getIntegerValue(IntTy32, APInt(32, i)));
525 for (int i = 8; i != 16; ++i)
526 ShuffleMask.push_back(UndefValue::get(IntTy32));
528 Value *SV = Builder.CreateShuffleVector(Builder.CreateBitCast(Op0, ShufTy),
529 Builder.CreateBitCast(Op1, ShufTy),
530 ConstantVector::get(ShuffleMask));
531 return Builder.CreateBitCast(SV, II.getType());
534 // See if we're dealing with constant values.
535 Constant *C0 = dyn_cast<Constant>(Op0);
536 Constant *C1 = dyn_cast<Constant>(Op1);
538 C0 ? dyn_cast<ConstantInt>(C0->getAggregateElement((unsigned)0))
541 C1 ? dyn_cast<ConstantInt>(C1->getAggregateElement((unsigned)0))
544 // Constant Fold - insert bottom Length bits starting at the Index'th bit.
546 APInt V00 = CI00->getValue();
547 APInt V10 = CI10->getValue();
548 APInt Mask = APInt::getLowBitsSet(64, Length).shl(Index);
550 V10 = V10.zextOrTrunc(Length).zextOrTrunc(64).shl(Index);
551 APInt Val = V00 | V10;
552 Type *IntTy64 = Type::getInt64Ty(II.getContext());
553 Constant *Args[] = {ConstantInt::get(IntTy64, Val.getZExtValue()),
554 UndefValue::get(IntTy64)};
555 return ConstantVector::get(Args);
558 // If we were an INSERTQ call, we'll save demanded elements if we convert to
560 if (II.getIntrinsicID() == Intrinsic::x86_sse4a_insertq) {
561 Type *IntTy8 = Type::getInt8Ty(II.getContext());
562 Constant *CILength = ConstantInt::get(IntTy8, Length, false);
563 Constant *CIIndex = ConstantInt::get(IntTy8, Index, false);
565 Value *Args[] = {Op0, Op1, CILength, CIIndex};
566 Module *M = II.getParent()->getParent()->getParent();
567 Value *F = Intrinsic::getDeclaration(M, Intrinsic::x86_sse4a_insertqi);
568 return Builder.CreateCall(F, Args);
574 /// The shuffle mask for a perm2*128 selects any two halves of two 256-bit
575 /// source vectors, unless a zero bit is set. If a zero bit is set,
576 /// then ignore that half of the mask and clear that half of the vector.
577 static Value *SimplifyX86vperm2(const IntrinsicInst &II,
578 InstCombiner::BuilderTy &Builder) {
579 if (auto *CInt = dyn_cast<ConstantInt>(II.getArgOperand(2))) {
580 VectorType *VecTy = cast<VectorType>(II.getType());
581 ConstantAggregateZero *ZeroVector = ConstantAggregateZero::get(VecTy);
583 // The immediate permute control byte looks like this:
584 // [1:0] - select 128 bits from sources for low half of destination
586 // [3] - zero low half of destination
587 // [5:4] - select 128 bits from sources for high half of destination
589 // [7] - zero high half of destination
591 uint8_t Imm = CInt->getZExtValue();
593 bool LowHalfZero = Imm & 0x08;
594 bool HighHalfZero = Imm & 0x80;
596 // If both zero mask bits are set, this was just a weird way to
597 // generate a zero vector.
598 if (LowHalfZero && HighHalfZero)
601 // If 0 or 1 zero mask bits are set, this is a simple shuffle.
602 unsigned NumElts = VecTy->getNumElements();
603 unsigned HalfSize = NumElts / 2;
604 SmallVector<int, 8> ShuffleMask(NumElts);
606 // The high bit of the selection field chooses the 1st or 2nd operand.
607 bool LowInputSelect = Imm & 0x02;
608 bool HighInputSelect = Imm & 0x20;
610 // The low bit of the selection field chooses the low or high half
611 // of the selected operand.
612 bool LowHalfSelect = Imm & 0x01;
613 bool HighHalfSelect = Imm & 0x10;
615 // Determine which operand(s) are actually in use for this instruction.
616 Value *V0 = LowInputSelect ? II.getArgOperand(1) : II.getArgOperand(0);
617 Value *V1 = HighInputSelect ? II.getArgOperand(1) : II.getArgOperand(0);
619 // If needed, replace operands based on zero mask.
620 V0 = LowHalfZero ? ZeroVector : V0;
621 V1 = HighHalfZero ? ZeroVector : V1;
623 // Permute low half of result.
624 unsigned StartIndex = LowHalfSelect ? HalfSize : 0;
625 for (unsigned i = 0; i < HalfSize; ++i)
626 ShuffleMask[i] = StartIndex + i;
628 // Permute high half of result.
629 StartIndex = HighHalfSelect ? HalfSize : 0;
630 StartIndex += NumElts;
631 for (unsigned i = 0; i < HalfSize; ++i)
632 ShuffleMask[i + HalfSize] = StartIndex + i;
634 return Builder.CreateShuffleVector(V0, V1, ShuffleMask);
639 /// Decode XOP integer vector comparison intrinsics.
640 static Value *SimplifyX86vpcom(const IntrinsicInst &II,
641 InstCombiner::BuilderTy &Builder, bool IsSigned) {
642 if (auto *CInt = dyn_cast<ConstantInt>(II.getArgOperand(2))) {
643 uint64_t Imm = CInt->getZExtValue() & 0x7;
644 VectorType *VecTy = cast<VectorType>(II.getType());
645 CmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
649 Pred = IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
652 Pred = IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
655 Pred = IsSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
658 Pred = IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
661 Pred = ICmpInst::ICMP_EQ; break;
663 Pred = ICmpInst::ICMP_NE; break;
665 return ConstantInt::getSigned(VecTy, 0); // FALSE
667 return ConstantInt::getSigned(VecTy, -1); // TRUE
670 if (Value *Cmp = Builder.CreateICmp(Pred, II.getArgOperand(0), II.getArgOperand(1)))
671 return Builder.CreateSExtOrTrunc(Cmp, VecTy);
676 /// visitCallInst - CallInst simplification. This mostly only handles folding
677 /// of intrinsic instructions. For normal calls, it allows visitCallSite to do
678 /// the heavy lifting.
680 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
681 auto Args = CI.arg_operands();
682 if (Value *V = SimplifyCall(CI.getCalledValue(), Args.begin(), Args.end(), DL,
684 return ReplaceInstUsesWith(CI, V);
686 if (isFreeCall(&CI, TLI))
687 return visitFree(CI);
689 // If the caller function is nounwind, mark the call as nounwind, even if the
691 if (CI.getParent()->getParent()->doesNotThrow() &&
692 !CI.doesNotThrow()) {
693 CI.setDoesNotThrow();
697 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
698 if (!II) return visitCallSite(&CI);
700 // Intrinsics cannot occur in an invoke, so handle them here instead of in
702 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
703 bool Changed = false;
705 // memmove/cpy/set of zero bytes is a noop.
706 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
707 if (NumBytes->isNullValue())
708 return EraseInstFromFunction(CI);
710 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
711 if (CI->getZExtValue() == 1) {
712 // Replace the instruction with just byte operations. We would
713 // transform other cases to loads/stores, but we don't know if
714 // alignment is sufficient.
718 // No other transformations apply to volatile transfers.
719 if (MI->isVolatile())
722 // If we have a memmove and the source operation is a constant global,
723 // then the source and dest pointers can't alias, so we can change this
724 // into a call to memcpy.
725 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
726 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
727 if (GVSrc->isConstant()) {
728 Module *M = CI.getParent()->getParent()->getParent();
729 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
730 Type *Tys[3] = { CI.getArgOperand(0)->getType(),
731 CI.getArgOperand(1)->getType(),
732 CI.getArgOperand(2)->getType() };
733 CI.setCalledFunction(Intrinsic::getDeclaration(M, MemCpyID, Tys));
738 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) {
739 // memmove(x,x,size) -> noop.
740 if (MTI->getSource() == MTI->getDest())
741 return EraseInstFromFunction(CI);
744 // If we can determine a pointer alignment that is bigger than currently
745 // set, update the alignment.
746 if (isa<MemTransferInst>(MI)) {
747 if (Instruction *I = SimplifyMemTransfer(MI))
749 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
750 if (Instruction *I = SimplifyMemSet(MSI))
754 if (Changed) return II;
757 auto SimplifyDemandedVectorEltsLow = [this](Value *Op, unsigned Width, unsigned DemandedWidth)
759 APInt UndefElts(Width, 0);
760 APInt DemandedElts = APInt::getLowBitsSet(Width, DemandedWidth);
761 return SimplifyDemandedVectorElts(Op, DemandedElts, UndefElts);
764 switch (II->getIntrinsicID()) {
766 case Intrinsic::objectsize: {
768 if (getObjectSize(II->getArgOperand(0), Size, DL, TLI))
769 return ReplaceInstUsesWith(CI, ConstantInt::get(CI.getType(), Size));
772 case Intrinsic::bswap: {
773 Value *IIOperand = II->getArgOperand(0);
776 // bswap(bswap(x)) -> x
777 if (match(IIOperand, m_BSwap(m_Value(X))))
778 return ReplaceInstUsesWith(CI, X);
780 // bswap(trunc(bswap(x))) -> trunc(lshr(x, c))
781 if (match(IIOperand, m_Trunc(m_BSwap(m_Value(X))))) {
782 unsigned C = X->getType()->getPrimitiveSizeInBits() -
783 IIOperand->getType()->getPrimitiveSizeInBits();
784 Value *CV = ConstantInt::get(X->getType(), C);
785 Value *V = Builder->CreateLShr(X, CV);
786 return new TruncInst(V, IIOperand->getType());
791 case Intrinsic::powi:
792 if (ConstantInt *Power = dyn_cast<ConstantInt>(II->getArgOperand(1))) {
795 return ReplaceInstUsesWith(CI, ConstantFP::get(CI.getType(), 1.0));
798 return ReplaceInstUsesWith(CI, II->getArgOperand(0));
799 // powi(x, -1) -> 1/x
800 if (Power->isAllOnesValue())
801 return BinaryOperator::CreateFDiv(ConstantFP::get(CI.getType(), 1.0),
802 II->getArgOperand(0));
805 case Intrinsic::cttz: {
806 // If all bits below the first known one are known zero,
807 // this value is constant.
808 IntegerType *IT = dyn_cast<IntegerType>(II->getArgOperand(0)->getType());
809 // FIXME: Try to simplify vectors of integers.
811 uint32_t BitWidth = IT->getBitWidth();
812 APInt KnownZero(BitWidth, 0);
813 APInt KnownOne(BitWidth, 0);
814 computeKnownBits(II->getArgOperand(0), KnownZero, KnownOne, 0, II);
815 unsigned TrailingZeros = KnownOne.countTrailingZeros();
816 APInt Mask(APInt::getLowBitsSet(BitWidth, TrailingZeros));
817 if ((Mask & KnownZero) == Mask)
818 return ReplaceInstUsesWith(CI, ConstantInt::get(IT,
819 APInt(BitWidth, TrailingZeros)));
823 case Intrinsic::ctlz: {
824 // If all bits above the first known one are known zero,
825 // this value is constant.
826 IntegerType *IT = dyn_cast<IntegerType>(II->getArgOperand(0)->getType());
827 // FIXME: Try to simplify vectors of integers.
829 uint32_t BitWidth = IT->getBitWidth();
830 APInt KnownZero(BitWidth, 0);
831 APInt KnownOne(BitWidth, 0);
832 computeKnownBits(II->getArgOperand(0), KnownZero, KnownOne, 0, II);
833 unsigned LeadingZeros = KnownOne.countLeadingZeros();
834 APInt Mask(APInt::getHighBitsSet(BitWidth, LeadingZeros));
835 if ((Mask & KnownZero) == Mask)
836 return ReplaceInstUsesWith(CI, ConstantInt::get(IT,
837 APInt(BitWidth, LeadingZeros)));
842 case Intrinsic::uadd_with_overflow:
843 case Intrinsic::sadd_with_overflow:
844 case Intrinsic::umul_with_overflow:
845 case Intrinsic::smul_with_overflow:
846 if (isa<Constant>(II->getArgOperand(0)) &&
847 !isa<Constant>(II->getArgOperand(1))) {
848 // Canonicalize constants into the RHS.
849 Value *LHS = II->getArgOperand(0);
850 II->setArgOperand(0, II->getArgOperand(1));
851 II->setArgOperand(1, LHS);
856 case Intrinsic::usub_with_overflow:
857 case Intrinsic::ssub_with_overflow: {
858 OverflowCheckFlavor OCF =
859 IntrinsicIDToOverflowCheckFlavor(II->getIntrinsicID());
860 assert(OCF != OCF_INVALID && "unexpected!");
862 Value *OperationResult = nullptr;
863 Constant *OverflowResult = nullptr;
864 if (OptimizeOverflowCheck(OCF, II->getArgOperand(0), II->getArgOperand(1),
865 *II, OperationResult, OverflowResult))
866 return CreateOverflowTuple(II, OperationResult, OverflowResult);
871 case Intrinsic::minnum:
872 case Intrinsic::maxnum: {
873 Value *Arg0 = II->getArgOperand(0);
874 Value *Arg1 = II->getArgOperand(1);
878 return ReplaceInstUsesWith(CI, Arg0);
880 const ConstantFP *C0 = dyn_cast<ConstantFP>(Arg0);
881 const ConstantFP *C1 = dyn_cast<ConstantFP>(Arg1);
883 // Canonicalize constants into the RHS.
885 II->setArgOperand(0, Arg1);
886 II->setArgOperand(1, Arg0);
891 if (C1 && C1->isNaN())
892 return ReplaceInstUsesWith(CI, Arg0);
894 // This is the value because if undef were NaN, we would return the other
895 // value and cannot return a NaN unless both operands are.
897 // fmin(undef, x) -> x
898 if (isa<UndefValue>(Arg0))
899 return ReplaceInstUsesWith(CI, Arg1);
901 // fmin(x, undef) -> x
902 if (isa<UndefValue>(Arg1))
903 return ReplaceInstUsesWith(CI, Arg0);
907 if (II->getIntrinsicID() == Intrinsic::minnum) {
908 // fmin(x, fmin(x, y)) -> fmin(x, y)
909 // fmin(y, fmin(x, y)) -> fmin(x, y)
910 if (match(Arg1, m_FMin(m_Value(X), m_Value(Y)))) {
911 if (Arg0 == X || Arg0 == Y)
912 return ReplaceInstUsesWith(CI, Arg1);
915 // fmin(fmin(x, y), x) -> fmin(x, y)
916 // fmin(fmin(x, y), y) -> fmin(x, y)
917 if (match(Arg0, m_FMin(m_Value(X), m_Value(Y)))) {
918 if (Arg1 == X || Arg1 == Y)
919 return ReplaceInstUsesWith(CI, Arg0);
922 // TODO: fmin(nnan x, inf) -> x
923 // TODO: fmin(nnan ninf x, flt_max) -> x
924 if (C1 && C1->isInfinity()) {
925 // fmin(x, -inf) -> -inf
926 if (C1->isNegative())
927 return ReplaceInstUsesWith(CI, Arg1);
930 assert(II->getIntrinsicID() == Intrinsic::maxnum);
931 // fmax(x, fmax(x, y)) -> fmax(x, y)
932 // fmax(y, fmax(x, y)) -> fmax(x, y)
933 if (match(Arg1, m_FMax(m_Value(X), m_Value(Y)))) {
934 if (Arg0 == X || Arg0 == Y)
935 return ReplaceInstUsesWith(CI, Arg1);
938 // fmax(fmax(x, y), x) -> fmax(x, y)
939 // fmax(fmax(x, y), y) -> fmax(x, y)
940 if (match(Arg0, m_FMax(m_Value(X), m_Value(Y)))) {
941 if (Arg1 == X || Arg1 == Y)
942 return ReplaceInstUsesWith(CI, Arg0);
945 // TODO: fmax(nnan x, -inf) -> x
946 // TODO: fmax(nnan ninf x, -flt_max) -> x
947 if (C1 && C1->isInfinity()) {
948 // fmax(x, inf) -> inf
949 if (!C1->isNegative())
950 return ReplaceInstUsesWith(CI, Arg1);
955 case Intrinsic::ppc_altivec_lvx:
956 case Intrinsic::ppc_altivec_lvxl:
957 // Turn PPC lvx -> load if the pointer is known aligned.
958 if (getOrEnforceKnownAlignment(II->getArgOperand(0), 16, DL, II, AC, DT) >=
960 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(0),
961 PointerType::getUnqual(II->getType()));
962 return new LoadInst(Ptr);
965 case Intrinsic::ppc_vsx_lxvw4x:
966 case Intrinsic::ppc_vsx_lxvd2x: {
967 // Turn PPC VSX loads into normal loads.
968 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(0),
969 PointerType::getUnqual(II->getType()));
970 return new LoadInst(Ptr, Twine(""), false, 1);
972 case Intrinsic::ppc_altivec_stvx:
973 case Intrinsic::ppc_altivec_stvxl:
974 // Turn stvx -> store if the pointer is known aligned.
975 if (getOrEnforceKnownAlignment(II->getArgOperand(1), 16, DL, II, AC, DT) >=
978 PointerType::getUnqual(II->getArgOperand(0)->getType());
979 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(1), OpPtrTy);
980 return new StoreInst(II->getArgOperand(0), Ptr);
983 case Intrinsic::ppc_vsx_stxvw4x:
984 case Intrinsic::ppc_vsx_stxvd2x: {
985 // Turn PPC VSX stores into normal stores.
986 Type *OpPtrTy = PointerType::getUnqual(II->getArgOperand(0)->getType());
987 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(1), OpPtrTy);
988 return new StoreInst(II->getArgOperand(0), Ptr, false, 1);
990 case Intrinsic::ppc_qpx_qvlfs:
991 // Turn PPC QPX qvlfs -> load if the pointer is known aligned.
992 if (getOrEnforceKnownAlignment(II->getArgOperand(0), 16, DL, II, AC, DT) >=
994 Type *VTy = VectorType::get(Builder->getFloatTy(),
995 II->getType()->getVectorNumElements());
996 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(0),
997 PointerType::getUnqual(VTy));
998 Value *Load = Builder->CreateLoad(Ptr);
999 return new FPExtInst(Load, II->getType());
1002 case Intrinsic::ppc_qpx_qvlfd:
1003 // Turn PPC QPX qvlfd -> load if the pointer is known aligned.
1004 if (getOrEnforceKnownAlignment(II->getArgOperand(0), 32, DL, II, AC, DT) >=
1006 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(0),
1007 PointerType::getUnqual(II->getType()));
1008 return new LoadInst(Ptr);
1011 case Intrinsic::ppc_qpx_qvstfs:
1012 // Turn PPC QPX qvstfs -> store if the pointer is known aligned.
1013 if (getOrEnforceKnownAlignment(II->getArgOperand(1), 16, DL, II, AC, DT) >=
1015 Type *VTy = VectorType::get(Builder->getFloatTy(),
1016 II->getArgOperand(0)->getType()->getVectorNumElements());
1017 Value *TOp = Builder->CreateFPTrunc(II->getArgOperand(0), VTy);
1018 Type *OpPtrTy = PointerType::getUnqual(VTy);
1019 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(1), OpPtrTy);
1020 return new StoreInst(TOp, Ptr);
1023 case Intrinsic::ppc_qpx_qvstfd:
1024 // Turn PPC QPX qvstfd -> store if the pointer is known aligned.
1025 if (getOrEnforceKnownAlignment(II->getArgOperand(1), 32, DL, II, AC, DT) >=
1028 PointerType::getUnqual(II->getArgOperand(0)->getType());
1029 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(1), OpPtrTy);
1030 return new StoreInst(II->getArgOperand(0), Ptr);
1034 case Intrinsic::x86_sse_storeu_ps:
1035 case Intrinsic::x86_sse2_storeu_pd:
1036 case Intrinsic::x86_sse2_storeu_dq:
1037 // Turn X86 storeu -> store if the pointer is known aligned.
1038 if (getOrEnforceKnownAlignment(II->getArgOperand(0), 16, DL, II, AC, DT) >=
1041 PointerType::getUnqual(II->getArgOperand(1)->getType());
1042 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(0), OpPtrTy);
1043 return new StoreInst(II->getArgOperand(1), Ptr);
1047 case Intrinsic::x86_vcvtph2ps_128:
1048 case Intrinsic::x86_vcvtph2ps_256: {
1049 auto Arg = II->getArgOperand(0);
1050 auto ArgType = cast<VectorType>(Arg->getType());
1051 auto RetType = cast<VectorType>(II->getType());
1052 unsigned ArgWidth = ArgType->getNumElements();
1053 unsigned RetWidth = RetType->getNumElements();
1054 assert(RetWidth <= ArgWidth && "Unexpected input/return vector widths");
1055 assert(ArgType->isIntOrIntVectorTy() &&
1056 ArgType->getScalarSizeInBits() == 16 &&
1057 "CVTPH2PS input type should be 16-bit integer vector");
1058 assert(RetType->getScalarType()->isFloatTy() &&
1059 "CVTPH2PS output type should be 32-bit float vector");
1061 // Constant folding: Convert to generic half to single conversion.
1062 if (isa<ConstantAggregateZero>(Arg))
1063 return ReplaceInstUsesWith(*II, ConstantAggregateZero::get(RetType));
1065 if (isa<ConstantDataVector>(Arg)) {
1066 auto VectorHalfAsShorts = Arg;
1067 if (RetWidth < ArgWidth) {
1068 SmallVector<int, 8> SubVecMask;
1069 for (unsigned i = 0; i != RetWidth; ++i)
1070 SubVecMask.push_back((int)i);
1071 VectorHalfAsShorts = Builder->CreateShuffleVector(
1072 Arg, UndefValue::get(ArgType), SubVecMask);
1075 auto VectorHalfType =
1076 VectorType::get(Type::getHalfTy(II->getContext()), RetWidth);
1078 Builder->CreateBitCast(VectorHalfAsShorts, VectorHalfType);
1079 auto VectorFloats = Builder->CreateFPExt(VectorHalfs, RetType);
1080 return ReplaceInstUsesWith(*II, VectorFloats);
1083 // We only use the lowest lanes of the argument.
1084 if (Value *V = SimplifyDemandedVectorEltsLow(Arg, ArgWidth, RetWidth)) {
1085 II->setArgOperand(0, V);
1091 case Intrinsic::x86_sse_cvtss2si:
1092 case Intrinsic::x86_sse_cvtss2si64:
1093 case Intrinsic::x86_sse_cvttss2si:
1094 case Intrinsic::x86_sse_cvttss2si64:
1095 case Intrinsic::x86_sse2_cvtsd2si:
1096 case Intrinsic::x86_sse2_cvtsd2si64:
1097 case Intrinsic::x86_sse2_cvttsd2si:
1098 case Intrinsic::x86_sse2_cvttsd2si64: {
1099 // These intrinsics only demand the 0th element of their input vectors. If
1100 // we can simplify the input based on that, do so now.
1101 Value *Arg = II->getArgOperand(0);
1102 unsigned VWidth = Arg->getType()->getVectorNumElements();
1103 if (Value *V = SimplifyDemandedVectorEltsLow(Arg, VWidth, 1)) {
1104 II->setArgOperand(0, V);
1110 // Constant fold ashr( <A x Bi>, Ci ).
1111 // Constant fold lshr( <A x Bi>, Ci ).
1112 // Constant fold shl( <A x Bi>, Ci ).
1113 case Intrinsic::x86_sse2_psrai_d:
1114 case Intrinsic::x86_sse2_psrai_w:
1115 case Intrinsic::x86_avx2_psrai_d:
1116 case Intrinsic::x86_avx2_psrai_w:
1117 case Intrinsic::x86_sse2_psrli_d:
1118 case Intrinsic::x86_sse2_psrli_q:
1119 case Intrinsic::x86_sse2_psrli_w:
1120 case Intrinsic::x86_avx2_psrli_d:
1121 case Intrinsic::x86_avx2_psrli_q:
1122 case Intrinsic::x86_avx2_psrli_w:
1123 case Intrinsic::x86_sse2_pslli_d:
1124 case Intrinsic::x86_sse2_pslli_q:
1125 case Intrinsic::x86_sse2_pslli_w:
1126 case Intrinsic::x86_avx2_pslli_d:
1127 case Intrinsic::x86_avx2_pslli_q:
1128 case Intrinsic::x86_avx2_pslli_w:
1129 if (Value *V = SimplifyX86immshift(*II, *Builder))
1130 return ReplaceInstUsesWith(*II, V);
1133 case Intrinsic::x86_sse2_psra_d:
1134 case Intrinsic::x86_sse2_psra_w:
1135 case Intrinsic::x86_avx2_psra_d:
1136 case Intrinsic::x86_avx2_psra_w:
1137 case Intrinsic::x86_sse2_psrl_d:
1138 case Intrinsic::x86_sse2_psrl_q:
1139 case Intrinsic::x86_sse2_psrl_w:
1140 case Intrinsic::x86_avx2_psrl_d:
1141 case Intrinsic::x86_avx2_psrl_q:
1142 case Intrinsic::x86_avx2_psrl_w:
1143 case Intrinsic::x86_sse2_psll_d:
1144 case Intrinsic::x86_sse2_psll_q:
1145 case Intrinsic::x86_sse2_psll_w:
1146 case Intrinsic::x86_avx2_psll_d:
1147 case Intrinsic::x86_avx2_psll_q:
1148 case Intrinsic::x86_avx2_psll_w: {
1149 if (Value *V = SimplifyX86immshift(*II, *Builder))
1150 return ReplaceInstUsesWith(*II, V);
1152 // SSE2/AVX2 uses only the first 64-bits of the 128-bit vector
1153 // operand to compute the shift amount.
1154 Value *Arg1 = II->getArgOperand(1);
1155 assert(Arg1->getType()->getPrimitiveSizeInBits() == 128 &&
1156 "Unexpected packed shift size");
1157 unsigned VWidth = Arg1->getType()->getVectorNumElements();
1159 if (Value *V = SimplifyDemandedVectorEltsLow(Arg1, VWidth, VWidth / 2)) {
1160 II->setArgOperand(1, V);
1166 case Intrinsic::x86_avx2_pmovsxbd:
1167 case Intrinsic::x86_avx2_pmovsxbq:
1168 case Intrinsic::x86_avx2_pmovsxbw:
1169 case Intrinsic::x86_avx2_pmovsxdq:
1170 case Intrinsic::x86_avx2_pmovsxwd:
1171 case Intrinsic::x86_avx2_pmovsxwq:
1172 if (Value *V = SimplifyX86extend(*II, *Builder, true))
1173 return ReplaceInstUsesWith(*II, V);
1176 case Intrinsic::x86_sse41_pmovzxbd:
1177 case Intrinsic::x86_sse41_pmovzxbq:
1178 case Intrinsic::x86_sse41_pmovzxbw:
1179 case Intrinsic::x86_sse41_pmovzxdq:
1180 case Intrinsic::x86_sse41_pmovzxwd:
1181 case Intrinsic::x86_sse41_pmovzxwq:
1182 case Intrinsic::x86_avx2_pmovzxbd:
1183 case Intrinsic::x86_avx2_pmovzxbq:
1184 case Intrinsic::x86_avx2_pmovzxbw:
1185 case Intrinsic::x86_avx2_pmovzxdq:
1186 case Intrinsic::x86_avx2_pmovzxwd:
1187 case Intrinsic::x86_avx2_pmovzxwq:
1188 if (Value *V = SimplifyX86extend(*II, *Builder, false))
1189 return ReplaceInstUsesWith(*II, V);
1192 case Intrinsic::x86_sse41_insertps:
1193 if (Value *V = SimplifyX86insertps(*II, *Builder))
1194 return ReplaceInstUsesWith(*II, V);
1197 case Intrinsic::x86_sse4a_extrq: {
1198 Value *Op0 = II->getArgOperand(0);
1199 Value *Op1 = II->getArgOperand(1);
1200 unsigned VWidth0 = Op0->getType()->getVectorNumElements();
1201 unsigned VWidth1 = Op1->getType()->getVectorNumElements();
1202 assert(Op0->getType()->getPrimitiveSizeInBits() == 128 &&
1203 Op1->getType()->getPrimitiveSizeInBits() == 128 && VWidth0 == 2 &&
1204 VWidth1 == 16 && "Unexpected operand sizes");
1206 // See if we're dealing with constant values.
1207 Constant *C1 = dyn_cast<Constant>(Op1);
1208 ConstantInt *CILength =
1209 C1 ? dyn_cast<ConstantInt>(C1->getAggregateElement((unsigned)0))
1211 ConstantInt *CIIndex =
1212 C1 ? dyn_cast<ConstantInt>(C1->getAggregateElement((unsigned)1))
1215 // Attempt to simplify to a constant, shuffle vector or EXTRQI call.
1216 if (Value *V = SimplifyX86extrq(*II, Op0, CILength, CIIndex, *Builder))
1217 return ReplaceInstUsesWith(*II, V);
1219 // EXTRQ only uses the lowest 64-bits of the first 128-bit vector
1220 // operands and the lowest 16-bits of the second.
1221 if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth0, 1)) {
1222 II->setArgOperand(0, V);
1225 if (Value *V = SimplifyDemandedVectorEltsLow(Op1, VWidth1, 2)) {
1226 II->setArgOperand(1, V);
1232 case Intrinsic::x86_sse4a_extrqi: {
1233 // EXTRQI: Extract Length bits starting from Index. Zero pad the remaining
1234 // bits of the lower 64-bits. The upper 64-bits are undefined.
1235 Value *Op0 = II->getArgOperand(0);
1236 unsigned VWidth = Op0->getType()->getVectorNumElements();
1237 assert(Op0->getType()->getPrimitiveSizeInBits() == 128 && VWidth == 2 &&
1238 "Unexpected operand size");
1240 // See if we're dealing with constant values.
1241 ConstantInt *CILength = dyn_cast<ConstantInt>(II->getArgOperand(1));
1242 ConstantInt *CIIndex = dyn_cast<ConstantInt>(II->getArgOperand(2));
1244 // Attempt to simplify to a constant or shuffle vector.
1245 if (Value *V = SimplifyX86extrq(*II, Op0, CILength, CIIndex, *Builder))
1246 return ReplaceInstUsesWith(*II, V);
1248 // EXTRQI only uses the lowest 64-bits of the first 128-bit vector
1250 if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth, 1)) {
1251 II->setArgOperand(0, V);
1257 case Intrinsic::x86_sse4a_insertq: {
1258 Value *Op0 = II->getArgOperand(0);
1259 Value *Op1 = II->getArgOperand(1);
1260 unsigned VWidth = Op0->getType()->getVectorNumElements();
1261 assert(Op0->getType()->getPrimitiveSizeInBits() == 128 &&
1262 Op1->getType()->getPrimitiveSizeInBits() == 128 && VWidth == 2 &&
1263 Op1->getType()->getVectorNumElements() == 2 &&
1264 "Unexpected operand size");
1266 // See if we're dealing with constant values.
1267 Constant *C1 = dyn_cast<Constant>(Op1);
1269 C1 ? dyn_cast<ConstantInt>(C1->getAggregateElement((unsigned)1))
1272 // Attempt to simplify to a constant, shuffle vector or INSERTQI call.
1274 APInt V11 = CI11->getValue();
1275 APInt Len = V11.zextOrTrunc(6);
1276 APInt Idx = V11.lshr(8).zextOrTrunc(6);
1277 if (Value *V = SimplifyX86insertq(*II, Op0, Op1, Len, Idx, *Builder))
1278 return ReplaceInstUsesWith(*II, V);
1281 // INSERTQ only uses the lowest 64-bits of the first 128-bit vector
1283 if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth, 1)) {
1284 II->setArgOperand(0, V);
1290 case Intrinsic::x86_sse4a_insertqi: {
1291 // INSERTQI: Extract lowest Length bits from lower half of second source and
1292 // insert over first source starting at Index bit. The upper 64-bits are
1294 Value *Op0 = II->getArgOperand(0);
1295 Value *Op1 = II->getArgOperand(1);
1296 unsigned VWidth0 = Op0->getType()->getVectorNumElements();
1297 unsigned VWidth1 = Op1->getType()->getVectorNumElements();
1298 assert(Op0->getType()->getPrimitiveSizeInBits() == 128 &&
1299 Op1->getType()->getPrimitiveSizeInBits() == 128 && VWidth0 == 2 &&
1300 VWidth1 == 2 && "Unexpected operand sizes");
1302 // See if we're dealing with constant values.
1303 ConstantInt *CILength = dyn_cast<ConstantInt>(II->getArgOperand(2));
1304 ConstantInt *CIIndex = dyn_cast<ConstantInt>(II->getArgOperand(3));
1306 // Attempt to simplify to a constant or shuffle vector.
1307 if (CILength && CIIndex) {
1308 APInt Len = CILength->getValue().zextOrTrunc(6);
1309 APInt Idx = CIIndex->getValue().zextOrTrunc(6);
1310 if (Value *V = SimplifyX86insertq(*II, Op0, Op1, Len, Idx, *Builder))
1311 return ReplaceInstUsesWith(*II, V);
1314 // INSERTQI only uses the lowest 64-bits of the first two 128-bit vector
1316 if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth0, 1)) {
1317 II->setArgOperand(0, V);
1321 if (Value *V = SimplifyDemandedVectorEltsLow(Op1, VWidth1, 1)) {
1322 II->setArgOperand(1, V);
1328 case Intrinsic::x86_sse41_pblendvb:
1329 case Intrinsic::x86_sse41_blendvps:
1330 case Intrinsic::x86_sse41_blendvpd:
1331 case Intrinsic::x86_avx_blendv_ps_256:
1332 case Intrinsic::x86_avx_blendv_pd_256:
1333 case Intrinsic::x86_avx2_pblendvb: {
1334 // Convert blendv* to vector selects if the mask is constant.
1335 // This optimization is convoluted because the intrinsic is defined as
1336 // getting a vector of floats or doubles for the ps and pd versions.
1337 // FIXME: That should be changed.
1339 Value *Op0 = II->getArgOperand(0);
1340 Value *Op1 = II->getArgOperand(1);
1341 Value *Mask = II->getArgOperand(2);
1343 // fold (blend A, A, Mask) -> A
1345 return ReplaceInstUsesWith(CI, Op0);
1347 // Zero Mask - select 1st argument.
1348 if (isa<ConstantAggregateZero>(Mask))
1349 return ReplaceInstUsesWith(CI, Op0);
1351 // Constant Mask - select 1st/2nd argument lane based on top bit of mask.
1352 if (auto C = dyn_cast<ConstantDataVector>(Mask)) {
1353 auto Tyi1 = Builder->getInt1Ty();
1354 auto SelectorType = cast<VectorType>(Mask->getType());
1355 auto EltTy = SelectorType->getElementType();
1356 unsigned Size = SelectorType->getNumElements();
1360 : (EltTy->isDoubleTy() ? 64 : EltTy->getIntegerBitWidth());
1361 assert((BitWidth == 64 || BitWidth == 32 || BitWidth == 8) &&
1362 "Wrong arguments for variable blend intrinsic");
1363 SmallVector<Constant *, 32> Selectors;
1364 for (unsigned I = 0; I < Size; ++I) {
1365 // The intrinsics only read the top bit
1368 Selector = C->getElementAsInteger(I);
1370 Selector = C->getElementAsAPFloat(I).bitcastToAPInt().getZExtValue();
1371 Selectors.push_back(ConstantInt::get(Tyi1, Selector >> (BitWidth - 1)));
1373 auto NewSelector = ConstantVector::get(Selectors);
1374 return SelectInst::Create(NewSelector, Op1, Op0, "blendv");
1379 case Intrinsic::x86_ssse3_pshuf_b_128:
1380 case Intrinsic::x86_avx2_pshuf_b: {
1381 // Turn pshufb(V1,mask) -> shuffle(V1,Zero,mask) if mask is a constant.
1382 auto *V = II->getArgOperand(1);
1383 auto *VTy = cast<VectorType>(V->getType());
1384 unsigned NumElts = VTy->getNumElements();
1385 assert((NumElts == 16 || NumElts == 32) &&
1386 "Unexpected number of elements in shuffle mask!");
1387 // Initialize the resulting shuffle mask to all zeroes.
1388 uint32_t Indexes[32] = {0};
1390 if (auto *Mask = dyn_cast<ConstantDataVector>(V)) {
1391 // Each byte in the shuffle control mask forms an index to permute the
1392 // corresponding byte in the destination operand.
1393 for (unsigned I = 0; I < NumElts; ++I) {
1394 int8_t Index = Mask->getElementAsInteger(I);
1395 // If the most significant bit (bit[7]) of each byte of the shuffle
1396 // control mask is set, then zero is written in the result byte.
1397 // The zero vector is in the right-hand side of the resulting
1400 // The value of each index is the least significant 4 bits of the
1401 // shuffle control byte.
1402 Indexes[I] = (Index < 0) ? NumElts : Index & 0xF;
1404 } else if (!isa<ConstantAggregateZero>(V))
1407 // The value of each index for the high 128-bit lane is the least
1408 // significant 4 bits of the respective shuffle control byte.
1409 for (unsigned I = 16; I < NumElts; ++I)
1410 Indexes[I] += I & 0xF0;
1412 auto NewC = ConstantDataVector::get(V->getContext(),
1413 makeArrayRef(Indexes, NumElts));
1414 auto V1 = II->getArgOperand(0);
1415 auto V2 = Constant::getNullValue(II->getType());
1416 auto Shuffle = Builder->CreateShuffleVector(V1, V2, NewC);
1417 return ReplaceInstUsesWith(CI, Shuffle);
1420 case Intrinsic::x86_avx_vpermilvar_ps:
1421 case Intrinsic::x86_avx_vpermilvar_ps_256:
1422 case Intrinsic::x86_avx_vpermilvar_pd:
1423 case Intrinsic::x86_avx_vpermilvar_pd_256: {
1424 // Convert vpermil* to shufflevector if the mask is constant.
1425 Value *V = II->getArgOperand(1);
1426 unsigned Size = cast<VectorType>(V->getType())->getNumElements();
1427 assert(Size == 8 || Size == 4 || Size == 2);
1428 uint32_t Indexes[8];
1429 if (auto C = dyn_cast<ConstantDataVector>(V)) {
1430 // The intrinsics only read one or two bits, clear the rest.
1431 for (unsigned I = 0; I < Size; ++I) {
1432 uint32_t Index = C->getElementAsInteger(I) & 0x3;
1433 if (II->getIntrinsicID() == Intrinsic::x86_avx_vpermilvar_pd ||
1434 II->getIntrinsicID() == Intrinsic::x86_avx_vpermilvar_pd_256)
1438 } else if (isa<ConstantAggregateZero>(V)) {
1439 for (unsigned I = 0; I < Size; ++I)
1444 // The _256 variants are a bit trickier since the mask bits always index
1445 // into the corresponding 128 half. In order to convert to a generic
1446 // shuffle, we have to make that explicit.
1447 if (II->getIntrinsicID() == Intrinsic::x86_avx_vpermilvar_ps_256 ||
1448 II->getIntrinsicID() == Intrinsic::x86_avx_vpermilvar_pd_256) {
1449 for (unsigned I = Size / 2; I < Size; ++I)
1450 Indexes[I] += Size / 2;
1453 ConstantDataVector::get(V->getContext(), makeArrayRef(Indexes, Size));
1454 auto V1 = II->getArgOperand(0);
1455 auto V2 = UndefValue::get(V1->getType());
1456 auto Shuffle = Builder->CreateShuffleVector(V1, V2, NewC);
1457 return ReplaceInstUsesWith(CI, Shuffle);
1460 case Intrinsic::x86_avx_vperm2f128_pd_256:
1461 case Intrinsic::x86_avx_vperm2f128_ps_256:
1462 case Intrinsic::x86_avx_vperm2f128_si_256:
1463 case Intrinsic::x86_avx2_vperm2i128:
1464 if (Value *V = SimplifyX86vperm2(*II, *Builder))
1465 return ReplaceInstUsesWith(*II, V);
1468 case Intrinsic::x86_xop_vpcomb:
1469 case Intrinsic::x86_xop_vpcomd:
1470 case Intrinsic::x86_xop_vpcomq:
1471 case Intrinsic::x86_xop_vpcomw:
1472 if (Value *V = SimplifyX86vpcom(*II, *Builder, true))
1473 return ReplaceInstUsesWith(*II, V);
1476 case Intrinsic::x86_xop_vpcomub:
1477 case Intrinsic::x86_xop_vpcomud:
1478 case Intrinsic::x86_xop_vpcomuq:
1479 case Intrinsic::x86_xop_vpcomuw:
1480 if (Value *V = SimplifyX86vpcom(*II, *Builder, false))
1481 return ReplaceInstUsesWith(*II, V);
1484 case Intrinsic::ppc_altivec_vperm:
1485 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
1486 // Note that ppc_altivec_vperm has a big-endian bias, so when creating
1487 // a vectorshuffle for little endian, we must undo the transformation
1488 // performed on vec_perm in altivec.h. That is, we must complement
1489 // the permutation mask with respect to 31 and reverse the order of
1491 if (Constant *Mask = dyn_cast<Constant>(II->getArgOperand(2))) {
1492 assert(Mask->getType()->getVectorNumElements() == 16 &&
1493 "Bad type for intrinsic!");
1495 // Check that all of the elements are integer constants or undefs.
1496 bool AllEltsOk = true;
1497 for (unsigned i = 0; i != 16; ++i) {
1498 Constant *Elt = Mask->getAggregateElement(i);
1499 if (!Elt || !(isa<ConstantInt>(Elt) || isa<UndefValue>(Elt))) {
1506 // Cast the input vectors to byte vectors.
1507 Value *Op0 = Builder->CreateBitCast(II->getArgOperand(0),
1509 Value *Op1 = Builder->CreateBitCast(II->getArgOperand(1),
1511 Value *Result = UndefValue::get(Op0->getType());
1513 // Only extract each element once.
1514 Value *ExtractedElts[32];
1515 memset(ExtractedElts, 0, sizeof(ExtractedElts));
1517 for (unsigned i = 0; i != 16; ++i) {
1518 if (isa<UndefValue>(Mask->getAggregateElement(i)))
1521 cast<ConstantInt>(Mask->getAggregateElement(i))->getZExtValue();
1522 Idx &= 31; // Match the hardware behavior.
1523 if (DL.isLittleEndian())
1526 if (!ExtractedElts[Idx]) {
1527 Value *Op0ToUse = (DL.isLittleEndian()) ? Op1 : Op0;
1528 Value *Op1ToUse = (DL.isLittleEndian()) ? Op0 : Op1;
1529 ExtractedElts[Idx] =
1530 Builder->CreateExtractElement(Idx < 16 ? Op0ToUse : Op1ToUse,
1531 Builder->getInt32(Idx&15));
1534 // Insert this value into the result vector.
1535 Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
1536 Builder->getInt32(i));
1538 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
1543 case Intrinsic::arm_neon_vld1:
1544 case Intrinsic::arm_neon_vld2:
1545 case Intrinsic::arm_neon_vld3:
1546 case Intrinsic::arm_neon_vld4:
1547 case Intrinsic::arm_neon_vld2lane:
1548 case Intrinsic::arm_neon_vld3lane:
1549 case Intrinsic::arm_neon_vld4lane:
1550 case Intrinsic::arm_neon_vst1:
1551 case Intrinsic::arm_neon_vst2:
1552 case Intrinsic::arm_neon_vst3:
1553 case Intrinsic::arm_neon_vst4:
1554 case Intrinsic::arm_neon_vst2lane:
1555 case Intrinsic::arm_neon_vst3lane:
1556 case Intrinsic::arm_neon_vst4lane: {
1557 unsigned MemAlign = getKnownAlignment(II->getArgOperand(0), DL, II, AC, DT);
1558 unsigned AlignArg = II->getNumArgOperands() - 1;
1559 ConstantInt *IntrAlign = dyn_cast<ConstantInt>(II->getArgOperand(AlignArg));
1560 if (IntrAlign && IntrAlign->getZExtValue() < MemAlign) {
1561 II->setArgOperand(AlignArg,
1562 ConstantInt::get(Type::getInt32Ty(II->getContext()),
1569 case Intrinsic::arm_neon_vmulls:
1570 case Intrinsic::arm_neon_vmullu:
1571 case Intrinsic::aarch64_neon_smull:
1572 case Intrinsic::aarch64_neon_umull: {
1573 Value *Arg0 = II->getArgOperand(0);
1574 Value *Arg1 = II->getArgOperand(1);
1576 // Handle mul by zero first:
1577 if (isa<ConstantAggregateZero>(Arg0) || isa<ConstantAggregateZero>(Arg1)) {
1578 return ReplaceInstUsesWith(CI, ConstantAggregateZero::get(II->getType()));
1581 // Check for constant LHS & RHS - in this case we just simplify.
1582 bool Zext = (II->getIntrinsicID() == Intrinsic::arm_neon_vmullu ||
1583 II->getIntrinsicID() == Intrinsic::aarch64_neon_umull);
1584 VectorType *NewVT = cast<VectorType>(II->getType());
1585 if (Constant *CV0 = dyn_cast<Constant>(Arg0)) {
1586 if (Constant *CV1 = dyn_cast<Constant>(Arg1)) {
1587 CV0 = ConstantExpr::getIntegerCast(CV0, NewVT, /*isSigned=*/!Zext);
1588 CV1 = ConstantExpr::getIntegerCast(CV1, NewVT, /*isSigned=*/!Zext);
1590 return ReplaceInstUsesWith(CI, ConstantExpr::getMul(CV0, CV1));
1593 // Couldn't simplify - canonicalize constant to the RHS.
1594 std::swap(Arg0, Arg1);
1597 // Handle mul by one:
1598 if (Constant *CV1 = dyn_cast<Constant>(Arg1))
1599 if (ConstantInt *Splat =
1600 dyn_cast_or_null<ConstantInt>(CV1->getSplatValue()))
1602 return CastInst::CreateIntegerCast(Arg0, II->getType(),
1603 /*isSigned=*/!Zext);
1608 case Intrinsic::AMDGPU_rcp: {
1609 if (const ConstantFP *C = dyn_cast<ConstantFP>(II->getArgOperand(0))) {
1610 const APFloat &ArgVal = C->getValueAPF();
1611 APFloat Val(ArgVal.getSemantics(), 1.0);
1612 APFloat::opStatus Status = Val.divide(ArgVal,
1613 APFloat::rmNearestTiesToEven);
1614 // Only do this if it was exact and therefore not dependent on the
1616 if (Status == APFloat::opOK)
1617 return ReplaceInstUsesWith(CI, ConstantFP::get(II->getContext(), Val));
1622 case Intrinsic::stackrestore: {
1623 // If the save is right next to the restore, remove the restore. This can
1624 // happen when variable allocas are DCE'd.
1625 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getArgOperand(0))) {
1626 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
1627 if (&*++SS->getIterator() == II)
1628 return EraseInstFromFunction(CI);
1632 // Scan down this block to see if there is another stack restore in the
1633 // same block without an intervening call/alloca.
1634 BasicBlock::iterator BI(II);
1635 TerminatorInst *TI = II->getParent()->getTerminator();
1636 bool CannotRemove = false;
1637 for (++BI; &*BI != TI; ++BI) {
1638 if (isa<AllocaInst>(BI)) {
1639 CannotRemove = true;
1642 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
1643 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
1644 // If there is a stackrestore below this one, remove this one.
1645 if (II->getIntrinsicID() == Intrinsic::stackrestore)
1646 return EraseInstFromFunction(CI);
1647 // Otherwise, ignore the intrinsic.
1649 // If we found a non-intrinsic call, we can't remove the stack
1651 CannotRemove = true;
1657 // If the stack restore is in a return, resume, or unwind block and if there
1658 // are no allocas or calls between the restore and the return, nuke the
1660 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<ResumeInst>(TI)))
1661 return EraseInstFromFunction(CI);
1664 case Intrinsic::lifetime_start: {
1665 // Remove trivially empty lifetime_start/end ranges, i.e. a start
1666 // immediately followed by an end (ignoring debuginfo or other
1667 // lifetime markers in between).
1668 BasicBlock::iterator BI = II->getIterator(), BE = II->getParent()->end();
1669 for (++BI; BI != BE; ++BI) {
1670 if (IntrinsicInst *LTE = dyn_cast<IntrinsicInst>(BI)) {
1671 if (isa<DbgInfoIntrinsic>(LTE) ||
1672 LTE->getIntrinsicID() == Intrinsic::lifetime_start)
1674 if (LTE->getIntrinsicID() == Intrinsic::lifetime_end) {
1675 if (II->getOperand(0) == LTE->getOperand(0) &&
1676 II->getOperand(1) == LTE->getOperand(1)) {
1677 EraseInstFromFunction(*LTE);
1678 return EraseInstFromFunction(*II);
1687 case Intrinsic::assume: {
1688 // Canonicalize assume(a && b) -> assume(a); assume(b);
1689 // Note: New assumption intrinsics created here are registered by
1690 // the InstCombineIRInserter object.
1691 Value *IIOperand = II->getArgOperand(0), *A, *B,
1692 *AssumeIntrinsic = II->getCalledValue();
1693 if (match(IIOperand, m_And(m_Value(A), m_Value(B)))) {
1694 Builder->CreateCall(AssumeIntrinsic, A, II->getName());
1695 Builder->CreateCall(AssumeIntrinsic, B, II->getName());
1696 return EraseInstFromFunction(*II);
1698 // assume(!(a || b)) -> assume(!a); assume(!b);
1699 if (match(IIOperand, m_Not(m_Or(m_Value(A), m_Value(B))))) {
1700 Builder->CreateCall(AssumeIntrinsic, Builder->CreateNot(A),
1702 Builder->CreateCall(AssumeIntrinsic, Builder->CreateNot(B),
1704 return EraseInstFromFunction(*II);
1707 // assume( (load addr) != null ) -> add 'nonnull' metadata to load
1708 // (if assume is valid at the load)
1709 if (ICmpInst* ICmp = dyn_cast<ICmpInst>(IIOperand)) {
1710 Value *LHS = ICmp->getOperand(0);
1711 Value *RHS = ICmp->getOperand(1);
1712 if (ICmpInst::ICMP_NE == ICmp->getPredicate() &&
1713 isa<LoadInst>(LHS) &&
1714 isa<Constant>(RHS) &&
1715 RHS->getType()->isPointerTy() &&
1716 cast<Constant>(RHS)->isNullValue()) {
1717 LoadInst* LI = cast<LoadInst>(LHS);
1718 if (isValidAssumeForContext(II, LI, DT)) {
1719 MDNode *MD = MDNode::get(II->getContext(), None);
1720 LI->setMetadata(LLVMContext::MD_nonnull, MD);
1721 return EraseInstFromFunction(*II);
1724 // TODO: apply nonnull return attributes to calls and invokes
1725 // TODO: apply range metadata for range check patterns?
1727 // If there is a dominating assume with the same condition as this one,
1728 // then this one is redundant, and should be removed.
1729 APInt KnownZero(1, 0), KnownOne(1, 0);
1730 computeKnownBits(IIOperand, KnownZero, KnownOne, 0, II);
1731 if (KnownOne.isAllOnesValue())
1732 return EraseInstFromFunction(*II);
1736 case Intrinsic::experimental_gc_relocate: {
1737 // Translate facts known about a pointer before relocating into
1738 // facts about the relocate value, while being careful to
1739 // preserve relocation semantics.
1740 GCRelocateOperands Operands(II);
1741 Value *DerivedPtr = Operands.getDerivedPtr();
1742 auto *GCRelocateType = cast<PointerType>(II->getType());
1744 // Remove the relocation if unused, note that this check is required
1745 // to prevent the cases below from looping forever.
1746 if (II->use_empty())
1747 return EraseInstFromFunction(*II);
1749 // Undef is undef, even after relocation.
1750 // TODO: provide a hook for this in GCStrategy. This is clearly legal for
1751 // most practical collectors, but there was discussion in the review thread
1752 // about whether it was legal for all possible collectors.
1753 if (isa<UndefValue>(DerivedPtr)) {
1754 // gc_relocate is uncasted. Use undef of gc_relocate's type to replace it.
1755 return ReplaceInstUsesWith(*II, UndefValue::get(GCRelocateType));
1758 // The relocation of null will be null for most any collector.
1759 // TODO: provide a hook for this in GCStrategy. There might be some weird
1760 // collector this property does not hold for.
1761 if (isa<ConstantPointerNull>(DerivedPtr)) {
1762 // gc_relocate is uncasted. Use null-pointer of gc_relocate's type to replace it.
1763 return ReplaceInstUsesWith(*II, ConstantPointerNull::get(GCRelocateType));
1766 // isKnownNonNull -> nonnull attribute
1767 if (isKnownNonNullAt(DerivedPtr, II, DT, TLI))
1768 II->addAttribute(AttributeSet::ReturnIndex, Attribute::NonNull);
1770 // isDereferenceablePointer -> deref attribute
1771 if (isDereferenceablePointer(DerivedPtr, DL)) {
1772 if (Argument *A = dyn_cast<Argument>(DerivedPtr)) {
1773 uint64_t Bytes = A->getDereferenceableBytes();
1774 II->addDereferenceableAttr(AttributeSet::ReturnIndex, Bytes);
1778 // TODO: bitcast(relocate(p)) -> relocate(bitcast(p))
1779 // Canonicalize on the type from the uses to the defs
1781 // TODO: relocate((gep p, C, C2, ...)) -> gep(relocate(p), C, C2, ...)
1785 return visitCallSite(II);
1788 // InvokeInst simplification
1790 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
1791 return visitCallSite(&II);
1794 /// isSafeToEliminateVarargsCast - If this cast does not affect the value
1795 /// passed through the varargs area, we can eliminate the use of the cast.
1796 static bool isSafeToEliminateVarargsCast(const CallSite CS,
1797 const DataLayout &DL,
1798 const CastInst *const CI,
1800 if (!CI->isLosslessCast())
1803 // If this is a GC intrinsic, avoid munging types. We need types for
1804 // statepoint reconstruction in SelectionDAG.
1805 // TODO: This is probably something which should be expanded to all
1806 // intrinsics since the entire point of intrinsics is that
1807 // they are understandable by the optimizer.
1808 if (isStatepoint(CS) || isGCRelocate(CS) || isGCResult(CS))
1811 // The size of ByVal or InAlloca arguments is derived from the type, so we
1812 // can't change to a type with a different size. If the size were
1813 // passed explicitly we could avoid this check.
1814 if (!CS.isByValOrInAllocaArgument(ix))
1818 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
1819 Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
1820 if (!SrcTy->isSized() || !DstTy->isSized())
1822 if (DL.getTypeAllocSize(SrcTy) != DL.getTypeAllocSize(DstTy))
1827 // Try to fold some different type of calls here.
1828 // Currently we're only working with the checking functions, memcpy_chk,
1829 // mempcpy_chk, memmove_chk, memset_chk, strcpy_chk, stpcpy_chk, strncpy_chk,
1830 // strcat_chk and strncat_chk.
1831 Instruction *InstCombiner::tryOptimizeCall(CallInst *CI) {
1832 if (!CI->getCalledFunction()) return nullptr;
1834 auto InstCombineRAUW = [this](Instruction *From, Value *With) {
1835 ReplaceInstUsesWith(*From, With);
1837 LibCallSimplifier Simplifier(DL, TLI, InstCombineRAUW);
1838 if (Value *With = Simplifier.optimizeCall(CI)) {
1840 return CI->use_empty() ? CI : ReplaceInstUsesWith(*CI, With);
1846 static IntrinsicInst *FindInitTrampolineFromAlloca(Value *TrampMem) {
1847 // Strip off at most one level of pointer casts, looking for an alloca. This
1848 // is good enough in practice and simpler than handling any number of casts.
1849 Value *Underlying = TrampMem->stripPointerCasts();
1850 if (Underlying != TrampMem &&
1851 (!Underlying->hasOneUse() || Underlying->user_back() != TrampMem))
1853 if (!isa<AllocaInst>(Underlying))
1856 IntrinsicInst *InitTrampoline = nullptr;
1857 for (User *U : TrampMem->users()) {
1858 IntrinsicInst *II = dyn_cast<IntrinsicInst>(U);
1861 if (II->getIntrinsicID() == Intrinsic::init_trampoline) {
1863 // More than one init_trampoline writes to this value. Give up.
1865 InitTrampoline = II;
1868 if (II->getIntrinsicID() == Intrinsic::adjust_trampoline)
1869 // Allow any number of calls to adjust.trampoline.
1874 // No call to init.trampoline found.
1875 if (!InitTrampoline)
1878 // Check that the alloca is being used in the expected way.
1879 if (InitTrampoline->getOperand(0) != TrampMem)
1882 return InitTrampoline;
1885 static IntrinsicInst *FindInitTrampolineFromBB(IntrinsicInst *AdjustTramp,
1887 // Visit all the previous instructions in the basic block, and try to find a
1888 // init.trampoline which has a direct path to the adjust.trampoline.
1889 for (BasicBlock::iterator I = AdjustTramp->getIterator(),
1890 E = AdjustTramp->getParent()->begin();
1892 Instruction *Inst = &*--I;
1893 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
1894 if (II->getIntrinsicID() == Intrinsic::init_trampoline &&
1895 II->getOperand(0) == TrampMem)
1897 if (Inst->mayWriteToMemory())
1903 // Given a call to llvm.adjust.trampoline, find and return the corresponding
1904 // call to llvm.init.trampoline if the call to the trampoline can be optimized
1905 // to a direct call to a function. Otherwise return NULL.
1907 static IntrinsicInst *FindInitTrampoline(Value *Callee) {
1908 Callee = Callee->stripPointerCasts();
1909 IntrinsicInst *AdjustTramp = dyn_cast<IntrinsicInst>(Callee);
1911 AdjustTramp->getIntrinsicID() != Intrinsic::adjust_trampoline)
1914 Value *TrampMem = AdjustTramp->getOperand(0);
1916 if (IntrinsicInst *IT = FindInitTrampolineFromAlloca(TrampMem))
1918 if (IntrinsicInst *IT = FindInitTrampolineFromBB(AdjustTramp, TrampMem))
1923 // visitCallSite - Improvements for call and invoke instructions.
1925 Instruction *InstCombiner::visitCallSite(CallSite CS) {
1927 if (isAllocLikeFn(CS.getInstruction(), TLI))
1928 return visitAllocSite(*CS.getInstruction());
1930 bool Changed = false;
1932 // Mark any parameters that are known to be non-null with the nonnull
1933 // attribute. This is helpful for inlining calls to functions with null
1934 // checks on their arguments.
1936 for (Value *V : CS.args()) {
1937 if (V->getType()->isPointerTy() && !CS.paramHasAttr(ArgNo+1, Attribute::NonNull) &&
1938 isKnownNonNullAt(V, CS.getInstruction(), DT, TLI)) {
1939 AttributeSet AS = CS.getAttributes();
1940 AS = AS.addAttribute(CS.getInstruction()->getContext(), ArgNo+1,
1941 Attribute::NonNull);
1942 CS.setAttributes(AS);
1947 assert(ArgNo == CS.arg_size() && "sanity check");
1949 // If the callee is a pointer to a function, attempt to move any casts to the
1950 // arguments of the call/invoke.
1951 Value *Callee = CS.getCalledValue();
1952 if (!isa<Function>(Callee) && transformConstExprCastCall(CS))
1955 if (Function *CalleeF = dyn_cast<Function>(Callee))
1956 // If the call and callee calling conventions don't match, this call must
1957 // be unreachable, as the call is undefined.
1958 if (CalleeF->getCallingConv() != CS.getCallingConv() &&
1959 // Only do this for calls to a function with a body. A prototype may
1960 // not actually end up matching the implementation's calling conv for a
1961 // variety of reasons (e.g. it may be written in assembly).
1962 !CalleeF->isDeclaration()) {
1963 Instruction *OldCall = CS.getInstruction();
1964 new StoreInst(ConstantInt::getTrue(Callee->getContext()),
1965 UndefValue::get(Type::getInt1PtrTy(Callee->getContext())),
1967 // If OldCall does not return void then replaceAllUsesWith undef.
1968 // This allows ValueHandlers and custom metadata to adjust itself.
1969 if (!OldCall->getType()->isVoidTy())
1970 ReplaceInstUsesWith(*OldCall, UndefValue::get(OldCall->getType()));
1971 if (isa<CallInst>(OldCall))
1972 return EraseInstFromFunction(*OldCall);
1974 // We cannot remove an invoke, because it would change the CFG, just
1975 // change the callee to a null pointer.
1976 cast<InvokeInst>(OldCall)->setCalledFunction(
1977 Constant::getNullValue(CalleeF->getType()));
1981 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
1982 // If CS does not return void then replaceAllUsesWith undef.
1983 // This allows ValueHandlers and custom metadata to adjust itself.
1984 if (!CS.getInstruction()->getType()->isVoidTy())
1985 ReplaceInstUsesWith(*CS.getInstruction(),
1986 UndefValue::get(CS.getInstruction()->getType()));
1988 if (isa<InvokeInst>(CS.getInstruction())) {
1989 // Can't remove an invoke because we cannot change the CFG.
1993 // This instruction is not reachable, just remove it. We insert a store to
1994 // undef so that we know that this code is not reachable, despite the fact
1995 // that we can't modify the CFG here.
1996 new StoreInst(ConstantInt::getTrue(Callee->getContext()),
1997 UndefValue::get(Type::getInt1PtrTy(Callee->getContext())),
1998 CS.getInstruction());
2000 return EraseInstFromFunction(*CS.getInstruction());
2003 if (IntrinsicInst *II = FindInitTrampoline(Callee))
2004 return transformCallThroughTrampoline(CS, II);
2006 PointerType *PTy = cast<PointerType>(Callee->getType());
2007 FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
2008 if (FTy->isVarArg()) {
2009 int ix = FTy->getNumParams();
2010 // See if we can optimize any arguments passed through the varargs area of
2012 for (CallSite::arg_iterator I = CS.arg_begin() + FTy->getNumParams(),
2013 E = CS.arg_end(); I != E; ++I, ++ix) {
2014 CastInst *CI = dyn_cast<CastInst>(*I);
2015 if (CI && isSafeToEliminateVarargsCast(CS, DL, CI, ix)) {
2016 *I = CI->getOperand(0);
2022 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
2023 // Inline asm calls cannot throw - mark them 'nounwind'.
2024 CS.setDoesNotThrow();
2028 // Try to optimize the call if possible, we require DataLayout for most of
2029 // this. None of these calls are seen as possibly dead so go ahead and
2030 // delete the instruction now.
2031 if (CallInst *CI = dyn_cast<CallInst>(CS.getInstruction())) {
2032 Instruction *I = tryOptimizeCall(CI);
2033 // If we changed something return the result, etc. Otherwise let
2034 // the fallthrough check.
2035 if (I) return EraseInstFromFunction(*I);
2038 return Changed ? CS.getInstruction() : nullptr;
2041 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
2042 // attempt to move the cast to the arguments of the call/invoke.
2044 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
2046 dyn_cast<Function>(CS.getCalledValue()->stripPointerCasts());
2049 // The prototype of thunks are a lie, don't try to directly call such
2051 if (Callee->hasFnAttribute("thunk"))
2053 Instruction *Caller = CS.getInstruction();
2054 const AttributeSet &CallerPAL = CS.getAttributes();
2056 // Okay, this is a cast from a function to a different type. Unless doing so
2057 // would cause a type conversion of one of our arguments, change this call to
2058 // be a direct call with arguments casted to the appropriate types.
2060 FunctionType *FT = Callee->getFunctionType();
2061 Type *OldRetTy = Caller->getType();
2062 Type *NewRetTy = FT->getReturnType();
2064 // Check to see if we are changing the return type...
2065 if (OldRetTy != NewRetTy) {
2067 if (NewRetTy->isStructTy())
2068 return false; // TODO: Handle multiple return values.
2070 if (!CastInst::isBitOrNoopPointerCastable(NewRetTy, OldRetTy, DL)) {
2071 if (Callee->isDeclaration())
2072 return false; // Cannot transform this return value.
2074 if (!Caller->use_empty() &&
2075 // void -> non-void is handled specially
2076 !NewRetTy->isVoidTy())
2077 return false; // Cannot transform this return value.
2080 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
2081 AttrBuilder RAttrs(CallerPAL, AttributeSet::ReturnIndex);
2082 if (RAttrs.overlaps(AttributeFuncs::typeIncompatible(NewRetTy)))
2083 return false; // Attribute not compatible with transformed value.
2086 // If the callsite is an invoke instruction, and the return value is used by
2087 // a PHI node in a successor, we cannot change the return type of the call
2088 // because there is no place to put the cast instruction (without breaking
2089 // the critical edge). Bail out in this case.
2090 if (!Caller->use_empty())
2091 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
2092 for (User *U : II->users())
2093 if (PHINode *PN = dyn_cast<PHINode>(U))
2094 if (PN->getParent() == II->getNormalDest() ||
2095 PN->getParent() == II->getUnwindDest())
2099 unsigned NumActualArgs = CS.arg_size();
2100 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
2102 // Prevent us turning:
2103 // declare void @takes_i32_inalloca(i32* inalloca)
2104 // call void bitcast (void (i32*)* @takes_i32_inalloca to void (i32)*)(i32 0)
2107 // call void @takes_i32_inalloca(i32* null)
2109 // Similarly, avoid folding away bitcasts of byval calls.
2110 if (Callee->getAttributes().hasAttrSomewhere(Attribute::InAlloca) ||
2111 Callee->getAttributes().hasAttrSomewhere(Attribute::ByVal))
2114 CallSite::arg_iterator AI = CS.arg_begin();
2115 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
2116 Type *ParamTy = FT->getParamType(i);
2117 Type *ActTy = (*AI)->getType();
2119 if (!CastInst::isBitOrNoopPointerCastable(ActTy, ParamTy, DL))
2120 return false; // Cannot transform this parameter value.
2122 if (AttrBuilder(CallerPAL.getParamAttributes(i + 1), i + 1).
2123 overlaps(AttributeFuncs::typeIncompatible(ParamTy)))
2124 return false; // Attribute not compatible with transformed value.
2126 if (CS.isInAllocaArgument(i))
2127 return false; // Cannot transform to and from inalloca.
2129 // If the parameter is passed as a byval argument, then we have to have a
2130 // sized type and the sized type has to have the same size as the old type.
2131 if (ParamTy != ActTy &&
2132 CallerPAL.getParamAttributes(i + 1).hasAttribute(i + 1,
2133 Attribute::ByVal)) {
2134 PointerType *ParamPTy = dyn_cast<PointerType>(ParamTy);
2135 if (!ParamPTy || !ParamPTy->getElementType()->isSized())
2138 Type *CurElTy = ActTy->getPointerElementType();
2139 if (DL.getTypeAllocSize(CurElTy) !=
2140 DL.getTypeAllocSize(ParamPTy->getElementType()))
2145 if (Callee->isDeclaration()) {
2146 // Do not delete arguments unless we have a function body.
2147 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg())
2150 // If the callee is just a declaration, don't change the varargsness of the
2151 // call. We don't want to introduce a varargs call where one doesn't
2153 PointerType *APTy = cast<PointerType>(CS.getCalledValue()->getType());
2154 if (FT->isVarArg()!=cast<FunctionType>(APTy->getElementType())->isVarArg())
2157 // If both the callee and the cast type are varargs, we still have to make
2158 // sure the number of fixed parameters are the same or we have the same
2159 // ABI issues as if we introduce a varargs call.
2160 if (FT->isVarArg() &&
2161 cast<FunctionType>(APTy->getElementType())->isVarArg() &&
2162 FT->getNumParams() !=
2163 cast<FunctionType>(APTy->getElementType())->getNumParams())
2167 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
2168 !CallerPAL.isEmpty())
2169 // In this case we have more arguments than the new function type, but we
2170 // won't be dropping them. Check that these extra arguments have attributes
2171 // that are compatible with being a vararg call argument.
2172 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
2173 unsigned Index = CallerPAL.getSlotIndex(i - 1);
2174 if (Index <= FT->getNumParams())
2177 // Check if it has an attribute that's incompatible with varargs.
2178 AttributeSet PAttrs = CallerPAL.getSlotAttributes(i - 1);
2179 if (PAttrs.hasAttribute(Index, Attribute::StructRet))
2184 // Okay, we decided that this is a safe thing to do: go ahead and start
2185 // inserting cast instructions as necessary.
2186 std::vector<Value*> Args;
2187 Args.reserve(NumActualArgs);
2188 SmallVector<AttributeSet, 8> attrVec;
2189 attrVec.reserve(NumCommonArgs);
2191 // Get any return attributes.
2192 AttrBuilder RAttrs(CallerPAL, AttributeSet::ReturnIndex);
2194 // If the return value is not being used, the type may not be compatible
2195 // with the existing attributes. Wipe out any problematic attributes.
2196 RAttrs.remove(AttributeFuncs::typeIncompatible(NewRetTy));
2198 // Add the new return attributes.
2199 if (RAttrs.hasAttributes())
2200 attrVec.push_back(AttributeSet::get(Caller->getContext(),
2201 AttributeSet::ReturnIndex, RAttrs));
2203 AI = CS.arg_begin();
2204 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
2205 Type *ParamTy = FT->getParamType(i);
2207 if ((*AI)->getType() == ParamTy) {
2208 Args.push_back(*AI);
2210 Args.push_back(Builder->CreateBitOrPointerCast(*AI, ParamTy));
2213 // Add any parameter attributes.
2214 AttrBuilder PAttrs(CallerPAL.getParamAttributes(i + 1), i + 1);
2215 if (PAttrs.hasAttributes())
2216 attrVec.push_back(AttributeSet::get(Caller->getContext(), i + 1,
2220 // If the function takes more arguments than the call was taking, add them
2222 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
2223 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
2225 // If we are removing arguments to the function, emit an obnoxious warning.
2226 if (FT->getNumParams() < NumActualArgs) {
2227 // TODO: if (!FT->isVarArg()) this call may be unreachable. PR14722
2228 if (FT->isVarArg()) {
2229 // Add all of the arguments in their promoted form to the arg list.
2230 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
2231 Type *PTy = getPromotedType((*AI)->getType());
2232 if (PTy != (*AI)->getType()) {
2233 // Must promote to pass through va_arg area!
2234 Instruction::CastOps opcode =
2235 CastInst::getCastOpcode(*AI, false, PTy, false);
2236 Args.push_back(Builder->CreateCast(opcode, *AI, PTy));
2238 Args.push_back(*AI);
2241 // Add any parameter attributes.
2242 AttrBuilder PAttrs(CallerPAL.getParamAttributes(i + 1), i + 1);
2243 if (PAttrs.hasAttributes())
2244 attrVec.push_back(AttributeSet::get(FT->getContext(), i + 1,
2250 AttributeSet FnAttrs = CallerPAL.getFnAttributes();
2251 if (CallerPAL.hasAttributes(AttributeSet::FunctionIndex))
2252 attrVec.push_back(AttributeSet::get(Callee->getContext(), FnAttrs));
2254 if (NewRetTy->isVoidTy())
2255 Caller->setName(""); // Void type should not have a name.
2257 const AttributeSet &NewCallerPAL = AttributeSet::get(Callee->getContext(),
2261 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
2262 NC = Builder->CreateInvoke(Callee, II->getNormalDest(),
2263 II->getUnwindDest(), Args);
2265 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
2266 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
2268 CallInst *CI = cast<CallInst>(Caller);
2269 NC = Builder->CreateCall(Callee, Args);
2271 if (CI->isTailCall())
2272 cast<CallInst>(NC)->setTailCall();
2273 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
2274 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
2277 // Insert a cast of the return type as necessary.
2279 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
2280 if (!NV->getType()->isVoidTy()) {
2281 NV = NC = CastInst::CreateBitOrPointerCast(NC, OldRetTy);
2282 NC->setDebugLoc(Caller->getDebugLoc());
2284 // If this is an invoke instruction, we should insert it after the first
2285 // non-phi, instruction in the normal successor block.
2286 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
2287 BasicBlock::iterator I = II->getNormalDest()->getFirstInsertionPt();
2288 InsertNewInstBefore(NC, *I);
2290 // Otherwise, it's a call, just insert cast right after the call.
2291 InsertNewInstBefore(NC, *Caller);
2293 Worklist.AddUsersToWorkList(*Caller);
2295 NV = UndefValue::get(Caller->getType());
2299 if (!Caller->use_empty())
2300 ReplaceInstUsesWith(*Caller, NV);
2301 else if (Caller->hasValueHandle()) {
2302 if (OldRetTy == NV->getType())
2303 ValueHandleBase::ValueIsRAUWd(Caller, NV);
2305 // We cannot call ValueIsRAUWd with a different type, and the
2306 // actual tracked value will disappear.
2307 ValueHandleBase::ValueIsDeleted(Caller);
2310 EraseInstFromFunction(*Caller);
2314 // transformCallThroughTrampoline - Turn a call to a function created by
2315 // init_trampoline / adjust_trampoline intrinsic pair into a direct call to the
2316 // underlying function.
2319 InstCombiner::transformCallThroughTrampoline(CallSite CS,
2320 IntrinsicInst *Tramp) {
2321 Value *Callee = CS.getCalledValue();
2322 PointerType *PTy = cast<PointerType>(Callee->getType());
2323 FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
2324 const AttributeSet &Attrs = CS.getAttributes();
2326 // If the call already has the 'nest' attribute somewhere then give up -
2327 // otherwise 'nest' would occur twice after splicing in the chain.
2328 if (Attrs.hasAttrSomewhere(Attribute::Nest))
2332 "transformCallThroughTrampoline called with incorrect CallSite.");
2334 Function *NestF =cast<Function>(Tramp->getArgOperand(1)->stripPointerCasts());
2335 PointerType *NestFPTy = cast<PointerType>(NestF->getType());
2336 FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
2338 const AttributeSet &NestAttrs = NestF->getAttributes();
2339 if (!NestAttrs.isEmpty()) {
2340 unsigned NestIdx = 1;
2341 Type *NestTy = nullptr;
2342 AttributeSet NestAttr;
2344 // Look for a parameter marked with the 'nest' attribute.
2345 for (FunctionType::param_iterator I = NestFTy->param_begin(),
2346 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
2347 if (NestAttrs.hasAttribute(NestIdx, Attribute::Nest)) {
2348 // Record the parameter type and any other attributes.
2350 NestAttr = NestAttrs.getParamAttributes(NestIdx);
2355 Instruction *Caller = CS.getInstruction();
2356 std::vector<Value*> NewArgs;
2357 NewArgs.reserve(CS.arg_size() + 1);
2359 SmallVector<AttributeSet, 8> NewAttrs;
2360 NewAttrs.reserve(Attrs.getNumSlots() + 1);
2362 // Insert the nest argument into the call argument list, which may
2363 // mean appending it. Likewise for attributes.
2365 // Add any result attributes.
2366 if (Attrs.hasAttributes(AttributeSet::ReturnIndex))
2367 NewAttrs.push_back(AttributeSet::get(Caller->getContext(),
2368 Attrs.getRetAttributes()));
2372 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
2374 if (Idx == NestIdx) {
2375 // Add the chain argument and attributes.
2376 Value *NestVal = Tramp->getArgOperand(2);
2377 if (NestVal->getType() != NestTy)
2378 NestVal = Builder->CreateBitCast(NestVal, NestTy, "nest");
2379 NewArgs.push_back(NestVal);
2380 NewAttrs.push_back(AttributeSet::get(Caller->getContext(),
2387 // Add the original argument and attributes.
2388 NewArgs.push_back(*I);
2389 AttributeSet Attr = Attrs.getParamAttributes(Idx);
2390 if (Attr.hasAttributes(Idx)) {
2391 AttrBuilder B(Attr, Idx);
2392 NewAttrs.push_back(AttributeSet::get(Caller->getContext(),
2393 Idx + (Idx >= NestIdx), B));
2400 // Add any function attributes.
2401 if (Attrs.hasAttributes(AttributeSet::FunctionIndex))
2402 NewAttrs.push_back(AttributeSet::get(FTy->getContext(),
2403 Attrs.getFnAttributes()));
2405 // The trampoline may have been bitcast to a bogus type (FTy).
2406 // Handle this by synthesizing a new function type, equal to FTy
2407 // with the chain parameter inserted.
2409 std::vector<Type*> NewTypes;
2410 NewTypes.reserve(FTy->getNumParams()+1);
2412 // Insert the chain's type into the list of parameter types, which may
2413 // mean appending it.
2416 FunctionType::param_iterator I = FTy->param_begin(),
2417 E = FTy->param_end();
2421 // Add the chain's type.
2422 NewTypes.push_back(NestTy);
2427 // Add the original type.
2428 NewTypes.push_back(*I);
2434 // Replace the trampoline call with a direct call. Let the generic
2435 // code sort out any function type mismatches.
2436 FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
2438 Constant *NewCallee =
2439 NestF->getType() == PointerType::getUnqual(NewFTy) ?
2440 NestF : ConstantExpr::getBitCast(NestF,
2441 PointerType::getUnqual(NewFTy));
2442 const AttributeSet &NewPAL =
2443 AttributeSet::get(FTy->getContext(), NewAttrs);
2445 Instruction *NewCaller;
2446 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
2447 NewCaller = InvokeInst::Create(NewCallee,
2448 II->getNormalDest(), II->getUnwindDest(),
2450 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
2451 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
2453 NewCaller = CallInst::Create(NewCallee, NewArgs);
2454 if (cast<CallInst>(Caller)->isTailCall())
2455 cast<CallInst>(NewCaller)->setTailCall();
2456 cast<CallInst>(NewCaller)->
2457 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
2458 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
2465 // Replace the trampoline call with a direct call. Since there is no 'nest'
2466 // parameter, there is no need to adjust the argument list. Let the generic
2467 // code sort out any function type mismatches.
2468 Constant *NewCallee =
2469 NestF->getType() == PTy ? NestF :
2470 ConstantExpr::getBitCast(NestF, PTy);
2471 CS.setCalledFunction(NewCallee);
2472 return CS.getInstruction();