blob: 49bc662d129460bae2bdd44a89d8db764af2a8e8 [file] [log] [blame]
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001//===- InstCombineCalls.cpp -----------------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the visitCall and visitInvoke functions.
11//
12//===----------------------------------------------------------------------===//
13
Chandler Carrutha9174582015-01-22 05:25:13 +000014#include "InstCombineInternal.h"
Meador Ingee3f2b262012-11-30 04:05:06 +000015#include "llvm/ADT/Statistic.h"
David Majnemer15032582015-05-22 03:56:46 +000016#include "llvm/Analysis/InstructionSimplify.h"
Artur Pilipenko31bcca42016-02-24 12:49:04 +000017#include "llvm/Analysis/Loads.h"
Chris Lattner7a9e47a2010-01-05 07:32:13 +000018#include "llvm/Analysis/MemoryBuiltins.h"
Chandler Carruth219b89b2014-03-04 11:01:28 +000019#include "llvm/IR/CallSite.h"
Hal Finkel04a15612014-10-04 21:27:06 +000020#include "llvm/IR/Dominators.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000021#include "llvm/IR/PatternMatch.h"
Philip Reames1a1bdb22014-12-02 18:50:36 +000022#include "llvm/IR/Statepoint.h"
Eric Christophera7fb58f2010-03-06 10:50:38 +000023#include "llvm/Transforms/Utils/BuildLibCalls.h"
Chris Lattner6fcd32e2010-12-25 20:37:57 +000024#include "llvm/Transforms/Utils/Local.h"
Chandler Carruthba4c5172015-01-21 11:23:40 +000025#include "llvm/Transforms/Utils/SimplifyLibCalls.h"
Chris Lattner7a9e47a2010-01-05 07:32:13 +000026using namespace llvm;
Michael Ilseman536cc322012-12-13 03:13:36 +000027using namespace PatternMatch;
Chris Lattner7a9e47a2010-01-05 07:32:13 +000028
Chandler Carruth964daaa2014-04-22 02:55:47 +000029#define DEBUG_TYPE "instcombine"
30
Meador Ingee3f2b262012-11-30 04:05:06 +000031STATISTIC(NumSimplified, "Number of library calls simplified");
32
Sanjay Patelcd4377c2016-01-20 22:24:38 +000033/// Return the specified type promoted as it would be to pass though a va_arg
34/// area.
Chris Lattner229907c2011-07-18 04:54:35 +000035static Type *getPromotedType(Type *Ty) {
36 if (IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +000037 if (ITy->getBitWidth() < 32)
38 return Type::getInt32Ty(Ty->getContext());
39 }
40 return Ty;
41}
42
Sanjay Patelcd4377c2016-01-20 22:24:38 +000043/// Given an aggregate type which ultimately holds a single scalar element,
44/// like {{{type}}} or [1 x type], return type.
Dan Gohmand0080c42012-09-13 18:19:06 +000045static Type *reduceToSingleValueType(Type *T) {
46 while (!T->isSingleValueType()) {
47 if (StructType *STy = dyn_cast<StructType>(T)) {
48 if (STy->getNumElements() == 1)
49 T = STy->getElementType(0);
50 else
51 break;
52 } else if (ArrayType *ATy = dyn_cast<ArrayType>(T)) {
53 if (ATy->getNumElements() == 1)
54 T = ATy->getElementType();
55 else
56 break;
57 } else
58 break;
59 }
60
61 return T;
62}
Chris Lattner7a9e47a2010-01-05 07:32:13 +000063
Sanjay Patel368ac5d2016-02-21 17:29:33 +000064/// Return a constant boolean vector that has true elements in all positions
Sanjay Patel24401302016-02-21 17:33:31 +000065/// where the input constant data vector has an element with the sign bit set.
Sanjay Patel368ac5d2016-02-21 17:29:33 +000066static Constant *getNegativeIsTrueBoolVec(ConstantDataVector *V) {
67 SmallVector<Constant *, 32> BoolVec;
68 IntegerType *BoolTy = Type::getInt1Ty(V->getContext());
69 for (unsigned I = 0, E = V->getNumElements(); I != E; ++I) {
70 Constant *Elt = V->getElementAsConstant(I);
71 assert((isa<ConstantInt>(Elt) || isa<ConstantFP>(Elt)) &&
72 "Unexpected constant data vector element type");
73 bool Sign = V->getElementType()->isIntegerTy()
74 ? cast<ConstantInt>(Elt)->isNegative()
75 : cast<ConstantFP>(Elt)->isNegative();
76 BoolVec.push_back(ConstantInt::get(BoolTy, Sign));
77 }
78 return ConstantVector::get(BoolVec);
79}
80
Pete Cooper67cf9a72015-11-19 05:56:52 +000081Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +000082 unsigned DstAlign = getKnownAlignment(MI->getArgOperand(0), DL, MI, AC, DT);
83 unsigned SrcAlign = getKnownAlignment(MI->getArgOperand(1), DL, MI, AC, DT);
Pete Cooper67cf9a72015-11-19 05:56:52 +000084 unsigned MinAlign = std::min(DstAlign, SrcAlign);
85 unsigned CopyAlign = MI->getAlignment();
Chris Lattner7a9e47a2010-01-05 07:32:13 +000086
Pete Cooper67cf9a72015-11-19 05:56:52 +000087 if (CopyAlign < MinAlign) {
88 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(), MinAlign, false));
Chris Lattner7a9e47a2010-01-05 07:32:13 +000089 return MI;
90 }
Jim Grosbach7815f562012-02-03 00:07:04 +000091
Chris Lattner7a9e47a2010-01-05 07:32:13 +000092 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
93 // load/store.
Gabor Greif0a136c92010-06-24 13:54:33 +000094 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getArgOperand(2));
Craig Topperf40110f2014-04-25 05:29:35 +000095 if (!MemOpLength) return nullptr;
Jim Grosbach7815f562012-02-03 00:07:04 +000096
Chris Lattner7a9e47a2010-01-05 07:32:13 +000097 // Source and destination pointer types are always "i8*" for intrinsic. See
98 // if the size is something we can handle with a single primitive load/store.
99 // A single load+store correctly handles overlapping memory in the memmove
100 // case.
Michael Liao69e172a2012-08-15 03:49:59 +0000101 uint64_t Size = MemOpLength->getLimitedValue();
Alp Tokercb402912014-01-24 17:20:08 +0000102 assert(Size && "0-sized memory transferring should be removed already.");
Jim Grosbach7815f562012-02-03 00:07:04 +0000103
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000104 if (Size > 8 || (Size&(Size-1)))
Craig Topperf40110f2014-04-25 05:29:35 +0000105 return nullptr; // If not 1/2/4/8 bytes, exit.
Jim Grosbach7815f562012-02-03 00:07:04 +0000106
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000107 // Use an integer load+store unless we can find something better.
Mon P Wangc576ee92010-04-04 03:10:48 +0000108 unsigned SrcAddrSp =
Gabor Greif0a136c92010-06-24 13:54:33 +0000109 cast<PointerType>(MI->getArgOperand(1)->getType())->getAddressSpace();
Gabor Greiff3755202010-04-16 15:33:14 +0000110 unsigned DstAddrSp =
Gabor Greif0a136c92010-06-24 13:54:33 +0000111 cast<PointerType>(MI->getArgOperand(0)->getType())->getAddressSpace();
Mon P Wangc576ee92010-04-04 03:10:48 +0000112
Chris Lattner229907c2011-07-18 04:54:35 +0000113 IntegerType* IntType = IntegerType::get(MI->getContext(), Size<<3);
Mon P Wangc576ee92010-04-04 03:10:48 +0000114 Type *NewSrcPtrTy = PointerType::get(IntType, SrcAddrSp);
115 Type *NewDstPtrTy = PointerType::get(IntType, DstAddrSp);
Jim Grosbach7815f562012-02-03 00:07:04 +0000116
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000117 // Memcpy forces the use of i8* for the source and destination. That means
118 // that if you're using memcpy to move one double around, you'll get a cast
119 // from double* to i8*. We'd much rather use a double load+store rather than
120 // an i64 load+store, here because this improves the odds that the source or
121 // dest address will be promotable. See if we can find a better type than the
122 // integer datatype.
Gabor Greif589a0b92010-06-24 12:58:35 +0000123 Value *StrippedDest = MI->getArgOperand(0)->stripPointerCasts();
Craig Topperf40110f2014-04-25 05:29:35 +0000124 MDNode *CopyMD = nullptr;
Gabor Greif589a0b92010-06-24 12:58:35 +0000125 if (StrippedDest != MI->getArgOperand(0)) {
Chris Lattner229907c2011-07-18 04:54:35 +0000126 Type *SrcETy = cast<PointerType>(StrippedDest->getType())
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000127 ->getElementType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000128 if (SrcETy->isSized() && DL.getTypeStoreSize(SrcETy) == Size) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000129 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
130 // down through these levels if so.
Dan Gohmand0080c42012-09-13 18:19:06 +0000131 SrcETy = reduceToSingleValueType(SrcETy);
Jim Grosbach7815f562012-02-03 00:07:04 +0000132
Mon P Wangc576ee92010-04-04 03:10:48 +0000133 if (SrcETy->isSingleValueType()) {
134 NewSrcPtrTy = PointerType::get(SrcETy, SrcAddrSp);
135 NewDstPtrTy = PointerType::get(SrcETy, DstAddrSp);
Dan Gohman3f553c22012-09-13 21:51:01 +0000136
137 // If the memcpy has metadata describing the members, see if we can
138 // get the TBAA tag describing our copy.
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000139 if (MDNode *M = MI->getMetadata(LLVMContext::MD_tbaa_struct)) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000140 if (M->getNumOperands() == 3 && M->getOperand(0) &&
141 mdconst::hasa<ConstantInt>(M->getOperand(0)) &&
142 mdconst::extract<ConstantInt>(M->getOperand(0))->isNullValue() &&
Nick Lewycky49ac81a2012-10-11 02:05:23 +0000143 M->getOperand(1) &&
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000144 mdconst::hasa<ConstantInt>(M->getOperand(1)) &&
145 mdconst::extract<ConstantInt>(M->getOperand(1))->getValue() ==
146 Size &&
147 M->getOperand(2) && isa<MDNode>(M->getOperand(2)))
Dan Gohman3f553c22012-09-13 21:51:01 +0000148 CopyMD = cast<MDNode>(M->getOperand(2));
149 }
Mon P Wangc576ee92010-04-04 03:10:48 +0000150 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000151 }
152 }
Jim Grosbach7815f562012-02-03 00:07:04 +0000153
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000154 // If the memcpy/memmove provides better alignment info than we can
155 // infer, use it.
Pete Cooper67cf9a72015-11-19 05:56:52 +0000156 SrcAlign = std::max(SrcAlign, CopyAlign);
157 DstAlign = std::max(DstAlign, CopyAlign);
Jim Grosbach7815f562012-02-03 00:07:04 +0000158
Gabor Greif5f3e6562010-06-25 07:57:14 +0000159 Value *Src = Builder->CreateBitCast(MI->getArgOperand(1), NewSrcPtrTy);
160 Value *Dest = Builder->CreateBitCast(MI->getArgOperand(0), NewDstPtrTy);
Eli Friedman49346012011-05-18 19:57:14 +0000161 LoadInst *L = Builder->CreateLoad(Src, MI->isVolatile());
162 L->setAlignment(SrcAlign);
Dan Gohman3f553c22012-09-13 21:51:01 +0000163 if (CopyMD)
164 L->setMetadata(LLVMContext::MD_tbaa, CopyMD);
Eli Friedman49346012011-05-18 19:57:14 +0000165 StoreInst *S = Builder->CreateStore(L, Dest, MI->isVolatile());
166 S->setAlignment(DstAlign);
Dan Gohman3f553c22012-09-13 21:51:01 +0000167 if (CopyMD)
168 S->setMetadata(LLVMContext::MD_tbaa, CopyMD);
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000169
170 // Set the size of the copy to 0, it will be deleted on the next iteration.
Gabor Greif5b1370e2010-06-28 16:50:57 +0000171 MI->setArgOperand(2, Constant::getNullValue(MemOpLength->getType()));
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000172 return MI;
173}
174
175Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000176 unsigned Alignment = getKnownAlignment(MI->getDest(), DL, MI, AC, DT);
Pete Cooper67cf9a72015-11-19 05:56:52 +0000177 if (MI->getAlignment() < Alignment) {
178 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
179 Alignment, false));
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000180 return MI;
181 }
Jim Grosbach7815f562012-02-03 00:07:04 +0000182
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000183 // Extract the length and alignment and fill if they are constant.
184 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
185 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
Duncan Sands9dff9be2010-02-15 16:12:20 +0000186 if (!LenC || !FillC || !FillC->getType()->isIntegerTy(8))
Craig Topperf40110f2014-04-25 05:29:35 +0000187 return nullptr;
Michael Liao69e172a2012-08-15 03:49:59 +0000188 uint64_t Len = LenC->getLimitedValue();
Pete Cooper67cf9a72015-11-19 05:56:52 +0000189 Alignment = MI->getAlignment();
Michael Liao69e172a2012-08-15 03:49:59 +0000190 assert(Len && "0-sized memory setting should be removed already.");
Jim Grosbach7815f562012-02-03 00:07:04 +0000191
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000192 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
193 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
Chris Lattner229907c2011-07-18 04:54:35 +0000194 Type *ITy = IntegerType::get(MI->getContext(), Len*8); // n=1 -> i8.
Jim Grosbach7815f562012-02-03 00:07:04 +0000195
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000196 Value *Dest = MI->getDest();
Mon P Wang1991c472010-12-20 01:05:30 +0000197 unsigned DstAddrSp = cast<PointerType>(Dest->getType())->getAddressSpace();
198 Type *NewDstPtrTy = PointerType::get(ITy, DstAddrSp);
199 Dest = Builder->CreateBitCast(Dest, NewDstPtrTy);
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000200
201 // Alignment 0 is identity for alignment 1 for memset, but not store.
202 if (Alignment == 0) Alignment = 1;
Jim Grosbach7815f562012-02-03 00:07:04 +0000203
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000204 // Extract the fill value and store.
205 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
Eli Friedman49346012011-05-18 19:57:14 +0000206 StoreInst *S = Builder->CreateStore(ConstantInt::get(ITy, Fill), Dest,
207 MI->isVolatile());
208 S->setAlignment(Alignment);
Jim Grosbach7815f562012-02-03 00:07:04 +0000209
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000210 // Set the size of the copy to 0, it will be deleted on the next iteration.
211 MI->setLength(Constant::getNullValue(LenC->getType()));
212 return MI;
213 }
214
Simon Pilgrim18617d12015-08-05 08:18:00 +0000215 return nullptr;
216}
217
Sanjay Patel6038d3e2016-01-29 23:27:03 +0000218static Value *simplifyX86immShift(const IntrinsicInst &II,
Simon Pilgrimbecd5e82015-08-13 07:39:03 +0000219 InstCombiner::BuilderTy &Builder) {
220 bool LogicalShift = false;
221 bool ShiftLeft = false;
222
223 switch (II.getIntrinsicID()) {
224 default:
225 return nullptr;
226 case Intrinsic::x86_sse2_psra_d:
227 case Intrinsic::x86_sse2_psra_w:
228 case Intrinsic::x86_sse2_psrai_d:
229 case Intrinsic::x86_sse2_psrai_w:
230 case Intrinsic::x86_avx2_psra_d:
231 case Intrinsic::x86_avx2_psra_w:
232 case Intrinsic::x86_avx2_psrai_d:
233 case Intrinsic::x86_avx2_psrai_w:
234 LogicalShift = false; ShiftLeft = false;
235 break;
236 case Intrinsic::x86_sse2_psrl_d:
237 case Intrinsic::x86_sse2_psrl_q:
238 case Intrinsic::x86_sse2_psrl_w:
239 case Intrinsic::x86_sse2_psrli_d:
240 case Intrinsic::x86_sse2_psrli_q:
241 case Intrinsic::x86_sse2_psrli_w:
242 case Intrinsic::x86_avx2_psrl_d:
243 case Intrinsic::x86_avx2_psrl_q:
244 case Intrinsic::x86_avx2_psrl_w:
245 case Intrinsic::x86_avx2_psrli_d:
246 case Intrinsic::x86_avx2_psrli_q:
247 case Intrinsic::x86_avx2_psrli_w:
248 LogicalShift = true; ShiftLeft = false;
249 break;
250 case Intrinsic::x86_sse2_psll_d:
251 case Intrinsic::x86_sse2_psll_q:
252 case Intrinsic::x86_sse2_psll_w:
253 case Intrinsic::x86_sse2_pslli_d:
254 case Intrinsic::x86_sse2_pslli_q:
255 case Intrinsic::x86_sse2_pslli_w:
256 case Intrinsic::x86_avx2_psll_d:
257 case Intrinsic::x86_avx2_psll_q:
258 case Intrinsic::x86_avx2_psll_w:
259 case Intrinsic::x86_avx2_pslli_d:
260 case Intrinsic::x86_avx2_pslli_q:
261 case Intrinsic::x86_avx2_pslli_w:
262 LogicalShift = true; ShiftLeft = true;
263 break;
264 }
Simon Pilgrima3a72b42015-08-10 20:21:15 +0000265 assert((LogicalShift || !ShiftLeft) && "Only logical shifts can shift left");
266
Simon Pilgrim3815c162015-08-07 18:22:50 +0000267 // Simplify if count is constant.
268 auto Arg1 = II.getArgOperand(1);
269 auto CAZ = dyn_cast<ConstantAggregateZero>(Arg1);
270 auto CDV = dyn_cast<ConstantDataVector>(Arg1);
271 auto CInt = dyn_cast<ConstantInt>(Arg1);
272 if (!CAZ && !CDV && !CInt)
Simon Pilgrim18617d12015-08-05 08:18:00 +0000273 return nullptr;
Simon Pilgrim3815c162015-08-07 18:22:50 +0000274
275 APInt Count(64, 0);
276 if (CDV) {
277 // SSE2/AVX2 uses all the first 64-bits of the 128-bit vector
278 // operand to compute the shift amount.
279 auto VT = cast<VectorType>(CDV->getType());
280 unsigned BitWidth = VT->getElementType()->getPrimitiveSizeInBits();
281 assert((64 % BitWidth) == 0 && "Unexpected packed shift size");
282 unsigned NumSubElts = 64 / BitWidth;
283
284 // Concatenate the sub-elements to create the 64-bit value.
285 for (unsigned i = 0; i != NumSubElts; ++i) {
286 unsigned SubEltIdx = (NumSubElts - 1) - i;
287 auto SubElt = cast<ConstantInt>(CDV->getElementAsConstant(SubEltIdx));
288 Count = Count.shl(BitWidth);
289 Count |= SubElt->getValue().zextOrTrunc(64);
290 }
291 }
292 else if (CInt)
293 Count = CInt->getValue();
Simon Pilgrim18617d12015-08-05 08:18:00 +0000294
295 auto Vec = II.getArgOperand(0);
296 auto VT = cast<VectorType>(Vec->getType());
297 auto SVT = VT->getElementType();
Simon Pilgrim3815c162015-08-07 18:22:50 +0000298 unsigned VWidth = VT->getNumElements();
299 unsigned BitWidth = SVT->getPrimitiveSizeInBits();
300
301 // If shift-by-zero then just return the original value.
302 if (Count == 0)
303 return Vec;
304
Simon Pilgrima3a72b42015-08-10 20:21:15 +0000305 // Handle cases when Shift >= BitWidth.
306 if (Count.uge(BitWidth)) {
307 // If LogicalShift - just return zero.
308 if (LogicalShift)
309 return ConstantAggregateZero::get(VT);
310
311 // If ArithmeticShift - clamp Shift to (BitWidth - 1).
312 Count = APInt(64, BitWidth - 1);
313 }
Simon Pilgrim18617d12015-08-05 08:18:00 +0000314
Simon Pilgrim18617d12015-08-05 08:18:00 +0000315 // Get a constant vector of the same type as the first operand.
Simon Pilgrim3815c162015-08-07 18:22:50 +0000316 auto ShiftAmt = ConstantInt::get(SVT, Count.zextOrTrunc(BitWidth));
317 auto ShiftVec = Builder.CreateVectorSplat(VWidth, ShiftAmt);
Simon Pilgrim18617d12015-08-05 08:18:00 +0000318
319 if (ShiftLeft)
Simon Pilgrim3815c162015-08-07 18:22:50 +0000320 return Builder.CreateShl(Vec, ShiftVec);
Simon Pilgrim18617d12015-08-05 08:18:00 +0000321
Simon Pilgrima3a72b42015-08-10 20:21:15 +0000322 if (LogicalShift)
323 return Builder.CreateLShr(Vec, ShiftVec);
324
325 return Builder.CreateAShr(Vec, ShiftVec);
Simon Pilgrim18617d12015-08-05 08:18:00 +0000326}
327
Simon Pilgrimdb9893f2016-06-07 10:27:15 +0000328// Attempt to simplify AVX2 per-element shift intrinsics to a generic IR shift.
329// Unlike the generic IR shifts, the intrinsics have defined behaviour for out
330// of range shift amounts (logical - set to zero, arithmetic - splat sign bit).
331static Value *simplifyX86varShift(const IntrinsicInst &II,
332 InstCombiner::BuilderTy &Builder) {
333 bool LogicalShift = false;
334 bool ShiftLeft = false;
335
336 switch (II.getIntrinsicID()) {
337 default:
338 return nullptr;
339 case Intrinsic::x86_avx2_psrav_d:
340 case Intrinsic::x86_avx2_psrav_d_256:
341 LogicalShift = false;
342 ShiftLeft = false;
343 break;
344 case Intrinsic::x86_avx2_psrlv_d:
345 case Intrinsic::x86_avx2_psrlv_d_256:
346 case Intrinsic::x86_avx2_psrlv_q:
347 case Intrinsic::x86_avx2_psrlv_q_256:
348 LogicalShift = true;
349 ShiftLeft = false;
350 break;
351 case Intrinsic::x86_avx2_psllv_d:
352 case Intrinsic::x86_avx2_psllv_d_256:
353 case Intrinsic::x86_avx2_psllv_q:
354 case Intrinsic::x86_avx2_psllv_q_256:
355 LogicalShift = true;
356 ShiftLeft = true;
357 break;
358 }
359 assert((LogicalShift || !ShiftLeft) && "Only logical shifts can shift left");
360
361 // Simplify if all shift amounts are constant/undef.
362 auto *CShift = dyn_cast<Constant>(II.getArgOperand(1));
363 if (!CShift)
364 return nullptr;
365
366 auto Vec = II.getArgOperand(0);
367 auto VT = cast<VectorType>(II.getType());
368 auto SVT = VT->getVectorElementType();
369 int NumElts = VT->getNumElements();
370 int BitWidth = SVT->getIntegerBitWidth();
371
372 // Collect each element's shift amount.
373 // We also collect special cases: UNDEF = -1, OUT-OF-RANGE = BitWidth.
374 bool AnyOutOfRange = false;
375 SmallVector<int, 8> ShiftAmts;
376 for (int I = 0; I < NumElts; ++I) {
377 auto *CElt = CShift->getAggregateElement(I);
378 if (CElt && isa<UndefValue>(CElt)) {
379 ShiftAmts.push_back(-1);
380 continue;
381 }
382
383 auto *COp = dyn_cast_or_null<ConstantInt>(CElt);
384 if (!COp)
385 return nullptr;
386
387 // Handle out of range shifts.
388 // If LogicalShift - set to BitWidth (special case).
389 // If ArithmeticShift - set to (BitWidth - 1) (sign splat).
390 APInt ShiftVal = COp->getValue();
391 if (ShiftVal.uge(BitWidth)) {
392 AnyOutOfRange = LogicalShift;
393 ShiftAmts.push_back(LogicalShift ? BitWidth : BitWidth - 1);
394 continue;
395 }
396
397 ShiftAmts.push_back((int)ShiftVal.getZExtValue());
398 }
399
400 // If all elements out of range or UNDEF, return vector of zeros/undefs.
401 // ArithmeticShift should only hit this if they are all UNDEF.
402 auto OutOfRange = [&](int Idx) { return (Idx < 0) || (BitWidth <= Idx); };
403 if (llvm::all_of(ShiftAmts, OutOfRange)) {
404 SmallVector<Constant *, 8> ConstantVec;
405 for (int Idx : ShiftAmts) {
406 if (Idx < 0) {
407 ConstantVec.push_back(UndefValue::get(SVT));
408 } else {
409 assert(LogicalShift && "Logical shift expected");
410 ConstantVec.push_back(ConstantInt::getNullValue(SVT));
411 }
412 }
413 return ConstantVector::get(ConstantVec);
414 }
415
416 // We can't handle only some out of range values with generic logical shifts.
417 if (AnyOutOfRange)
418 return nullptr;
419
420 // Build the shift amount constant vector.
421 SmallVector<Constant *, 8> ShiftVecAmts;
422 for (int Idx : ShiftAmts) {
423 if (Idx < 0)
424 ShiftVecAmts.push_back(UndefValue::get(SVT));
425 else
426 ShiftVecAmts.push_back(ConstantInt::get(SVT, Idx));
427 }
428 auto ShiftVec = ConstantVector::get(ShiftVecAmts);
429
430 if (ShiftLeft)
431 return Builder.CreateShl(Vec, ShiftVec);
432
433 if (LogicalShift)
434 return Builder.CreateLShr(Vec, ShiftVec);
435
436 return Builder.CreateAShr(Vec, ShiftVec);
437}
438
Simon Pilgrim91e3ac82016-06-07 08:18:35 +0000439static Value *simplifyX86movmsk(const IntrinsicInst &II,
440 InstCombiner::BuilderTy &Builder) {
441 Value *Arg = II.getArgOperand(0);
442 Type *ResTy = II.getType();
443 Type *ArgTy = Arg->getType();
444
445 // movmsk(undef) -> zero as we must ensure the upper bits are zero.
446 if (isa<UndefValue>(Arg))
447 return Constant::getNullValue(ResTy);
448
449 // We can't easily peek through x86_mmx types.
450 if (!ArgTy->isVectorTy())
451 return nullptr;
452
453 auto *C = dyn_cast<Constant>(Arg);
454 if (!C)
455 return nullptr;
456
457 // Extract signbits of the vector input and pack into integer result.
458 APInt Result(ResTy->getPrimitiveSizeInBits(), 0);
459 for (unsigned I = 0, E = ArgTy->getVectorNumElements(); I != E; ++I) {
460 auto *COp = C->getAggregateElement(I);
461 if (!COp)
462 return nullptr;
463 if (isa<UndefValue>(COp))
464 continue;
465
466 auto *CInt = dyn_cast<ConstantInt>(COp);
467 auto *CFp = dyn_cast<ConstantFP>(COp);
468 if (!CInt && !CFp)
469 return nullptr;
470
471 if ((CInt && CInt->isNegative()) || (CFp && CFp->isNegative()))
472 Result.setBit(I);
473 }
474
475 return Constant::getIntegerValue(ResTy, Result);
476}
477
Sanjay Patel6038d3e2016-01-29 23:27:03 +0000478static Value *simplifyX86insertps(const IntrinsicInst &II,
Sanjay Patelc86867c2015-04-16 17:52:13 +0000479 InstCombiner::BuilderTy &Builder) {
Sanjay Patel03c03f52016-01-28 00:03:16 +0000480 auto *CInt = dyn_cast<ConstantInt>(II.getArgOperand(2));
481 if (!CInt)
482 return nullptr;
Simon Pilgrim54fcd622015-07-25 20:41:00 +0000483
Sanjay Patel03c03f52016-01-28 00:03:16 +0000484 VectorType *VecTy = cast<VectorType>(II.getType());
485 assert(VecTy->getNumElements() == 4 && "insertps with wrong vector type");
Sanjay Patelc86867c2015-04-16 17:52:13 +0000486
Sanjay Patel03c03f52016-01-28 00:03:16 +0000487 // The immediate permute control byte looks like this:
488 // [3:0] - zero mask for each 32-bit lane
489 // [5:4] - select one 32-bit destination lane
490 // [7:6] - select one 32-bit source lane
Sanjay Patelc86867c2015-04-16 17:52:13 +0000491
Sanjay Patel03c03f52016-01-28 00:03:16 +0000492 uint8_t Imm = CInt->getZExtValue();
493 uint8_t ZMask = Imm & 0xf;
494 uint8_t DestLane = (Imm >> 4) & 0x3;
495 uint8_t SourceLane = (Imm >> 6) & 0x3;
Sanjay Patelc1d20a32015-04-25 20:55:25 +0000496
Sanjay Patel03c03f52016-01-28 00:03:16 +0000497 ConstantAggregateZero *ZeroVector = ConstantAggregateZero::get(VecTy);
Sanjay Patelc86867c2015-04-16 17:52:13 +0000498
Sanjay Patel03c03f52016-01-28 00:03:16 +0000499 // If all zero mask bits are set, this was just a weird way to
500 // generate a zero vector.
501 if (ZMask == 0xf)
502 return ZeroVector;
Sanjay Patelc1d20a32015-04-25 20:55:25 +0000503
Sanjay Patel03c03f52016-01-28 00:03:16 +0000504 // Initialize by passing all of the first source bits through.
505 int ShuffleMask[4] = { 0, 1, 2, 3 };
Sanjay Patelc1d20a32015-04-25 20:55:25 +0000506
Sanjay Patel03c03f52016-01-28 00:03:16 +0000507 // We may replace the second operand with the zero vector.
508 Value *V1 = II.getArgOperand(1);
509
510 if (ZMask) {
511 // If the zero mask is being used with a single input or the zero mask
512 // overrides the destination lane, this is a shuffle with the zero vector.
513 if ((II.getArgOperand(0) == II.getArgOperand(1)) ||
514 (ZMask & (1 << DestLane))) {
515 V1 = ZeroVector;
516 // We may still move 32-bits of the first source vector from one lane
517 // to another.
518 ShuffleMask[DestLane] = SourceLane;
519 // The zero mask may override the previous insert operation.
520 for (unsigned i = 0; i < 4; ++i)
521 if ((ZMask >> i) & 0x1)
522 ShuffleMask[i] = i + 4;
Sanjay Patelc1d20a32015-04-25 20:55:25 +0000523 } else {
Sanjay Patel03c03f52016-01-28 00:03:16 +0000524 // TODO: Model this case as 2 shuffles or a 'logical and' plus shuffle?
525 return nullptr;
Sanjay Patelc1d20a32015-04-25 20:55:25 +0000526 }
Sanjay Patel03c03f52016-01-28 00:03:16 +0000527 } else {
528 // Replace the selected destination lane with the selected source lane.
529 ShuffleMask[DestLane] = SourceLane + 4;
Sanjay Patelc86867c2015-04-16 17:52:13 +0000530 }
Sanjay Patel03c03f52016-01-28 00:03:16 +0000531
532 return Builder.CreateShuffleVector(II.getArgOperand(0), V1, ShuffleMask);
Sanjay Patelc86867c2015-04-16 17:52:13 +0000533}
534
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000535/// Attempt to simplify SSE4A EXTRQ/EXTRQI instructions using constant folding
536/// or conversion to a shuffle vector.
Sanjay Patel6038d3e2016-01-29 23:27:03 +0000537static Value *simplifyX86extrq(IntrinsicInst &II, Value *Op0,
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000538 ConstantInt *CILength, ConstantInt *CIIndex,
539 InstCombiner::BuilderTy &Builder) {
540 auto LowConstantHighUndef = [&](uint64_t Val) {
541 Type *IntTy64 = Type::getInt64Ty(II.getContext());
542 Constant *Args[] = {ConstantInt::get(IntTy64, Val),
543 UndefValue::get(IntTy64)};
544 return ConstantVector::get(Args);
545 };
546
547 // See if we're dealing with constant values.
548 Constant *C0 = dyn_cast<Constant>(Op0);
549 ConstantInt *CI0 =
550 C0 ? dyn_cast<ConstantInt>(C0->getAggregateElement((unsigned)0))
551 : nullptr;
552
553 // Attempt to constant fold.
554 if (CILength && CIIndex) {
555 // From AMD documentation: "The bit index and field length are each six
556 // bits in length other bits of the field are ignored."
557 APInt APIndex = CIIndex->getValue().zextOrTrunc(6);
558 APInt APLength = CILength->getValue().zextOrTrunc(6);
559
560 unsigned Index = APIndex.getZExtValue();
561
562 // From AMD documentation: "a value of zero in the field length is
563 // defined as length of 64".
564 unsigned Length = APLength == 0 ? 64 : APLength.getZExtValue();
565
566 // From AMD documentation: "If the sum of the bit index + length field
567 // is greater than 64, the results are undefined".
568 unsigned End = Index + Length;
569
570 // Note that both field index and field length are 8-bit quantities.
571 // Since variables 'Index' and 'Length' are unsigned values
572 // obtained from zero-extending field index and field length
573 // respectively, their sum should never wrap around.
574 if (End > 64)
575 return UndefValue::get(II.getType());
576
577 // If we are inserting whole bytes, we can convert this to a shuffle.
578 // Lowering can recognize EXTRQI shuffle masks.
579 if ((Length % 8) == 0 && (Index % 8) == 0) {
580 // Convert bit indices to byte indices.
581 Length /= 8;
582 Index /= 8;
583
584 Type *IntTy8 = Type::getInt8Ty(II.getContext());
585 Type *IntTy32 = Type::getInt32Ty(II.getContext());
586 VectorType *ShufTy = VectorType::get(IntTy8, 16);
587
588 SmallVector<Constant *, 16> ShuffleMask;
589 for (int i = 0; i != (int)Length; ++i)
590 ShuffleMask.push_back(
591 Constant::getIntegerValue(IntTy32, APInt(32, i + Index)));
592 for (int i = Length; i != 8; ++i)
593 ShuffleMask.push_back(
594 Constant::getIntegerValue(IntTy32, APInt(32, i + 16)));
595 for (int i = 8; i != 16; ++i)
596 ShuffleMask.push_back(UndefValue::get(IntTy32));
597
598 Value *SV = Builder.CreateShuffleVector(
599 Builder.CreateBitCast(Op0, ShufTy),
600 ConstantAggregateZero::get(ShufTy), ConstantVector::get(ShuffleMask));
601 return Builder.CreateBitCast(SV, II.getType());
602 }
603
604 // Constant Fold - shift Index'th bit to lowest position and mask off
605 // Length bits.
606 if (CI0) {
607 APInt Elt = CI0->getValue();
608 Elt = Elt.lshr(Index).zextOrTrunc(Length);
609 return LowConstantHighUndef(Elt.getZExtValue());
610 }
611
612 // If we were an EXTRQ call, we'll save registers if we convert to EXTRQI.
613 if (II.getIntrinsicID() == Intrinsic::x86_sse4a_extrq) {
614 Value *Args[] = {Op0, CILength, CIIndex};
Sanjay Patelaf674fb2015-12-14 17:24:23 +0000615 Module *M = II.getModule();
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000616 Value *F = Intrinsic::getDeclaration(M, Intrinsic::x86_sse4a_extrqi);
617 return Builder.CreateCall(F, Args);
618 }
619 }
620
621 // Constant Fold - extraction from zero is always {zero, undef}.
622 if (CI0 && CI0->equalsInt(0))
623 return LowConstantHighUndef(0);
624
625 return nullptr;
626}
627
628/// Attempt to simplify SSE4A INSERTQ/INSERTQI instructions using constant
629/// folding or conversion to a shuffle vector.
Sanjay Patel6038d3e2016-01-29 23:27:03 +0000630static Value *simplifyX86insertq(IntrinsicInst &II, Value *Op0, Value *Op1,
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000631 APInt APLength, APInt APIndex,
632 InstCombiner::BuilderTy &Builder) {
633
634 // From AMD documentation: "The bit index and field length are each six bits
635 // in length other bits of the field are ignored."
636 APIndex = APIndex.zextOrTrunc(6);
637 APLength = APLength.zextOrTrunc(6);
638
639 // Attempt to constant fold.
640 unsigned Index = APIndex.getZExtValue();
641
642 // From AMD documentation: "a value of zero in the field length is
643 // defined as length of 64".
644 unsigned Length = APLength == 0 ? 64 : APLength.getZExtValue();
645
646 // From AMD documentation: "If the sum of the bit index + length field
647 // is greater than 64, the results are undefined".
648 unsigned End = Index + Length;
649
650 // Note that both field index and field length are 8-bit quantities.
651 // Since variables 'Index' and 'Length' are unsigned values
652 // obtained from zero-extending field index and field length
653 // respectively, their sum should never wrap around.
654 if (End > 64)
655 return UndefValue::get(II.getType());
656
657 // If we are inserting whole bytes, we can convert this to a shuffle.
658 // Lowering can recognize INSERTQI shuffle masks.
659 if ((Length % 8) == 0 && (Index % 8) == 0) {
660 // Convert bit indices to byte indices.
661 Length /= 8;
662 Index /= 8;
663
664 Type *IntTy8 = Type::getInt8Ty(II.getContext());
665 Type *IntTy32 = Type::getInt32Ty(II.getContext());
666 VectorType *ShufTy = VectorType::get(IntTy8, 16);
667
668 SmallVector<Constant *, 16> ShuffleMask;
669 for (int i = 0; i != (int)Index; ++i)
670 ShuffleMask.push_back(Constant::getIntegerValue(IntTy32, APInt(32, i)));
671 for (int i = 0; i != (int)Length; ++i)
672 ShuffleMask.push_back(
673 Constant::getIntegerValue(IntTy32, APInt(32, i + 16)));
674 for (int i = Index + Length; i != 8; ++i)
675 ShuffleMask.push_back(Constant::getIntegerValue(IntTy32, APInt(32, i)));
676 for (int i = 8; i != 16; ++i)
677 ShuffleMask.push_back(UndefValue::get(IntTy32));
678
679 Value *SV = Builder.CreateShuffleVector(Builder.CreateBitCast(Op0, ShufTy),
680 Builder.CreateBitCast(Op1, ShufTy),
681 ConstantVector::get(ShuffleMask));
682 return Builder.CreateBitCast(SV, II.getType());
683 }
684
685 // See if we're dealing with constant values.
686 Constant *C0 = dyn_cast<Constant>(Op0);
687 Constant *C1 = dyn_cast<Constant>(Op1);
688 ConstantInt *CI00 =
689 C0 ? dyn_cast<ConstantInt>(C0->getAggregateElement((unsigned)0))
690 : nullptr;
691 ConstantInt *CI10 =
692 C1 ? dyn_cast<ConstantInt>(C1->getAggregateElement((unsigned)0))
693 : nullptr;
694
695 // Constant Fold - insert bottom Length bits starting at the Index'th bit.
696 if (CI00 && CI10) {
697 APInt V00 = CI00->getValue();
698 APInt V10 = CI10->getValue();
699 APInt Mask = APInt::getLowBitsSet(64, Length).shl(Index);
700 V00 = V00 & ~Mask;
701 V10 = V10.zextOrTrunc(Length).zextOrTrunc(64).shl(Index);
702 APInt Val = V00 | V10;
703 Type *IntTy64 = Type::getInt64Ty(II.getContext());
704 Constant *Args[] = {ConstantInt::get(IntTy64, Val.getZExtValue()),
705 UndefValue::get(IntTy64)};
706 return ConstantVector::get(Args);
707 }
708
709 // If we were an INSERTQ call, we'll save demanded elements if we convert to
710 // INSERTQI.
711 if (II.getIntrinsicID() == Intrinsic::x86_sse4a_insertq) {
712 Type *IntTy8 = Type::getInt8Ty(II.getContext());
713 Constant *CILength = ConstantInt::get(IntTy8, Length, false);
714 Constant *CIIndex = ConstantInt::get(IntTy8, Index, false);
715
716 Value *Args[] = {Op0, Op1, CILength, CIIndex};
Sanjay Patelaf674fb2015-12-14 17:24:23 +0000717 Module *M = II.getModule();
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000718 Value *F = Intrinsic::getDeclaration(M, Intrinsic::x86_sse4a_insertqi);
719 return Builder.CreateCall(F, Args);
720 }
721
722 return nullptr;
723}
724
Simon Pilgrimc0c56e72016-04-24 17:00:34 +0000725/// Attempt to convert pshufb* to shufflevector if the mask is constant.
726static Value *simplifyX86pshufb(const IntrinsicInst &II,
727 InstCombiner::BuilderTy &Builder) {
Simon Pilgrimbf60cc42016-04-29 21:34:54 +0000728 Constant *V = dyn_cast<Constant>(II.getArgOperand(1));
729 if (!V)
730 return nullptr;
731
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +0000732 auto *VecTy = cast<VectorType>(II.getType());
733 auto *MaskEltTy = Type::getInt32Ty(II.getContext());
734 unsigned NumElts = VecTy->getNumElements();
Simon Pilgrimc0c56e72016-04-24 17:00:34 +0000735 assert((NumElts == 16 || NumElts == 32) &&
736 "Unexpected number of elements in shuffle mask!");
Simon Pilgrimbf60cc42016-04-29 21:34:54 +0000737
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +0000738 // Construct a shuffle mask from constant integers or UNDEFs.
Simon Pilgrimeeacc402016-05-01 20:22:42 +0000739 Constant *Indexes[32] = {NULL};
Simon Pilgrimc0c56e72016-04-24 17:00:34 +0000740
Simon Pilgrimbf60cc42016-04-29 21:34:54 +0000741 // Each byte in the shuffle control mask forms an index to permute the
742 // corresponding byte in the destination operand.
743 for (unsigned I = 0; I < NumElts; ++I) {
744 Constant *COp = V->getAggregateElement(I);
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +0000745 if (!COp || (!isa<UndefValue>(COp) && !isa<ConstantInt>(COp)))
Simon Pilgrimbf60cc42016-04-29 21:34:54 +0000746 return nullptr;
Simon Pilgrimc0c56e72016-04-24 17:00:34 +0000747
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +0000748 if (isa<UndefValue>(COp)) {
749 Indexes[I] = UndefValue::get(MaskEltTy);
750 continue;
751 }
752
Simon Pilgrimbf60cc42016-04-29 21:34:54 +0000753 int8_t Index = cast<ConstantInt>(COp)->getValue().getZExtValue();
754
755 // If the most significant bit (bit[7]) of each byte of the shuffle
756 // control mask is set, then zero is written in the result byte.
757 // The zero vector is in the right-hand side of the resulting
758 // shufflevector.
759
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +0000760 // The value of each index for the high 128-bit lane is the least
761 // significant 4 bits of the respective shuffle control byte.
762 Index = ((Index < 0) ? NumElts : Index & 0x0F) + (I & 0xF0);
763 Indexes[I] = ConstantInt::get(MaskEltTy, Index);
Simon Pilgrimbf60cc42016-04-29 21:34:54 +0000764 }
Simon Pilgrimc0c56e72016-04-24 17:00:34 +0000765
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +0000766 auto ShuffleMask = ConstantVector::get(makeArrayRef(Indexes, NumElts));
Simon Pilgrimc0c56e72016-04-24 17:00:34 +0000767 auto V1 = II.getArgOperand(0);
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +0000768 auto V2 = Constant::getNullValue(VecTy);
Simon Pilgrimc0c56e72016-04-24 17:00:34 +0000769 return Builder.CreateShuffleVector(V1, V2, ShuffleMask);
770}
771
Simon Pilgrim2f6097d2016-04-24 17:23:46 +0000772/// Attempt to convert vpermilvar* to shufflevector if the mask is constant.
773static Value *simplifyX86vpermilvar(const IntrinsicInst &II,
774 InstCombiner::BuilderTy &Builder) {
Simon Pilgrim640f9962016-04-30 07:23:30 +0000775 Constant *V = dyn_cast<Constant>(II.getArgOperand(1));
776 if (!V)
777 return nullptr;
Simon Pilgrim2f6097d2016-04-24 17:23:46 +0000778
Simon Pilgrimeeacc402016-05-01 20:22:42 +0000779 auto *MaskEltTy = Type::getInt32Ty(II.getContext());
780 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
781 assert(NumElts == 8 || NumElts == 4 || NumElts == 2);
Simon Pilgrim2f6097d2016-04-24 17:23:46 +0000782
Simon Pilgrimeeacc402016-05-01 20:22:42 +0000783 // Construct a shuffle mask from constant integers or UNDEFs.
784 Constant *Indexes[8] = {NULL};
Simon Pilgrim640f9962016-04-30 07:23:30 +0000785
786 // The intrinsics only read one or two bits, clear the rest.
Simon Pilgrimeeacc402016-05-01 20:22:42 +0000787 for (unsigned I = 0; I < NumElts; ++I) {
Simon Pilgrim640f9962016-04-30 07:23:30 +0000788 Constant *COp = V->getAggregateElement(I);
Simon Pilgrimeeacc402016-05-01 20:22:42 +0000789 if (!COp || (!isa<UndefValue>(COp) && !isa<ConstantInt>(COp)))
Simon Pilgrim640f9962016-04-30 07:23:30 +0000790 return nullptr;
791
Simon Pilgrimeeacc402016-05-01 20:22:42 +0000792 if (isa<UndefValue>(COp)) {
793 Indexes[I] = UndefValue::get(MaskEltTy);
794 continue;
795 }
796
797 APInt Index = cast<ConstantInt>(COp)->getValue();
798 Index = Index.zextOrTrunc(32).getLoBits(2);
Simon Pilgrim640f9962016-04-30 07:23:30 +0000799
800 // The PD variants uses bit 1 to select per-lane element index, so
801 // shift down to convert to generic shuffle mask index.
802 if (II.getIntrinsicID() == Intrinsic::x86_avx_vpermilvar_pd ||
803 II.getIntrinsicID() == Intrinsic::x86_avx_vpermilvar_pd_256)
Simon Pilgrimeeacc402016-05-01 20:22:42 +0000804 Index = Index.lshr(1);
805
806 // The _256 variants are a bit trickier since the mask bits always index
807 // into the corresponding 128 half. In order to convert to a generic
808 // shuffle, we have to make that explicit.
809 if ((II.getIntrinsicID() == Intrinsic::x86_avx_vpermilvar_ps_256 ||
810 II.getIntrinsicID() == Intrinsic::x86_avx_vpermilvar_pd_256) &&
811 ((NumElts / 2) <= I)) {
812 Index += APInt(32, NumElts / 2);
813 }
814
815 Indexes[I] = ConstantInt::get(MaskEltTy, Index);
Simon Pilgrim2f6097d2016-04-24 17:23:46 +0000816 }
817
Simon Pilgrimeeacc402016-05-01 20:22:42 +0000818 auto ShuffleMask = ConstantVector::get(makeArrayRef(Indexes, NumElts));
Simon Pilgrim2f6097d2016-04-24 17:23:46 +0000819 auto V1 = II.getArgOperand(0);
820 auto V2 = UndefValue::get(V1->getType());
821 return Builder.CreateShuffleVector(V1, V2, ShuffleMask);
822}
823
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +0000824/// Attempt to convert vpermd/vpermps to shufflevector if the mask is constant.
825static Value *simplifyX86vpermv(const IntrinsicInst &II,
826 InstCombiner::BuilderTy &Builder) {
827 auto *V = dyn_cast<Constant>(II.getArgOperand(1));
828 if (!V)
829 return nullptr;
830
Simon Pilgrimca140b12016-05-01 20:43:02 +0000831 auto *VecTy = cast<VectorType>(II.getType());
832 auto *MaskEltTy = Type::getInt32Ty(II.getContext());
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +0000833 unsigned Size = VecTy->getNumElements();
834 assert(Size == 8 && "Unexpected shuffle mask size");
835
Simon Pilgrimca140b12016-05-01 20:43:02 +0000836 // Construct a shuffle mask from constant integers or UNDEFs.
837 Constant *Indexes[8] = {NULL};
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +0000838
839 for (unsigned I = 0; I < Size; ++I) {
840 Constant *COp = V->getAggregateElement(I);
Simon Pilgrimca140b12016-05-01 20:43:02 +0000841 if (!COp || (!isa<UndefValue>(COp) && !isa<ConstantInt>(COp)))
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +0000842 return nullptr;
843
Simon Pilgrimca140b12016-05-01 20:43:02 +0000844 if (isa<UndefValue>(COp)) {
845 Indexes[I] = UndefValue::get(MaskEltTy);
846 continue;
847 }
848
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +0000849 APInt Index = cast<ConstantInt>(COp)->getValue();
Simon Pilgrimca140b12016-05-01 20:43:02 +0000850 Index = Index.zextOrTrunc(32).getLoBits(3);
851 Indexes[I] = ConstantInt::get(MaskEltTy, Index);
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +0000852 }
853
Simon Pilgrimca140b12016-05-01 20:43:02 +0000854 auto ShuffleMask = ConstantVector::get(makeArrayRef(Indexes, Size));
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +0000855 auto V1 = II.getArgOperand(0);
856 auto V2 = UndefValue::get(VecTy);
857 return Builder.CreateShuffleVector(V1, V2, ShuffleMask);
858}
859
Sanjay Patelccf5f242015-03-20 21:47:56 +0000860/// The shuffle mask for a perm2*128 selects any two halves of two 256-bit
861/// source vectors, unless a zero bit is set. If a zero bit is set,
862/// then ignore that half of the mask and clear that half of the vector.
Sanjay Patel6038d3e2016-01-29 23:27:03 +0000863static Value *simplifyX86vperm2(const IntrinsicInst &II,
Sanjay Patelccf5f242015-03-20 21:47:56 +0000864 InstCombiner::BuilderTy &Builder) {
Sanjay Patel03c03f52016-01-28 00:03:16 +0000865 auto *CInt = dyn_cast<ConstantInt>(II.getArgOperand(2));
866 if (!CInt)
867 return nullptr;
Sanjay Patelccf5f242015-03-20 21:47:56 +0000868
Sanjay Patel03c03f52016-01-28 00:03:16 +0000869 VectorType *VecTy = cast<VectorType>(II.getType());
870 ConstantAggregateZero *ZeroVector = ConstantAggregateZero::get(VecTy);
Sanjay Patel43a87fd2015-03-24 20:36:42 +0000871
Sanjay Patel03c03f52016-01-28 00:03:16 +0000872 // The immediate permute control byte looks like this:
873 // [1:0] - select 128 bits from sources for low half of destination
874 // [2] - ignore
875 // [3] - zero low half of destination
876 // [5:4] - select 128 bits from sources for high half of destination
877 // [6] - ignore
878 // [7] - zero high half of destination
Sanjay Patel43a87fd2015-03-24 20:36:42 +0000879
Sanjay Patel03c03f52016-01-28 00:03:16 +0000880 uint8_t Imm = CInt->getZExtValue();
Sanjay Patel43a87fd2015-03-24 20:36:42 +0000881
Sanjay Patel03c03f52016-01-28 00:03:16 +0000882 bool LowHalfZero = Imm & 0x08;
883 bool HighHalfZero = Imm & 0x80;
Sanjay Patel43a87fd2015-03-24 20:36:42 +0000884
Sanjay Patel03c03f52016-01-28 00:03:16 +0000885 // If both zero mask bits are set, this was just a weird way to
886 // generate a zero vector.
887 if (LowHalfZero && HighHalfZero)
888 return ZeroVector;
Sanjay Patel43a87fd2015-03-24 20:36:42 +0000889
Sanjay Patel03c03f52016-01-28 00:03:16 +0000890 // If 0 or 1 zero mask bits are set, this is a simple shuffle.
891 unsigned NumElts = VecTy->getNumElements();
892 unsigned HalfSize = NumElts / 2;
893 SmallVector<int, 8> ShuffleMask(NumElts);
Simon Pilgrim54fcd622015-07-25 20:41:00 +0000894
Sanjay Patel03c03f52016-01-28 00:03:16 +0000895 // The high bit of the selection field chooses the 1st or 2nd operand.
896 bool LowInputSelect = Imm & 0x02;
897 bool HighInputSelect = Imm & 0x20;
Sanjay Patelccf5f242015-03-20 21:47:56 +0000898
Sanjay Patel03c03f52016-01-28 00:03:16 +0000899 // The low bit of the selection field chooses the low or high half
900 // of the selected operand.
901 bool LowHalfSelect = Imm & 0x01;
902 bool HighHalfSelect = Imm & 0x10;
Simon Pilgrim54fcd622015-07-25 20:41:00 +0000903
Sanjay Patel03c03f52016-01-28 00:03:16 +0000904 // Determine which operand(s) are actually in use for this instruction.
905 Value *V0 = LowInputSelect ? II.getArgOperand(1) : II.getArgOperand(0);
906 Value *V1 = HighInputSelect ? II.getArgOperand(1) : II.getArgOperand(0);
Simon Pilgrim54fcd622015-07-25 20:41:00 +0000907
Sanjay Patel03c03f52016-01-28 00:03:16 +0000908 // If needed, replace operands based on zero mask.
909 V0 = LowHalfZero ? ZeroVector : V0;
910 V1 = HighHalfZero ? ZeroVector : V1;
Sanjay Patelccf5f242015-03-20 21:47:56 +0000911
Sanjay Patel03c03f52016-01-28 00:03:16 +0000912 // Permute low half of result.
913 unsigned StartIndex = LowHalfSelect ? HalfSize : 0;
914 for (unsigned i = 0; i < HalfSize; ++i)
915 ShuffleMask[i] = StartIndex + i;
Sanjay Patel43a87fd2015-03-24 20:36:42 +0000916
Sanjay Patel03c03f52016-01-28 00:03:16 +0000917 // Permute high half of result.
918 StartIndex = HighHalfSelect ? HalfSize : 0;
919 StartIndex += NumElts;
920 for (unsigned i = 0; i < HalfSize; ++i)
921 ShuffleMask[i + HalfSize] = StartIndex + i;
922
923 return Builder.CreateShuffleVector(V0, V1, ShuffleMask);
Sanjay Patelccf5f242015-03-20 21:47:56 +0000924}
925
Simon Pilgrim1d1c56e22015-10-11 14:38:34 +0000926/// Decode XOP integer vector comparison intrinsics.
Sanjay Patel6038d3e2016-01-29 23:27:03 +0000927static Value *simplifyX86vpcom(const IntrinsicInst &II,
Sanjay Patelf9f5d3c2016-01-29 23:14:58 +0000928 InstCombiner::BuilderTy &Builder,
929 bool IsSigned) {
Simon Pilgrim1d1c56e22015-10-11 14:38:34 +0000930 if (auto *CInt = dyn_cast<ConstantInt>(II.getArgOperand(2))) {
931 uint64_t Imm = CInt->getZExtValue() & 0x7;
932 VectorType *VecTy = cast<VectorType>(II.getType());
933 CmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
934
935 switch (Imm) {
936 case 0x0:
937 Pred = IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
938 break;
939 case 0x1:
940 Pred = IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
941 break;
942 case 0x2:
943 Pred = IsSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
944 break;
945 case 0x3:
946 Pred = IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
947 break;
948 case 0x4:
949 Pred = ICmpInst::ICMP_EQ; break;
950 case 0x5:
951 Pred = ICmpInst::ICMP_NE; break;
952 case 0x6:
953 return ConstantInt::getSigned(VecTy, 0); // FALSE
954 case 0x7:
955 return ConstantInt::getSigned(VecTy, -1); // TRUE
956 }
957
Sanjay Patelf9f5d3c2016-01-29 23:14:58 +0000958 if (Value *Cmp = Builder.CreateICmp(Pred, II.getArgOperand(0),
959 II.getArgOperand(1)))
Simon Pilgrim1d1c56e22015-10-11 14:38:34 +0000960 return Builder.CreateSExtOrTrunc(Cmp, VecTy);
961 }
962 return nullptr;
963}
964
Sanjay Patel0069f562016-01-31 16:35:23 +0000965static Value *simplifyMinnumMaxnum(const IntrinsicInst &II) {
966 Value *Arg0 = II.getArgOperand(0);
967 Value *Arg1 = II.getArgOperand(1);
968
969 // fmin(x, x) -> x
970 if (Arg0 == Arg1)
971 return Arg0;
972
973 const auto *C1 = dyn_cast<ConstantFP>(Arg1);
974
975 // fmin(x, nan) -> x
976 if (C1 && C1->isNaN())
977 return Arg0;
978
979 // This is the value because if undef were NaN, we would return the other
980 // value and cannot return a NaN unless both operands are.
981 //
982 // fmin(undef, x) -> x
983 if (isa<UndefValue>(Arg0))
984 return Arg1;
985
986 // fmin(x, undef) -> x
987 if (isa<UndefValue>(Arg1))
988 return Arg0;
989
990 Value *X = nullptr;
991 Value *Y = nullptr;
992 if (II.getIntrinsicID() == Intrinsic::minnum) {
993 // fmin(x, fmin(x, y)) -> fmin(x, y)
994 // fmin(y, fmin(x, y)) -> fmin(x, y)
995 if (match(Arg1, m_FMin(m_Value(X), m_Value(Y)))) {
996 if (Arg0 == X || Arg0 == Y)
997 return Arg1;
998 }
999
1000 // fmin(fmin(x, y), x) -> fmin(x, y)
1001 // fmin(fmin(x, y), y) -> fmin(x, y)
1002 if (match(Arg0, m_FMin(m_Value(X), m_Value(Y)))) {
1003 if (Arg1 == X || Arg1 == Y)
1004 return Arg0;
1005 }
1006
1007 // TODO: fmin(nnan x, inf) -> x
1008 // TODO: fmin(nnan ninf x, flt_max) -> x
1009 if (C1 && C1->isInfinity()) {
1010 // fmin(x, -inf) -> -inf
1011 if (C1->isNegative())
1012 return Arg1;
1013 }
1014 } else {
1015 assert(II.getIntrinsicID() == Intrinsic::maxnum);
1016 // fmax(x, fmax(x, y)) -> fmax(x, y)
1017 // fmax(y, fmax(x, y)) -> fmax(x, y)
1018 if (match(Arg1, m_FMax(m_Value(X), m_Value(Y)))) {
1019 if (Arg0 == X || Arg0 == Y)
1020 return Arg1;
1021 }
1022
1023 // fmax(fmax(x, y), x) -> fmax(x, y)
1024 // fmax(fmax(x, y), y) -> fmax(x, y)
1025 if (match(Arg0, m_FMax(m_Value(X), m_Value(Y)))) {
1026 if (Arg1 == X || Arg1 == Y)
1027 return Arg0;
1028 }
1029
1030 // TODO: fmax(nnan x, -inf) -> x
1031 // TODO: fmax(nnan ninf x, -flt_max) -> x
1032 if (C1 && C1->isInfinity()) {
1033 // fmax(x, inf) -> inf
1034 if (!C1->isNegative())
1035 return Arg1;
1036 }
1037 }
1038 return nullptr;
1039}
1040
Sanjay Patelb695c552016-02-01 17:00:10 +00001041static Value *simplifyMaskedLoad(const IntrinsicInst &II,
1042 InstCombiner::BuilderTy &Builder) {
1043 auto *ConstMask = dyn_cast<Constant>(II.getArgOperand(2));
1044 if (!ConstMask)
1045 return nullptr;
1046
1047 // If the mask is all zeros, the "passthru" argument is the result.
1048 if (ConstMask->isNullValue())
1049 return II.getArgOperand(3);
1050
1051 // If the mask is all ones, this is a plain vector load of the 1st argument.
1052 if (ConstMask->isAllOnesValue()) {
1053 Value *LoadPtr = II.getArgOperand(0);
1054 unsigned Alignment = cast<ConstantInt>(II.getArgOperand(1))->getZExtValue();
1055 return Builder.CreateAlignedLoad(LoadPtr, Alignment, "unmaskedload");
1056 }
1057
1058 return nullptr;
1059}
1060
Sanjay Patel04f792b2016-02-01 19:39:52 +00001061static Instruction *simplifyMaskedStore(IntrinsicInst &II, InstCombiner &IC) {
1062 auto *ConstMask = dyn_cast<Constant>(II.getArgOperand(3));
1063 if (!ConstMask)
1064 return nullptr;
1065
1066 // If the mask is all zeros, this instruction does nothing.
1067 if (ConstMask->isNullValue())
Sanjay Patel4b198802016-02-01 22:23:39 +00001068 return IC.eraseInstFromFunction(II);
Sanjay Patel04f792b2016-02-01 19:39:52 +00001069
1070 // If the mask is all ones, this is a plain vector store of the 1st argument.
1071 if (ConstMask->isAllOnesValue()) {
1072 Value *StorePtr = II.getArgOperand(1);
1073 unsigned Alignment = cast<ConstantInt>(II.getArgOperand(2))->getZExtValue();
1074 return new StoreInst(II.getArgOperand(0), StorePtr, false, Alignment);
1075 }
1076
1077 return nullptr;
1078}
1079
Sanjay Patel103ab7d2016-02-01 22:10:26 +00001080static Instruction *simplifyMaskedGather(IntrinsicInst &II, InstCombiner &IC) {
1081 // If the mask is all zeros, return the "passthru" argument of the gather.
1082 auto *ConstMask = dyn_cast<Constant>(II.getArgOperand(2));
1083 if (ConstMask && ConstMask->isNullValue())
Sanjay Patel4b198802016-02-01 22:23:39 +00001084 return IC.replaceInstUsesWith(II, II.getArgOperand(3));
Sanjay Patel103ab7d2016-02-01 22:10:26 +00001085
1086 return nullptr;
1087}
1088
1089static Instruction *simplifyMaskedScatter(IntrinsicInst &II, InstCombiner &IC) {
1090 // If the mask is all zeros, a scatter does nothing.
1091 auto *ConstMask = dyn_cast<Constant>(II.getArgOperand(3));
1092 if (ConstMask && ConstMask->isNullValue())
Sanjay Patel4b198802016-02-01 22:23:39 +00001093 return IC.eraseInstFromFunction(II);
Sanjay Patel103ab7d2016-02-01 22:10:26 +00001094
1095 return nullptr;
1096}
1097
Sanjay Patel1ace9932016-02-26 21:04:14 +00001098// TODO: If the x86 backend knew how to convert a bool vector mask back to an
1099// XMM register mask efficiently, we could transform all x86 masked intrinsics
1100// to LLVM masked intrinsics and remove the x86 masked intrinsic defs.
Sanjay Patel98a71502016-02-29 23:16:48 +00001101static Instruction *simplifyX86MaskedLoad(IntrinsicInst &II, InstCombiner &IC) {
1102 Value *Ptr = II.getOperand(0);
1103 Value *Mask = II.getOperand(1);
Sanjay Patel5e5056d2016-04-12 23:16:23 +00001104 Constant *ZeroVec = Constant::getNullValue(II.getType());
Sanjay Patel98a71502016-02-29 23:16:48 +00001105
1106 // Special case a zero mask since that's not a ConstantDataVector.
Sanjay Patel5e5056d2016-04-12 23:16:23 +00001107 // This masked load instruction creates a zero vector.
Sanjay Patel98a71502016-02-29 23:16:48 +00001108 if (isa<ConstantAggregateZero>(Mask))
Sanjay Patel5e5056d2016-04-12 23:16:23 +00001109 return IC.replaceInstUsesWith(II, ZeroVec);
Sanjay Patel98a71502016-02-29 23:16:48 +00001110
1111 auto *ConstMask = dyn_cast<ConstantDataVector>(Mask);
1112 if (!ConstMask)
1113 return nullptr;
1114
1115 // The mask is constant. Convert this x86 intrinsic to the LLVM instrinsic
1116 // to allow target-independent optimizations.
1117
1118 // First, cast the x86 intrinsic scalar pointer to a vector pointer to match
1119 // the LLVM intrinsic definition for the pointer argument.
1120 unsigned AddrSpace = cast<PointerType>(Ptr->getType())->getAddressSpace();
1121 PointerType *VecPtrTy = PointerType::get(II.getType(), AddrSpace);
1122 Value *PtrCast = IC.Builder->CreateBitCast(Ptr, VecPtrTy, "castvec");
1123
1124 // Second, convert the x86 XMM integer vector mask to a vector of bools based
1125 // on each element's most significant bit (the sign bit).
1126 Constant *BoolMask = getNegativeIsTrueBoolVec(ConstMask);
1127
Sanjay Patel5e5056d2016-04-12 23:16:23 +00001128 // The pass-through vector for an x86 masked load is a zero vector.
1129 CallInst *NewMaskedLoad =
1130 IC.Builder->CreateMaskedLoad(PtrCast, 1, BoolMask, ZeroVec);
Sanjay Patel98a71502016-02-29 23:16:48 +00001131 return IC.replaceInstUsesWith(II, NewMaskedLoad);
1132}
1133
1134// TODO: If the x86 backend knew how to convert a bool vector mask back to an
1135// XMM register mask efficiently, we could transform all x86 masked intrinsics
1136// to LLVM masked intrinsics and remove the x86 masked intrinsic defs.
Sanjay Patel1ace9932016-02-26 21:04:14 +00001137static bool simplifyX86MaskedStore(IntrinsicInst &II, InstCombiner &IC) {
1138 Value *Ptr = II.getOperand(0);
1139 Value *Mask = II.getOperand(1);
1140 Value *Vec = II.getOperand(2);
1141
1142 // Special case a zero mask since that's not a ConstantDataVector:
1143 // this masked store instruction does nothing.
1144 if (isa<ConstantAggregateZero>(Mask)) {
1145 IC.eraseInstFromFunction(II);
1146 return true;
1147 }
1148
Sanjay Patelc4acbae2016-03-12 15:16:59 +00001149 // The SSE2 version is too weird (eg, unaligned but non-temporal) to do
1150 // anything else at this level.
1151 if (II.getIntrinsicID() == Intrinsic::x86_sse2_maskmov_dqu)
1152 return false;
1153
Sanjay Patel1ace9932016-02-26 21:04:14 +00001154 auto *ConstMask = dyn_cast<ConstantDataVector>(Mask);
1155 if (!ConstMask)
1156 return false;
1157
1158 // The mask is constant. Convert this x86 intrinsic to the LLVM instrinsic
1159 // to allow target-independent optimizations.
1160
1161 // First, cast the x86 intrinsic scalar pointer to a vector pointer to match
1162 // the LLVM intrinsic definition for the pointer argument.
1163 unsigned AddrSpace = cast<PointerType>(Ptr->getType())->getAddressSpace();
1164 PointerType *VecPtrTy = PointerType::get(Vec->getType(), AddrSpace);
Sanjay Patel1ace9932016-02-26 21:04:14 +00001165 Value *PtrCast = IC.Builder->CreateBitCast(Ptr, VecPtrTy, "castvec");
1166
1167 // Second, convert the x86 XMM integer vector mask to a vector of bools based
1168 // on each element's most significant bit (the sign bit).
1169 Constant *BoolMask = getNegativeIsTrueBoolVec(ConstMask);
1170
1171 IC.Builder->CreateMaskedStore(Vec, PtrCast, 1, BoolMask);
1172
1173 // 'Replace uses' doesn't work for stores. Erase the original masked store.
1174 IC.eraseInstFromFunction(II);
1175 return true;
1176}
1177
Arnaud A. de Grandmaison333ef382016-05-10 09:24:49 +00001178// Returns true iff the 2 intrinsics have the same operands, limiting the
1179// comparison to the first NumOperands.
1180static bool haveSameOperands(const IntrinsicInst &I, const IntrinsicInst &E,
1181 unsigned NumOperands) {
1182 assert(I.getNumArgOperands() >= NumOperands && "Not enough operands");
1183 assert(E.getNumArgOperands() >= NumOperands && "Not enough operands");
1184 for (unsigned i = 0; i < NumOperands; i++)
1185 if (I.getArgOperand(i) != E.getArgOperand(i))
1186 return false;
1187 return true;
1188}
1189
1190// Remove trivially empty start/end intrinsic ranges, i.e. a start
1191// immediately followed by an end (ignoring debuginfo or other
1192// start/end intrinsics in between). As this handles only the most trivial
1193// cases, tracking the nesting level is not needed:
1194//
1195// call @llvm.foo.start(i1 0) ; &I
1196// call @llvm.foo.start(i1 0)
1197// call @llvm.foo.end(i1 0) ; This one will not be skipped: it will be removed
1198// call @llvm.foo.end(i1 0)
1199static bool removeTriviallyEmptyRange(IntrinsicInst &I, unsigned StartID,
1200 unsigned EndID, InstCombiner &IC) {
1201 assert(I.getIntrinsicID() == StartID &&
1202 "Start intrinsic does not have expected ID");
1203 BasicBlock::iterator BI(I), BE(I.getParent()->end());
1204 for (++BI; BI != BE; ++BI) {
1205 if (auto *E = dyn_cast<IntrinsicInst>(BI)) {
1206 if (isa<DbgInfoIntrinsic>(E) || E->getIntrinsicID() == StartID)
1207 continue;
1208 if (E->getIntrinsicID() == EndID &&
1209 haveSameOperands(I, *E, E->getNumArgOperands())) {
1210 IC.eraseInstFromFunction(*E);
1211 IC.eraseInstFromFunction(I);
1212 return true;
1213 }
1214 }
1215 break;
1216 }
1217
1218 return false;
1219}
1220
1221Instruction *InstCombiner::visitVAStartInst(VAStartInst &I) {
1222 removeTriviallyEmptyRange(I, Intrinsic::vastart, Intrinsic::vaend, *this);
1223 return nullptr;
1224}
1225
1226Instruction *InstCombiner::visitVACopyInst(VACopyInst &I) {
1227 removeTriviallyEmptyRange(I, Intrinsic::vacopy, Intrinsic::vaend, *this);
1228 return nullptr;
1229}
1230
Sanjay Patelcd4377c2016-01-20 22:24:38 +00001231/// CallInst simplification. This mostly only handles folding of intrinsic
1232/// instructions. For normal calls, it allows visitCallSite to do the heavy
1233/// lifting.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001234Instruction *InstCombiner::visitCallInst(CallInst &CI) {
David Majnemer15032582015-05-22 03:56:46 +00001235 auto Args = CI.arg_operands();
1236 if (Value *V = SimplifyCall(CI.getCalledValue(), Args.begin(), Args.end(), DL,
1237 TLI, DT, AC))
Sanjay Patel4b198802016-02-01 22:23:39 +00001238 return replaceInstUsesWith(CI, V);
David Majnemer15032582015-05-22 03:56:46 +00001239
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00001240 if (isFreeCall(&CI, TLI))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001241 return visitFree(CI);
1242
1243 // If the caller function is nounwind, mark the call as nounwind, even if the
1244 // callee isn't.
1245 if (CI.getParent()->getParent()->doesNotThrow() &&
1246 !CI.doesNotThrow()) {
1247 CI.setDoesNotThrow();
1248 return &CI;
1249 }
Jim Grosbach7815f562012-02-03 00:07:04 +00001250
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001251 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
1252 if (!II) return visitCallSite(&CI);
Gabor Greif589a0b92010-06-24 12:58:35 +00001253
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001254 // Intrinsics cannot occur in an invoke, so handle them here instead of in
1255 // visitCallSite.
1256 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
1257 bool Changed = false;
1258
1259 // memmove/cpy/set of zero bytes is a noop.
1260 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
Chris Lattnerc663a672010-10-01 05:51:02 +00001261 if (NumBytes->isNullValue())
Sanjay Patel4b198802016-02-01 22:23:39 +00001262 return eraseInstFromFunction(CI);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001263
1264 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
1265 if (CI->getZExtValue() == 1) {
1266 // Replace the instruction with just byte operations. We would
1267 // transform other cases to loads/stores, but we don't know if
1268 // alignment is sufficient.
1269 }
1270 }
Jim Grosbach7815f562012-02-03 00:07:04 +00001271
Chris Lattnerc663a672010-10-01 05:51:02 +00001272 // No other transformations apply to volatile transfers.
1273 if (MI->isVolatile())
Craig Topperf40110f2014-04-25 05:29:35 +00001274 return nullptr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001275
1276 // If we have a memmove and the source operation is a constant global,
1277 // then the source and dest pointers can't alias, so we can change this
1278 // into a call to memcpy.
1279 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
1280 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
1281 if (GVSrc->isConstant()) {
Sanjay Patelaf674fb2015-12-14 17:24:23 +00001282 Module *M = CI.getModule();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001283 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
Jay Foadb804a2b2011-07-12 14:06:48 +00001284 Type *Tys[3] = { CI.getArgOperand(0)->getType(),
1285 CI.getArgOperand(1)->getType(),
1286 CI.getArgOperand(2)->getType() };
Benjamin Kramere6e19332011-07-14 17:45:39 +00001287 CI.setCalledFunction(Intrinsic::getDeclaration(M, MemCpyID, Tys));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001288 Changed = true;
1289 }
1290 }
1291
1292 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) {
1293 // memmove(x,x,size) -> noop.
1294 if (MTI->getSource() == MTI->getDest())
Sanjay Patel4b198802016-02-01 22:23:39 +00001295 return eraseInstFromFunction(CI);
Eric Christopher7258dcd2010-04-16 23:37:20 +00001296 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001297
Eric Christopher7258dcd2010-04-16 23:37:20 +00001298 // If we can determine a pointer alignment that is bigger than currently
1299 // set, update the alignment.
Pete Cooper67cf9a72015-11-19 05:56:52 +00001300 if (isa<MemTransferInst>(MI)) {
1301 if (Instruction *I = SimplifyMemTransfer(MI))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001302 return I;
1303 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
1304 if (Instruction *I = SimplifyMemSet(MSI))
1305 return I;
1306 }
Gabor Greif590d95e2010-06-24 13:42:49 +00001307
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001308 if (Changed) return II;
1309 }
Jim Grosbach7815f562012-02-03 00:07:04 +00001310
Sanjay Patel1c600c62016-01-20 16:41:43 +00001311 auto SimplifyDemandedVectorEltsLow = [this](Value *Op, unsigned Width,
1312 unsigned DemandedWidth) {
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001313 APInt UndefElts(Width, 0);
1314 APInt DemandedElts = APInt::getLowBitsSet(Width, DemandedWidth);
1315 return SimplifyDemandedVectorElts(Op, DemandedElts, UndefElts);
1316 };
Simon Pilgrim424da162016-04-24 18:12:42 +00001317 auto SimplifyDemandedVectorEltsHigh = [this](Value *Op, unsigned Width,
1318 unsigned DemandedWidth) {
1319 APInt UndefElts(Width, 0);
1320 APInt DemandedElts = APInt::getHighBitsSet(Width, DemandedWidth);
1321 return SimplifyDemandedVectorElts(Op, DemandedElts, UndefElts);
1322 };
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001323
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001324 switch (II->getIntrinsicID()) {
1325 default: break;
Eric Christopher7b7028f2010-02-09 21:24:27 +00001326 case Intrinsic::objectsize: {
Nuno Lopes55fff832012-06-21 15:45:28 +00001327 uint64_t Size;
George Burgess IV278199f2016-04-12 01:05:35 +00001328 if (getObjectSize(II->getArgOperand(0), Size, DL, TLI)) {
1329 APInt APSize(II->getType()->getIntegerBitWidth(), Size);
1330 // Equality check to be sure that `Size` can fit in a value of type
1331 // `II->getType()`
1332 if (APSize == Size)
1333 return replaceInstUsesWith(CI, ConstantInt::get(II->getType(), APSize));
1334 }
Craig Topperf40110f2014-04-25 05:29:35 +00001335 return nullptr;
Eric Christopher7b7028f2010-02-09 21:24:27 +00001336 }
Michael Ilseman536cc322012-12-13 03:13:36 +00001337 case Intrinsic::bswap: {
1338 Value *IIOperand = II->getArgOperand(0);
Craig Topperf40110f2014-04-25 05:29:35 +00001339 Value *X = nullptr;
Michael Ilseman536cc322012-12-13 03:13:36 +00001340
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001341 // bswap(bswap(x)) -> x
Michael Ilseman536cc322012-12-13 03:13:36 +00001342 if (match(IIOperand, m_BSwap(m_Value(X))))
Sanjay Patel4b198802016-02-01 22:23:39 +00001343 return replaceInstUsesWith(CI, X);
Jim Grosbach7815f562012-02-03 00:07:04 +00001344
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001345 // bswap(trunc(bswap(x))) -> trunc(lshr(x, c))
Michael Ilseman536cc322012-12-13 03:13:36 +00001346 if (match(IIOperand, m_Trunc(m_BSwap(m_Value(X))))) {
1347 unsigned C = X->getType()->getPrimitiveSizeInBits() -
1348 IIOperand->getType()->getPrimitiveSizeInBits();
1349 Value *CV = ConstantInt::get(X->getType(), C);
1350 Value *V = Builder->CreateLShr(X, CV);
1351 return new TruncInst(V, IIOperand->getType());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001352 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001353 break;
Michael Ilseman536cc322012-12-13 03:13:36 +00001354 }
1355
James Molloy2d09c002015-11-12 12:39:41 +00001356 case Intrinsic::bitreverse: {
1357 Value *IIOperand = II->getArgOperand(0);
1358 Value *X = nullptr;
1359
1360 // bitreverse(bitreverse(x)) -> x
1361 if (match(IIOperand, m_Intrinsic<Intrinsic::bitreverse>(m_Value(X))))
Sanjay Patel4b198802016-02-01 22:23:39 +00001362 return replaceInstUsesWith(CI, X);
James Molloy2d09c002015-11-12 12:39:41 +00001363 break;
1364 }
1365
Sanjay Patelb695c552016-02-01 17:00:10 +00001366 case Intrinsic::masked_load:
1367 if (Value *SimplifiedMaskedOp = simplifyMaskedLoad(*II, *Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00001368 return replaceInstUsesWith(CI, SimplifiedMaskedOp);
Sanjay Patelb695c552016-02-01 17:00:10 +00001369 break;
Sanjay Patel04f792b2016-02-01 19:39:52 +00001370 case Intrinsic::masked_store:
1371 return simplifyMaskedStore(*II, *this);
Sanjay Patel103ab7d2016-02-01 22:10:26 +00001372 case Intrinsic::masked_gather:
1373 return simplifyMaskedGather(*II, *this);
1374 case Intrinsic::masked_scatter:
1375 return simplifyMaskedScatter(*II, *this);
Sanjay Patelb695c552016-02-01 17:00:10 +00001376
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001377 case Intrinsic::powi:
Gabor Greif589a0b92010-06-24 12:58:35 +00001378 if (ConstantInt *Power = dyn_cast<ConstantInt>(II->getArgOperand(1))) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001379 // powi(x, 0) -> 1.0
1380 if (Power->isZero())
Sanjay Patel4b198802016-02-01 22:23:39 +00001381 return replaceInstUsesWith(CI, ConstantFP::get(CI.getType(), 1.0));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001382 // powi(x, 1) -> x
1383 if (Power->isOne())
Sanjay Patel4b198802016-02-01 22:23:39 +00001384 return replaceInstUsesWith(CI, II->getArgOperand(0));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001385 // powi(x, -1) -> 1/x
1386 if (Power->isAllOnesValue())
1387 return BinaryOperator::CreateFDiv(ConstantFP::get(CI.getType(), 1.0),
Gabor Greif589a0b92010-06-24 12:58:35 +00001388 II->getArgOperand(0));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001389 }
1390 break;
1391 case Intrinsic::cttz: {
1392 // If all bits below the first known one are known zero,
1393 // this value is constant.
Chris Lattner229907c2011-07-18 04:54:35 +00001394 IntegerType *IT = dyn_cast<IntegerType>(II->getArgOperand(0)->getType());
Owen Anderson2f37bdc2011-07-01 21:52:38 +00001395 // FIXME: Try to simplify vectors of integers.
1396 if (!IT) break;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001397 uint32_t BitWidth = IT->getBitWidth();
1398 APInt KnownZero(BitWidth, 0);
1399 APInt KnownOne(BitWidth, 0);
Hal Finkel60db0582014-09-07 18:57:58 +00001400 computeKnownBits(II->getArgOperand(0), KnownZero, KnownOne, 0, II);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001401 unsigned TrailingZeros = KnownOne.countTrailingZeros();
1402 APInt Mask(APInt::getLowBitsSet(BitWidth, TrailingZeros));
1403 if ((Mask & KnownZero) == Mask)
Sanjay Patel4b198802016-02-01 22:23:39 +00001404 return replaceInstUsesWith(CI, ConstantInt::get(IT,
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001405 APInt(BitWidth, TrailingZeros)));
Jim Grosbach7815f562012-02-03 00:07:04 +00001406
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001407 }
1408 break;
1409 case Intrinsic::ctlz: {
1410 // If all bits above the first known one are known zero,
1411 // this value is constant.
Chris Lattner229907c2011-07-18 04:54:35 +00001412 IntegerType *IT = dyn_cast<IntegerType>(II->getArgOperand(0)->getType());
Owen Anderson2f37bdc2011-07-01 21:52:38 +00001413 // FIXME: Try to simplify vectors of integers.
1414 if (!IT) break;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001415 uint32_t BitWidth = IT->getBitWidth();
1416 APInt KnownZero(BitWidth, 0);
1417 APInt KnownOne(BitWidth, 0);
Hal Finkel60db0582014-09-07 18:57:58 +00001418 computeKnownBits(II->getArgOperand(0), KnownZero, KnownOne, 0, II);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001419 unsigned LeadingZeros = KnownOne.countLeadingZeros();
1420 APInt Mask(APInt::getHighBitsSet(BitWidth, LeadingZeros));
1421 if ((Mask & KnownZero) == Mask)
Sanjay Patel4b198802016-02-01 22:23:39 +00001422 return replaceInstUsesWith(CI, ConstantInt::get(IT,
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001423 APInt(BitWidth, LeadingZeros)));
Jim Grosbach7815f562012-02-03 00:07:04 +00001424
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001425 }
1426 break;
Sanjoy Dasb0984472015-04-08 04:27:22 +00001427
Nick Lewyckyabe2cc12015-04-13 19:17:37 +00001428 case Intrinsic::uadd_with_overflow:
1429 case Intrinsic::sadd_with_overflow:
1430 case Intrinsic::umul_with_overflow:
1431 case Intrinsic::smul_with_overflow:
Gabor Greif5b1370e2010-06-28 16:50:57 +00001432 if (isa<Constant>(II->getArgOperand(0)) &&
1433 !isa<Constant>(II->getArgOperand(1))) {
Sanjoy Dasb0984472015-04-08 04:27:22 +00001434 // Canonicalize constants into the RHS.
Gabor Greif5b1370e2010-06-28 16:50:57 +00001435 Value *LHS = II->getArgOperand(0);
1436 II->setArgOperand(0, II->getArgOperand(1));
1437 II->setArgOperand(1, LHS);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001438 return II;
1439 }
Nick Lewyckyd6f241d2015-04-13 20:03:08 +00001440 // fall through
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001441
Nick Lewyckyabe2cc12015-04-13 19:17:37 +00001442 case Intrinsic::usub_with_overflow:
1443 case Intrinsic::ssub_with_overflow: {
Sanjoy Dasb0984472015-04-08 04:27:22 +00001444 OverflowCheckFlavor OCF =
1445 IntrinsicIDToOverflowCheckFlavor(II->getIntrinsicID());
1446 assert(OCF != OCF_INVALID && "unexpected!");
Jim Grosbach7815f562012-02-03 00:07:04 +00001447
Sanjoy Dasb0984472015-04-08 04:27:22 +00001448 Value *OperationResult = nullptr;
1449 Constant *OverflowResult = nullptr;
1450 if (OptimizeOverflowCheck(OCF, II->getArgOperand(0), II->getArgOperand(1),
1451 *II, OperationResult, OverflowResult))
1452 return CreateOverflowTuple(II, OperationResult, OverflowResult);
Benjamin Kramera420df22014-07-04 10:22:21 +00001453
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001454 break;
Erik Eckstein096ff7d2014-12-11 08:02:30 +00001455 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001456
Matt Arsenaultd6511b42014-10-21 23:00:20 +00001457 case Intrinsic::minnum:
1458 case Intrinsic::maxnum: {
1459 Value *Arg0 = II->getArgOperand(0);
1460 Value *Arg1 = II->getArgOperand(1);
Sanjay Patel0069f562016-01-31 16:35:23 +00001461 // Canonicalize constants to the RHS.
1462 if (isa<ConstantFP>(Arg0) && !isa<ConstantFP>(Arg1)) {
Matt Arsenaultd6511b42014-10-21 23:00:20 +00001463 II->setArgOperand(0, Arg1);
1464 II->setArgOperand(1, Arg0);
1465 return II;
1466 }
Sanjay Patel0069f562016-01-31 16:35:23 +00001467 if (Value *V = simplifyMinnumMaxnum(*II))
Sanjay Patel4b198802016-02-01 22:23:39 +00001468 return replaceInstUsesWith(*II, V);
Matt Arsenaultd6511b42014-10-21 23:00:20 +00001469 break;
1470 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001471 case Intrinsic::ppc_altivec_lvx:
1472 case Intrinsic::ppc_altivec_lvxl:
Bill Wendlingb902f1d2011-04-13 00:36:11 +00001473 // Turn PPC lvx -> load if the pointer is known aligned.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001474 if (getOrEnforceKnownAlignment(II->getArgOperand(0), 16, DL, II, AC, DT) >=
Chandler Carruth66b31302015-01-04 12:03:27 +00001475 16) {
Gabor Greif589a0b92010-06-24 12:58:35 +00001476 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(0),
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001477 PointerType::getUnqual(II->getType()));
1478 return new LoadInst(Ptr);
1479 }
1480 break;
Bill Schmidt72954782014-11-12 04:19:40 +00001481 case Intrinsic::ppc_vsx_lxvw4x:
1482 case Intrinsic::ppc_vsx_lxvd2x: {
1483 // Turn PPC VSX loads into normal loads.
1484 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(0),
1485 PointerType::getUnqual(II->getType()));
1486 return new LoadInst(Ptr, Twine(""), false, 1);
1487 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001488 case Intrinsic::ppc_altivec_stvx:
1489 case Intrinsic::ppc_altivec_stvxl:
1490 // Turn stvx -> store if the pointer is known aligned.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001491 if (getOrEnforceKnownAlignment(II->getArgOperand(1), 16, DL, II, AC, DT) >=
Chandler Carruth66b31302015-01-04 12:03:27 +00001492 16) {
Jim Grosbach7815f562012-02-03 00:07:04 +00001493 Type *OpPtrTy =
Gabor Greifa6d75e22010-06-24 15:51:11 +00001494 PointerType::getUnqual(II->getArgOperand(0)->getType());
1495 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(1), OpPtrTy);
1496 return new StoreInst(II->getArgOperand(0), Ptr);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001497 }
1498 break;
Bill Schmidt72954782014-11-12 04:19:40 +00001499 case Intrinsic::ppc_vsx_stxvw4x:
1500 case Intrinsic::ppc_vsx_stxvd2x: {
1501 // Turn PPC VSX stores into normal stores.
1502 Type *OpPtrTy = PointerType::getUnqual(II->getArgOperand(0)->getType());
1503 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(1), OpPtrTy);
1504 return new StoreInst(II->getArgOperand(0), Ptr, false, 1);
1505 }
Hal Finkel221f4672015-02-26 18:56:03 +00001506 case Intrinsic::ppc_qpx_qvlfs:
1507 // Turn PPC QPX qvlfs -> load if the pointer is known aligned.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001508 if (getOrEnforceKnownAlignment(II->getArgOperand(0), 16, DL, II, AC, DT) >=
Hal Finkel221f4672015-02-26 18:56:03 +00001509 16) {
Hal Finkelf0d68d72015-05-11 06:37:03 +00001510 Type *VTy = VectorType::get(Builder->getFloatTy(),
1511 II->getType()->getVectorNumElements());
Hal Finkel221f4672015-02-26 18:56:03 +00001512 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(0),
Hal Finkelf0d68d72015-05-11 06:37:03 +00001513 PointerType::getUnqual(VTy));
1514 Value *Load = Builder->CreateLoad(Ptr);
1515 return new FPExtInst(Load, II->getType());
Hal Finkel221f4672015-02-26 18:56:03 +00001516 }
1517 break;
1518 case Intrinsic::ppc_qpx_qvlfd:
1519 // Turn PPC QPX qvlfd -> load if the pointer is known aligned.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001520 if (getOrEnforceKnownAlignment(II->getArgOperand(0), 32, DL, II, AC, DT) >=
Hal Finkel221f4672015-02-26 18:56:03 +00001521 32) {
1522 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(0),
1523 PointerType::getUnqual(II->getType()));
1524 return new LoadInst(Ptr);
1525 }
1526 break;
1527 case Intrinsic::ppc_qpx_qvstfs:
1528 // Turn PPC QPX qvstfs -> store if the pointer is known aligned.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001529 if (getOrEnforceKnownAlignment(II->getArgOperand(1), 16, DL, II, AC, DT) >=
Hal Finkel221f4672015-02-26 18:56:03 +00001530 16) {
Hal Finkelf0d68d72015-05-11 06:37:03 +00001531 Type *VTy = VectorType::get(Builder->getFloatTy(),
1532 II->getArgOperand(0)->getType()->getVectorNumElements());
1533 Value *TOp = Builder->CreateFPTrunc(II->getArgOperand(0), VTy);
1534 Type *OpPtrTy = PointerType::getUnqual(VTy);
Hal Finkel221f4672015-02-26 18:56:03 +00001535 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(1), OpPtrTy);
Hal Finkelf0d68d72015-05-11 06:37:03 +00001536 return new StoreInst(TOp, Ptr);
Hal Finkel221f4672015-02-26 18:56:03 +00001537 }
1538 break;
1539 case Intrinsic::ppc_qpx_qvstfd:
1540 // Turn PPC QPX qvstfd -> store if the pointer is known aligned.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001541 if (getOrEnforceKnownAlignment(II->getArgOperand(1), 32, DL, II, AC, DT) >=
Hal Finkel221f4672015-02-26 18:56:03 +00001542 32) {
1543 Type *OpPtrTy =
1544 PointerType::getUnqual(II->getArgOperand(0)->getType());
1545 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(1), OpPtrTy);
1546 return new StoreInst(II->getArgOperand(0), Ptr);
1547 }
1548 break;
Simon Pilgrim20c607b2015-09-12 13:39:53 +00001549
Simon Pilgrim20c607b2015-09-12 13:39:53 +00001550 case Intrinsic::x86_vcvtph2ps_128:
1551 case Intrinsic::x86_vcvtph2ps_256: {
1552 auto Arg = II->getArgOperand(0);
1553 auto ArgType = cast<VectorType>(Arg->getType());
1554 auto RetType = cast<VectorType>(II->getType());
1555 unsigned ArgWidth = ArgType->getNumElements();
1556 unsigned RetWidth = RetType->getNumElements();
1557 assert(RetWidth <= ArgWidth && "Unexpected input/return vector widths");
1558 assert(ArgType->isIntOrIntVectorTy() &&
1559 ArgType->getScalarSizeInBits() == 16 &&
1560 "CVTPH2PS input type should be 16-bit integer vector");
1561 assert(RetType->getScalarType()->isFloatTy() &&
1562 "CVTPH2PS output type should be 32-bit float vector");
1563
1564 // Constant folding: Convert to generic half to single conversion.
Simon Pilgrim48ffca02015-09-12 14:00:17 +00001565 if (isa<ConstantAggregateZero>(Arg))
Sanjay Patel4b198802016-02-01 22:23:39 +00001566 return replaceInstUsesWith(*II, ConstantAggregateZero::get(RetType));
Simon Pilgrim20c607b2015-09-12 13:39:53 +00001567
Simon Pilgrim48ffca02015-09-12 14:00:17 +00001568 if (isa<ConstantDataVector>(Arg)) {
Simon Pilgrim20c607b2015-09-12 13:39:53 +00001569 auto VectorHalfAsShorts = Arg;
1570 if (RetWidth < ArgWidth) {
1571 SmallVector<int, 8> SubVecMask;
1572 for (unsigned i = 0; i != RetWidth; ++i)
1573 SubVecMask.push_back((int)i);
1574 VectorHalfAsShorts = Builder->CreateShuffleVector(
1575 Arg, UndefValue::get(ArgType), SubVecMask);
1576 }
1577
1578 auto VectorHalfType =
1579 VectorType::get(Type::getHalfTy(II->getContext()), RetWidth);
1580 auto VectorHalfs =
1581 Builder->CreateBitCast(VectorHalfAsShorts, VectorHalfType);
1582 auto VectorFloats = Builder->CreateFPExt(VectorHalfs, RetType);
Sanjay Patel4b198802016-02-01 22:23:39 +00001583 return replaceInstUsesWith(*II, VectorFloats);
Simon Pilgrim20c607b2015-09-12 13:39:53 +00001584 }
1585
1586 // We only use the lowest lanes of the argument.
Simon Pilgrim996725e2015-09-19 11:41:53 +00001587 if (Value *V = SimplifyDemandedVectorEltsLow(Arg, ArgWidth, RetWidth)) {
Simon Pilgrim20c607b2015-09-12 13:39:53 +00001588 II->setArgOperand(0, V);
1589 return II;
1590 }
1591 break;
1592 }
1593
Chandler Carruthcf414cf2011-01-10 07:19:37 +00001594 case Intrinsic::x86_sse_cvtss2si:
1595 case Intrinsic::x86_sse_cvtss2si64:
1596 case Intrinsic::x86_sse_cvttss2si:
1597 case Intrinsic::x86_sse_cvttss2si64:
1598 case Intrinsic::x86_sse2_cvtsd2si:
1599 case Intrinsic::x86_sse2_cvtsd2si64:
1600 case Intrinsic::x86_sse2_cvttsd2si:
1601 case Intrinsic::x86_sse2_cvttsd2si64: {
1602 // These intrinsics only demand the 0th element of their input vectors. If
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001603 // we can simplify the input based on that, do so now.
Simon Pilgrim996725e2015-09-19 11:41:53 +00001604 Value *Arg = II->getArgOperand(0);
1605 unsigned VWidth = Arg->getType()->getVectorNumElements();
1606 if (Value *V = SimplifyDemandedVectorEltsLow(Arg, VWidth, 1)) {
Gabor Greif5b1370e2010-06-28 16:50:57 +00001607 II->setArgOperand(0, V);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001608 return II;
1609 }
Simon Pilgrim18617d12015-08-05 08:18:00 +00001610 break;
1611 }
1612
Simon Pilgrim91e3ac82016-06-07 08:18:35 +00001613 case Intrinsic::x86_mmx_pmovmskb:
1614 case Intrinsic::x86_sse_movmsk_ps:
1615 case Intrinsic::x86_sse2_movmsk_pd:
1616 case Intrinsic::x86_sse2_pmovmskb_128:
1617 case Intrinsic::x86_avx_movmsk_pd_256:
1618 case Intrinsic::x86_avx_movmsk_ps_256:
1619 case Intrinsic::x86_avx2_pmovmskb: {
1620 if (Value *V = simplifyX86movmsk(*II, *Builder))
1621 return replaceInstUsesWith(*II, V);
1622 break;
1623 }
1624
Simon Pilgrim471efd22016-02-20 23:17:35 +00001625 case Intrinsic::x86_sse_comieq_ss:
1626 case Intrinsic::x86_sse_comige_ss:
1627 case Intrinsic::x86_sse_comigt_ss:
1628 case Intrinsic::x86_sse_comile_ss:
1629 case Intrinsic::x86_sse_comilt_ss:
1630 case Intrinsic::x86_sse_comineq_ss:
1631 case Intrinsic::x86_sse_ucomieq_ss:
1632 case Intrinsic::x86_sse_ucomige_ss:
1633 case Intrinsic::x86_sse_ucomigt_ss:
1634 case Intrinsic::x86_sse_ucomile_ss:
1635 case Intrinsic::x86_sse_ucomilt_ss:
1636 case Intrinsic::x86_sse_ucomineq_ss:
1637 case Intrinsic::x86_sse2_comieq_sd:
1638 case Intrinsic::x86_sse2_comige_sd:
1639 case Intrinsic::x86_sse2_comigt_sd:
1640 case Intrinsic::x86_sse2_comile_sd:
1641 case Intrinsic::x86_sse2_comilt_sd:
1642 case Intrinsic::x86_sse2_comineq_sd:
1643 case Intrinsic::x86_sse2_ucomieq_sd:
1644 case Intrinsic::x86_sse2_ucomige_sd:
1645 case Intrinsic::x86_sse2_ucomigt_sd:
1646 case Intrinsic::x86_sse2_ucomile_sd:
1647 case Intrinsic::x86_sse2_ucomilt_sd:
1648 case Intrinsic::x86_sse2_ucomineq_sd: {
1649 // These intrinsics only demand the 0th element of their input vectors. If
1650 // we can simplify the input based on that, do so now.
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00001651 bool MadeChange = false;
Simon Pilgrim471efd22016-02-20 23:17:35 +00001652 Value *Arg0 = II->getArgOperand(0);
1653 Value *Arg1 = II->getArgOperand(1);
1654 unsigned VWidth = Arg0->getType()->getVectorNumElements();
1655 if (Value *V = SimplifyDemandedVectorEltsLow(Arg0, VWidth, 1)) {
1656 II->setArgOperand(0, V);
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00001657 MadeChange = true;
Simon Pilgrim471efd22016-02-20 23:17:35 +00001658 }
1659 if (Value *V = SimplifyDemandedVectorEltsLow(Arg1, VWidth, 1)) {
1660 II->setArgOperand(1, V);
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00001661 MadeChange = true;
Simon Pilgrim471efd22016-02-20 23:17:35 +00001662 }
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00001663 if (MadeChange)
1664 return II;
Simon Pilgrim471efd22016-02-20 23:17:35 +00001665 break;
1666 }
1667
Simon Pilgrim424da162016-04-24 18:12:42 +00001668 case Intrinsic::x86_sse_add_ss:
1669 case Intrinsic::x86_sse_sub_ss:
1670 case Intrinsic::x86_sse_mul_ss:
1671 case Intrinsic::x86_sse_div_ss:
1672 case Intrinsic::x86_sse_min_ss:
1673 case Intrinsic::x86_sse_max_ss:
1674 case Intrinsic::x86_sse_cmp_ss:
1675 case Intrinsic::x86_sse2_add_sd:
1676 case Intrinsic::x86_sse2_sub_sd:
1677 case Intrinsic::x86_sse2_mul_sd:
1678 case Intrinsic::x86_sse2_div_sd:
1679 case Intrinsic::x86_sse2_min_sd:
1680 case Intrinsic::x86_sse2_max_sd:
1681 case Intrinsic::x86_sse2_cmp_sd: {
1682 // These intrinsics only demand the lowest element of the second input
1683 // vector.
1684 Value *Arg1 = II->getArgOperand(1);
1685 unsigned VWidth = Arg1->getType()->getVectorNumElements();
1686 if (Value *V = SimplifyDemandedVectorEltsLow(Arg1, VWidth, 1)) {
1687 II->setArgOperand(1, V);
1688 return II;
1689 }
1690 break;
1691 }
1692
1693 case Intrinsic::x86_sse41_round_ss:
1694 case Intrinsic::x86_sse41_round_sd: {
1695 // These intrinsics demand the upper elements of the first input vector and
1696 // the lowest element of the second input vector.
1697 bool MadeChange = false;
1698 Value *Arg0 = II->getArgOperand(0);
1699 Value *Arg1 = II->getArgOperand(1);
1700 unsigned VWidth = Arg0->getType()->getVectorNumElements();
1701 if (Value *V = SimplifyDemandedVectorEltsHigh(Arg0, VWidth, VWidth - 1)) {
1702 II->setArgOperand(0, V);
1703 MadeChange = true;
1704 }
1705 if (Value *V = SimplifyDemandedVectorEltsLow(Arg1, VWidth, 1)) {
1706 II->setArgOperand(1, V);
1707 MadeChange = true;
1708 }
1709 if (MadeChange)
1710 return II;
1711 break;
1712 }
1713
Simon Pilgrima3a72b42015-08-10 20:21:15 +00001714 // Constant fold ashr( <A x Bi>, Ci ).
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00001715 // Constant fold lshr( <A x Bi>, Ci ).
1716 // Constant fold shl( <A x Bi>, Ci ).
Simon Pilgrima3a72b42015-08-10 20:21:15 +00001717 case Intrinsic::x86_sse2_psrai_d:
1718 case Intrinsic::x86_sse2_psrai_w:
Simon Pilgrima3a72b42015-08-10 20:21:15 +00001719 case Intrinsic::x86_avx2_psrai_d:
1720 case Intrinsic::x86_avx2_psrai_w:
Simon Pilgrim18617d12015-08-05 08:18:00 +00001721 case Intrinsic::x86_sse2_psrli_d:
1722 case Intrinsic::x86_sse2_psrli_q:
1723 case Intrinsic::x86_sse2_psrli_w:
Simon Pilgrim18617d12015-08-05 08:18:00 +00001724 case Intrinsic::x86_avx2_psrli_d:
1725 case Intrinsic::x86_avx2_psrli_q:
1726 case Intrinsic::x86_avx2_psrli_w:
Michael J. Spencerdee4b2c2014-04-24 00:58:18 +00001727 case Intrinsic::x86_sse2_pslli_d:
1728 case Intrinsic::x86_sse2_pslli_q:
1729 case Intrinsic::x86_sse2_pslli_w:
Simon Pilgrim18617d12015-08-05 08:18:00 +00001730 case Intrinsic::x86_avx2_pslli_d:
1731 case Intrinsic::x86_avx2_pslli_q:
1732 case Intrinsic::x86_avx2_pslli_w:
Sanjay Patel6038d3e2016-01-29 23:27:03 +00001733 if (Value *V = simplifyX86immShift(*II, *Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00001734 return replaceInstUsesWith(*II, V);
Simon Pilgrim18617d12015-08-05 08:18:00 +00001735 break;
1736
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00001737 case Intrinsic::x86_sse2_psra_d:
1738 case Intrinsic::x86_sse2_psra_w:
1739 case Intrinsic::x86_avx2_psra_d:
1740 case Intrinsic::x86_avx2_psra_w:
1741 case Intrinsic::x86_sse2_psrl_d:
1742 case Intrinsic::x86_sse2_psrl_q:
1743 case Intrinsic::x86_sse2_psrl_w:
1744 case Intrinsic::x86_avx2_psrl_d:
1745 case Intrinsic::x86_avx2_psrl_q:
1746 case Intrinsic::x86_avx2_psrl_w:
1747 case Intrinsic::x86_sse2_psll_d:
1748 case Intrinsic::x86_sse2_psll_q:
1749 case Intrinsic::x86_sse2_psll_w:
1750 case Intrinsic::x86_avx2_psll_d:
1751 case Intrinsic::x86_avx2_psll_q:
1752 case Intrinsic::x86_avx2_psll_w: {
Sanjay Patel6038d3e2016-01-29 23:27:03 +00001753 if (Value *V = simplifyX86immShift(*II, *Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00001754 return replaceInstUsesWith(*II, V);
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00001755
1756 // SSE2/AVX2 uses only the first 64-bits of the 128-bit vector
1757 // operand to compute the shift amount.
Simon Pilgrim996725e2015-09-19 11:41:53 +00001758 Value *Arg1 = II->getArgOperand(1);
1759 assert(Arg1->getType()->getPrimitiveSizeInBits() == 128 &&
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00001760 "Unexpected packed shift size");
Simon Pilgrim996725e2015-09-19 11:41:53 +00001761 unsigned VWidth = Arg1->getType()->getVectorNumElements();
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00001762
Simon Pilgrim996725e2015-09-19 11:41:53 +00001763 if (Value *V = SimplifyDemandedVectorEltsLow(Arg1, VWidth, VWidth / 2)) {
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00001764 II->setArgOperand(1, V);
1765 return II;
1766 }
1767 break;
1768 }
1769
Simon Pilgrimdb9893f2016-06-07 10:27:15 +00001770 case Intrinsic::x86_avx2_psllv_d:
1771 case Intrinsic::x86_avx2_psllv_d_256:
1772 case Intrinsic::x86_avx2_psllv_q:
1773 case Intrinsic::x86_avx2_psllv_q_256:
1774 case Intrinsic::x86_avx2_psrav_d:
1775 case Intrinsic::x86_avx2_psrav_d_256:
1776 case Intrinsic::x86_avx2_psrlv_d:
1777 case Intrinsic::x86_avx2_psrlv_d_256:
1778 case Intrinsic::x86_avx2_psrlv_q:
1779 case Intrinsic::x86_avx2_psrlv_q_256:
1780 if (Value *V = simplifyX86varShift(*II, *Builder))
1781 return replaceInstUsesWith(*II, V);
1782 break;
1783
Sanjay Patelc86867c2015-04-16 17:52:13 +00001784 case Intrinsic::x86_sse41_insertps:
Sanjay Patel6038d3e2016-01-29 23:27:03 +00001785 if (Value *V = simplifyX86insertps(*II, *Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00001786 return replaceInstUsesWith(*II, V);
Sanjay Patelc86867c2015-04-16 17:52:13 +00001787 break;
Simon Pilgrim54fcd622015-07-25 20:41:00 +00001788
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001789 case Intrinsic::x86_sse4a_extrq: {
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001790 Value *Op0 = II->getArgOperand(0);
1791 Value *Op1 = II->getArgOperand(1);
1792 unsigned VWidth0 = Op0->getType()->getVectorNumElements();
1793 unsigned VWidth1 = Op1->getType()->getVectorNumElements();
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00001794 assert(Op0->getType()->getPrimitiveSizeInBits() == 128 &&
1795 Op1->getType()->getPrimitiveSizeInBits() == 128 && VWidth0 == 2 &&
1796 VWidth1 == 16 && "Unexpected operand sizes");
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001797
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00001798 // See if we're dealing with constant values.
1799 Constant *C1 = dyn_cast<Constant>(Op1);
1800 ConstantInt *CILength =
1801 C1 ? dyn_cast<ConstantInt>(C1->getAggregateElement((unsigned)0))
1802 : nullptr;
1803 ConstantInt *CIIndex =
1804 C1 ? dyn_cast<ConstantInt>(C1->getAggregateElement((unsigned)1))
1805 : nullptr;
1806
1807 // Attempt to simplify to a constant, shuffle vector or EXTRQI call.
Sanjay Patel6038d3e2016-01-29 23:27:03 +00001808 if (Value *V = simplifyX86extrq(*II, Op0, CILength, CIIndex, *Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00001809 return replaceInstUsesWith(*II, V);
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00001810
1811 // EXTRQ only uses the lowest 64-bits of the first 128-bit vector
1812 // operands and the lowest 16-bits of the second.
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00001813 bool MadeChange = false;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001814 if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth0, 1)) {
1815 II->setArgOperand(0, V);
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00001816 MadeChange = true;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001817 }
1818 if (Value *V = SimplifyDemandedVectorEltsLow(Op1, VWidth1, 2)) {
1819 II->setArgOperand(1, V);
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00001820 MadeChange = true;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001821 }
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00001822 if (MadeChange)
1823 return II;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001824 break;
1825 }
1826
1827 case Intrinsic::x86_sse4a_extrqi: {
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00001828 // EXTRQI: Extract Length bits starting from Index. Zero pad the remaining
1829 // bits of the lower 64-bits. The upper 64-bits are undefined.
1830 Value *Op0 = II->getArgOperand(0);
1831 unsigned VWidth = Op0->getType()->getVectorNumElements();
1832 assert(Op0->getType()->getPrimitiveSizeInBits() == 128 && VWidth == 2 &&
1833 "Unexpected operand size");
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001834
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00001835 // See if we're dealing with constant values.
1836 ConstantInt *CILength = dyn_cast<ConstantInt>(II->getArgOperand(1));
1837 ConstantInt *CIIndex = dyn_cast<ConstantInt>(II->getArgOperand(2));
1838
1839 // Attempt to simplify to a constant or shuffle vector.
Sanjay Patel6038d3e2016-01-29 23:27:03 +00001840 if (Value *V = simplifyX86extrq(*II, Op0, CILength, CIIndex, *Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00001841 return replaceInstUsesWith(*II, V);
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00001842
1843 // EXTRQI only uses the lowest 64-bits of the first 128-bit vector
1844 // operand.
1845 if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth, 1)) {
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001846 II->setArgOperand(0, V);
1847 return II;
1848 }
1849 break;
1850 }
1851
1852 case Intrinsic::x86_sse4a_insertq: {
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00001853 Value *Op0 = II->getArgOperand(0);
1854 Value *Op1 = II->getArgOperand(1);
1855 unsigned VWidth = Op0->getType()->getVectorNumElements();
1856 assert(Op0->getType()->getPrimitiveSizeInBits() == 128 &&
1857 Op1->getType()->getPrimitiveSizeInBits() == 128 && VWidth == 2 &&
1858 Op1->getType()->getVectorNumElements() == 2 &&
1859 "Unexpected operand size");
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001860
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00001861 // See if we're dealing with constant values.
1862 Constant *C1 = dyn_cast<Constant>(Op1);
1863 ConstantInt *CI11 =
1864 C1 ? dyn_cast<ConstantInt>(C1->getAggregateElement((unsigned)1))
1865 : nullptr;
1866
1867 // Attempt to simplify to a constant, shuffle vector or INSERTQI call.
1868 if (CI11) {
1869 APInt V11 = CI11->getValue();
1870 APInt Len = V11.zextOrTrunc(6);
1871 APInt Idx = V11.lshr(8).zextOrTrunc(6);
Sanjay Patel6038d3e2016-01-29 23:27:03 +00001872 if (Value *V = simplifyX86insertq(*II, Op0, Op1, Len, Idx, *Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00001873 return replaceInstUsesWith(*II, V);
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00001874 }
1875
1876 // INSERTQ only uses the lowest 64-bits of the first 128-bit vector
1877 // operand.
1878 if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth, 1)) {
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001879 II->setArgOperand(0, V);
1880 return II;
1881 }
1882 break;
1883 }
1884
Filipe Cabecinhas1a805952014-04-24 00:38:14 +00001885 case Intrinsic::x86_sse4a_insertqi: {
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00001886 // INSERTQI: Extract lowest Length bits from lower half of second source and
1887 // insert over first source starting at Index bit. The upper 64-bits are
1888 // undefined.
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001889 Value *Op0 = II->getArgOperand(0);
1890 Value *Op1 = II->getArgOperand(1);
1891 unsigned VWidth0 = Op0->getType()->getVectorNumElements();
1892 unsigned VWidth1 = Op1->getType()->getVectorNumElements();
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00001893 assert(Op0->getType()->getPrimitiveSizeInBits() == 128 &&
1894 Op1->getType()->getPrimitiveSizeInBits() == 128 && VWidth0 == 2 &&
1895 VWidth1 == 2 && "Unexpected operand sizes");
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001896
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00001897 // See if we're dealing with constant values.
1898 ConstantInt *CILength = dyn_cast<ConstantInt>(II->getArgOperand(2));
1899 ConstantInt *CIIndex = dyn_cast<ConstantInt>(II->getArgOperand(3));
1900
1901 // Attempt to simplify to a constant or shuffle vector.
1902 if (CILength && CIIndex) {
1903 APInt Len = CILength->getValue().zextOrTrunc(6);
1904 APInt Idx = CIIndex->getValue().zextOrTrunc(6);
Sanjay Patel6038d3e2016-01-29 23:27:03 +00001905 if (Value *V = simplifyX86insertq(*II, Op0, Op1, Len, Idx, *Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00001906 return replaceInstUsesWith(*II, V);
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00001907 }
1908
1909 // INSERTQI only uses the lowest 64-bits of the first two 128-bit vector
1910 // operands.
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00001911 bool MadeChange = false;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001912 if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth0, 1)) {
1913 II->setArgOperand(0, V);
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00001914 MadeChange = true;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001915 }
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001916 if (Value *V = SimplifyDemandedVectorEltsLow(Op1, VWidth1, 1)) {
1917 II->setArgOperand(1, V);
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00001918 MadeChange = true;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001919 }
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00001920 if (MadeChange)
1921 return II;
Filipe Cabecinhas1a805952014-04-24 00:38:14 +00001922 break;
1923 }
1924
Filipe Cabecinhas82ac07c2014-05-27 03:42:20 +00001925 case Intrinsic::x86_sse41_pblendvb:
1926 case Intrinsic::x86_sse41_blendvps:
1927 case Intrinsic::x86_sse41_blendvpd:
1928 case Intrinsic::x86_avx_blendv_ps_256:
1929 case Intrinsic::x86_avx_blendv_pd_256:
1930 case Intrinsic::x86_avx2_pblendvb: {
1931 // Convert blendv* to vector selects if the mask is constant.
1932 // This optimization is convoluted because the intrinsic is defined as
1933 // getting a vector of floats or doubles for the ps and pd versions.
1934 // FIXME: That should be changed.
Simon Pilgrim8c049d52015-08-12 08:08:56 +00001935
1936 Value *Op0 = II->getArgOperand(0);
1937 Value *Op1 = II->getArgOperand(1);
Filipe Cabecinhas82ac07c2014-05-27 03:42:20 +00001938 Value *Mask = II->getArgOperand(2);
Simon Pilgrim8c049d52015-08-12 08:08:56 +00001939
1940 // fold (blend A, A, Mask) -> A
1941 if (Op0 == Op1)
Sanjay Patel4b198802016-02-01 22:23:39 +00001942 return replaceInstUsesWith(CI, Op0);
Simon Pilgrim8c049d52015-08-12 08:08:56 +00001943
1944 // Zero Mask - select 1st argument.
Simon Pilgrim93f59f52015-08-12 08:23:36 +00001945 if (isa<ConstantAggregateZero>(Mask))
Sanjay Patel4b198802016-02-01 22:23:39 +00001946 return replaceInstUsesWith(CI, Op0);
Simon Pilgrim8c049d52015-08-12 08:08:56 +00001947
1948 // Constant Mask - select 1st/2nd argument lane based on top bit of mask.
Sanjay Patel368ac5d2016-02-21 17:29:33 +00001949 if (auto *ConstantMask = dyn_cast<ConstantDataVector>(Mask)) {
1950 Constant *NewSelector = getNegativeIsTrueBoolVec(ConstantMask);
Simon Pilgrim8c049d52015-08-12 08:08:56 +00001951 return SelectInst::Create(NewSelector, Op1, Op0, "blendv");
Filipe Cabecinhas82ac07c2014-05-27 03:42:20 +00001952 }
Simon Pilgrim8c049d52015-08-12 08:08:56 +00001953 break;
Filipe Cabecinhas82ac07c2014-05-27 03:42:20 +00001954 }
1955
Andrea Di Biagio0594e2a2015-09-30 16:44:39 +00001956 case Intrinsic::x86_ssse3_pshuf_b_128:
Simon Pilgrimc0c56e72016-04-24 17:00:34 +00001957 case Intrinsic::x86_avx2_pshuf_b:
1958 if (Value *V = simplifyX86pshufb(*II, *Builder))
1959 return replaceInstUsesWith(*II, V);
1960 break;
Andrea Di Biagio0594e2a2015-09-30 16:44:39 +00001961
Rafael Espindolabad3f772014-04-21 22:06:04 +00001962 case Intrinsic::x86_avx_vpermilvar_ps:
1963 case Intrinsic::x86_avx_vpermilvar_ps_256:
1964 case Intrinsic::x86_avx_vpermilvar_pd:
Simon Pilgrim2f6097d2016-04-24 17:23:46 +00001965 case Intrinsic::x86_avx_vpermilvar_pd_256:
1966 if (Value *V = simplifyX86vpermilvar(*II, *Builder))
1967 return replaceInstUsesWith(*II, V);
1968 break;
Rafael Espindolabad3f772014-04-21 22:06:04 +00001969
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +00001970 case Intrinsic::x86_avx2_permd:
1971 case Intrinsic::x86_avx2_permps:
1972 if (Value *V = simplifyX86vpermv(*II, *Builder))
1973 return replaceInstUsesWith(*II, V);
1974 break;
1975
Sanjay Patelccf5f242015-03-20 21:47:56 +00001976 case Intrinsic::x86_avx_vperm2f128_pd_256:
1977 case Intrinsic::x86_avx_vperm2f128_ps_256:
1978 case Intrinsic::x86_avx_vperm2f128_si_256:
Sanjay Patele304bea2015-03-24 22:39:29 +00001979 case Intrinsic::x86_avx2_vperm2i128:
Sanjay Patel6038d3e2016-01-29 23:27:03 +00001980 if (Value *V = simplifyX86vperm2(*II, *Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00001981 return replaceInstUsesWith(*II, V);
Sanjay Patelccf5f242015-03-20 21:47:56 +00001982 break;
1983
Sanjay Patel98a71502016-02-29 23:16:48 +00001984 case Intrinsic::x86_avx_maskload_ps:
Sanjay Patel6f2c01f2016-02-29 23:59:00 +00001985 case Intrinsic::x86_avx_maskload_pd:
1986 case Intrinsic::x86_avx_maskload_ps_256:
1987 case Intrinsic::x86_avx_maskload_pd_256:
1988 case Intrinsic::x86_avx2_maskload_d:
1989 case Intrinsic::x86_avx2_maskload_q:
1990 case Intrinsic::x86_avx2_maskload_d_256:
1991 case Intrinsic::x86_avx2_maskload_q_256:
Sanjay Patel98a71502016-02-29 23:16:48 +00001992 if (Instruction *I = simplifyX86MaskedLoad(*II, *this))
1993 return I;
1994 break;
1995
Sanjay Patelc4acbae2016-03-12 15:16:59 +00001996 case Intrinsic::x86_sse2_maskmov_dqu:
Sanjay Patel1ace9932016-02-26 21:04:14 +00001997 case Intrinsic::x86_avx_maskstore_ps:
1998 case Intrinsic::x86_avx_maskstore_pd:
1999 case Intrinsic::x86_avx_maskstore_ps_256:
2000 case Intrinsic::x86_avx_maskstore_pd_256:
Sanjay Patelfc7e7eb2016-02-26 21:51:44 +00002001 case Intrinsic::x86_avx2_maskstore_d:
2002 case Intrinsic::x86_avx2_maskstore_q:
2003 case Intrinsic::x86_avx2_maskstore_d_256:
2004 case Intrinsic::x86_avx2_maskstore_q_256:
Sanjay Patel1ace9932016-02-26 21:04:14 +00002005 if (simplifyX86MaskedStore(*II, *this))
2006 return nullptr;
2007 break;
2008
Simon Pilgrim1d1c56e22015-10-11 14:38:34 +00002009 case Intrinsic::x86_xop_vpcomb:
2010 case Intrinsic::x86_xop_vpcomd:
2011 case Intrinsic::x86_xop_vpcomq:
2012 case Intrinsic::x86_xop_vpcomw:
Sanjay Patel6038d3e2016-01-29 23:27:03 +00002013 if (Value *V = simplifyX86vpcom(*II, *Builder, true))
Sanjay Patel4b198802016-02-01 22:23:39 +00002014 return replaceInstUsesWith(*II, V);
Simon Pilgrim1d1c56e22015-10-11 14:38:34 +00002015 break;
2016
2017 case Intrinsic::x86_xop_vpcomub:
2018 case Intrinsic::x86_xop_vpcomud:
2019 case Intrinsic::x86_xop_vpcomuq:
2020 case Intrinsic::x86_xop_vpcomuw:
Sanjay Patel6038d3e2016-01-29 23:27:03 +00002021 if (Value *V = simplifyX86vpcom(*II, *Builder, false))
Sanjay Patel4b198802016-02-01 22:23:39 +00002022 return replaceInstUsesWith(*II, V);
Simon Pilgrim1d1c56e22015-10-11 14:38:34 +00002023 break;
2024
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002025 case Intrinsic::ppc_altivec_vperm:
2026 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
Bill Schmidta1184632014-06-05 19:46:04 +00002027 // Note that ppc_altivec_vperm has a big-endian bias, so when creating
2028 // a vectorshuffle for little endian, we must undo the transformation
2029 // performed on vec_perm in altivec.h. That is, we must complement
2030 // the permutation mask with respect to 31 and reverse the order of
2031 // V1 and V2.
Chris Lattner0256be92012-01-27 03:08:05 +00002032 if (Constant *Mask = dyn_cast<Constant>(II->getArgOperand(2))) {
2033 assert(Mask->getType()->getVectorNumElements() == 16 &&
2034 "Bad type for intrinsic!");
Jim Grosbach7815f562012-02-03 00:07:04 +00002035
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002036 // Check that all of the elements are integer constants or undefs.
2037 bool AllEltsOk = true;
2038 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0256be92012-01-27 03:08:05 +00002039 Constant *Elt = Mask->getAggregateElement(i);
Craig Topperf40110f2014-04-25 05:29:35 +00002040 if (!Elt || !(isa<ConstantInt>(Elt) || isa<UndefValue>(Elt))) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002041 AllEltsOk = false;
2042 break;
2043 }
2044 }
Jim Grosbach7815f562012-02-03 00:07:04 +00002045
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002046 if (AllEltsOk) {
2047 // Cast the input vectors to byte vectors.
Gabor Greif3e44ea12010-07-22 10:37:47 +00002048 Value *Op0 = Builder->CreateBitCast(II->getArgOperand(0),
2049 Mask->getType());
2050 Value *Op1 = Builder->CreateBitCast(II->getArgOperand(1),
2051 Mask->getType());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002052 Value *Result = UndefValue::get(Op0->getType());
Jim Grosbach7815f562012-02-03 00:07:04 +00002053
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002054 // Only extract each element once.
2055 Value *ExtractedElts[32];
2056 memset(ExtractedElts, 0, sizeof(ExtractedElts));
Jim Grosbach7815f562012-02-03 00:07:04 +00002057
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002058 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0256be92012-01-27 03:08:05 +00002059 if (isa<UndefValue>(Mask->getAggregateElement(i)))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002060 continue;
Jim Grosbach7815f562012-02-03 00:07:04 +00002061 unsigned Idx =
Chris Lattner0256be92012-01-27 03:08:05 +00002062 cast<ConstantInt>(Mask->getAggregateElement(i))->getZExtValue();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002063 Idx &= 31; // Match the hardware behavior.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002064 if (DL.isLittleEndian())
Bill Schmidta1184632014-06-05 19:46:04 +00002065 Idx = 31 - Idx;
Jim Grosbach7815f562012-02-03 00:07:04 +00002066
Craig Topperf40110f2014-04-25 05:29:35 +00002067 if (!ExtractedElts[Idx]) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002068 Value *Op0ToUse = (DL.isLittleEndian()) ? Op1 : Op0;
2069 Value *Op1ToUse = (DL.isLittleEndian()) ? Op0 : Op1;
Jim Grosbach7815f562012-02-03 00:07:04 +00002070 ExtractedElts[Idx] =
Bill Schmidta1184632014-06-05 19:46:04 +00002071 Builder->CreateExtractElement(Idx < 16 ? Op0ToUse : Op1ToUse,
Benjamin Kramer547b6c52011-09-27 20:39:19 +00002072 Builder->getInt32(Idx&15));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002073 }
Jim Grosbach7815f562012-02-03 00:07:04 +00002074
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002075 // Insert this value into the result vector.
2076 Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
Benjamin Kramer547b6c52011-09-27 20:39:19 +00002077 Builder->getInt32(i));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002078 }
2079 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
2080 }
2081 }
2082 break;
2083
Bob Wilsona4e231c2010-10-22 21:41:48 +00002084 case Intrinsic::arm_neon_vld1:
2085 case Intrinsic::arm_neon_vld2:
2086 case Intrinsic::arm_neon_vld3:
2087 case Intrinsic::arm_neon_vld4:
2088 case Intrinsic::arm_neon_vld2lane:
2089 case Intrinsic::arm_neon_vld3lane:
2090 case Intrinsic::arm_neon_vld4lane:
2091 case Intrinsic::arm_neon_vst1:
2092 case Intrinsic::arm_neon_vst2:
2093 case Intrinsic::arm_neon_vst3:
2094 case Intrinsic::arm_neon_vst4:
2095 case Intrinsic::arm_neon_vst2lane:
2096 case Intrinsic::arm_neon_vst3lane:
2097 case Intrinsic::arm_neon_vst4lane: {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002098 unsigned MemAlign = getKnownAlignment(II->getArgOperand(0), DL, II, AC, DT);
Bob Wilsona4e231c2010-10-22 21:41:48 +00002099 unsigned AlignArg = II->getNumArgOperands() - 1;
2100 ConstantInt *IntrAlign = dyn_cast<ConstantInt>(II->getArgOperand(AlignArg));
2101 if (IntrAlign && IntrAlign->getZExtValue() < MemAlign) {
2102 II->setArgOperand(AlignArg,
2103 ConstantInt::get(Type::getInt32Ty(II->getContext()),
2104 MemAlign, false));
2105 return II;
2106 }
2107 break;
2108 }
2109
Lang Hames3a90fab2012-05-01 00:20:38 +00002110 case Intrinsic::arm_neon_vmulls:
Tim Northover00ed9962014-03-29 10:18:08 +00002111 case Intrinsic::arm_neon_vmullu:
Tim Northover3b0846e2014-05-24 12:50:23 +00002112 case Intrinsic::aarch64_neon_smull:
2113 case Intrinsic::aarch64_neon_umull: {
Lang Hames3a90fab2012-05-01 00:20:38 +00002114 Value *Arg0 = II->getArgOperand(0);
2115 Value *Arg1 = II->getArgOperand(1);
2116
2117 // Handle mul by zero first:
2118 if (isa<ConstantAggregateZero>(Arg0) || isa<ConstantAggregateZero>(Arg1)) {
Sanjay Patel4b198802016-02-01 22:23:39 +00002119 return replaceInstUsesWith(CI, ConstantAggregateZero::get(II->getType()));
Lang Hames3a90fab2012-05-01 00:20:38 +00002120 }
2121
2122 // Check for constant LHS & RHS - in this case we just simplify.
Tim Northover00ed9962014-03-29 10:18:08 +00002123 bool Zext = (II->getIntrinsicID() == Intrinsic::arm_neon_vmullu ||
Tim Northover3b0846e2014-05-24 12:50:23 +00002124 II->getIntrinsicID() == Intrinsic::aarch64_neon_umull);
Lang Hames3a90fab2012-05-01 00:20:38 +00002125 VectorType *NewVT = cast<VectorType>(II->getType());
Benjamin Kramer92040952014-02-13 18:23:24 +00002126 if (Constant *CV0 = dyn_cast<Constant>(Arg0)) {
2127 if (Constant *CV1 = dyn_cast<Constant>(Arg1)) {
2128 CV0 = ConstantExpr::getIntegerCast(CV0, NewVT, /*isSigned=*/!Zext);
2129 CV1 = ConstantExpr::getIntegerCast(CV1, NewVT, /*isSigned=*/!Zext);
2130
Sanjay Patel4b198802016-02-01 22:23:39 +00002131 return replaceInstUsesWith(CI, ConstantExpr::getMul(CV0, CV1));
Lang Hames3a90fab2012-05-01 00:20:38 +00002132 }
2133
Alp Tokercb402912014-01-24 17:20:08 +00002134 // Couldn't simplify - canonicalize constant to the RHS.
Lang Hames3a90fab2012-05-01 00:20:38 +00002135 std::swap(Arg0, Arg1);
2136 }
2137
2138 // Handle mul by one:
Benjamin Kramer92040952014-02-13 18:23:24 +00002139 if (Constant *CV1 = dyn_cast<Constant>(Arg1))
Lang Hames3a90fab2012-05-01 00:20:38 +00002140 if (ConstantInt *Splat =
Benjamin Kramer92040952014-02-13 18:23:24 +00002141 dyn_cast_or_null<ConstantInt>(CV1->getSplatValue()))
2142 if (Splat->isOne())
2143 return CastInst::CreateIntegerCast(Arg0, II->getType(),
2144 /*isSigned=*/!Zext);
Lang Hames3a90fab2012-05-01 00:20:38 +00002145
2146 break;
2147 }
2148
Matt Arsenaultbef34e22016-01-22 21:30:34 +00002149 case Intrinsic::amdgcn_rcp: {
Matt Arsenaulta0050b02014-06-19 01:19:19 +00002150 if (const ConstantFP *C = dyn_cast<ConstantFP>(II->getArgOperand(0))) {
2151 const APFloat &ArgVal = C->getValueAPF();
2152 APFloat Val(ArgVal.getSemantics(), 1.0);
2153 APFloat::opStatus Status = Val.divide(ArgVal,
2154 APFloat::rmNearestTiesToEven);
2155 // Only do this if it was exact and therefore not dependent on the
2156 // rounding mode.
2157 if (Status == APFloat::opOK)
Sanjay Patel4b198802016-02-01 22:23:39 +00002158 return replaceInstUsesWith(CI, ConstantFP::get(II->getContext(), Val));
Matt Arsenaulta0050b02014-06-19 01:19:19 +00002159 }
2160
2161 break;
2162 }
Matt Arsenault2fe4fbc2016-03-30 22:28:52 +00002163 case Intrinsic::amdgcn_frexp_mant:
2164 case Intrinsic::amdgcn_frexp_exp: {
Matt Arsenault5cd4f8f2016-03-30 22:28:26 +00002165 Value *Src = II->getArgOperand(0);
2166 if (const ConstantFP *C = dyn_cast<ConstantFP>(Src)) {
2167 int Exp;
2168 APFloat Significand = frexp(C->getValueAPF(), Exp,
2169 APFloat::rmNearestTiesToEven);
2170
Matt Arsenault2fe4fbc2016-03-30 22:28:52 +00002171 if (II->getIntrinsicID() == Intrinsic::amdgcn_frexp_mant) {
2172 return replaceInstUsesWith(CI, ConstantFP::get(II->getContext(),
2173 Significand));
2174 }
2175
2176 // Match instruction special case behavior.
2177 if (Exp == APFloat::IEK_NaN || Exp == APFloat::IEK_Inf)
2178 Exp = 0;
2179
2180 return replaceInstUsesWith(CI, ConstantInt::get(II->getType(), Exp));
2181 }
2182
2183 if (isa<UndefValue>(Src))
2184 return replaceInstUsesWith(CI, UndefValue::get(II->getType()));
Matt Arsenault5cd4f8f2016-03-30 22:28:26 +00002185
2186 break;
2187 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002188 case Intrinsic::stackrestore: {
2189 // If the save is right next to the restore, remove the restore. This can
2190 // happen when variable allocas are DCE'd.
Gabor Greif589a0b92010-06-24 12:58:35 +00002191 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getArgOperand(0))) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002192 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00002193 if (&*++SS->getIterator() == II)
Sanjay Patel4b198802016-02-01 22:23:39 +00002194 return eraseInstFromFunction(CI);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002195 }
2196 }
Jim Grosbach7815f562012-02-03 00:07:04 +00002197
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002198 // Scan down this block to see if there is another stack restore in the
2199 // same block without an intervening call/alloca.
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00002200 BasicBlock::iterator BI(II);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002201 TerminatorInst *TI = II->getParent()->getTerminator();
2202 bool CannotRemove = false;
2203 for (++BI; &*BI != TI; ++BI) {
Nuno Lopes55fff832012-06-21 15:45:28 +00002204 if (isa<AllocaInst>(BI)) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002205 CannotRemove = true;
2206 break;
2207 }
2208 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
2209 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
2210 // If there is a stackrestore below this one, remove this one.
2211 if (II->getIntrinsicID() == Intrinsic::stackrestore)
Sanjay Patel4b198802016-02-01 22:23:39 +00002212 return eraseInstFromFunction(CI);
Reid Kleckner892ae2e2016-02-27 00:53:54 +00002213
2214 // Bail if we cross over an intrinsic with side effects, such as
2215 // llvm.stacksave, llvm.read_register, or llvm.setjmp.
2216 if (II->mayHaveSideEffects()) {
2217 CannotRemove = true;
2218 break;
2219 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002220 } else {
2221 // If we found a non-intrinsic call, we can't remove the stack
2222 // restore.
2223 CannotRemove = true;
2224 break;
2225 }
2226 }
2227 }
Jim Grosbach7815f562012-02-03 00:07:04 +00002228
Bill Wendlingf891bf82011-07-31 06:30:59 +00002229 // If the stack restore is in a return, resume, or unwind block and if there
2230 // are no allocas or calls between the restore and the return, nuke the
2231 // restore.
Bill Wendlingd5d95b02012-02-06 21:16:41 +00002232 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<ResumeInst>(TI)))
Sanjay Patel4b198802016-02-01 22:23:39 +00002233 return eraseInstFromFunction(CI);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002234 break;
2235 }
Arnaud A. de Grandmaison333ef382016-05-10 09:24:49 +00002236 case Intrinsic::lifetime_start:
2237 if (removeTriviallyEmptyRange(*II, Intrinsic::lifetime_start,
2238 Intrinsic::lifetime_end, *this))
2239 return nullptr;
Arnaud A. de Grandmaison849f3bf2015-10-01 14:54:31 +00002240 break;
Hal Finkelf5867a72014-07-25 21:45:17 +00002241 case Intrinsic::assume: {
David Majnemerfcc58112016-04-08 16:37:12 +00002242 Value *IIOperand = II->getArgOperand(0);
2243 // Remove an assume if it is immediately followed by an identical assume.
2244 if (match(II->getNextNode(),
2245 m_Intrinsic<Intrinsic::assume>(m_Specific(IIOperand))))
2246 return eraseInstFromFunction(CI);
2247
Hal Finkelf5867a72014-07-25 21:45:17 +00002248 // Canonicalize assume(a && b) -> assume(a); assume(b);
Hal Finkel74c2f352014-09-07 12:44:26 +00002249 // Note: New assumption intrinsics created here are registered by
2250 // the InstCombineIRInserter object.
David Majnemerfcc58112016-04-08 16:37:12 +00002251 Value *AssumeIntrinsic = II->getCalledValue(), *A, *B;
Hal Finkelf5867a72014-07-25 21:45:17 +00002252 if (match(IIOperand, m_And(m_Value(A), m_Value(B)))) {
2253 Builder->CreateCall(AssumeIntrinsic, A, II->getName());
2254 Builder->CreateCall(AssumeIntrinsic, B, II->getName());
Sanjay Patel4b198802016-02-01 22:23:39 +00002255 return eraseInstFromFunction(*II);
Hal Finkelf5867a72014-07-25 21:45:17 +00002256 }
2257 // assume(!(a || b)) -> assume(!a); assume(!b);
2258 if (match(IIOperand, m_Not(m_Or(m_Value(A), m_Value(B))))) {
Hal Finkel74c2f352014-09-07 12:44:26 +00002259 Builder->CreateCall(AssumeIntrinsic, Builder->CreateNot(A),
2260 II->getName());
2261 Builder->CreateCall(AssumeIntrinsic, Builder->CreateNot(B),
2262 II->getName());
Sanjay Patel4b198802016-02-01 22:23:39 +00002263 return eraseInstFromFunction(*II);
Hal Finkelf5867a72014-07-25 21:45:17 +00002264 }
Hal Finkel04a15612014-10-04 21:27:06 +00002265
Philip Reames66c6de62014-11-11 23:33:19 +00002266 // assume( (load addr) != null ) -> add 'nonnull' metadata to load
2267 // (if assume is valid at the load)
2268 if (ICmpInst* ICmp = dyn_cast<ICmpInst>(IIOperand)) {
2269 Value *LHS = ICmp->getOperand(0);
2270 Value *RHS = ICmp->getOperand(1);
2271 if (ICmpInst::ICMP_NE == ICmp->getPredicate() &&
2272 isa<LoadInst>(LHS) &&
2273 isa<Constant>(RHS) &&
2274 RHS->getType()->isPointerTy() &&
2275 cast<Constant>(RHS)->isNullValue()) {
2276 LoadInst* LI = cast<LoadInst>(LHS);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002277 if (isValidAssumeForContext(II, LI, DT)) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002278 MDNode *MD = MDNode::get(II->getContext(), None);
Philip Reames66c6de62014-11-11 23:33:19 +00002279 LI->setMetadata(LLVMContext::MD_nonnull, MD);
Sanjay Patel4b198802016-02-01 22:23:39 +00002280 return eraseInstFromFunction(*II);
Philip Reames66c6de62014-11-11 23:33:19 +00002281 }
2282 }
Chandler Carruth24969102015-02-10 08:07:32 +00002283 // TODO: apply nonnull return attributes to calls and invokes
Philip Reames66c6de62014-11-11 23:33:19 +00002284 // TODO: apply range metadata for range check patterns?
2285 }
Hal Finkel04a15612014-10-04 21:27:06 +00002286 // If there is a dominating assume with the same condition as this one,
2287 // then this one is redundant, and should be removed.
Hal Finkel45646882014-10-05 00:53:02 +00002288 APInt KnownZero(1, 0), KnownOne(1, 0);
2289 computeKnownBits(IIOperand, KnownZero, KnownOne, 0, II);
2290 if (KnownOne.isAllOnesValue())
Sanjay Patel4b198802016-02-01 22:23:39 +00002291 return eraseInstFromFunction(*II);
Hal Finkel04a15612014-10-04 21:27:06 +00002292
Hal Finkelf5867a72014-07-25 21:45:17 +00002293 break;
2294 }
Philip Reames9db26ff2014-12-29 23:27:30 +00002295 case Intrinsic::experimental_gc_relocate: {
2296 // Translate facts known about a pointer before relocating into
2297 // facts about the relocate value, while being careful to
2298 // preserve relocation semantics.
Manuel Jacob83eefa62016-01-05 04:03:00 +00002299 Value *DerivedPtr = cast<GCRelocateInst>(II)->getDerivedPtr();
Philip Reames9db26ff2014-12-29 23:27:30 +00002300
2301 // Remove the relocation if unused, note that this check is required
2302 // to prevent the cases below from looping forever.
2303 if (II->use_empty())
Sanjay Patel4b198802016-02-01 22:23:39 +00002304 return eraseInstFromFunction(*II);
Philip Reames9db26ff2014-12-29 23:27:30 +00002305
2306 // Undef is undef, even after relocation.
2307 // TODO: provide a hook for this in GCStrategy. This is clearly legal for
2308 // most practical collectors, but there was discussion in the review thread
2309 // about whether it was legal for all possible collectors.
Philip Reamesea4d8e82016-02-09 21:09:22 +00002310 if (isa<UndefValue>(DerivedPtr))
2311 // Use undef of gc_relocate's type to replace it.
2312 return replaceInstUsesWith(*II, UndefValue::get(II->getType()));
Philip Reames9db26ff2014-12-29 23:27:30 +00002313
Philip Reamesea4d8e82016-02-09 21:09:22 +00002314 if (auto *PT = dyn_cast<PointerType>(II->getType())) {
2315 // The relocation of null will be null for most any collector.
2316 // TODO: provide a hook for this in GCStrategy. There might be some
2317 // weird collector this property does not hold for.
2318 if (isa<ConstantPointerNull>(DerivedPtr))
2319 // Use null-pointer of gc_relocate's type to replace it.
2320 return replaceInstUsesWith(*II, ConstantPointerNull::get(PT));
Simon Pilgrimc0c56e72016-04-24 17:00:34 +00002321
Philip Reamesea4d8e82016-02-09 21:09:22 +00002322 // isKnownNonNull -> nonnull attribute
2323 if (isKnownNonNullAt(DerivedPtr, II, DT, TLI))
2324 II->addAttribute(AttributeSet::ReturnIndex, Attribute::NonNull);
Ramkumar Ramachandra8fcb4982015-02-14 19:37:54 +00002325 }
Philip Reames9db26ff2014-12-29 23:27:30 +00002326
2327 // TODO: bitcast(relocate(p)) -> relocate(bitcast(p))
2328 // Canonicalize on the type from the uses to the defs
Ramkumar Ramachandra8fcb4982015-02-14 19:37:54 +00002329
Philip Reames9db26ff2014-12-29 23:27:30 +00002330 // TODO: relocate((gep p, C, C2, ...)) -> gep(relocate(p), C, C2, ...)
Philip Reamesea4d8e82016-02-09 21:09:22 +00002331 break;
Philip Reames9db26ff2014-12-29 23:27:30 +00002332 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002333 }
2334
2335 return visitCallSite(II);
2336}
2337
2338// InvokeInst simplification
2339//
2340Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
2341 return visitCallSite(&II);
2342}
2343
Sanjay Patelcd4377c2016-01-20 22:24:38 +00002344/// If this cast does not affect the value passed through the varargs area, we
2345/// can eliminate the use of the cast.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002346static bool isSafeToEliminateVarargsCast(const CallSite CS,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002347 const DataLayout &DL,
2348 const CastInst *const CI,
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002349 const int ix) {
2350 if (!CI->isLosslessCast())
2351 return false;
2352
Philip Reames1a1bdb22014-12-02 18:50:36 +00002353 // If this is a GC intrinsic, avoid munging types. We need types for
2354 // statepoint reconstruction in SelectionDAG.
2355 // TODO: This is probably something which should be expanded to all
2356 // intrinsics since the entire point of intrinsics is that
2357 // they are understandable by the optimizer.
2358 if (isStatepoint(CS) || isGCRelocate(CS) || isGCResult(CS))
2359 return false;
2360
Reid Kleckner26af2ca2014-01-28 02:38:36 +00002361 // The size of ByVal or InAlloca arguments is derived from the type, so we
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002362 // can't change to a type with a different size. If the size were
2363 // passed explicitly we could avoid this check.
Reid Kleckner26af2ca2014-01-28 02:38:36 +00002364 if (!CS.isByValOrInAllocaArgument(ix))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002365 return true;
2366
Jim Grosbach7815f562012-02-03 00:07:04 +00002367 Type* SrcTy =
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002368 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
Chris Lattner229907c2011-07-18 04:54:35 +00002369 Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002370 if (!SrcTy->isSized() || !DstTy->isSized())
2371 return false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002372 if (DL.getTypeAllocSize(SrcTy) != DL.getTypeAllocSize(DstTy))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002373 return false;
2374 return true;
2375}
2376
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002377Instruction *InstCombiner::tryOptimizeCall(CallInst *CI) {
Craig Topperf40110f2014-04-25 05:29:35 +00002378 if (!CI->getCalledFunction()) return nullptr;
Eric Christophera7fb58f2010-03-06 10:50:38 +00002379
Chandler Carruthba4c5172015-01-21 11:23:40 +00002380 auto InstCombineRAUW = [this](Instruction *From, Value *With) {
Sanjay Patel4b198802016-02-01 22:23:39 +00002381 replaceInstUsesWith(*From, With);
Chandler Carruthba4c5172015-01-21 11:23:40 +00002382 };
2383 LibCallSimplifier Simplifier(DL, TLI, InstCombineRAUW);
2384 if (Value *With = Simplifier.optimizeCall(CI)) {
Meador Ingee3f2b262012-11-30 04:05:06 +00002385 ++NumSimplified;
Sanjay Patel4b198802016-02-01 22:23:39 +00002386 return CI->use_empty() ? CI : replaceInstUsesWith(*CI, With);
Meador Ingee3f2b262012-11-30 04:05:06 +00002387 }
Meador Ingedf796f82012-10-13 16:45:24 +00002388
Craig Topperf40110f2014-04-25 05:29:35 +00002389 return nullptr;
Eric Christophera7fb58f2010-03-06 10:50:38 +00002390}
2391
Sanjay Patel6038d3e2016-01-29 23:27:03 +00002392static IntrinsicInst *findInitTrampolineFromAlloca(Value *TrampMem) {
Duncan Sandsa0984362011-09-06 13:37:06 +00002393 // Strip off at most one level of pointer casts, looking for an alloca. This
2394 // is good enough in practice and simpler than handling any number of casts.
2395 Value *Underlying = TrampMem->stripPointerCasts();
2396 if (Underlying != TrampMem &&
Chandler Carruthcdf47882014-03-09 03:16:01 +00002397 (!Underlying->hasOneUse() || Underlying->user_back() != TrampMem))
Craig Topperf40110f2014-04-25 05:29:35 +00002398 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00002399 if (!isa<AllocaInst>(Underlying))
Craig Topperf40110f2014-04-25 05:29:35 +00002400 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00002401
Craig Topperf40110f2014-04-25 05:29:35 +00002402 IntrinsicInst *InitTrampoline = nullptr;
Chandler Carruthcdf47882014-03-09 03:16:01 +00002403 for (User *U : TrampMem->users()) {
2404 IntrinsicInst *II = dyn_cast<IntrinsicInst>(U);
Duncan Sandsa0984362011-09-06 13:37:06 +00002405 if (!II)
Craig Topperf40110f2014-04-25 05:29:35 +00002406 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00002407 if (II->getIntrinsicID() == Intrinsic::init_trampoline) {
2408 if (InitTrampoline)
2409 // More than one init_trampoline writes to this value. Give up.
Craig Topperf40110f2014-04-25 05:29:35 +00002410 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00002411 InitTrampoline = II;
2412 continue;
2413 }
2414 if (II->getIntrinsicID() == Intrinsic::adjust_trampoline)
2415 // Allow any number of calls to adjust.trampoline.
2416 continue;
Craig Topperf40110f2014-04-25 05:29:35 +00002417 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00002418 }
2419
2420 // No call to init.trampoline found.
2421 if (!InitTrampoline)
Craig Topperf40110f2014-04-25 05:29:35 +00002422 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00002423
2424 // Check that the alloca is being used in the expected way.
2425 if (InitTrampoline->getOperand(0) != TrampMem)
Craig Topperf40110f2014-04-25 05:29:35 +00002426 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00002427
2428 return InitTrampoline;
2429}
2430
Sanjay Patel6038d3e2016-01-29 23:27:03 +00002431static IntrinsicInst *findInitTrampolineFromBB(IntrinsicInst *AdjustTramp,
Duncan Sandsa0984362011-09-06 13:37:06 +00002432 Value *TrampMem) {
2433 // Visit all the previous instructions in the basic block, and try to find a
2434 // init.trampoline which has a direct path to the adjust.trampoline.
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00002435 for (BasicBlock::iterator I = AdjustTramp->getIterator(),
2436 E = AdjustTramp->getParent()->begin();
2437 I != E;) {
2438 Instruction *Inst = &*--I;
Duncan Sandsa0984362011-09-06 13:37:06 +00002439 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
2440 if (II->getIntrinsicID() == Intrinsic::init_trampoline &&
2441 II->getOperand(0) == TrampMem)
2442 return II;
2443 if (Inst->mayWriteToMemory())
Craig Topperf40110f2014-04-25 05:29:35 +00002444 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00002445 }
Craig Topperf40110f2014-04-25 05:29:35 +00002446 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00002447}
2448
2449// Given a call to llvm.adjust.trampoline, find and return the corresponding
2450// call to llvm.init.trampoline if the call to the trampoline can be optimized
2451// to a direct call to a function. Otherwise return NULL.
2452//
Sanjay Patel6038d3e2016-01-29 23:27:03 +00002453static IntrinsicInst *findInitTrampoline(Value *Callee) {
Duncan Sandsa0984362011-09-06 13:37:06 +00002454 Callee = Callee->stripPointerCasts();
2455 IntrinsicInst *AdjustTramp = dyn_cast<IntrinsicInst>(Callee);
2456 if (!AdjustTramp ||
2457 AdjustTramp->getIntrinsicID() != Intrinsic::adjust_trampoline)
Craig Topperf40110f2014-04-25 05:29:35 +00002458 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00002459
2460 Value *TrampMem = AdjustTramp->getOperand(0);
2461
Sanjay Patel6038d3e2016-01-29 23:27:03 +00002462 if (IntrinsicInst *IT = findInitTrampolineFromAlloca(TrampMem))
Duncan Sandsa0984362011-09-06 13:37:06 +00002463 return IT;
Sanjay Patel6038d3e2016-01-29 23:27:03 +00002464 if (IntrinsicInst *IT = findInitTrampolineFromBB(AdjustTramp, TrampMem))
Duncan Sandsa0984362011-09-06 13:37:06 +00002465 return IT;
Craig Topperf40110f2014-04-25 05:29:35 +00002466 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00002467}
2468
Sanjay Patelcd4377c2016-01-20 22:24:38 +00002469/// Improvements for call and invoke instructions.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002470Instruction *InstCombiner::visitCallSite(CallSite CS) {
Philip Reamesc25df112015-06-16 20:24:25 +00002471
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00002472 if (isAllocLikeFn(CS.getInstruction(), TLI))
Nuno Lopes95cc4f32012-07-09 18:38:20 +00002473 return visitAllocSite(*CS.getInstruction());
Nuno Lopesdc6085e2012-06-21 21:25:05 +00002474
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002475 bool Changed = false;
2476
Philip Reamesc25df112015-06-16 20:24:25 +00002477 // Mark any parameters that are known to be non-null with the nonnull
2478 // attribute. This is helpful for inlining calls to functions with null
2479 // checks on their arguments.
Akira Hatanaka237916b2015-12-02 06:58:49 +00002480 SmallVector<unsigned, 4> Indices;
Philip Reamesc25df112015-06-16 20:24:25 +00002481 unsigned ArgNo = 0;
Akira Hatanaka237916b2015-12-02 06:58:49 +00002482
Philip Reamesc25df112015-06-16 20:24:25 +00002483 for (Value *V : CS.args()) {
Sanjay Patelf9f5d3c2016-01-29 23:14:58 +00002484 if (V->getType()->isPointerTy() &&
2485 !CS.paramHasAttr(ArgNo + 1, Attribute::NonNull) &&
Akira Hatanaka237916b2015-12-02 06:58:49 +00002486 isKnownNonNullAt(V, CS.getInstruction(), DT, TLI))
2487 Indices.push_back(ArgNo + 1);
Philip Reamesc25df112015-06-16 20:24:25 +00002488 ArgNo++;
2489 }
Akira Hatanaka237916b2015-12-02 06:58:49 +00002490
Philip Reamesc25df112015-06-16 20:24:25 +00002491 assert(ArgNo == CS.arg_size() && "sanity check");
2492
Akira Hatanaka237916b2015-12-02 06:58:49 +00002493 if (!Indices.empty()) {
2494 AttributeSet AS = CS.getAttributes();
2495 LLVMContext &Ctx = CS.getInstruction()->getContext();
2496 AS = AS.addAttribute(Ctx, Indices,
2497 Attribute::get(Ctx, Attribute::NonNull));
2498 CS.setAttributes(AS);
2499 Changed = true;
2500 }
2501
Chris Lattner73989652010-12-20 08:25:06 +00002502 // If the callee is a pointer to a function, attempt to move any casts to the
2503 // arguments of the call/invoke.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002504 Value *Callee = CS.getCalledValue();
Chris Lattner73989652010-12-20 08:25:06 +00002505 if (!isa<Function>(Callee) && transformConstExprCastCall(CS))
Craig Topperf40110f2014-04-25 05:29:35 +00002506 return nullptr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002507
Justin Lebar9d943972016-03-14 20:18:54 +00002508 if (Function *CalleeF = dyn_cast<Function>(Callee)) {
2509 // Remove the convergent attr on calls when the callee is not convergent.
2510 if (CS.isConvergent() && !CalleeF->isConvergent()) {
2511 DEBUG(dbgs() << "Removing convergent attr from instr "
2512 << CS.getInstruction() << "\n");
2513 CS.setNotConvergent();
2514 return CS.getInstruction();
2515 }
2516
Chris Lattner846a52e2010-02-01 18:11:34 +00002517 // If the call and callee calling conventions don't match, this call must
2518 // be unreachable, as the call is undefined.
2519 if (CalleeF->getCallingConv() != CS.getCallingConv() &&
2520 // Only do this for calls to a function with a body. A prototype may
2521 // not actually end up matching the implementation's calling conv for a
2522 // variety of reasons (e.g. it may be written in assembly).
2523 !CalleeF->isDeclaration()) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002524 Instruction *OldCall = CS.getInstruction();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002525 new StoreInst(ConstantInt::getTrue(Callee->getContext()),
Jim Grosbach7815f562012-02-03 00:07:04 +00002526 UndefValue::get(Type::getInt1PtrTy(Callee->getContext())),
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002527 OldCall);
Chad Rosiere28ae302012-12-13 00:18:46 +00002528 // If OldCall does not return void then replaceAllUsesWith undef.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002529 // This allows ValueHandlers and custom metadata to adjust itself.
2530 if (!OldCall->getType()->isVoidTy())
Sanjay Patel4b198802016-02-01 22:23:39 +00002531 replaceInstUsesWith(*OldCall, UndefValue::get(OldCall->getType()));
Chris Lattner2cecedf2010-02-01 18:04:58 +00002532 if (isa<CallInst>(OldCall))
Sanjay Patel4b198802016-02-01 22:23:39 +00002533 return eraseInstFromFunction(*OldCall);
Jim Grosbach7815f562012-02-03 00:07:04 +00002534
Chris Lattner2cecedf2010-02-01 18:04:58 +00002535 // We cannot remove an invoke, because it would change the CFG, just
2536 // change the callee to a null pointer.
Gabor Greiffebf6ab2010-03-20 21:00:25 +00002537 cast<InvokeInst>(OldCall)->setCalledFunction(
Chris Lattner2cecedf2010-02-01 18:04:58 +00002538 Constant::getNullValue(CalleeF->getType()));
Craig Topperf40110f2014-04-25 05:29:35 +00002539 return nullptr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002540 }
Justin Lebar9d943972016-03-14 20:18:54 +00002541 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002542
2543 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
Gabor Greif589a0b92010-06-24 12:58:35 +00002544 // If CS does not return void then replaceAllUsesWith undef.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002545 // This allows ValueHandlers and custom metadata to adjust itself.
2546 if (!CS.getInstruction()->getType()->isVoidTy())
Sanjay Patel4b198802016-02-01 22:23:39 +00002547 replaceInstUsesWith(*CS.getInstruction(),
Eli Friedmanb9ed18f2011-05-18 00:32:01 +00002548 UndefValue::get(CS.getInstruction()->getType()));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002549
Nuno Lopes771e7bd2012-06-21 23:52:14 +00002550 if (isa<InvokeInst>(CS.getInstruction())) {
2551 // Can't remove an invoke because we cannot change the CFG.
Craig Topperf40110f2014-04-25 05:29:35 +00002552 return nullptr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002553 }
Nuno Lopes771e7bd2012-06-21 23:52:14 +00002554
2555 // This instruction is not reachable, just remove it. We insert a store to
2556 // undef so that we know that this code is not reachable, despite the fact
2557 // that we can't modify the CFG here.
2558 new StoreInst(ConstantInt::getTrue(Callee->getContext()),
2559 UndefValue::get(Type::getInt1PtrTy(Callee->getContext())),
2560 CS.getInstruction());
2561
Sanjay Patel4b198802016-02-01 22:23:39 +00002562 return eraseInstFromFunction(*CS.getInstruction());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002563 }
2564
Sanjay Patel6038d3e2016-01-29 23:27:03 +00002565 if (IntrinsicInst *II = findInitTrampoline(Callee))
Duncan Sandsa0984362011-09-06 13:37:06 +00002566 return transformCallThroughTrampoline(CS, II);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002567
Chris Lattner229907c2011-07-18 04:54:35 +00002568 PointerType *PTy = cast<PointerType>(Callee->getType());
2569 FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002570 if (FTy->isVarArg()) {
Eli Friedman7534b4682011-11-29 01:18:23 +00002571 int ix = FTy->getNumParams();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002572 // See if we can optimize any arguments passed through the varargs area of
2573 // the call.
Matt Arsenault5d2e85f2013-06-28 00:25:40 +00002574 for (CallSite::arg_iterator I = CS.arg_begin() + FTy->getNumParams(),
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002575 E = CS.arg_end(); I != E; ++I, ++ix) {
2576 CastInst *CI = dyn_cast<CastInst>(*I);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002577 if (CI && isSafeToEliminateVarargsCast(CS, DL, CI, ix)) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002578 *I = CI->getOperand(0);
2579 Changed = true;
2580 }
2581 }
2582 }
2583
2584 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
2585 // Inline asm calls cannot throw - mark them 'nounwind'.
2586 CS.setDoesNotThrow();
2587 Changed = true;
2588 }
2589
Micah Villmowcdfe20b2012-10-08 16:38:25 +00002590 // Try to optimize the call if possible, we require DataLayout for most of
Eric Christophera7fb58f2010-03-06 10:50:38 +00002591 // this. None of these calls are seen as possibly dead so go ahead and
2592 // delete the instruction now.
2593 if (CallInst *CI = dyn_cast<CallInst>(CS.getInstruction())) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002594 Instruction *I = tryOptimizeCall(CI);
Eric Christopher1810d772010-03-06 10:59:25 +00002595 // If we changed something return the result, etc. Otherwise let
2596 // the fallthrough check.
Sanjay Patel4b198802016-02-01 22:23:39 +00002597 if (I) return eraseInstFromFunction(*I);
Eric Christophera7fb58f2010-03-06 10:50:38 +00002598 }
2599
Craig Topperf40110f2014-04-25 05:29:35 +00002600 return Changed ? CS.getInstruction() : nullptr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002601}
2602
Sanjay Patelcd4377c2016-01-20 22:24:38 +00002603/// If the callee is a constexpr cast of a function, attempt to move the cast to
2604/// the arguments of the call/invoke.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002605bool InstCombiner::transformConstExprCastCall(CallSite CS) {
Chris Lattner73989652010-12-20 08:25:06 +00002606 Function *Callee =
2607 dyn_cast<Function>(CS.getCalledValue()->stripPointerCasts());
Craig Topperf40110f2014-04-25 05:29:35 +00002608 if (!Callee)
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002609 return false;
David Majnemer4c0a6e92015-01-21 22:32:04 +00002610 // The prototype of thunks are a lie, don't try to directly call such
2611 // functions.
2612 if (Callee->hasFnAttribute("thunk"))
2613 return false;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002614 Instruction *Caller = CS.getInstruction();
Bill Wendlinge94d8432012-12-07 23:16:57 +00002615 const AttributeSet &CallerPAL = CS.getAttributes();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002616
2617 // Okay, this is a cast from a function to a different type. Unless doing so
2618 // would cause a type conversion of one of our arguments, change this call to
2619 // be a direct call with arguments casted to the appropriate types.
2620 //
Chris Lattner229907c2011-07-18 04:54:35 +00002621 FunctionType *FT = Callee->getFunctionType();
2622 Type *OldRetTy = Caller->getType();
2623 Type *NewRetTy = FT->getReturnType();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002624
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002625 // Check to see if we are changing the return type...
2626 if (OldRetTy != NewRetTy) {
Nick Lewyckya6a17d72014-01-18 22:47:12 +00002627
2628 if (NewRetTy->isStructTy())
2629 return false; // TODO: Handle multiple return values.
2630
David Majnemer9b6b8222015-01-06 08:41:31 +00002631 if (!CastInst::isBitOrNoopPointerCastable(NewRetTy, OldRetTy, DL)) {
Matt Arsenaulte6952f22013-09-17 21:10:14 +00002632 if (Callee->isDeclaration())
2633 return false; // Cannot transform this return value.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002634
Matt Arsenaulte6952f22013-09-17 21:10:14 +00002635 if (!Caller->use_empty() &&
2636 // void -> non-void is handled specially
2637 !NewRetTy->isVoidTy())
Frederic Rissc1892e22014-10-23 04:08:42 +00002638 return false; // Cannot transform this return value.
Matt Arsenaulte6952f22013-09-17 21:10:14 +00002639 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002640
2641 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Bill Wendling658d24d2013-01-18 21:53:16 +00002642 AttrBuilder RAttrs(CallerPAL, AttributeSet::ReturnIndex);
Pete Cooper2777d8872015-05-06 23:19:56 +00002643 if (RAttrs.overlaps(AttributeFuncs::typeIncompatible(NewRetTy)))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002644 return false; // Attribute not compatible with transformed value.
2645 }
2646
2647 // If the callsite is an invoke instruction, and the return value is used by
2648 // a PHI node in a successor, we cannot change the return type of the call
2649 // because there is no place to put the cast instruction (without breaking
2650 // the critical edge). Bail out in this case.
2651 if (!Caller->use_empty())
2652 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
Chandler Carruthcdf47882014-03-09 03:16:01 +00002653 for (User *U : II->users())
2654 if (PHINode *PN = dyn_cast<PHINode>(U))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002655 if (PN->getParent() == II->getNormalDest() ||
2656 PN->getParent() == II->getUnwindDest())
2657 return false;
2658 }
2659
Matt Arsenault5d2e85f2013-06-28 00:25:40 +00002660 unsigned NumActualArgs = CS.arg_size();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002661 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
2662
David Majnemer9b6b8222015-01-06 08:41:31 +00002663 // Prevent us turning:
2664 // declare void @takes_i32_inalloca(i32* inalloca)
2665 // call void bitcast (void (i32*)* @takes_i32_inalloca to void (i32)*)(i32 0)
2666 //
2667 // into:
2668 // call void @takes_i32_inalloca(i32* null)
David Majnemerd61a6fd2015-03-11 18:03:05 +00002669 //
2670 // Similarly, avoid folding away bitcasts of byval calls.
2671 if (Callee->getAttributes().hasAttrSomewhere(Attribute::InAlloca) ||
2672 Callee->getAttributes().hasAttrSomewhere(Attribute::ByVal))
David Majnemer9b6b8222015-01-06 08:41:31 +00002673 return false;
2674
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002675 CallSite::arg_iterator AI = CS.arg_begin();
2676 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
Chris Lattner229907c2011-07-18 04:54:35 +00002677 Type *ParamTy = FT->getParamType(i);
2678 Type *ActTy = (*AI)->getType();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002679
David Majnemer9b6b8222015-01-06 08:41:31 +00002680 if (!CastInst::isBitOrNoopPointerCastable(ActTy, ParamTy, DL))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002681 return false; // Cannot transform this parameter value.
2682
Bill Wendling49bc76c2013-01-23 06:14:59 +00002683 if (AttrBuilder(CallerPAL.getParamAttributes(i + 1), i + 1).
Pete Cooper2777d8872015-05-06 23:19:56 +00002684 overlaps(AttributeFuncs::typeIncompatible(ParamTy)))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002685 return false; // Attribute not compatible with transformed value.
Jim Grosbach7815f562012-02-03 00:07:04 +00002686
Reid Kleckner26af2ca2014-01-28 02:38:36 +00002687 if (CS.isInAllocaArgument(i))
2688 return false; // Cannot transform to and from inalloca.
2689
Chris Lattner27ca8eb2010-12-20 08:36:38 +00002690 // If the parameter is passed as a byval argument, then we have to have a
2691 // sized type and the sized type has to have the same size as the old type.
Bill Wendling49bc76c2013-01-23 06:14:59 +00002692 if (ParamTy != ActTy &&
2693 CallerPAL.getParamAttributes(i + 1).hasAttribute(i + 1,
2694 Attribute::ByVal)) {
Chris Lattner229907c2011-07-18 04:54:35 +00002695 PointerType *ParamPTy = dyn_cast<PointerType>(ParamTy);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002696 if (!ParamPTy || !ParamPTy->getElementType()->isSized())
Chris Lattner27ca8eb2010-12-20 08:36:38 +00002697 return false;
Jim Grosbach7815f562012-02-03 00:07:04 +00002698
Matt Arsenaultfa252722013-09-27 22:18:51 +00002699 Type *CurElTy = ActTy->getPointerElementType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002700 if (DL.getTypeAllocSize(CurElTy) !=
2701 DL.getTypeAllocSize(ParamPTy->getElementType()))
Chris Lattner27ca8eb2010-12-20 08:36:38 +00002702 return false;
2703 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002704 }
2705
Chris Lattneradf38b32011-02-24 05:10:56 +00002706 if (Callee->isDeclaration()) {
2707 // Do not delete arguments unless we have a function body.
2708 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg())
2709 return false;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002710
Chris Lattneradf38b32011-02-24 05:10:56 +00002711 // If the callee is just a declaration, don't change the varargsness of the
2712 // call. We don't want to introduce a varargs call where one doesn't
2713 // already exist.
Chris Lattner229907c2011-07-18 04:54:35 +00002714 PointerType *APTy = cast<PointerType>(CS.getCalledValue()->getType());
Chris Lattneradf38b32011-02-24 05:10:56 +00002715 if (FT->isVarArg()!=cast<FunctionType>(APTy->getElementType())->isVarArg())
2716 return false;
Jim Grosbache84ae7b2012-02-03 00:00:55 +00002717
2718 // If both the callee and the cast type are varargs, we still have to make
2719 // sure the number of fixed parameters are the same or we have the same
2720 // ABI issues as if we introduce a varargs call.
Jim Grosbach1df8cdc2012-02-03 00:26:07 +00002721 if (FT->isVarArg() &&
2722 cast<FunctionType>(APTy->getElementType())->isVarArg() &&
2723 FT->getNumParams() !=
Jim Grosbache84ae7b2012-02-03 00:00:55 +00002724 cast<FunctionType>(APTy->getElementType())->getNumParams())
2725 return false;
Chris Lattneradf38b32011-02-24 05:10:56 +00002726 }
Jim Grosbach7815f562012-02-03 00:07:04 +00002727
Jim Grosbach0ab54182012-02-03 00:00:50 +00002728 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
2729 !CallerPAL.isEmpty())
2730 // In this case we have more arguments than the new function type, but we
2731 // won't be dropping them. Check that these extra arguments have attributes
2732 // that are compatible with being a vararg call argument.
2733 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
Bill Wendling57625a42013-01-25 23:09:36 +00002734 unsigned Index = CallerPAL.getSlotIndex(i - 1);
2735 if (Index <= FT->getNumParams())
Jim Grosbach0ab54182012-02-03 00:00:50 +00002736 break;
Bill Wendling57625a42013-01-25 23:09:36 +00002737
Bill Wendlingd97b75d2012-12-19 08:57:40 +00002738 // Check if it has an attribute that's incompatible with varargs.
Bill Wendling57625a42013-01-25 23:09:36 +00002739 AttributeSet PAttrs = CallerPAL.getSlotAttributes(i - 1);
2740 if (PAttrs.hasAttribute(Index, Attribute::StructRet))
Jim Grosbach0ab54182012-02-03 00:00:50 +00002741 return false;
2742 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002743
Jim Grosbach7815f562012-02-03 00:07:04 +00002744
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002745 // Okay, we decided that this is a safe thing to do: go ahead and start
Chris Lattneradf38b32011-02-24 05:10:56 +00002746 // inserting cast instructions as necessary.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002747 std::vector<Value*> Args;
2748 Args.reserve(NumActualArgs);
Bill Wendling3575c8c2013-01-27 02:08:22 +00002749 SmallVector<AttributeSet, 8> attrVec;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002750 attrVec.reserve(NumCommonArgs);
2751
2752 // Get any return attributes.
Bill Wendling658d24d2013-01-18 21:53:16 +00002753 AttrBuilder RAttrs(CallerPAL, AttributeSet::ReturnIndex);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002754
2755 // If the return value is not being used, the type may not be compatible
2756 // with the existing attributes. Wipe out any problematic attributes.
Pete Cooper2777d8872015-05-06 23:19:56 +00002757 RAttrs.remove(AttributeFuncs::typeIncompatible(NewRetTy));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002758
2759 // Add the new return attributes.
Bill Wendling70f39172012-10-09 00:01:21 +00002760 if (RAttrs.hasAttributes())
Bill Wendling3575c8c2013-01-27 02:08:22 +00002761 attrVec.push_back(AttributeSet::get(Caller->getContext(),
2762 AttributeSet::ReturnIndex, RAttrs));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002763
2764 AI = CS.arg_begin();
2765 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
Chris Lattner229907c2011-07-18 04:54:35 +00002766 Type *ParamTy = FT->getParamType(i);
Matt Arsenaultcacbb232013-07-30 20:45:05 +00002767
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002768 if ((*AI)->getType() == ParamTy) {
2769 Args.push_back(*AI);
2770 } else {
David Majnemer9b6b8222015-01-06 08:41:31 +00002771 Args.push_back(Builder->CreateBitOrPointerCast(*AI, ParamTy));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002772 }
2773
2774 // Add any parameter attributes.
Bill Wendling49bc76c2013-01-23 06:14:59 +00002775 AttrBuilder PAttrs(CallerPAL.getParamAttributes(i + 1), i + 1);
Bill Wendling76d2cd22012-10-14 08:54:26 +00002776 if (PAttrs.hasAttributes())
Bill Wendling3575c8c2013-01-27 02:08:22 +00002777 attrVec.push_back(AttributeSet::get(Caller->getContext(), i + 1,
2778 PAttrs));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002779 }
2780
2781 // If the function takes more arguments than the call was taking, add them
2782 // now.
2783 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
2784 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
2785
2786 // If we are removing arguments to the function, emit an obnoxious warning.
2787 if (FT->getNumParams() < NumActualArgs) {
Nick Lewycky90053a12012-12-26 22:00:35 +00002788 // TODO: if (!FT->isVarArg()) this call may be unreachable. PR14722
2789 if (FT->isVarArg()) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002790 // Add all of the arguments in their promoted form to the arg list.
2791 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
Chris Lattner229907c2011-07-18 04:54:35 +00002792 Type *PTy = getPromotedType((*AI)->getType());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002793 if (PTy != (*AI)->getType()) {
2794 // Must promote to pass through va_arg area!
2795 Instruction::CastOps opcode =
2796 CastInst::getCastOpcode(*AI, false, PTy, false);
Benjamin Kramer547b6c52011-09-27 20:39:19 +00002797 Args.push_back(Builder->CreateCast(opcode, *AI, PTy));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002798 } else {
2799 Args.push_back(*AI);
2800 }
2801
2802 // Add any parameter attributes.
Bill Wendling49bc76c2013-01-23 06:14:59 +00002803 AttrBuilder PAttrs(CallerPAL.getParamAttributes(i + 1), i + 1);
Bill Wendling76d2cd22012-10-14 08:54:26 +00002804 if (PAttrs.hasAttributes())
Bill Wendling3575c8c2013-01-27 02:08:22 +00002805 attrVec.push_back(AttributeSet::get(FT->getContext(), i + 1,
2806 PAttrs));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002807 }
2808 }
2809 }
2810
Bill Wendlingbd4ea162013-01-21 21:57:28 +00002811 AttributeSet FnAttrs = CallerPAL.getFnAttributes();
Bill Wendling77543892013-01-18 21:11:39 +00002812 if (CallerPAL.hasAttributes(AttributeSet::FunctionIndex))
Bill Wendling3575c8c2013-01-27 02:08:22 +00002813 attrVec.push_back(AttributeSet::get(Callee->getContext(), FnAttrs));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002814
2815 if (NewRetTy->isVoidTy())
2816 Caller->setName(""); // Void type should not have a name.
2817
Bill Wendlinge94d8432012-12-07 23:16:57 +00002818 const AttributeSet &NewCallerPAL = AttributeSet::get(Callee->getContext(),
Bill Wendlingbd4ea162013-01-21 21:57:28 +00002819 attrVec);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002820
Sanjoy Das76293462015-11-25 00:42:19 +00002821 SmallVector<OperandBundleDef, 1> OpBundles;
Sanjoy Dasc521c7b2015-11-25 00:42:24 +00002822 CS.getOperandBundlesAsDefs(OpBundles);
Sanjoy Das76293462015-11-25 00:42:19 +00002823
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002824 Instruction *NC;
2825 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Sanjoy Das76293462015-11-25 00:42:19 +00002826 NC = Builder->CreateInvoke(Callee, II->getNormalDest(), II->getUnwindDest(),
2827 Args, OpBundles);
Eli Friedman96254a02011-05-18 01:28:27 +00002828 NC->takeName(II);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002829 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
2830 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
2831 } else {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002832 CallInst *CI = cast<CallInst>(Caller);
Sanjoy Das76293462015-11-25 00:42:19 +00002833 NC = Builder->CreateCall(Callee, Args, OpBundles);
Eli Friedman96254a02011-05-18 01:28:27 +00002834 NC->takeName(CI);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002835 if (CI->isTailCall())
2836 cast<CallInst>(NC)->setTailCall();
2837 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
2838 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
2839 }
2840
2841 // Insert a cast of the return type as necessary.
2842 Value *NV = NC;
2843 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
2844 if (!NV->getType()->isVoidTy()) {
David Majnemer9b6b8222015-01-06 08:41:31 +00002845 NV = NC = CastInst::CreateBitOrPointerCast(NC, OldRetTy);
Eli Friedman35211c62011-05-27 00:19:40 +00002846 NC->setDebugLoc(Caller->getDebugLoc());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002847
2848 // If this is an invoke instruction, we should insert it after the first
2849 // non-phi, instruction in the normal successor block.
2850 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Bill Wendling07efd6f2011-08-25 01:08:34 +00002851 BasicBlock::iterator I = II->getNormalDest()->getFirstInsertionPt();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002852 InsertNewInstBefore(NC, *I);
2853 } else {
Chris Lattner73989652010-12-20 08:25:06 +00002854 // Otherwise, it's a call, just insert cast right after the call.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002855 InsertNewInstBefore(NC, *Caller);
2856 }
2857 Worklist.AddUsersToWorkList(*Caller);
2858 } else {
2859 NV = UndefValue::get(Caller->getType());
2860 }
2861 }
2862
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002863 if (!Caller->use_empty())
Sanjay Patel4b198802016-02-01 22:23:39 +00002864 replaceInstUsesWith(*Caller, NV);
Frederic Rissc1892e22014-10-23 04:08:42 +00002865 else if (Caller->hasValueHandle()) {
2866 if (OldRetTy == NV->getType())
2867 ValueHandleBase::ValueIsRAUWd(Caller, NV);
2868 else
2869 // We cannot call ValueIsRAUWd with a different type, and the
2870 // actual tracked value will disappear.
2871 ValueHandleBase::ValueIsDeleted(Caller);
2872 }
Eli Friedmanb9ed18f2011-05-18 00:32:01 +00002873
Sanjay Patel4b198802016-02-01 22:23:39 +00002874 eraseInstFromFunction(*Caller);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002875 return true;
2876}
2877
Sanjay Patelcd4377c2016-01-20 22:24:38 +00002878/// Turn a call to a function created by init_trampoline / adjust_trampoline
2879/// intrinsic pair into a direct call to the underlying function.
Duncan Sandsa0984362011-09-06 13:37:06 +00002880Instruction *
2881InstCombiner::transformCallThroughTrampoline(CallSite CS,
2882 IntrinsicInst *Tramp) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002883 Value *Callee = CS.getCalledValue();
Chris Lattner229907c2011-07-18 04:54:35 +00002884 PointerType *PTy = cast<PointerType>(Callee->getType());
2885 FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Bill Wendlinge94d8432012-12-07 23:16:57 +00002886 const AttributeSet &Attrs = CS.getAttributes();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002887
2888 // If the call already has the 'nest' attribute somewhere then give up -
2889 // otherwise 'nest' would occur twice after splicing in the chain.
Bill Wendling6e95ae82012-12-31 00:49:59 +00002890 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Craig Topperf40110f2014-04-25 05:29:35 +00002891 return nullptr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002892
Duncan Sandsa0984362011-09-06 13:37:06 +00002893 assert(Tramp &&
2894 "transformCallThroughTrampoline called with incorrect CallSite.");
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002895
Gabor Greif3e44ea12010-07-22 10:37:47 +00002896 Function *NestF =cast<Function>(Tramp->getArgOperand(1)->stripPointerCasts());
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00002897 FunctionType *NestFTy = cast<FunctionType>(NestF->getValueType());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002898
Bill Wendlinge94d8432012-12-07 23:16:57 +00002899 const AttributeSet &NestAttrs = NestF->getAttributes();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002900 if (!NestAttrs.isEmpty()) {
2901 unsigned NestIdx = 1;
Craig Topperf40110f2014-04-25 05:29:35 +00002902 Type *NestTy = nullptr;
Bill Wendling49bc76c2013-01-23 06:14:59 +00002903 AttributeSet NestAttr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002904
2905 // Look for a parameter marked with the 'nest' attribute.
2906 for (FunctionType::param_iterator I = NestFTy->param_begin(),
2907 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Bill Wendling49bc76c2013-01-23 06:14:59 +00002908 if (NestAttrs.hasAttribute(NestIdx, Attribute::Nest)) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002909 // Record the parameter type and any other attributes.
2910 NestTy = *I;
2911 NestAttr = NestAttrs.getParamAttributes(NestIdx);
2912 break;
2913 }
2914
2915 if (NestTy) {
2916 Instruction *Caller = CS.getInstruction();
2917 std::vector<Value*> NewArgs;
Matt Arsenault5d2e85f2013-06-28 00:25:40 +00002918 NewArgs.reserve(CS.arg_size() + 1);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002919
Bill Wendling3575c8c2013-01-27 02:08:22 +00002920 SmallVector<AttributeSet, 8> NewAttrs;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002921 NewAttrs.reserve(Attrs.getNumSlots() + 1);
2922
2923 // Insert the nest argument into the call argument list, which may
2924 // mean appending it. Likewise for attributes.
2925
2926 // Add any result attributes.
Bill Wendling658d24d2013-01-18 21:53:16 +00002927 if (Attrs.hasAttributes(AttributeSet::ReturnIndex))
Bill Wendling3575c8c2013-01-27 02:08:22 +00002928 NewAttrs.push_back(AttributeSet::get(Caller->getContext(),
2929 Attrs.getRetAttributes()));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002930
2931 {
2932 unsigned Idx = 1;
2933 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
2934 do {
2935 if (Idx == NestIdx) {
2936 // Add the chain argument and attributes.
Gabor Greif589a0b92010-06-24 12:58:35 +00002937 Value *NestVal = Tramp->getArgOperand(2);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002938 if (NestVal->getType() != NestTy)
Eli Friedman41e509a2011-05-18 23:58:37 +00002939 NestVal = Builder->CreateBitCast(NestVal, NestTy, "nest");
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002940 NewArgs.push_back(NestVal);
Bill Wendling3575c8c2013-01-27 02:08:22 +00002941 NewAttrs.push_back(AttributeSet::get(Caller->getContext(),
2942 NestAttr));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002943 }
2944
2945 if (I == E)
2946 break;
2947
2948 // Add the original argument and attributes.
2949 NewArgs.push_back(*I);
Bill Wendling49bc76c2013-01-23 06:14:59 +00002950 AttributeSet Attr = Attrs.getParamAttributes(Idx);
2951 if (Attr.hasAttributes(Idx)) {
Bill Wendling3575c8c2013-01-27 02:08:22 +00002952 AttrBuilder B(Attr, Idx);
2953 NewAttrs.push_back(AttributeSet::get(Caller->getContext(),
2954 Idx + (Idx >= NestIdx), B));
Bill Wendling49bc76c2013-01-23 06:14:59 +00002955 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002956
Richard Trieu7a083812016-02-18 22:09:30 +00002957 ++Idx;
2958 ++I;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002959 } while (1);
2960 }
2961
2962 // Add any function attributes.
Bill Wendling77543892013-01-18 21:11:39 +00002963 if (Attrs.hasAttributes(AttributeSet::FunctionIndex))
Bill Wendling3575c8c2013-01-27 02:08:22 +00002964 NewAttrs.push_back(AttributeSet::get(FTy->getContext(),
2965 Attrs.getFnAttributes()));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002966
2967 // The trampoline may have been bitcast to a bogus type (FTy).
2968 // Handle this by synthesizing a new function type, equal to FTy
2969 // with the chain parameter inserted.
2970
Jay Foadb804a2b2011-07-12 14:06:48 +00002971 std::vector<Type*> NewTypes;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002972 NewTypes.reserve(FTy->getNumParams()+1);
2973
2974 // Insert the chain's type into the list of parameter types, which may
2975 // mean appending it.
2976 {
2977 unsigned Idx = 1;
2978 FunctionType::param_iterator I = FTy->param_begin(),
2979 E = FTy->param_end();
2980
2981 do {
2982 if (Idx == NestIdx)
2983 // Add the chain's type.
2984 NewTypes.push_back(NestTy);
2985
2986 if (I == E)
2987 break;
2988
2989 // Add the original type.
2990 NewTypes.push_back(*I);
2991
Richard Trieu7a083812016-02-18 22:09:30 +00002992 ++Idx;
2993 ++I;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002994 } while (1);
2995 }
2996
2997 // Replace the trampoline call with a direct call. Let the generic
2998 // code sort out any function type mismatches.
Jim Grosbach7815f562012-02-03 00:07:04 +00002999 FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003000 FTy->isVarArg());
3001 Constant *NewCallee =
3002 NestF->getType() == PointerType::getUnqual(NewFTy) ?
Jim Grosbach7815f562012-02-03 00:07:04 +00003003 NestF : ConstantExpr::getBitCast(NestF,
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003004 PointerType::getUnqual(NewFTy));
Jim Grosbachbdbd7342013-04-05 21:20:12 +00003005 const AttributeSet &NewPAL =
3006 AttributeSet::get(FTy->getContext(), NewAttrs);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003007
David Majnemer231a68c2016-04-29 08:07:20 +00003008 SmallVector<OperandBundleDef, 1> OpBundles;
3009 CS.getOperandBundlesAsDefs(OpBundles);
3010
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003011 Instruction *NewCaller;
3012 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
3013 NewCaller = InvokeInst::Create(NewCallee,
3014 II->getNormalDest(), II->getUnwindDest(),
David Majnemer231a68c2016-04-29 08:07:20 +00003015 NewArgs, OpBundles);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003016 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
3017 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
3018 } else {
David Majnemer231a68c2016-04-29 08:07:20 +00003019 NewCaller = CallInst::Create(NewCallee, NewArgs, OpBundles);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003020 if (cast<CallInst>(Caller)->isTailCall())
3021 cast<CallInst>(NewCaller)->setTailCall();
3022 cast<CallInst>(NewCaller)->
3023 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
3024 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
3025 }
Eli Friedman49346012011-05-18 19:57:14 +00003026
3027 return NewCaller;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003028 }
3029 }
3030
3031 // Replace the trampoline call with a direct call. Since there is no 'nest'
3032 // parameter, there is no need to adjust the argument list. Let the generic
3033 // code sort out any function type mismatches.
3034 Constant *NewCallee =
Jim Grosbach7815f562012-02-03 00:07:04 +00003035 NestF->getType() == PTy ? NestF :
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003036 ConstantExpr::getBitCast(NestF, PTy);
3037 CS.setCalledFunction(NewCallee);
3038 return CS.getInstruction();
3039}