blob: b5e206474e00506a11b716618c33ad4e72b52e94 [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"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000015#include "llvm/ADT/APFloat.h"
16#include "llvm/ADT/APInt.h"
17#include "llvm/ADT/ArrayRef.h"
18#include "llvm/ADT/None.h"
Meador Ingee3f2b262012-11-30 04:05:06 +000019#include "llvm/ADT/Statistic.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000020#include "llvm/ADT/STLExtras.h"
21#include "llvm/ADT/SmallVector.h"
22#include "llvm/ADT/Twine.h"
David Majnemer15032582015-05-22 03:56:46 +000023#include "llvm/Analysis/InstructionSimplify.h"
Chris Lattner7a9e47a2010-01-05 07:32:13 +000024#include "llvm/Analysis/MemoryBuiltins.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000025#include "llvm/Analysis/ValueTracking.h"
26#include "llvm/IR/BasicBlock.h"
Chandler Carruth219b89b2014-03-04 11:01:28 +000027#include "llvm/IR/CallSite.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000028#include "llvm/IR/Constant.h"
29#include "llvm/IR/DataLayout.h"
30#include "llvm/IR/DerivedTypes.h"
31#include "llvm/IR/Function.h"
32#include "llvm/IR/GlobalVariable.h"
33#include "llvm/IR/InstrTypes.h"
34#include "llvm/IR/Instruction.h"
35#include "llvm/IR/Instructions.h"
36#include "llvm/IR/IntrinsicInst.h"
37#include "llvm/IR/Intrinsics.h"
38#include "llvm/IR/LLVMContext.h"
39#include "llvm/IR/Metadata.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000040#include "llvm/IR/PatternMatch.h"
Philip Reames1a1bdb22014-12-02 18:50:36 +000041#include "llvm/IR/Statepoint.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000042#include "llvm/IR/Type.h"
43#include "llvm/IR/Value.h"
44#include "llvm/IR/ValueHandle.h"
45#include "llvm/Support/Casting.h"
46#include "llvm/Support/Debug.h"
47#include "llvm/Support/MathExtras.h"
Chris Lattner6fcd32e2010-12-25 20:37:57 +000048#include "llvm/Transforms/Utils/Local.h"
Chandler Carruthba4c5172015-01-21 11:23:40 +000049#include "llvm/Transforms/Utils/SimplifyLibCalls.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000050#include <algorithm>
51#include <cassert>
52#include <cstdint>
53#include <cstring>
54#include <vector>
55
Chris Lattner7a9e47a2010-01-05 07:32:13 +000056using namespace llvm;
Michael Ilseman536cc322012-12-13 03:13:36 +000057using namespace PatternMatch;
Chris Lattner7a9e47a2010-01-05 07:32:13 +000058
Chandler Carruth964daaa2014-04-22 02:55:47 +000059#define DEBUG_TYPE "instcombine"
60
Meador Ingee3f2b262012-11-30 04:05:06 +000061STATISTIC(NumSimplified, "Number of library calls simplified");
62
Sanjay Patelcd4377c2016-01-20 22:24:38 +000063/// Return the specified type promoted as it would be to pass though a va_arg
64/// area.
Chris Lattner229907c2011-07-18 04:54:35 +000065static Type *getPromotedType(Type *Ty) {
66 if (IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +000067 if (ITy->getBitWidth() < 32)
68 return Type::getInt32Ty(Ty->getContext());
69 }
70 return Ty;
71}
72
Sanjay Patelcd4377c2016-01-20 22:24:38 +000073/// Given an aggregate type which ultimately holds a single scalar element,
74/// like {{{type}}} or [1 x type], return type.
Dan Gohmand0080c42012-09-13 18:19:06 +000075static Type *reduceToSingleValueType(Type *T) {
76 while (!T->isSingleValueType()) {
77 if (StructType *STy = dyn_cast<StructType>(T)) {
78 if (STy->getNumElements() == 1)
79 T = STy->getElementType(0);
80 else
81 break;
82 } else if (ArrayType *ATy = dyn_cast<ArrayType>(T)) {
83 if (ATy->getNumElements() == 1)
84 T = ATy->getElementType();
85 else
86 break;
87 } else
88 break;
89 }
90
91 return T;
92}
Chris Lattner7a9e47a2010-01-05 07:32:13 +000093
Sanjay Patel368ac5d2016-02-21 17:29:33 +000094/// Return a constant boolean vector that has true elements in all positions
Sanjay Patel24401302016-02-21 17:33:31 +000095/// where the input constant data vector has an element with the sign bit set.
Sanjay Patel368ac5d2016-02-21 17:29:33 +000096static Constant *getNegativeIsTrueBoolVec(ConstantDataVector *V) {
97 SmallVector<Constant *, 32> BoolVec;
98 IntegerType *BoolTy = Type::getInt1Ty(V->getContext());
99 for (unsigned I = 0, E = V->getNumElements(); I != E; ++I) {
100 Constant *Elt = V->getElementAsConstant(I);
101 assert((isa<ConstantInt>(Elt) || isa<ConstantFP>(Elt)) &&
102 "Unexpected constant data vector element type");
103 bool Sign = V->getElementType()->isIntegerTy()
104 ? cast<ConstantInt>(Elt)->isNegative()
105 : cast<ConstantFP>(Elt)->isNegative();
106 BoolVec.push_back(ConstantInt::get(BoolTy, Sign));
107 }
108 return ConstantVector::get(BoolVec);
109}
110
Pete Cooper67cf9a72015-11-19 05:56:52 +0000111Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Justin Bogner99798402016-08-05 01:06:44 +0000112 unsigned DstAlign = getKnownAlignment(MI->getArgOperand(0), DL, MI, &AC, &DT);
113 unsigned SrcAlign = getKnownAlignment(MI->getArgOperand(1), DL, MI, &AC, &DT);
Pete Cooper67cf9a72015-11-19 05:56:52 +0000114 unsigned MinAlign = std::min(DstAlign, SrcAlign);
115 unsigned CopyAlign = MI->getAlignment();
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000116
Pete Cooper67cf9a72015-11-19 05:56:52 +0000117 if (CopyAlign < MinAlign) {
118 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(), MinAlign, false));
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000119 return MI;
120 }
Jim Grosbach7815f562012-02-03 00:07:04 +0000121
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000122 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
123 // load/store.
Gabor Greif0a136c92010-06-24 13:54:33 +0000124 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getArgOperand(2));
Craig Topperf40110f2014-04-25 05:29:35 +0000125 if (!MemOpLength) return nullptr;
Jim Grosbach7815f562012-02-03 00:07:04 +0000126
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000127 // Source and destination pointer types are always "i8*" for intrinsic. See
128 // if the size is something we can handle with a single primitive load/store.
129 // A single load+store correctly handles overlapping memory in the memmove
130 // case.
Michael Liao69e172a2012-08-15 03:49:59 +0000131 uint64_t Size = MemOpLength->getLimitedValue();
Alp Tokercb402912014-01-24 17:20:08 +0000132 assert(Size && "0-sized memory transferring should be removed already.");
Jim Grosbach7815f562012-02-03 00:07:04 +0000133
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000134 if (Size > 8 || (Size&(Size-1)))
Craig Topperf40110f2014-04-25 05:29:35 +0000135 return nullptr; // If not 1/2/4/8 bytes, exit.
Jim Grosbach7815f562012-02-03 00:07:04 +0000136
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000137 // Use an integer load+store unless we can find something better.
Mon P Wangc576ee92010-04-04 03:10:48 +0000138 unsigned SrcAddrSp =
Gabor Greif0a136c92010-06-24 13:54:33 +0000139 cast<PointerType>(MI->getArgOperand(1)->getType())->getAddressSpace();
Gabor Greiff3755202010-04-16 15:33:14 +0000140 unsigned DstAddrSp =
Gabor Greif0a136c92010-06-24 13:54:33 +0000141 cast<PointerType>(MI->getArgOperand(0)->getType())->getAddressSpace();
Mon P Wangc576ee92010-04-04 03:10:48 +0000142
Chris Lattner229907c2011-07-18 04:54:35 +0000143 IntegerType* IntType = IntegerType::get(MI->getContext(), Size<<3);
Mon P Wangc576ee92010-04-04 03:10:48 +0000144 Type *NewSrcPtrTy = PointerType::get(IntType, SrcAddrSp);
145 Type *NewDstPtrTy = PointerType::get(IntType, DstAddrSp);
Jim Grosbach7815f562012-02-03 00:07:04 +0000146
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000147 // Memcpy forces the use of i8* for the source and destination. That means
148 // that if you're using memcpy to move one double around, you'll get a cast
149 // from double* to i8*. We'd much rather use a double load+store rather than
150 // an i64 load+store, here because this improves the odds that the source or
151 // dest address will be promotable. See if we can find a better type than the
152 // integer datatype.
Gabor Greif589a0b92010-06-24 12:58:35 +0000153 Value *StrippedDest = MI->getArgOperand(0)->stripPointerCasts();
Craig Topperf40110f2014-04-25 05:29:35 +0000154 MDNode *CopyMD = nullptr;
Gabor Greif589a0b92010-06-24 12:58:35 +0000155 if (StrippedDest != MI->getArgOperand(0)) {
Chris Lattner229907c2011-07-18 04:54:35 +0000156 Type *SrcETy = cast<PointerType>(StrippedDest->getType())
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000157 ->getElementType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000158 if (SrcETy->isSized() && DL.getTypeStoreSize(SrcETy) == Size) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000159 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
160 // down through these levels if so.
Dan Gohmand0080c42012-09-13 18:19:06 +0000161 SrcETy = reduceToSingleValueType(SrcETy);
Jim Grosbach7815f562012-02-03 00:07:04 +0000162
Mon P Wangc576ee92010-04-04 03:10:48 +0000163 if (SrcETy->isSingleValueType()) {
164 NewSrcPtrTy = PointerType::get(SrcETy, SrcAddrSp);
165 NewDstPtrTy = PointerType::get(SrcETy, DstAddrSp);
Dan Gohman3f553c22012-09-13 21:51:01 +0000166
167 // If the memcpy has metadata describing the members, see if we can
168 // get the TBAA tag describing our copy.
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000169 if (MDNode *M = MI->getMetadata(LLVMContext::MD_tbaa_struct)) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000170 if (M->getNumOperands() == 3 && M->getOperand(0) &&
171 mdconst::hasa<ConstantInt>(M->getOperand(0)) &&
172 mdconst::extract<ConstantInt>(M->getOperand(0))->isNullValue() &&
Nick Lewycky49ac81a2012-10-11 02:05:23 +0000173 M->getOperand(1) &&
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000174 mdconst::hasa<ConstantInt>(M->getOperand(1)) &&
175 mdconst::extract<ConstantInt>(M->getOperand(1))->getValue() ==
176 Size &&
177 M->getOperand(2) && isa<MDNode>(M->getOperand(2)))
Dan Gohman3f553c22012-09-13 21:51:01 +0000178 CopyMD = cast<MDNode>(M->getOperand(2));
179 }
Mon P Wangc576ee92010-04-04 03:10:48 +0000180 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000181 }
182 }
Jim Grosbach7815f562012-02-03 00:07:04 +0000183
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000184 // If the memcpy/memmove provides better alignment info than we can
185 // infer, use it.
Pete Cooper67cf9a72015-11-19 05:56:52 +0000186 SrcAlign = std::max(SrcAlign, CopyAlign);
187 DstAlign = std::max(DstAlign, CopyAlign);
Jim Grosbach7815f562012-02-03 00:07:04 +0000188
Gabor Greif5f3e6562010-06-25 07:57:14 +0000189 Value *Src = Builder->CreateBitCast(MI->getArgOperand(1), NewSrcPtrTy);
190 Value *Dest = Builder->CreateBitCast(MI->getArgOperand(0), NewDstPtrTy);
Eli Friedman49346012011-05-18 19:57:14 +0000191 LoadInst *L = Builder->CreateLoad(Src, MI->isVolatile());
192 L->setAlignment(SrcAlign);
Dan Gohman3f553c22012-09-13 21:51:01 +0000193 if (CopyMD)
194 L->setMetadata(LLVMContext::MD_tbaa, CopyMD);
Dorit Nuzman7673ba72016-09-04 07:06:00 +0000195
Eli Friedman49346012011-05-18 19:57:14 +0000196 StoreInst *S = Builder->CreateStore(L, Dest, MI->isVolatile());
197 S->setAlignment(DstAlign);
Dan Gohman3f553c22012-09-13 21:51:01 +0000198 if (CopyMD)
199 S->setMetadata(LLVMContext::MD_tbaa, CopyMD);
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000200
201 // Set the size of the copy to 0, it will be deleted on the next iteration.
Gabor Greif5b1370e2010-06-28 16:50:57 +0000202 MI->setArgOperand(2, Constant::getNullValue(MemOpLength->getType()));
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000203 return MI;
204}
205
206Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
Justin Bogner99798402016-08-05 01:06:44 +0000207 unsigned Alignment = getKnownAlignment(MI->getDest(), DL, MI, &AC, &DT);
Pete Cooper67cf9a72015-11-19 05:56:52 +0000208 if (MI->getAlignment() < Alignment) {
209 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
210 Alignment, false));
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000211 return MI;
212 }
Jim Grosbach7815f562012-02-03 00:07:04 +0000213
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000214 // Extract the length and alignment and fill if they are constant.
215 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
216 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
Duncan Sands9dff9be2010-02-15 16:12:20 +0000217 if (!LenC || !FillC || !FillC->getType()->isIntegerTy(8))
Craig Topperf40110f2014-04-25 05:29:35 +0000218 return nullptr;
Michael Liao69e172a2012-08-15 03:49:59 +0000219 uint64_t Len = LenC->getLimitedValue();
Pete Cooper67cf9a72015-11-19 05:56:52 +0000220 Alignment = MI->getAlignment();
Michael Liao69e172a2012-08-15 03:49:59 +0000221 assert(Len && "0-sized memory setting should be removed already.");
Jim Grosbach7815f562012-02-03 00:07:04 +0000222
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000223 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
224 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
Chris Lattner229907c2011-07-18 04:54:35 +0000225 Type *ITy = IntegerType::get(MI->getContext(), Len*8); // n=1 -> i8.
Jim Grosbach7815f562012-02-03 00:07:04 +0000226
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000227 Value *Dest = MI->getDest();
Mon P Wang1991c472010-12-20 01:05:30 +0000228 unsigned DstAddrSp = cast<PointerType>(Dest->getType())->getAddressSpace();
229 Type *NewDstPtrTy = PointerType::get(ITy, DstAddrSp);
230 Dest = Builder->CreateBitCast(Dest, NewDstPtrTy);
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000231
232 // Alignment 0 is identity for alignment 1 for memset, but not store.
233 if (Alignment == 0) Alignment = 1;
Jim Grosbach7815f562012-02-03 00:07:04 +0000234
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000235 // Extract the fill value and store.
236 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
Eli Friedman49346012011-05-18 19:57:14 +0000237 StoreInst *S = Builder->CreateStore(ConstantInt::get(ITy, Fill), Dest,
238 MI->isVolatile());
239 S->setAlignment(Alignment);
Jim Grosbach7815f562012-02-03 00:07:04 +0000240
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000241 // Set the size of the copy to 0, it will be deleted on the next iteration.
242 MI->setLength(Constant::getNullValue(LenC->getType()));
243 return MI;
244 }
245
Simon Pilgrim18617d12015-08-05 08:18:00 +0000246 return nullptr;
247}
248
Sanjay Patel6038d3e2016-01-29 23:27:03 +0000249static Value *simplifyX86immShift(const IntrinsicInst &II,
Simon Pilgrimbecd5e82015-08-13 07:39:03 +0000250 InstCombiner::BuilderTy &Builder) {
251 bool LogicalShift = false;
252 bool ShiftLeft = false;
253
254 switch (II.getIntrinsicID()) {
255 default:
256 return nullptr;
257 case Intrinsic::x86_sse2_psra_d:
258 case Intrinsic::x86_sse2_psra_w:
259 case Intrinsic::x86_sse2_psrai_d:
260 case Intrinsic::x86_sse2_psrai_w:
261 case Intrinsic::x86_avx2_psra_d:
262 case Intrinsic::x86_avx2_psra_w:
263 case Intrinsic::x86_avx2_psrai_d:
264 case Intrinsic::x86_avx2_psrai_w:
265 LogicalShift = false; ShiftLeft = false;
266 break;
267 case Intrinsic::x86_sse2_psrl_d:
268 case Intrinsic::x86_sse2_psrl_q:
269 case Intrinsic::x86_sse2_psrl_w:
270 case Intrinsic::x86_sse2_psrli_d:
271 case Intrinsic::x86_sse2_psrli_q:
272 case Intrinsic::x86_sse2_psrli_w:
273 case Intrinsic::x86_avx2_psrl_d:
274 case Intrinsic::x86_avx2_psrl_q:
275 case Intrinsic::x86_avx2_psrl_w:
276 case Intrinsic::x86_avx2_psrli_d:
277 case Intrinsic::x86_avx2_psrli_q:
278 case Intrinsic::x86_avx2_psrli_w:
279 LogicalShift = true; ShiftLeft = false;
280 break;
281 case Intrinsic::x86_sse2_psll_d:
282 case Intrinsic::x86_sse2_psll_q:
283 case Intrinsic::x86_sse2_psll_w:
284 case Intrinsic::x86_sse2_pslli_d:
285 case Intrinsic::x86_sse2_pslli_q:
286 case Intrinsic::x86_sse2_pslli_w:
287 case Intrinsic::x86_avx2_psll_d:
288 case Intrinsic::x86_avx2_psll_q:
289 case Intrinsic::x86_avx2_psll_w:
290 case Intrinsic::x86_avx2_pslli_d:
291 case Intrinsic::x86_avx2_pslli_q:
292 case Intrinsic::x86_avx2_pslli_w:
293 LogicalShift = true; ShiftLeft = true;
294 break;
295 }
Simon Pilgrima3a72b42015-08-10 20:21:15 +0000296 assert((LogicalShift || !ShiftLeft) && "Only logical shifts can shift left");
297
Simon Pilgrim3815c162015-08-07 18:22:50 +0000298 // Simplify if count is constant.
299 auto Arg1 = II.getArgOperand(1);
300 auto CAZ = dyn_cast<ConstantAggregateZero>(Arg1);
301 auto CDV = dyn_cast<ConstantDataVector>(Arg1);
302 auto CInt = dyn_cast<ConstantInt>(Arg1);
303 if (!CAZ && !CDV && !CInt)
Simon Pilgrim18617d12015-08-05 08:18:00 +0000304 return nullptr;
Simon Pilgrim3815c162015-08-07 18:22:50 +0000305
306 APInt Count(64, 0);
307 if (CDV) {
308 // SSE2/AVX2 uses all the first 64-bits of the 128-bit vector
309 // operand to compute the shift amount.
310 auto VT = cast<VectorType>(CDV->getType());
311 unsigned BitWidth = VT->getElementType()->getPrimitiveSizeInBits();
312 assert((64 % BitWidth) == 0 && "Unexpected packed shift size");
313 unsigned NumSubElts = 64 / BitWidth;
314
315 // Concatenate the sub-elements to create the 64-bit value.
316 for (unsigned i = 0; i != NumSubElts; ++i) {
317 unsigned SubEltIdx = (NumSubElts - 1) - i;
318 auto SubElt = cast<ConstantInt>(CDV->getElementAsConstant(SubEltIdx));
319 Count = Count.shl(BitWidth);
320 Count |= SubElt->getValue().zextOrTrunc(64);
321 }
322 }
323 else if (CInt)
324 Count = CInt->getValue();
Simon Pilgrim18617d12015-08-05 08:18:00 +0000325
326 auto Vec = II.getArgOperand(0);
327 auto VT = cast<VectorType>(Vec->getType());
328 auto SVT = VT->getElementType();
Simon Pilgrim3815c162015-08-07 18:22:50 +0000329 unsigned VWidth = VT->getNumElements();
330 unsigned BitWidth = SVT->getPrimitiveSizeInBits();
331
332 // If shift-by-zero then just return the original value.
333 if (Count == 0)
334 return Vec;
335
Simon Pilgrima3a72b42015-08-10 20:21:15 +0000336 // Handle cases when Shift >= BitWidth.
337 if (Count.uge(BitWidth)) {
338 // If LogicalShift - just return zero.
339 if (LogicalShift)
340 return ConstantAggregateZero::get(VT);
341
342 // If ArithmeticShift - clamp Shift to (BitWidth - 1).
343 Count = APInt(64, BitWidth - 1);
344 }
Simon Pilgrim18617d12015-08-05 08:18:00 +0000345
Simon Pilgrim18617d12015-08-05 08:18:00 +0000346 // Get a constant vector of the same type as the first operand.
Simon Pilgrim3815c162015-08-07 18:22:50 +0000347 auto ShiftAmt = ConstantInt::get(SVT, Count.zextOrTrunc(BitWidth));
348 auto ShiftVec = Builder.CreateVectorSplat(VWidth, ShiftAmt);
Simon Pilgrim18617d12015-08-05 08:18:00 +0000349
350 if (ShiftLeft)
Simon Pilgrim3815c162015-08-07 18:22:50 +0000351 return Builder.CreateShl(Vec, ShiftVec);
Simon Pilgrim18617d12015-08-05 08:18:00 +0000352
Simon Pilgrima3a72b42015-08-10 20:21:15 +0000353 if (LogicalShift)
354 return Builder.CreateLShr(Vec, ShiftVec);
355
356 return Builder.CreateAShr(Vec, ShiftVec);
Simon Pilgrim18617d12015-08-05 08:18:00 +0000357}
358
Simon Pilgrimdb9893f2016-06-07 10:27:15 +0000359// Attempt to simplify AVX2 per-element shift intrinsics to a generic IR shift.
360// Unlike the generic IR shifts, the intrinsics have defined behaviour for out
361// of range shift amounts (logical - set to zero, arithmetic - splat sign bit).
362static Value *simplifyX86varShift(const IntrinsicInst &II,
363 InstCombiner::BuilderTy &Builder) {
364 bool LogicalShift = false;
365 bool ShiftLeft = false;
366
367 switch (II.getIntrinsicID()) {
368 default:
369 return nullptr;
370 case Intrinsic::x86_avx2_psrav_d:
371 case Intrinsic::x86_avx2_psrav_d_256:
372 LogicalShift = false;
373 ShiftLeft = false;
374 break;
375 case Intrinsic::x86_avx2_psrlv_d:
376 case Intrinsic::x86_avx2_psrlv_d_256:
377 case Intrinsic::x86_avx2_psrlv_q:
378 case Intrinsic::x86_avx2_psrlv_q_256:
379 LogicalShift = true;
380 ShiftLeft = false;
381 break;
382 case Intrinsic::x86_avx2_psllv_d:
383 case Intrinsic::x86_avx2_psllv_d_256:
384 case Intrinsic::x86_avx2_psllv_q:
385 case Intrinsic::x86_avx2_psllv_q_256:
386 LogicalShift = true;
387 ShiftLeft = true;
388 break;
389 }
390 assert((LogicalShift || !ShiftLeft) && "Only logical shifts can shift left");
391
392 // Simplify if all shift amounts are constant/undef.
393 auto *CShift = dyn_cast<Constant>(II.getArgOperand(1));
394 if (!CShift)
395 return nullptr;
396
397 auto Vec = II.getArgOperand(0);
398 auto VT = cast<VectorType>(II.getType());
399 auto SVT = VT->getVectorElementType();
400 int NumElts = VT->getNumElements();
401 int BitWidth = SVT->getIntegerBitWidth();
402
403 // Collect each element's shift amount.
404 // We also collect special cases: UNDEF = -1, OUT-OF-RANGE = BitWidth.
405 bool AnyOutOfRange = false;
406 SmallVector<int, 8> ShiftAmts;
407 for (int I = 0; I < NumElts; ++I) {
408 auto *CElt = CShift->getAggregateElement(I);
409 if (CElt && isa<UndefValue>(CElt)) {
410 ShiftAmts.push_back(-1);
411 continue;
412 }
413
414 auto *COp = dyn_cast_or_null<ConstantInt>(CElt);
415 if (!COp)
416 return nullptr;
417
418 // Handle out of range shifts.
419 // If LogicalShift - set to BitWidth (special case).
420 // If ArithmeticShift - set to (BitWidth - 1) (sign splat).
421 APInt ShiftVal = COp->getValue();
422 if (ShiftVal.uge(BitWidth)) {
423 AnyOutOfRange = LogicalShift;
424 ShiftAmts.push_back(LogicalShift ? BitWidth : BitWidth - 1);
425 continue;
426 }
427
428 ShiftAmts.push_back((int)ShiftVal.getZExtValue());
429 }
430
431 // If all elements out of range or UNDEF, return vector of zeros/undefs.
432 // ArithmeticShift should only hit this if they are all UNDEF.
433 auto OutOfRange = [&](int Idx) { return (Idx < 0) || (BitWidth <= Idx); };
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000434 if (all_of(ShiftAmts, OutOfRange)) {
Simon Pilgrimdb9893f2016-06-07 10:27:15 +0000435 SmallVector<Constant *, 8> ConstantVec;
436 for (int Idx : ShiftAmts) {
437 if (Idx < 0) {
438 ConstantVec.push_back(UndefValue::get(SVT));
439 } else {
440 assert(LogicalShift && "Logical shift expected");
441 ConstantVec.push_back(ConstantInt::getNullValue(SVT));
442 }
443 }
444 return ConstantVector::get(ConstantVec);
445 }
446
447 // We can't handle only some out of range values with generic logical shifts.
448 if (AnyOutOfRange)
449 return nullptr;
450
451 // Build the shift amount constant vector.
452 SmallVector<Constant *, 8> ShiftVecAmts;
453 for (int Idx : ShiftAmts) {
454 if (Idx < 0)
455 ShiftVecAmts.push_back(UndefValue::get(SVT));
456 else
457 ShiftVecAmts.push_back(ConstantInt::get(SVT, Idx));
458 }
459 auto ShiftVec = ConstantVector::get(ShiftVecAmts);
460
461 if (ShiftLeft)
462 return Builder.CreateShl(Vec, ShiftVec);
463
464 if (LogicalShift)
465 return Builder.CreateLShr(Vec, ShiftVec);
466
467 return Builder.CreateAShr(Vec, ShiftVec);
468}
469
Simon Pilgrim91e3ac82016-06-07 08:18:35 +0000470static Value *simplifyX86movmsk(const IntrinsicInst &II,
471 InstCombiner::BuilderTy &Builder) {
472 Value *Arg = II.getArgOperand(0);
473 Type *ResTy = II.getType();
474 Type *ArgTy = Arg->getType();
475
476 // movmsk(undef) -> zero as we must ensure the upper bits are zero.
477 if (isa<UndefValue>(Arg))
478 return Constant::getNullValue(ResTy);
479
480 // We can't easily peek through x86_mmx types.
481 if (!ArgTy->isVectorTy())
482 return nullptr;
483
484 auto *C = dyn_cast<Constant>(Arg);
485 if (!C)
486 return nullptr;
487
488 // Extract signbits of the vector input and pack into integer result.
489 APInt Result(ResTy->getPrimitiveSizeInBits(), 0);
490 for (unsigned I = 0, E = ArgTy->getVectorNumElements(); I != E; ++I) {
491 auto *COp = C->getAggregateElement(I);
492 if (!COp)
493 return nullptr;
494 if (isa<UndefValue>(COp))
495 continue;
496
497 auto *CInt = dyn_cast<ConstantInt>(COp);
498 auto *CFp = dyn_cast<ConstantFP>(COp);
499 if (!CInt && !CFp)
500 return nullptr;
501
502 if ((CInt && CInt->isNegative()) || (CFp && CFp->isNegative()))
503 Result.setBit(I);
504 }
505
506 return Constant::getIntegerValue(ResTy, Result);
507}
508
Sanjay Patel6038d3e2016-01-29 23:27:03 +0000509static Value *simplifyX86insertps(const IntrinsicInst &II,
Sanjay Patelc86867c2015-04-16 17:52:13 +0000510 InstCombiner::BuilderTy &Builder) {
Sanjay Patel03c03f52016-01-28 00:03:16 +0000511 auto *CInt = dyn_cast<ConstantInt>(II.getArgOperand(2));
512 if (!CInt)
513 return nullptr;
Simon Pilgrim54fcd622015-07-25 20:41:00 +0000514
Sanjay Patel03c03f52016-01-28 00:03:16 +0000515 VectorType *VecTy = cast<VectorType>(II.getType());
516 assert(VecTy->getNumElements() == 4 && "insertps with wrong vector type");
Sanjay Patelc86867c2015-04-16 17:52:13 +0000517
Sanjay Patel03c03f52016-01-28 00:03:16 +0000518 // The immediate permute control byte looks like this:
519 // [3:0] - zero mask for each 32-bit lane
520 // [5:4] - select one 32-bit destination lane
521 // [7:6] - select one 32-bit source lane
Sanjay Patelc86867c2015-04-16 17:52:13 +0000522
Sanjay Patel03c03f52016-01-28 00:03:16 +0000523 uint8_t Imm = CInt->getZExtValue();
524 uint8_t ZMask = Imm & 0xf;
525 uint8_t DestLane = (Imm >> 4) & 0x3;
526 uint8_t SourceLane = (Imm >> 6) & 0x3;
Sanjay Patelc1d20a32015-04-25 20:55:25 +0000527
Sanjay Patel03c03f52016-01-28 00:03:16 +0000528 ConstantAggregateZero *ZeroVector = ConstantAggregateZero::get(VecTy);
Sanjay Patelc86867c2015-04-16 17:52:13 +0000529
Sanjay Patel03c03f52016-01-28 00:03:16 +0000530 // If all zero mask bits are set, this was just a weird way to
531 // generate a zero vector.
532 if (ZMask == 0xf)
533 return ZeroVector;
Sanjay Patelc1d20a32015-04-25 20:55:25 +0000534
Sanjay Patel03c03f52016-01-28 00:03:16 +0000535 // Initialize by passing all of the first source bits through.
Craig Topper99d1eab2016-06-12 00:41:19 +0000536 uint32_t ShuffleMask[4] = { 0, 1, 2, 3 };
Sanjay Patelc1d20a32015-04-25 20:55:25 +0000537
Sanjay Patel03c03f52016-01-28 00:03:16 +0000538 // We may replace the second operand with the zero vector.
539 Value *V1 = II.getArgOperand(1);
540
541 if (ZMask) {
542 // If the zero mask is being used with a single input or the zero mask
543 // overrides the destination lane, this is a shuffle with the zero vector.
544 if ((II.getArgOperand(0) == II.getArgOperand(1)) ||
545 (ZMask & (1 << DestLane))) {
546 V1 = ZeroVector;
547 // We may still move 32-bits of the first source vector from one lane
548 // to another.
549 ShuffleMask[DestLane] = SourceLane;
550 // The zero mask may override the previous insert operation.
551 for (unsigned i = 0; i < 4; ++i)
552 if ((ZMask >> i) & 0x1)
553 ShuffleMask[i] = i + 4;
Sanjay Patelc1d20a32015-04-25 20:55:25 +0000554 } else {
Sanjay Patel03c03f52016-01-28 00:03:16 +0000555 // TODO: Model this case as 2 shuffles or a 'logical and' plus shuffle?
556 return nullptr;
Sanjay Patelc1d20a32015-04-25 20:55:25 +0000557 }
Sanjay Patel03c03f52016-01-28 00:03:16 +0000558 } else {
559 // Replace the selected destination lane with the selected source lane.
560 ShuffleMask[DestLane] = SourceLane + 4;
Sanjay Patelc86867c2015-04-16 17:52:13 +0000561 }
Sanjay Patel03c03f52016-01-28 00:03:16 +0000562
563 return Builder.CreateShuffleVector(II.getArgOperand(0), V1, ShuffleMask);
Sanjay Patelc86867c2015-04-16 17:52:13 +0000564}
565
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000566/// Attempt to simplify SSE4A EXTRQ/EXTRQI instructions using constant folding
567/// or conversion to a shuffle vector.
Sanjay Patel6038d3e2016-01-29 23:27:03 +0000568static Value *simplifyX86extrq(IntrinsicInst &II, Value *Op0,
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000569 ConstantInt *CILength, ConstantInt *CIIndex,
570 InstCombiner::BuilderTy &Builder) {
571 auto LowConstantHighUndef = [&](uint64_t Val) {
572 Type *IntTy64 = Type::getInt64Ty(II.getContext());
573 Constant *Args[] = {ConstantInt::get(IntTy64, Val),
574 UndefValue::get(IntTy64)};
575 return ConstantVector::get(Args);
576 };
577
578 // See if we're dealing with constant values.
579 Constant *C0 = dyn_cast<Constant>(Op0);
580 ConstantInt *CI0 =
581 C0 ? dyn_cast<ConstantInt>(C0->getAggregateElement((unsigned)0))
582 : nullptr;
583
584 // Attempt to constant fold.
585 if (CILength && CIIndex) {
586 // From AMD documentation: "The bit index and field length are each six
587 // bits in length other bits of the field are ignored."
588 APInt APIndex = CIIndex->getValue().zextOrTrunc(6);
589 APInt APLength = CILength->getValue().zextOrTrunc(6);
590
591 unsigned Index = APIndex.getZExtValue();
592
593 // From AMD documentation: "a value of zero in the field length is
594 // defined as length of 64".
595 unsigned Length = APLength == 0 ? 64 : APLength.getZExtValue();
596
597 // From AMD documentation: "If the sum of the bit index + length field
598 // is greater than 64, the results are undefined".
599 unsigned End = Index + Length;
600
601 // Note that both field index and field length are 8-bit quantities.
602 // Since variables 'Index' and 'Length' are unsigned values
603 // obtained from zero-extending field index and field length
604 // respectively, their sum should never wrap around.
605 if (End > 64)
606 return UndefValue::get(II.getType());
607
608 // If we are inserting whole bytes, we can convert this to a shuffle.
609 // Lowering can recognize EXTRQI shuffle masks.
610 if ((Length % 8) == 0 && (Index % 8) == 0) {
611 // Convert bit indices to byte indices.
612 Length /= 8;
613 Index /= 8;
614
615 Type *IntTy8 = Type::getInt8Ty(II.getContext());
616 Type *IntTy32 = Type::getInt32Ty(II.getContext());
617 VectorType *ShufTy = VectorType::get(IntTy8, 16);
618
619 SmallVector<Constant *, 16> ShuffleMask;
620 for (int i = 0; i != (int)Length; ++i)
621 ShuffleMask.push_back(
622 Constant::getIntegerValue(IntTy32, APInt(32, i + Index)));
623 for (int i = Length; i != 8; ++i)
624 ShuffleMask.push_back(
625 Constant::getIntegerValue(IntTy32, APInt(32, i + 16)));
626 for (int i = 8; i != 16; ++i)
627 ShuffleMask.push_back(UndefValue::get(IntTy32));
628
629 Value *SV = Builder.CreateShuffleVector(
630 Builder.CreateBitCast(Op0, ShufTy),
631 ConstantAggregateZero::get(ShufTy), ConstantVector::get(ShuffleMask));
632 return Builder.CreateBitCast(SV, II.getType());
633 }
634
635 // Constant Fold - shift Index'th bit to lowest position and mask off
636 // Length bits.
637 if (CI0) {
638 APInt Elt = CI0->getValue();
639 Elt = Elt.lshr(Index).zextOrTrunc(Length);
640 return LowConstantHighUndef(Elt.getZExtValue());
641 }
642
643 // If we were an EXTRQ call, we'll save registers if we convert to EXTRQI.
644 if (II.getIntrinsicID() == Intrinsic::x86_sse4a_extrq) {
645 Value *Args[] = {Op0, CILength, CIIndex};
Sanjay Patelaf674fb2015-12-14 17:24:23 +0000646 Module *M = II.getModule();
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000647 Value *F = Intrinsic::getDeclaration(M, Intrinsic::x86_sse4a_extrqi);
648 return Builder.CreateCall(F, Args);
649 }
650 }
651
652 // Constant Fold - extraction from zero is always {zero, undef}.
653 if (CI0 && CI0->equalsInt(0))
654 return LowConstantHighUndef(0);
655
656 return nullptr;
657}
658
659/// Attempt to simplify SSE4A INSERTQ/INSERTQI instructions using constant
660/// folding or conversion to a shuffle vector.
Sanjay Patel6038d3e2016-01-29 23:27:03 +0000661static Value *simplifyX86insertq(IntrinsicInst &II, Value *Op0, Value *Op1,
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000662 APInt APLength, APInt APIndex,
663 InstCombiner::BuilderTy &Builder) {
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000664 // From AMD documentation: "The bit index and field length are each six bits
665 // in length other bits of the field are ignored."
666 APIndex = APIndex.zextOrTrunc(6);
667 APLength = APLength.zextOrTrunc(6);
668
669 // Attempt to constant fold.
670 unsigned Index = APIndex.getZExtValue();
671
672 // From AMD documentation: "a value of zero in the field length is
673 // defined as length of 64".
674 unsigned Length = APLength == 0 ? 64 : APLength.getZExtValue();
675
676 // From AMD documentation: "If the sum of the bit index + length field
677 // is greater than 64, the results are undefined".
678 unsigned End = Index + Length;
679
680 // Note that both field index and field length are 8-bit quantities.
681 // Since variables 'Index' and 'Length' are unsigned values
682 // obtained from zero-extending field index and field length
683 // respectively, their sum should never wrap around.
684 if (End > 64)
685 return UndefValue::get(II.getType());
686
687 // If we are inserting whole bytes, we can convert this to a shuffle.
688 // Lowering can recognize INSERTQI shuffle masks.
689 if ((Length % 8) == 0 && (Index % 8) == 0) {
690 // Convert bit indices to byte indices.
691 Length /= 8;
692 Index /= 8;
693
694 Type *IntTy8 = Type::getInt8Ty(II.getContext());
695 Type *IntTy32 = Type::getInt32Ty(II.getContext());
696 VectorType *ShufTy = VectorType::get(IntTy8, 16);
697
698 SmallVector<Constant *, 16> ShuffleMask;
699 for (int i = 0; i != (int)Index; ++i)
700 ShuffleMask.push_back(Constant::getIntegerValue(IntTy32, APInt(32, i)));
701 for (int i = 0; i != (int)Length; ++i)
702 ShuffleMask.push_back(
703 Constant::getIntegerValue(IntTy32, APInt(32, i + 16)));
704 for (int i = Index + Length; i != 8; ++i)
705 ShuffleMask.push_back(Constant::getIntegerValue(IntTy32, APInt(32, i)));
706 for (int i = 8; i != 16; ++i)
707 ShuffleMask.push_back(UndefValue::get(IntTy32));
708
709 Value *SV = Builder.CreateShuffleVector(Builder.CreateBitCast(Op0, ShufTy),
710 Builder.CreateBitCast(Op1, ShufTy),
711 ConstantVector::get(ShuffleMask));
712 return Builder.CreateBitCast(SV, II.getType());
713 }
714
715 // See if we're dealing with constant values.
716 Constant *C0 = dyn_cast<Constant>(Op0);
717 Constant *C1 = dyn_cast<Constant>(Op1);
718 ConstantInt *CI00 =
719 C0 ? dyn_cast<ConstantInt>(C0->getAggregateElement((unsigned)0))
720 : nullptr;
721 ConstantInt *CI10 =
722 C1 ? dyn_cast<ConstantInt>(C1->getAggregateElement((unsigned)0))
723 : nullptr;
724
725 // Constant Fold - insert bottom Length bits starting at the Index'th bit.
726 if (CI00 && CI10) {
727 APInt V00 = CI00->getValue();
728 APInt V10 = CI10->getValue();
729 APInt Mask = APInt::getLowBitsSet(64, Length).shl(Index);
730 V00 = V00 & ~Mask;
731 V10 = V10.zextOrTrunc(Length).zextOrTrunc(64).shl(Index);
732 APInt Val = V00 | V10;
733 Type *IntTy64 = Type::getInt64Ty(II.getContext());
734 Constant *Args[] = {ConstantInt::get(IntTy64, Val.getZExtValue()),
735 UndefValue::get(IntTy64)};
736 return ConstantVector::get(Args);
737 }
738
739 // If we were an INSERTQ call, we'll save demanded elements if we convert to
740 // INSERTQI.
741 if (II.getIntrinsicID() == Intrinsic::x86_sse4a_insertq) {
742 Type *IntTy8 = Type::getInt8Ty(II.getContext());
743 Constant *CILength = ConstantInt::get(IntTy8, Length, false);
744 Constant *CIIndex = ConstantInt::get(IntTy8, Index, false);
745
746 Value *Args[] = {Op0, Op1, CILength, CIIndex};
Sanjay Patelaf674fb2015-12-14 17:24:23 +0000747 Module *M = II.getModule();
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000748 Value *F = Intrinsic::getDeclaration(M, Intrinsic::x86_sse4a_insertqi);
749 return Builder.CreateCall(F, Args);
750 }
751
752 return nullptr;
753}
754
Simon Pilgrimc0c56e72016-04-24 17:00:34 +0000755/// Attempt to convert pshufb* to shufflevector if the mask is constant.
756static Value *simplifyX86pshufb(const IntrinsicInst &II,
757 InstCombiner::BuilderTy &Builder) {
Simon Pilgrimbf60cc42016-04-29 21:34:54 +0000758 Constant *V = dyn_cast<Constant>(II.getArgOperand(1));
759 if (!V)
760 return nullptr;
761
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +0000762 auto *VecTy = cast<VectorType>(II.getType());
763 auto *MaskEltTy = Type::getInt32Ty(II.getContext());
764 unsigned NumElts = VecTy->getNumElements();
Simon Pilgrimc0c56e72016-04-24 17:00:34 +0000765 assert((NumElts == 16 || NumElts == 32) &&
766 "Unexpected number of elements in shuffle mask!");
Simon Pilgrimbf60cc42016-04-29 21:34:54 +0000767
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +0000768 // Construct a shuffle mask from constant integers or UNDEFs.
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000769 Constant *Indexes[32] = {nullptr};
Simon Pilgrimc0c56e72016-04-24 17:00:34 +0000770
Simon Pilgrimbf60cc42016-04-29 21:34:54 +0000771 // Each byte in the shuffle control mask forms an index to permute the
772 // corresponding byte in the destination operand.
773 for (unsigned I = 0; I < NumElts; ++I) {
774 Constant *COp = V->getAggregateElement(I);
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +0000775 if (!COp || (!isa<UndefValue>(COp) && !isa<ConstantInt>(COp)))
Simon Pilgrimbf60cc42016-04-29 21:34:54 +0000776 return nullptr;
Simon Pilgrimc0c56e72016-04-24 17:00:34 +0000777
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +0000778 if (isa<UndefValue>(COp)) {
779 Indexes[I] = UndefValue::get(MaskEltTy);
780 continue;
781 }
782
Simon Pilgrimbf60cc42016-04-29 21:34:54 +0000783 int8_t Index = cast<ConstantInt>(COp)->getValue().getZExtValue();
784
785 // If the most significant bit (bit[7]) of each byte of the shuffle
786 // control mask is set, then zero is written in the result byte.
787 // The zero vector is in the right-hand side of the resulting
788 // shufflevector.
789
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +0000790 // The value of each index for the high 128-bit lane is the least
791 // significant 4 bits of the respective shuffle control byte.
792 Index = ((Index < 0) ? NumElts : Index & 0x0F) + (I & 0xF0);
793 Indexes[I] = ConstantInt::get(MaskEltTy, Index);
Simon Pilgrimbf60cc42016-04-29 21:34:54 +0000794 }
Simon Pilgrimc0c56e72016-04-24 17:00:34 +0000795
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +0000796 auto ShuffleMask = ConstantVector::get(makeArrayRef(Indexes, NumElts));
Simon Pilgrimc0c56e72016-04-24 17:00:34 +0000797 auto V1 = II.getArgOperand(0);
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +0000798 auto V2 = Constant::getNullValue(VecTy);
Simon Pilgrimc0c56e72016-04-24 17:00:34 +0000799 return Builder.CreateShuffleVector(V1, V2, ShuffleMask);
800}
801
Simon Pilgrim2f6097d2016-04-24 17:23:46 +0000802/// Attempt to convert vpermilvar* to shufflevector if the mask is constant.
803static Value *simplifyX86vpermilvar(const IntrinsicInst &II,
804 InstCombiner::BuilderTy &Builder) {
Simon Pilgrim640f9962016-04-30 07:23:30 +0000805 Constant *V = dyn_cast<Constant>(II.getArgOperand(1));
806 if (!V)
807 return nullptr;
Simon Pilgrim2f6097d2016-04-24 17:23:46 +0000808
Simon Pilgrimeeacc402016-05-01 20:22:42 +0000809 auto *MaskEltTy = Type::getInt32Ty(II.getContext());
810 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
811 assert(NumElts == 8 || NumElts == 4 || NumElts == 2);
Simon Pilgrim2f6097d2016-04-24 17:23:46 +0000812
Simon Pilgrimeeacc402016-05-01 20:22:42 +0000813 // Construct a shuffle mask from constant integers or UNDEFs.
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000814 Constant *Indexes[8] = {nullptr};
Simon Pilgrim640f9962016-04-30 07:23:30 +0000815
816 // The intrinsics only read one or two bits, clear the rest.
Simon Pilgrimeeacc402016-05-01 20:22:42 +0000817 for (unsigned I = 0; I < NumElts; ++I) {
Simon Pilgrim640f9962016-04-30 07:23:30 +0000818 Constant *COp = V->getAggregateElement(I);
Simon Pilgrimeeacc402016-05-01 20:22:42 +0000819 if (!COp || (!isa<UndefValue>(COp) && !isa<ConstantInt>(COp)))
Simon Pilgrim640f9962016-04-30 07:23:30 +0000820 return nullptr;
821
Simon Pilgrimeeacc402016-05-01 20:22:42 +0000822 if (isa<UndefValue>(COp)) {
823 Indexes[I] = UndefValue::get(MaskEltTy);
824 continue;
825 }
826
827 APInt Index = cast<ConstantInt>(COp)->getValue();
828 Index = Index.zextOrTrunc(32).getLoBits(2);
Simon Pilgrim640f9962016-04-30 07:23:30 +0000829
830 // The PD variants uses bit 1 to select per-lane element index, so
831 // shift down to convert to generic shuffle mask index.
832 if (II.getIntrinsicID() == Intrinsic::x86_avx_vpermilvar_pd ||
833 II.getIntrinsicID() == Intrinsic::x86_avx_vpermilvar_pd_256)
Simon Pilgrimeeacc402016-05-01 20:22:42 +0000834 Index = Index.lshr(1);
835
836 // The _256 variants are a bit trickier since the mask bits always index
837 // into the corresponding 128 half. In order to convert to a generic
838 // shuffle, we have to make that explicit.
839 if ((II.getIntrinsicID() == Intrinsic::x86_avx_vpermilvar_ps_256 ||
840 II.getIntrinsicID() == Intrinsic::x86_avx_vpermilvar_pd_256) &&
841 ((NumElts / 2) <= I)) {
842 Index += APInt(32, NumElts / 2);
843 }
844
845 Indexes[I] = ConstantInt::get(MaskEltTy, Index);
Simon Pilgrim2f6097d2016-04-24 17:23:46 +0000846 }
847
Simon Pilgrimeeacc402016-05-01 20:22:42 +0000848 auto ShuffleMask = ConstantVector::get(makeArrayRef(Indexes, NumElts));
Simon Pilgrim2f6097d2016-04-24 17:23:46 +0000849 auto V1 = II.getArgOperand(0);
850 auto V2 = UndefValue::get(V1->getType());
851 return Builder.CreateShuffleVector(V1, V2, ShuffleMask);
852}
853
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +0000854/// Attempt to convert vpermd/vpermps to shufflevector if the mask is constant.
855static Value *simplifyX86vpermv(const IntrinsicInst &II,
856 InstCombiner::BuilderTy &Builder) {
857 auto *V = dyn_cast<Constant>(II.getArgOperand(1));
858 if (!V)
859 return nullptr;
860
Simon Pilgrimca140b12016-05-01 20:43:02 +0000861 auto *VecTy = cast<VectorType>(II.getType());
862 auto *MaskEltTy = Type::getInt32Ty(II.getContext());
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +0000863 unsigned Size = VecTy->getNumElements();
864 assert(Size == 8 && "Unexpected shuffle mask size");
865
Simon Pilgrimca140b12016-05-01 20:43:02 +0000866 // Construct a shuffle mask from constant integers or UNDEFs.
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000867 Constant *Indexes[8] = {nullptr};
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +0000868
869 for (unsigned I = 0; I < Size; ++I) {
870 Constant *COp = V->getAggregateElement(I);
Simon Pilgrimca140b12016-05-01 20:43:02 +0000871 if (!COp || (!isa<UndefValue>(COp) && !isa<ConstantInt>(COp)))
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +0000872 return nullptr;
873
Simon Pilgrimca140b12016-05-01 20:43:02 +0000874 if (isa<UndefValue>(COp)) {
875 Indexes[I] = UndefValue::get(MaskEltTy);
876 continue;
877 }
878
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +0000879 APInt Index = cast<ConstantInt>(COp)->getValue();
Simon Pilgrimca140b12016-05-01 20:43:02 +0000880 Index = Index.zextOrTrunc(32).getLoBits(3);
881 Indexes[I] = ConstantInt::get(MaskEltTy, Index);
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +0000882 }
883
Simon Pilgrimca140b12016-05-01 20:43:02 +0000884 auto ShuffleMask = ConstantVector::get(makeArrayRef(Indexes, Size));
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +0000885 auto V1 = II.getArgOperand(0);
886 auto V2 = UndefValue::get(VecTy);
887 return Builder.CreateShuffleVector(V1, V2, ShuffleMask);
888}
889
Sanjay Patelccf5f242015-03-20 21:47:56 +0000890/// The shuffle mask for a perm2*128 selects any two halves of two 256-bit
891/// source vectors, unless a zero bit is set. If a zero bit is set,
892/// then ignore that half of the mask and clear that half of the vector.
Sanjay Patel6038d3e2016-01-29 23:27:03 +0000893static Value *simplifyX86vperm2(const IntrinsicInst &II,
Sanjay Patelccf5f242015-03-20 21:47:56 +0000894 InstCombiner::BuilderTy &Builder) {
Sanjay Patel03c03f52016-01-28 00:03:16 +0000895 auto *CInt = dyn_cast<ConstantInt>(II.getArgOperand(2));
896 if (!CInt)
897 return nullptr;
Sanjay Patelccf5f242015-03-20 21:47:56 +0000898
Sanjay Patel03c03f52016-01-28 00:03:16 +0000899 VectorType *VecTy = cast<VectorType>(II.getType());
900 ConstantAggregateZero *ZeroVector = ConstantAggregateZero::get(VecTy);
Sanjay Patel43a87fd2015-03-24 20:36:42 +0000901
Sanjay Patel03c03f52016-01-28 00:03:16 +0000902 // The immediate permute control byte looks like this:
903 // [1:0] - select 128 bits from sources for low half of destination
904 // [2] - ignore
905 // [3] - zero low half of destination
906 // [5:4] - select 128 bits from sources for high half of destination
907 // [6] - ignore
908 // [7] - zero high half of destination
Sanjay Patel43a87fd2015-03-24 20:36:42 +0000909
Sanjay Patel03c03f52016-01-28 00:03:16 +0000910 uint8_t Imm = CInt->getZExtValue();
Sanjay Patel43a87fd2015-03-24 20:36:42 +0000911
Sanjay Patel03c03f52016-01-28 00:03:16 +0000912 bool LowHalfZero = Imm & 0x08;
913 bool HighHalfZero = Imm & 0x80;
Sanjay Patel43a87fd2015-03-24 20:36:42 +0000914
Sanjay Patel03c03f52016-01-28 00:03:16 +0000915 // If both zero mask bits are set, this was just a weird way to
916 // generate a zero vector.
917 if (LowHalfZero && HighHalfZero)
918 return ZeroVector;
Sanjay Patel43a87fd2015-03-24 20:36:42 +0000919
Sanjay Patel03c03f52016-01-28 00:03:16 +0000920 // If 0 or 1 zero mask bits are set, this is a simple shuffle.
921 unsigned NumElts = VecTy->getNumElements();
922 unsigned HalfSize = NumElts / 2;
Craig Topper99d1eab2016-06-12 00:41:19 +0000923 SmallVector<uint32_t, 8> ShuffleMask(NumElts);
Simon Pilgrim54fcd622015-07-25 20:41:00 +0000924
Sanjay Patel03c03f52016-01-28 00:03:16 +0000925 // The high bit of the selection field chooses the 1st or 2nd operand.
926 bool LowInputSelect = Imm & 0x02;
927 bool HighInputSelect = Imm & 0x20;
Sanjay Patelccf5f242015-03-20 21:47:56 +0000928
Sanjay Patel03c03f52016-01-28 00:03:16 +0000929 // The low bit of the selection field chooses the low or high half
930 // of the selected operand.
931 bool LowHalfSelect = Imm & 0x01;
932 bool HighHalfSelect = Imm & 0x10;
Simon Pilgrim54fcd622015-07-25 20:41:00 +0000933
Sanjay Patel03c03f52016-01-28 00:03:16 +0000934 // Determine which operand(s) are actually in use for this instruction.
935 Value *V0 = LowInputSelect ? II.getArgOperand(1) : II.getArgOperand(0);
936 Value *V1 = HighInputSelect ? II.getArgOperand(1) : II.getArgOperand(0);
Simon Pilgrim54fcd622015-07-25 20:41:00 +0000937
Sanjay Patel03c03f52016-01-28 00:03:16 +0000938 // If needed, replace operands based on zero mask.
939 V0 = LowHalfZero ? ZeroVector : V0;
940 V1 = HighHalfZero ? ZeroVector : V1;
Sanjay Patelccf5f242015-03-20 21:47:56 +0000941
Sanjay Patel03c03f52016-01-28 00:03:16 +0000942 // Permute low half of result.
943 unsigned StartIndex = LowHalfSelect ? HalfSize : 0;
944 for (unsigned i = 0; i < HalfSize; ++i)
945 ShuffleMask[i] = StartIndex + i;
Sanjay Patel43a87fd2015-03-24 20:36:42 +0000946
Sanjay Patel03c03f52016-01-28 00:03:16 +0000947 // Permute high half of result.
948 StartIndex = HighHalfSelect ? HalfSize : 0;
949 StartIndex += NumElts;
950 for (unsigned i = 0; i < HalfSize; ++i)
951 ShuffleMask[i + HalfSize] = StartIndex + i;
952
953 return Builder.CreateShuffleVector(V0, V1, ShuffleMask);
Sanjay Patelccf5f242015-03-20 21:47:56 +0000954}
955
Simon Pilgrim1d1c56e22015-10-11 14:38:34 +0000956/// Decode XOP integer vector comparison intrinsics.
Sanjay Patel6038d3e2016-01-29 23:27:03 +0000957static Value *simplifyX86vpcom(const IntrinsicInst &II,
Sanjay Patelf9f5d3c2016-01-29 23:14:58 +0000958 InstCombiner::BuilderTy &Builder,
959 bool IsSigned) {
Simon Pilgrim1d1c56e22015-10-11 14:38:34 +0000960 if (auto *CInt = dyn_cast<ConstantInt>(II.getArgOperand(2))) {
961 uint64_t Imm = CInt->getZExtValue() & 0x7;
962 VectorType *VecTy = cast<VectorType>(II.getType());
963 CmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
964
965 switch (Imm) {
966 case 0x0:
967 Pred = IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
968 break;
969 case 0x1:
970 Pred = IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
971 break;
972 case 0x2:
973 Pred = IsSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
974 break;
975 case 0x3:
976 Pred = IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
977 break;
978 case 0x4:
979 Pred = ICmpInst::ICMP_EQ; break;
980 case 0x5:
981 Pred = ICmpInst::ICMP_NE; break;
982 case 0x6:
983 return ConstantInt::getSigned(VecTy, 0); // FALSE
984 case 0x7:
985 return ConstantInt::getSigned(VecTy, -1); // TRUE
986 }
987
Sanjay Patelf9f5d3c2016-01-29 23:14:58 +0000988 if (Value *Cmp = Builder.CreateICmp(Pred, II.getArgOperand(0),
989 II.getArgOperand(1)))
Simon Pilgrim1d1c56e22015-10-11 14:38:34 +0000990 return Builder.CreateSExtOrTrunc(Cmp, VecTy);
991 }
992 return nullptr;
993}
994
Sanjay Patel0069f562016-01-31 16:35:23 +0000995static Value *simplifyMinnumMaxnum(const IntrinsicInst &II) {
996 Value *Arg0 = II.getArgOperand(0);
997 Value *Arg1 = II.getArgOperand(1);
998
999 // fmin(x, x) -> x
1000 if (Arg0 == Arg1)
1001 return Arg0;
1002
1003 const auto *C1 = dyn_cast<ConstantFP>(Arg1);
1004
1005 // fmin(x, nan) -> x
1006 if (C1 && C1->isNaN())
1007 return Arg0;
1008
1009 // This is the value because if undef were NaN, we would return the other
1010 // value and cannot return a NaN unless both operands are.
1011 //
1012 // fmin(undef, x) -> x
1013 if (isa<UndefValue>(Arg0))
1014 return Arg1;
1015
1016 // fmin(x, undef) -> x
1017 if (isa<UndefValue>(Arg1))
1018 return Arg0;
1019
1020 Value *X = nullptr;
1021 Value *Y = nullptr;
1022 if (II.getIntrinsicID() == Intrinsic::minnum) {
1023 // fmin(x, fmin(x, y)) -> fmin(x, y)
1024 // fmin(y, fmin(x, y)) -> fmin(x, y)
1025 if (match(Arg1, m_FMin(m_Value(X), m_Value(Y)))) {
1026 if (Arg0 == X || Arg0 == Y)
1027 return Arg1;
1028 }
1029
1030 // fmin(fmin(x, y), x) -> fmin(x, y)
1031 // fmin(fmin(x, y), y) -> fmin(x, y)
1032 if (match(Arg0, m_FMin(m_Value(X), m_Value(Y)))) {
1033 if (Arg1 == X || Arg1 == Y)
1034 return Arg0;
1035 }
1036
1037 // TODO: fmin(nnan x, inf) -> x
1038 // TODO: fmin(nnan ninf x, flt_max) -> x
1039 if (C1 && C1->isInfinity()) {
1040 // fmin(x, -inf) -> -inf
1041 if (C1->isNegative())
1042 return Arg1;
1043 }
1044 } else {
1045 assert(II.getIntrinsicID() == Intrinsic::maxnum);
1046 // fmax(x, fmax(x, y)) -> fmax(x, y)
1047 // fmax(y, fmax(x, y)) -> fmax(x, y)
1048 if (match(Arg1, m_FMax(m_Value(X), m_Value(Y)))) {
1049 if (Arg0 == X || Arg0 == Y)
1050 return Arg1;
1051 }
1052
1053 // fmax(fmax(x, y), x) -> fmax(x, y)
1054 // fmax(fmax(x, y), y) -> fmax(x, y)
1055 if (match(Arg0, m_FMax(m_Value(X), m_Value(Y)))) {
1056 if (Arg1 == X || Arg1 == Y)
1057 return Arg0;
1058 }
1059
1060 // TODO: fmax(nnan x, -inf) -> x
1061 // TODO: fmax(nnan ninf x, -flt_max) -> x
1062 if (C1 && C1->isInfinity()) {
1063 // fmax(x, inf) -> inf
1064 if (!C1->isNegative())
1065 return Arg1;
1066 }
1067 }
1068 return nullptr;
1069}
1070
David Majnemer666aa942016-07-14 06:58:42 +00001071static bool maskIsAllOneOrUndef(Value *Mask) {
1072 auto *ConstMask = dyn_cast<Constant>(Mask);
1073 if (!ConstMask)
1074 return false;
1075 if (ConstMask->isAllOnesValue() || isa<UndefValue>(ConstMask))
1076 return true;
1077 for (unsigned I = 0, E = ConstMask->getType()->getVectorNumElements(); I != E;
1078 ++I) {
1079 if (auto *MaskElt = ConstMask->getAggregateElement(I))
1080 if (MaskElt->isAllOnesValue() || isa<UndefValue>(MaskElt))
1081 continue;
1082 return false;
1083 }
1084 return true;
1085}
1086
Sanjay Patelb695c552016-02-01 17:00:10 +00001087static Value *simplifyMaskedLoad(const IntrinsicInst &II,
1088 InstCombiner::BuilderTy &Builder) {
David Majnemer666aa942016-07-14 06:58:42 +00001089 // If the mask is all ones or undefs, this is a plain vector load of the 1st
1090 // argument.
1091 if (maskIsAllOneOrUndef(II.getArgOperand(2))) {
Sanjay Patelb695c552016-02-01 17:00:10 +00001092 Value *LoadPtr = II.getArgOperand(0);
1093 unsigned Alignment = cast<ConstantInt>(II.getArgOperand(1))->getZExtValue();
1094 return Builder.CreateAlignedLoad(LoadPtr, Alignment, "unmaskedload");
1095 }
1096
1097 return nullptr;
1098}
1099
Sanjay Patel04f792b2016-02-01 19:39:52 +00001100static Instruction *simplifyMaskedStore(IntrinsicInst &II, InstCombiner &IC) {
1101 auto *ConstMask = dyn_cast<Constant>(II.getArgOperand(3));
1102 if (!ConstMask)
1103 return nullptr;
1104
1105 // If the mask is all zeros, this instruction does nothing.
1106 if (ConstMask->isNullValue())
Sanjay Patel4b198802016-02-01 22:23:39 +00001107 return IC.eraseInstFromFunction(II);
Sanjay Patel04f792b2016-02-01 19:39:52 +00001108
1109 // If the mask is all ones, this is a plain vector store of the 1st argument.
1110 if (ConstMask->isAllOnesValue()) {
1111 Value *StorePtr = II.getArgOperand(1);
1112 unsigned Alignment = cast<ConstantInt>(II.getArgOperand(2))->getZExtValue();
1113 return new StoreInst(II.getArgOperand(0), StorePtr, false, Alignment);
1114 }
1115
1116 return nullptr;
1117}
1118
Sanjay Patel103ab7d2016-02-01 22:10:26 +00001119static Instruction *simplifyMaskedGather(IntrinsicInst &II, InstCombiner &IC) {
1120 // If the mask is all zeros, return the "passthru" argument of the gather.
1121 auto *ConstMask = dyn_cast<Constant>(II.getArgOperand(2));
1122 if (ConstMask && ConstMask->isNullValue())
Sanjay Patel4b198802016-02-01 22:23:39 +00001123 return IC.replaceInstUsesWith(II, II.getArgOperand(3));
Sanjay Patel103ab7d2016-02-01 22:10:26 +00001124
1125 return nullptr;
1126}
1127
1128static Instruction *simplifyMaskedScatter(IntrinsicInst &II, InstCombiner &IC) {
1129 // If the mask is all zeros, a scatter does nothing.
1130 auto *ConstMask = dyn_cast<Constant>(II.getArgOperand(3));
1131 if (ConstMask && ConstMask->isNullValue())
Sanjay Patel4b198802016-02-01 22:23:39 +00001132 return IC.eraseInstFromFunction(II);
Sanjay Patel103ab7d2016-02-01 22:10:26 +00001133
1134 return nullptr;
1135}
1136
Amaury Sechet763c59d2016-08-18 20:43:50 +00001137static Instruction *foldCttzCtlz(IntrinsicInst &II, InstCombiner &IC) {
1138 assert((II.getIntrinsicID() == Intrinsic::cttz ||
1139 II.getIntrinsicID() == Intrinsic::ctlz) &&
1140 "Expected cttz or ctlz intrinsic");
Sanjay Patel8e3ab172016-08-05 22:42:46 +00001141 Value *Op0 = II.getArgOperand(0);
1142 // FIXME: Try to simplify vectors of integers.
1143 auto *IT = dyn_cast<IntegerType>(Op0->getType());
1144 if (!IT)
1145 return nullptr;
1146
1147 unsigned BitWidth = IT->getBitWidth();
1148 APInt KnownZero(BitWidth, 0);
1149 APInt KnownOne(BitWidth, 0);
1150 IC.computeKnownBits(Op0, KnownZero, KnownOne, 0, &II);
1151
1152 // Create a mask for bits above (ctlz) or below (cttz) the first known one.
1153 bool IsTZ = II.getIntrinsicID() == Intrinsic::cttz;
1154 unsigned NumMaskBits = IsTZ ? KnownOne.countTrailingZeros()
1155 : KnownOne.countLeadingZeros();
1156 APInt Mask = IsTZ ? APInt::getLowBitsSet(BitWidth, NumMaskBits)
1157 : APInt::getHighBitsSet(BitWidth, NumMaskBits);
1158
1159 // If all bits above (ctlz) or below (cttz) the first known one are known
1160 // zero, this value is constant.
1161 // FIXME: This should be in InstSimplify because we're replacing an
1162 // instruction with a constant.
Amaury Sechet763c59d2016-08-18 20:43:50 +00001163 if ((Mask & KnownZero) == Mask) {
1164 auto *C = ConstantInt::get(IT, APInt(BitWidth, NumMaskBits));
1165 return IC.replaceInstUsesWith(II, C);
1166 }
1167
1168 // If the input to cttz/ctlz is known to be non-zero,
1169 // then change the 'ZeroIsUndef' parameter to 'true'
1170 // because we know the zero behavior can't affect the result.
1171 if (KnownOne != 0 || isKnownNonZero(Op0, IC.getDataLayout())) {
1172 if (!match(II.getArgOperand(1), m_One())) {
1173 II.setOperand(1, IC.Builder->getTrue());
1174 return &II;
1175 }
1176 }
Sanjay Patel8e3ab172016-08-05 22:42:46 +00001177
1178 return nullptr;
1179}
1180
Sanjay Patel1ace9932016-02-26 21:04:14 +00001181// TODO: If the x86 backend knew how to convert a bool vector mask back to an
1182// XMM register mask efficiently, we could transform all x86 masked intrinsics
1183// to LLVM masked intrinsics and remove the x86 masked intrinsic defs.
Sanjay Patel98a71502016-02-29 23:16:48 +00001184static Instruction *simplifyX86MaskedLoad(IntrinsicInst &II, InstCombiner &IC) {
1185 Value *Ptr = II.getOperand(0);
1186 Value *Mask = II.getOperand(1);
Sanjay Patel5e5056d2016-04-12 23:16:23 +00001187 Constant *ZeroVec = Constant::getNullValue(II.getType());
Sanjay Patel98a71502016-02-29 23:16:48 +00001188
1189 // Special case a zero mask since that's not a ConstantDataVector.
Sanjay Patel5e5056d2016-04-12 23:16:23 +00001190 // This masked load instruction creates a zero vector.
Sanjay Patel98a71502016-02-29 23:16:48 +00001191 if (isa<ConstantAggregateZero>(Mask))
Sanjay Patel5e5056d2016-04-12 23:16:23 +00001192 return IC.replaceInstUsesWith(II, ZeroVec);
Sanjay Patel98a71502016-02-29 23:16:48 +00001193
1194 auto *ConstMask = dyn_cast<ConstantDataVector>(Mask);
1195 if (!ConstMask)
1196 return nullptr;
1197
1198 // The mask is constant. Convert this x86 intrinsic to the LLVM instrinsic
1199 // to allow target-independent optimizations.
1200
1201 // First, cast the x86 intrinsic scalar pointer to a vector pointer to match
1202 // the LLVM intrinsic definition for the pointer argument.
1203 unsigned AddrSpace = cast<PointerType>(Ptr->getType())->getAddressSpace();
1204 PointerType *VecPtrTy = PointerType::get(II.getType(), AddrSpace);
1205 Value *PtrCast = IC.Builder->CreateBitCast(Ptr, VecPtrTy, "castvec");
1206
1207 // Second, convert the x86 XMM integer vector mask to a vector of bools based
1208 // on each element's most significant bit (the sign bit).
1209 Constant *BoolMask = getNegativeIsTrueBoolVec(ConstMask);
1210
Sanjay Patel5e5056d2016-04-12 23:16:23 +00001211 // The pass-through vector for an x86 masked load is a zero vector.
1212 CallInst *NewMaskedLoad =
1213 IC.Builder->CreateMaskedLoad(PtrCast, 1, BoolMask, ZeroVec);
Sanjay Patel98a71502016-02-29 23:16:48 +00001214 return IC.replaceInstUsesWith(II, NewMaskedLoad);
1215}
1216
1217// TODO: If the x86 backend knew how to convert a bool vector mask back to an
1218// XMM register mask efficiently, we could transform all x86 masked intrinsics
1219// to LLVM masked intrinsics and remove the x86 masked intrinsic defs.
Sanjay Patel1ace9932016-02-26 21:04:14 +00001220static bool simplifyX86MaskedStore(IntrinsicInst &II, InstCombiner &IC) {
1221 Value *Ptr = II.getOperand(0);
1222 Value *Mask = II.getOperand(1);
1223 Value *Vec = II.getOperand(2);
1224
1225 // Special case a zero mask since that's not a ConstantDataVector:
1226 // this masked store instruction does nothing.
1227 if (isa<ConstantAggregateZero>(Mask)) {
1228 IC.eraseInstFromFunction(II);
1229 return true;
1230 }
1231
Sanjay Patelc4acbae2016-03-12 15:16:59 +00001232 // The SSE2 version is too weird (eg, unaligned but non-temporal) to do
1233 // anything else at this level.
1234 if (II.getIntrinsicID() == Intrinsic::x86_sse2_maskmov_dqu)
1235 return false;
1236
Sanjay Patel1ace9932016-02-26 21:04:14 +00001237 auto *ConstMask = dyn_cast<ConstantDataVector>(Mask);
1238 if (!ConstMask)
1239 return false;
1240
1241 // The mask is constant. Convert this x86 intrinsic to the LLVM instrinsic
1242 // to allow target-independent optimizations.
1243
1244 // First, cast the x86 intrinsic scalar pointer to a vector pointer to match
1245 // the LLVM intrinsic definition for the pointer argument.
1246 unsigned AddrSpace = cast<PointerType>(Ptr->getType())->getAddressSpace();
1247 PointerType *VecPtrTy = PointerType::get(Vec->getType(), AddrSpace);
Sanjay Patel1ace9932016-02-26 21:04:14 +00001248 Value *PtrCast = IC.Builder->CreateBitCast(Ptr, VecPtrTy, "castvec");
1249
1250 // Second, convert the x86 XMM integer vector mask to a vector of bools based
1251 // on each element's most significant bit (the sign bit).
1252 Constant *BoolMask = getNegativeIsTrueBoolVec(ConstMask);
1253
1254 IC.Builder->CreateMaskedStore(Vec, PtrCast, 1, BoolMask);
1255
1256 // 'Replace uses' doesn't work for stores. Erase the original masked store.
1257 IC.eraseInstFromFunction(II);
1258 return true;
1259}
1260
Arnaud A. de Grandmaison333ef382016-05-10 09:24:49 +00001261// Returns true iff the 2 intrinsics have the same operands, limiting the
1262// comparison to the first NumOperands.
1263static bool haveSameOperands(const IntrinsicInst &I, const IntrinsicInst &E,
1264 unsigned NumOperands) {
1265 assert(I.getNumArgOperands() >= NumOperands && "Not enough operands");
1266 assert(E.getNumArgOperands() >= NumOperands && "Not enough operands");
1267 for (unsigned i = 0; i < NumOperands; i++)
1268 if (I.getArgOperand(i) != E.getArgOperand(i))
1269 return false;
1270 return true;
1271}
1272
1273// Remove trivially empty start/end intrinsic ranges, i.e. a start
1274// immediately followed by an end (ignoring debuginfo or other
1275// start/end intrinsics in between). As this handles only the most trivial
1276// cases, tracking the nesting level is not needed:
1277//
1278// call @llvm.foo.start(i1 0) ; &I
1279// call @llvm.foo.start(i1 0)
1280// call @llvm.foo.end(i1 0) ; This one will not be skipped: it will be removed
1281// call @llvm.foo.end(i1 0)
1282static bool removeTriviallyEmptyRange(IntrinsicInst &I, unsigned StartID,
1283 unsigned EndID, InstCombiner &IC) {
1284 assert(I.getIntrinsicID() == StartID &&
1285 "Start intrinsic does not have expected ID");
1286 BasicBlock::iterator BI(I), BE(I.getParent()->end());
1287 for (++BI; BI != BE; ++BI) {
1288 if (auto *E = dyn_cast<IntrinsicInst>(BI)) {
1289 if (isa<DbgInfoIntrinsic>(E) || E->getIntrinsicID() == StartID)
1290 continue;
1291 if (E->getIntrinsicID() == EndID &&
1292 haveSameOperands(I, *E, E->getNumArgOperands())) {
1293 IC.eraseInstFromFunction(*E);
1294 IC.eraseInstFromFunction(I);
1295 return true;
1296 }
1297 }
1298 break;
1299 }
1300
1301 return false;
1302}
1303
1304Instruction *InstCombiner::visitVAStartInst(VAStartInst &I) {
1305 removeTriviallyEmptyRange(I, Intrinsic::vastart, Intrinsic::vaend, *this);
1306 return nullptr;
1307}
1308
1309Instruction *InstCombiner::visitVACopyInst(VACopyInst &I) {
1310 removeTriviallyEmptyRange(I, Intrinsic::vacopy, Intrinsic::vaend, *this);
1311 return nullptr;
1312}
1313
Sanjay Patelcd4377c2016-01-20 22:24:38 +00001314/// CallInst simplification. This mostly only handles folding of intrinsic
1315/// instructions. For normal calls, it allows visitCallSite to do the heavy
1316/// lifting.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001317Instruction *InstCombiner::visitCallInst(CallInst &CI) {
David Majnemer15032582015-05-22 03:56:46 +00001318 auto Args = CI.arg_operands();
1319 if (Value *V = SimplifyCall(CI.getCalledValue(), Args.begin(), Args.end(), DL,
Justin Bogner99798402016-08-05 01:06:44 +00001320 &TLI, &DT, &AC))
Sanjay Patel4b198802016-02-01 22:23:39 +00001321 return replaceInstUsesWith(CI, V);
David Majnemer15032582015-05-22 03:56:46 +00001322
Justin Bogner99798402016-08-05 01:06:44 +00001323 if (isFreeCall(&CI, &TLI))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001324 return visitFree(CI);
1325
1326 // If the caller function is nounwind, mark the call as nounwind, even if the
1327 // callee isn't.
Sanjay Patel5a470952016-08-11 15:16:06 +00001328 if (CI.getFunction()->doesNotThrow() && !CI.doesNotThrow()) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001329 CI.setDoesNotThrow();
1330 return &CI;
1331 }
Jim Grosbach7815f562012-02-03 00:07:04 +00001332
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001333 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
1334 if (!II) return visitCallSite(&CI);
Gabor Greif589a0b92010-06-24 12:58:35 +00001335
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001336 // Intrinsics cannot occur in an invoke, so handle them here instead of in
1337 // visitCallSite.
1338 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
1339 bool Changed = false;
1340
1341 // memmove/cpy/set of zero bytes is a noop.
1342 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
Chris Lattnerc663a672010-10-01 05:51:02 +00001343 if (NumBytes->isNullValue())
Sanjay Patel4b198802016-02-01 22:23:39 +00001344 return eraseInstFromFunction(CI);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001345
1346 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
1347 if (CI->getZExtValue() == 1) {
1348 // Replace the instruction with just byte operations. We would
1349 // transform other cases to loads/stores, but we don't know if
1350 // alignment is sufficient.
1351 }
1352 }
Jim Grosbach7815f562012-02-03 00:07:04 +00001353
Chris Lattnerc663a672010-10-01 05:51:02 +00001354 // No other transformations apply to volatile transfers.
1355 if (MI->isVolatile())
Craig Topperf40110f2014-04-25 05:29:35 +00001356 return nullptr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001357
1358 // If we have a memmove and the source operation is a constant global,
1359 // then the source and dest pointers can't alias, so we can change this
1360 // into a call to memcpy.
1361 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
1362 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
1363 if (GVSrc->isConstant()) {
Sanjay Patelaf674fb2015-12-14 17:24:23 +00001364 Module *M = CI.getModule();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001365 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
Jay Foadb804a2b2011-07-12 14:06:48 +00001366 Type *Tys[3] = { CI.getArgOperand(0)->getType(),
1367 CI.getArgOperand(1)->getType(),
1368 CI.getArgOperand(2)->getType() };
Benjamin Kramere6e19332011-07-14 17:45:39 +00001369 CI.setCalledFunction(Intrinsic::getDeclaration(M, MemCpyID, Tys));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001370 Changed = true;
1371 }
1372 }
1373
1374 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) {
1375 // memmove(x,x,size) -> noop.
1376 if (MTI->getSource() == MTI->getDest())
Sanjay Patel4b198802016-02-01 22:23:39 +00001377 return eraseInstFromFunction(CI);
Eric Christopher7258dcd2010-04-16 23:37:20 +00001378 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001379
Eric Christopher7258dcd2010-04-16 23:37:20 +00001380 // If we can determine a pointer alignment that is bigger than currently
1381 // set, update the alignment.
Pete Cooper67cf9a72015-11-19 05:56:52 +00001382 if (isa<MemTransferInst>(MI)) {
1383 if (Instruction *I = SimplifyMemTransfer(MI))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001384 return I;
1385 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
1386 if (Instruction *I = SimplifyMemSet(MSI))
1387 return I;
1388 }
Gabor Greif590d95e2010-06-24 13:42:49 +00001389
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001390 if (Changed) return II;
1391 }
Jim Grosbach7815f562012-02-03 00:07:04 +00001392
Sanjay Patel1c600c62016-01-20 16:41:43 +00001393 auto SimplifyDemandedVectorEltsLow = [this](Value *Op, unsigned Width,
1394 unsigned DemandedWidth) {
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001395 APInt UndefElts(Width, 0);
1396 APInt DemandedElts = APInt::getLowBitsSet(Width, DemandedWidth);
1397 return SimplifyDemandedVectorElts(Op, DemandedElts, UndefElts);
1398 };
Simon Pilgrim424da162016-04-24 18:12:42 +00001399 auto SimplifyDemandedVectorEltsHigh = [this](Value *Op, unsigned Width,
1400 unsigned DemandedWidth) {
1401 APInt UndefElts(Width, 0);
1402 APInt DemandedElts = APInt::getHighBitsSet(Width, DemandedWidth);
1403 return SimplifyDemandedVectorElts(Op, DemandedElts, UndefElts);
1404 };
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001405
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001406 switch (II->getIntrinsicID()) {
1407 default: break;
Eric Christopher7b7028f2010-02-09 21:24:27 +00001408 case Intrinsic::objectsize: {
Nuno Lopes55fff832012-06-21 15:45:28 +00001409 uint64_t Size;
Justin Bogner99798402016-08-05 01:06:44 +00001410 if (getObjectSize(II->getArgOperand(0), Size, DL, &TLI)) {
George Burgess IV278199f2016-04-12 01:05:35 +00001411 APInt APSize(II->getType()->getIntegerBitWidth(), Size);
1412 // Equality check to be sure that `Size` can fit in a value of type
1413 // `II->getType()`
1414 if (APSize == Size)
1415 return replaceInstUsesWith(CI, ConstantInt::get(II->getType(), APSize));
1416 }
Craig Topperf40110f2014-04-25 05:29:35 +00001417 return nullptr;
Eric Christopher7b7028f2010-02-09 21:24:27 +00001418 }
Michael Ilseman536cc322012-12-13 03:13:36 +00001419 case Intrinsic::bswap: {
1420 Value *IIOperand = II->getArgOperand(0);
Craig Topperf40110f2014-04-25 05:29:35 +00001421 Value *X = nullptr;
Michael Ilseman536cc322012-12-13 03:13:36 +00001422
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001423 // bswap(bswap(x)) -> x
Michael Ilseman536cc322012-12-13 03:13:36 +00001424 if (match(IIOperand, m_BSwap(m_Value(X))))
Sanjay Patel4b198802016-02-01 22:23:39 +00001425 return replaceInstUsesWith(CI, X);
Jim Grosbach7815f562012-02-03 00:07:04 +00001426
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001427 // bswap(trunc(bswap(x))) -> trunc(lshr(x, c))
Michael Ilseman536cc322012-12-13 03:13:36 +00001428 if (match(IIOperand, m_Trunc(m_BSwap(m_Value(X))))) {
1429 unsigned C = X->getType()->getPrimitiveSizeInBits() -
1430 IIOperand->getType()->getPrimitiveSizeInBits();
1431 Value *CV = ConstantInt::get(X->getType(), C);
1432 Value *V = Builder->CreateLShr(X, CV);
1433 return new TruncInst(V, IIOperand->getType());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001434 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001435 break;
Michael Ilseman536cc322012-12-13 03:13:36 +00001436 }
1437
James Molloy2d09c002015-11-12 12:39:41 +00001438 case Intrinsic::bitreverse: {
1439 Value *IIOperand = II->getArgOperand(0);
1440 Value *X = nullptr;
1441
1442 // bitreverse(bitreverse(x)) -> x
1443 if (match(IIOperand, m_Intrinsic<Intrinsic::bitreverse>(m_Value(X))))
Sanjay Patel4b198802016-02-01 22:23:39 +00001444 return replaceInstUsesWith(CI, X);
James Molloy2d09c002015-11-12 12:39:41 +00001445 break;
1446 }
1447
Sanjay Patelb695c552016-02-01 17:00:10 +00001448 case Intrinsic::masked_load:
1449 if (Value *SimplifiedMaskedOp = simplifyMaskedLoad(*II, *Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00001450 return replaceInstUsesWith(CI, SimplifiedMaskedOp);
Sanjay Patelb695c552016-02-01 17:00:10 +00001451 break;
Sanjay Patel04f792b2016-02-01 19:39:52 +00001452 case Intrinsic::masked_store:
1453 return simplifyMaskedStore(*II, *this);
Sanjay Patel103ab7d2016-02-01 22:10:26 +00001454 case Intrinsic::masked_gather:
1455 return simplifyMaskedGather(*II, *this);
1456 case Intrinsic::masked_scatter:
1457 return simplifyMaskedScatter(*II, *this);
Sanjay Patelb695c552016-02-01 17:00:10 +00001458
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001459 case Intrinsic::powi:
Gabor Greif589a0b92010-06-24 12:58:35 +00001460 if (ConstantInt *Power = dyn_cast<ConstantInt>(II->getArgOperand(1))) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001461 // powi(x, 0) -> 1.0
1462 if (Power->isZero())
Sanjay Patel4b198802016-02-01 22:23:39 +00001463 return replaceInstUsesWith(CI, ConstantFP::get(CI.getType(), 1.0));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001464 // powi(x, 1) -> x
1465 if (Power->isOne())
Sanjay Patel4b198802016-02-01 22:23:39 +00001466 return replaceInstUsesWith(CI, II->getArgOperand(0));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001467 // powi(x, -1) -> 1/x
1468 if (Power->isAllOnesValue())
1469 return BinaryOperator::CreateFDiv(ConstantFP::get(CI.getType(), 1.0),
Gabor Greif589a0b92010-06-24 12:58:35 +00001470 II->getArgOperand(0));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001471 }
1472 break;
Jim Grosbach7815f562012-02-03 00:07:04 +00001473
Sanjay Patel8e3ab172016-08-05 22:42:46 +00001474 case Intrinsic::cttz:
1475 case Intrinsic::ctlz:
Amaury Sechet763c59d2016-08-18 20:43:50 +00001476 if (auto *I = foldCttzCtlz(*II, *this))
1477 return I;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001478 break;
Sanjoy Dasb0984472015-04-08 04:27:22 +00001479
Nick Lewyckyabe2cc12015-04-13 19:17:37 +00001480 case Intrinsic::uadd_with_overflow:
1481 case Intrinsic::sadd_with_overflow:
1482 case Intrinsic::umul_with_overflow:
1483 case Intrinsic::smul_with_overflow:
Gabor Greif5b1370e2010-06-28 16:50:57 +00001484 if (isa<Constant>(II->getArgOperand(0)) &&
1485 !isa<Constant>(II->getArgOperand(1))) {
Sanjoy Dasb0984472015-04-08 04:27:22 +00001486 // Canonicalize constants into the RHS.
Gabor Greif5b1370e2010-06-28 16:50:57 +00001487 Value *LHS = II->getArgOperand(0);
1488 II->setArgOperand(0, II->getArgOperand(1));
1489 II->setArgOperand(1, LHS);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001490 return II;
1491 }
Justin Bognercd1d5aa2016-08-17 20:30:52 +00001492 LLVM_FALLTHROUGH;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001493
Nick Lewyckyabe2cc12015-04-13 19:17:37 +00001494 case Intrinsic::usub_with_overflow:
1495 case Intrinsic::ssub_with_overflow: {
Sanjoy Dasb0984472015-04-08 04:27:22 +00001496 OverflowCheckFlavor OCF =
1497 IntrinsicIDToOverflowCheckFlavor(II->getIntrinsicID());
1498 assert(OCF != OCF_INVALID && "unexpected!");
Jim Grosbach7815f562012-02-03 00:07:04 +00001499
Sanjoy Dasb0984472015-04-08 04:27:22 +00001500 Value *OperationResult = nullptr;
1501 Constant *OverflowResult = nullptr;
1502 if (OptimizeOverflowCheck(OCF, II->getArgOperand(0), II->getArgOperand(1),
1503 *II, OperationResult, OverflowResult))
1504 return CreateOverflowTuple(II, OperationResult, OverflowResult);
Benjamin Kramera420df22014-07-04 10:22:21 +00001505
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001506 break;
Erik Eckstein096ff7d2014-12-11 08:02:30 +00001507 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001508
Matt Arsenaultd6511b42014-10-21 23:00:20 +00001509 case Intrinsic::minnum:
1510 case Intrinsic::maxnum: {
1511 Value *Arg0 = II->getArgOperand(0);
1512 Value *Arg1 = II->getArgOperand(1);
Sanjay Patel0069f562016-01-31 16:35:23 +00001513 // Canonicalize constants to the RHS.
1514 if (isa<ConstantFP>(Arg0) && !isa<ConstantFP>(Arg1)) {
Matt Arsenaultd6511b42014-10-21 23:00:20 +00001515 II->setArgOperand(0, Arg1);
1516 II->setArgOperand(1, Arg0);
1517 return II;
1518 }
Sanjay Patel0069f562016-01-31 16:35:23 +00001519 if (Value *V = simplifyMinnumMaxnum(*II))
Sanjay Patel4b198802016-02-01 22:23:39 +00001520 return replaceInstUsesWith(*II, V);
Matt Arsenaultd6511b42014-10-21 23:00:20 +00001521 break;
1522 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001523 case Intrinsic::ppc_altivec_lvx:
1524 case Intrinsic::ppc_altivec_lvxl:
Bill Wendlingb902f1d2011-04-13 00:36:11 +00001525 // Turn PPC lvx -> load if the pointer is known aligned.
Justin Bogner99798402016-08-05 01:06:44 +00001526 if (getOrEnforceKnownAlignment(II->getArgOperand(0), 16, DL, II, &AC,
1527 &DT) >= 16) {
Gabor Greif589a0b92010-06-24 12:58:35 +00001528 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(0),
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001529 PointerType::getUnqual(II->getType()));
1530 return new LoadInst(Ptr);
1531 }
1532 break;
Bill Schmidt72954782014-11-12 04:19:40 +00001533 case Intrinsic::ppc_vsx_lxvw4x:
1534 case Intrinsic::ppc_vsx_lxvd2x: {
1535 // Turn PPC VSX loads into normal loads.
1536 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(0),
1537 PointerType::getUnqual(II->getType()));
1538 return new LoadInst(Ptr, Twine(""), false, 1);
1539 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001540 case Intrinsic::ppc_altivec_stvx:
1541 case Intrinsic::ppc_altivec_stvxl:
1542 // Turn stvx -> store if the pointer is known aligned.
Justin Bogner99798402016-08-05 01:06:44 +00001543 if (getOrEnforceKnownAlignment(II->getArgOperand(1), 16, DL, II, &AC,
1544 &DT) >= 16) {
Jim Grosbach7815f562012-02-03 00:07:04 +00001545 Type *OpPtrTy =
Gabor Greifa6d75e22010-06-24 15:51:11 +00001546 PointerType::getUnqual(II->getArgOperand(0)->getType());
1547 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(1), OpPtrTy);
1548 return new StoreInst(II->getArgOperand(0), Ptr);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001549 }
1550 break;
Bill Schmidt72954782014-11-12 04:19:40 +00001551 case Intrinsic::ppc_vsx_stxvw4x:
1552 case Intrinsic::ppc_vsx_stxvd2x: {
1553 // Turn PPC VSX stores into normal stores.
1554 Type *OpPtrTy = PointerType::getUnqual(II->getArgOperand(0)->getType());
1555 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(1), OpPtrTy);
1556 return new StoreInst(II->getArgOperand(0), Ptr, false, 1);
1557 }
Hal Finkel221f4672015-02-26 18:56:03 +00001558 case Intrinsic::ppc_qpx_qvlfs:
1559 // Turn PPC QPX qvlfs -> load if the pointer is known aligned.
Justin Bogner99798402016-08-05 01:06:44 +00001560 if (getOrEnforceKnownAlignment(II->getArgOperand(0), 16, DL, II, &AC,
1561 &DT) >= 16) {
Hal Finkelf0d68d72015-05-11 06:37:03 +00001562 Type *VTy = VectorType::get(Builder->getFloatTy(),
1563 II->getType()->getVectorNumElements());
Hal Finkel221f4672015-02-26 18:56:03 +00001564 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(0),
Hal Finkelf0d68d72015-05-11 06:37:03 +00001565 PointerType::getUnqual(VTy));
1566 Value *Load = Builder->CreateLoad(Ptr);
1567 return new FPExtInst(Load, II->getType());
Hal Finkel221f4672015-02-26 18:56:03 +00001568 }
1569 break;
1570 case Intrinsic::ppc_qpx_qvlfd:
1571 // Turn PPC QPX qvlfd -> load if the pointer is known aligned.
Justin Bogner99798402016-08-05 01:06:44 +00001572 if (getOrEnforceKnownAlignment(II->getArgOperand(0), 32, DL, II, &AC,
1573 &DT) >= 32) {
Hal Finkel221f4672015-02-26 18:56:03 +00001574 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(0),
1575 PointerType::getUnqual(II->getType()));
1576 return new LoadInst(Ptr);
1577 }
1578 break;
1579 case Intrinsic::ppc_qpx_qvstfs:
1580 // Turn PPC QPX qvstfs -> store if the pointer is known aligned.
Justin Bogner99798402016-08-05 01:06:44 +00001581 if (getOrEnforceKnownAlignment(II->getArgOperand(1), 16, DL, II, &AC,
1582 &DT) >= 16) {
Hal Finkelf0d68d72015-05-11 06:37:03 +00001583 Type *VTy = VectorType::get(Builder->getFloatTy(),
1584 II->getArgOperand(0)->getType()->getVectorNumElements());
1585 Value *TOp = Builder->CreateFPTrunc(II->getArgOperand(0), VTy);
1586 Type *OpPtrTy = PointerType::getUnqual(VTy);
Hal Finkel221f4672015-02-26 18:56:03 +00001587 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(1), OpPtrTy);
Hal Finkelf0d68d72015-05-11 06:37:03 +00001588 return new StoreInst(TOp, Ptr);
Hal Finkel221f4672015-02-26 18:56:03 +00001589 }
1590 break;
1591 case Intrinsic::ppc_qpx_qvstfd:
1592 // Turn PPC QPX qvstfd -> store if the pointer is known aligned.
Justin Bogner99798402016-08-05 01:06:44 +00001593 if (getOrEnforceKnownAlignment(II->getArgOperand(1), 32, DL, II, &AC,
1594 &DT) >= 32) {
Hal Finkel221f4672015-02-26 18:56:03 +00001595 Type *OpPtrTy =
1596 PointerType::getUnqual(II->getArgOperand(0)->getType());
1597 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(1), OpPtrTy);
1598 return new StoreInst(II->getArgOperand(0), Ptr);
1599 }
1600 break;
Simon Pilgrim20c607b2015-09-12 13:39:53 +00001601
Simon Pilgrim20c607b2015-09-12 13:39:53 +00001602 case Intrinsic::x86_vcvtph2ps_128:
1603 case Intrinsic::x86_vcvtph2ps_256: {
1604 auto Arg = II->getArgOperand(0);
1605 auto ArgType = cast<VectorType>(Arg->getType());
1606 auto RetType = cast<VectorType>(II->getType());
1607 unsigned ArgWidth = ArgType->getNumElements();
1608 unsigned RetWidth = RetType->getNumElements();
1609 assert(RetWidth <= ArgWidth && "Unexpected input/return vector widths");
1610 assert(ArgType->isIntOrIntVectorTy() &&
1611 ArgType->getScalarSizeInBits() == 16 &&
1612 "CVTPH2PS input type should be 16-bit integer vector");
1613 assert(RetType->getScalarType()->isFloatTy() &&
1614 "CVTPH2PS output type should be 32-bit float vector");
1615
1616 // Constant folding: Convert to generic half to single conversion.
Simon Pilgrim48ffca02015-09-12 14:00:17 +00001617 if (isa<ConstantAggregateZero>(Arg))
Sanjay Patel4b198802016-02-01 22:23:39 +00001618 return replaceInstUsesWith(*II, ConstantAggregateZero::get(RetType));
Simon Pilgrim20c607b2015-09-12 13:39:53 +00001619
Simon Pilgrim48ffca02015-09-12 14:00:17 +00001620 if (isa<ConstantDataVector>(Arg)) {
Simon Pilgrim20c607b2015-09-12 13:39:53 +00001621 auto VectorHalfAsShorts = Arg;
1622 if (RetWidth < ArgWidth) {
Craig Topper99d1eab2016-06-12 00:41:19 +00001623 SmallVector<uint32_t, 8> SubVecMask;
Simon Pilgrim20c607b2015-09-12 13:39:53 +00001624 for (unsigned i = 0; i != RetWidth; ++i)
1625 SubVecMask.push_back((int)i);
1626 VectorHalfAsShorts = Builder->CreateShuffleVector(
1627 Arg, UndefValue::get(ArgType), SubVecMask);
1628 }
1629
1630 auto VectorHalfType =
1631 VectorType::get(Type::getHalfTy(II->getContext()), RetWidth);
1632 auto VectorHalfs =
1633 Builder->CreateBitCast(VectorHalfAsShorts, VectorHalfType);
1634 auto VectorFloats = Builder->CreateFPExt(VectorHalfs, RetType);
Sanjay Patel4b198802016-02-01 22:23:39 +00001635 return replaceInstUsesWith(*II, VectorFloats);
Simon Pilgrim20c607b2015-09-12 13:39:53 +00001636 }
1637
1638 // We only use the lowest lanes of the argument.
Simon Pilgrim996725e2015-09-19 11:41:53 +00001639 if (Value *V = SimplifyDemandedVectorEltsLow(Arg, ArgWidth, RetWidth)) {
Simon Pilgrim20c607b2015-09-12 13:39:53 +00001640 II->setArgOperand(0, V);
1641 return II;
1642 }
1643 break;
1644 }
1645
Chandler Carruthcf414cf2011-01-10 07:19:37 +00001646 case Intrinsic::x86_sse_cvtss2si:
1647 case Intrinsic::x86_sse_cvtss2si64:
1648 case Intrinsic::x86_sse_cvttss2si:
1649 case Intrinsic::x86_sse_cvttss2si64:
1650 case Intrinsic::x86_sse2_cvtsd2si:
1651 case Intrinsic::x86_sse2_cvtsd2si64:
1652 case Intrinsic::x86_sse2_cvttsd2si:
1653 case Intrinsic::x86_sse2_cvttsd2si64: {
1654 // These intrinsics only demand the 0th element of their input vectors. If
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001655 // we can simplify the input based on that, do so now.
Simon Pilgrim996725e2015-09-19 11:41:53 +00001656 Value *Arg = II->getArgOperand(0);
1657 unsigned VWidth = Arg->getType()->getVectorNumElements();
1658 if (Value *V = SimplifyDemandedVectorEltsLow(Arg, VWidth, 1)) {
Gabor Greif5b1370e2010-06-28 16:50:57 +00001659 II->setArgOperand(0, V);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001660 return II;
1661 }
Simon Pilgrim18617d12015-08-05 08:18:00 +00001662 break;
1663 }
1664
Simon Pilgrim91e3ac82016-06-07 08:18:35 +00001665 case Intrinsic::x86_mmx_pmovmskb:
1666 case Intrinsic::x86_sse_movmsk_ps:
1667 case Intrinsic::x86_sse2_movmsk_pd:
1668 case Intrinsic::x86_sse2_pmovmskb_128:
1669 case Intrinsic::x86_avx_movmsk_pd_256:
1670 case Intrinsic::x86_avx_movmsk_ps_256:
1671 case Intrinsic::x86_avx2_pmovmskb: {
1672 if (Value *V = simplifyX86movmsk(*II, *Builder))
1673 return replaceInstUsesWith(*II, V);
1674 break;
1675 }
1676
Simon Pilgrim471efd22016-02-20 23:17:35 +00001677 case Intrinsic::x86_sse_comieq_ss:
1678 case Intrinsic::x86_sse_comige_ss:
1679 case Intrinsic::x86_sse_comigt_ss:
1680 case Intrinsic::x86_sse_comile_ss:
1681 case Intrinsic::x86_sse_comilt_ss:
1682 case Intrinsic::x86_sse_comineq_ss:
1683 case Intrinsic::x86_sse_ucomieq_ss:
1684 case Intrinsic::x86_sse_ucomige_ss:
1685 case Intrinsic::x86_sse_ucomigt_ss:
1686 case Intrinsic::x86_sse_ucomile_ss:
1687 case Intrinsic::x86_sse_ucomilt_ss:
1688 case Intrinsic::x86_sse_ucomineq_ss:
1689 case Intrinsic::x86_sse2_comieq_sd:
1690 case Intrinsic::x86_sse2_comige_sd:
1691 case Intrinsic::x86_sse2_comigt_sd:
1692 case Intrinsic::x86_sse2_comile_sd:
1693 case Intrinsic::x86_sse2_comilt_sd:
1694 case Intrinsic::x86_sse2_comineq_sd:
1695 case Intrinsic::x86_sse2_ucomieq_sd:
1696 case Intrinsic::x86_sse2_ucomige_sd:
1697 case Intrinsic::x86_sse2_ucomigt_sd:
1698 case Intrinsic::x86_sse2_ucomile_sd:
1699 case Intrinsic::x86_sse2_ucomilt_sd:
1700 case Intrinsic::x86_sse2_ucomineq_sd: {
1701 // These intrinsics only demand the 0th element of their input vectors. If
1702 // we can simplify the input based on that, do so now.
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00001703 bool MadeChange = false;
Simon Pilgrim471efd22016-02-20 23:17:35 +00001704 Value *Arg0 = II->getArgOperand(0);
1705 Value *Arg1 = II->getArgOperand(1);
1706 unsigned VWidth = Arg0->getType()->getVectorNumElements();
1707 if (Value *V = SimplifyDemandedVectorEltsLow(Arg0, VWidth, 1)) {
1708 II->setArgOperand(0, V);
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00001709 MadeChange = true;
Simon Pilgrim471efd22016-02-20 23:17:35 +00001710 }
1711 if (Value *V = SimplifyDemandedVectorEltsLow(Arg1, VWidth, 1)) {
1712 II->setArgOperand(1, V);
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00001713 MadeChange = true;
Simon Pilgrim471efd22016-02-20 23:17:35 +00001714 }
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00001715 if (MadeChange)
1716 return II;
Simon Pilgrim471efd22016-02-20 23:17:35 +00001717 break;
1718 }
1719
Simon Pilgrim424da162016-04-24 18:12:42 +00001720 case Intrinsic::x86_sse_add_ss:
1721 case Intrinsic::x86_sse_sub_ss:
1722 case Intrinsic::x86_sse_mul_ss:
1723 case Intrinsic::x86_sse_div_ss:
1724 case Intrinsic::x86_sse_min_ss:
1725 case Intrinsic::x86_sse_max_ss:
1726 case Intrinsic::x86_sse_cmp_ss:
1727 case Intrinsic::x86_sse2_add_sd:
1728 case Intrinsic::x86_sse2_sub_sd:
1729 case Intrinsic::x86_sse2_mul_sd:
1730 case Intrinsic::x86_sse2_div_sd:
1731 case Intrinsic::x86_sse2_min_sd:
1732 case Intrinsic::x86_sse2_max_sd:
1733 case Intrinsic::x86_sse2_cmp_sd: {
1734 // These intrinsics only demand the lowest element of the second input
1735 // vector.
1736 Value *Arg1 = II->getArgOperand(1);
1737 unsigned VWidth = Arg1->getType()->getVectorNumElements();
1738 if (Value *V = SimplifyDemandedVectorEltsLow(Arg1, VWidth, 1)) {
1739 II->setArgOperand(1, V);
1740 return II;
1741 }
1742 break;
1743 }
1744
1745 case Intrinsic::x86_sse41_round_ss:
1746 case Intrinsic::x86_sse41_round_sd: {
1747 // These intrinsics demand the upper elements of the first input vector and
1748 // the lowest element of the second input vector.
1749 bool MadeChange = false;
1750 Value *Arg0 = II->getArgOperand(0);
1751 Value *Arg1 = II->getArgOperand(1);
1752 unsigned VWidth = Arg0->getType()->getVectorNumElements();
1753 if (Value *V = SimplifyDemandedVectorEltsHigh(Arg0, VWidth, VWidth - 1)) {
1754 II->setArgOperand(0, V);
1755 MadeChange = true;
1756 }
1757 if (Value *V = SimplifyDemandedVectorEltsLow(Arg1, VWidth, 1)) {
1758 II->setArgOperand(1, V);
1759 MadeChange = true;
1760 }
1761 if (MadeChange)
1762 return II;
1763 break;
1764 }
1765
Simon Pilgrima3a72b42015-08-10 20:21:15 +00001766 // Constant fold ashr( <A x Bi>, Ci ).
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00001767 // Constant fold lshr( <A x Bi>, Ci ).
1768 // Constant fold shl( <A x Bi>, Ci ).
Simon Pilgrima3a72b42015-08-10 20:21:15 +00001769 case Intrinsic::x86_sse2_psrai_d:
1770 case Intrinsic::x86_sse2_psrai_w:
Simon Pilgrima3a72b42015-08-10 20:21:15 +00001771 case Intrinsic::x86_avx2_psrai_d:
1772 case Intrinsic::x86_avx2_psrai_w:
Simon Pilgrim18617d12015-08-05 08:18:00 +00001773 case Intrinsic::x86_sse2_psrli_d:
1774 case Intrinsic::x86_sse2_psrli_q:
1775 case Intrinsic::x86_sse2_psrli_w:
Simon Pilgrim18617d12015-08-05 08:18:00 +00001776 case Intrinsic::x86_avx2_psrli_d:
1777 case Intrinsic::x86_avx2_psrli_q:
1778 case Intrinsic::x86_avx2_psrli_w:
Michael J. Spencerdee4b2c2014-04-24 00:58:18 +00001779 case Intrinsic::x86_sse2_pslli_d:
1780 case Intrinsic::x86_sse2_pslli_q:
1781 case Intrinsic::x86_sse2_pslli_w:
Simon Pilgrim18617d12015-08-05 08:18:00 +00001782 case Intrinsic::x86_avx2_pslli_d:
1783 case Intrinsic::x86_avx2_pslli_q:
1784 case Intrinsic::x86_avx2_pslli_w:
Sanjay Patel6038d3e2016-01-29 23:27:03 +00001785 if (Value *V = simplifyX86immShift(*II, *Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00001786 return replaceInstUsesWith(*II, V);
Simon Pilgrim18617d12015-08-05 08:18:00 +00001787 break;
1788
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00001789 case Intrinsic::x86_sse2_psra_d:
1790 case Intrinsic::x86_sse2_psra_w:
1791 case Intrinsic::x86_avx2_psra_d:
1792 case Intrinsic::x86_avx2_psra_w:
1793 case Intrinsic::x86_sse2_psrl_d:
1794 case Intrinsic::x86_sse2_psrl_q:
1795 case Intrinsic::x86_sse2_psrl_w:
1796 case Intrinsic::x86_avx2_psrl_d:
1797 case Intrinsic::x86_avx2_psrl_q:
1798 case Intrinsic::x86_avx2_psrl_w:
1799 case Intrinsic::x86_sse2_psll_d:
1800 case Intrinsic::x86_sse2_psll_q:
1801 case Intrinsic::x86_sse2_psll_w:
1802 case Intrinsic::x86_avx2_psll_d:
1803 case Intrinsic::x86_avx2_psll_q:
1804 case Intrinsic::x86_avx2_psll_w: {
Sanjay Patel6038d3e2016-01-29 23:27:03 +00001805 if (Value *V = simplifyX86immShift(*II, *Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00001806 return replaceInstUsesWith(*II, V);
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00001807
1808 // SSE2/AVX2 uses only the first 64-bits of the 128-bit vector
1809 // operand to compute the shift amount.
Simon Pilgrim996725e2015-09-19 11:41:53 +00001810 Value *Arg1 = II->getArgOperand(1);
1811 assert(Arg1->getType()->getPrimitiveSizeInBits() == 128 &&
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00001812 "Unexpected packed shift size");
Simon Pilgrim996725e2015-09-19 11:41:53 +00001813 unsigned VWidth = Arg1->getType()->getVectorNumElements();
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00001814
Simon Pilgrim996725e2015-09-19 11:41:53 +00001815 if (Value *V = SimplifyDemandedVectorEltsLow(Arg1, VWidth, VWidth / 2)) {
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00001816 II->setArgOperand(1, V);
1817 return II;
1818 }
1819 break;
1820 }
1821
Simon Pilgrimdb9893f2016-06-07 10:27:15 +00001822 case Intrinsic::x86_avx2_psllv_d:
1823 case Intrinsic::x86_avx2_psllv_d_256:
1824 case Intrinsic::x86_avx2_psllv_q:
1825 case Intrinsic::x86_avx2_psllv_q_256:
1826 case Intrinsic::x86_avx2_psrav_d:
1827 case Intrinsic::x86_avx2_psrav_d_256:
1828 case Intrinsic::x86_avx2_psrlv_d:
1829 case Intrinsic::x86_avx2_psrlv_d_256:
1830 case Intrinsic::x86_avx2_psrlv_q:
1831 case Intrinsic::x86_avx2_psrlv_q_256:
1832 if (Value *V = simplifyX86varShift(*II, *Builder))
1833 return replaceInstUsesWith(*II, V);
1834 break;
1835
Sanjay Patelc86867c2015-04-16 17:52:13 +00001836 case Intrinsic::x86_sse41_insertps:
Sanjay Patel6038d3e2016-01-29 23:27:03 +00001837 if (Value *V = simplifyX86insertps(*II, *Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00001838 return replaceInstUsesWith(*II, V);
Sanjay Patelc86867c2015-04-16 17:52:13 +00001839 break;
Simon Pilgrim54fcd622015-07-25 20:41:00 +00001840
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001841 case Intrinsic::x86_sse4a_extrq: {
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001842 Value *Op0 = II->getArgOperand(0);
1843 Value *Op1 = II->getArgOperand(1);
1844 unsigned VWidth0 = Op0->getType()->getVectorNumElements();
1845 unsigned VWidth1 = Op1->getType()->getVectorNumElements();
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00001846 assert(Op0->getType()->getPrimitiveSizeInBits() == 128 &&
1847 Op1->getType()->getPrimitiveSizeInBits() == 128 && VWidth0 == 2 &&
1848 VWidth1 == 16 && "Unexpected operand sizes");
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001849
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00001850 // See if we're dealing with constant values.
1851 Constant *C1 = dyn_cast<Constant>(Op1);
1852 ConstantInt *CILength =
1853 C1 ? dyn_cast<ConstantInt>(C1->getAggregateElement((unsigned)0))
1854 : nullptr;
1855 ConstantInt *CIIndex =
1856 C1 ? dyn_cast<ConstantInt>(C1->getAggregateElement((unsigned)1))
1857 : nullptr;
1858
1859 // Attempt to simplify to a constant, shuffle vector or EXTRQI call.
Sanjay Patel6038d3e2016-01-29 23:27:03 +00001860 if (Value *V = simplifyX86extrq(*II, Op0, CILength, CIIndex, *Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00001861 return replaceInstUsesWith(*II, V);
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00001862
1863 // EXTRQ only uses the lowest 64-bits of the first 128-bit vector
1864 // operands and the lowest 16-bits of the second.
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00001865 bool MadeChange = false;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001866 if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth0, 1)) {
1867 II->setArgOperand(0, V);
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00001868 MadeChange = true;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001869 }
1870 if (Value *V = SimplifyDemandedVectorEltsLow(Op1, VWidth1, 2)) {
1871 II->setArgOperand(1, V);
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00001872 MadeChange = true;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001873 }
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00001874 if (MadeChange)
1875 return II;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001876 break;
1877 }
1878
1879 case Intrinsic::x86_sse4a_extrqi: {
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00001880 // EXTRQI: Extract Length bits starting from Index. Zero pad the remaining
1881 // bits of the lower 64-bits. The upper 64-bits are undefined.
1882 Value *Op0 = II->getArgOperand(0);
1883 unsigned VWidth = Op0->getType()->getVectorNumElements();
1884 assert(Op0->getType()->getPrimitiveSizeInBits() == 128 && VWidth == 2 &&
1885 "Unexpected operand size");
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001886
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00001887 // See if we're dealing with constant values.
1888 ConstantInt *CILength = dyn_cast<ConstantInt>(II->getArgOperand(1));
1889 ConstantInt *CIIndex = dyn_cast<ConstantInt>(II->getArgOperand(2));
1890
1891 // Attempt to simplify to a constant or shuffle vector.
Sanjay Patel6038d3e2016-01-29 23:27:03 +00001892 if (Value *V = simplifyX86extrq(*II, Op0, CILength, CIIndex, *Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00001893 return replaceInstUsesWith(*II, V);
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00001894
1895 // EXTRQI only uses the lowest 64-bits of the first 128-bit vector
1896 // operand.
1897 if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth, 1)) {
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001898 II->setArgOperand(0, V);
1899 return II;
1900 }
1901 break;
1902 }
1903
1904 case Intrinsic::x86_sse4a_insertq: {
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00001905 Value *Op0 = II->getArgOperand(0);
1906 Value *Op1 = II->getArgOperand(1);
1907 unsigned VWidth = Op0->getType()->getVectorNumElements();
1908 assert(Op0->getType()->getPrimitiveSizeInBits() == 128 &&
1909 Op1->getType()->getPrimitiveSizeInBits() == 128 && VWidth == 2 &&
1910 Op1->getType()->getVectorNumElements() == 2 &&
1911 "Unexpected operand size");
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001912
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00001913 // See if we're dealing with constant values.
1914 Constant *C1 = dyn_cast<Constant>(Op1);
1915 ConstantInt *CI11 =
1916 C1 ? dyn_cast<ConstantInt>(C1->getAggregateElement((unsigned)1))
1917 : nullptr;
1918
1919 // Attempt to simplify to a constant, shuffle vector or INSERTQI call.
1920 if (CI11) {
Benjamin Kramer46e38f32016-06-08 10:01:20 +00001921 const APInt &V11 = CI11->getValue();
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00001922 APInt Len = V11.zextOrTrunc(6);
1923 APInt Idx = V11.lshr(8).zextOrTrunc(6);
Sanjay Patel6038d3e2016-01-29 23:27:03 +00001924 if (Value *V = simplifyX86insertq(*II, Op0, Op1, Len, Idx, *Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00001925 return replaceInstUsesWith(*II, V);
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00001926 }
1927
1928 // INSERTQ only uses the lowest 64-bits of the first 128-bit vector
1929 // operand.
1930 if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth, 1)) {
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001931 II->setArgOperand(0, V);
1932 return II;
1933 }
1934 break;
1935 }
1936
Filipe Cabecinhas1a805952014-04-24 00:38:14 +00001937 case Intrinsic::x86_sse4a_insertqi: {
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00001938 // INSERTQI: Extract lowest Length bits from lower half of second source and
1939 // insert over first source starting at Index bit. The upper 64-bits are
1940 // undefined.
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001941 Value *Op0 = II->getArgOperand(0);
1942 Value *Op1 = II->getArgOperand(1);
1943 unsigned VWidth0 = Op0->getType()->getVectorNumElements();
1944 unsigned VWidth1 = Op1->getType()->getVectorNumElements();
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00001945 assert(Op0->getType()->getPrimitiveSizeInBits() == 128 &&
1946 Op1->getType()->getPrimitiveSizeInBits() == 128 && VWidth0 == 2 &&
1947 VWidth1 == 2 && "Unexpected operand sizes");
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001948
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00001949 // See if we're dealing with constant values.
1950 ConstantInt *CILength = dyn_cast<ConstantInt>(II->getArgOperand(2));
1951 ConstantInt *CIIndex = dyn_cast<ConstantInt>(II->getArgOperand(3));
1952
1953 // Attempt to simplify to a constant or shuffle vector.
1954 if (CILength && CIIndex) {
1955 APInt Len = CILength->getValue().zextOrTrunc(6);
1956 APInt Idx = CIIndex->getValue().zextOrTrunc(6);
Sanjay Patel6038d3e2016-01-29 23:27:03 +00001957 if (Value *V = simplifyX86insertq(*II, Op0, Op1, Len, Idx, *Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00001958 return replaceInstUsesWith(*II, V);
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00001959 }
1960
1961 // INSERTQI only uses the lowest 64-bits of the first two 128-bit vector
1962 // operands.
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00001963 bool MadeChange = false;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001964 if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth0, 1)) {
1965 II->setArgOperand(0, V);
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00001966 MadeChange = true;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001967 }
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001968 if (Value *V = SimplifyDemandedVectorEltsLow(Op1, VWidth1, 1)) {
1969 II->setArgOperand(1, V);
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00001970 MadeChange = true;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001971 }
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00001972 if (MadeChange)
1973 return II;
Filipe Cabecinhas1a805952014-04-24 00:38:14 +00001974 break;
1975 }
1976
Filipe Cabecinhas82ac07c2014-05-27 03:42:20 +00001977 case Intrinsic::x86_sse41_pblendvb:
1978 case Intrinsic::x86_sse41_blendvps:
1979 case Intrinsic::x86_sse41_blendvpd:
1980 case Intrinsic::x86_avx_blendv_ps_256:
1981 case Intrinsic::x86_avx_blendv_pd_256:
1982 case Intrinsic::x86_avx2_pblendvb: {
1983 // Convert blendv* to vector selects if the mask is constant.
1984 // This optimization is convoluted because the intrinsic is defined as
1985 // getting a vector of floats or doubles for the ps and pd versions.
1986 // FIXME: That should be changed.
Simon Pilgrim8c049d52015-08-12 08:08:56 +00001987
1988 Value *Op0 = II->getArgOperand(0);
1989 Value *Op1 = II->getArgOperand(1);
Filipe Cabecinhas82ac07c2014-05-27 03:42:20 +00001990 Value *Mask = II->getArgOperand(2);
Simon Pilgrim8c049d52015-08-12 08:08:56 +00001991
1992 // fold (blend A, A, Mask) -> A
1993 if (Op0 == Op1)
Sanjay Patel4b198802016-02-01 22:23:39 +00001994 return replaceInstUsesWith(CI, Op0);
Simon Pilgrim8c049d52015-08-12 08:08:56 +00001995
1996 // Zero Mask - select 1st argument.
Simon Pilgrim93f59f52015-08-12 08:23:36 +00001997 if (isa<ConstantAggregateZero>(Mask))
Sanjay Patel4b198802016-02-01 22:23:39 +00001998 return replaceInstUsesWith(CI, Op0);
Simon Pilgrim8c049d52015-08-12 08:08:56 +00001999
2000 // Constant Mask - select 1st/2nd argument lane based on top bit of mask.
Sanjay Patel368ac5d2016-02-21 17:29:33 +00002001 if (auto *ConstantMask = dyn_cast<ConstantDataVector>(Mask)) {
2002 Constant *NewSelector = getNegativeIsTrueBoolVec(ConstantMask);
Simon Pilgrim8c049d52015-08-12 08:08:56 +00002003 return SelectInst::Create(NewSelector, Op1, Op0, "blendv");
Filipe Cabecinhas82ac07c2014-05-27 03:42:20 +00002004 }
Simon Pilgrim8c049d52015-08-12 08:08:56 +00002005 break;
Filipe Cabecinhas82ac07c2014-05-27 03:42:20 +00002006 }
2007
Andrea Di Biagio0594e2a2015-09-30 16:44:39 +00002008 case Intrinsic::x86_ssse3_pshuf_b_128:
Simon Pilgrimc0c56e72016-04-24 17:00:34 +00002009 case Intrinsic::x86_avx2_pshuf_b:
2010 if (Value *V = simplifyX86pshufb(*II, *Builder))
2011 return replaceInstUsesWith(*II, V);
2012 break;
Andrea Di Biagio0594e2a2015-09-30 16:44:39 +00002013
Rafael Espindolabad3f772014-04-21 22:06:04 +00002014 case Intrinsic::x86_avx_vpermilvar_ps:
2015 case Intrinsic::x86_avx_vpermilvar_ps_256:
2016 case Intrinsic::x86_avx_vpermilvar_pd:
Simon Pilgrim2f6097d2016-04-24 17:23:46 +00002017 case Intrinsic::x86_avx_vpermilvar_pd_256:
2018 if (Value *V = simplifyX86vpermilvar(*II, *Builder))
2019 return replaceInstUsesWith(*II, V);
2020 break;
Rafael Espindolabad3f772014-04-21 22:06:04 +00002021
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +00002022 case Intrinsic::x86_avx2_permd:
2023 case Intrinsic::x86_avx2_permps:
2024 if (Value *V = simplifyX86vpermv(*II, *Builder))
2025 return replaceInstUsesWith(*II, V);
2026 break;
2027
Sanjay Patelccf5f242015-03-20 21:47:56 +00002028 case Intrinsic::x86_avx_vperm2f128_pd_256:
2029 case Intrinsic::x86_avx_vperm2f128_ps_256:
2030 case Intrinsic::x86_avx_vperm2f128_si_256:
Sanjay Patele304bea2015-03-24 22:39:29 +00002031 case Intrinsic::x86_avx2_vperm2i128:
Sanjay Patel6038d3e2016-01-29 23:27:03 +00002032 if (Value *V = simplifyX86vperm2(*II, *Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00002033 return replaceInstUsesWith(*II, V);
Sanjay Patelccf5f242015-03-20 21:47:56 +00002034 break;
2035
Sanjay Patel98a71502016-02-29 23:16:48 +00002036 case Intrinsic::x86_avx_maskload_ps:
Sanjay Patel6f2c01f2016-02-29 23:59:00 +00002037 case Intrinsic::x86_avx_maskload_pd:
2038 case Intrinsic::x86_avx_maskload_ps_256:
2039 case Intrinsic::x86_avx_maskload_pd_256:
2040 case Intrinsic::x86_avx2_maskload_d:
2041 case Intrinsic::x86_avx2_maskload_q:
2042 case Intrinsic::x86_avx2_maskload_d_256:
2043 case Intrinsic::x86_avx2_maskload_q_256:
Sanjay Patel98a71502016-02-29 23:16:48 +00002044 if (Instruction *I = simplifyX86MaskedLoad(*II, *this))
2045 return I;
2046 break;
2047
Sanjay Patelc4acbae2016-03-12 15:16:59 +00002048 case Intrinsic::x86_sse2_maskmov_dqu:
Sanjay Patel1ace9932016-02-26 21:04:14 +00002049 case Intrinsic::x86_avx_maskstore_ps:
2050 case Intrinsic::x86_avx_maskstore_pd:
2051 case Intrinsic::x86_avx_maskstore_ps_256:
2052 case Intrinsic::x86_avx_maskstore_pd_256:
Sanjay Patelfc7e7eb2016-02-26 21:51:44 +00002053 case Intrinsic::x86_avx2_maskstore_d:
2054 case Intrinsic::x86_avx2_maskstore_q:
2055 case Intrinsic::x86_avx2_maskstore_d_256:
2056 case Intrinsic::x86_avx2_maskstore_q_256:
Sanjay Patel1ace9932016-02-26 21:04:14 +00002057 if (simplifyX86MaskedStore(*II, *this))
2058 return nullptr;
2059 break;
2060
Simon Pilgrim1d1c56e22015-10-11 14:38:34 +00002061 case Intrinsic::x86_xop_vpcomb:
2062 case Intrinsic::x86_xop_vpcomd:
2063 case Intrinsic::x86_xop_vpcomq:
2064 case Intrinsic::x86_xop_vpcomw:
Sanjay Patel6038d3e2016-01-29 23:27:03 +00002065 if (Value *V = simplifyX86vpcom(*II, *Builder, true))
Sanjay Patel4b198802016-02-01 22:23:39 +00002066 return replaceInstUsesWith(*II, V);
Simon Pilgrim1d1c56e22015-10-11 14:38:34 +00002067 break;
2068
2069 case Intrinsic::x86_xop_vpcomub:
2070 case Intrinsic::x86_xop_vpcomud:
2071 case Intrinsic::x86_xop_vpcomuq:
2072 case Intrinsic::x86_xop_vpcomuw:
Sanjay Patel6038d3e2016-01-29 23:27:03 +00002073 if (Value *V = simplifyX86vpcom(*II, *Builder, false))
Sanjay Patel4b198802016-02-01 22:23:39 +00002074 return replaceInstUsesWith(*II, V);
Simon Pilgrim1d1c56e22015-10-11 14:38:34 +00002075 break;
2076
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002077 case Intrinsic::ppc_altivec_vperm:
2078 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
Bill Schmidta1184632014-06-05 19:46:04 +00002079 // Note that ppc_altivec_vperm has a big-endian bias, so when creating
2080 // a vectorshuffle for little endian, we must undo the transformation
2081 // performed on vec_perm in altivec.h. That is, we must complement
2082 // the permutation mask with respect to 31 and reverse the order of
2083 // V1 and V2.
Chris Lattner0256be92012-01-27 03:08:05 +00002084 if (Constant *Mask = dyn_cast<Constant>(II->getArgOperand(2))) {
2085 assert(Mask->getType()->getVectorNumElements() == 16 &&
2086 "Bad type for intrinsic!");
Jim Grosbach7815f562012-02-03 00:07:04 +00002087
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002088 // Check that all of the elements are integer constants or undefs.
2089 bool AllEltsOk = true;
2090 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0256be92012-01-27 03:08:05 +00002091 Constant *Elt = Mask->getAggregateElement(i);
Craig Topperf40110f2014-04-25 05:29:35 +00002092 if (!Elt || !(isa<ConstantInt>(Elt) || isa<UndefValue>(Elt))) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002093 AllEltsOk = false;
2094 break;
2095 }
2096 }
Jim Grosbach7815f562012-02-03 00:07:04 +00002097
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002098 if (AllEltsOk) {
2099 // Cast the input vectors to byte vectors.
Gabor Greif3e44ea12010-07-22 10:37:47 +00002100 Value *Op0 = Builder->CreateBitCast(II->getArgOperand(0),
2101 Mask->getType());
2102 Value *Op1 = Builder->CreateBitCast(II->getArgOperand(1),
2103 Mask->getType());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002104 Value *Result = UndefValue::get(Op0->getType());
Jim Grosbach7815f562012-02-03 00:07:04 +00002105
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002106 // Only extract each element once.
2107 Value *ExtractedElts[32];
2108 memset(ExtractedElts, 0, sizeof(ExtractedElts));
Jim Grosbach7815f562012-02-03 00:07:04 +00002109
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002110 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0256be92012-01-27 03:08:05 +00002111 if (isa<UndefValue>(Mask->getAggregateElement(i)))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002112 continue;
Jim Grosbach7815f562012-02-03 00:07:04 +00002113 unsigned Idx =
Chris Lattner0256be92012-01-27 03:08:05 +00002114 cast<ConstantInt>(Mask->getAggregateElement(i))->getZExtValue();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002115 Idx &= 31; // Match the hardware behavior.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002116 if (DL.isLittleEndian())
Bill Schmidta1184632014-06-05 19:46:04 +00002117 Idx = 31 - Idx;
Jim Grosbach7815f562012-02-03 00:07:04 +00002118
Craig Topperf40110f2014-04-25 05:29:35 +00002119 if (!ExtractedElts[Idx]) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002120 Value *Op0ToUse = (DL.isLittleEndian()) ? Op1 : Op0;
2121 Value *Op1ToUse = (DL.isLittleEndian()) ? Op0 : Op1;
Jim Grosbach7815f562012-02-03 00:07:04 +00002122 ExtractedElts[Idx] =
Bill Schmidta1184632014-06-05 19:46:04 +00002123 Builder->CreateExtractElement(Idx < 16 ? Op0ToUse : Op1ToUse,
Benjamin Kramer547b6c52011-09-27 20:39:19 +00002124 Builder->getInt32(Idx&15));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002125 }
Jim Grosbach7815f562012-02-03 00:07:04 +00002126
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002127 // Insert this value into the result vector.
2128 Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
Benjamin Kramer547b6c52011-09-27 20:39:19 +00002129 Builder->getInt32(i));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002130 }
2131 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
2132 }
2133 }
2134 break;
2135
Bob Wilsona4e231c2010-10-22 21:41:48 +00002136 case Intrinsic::arm_neon_vld1:
2137 case Intrinsic::arm_neon_vld2:
2138 case Intrinsic::arm_neon_vld3:
2139 case Intrinsic::arm_neon_vld4:
2140 case Intrinsic::arm_neon_vld2lane:
2141 case Intrinsic::arm_neon_vld3lane:
2142 case Intrinsic::arm_neon_vld4lane:
2143 case Intrinsic::arm_neon_vst1:
2144 case Intrinsic::arm_neon_vst2:
2145 case Intrinsic::arm_neon_vst3:
2146 case Intrinsic::arm_neon_vst4:
2147 case Intrinsic::arm_neon_vst2lane:
2148 case Intrinsic::arm_neon_vst3lane:
2149 case Intrinsic::arm_neon_vst4lane: {
Justin Bogner99798402016-08-05 01:06:44 +00002150 unsigned MemAlign =
2151 getKnownAlignment(II->getArgOperand(0), DL, II, &AC, &DT);
Bob Wilsona4e231c2010-10-22 21:41:48 +00002152 unsigned AlignArg = II->getNumArgOperands() - 1;
2153 ConstantInt *IntrAlign = dyn_cast<ConstantInt>(II->getArgOperand(AlignArg));
2154 if (IntrAlign && IntrAlign->getZExtValue() < MemAlign) {
2155 II->setArgOperand(AlignArg,
2156 ConstantInt::get(Type::getInt32Ty(II->getContext()),
2157 MemAlign, false));
2158 return II;
2159 }
2160 break;
2161 }
2162
Lang Hames3a90fab2012-05-01 00:20:38 +00002163 case Intrinsic::arm_neon_vmulls:
Tim Northover00ed9962014-03-29 10:18:08 +00002164 case Intrinsic::arm_neon_vmullu:
Tim Northover3b0846e2014-05-24 12:50:23 +00002165 case Intrinsic::aarch64_neon_smull:
2166 case Intrinsic::aarch64_neon_umull: {
Lang Hames3a90fab2012-05-01 00:20:38 +00002167 Value *Arg0 = II->getArgOperand(0);
2168 Value *Arg1 = II->getArgOperand(1);
2169
2170 // Handle mul by zero first:
2171 if (isa<ConstantAggregateZero>(Arg0) || isa<ConstantAggregateZero>(Arg1)) {
Sanjay Patel4b198802016-02-01 22:23:39 +00002172 return replaceInstUsesWith(CI, ConstantAggregateZero::get(II->getType()));
Lang Hames3a90fab2012-05-01 00:20:38 +00002173 }
2174
2175 // Check for constant LHS & RHS - in this case we just simplify.
Tim Northover00ed9962014-03-29 10:18:08 +00002176 bool Zext = (II->getIntrinsicID() == Intrinsic::arm_neon_vmullu ||
Tim Northover3b0846e2014-05-24 12:50:23 +00002177 II->getIntrinsicID() == Intrinsic::aarch64_neon_umull);
Lang Hames3a90fab2012-05-01 00:20:38 +00002178 VectorType *NewVT = cast<VectorType>(II->getType());
Benjamin Kramer92040952014-02-13 18:23:24 +00002179 if (Constant *CV0 = dyn_cast<Constant>(Arg0)) {
2180 if (Constant *CV1 = dyn_cast<Constant>(Arg1)) {
2181 CV0 = ConstantExpr::getIntegerCast(CV0, NewVT, /*isSigned=*/!Zext);
2182 CV1 = ConstantExpr::getIntegerCast(CV1, NewVT, /*isSigned=*/!Zext);
2183
Sanjay Patel4b198802016-02-01 22:23:39 +00002184 return replaceInstUsesWith(CI, ConstantExpr::getMul(CV0, CV1));
Lang Hames3a90fab2012-05-01 00:20:38 +00002185 }
2186
Alp Tokercb402912014-01-24 17:20:08 +00002187 // Couldn't simplify - canonicalize constant to the RHS.
Lang Hames3a90fab2012-05-01 00:20:38 +00002188 std::swap(Arg0, Arg1);
2189 }
2190
2191 // Handle mul by one:
Benjamin Kramer92040952014-02-13 18:23:24 +00002192 if (Constant *CV1 = dyn_cast<Constant>(Arg1))
Lang Hames3a90fab2012-05-01 00:20:38 +00002193 if (ConstantInt *Splat =
Benjamin Kramer92040952014-02-13 18:23:24 +00002194 dyn_cast_or_null<ConstantInt>(CV1->getSplatValue()))
2195 if (Splat->isOne())
2196 return CastInst::CreateIntegerCast(Arg0, II->getType(),
2197 /*isSigned=*/!Zext);
Lang Hames3a90fab2012-05-01 00:20:38 +00002198
2199 break;
2200 }
2201
Matt Arsenaultbef34e22016-01-22 21:30:34 +00002202 case Intrinsic::amdgcn_rcp: {
Matt Arsenaulta0050b02014-06-19 01:19:19 +00002203 if (const ConstantFP *C = dyn_cast<ConstantFP>(II->getArgOperand(0))) {
2204 const APFloat &ArgVal = C->getValueAPF();
2205 APFloat Val(ArgVal.getSemantics(), 1.0);
2206 APFloat::opStatus Status = Val.divide(ArgVal,
2207 APFloat::rmNearestTiesToEven);
2208 // Only do this if it was exact and therefore not dependent on the
2209 // rounding mode.
2210 if (Status == APFloat::opOK)
Sanjay Patel4b198802016-02-01 22:23:39 +00002211 return replaceInstUsesWith(CI, ConstantFP::get(II->getContext(), Val));
Matt Arsenaulta0050b02014-06-19 01:19:19 +00002212 }
2213
2214 break;
2215 }
Matt Arsenault2fe4fbc2016-03-30 22:28:52 +00002216 case Intrinsic::amdgcn_frexp_mant:
2217 case Intrinsic::amdgcn_frexp_exp: {
Matt Arsenault5cd4f8f2016-03-30 22:28:26 +00002218 Value *Src = II->getArgOperand(0);
2219 if (const ConstantFP *C = dyn_cast<ConstantFP>(Src)) {
2220 int Exp;
2221 APFloat Significand = frexp(C->getValueAPF(), Exp,
2222 APFloat::rmNearestTiesToEven);
2223
Matt Arsenault2fe4fbc2016-03-30 22:28:52 +00002224 if (II->getIntrinsicID() == Intrinsic::amdgcn_frexp_mant) {
2225 return replaceInstUsesWith(CI, ConstantFP::get(II->getContext(),
2226 Significand));
2227 }
2228
2229 // Match instruction special case behavior.
2230 if (Exp == APFloat::IEK_NaN || Exp == APFloat::IEK_Inf)
2231 Exp = 0;
2232
2233 return replaceInstUsesWith(CI, ConstantInt::get(II->getType(), Exp));
2234 }
2235
2236 if (isa<UndefValue>(Src))
2237 return replaceInstUsesWith(CI, UndefValue::get(II->getType()));
Matt Arsenault5cd4f8f2016-03-30 22:28:26 +00002238
2239 break;
2240 }
Matt Arsenault46a03822016-09-03 07:06:58 +00002241 case Intrinsic::amdgcn_class: {
2242 enum {
2243 S_NAN = 1 << 0, // Signaling NaN
2244 Q_NAN = 1 << 1, // Quiet NaN
2245 N_INFINITY = 1 << 2, // Negative infinity
2246 N_NORMAL = 1 << 3, // Negative normal
2247 N_SUBNORMAL = 1 << 4, // Negative subnormal
2248 N_ZERO = 1 << 5, // Negative zero
2249 P_ZERO = 1 << 6, // Positive zero
2250 P_SUBNORMAL = 1 << 7, // Positive subnormal
2251 P_NORMAL = 1 << 8, // Positive normal
2252 P_INFINITY = 1 << 9 // Positive infinity
2253 };
2254
2255 const uint32_t FullMask = S_NAN | Q_NAN | N_INFINITY | N_NORMAL |
2256 N_SUBNORMAL | N_ZERO | P_ZERO | P_SUBNORMAL | P_NORMAL | P_INFINITY;
2257
2258 Value *Src0 = II->getArgOperand(0);
2259 Value *Src1 = II->getArgOperand(1);
2260 const ConstantInt *CMask = dyn_cast<ConstantInt>(Src1);
2261 if (!CMask) {
2262 if (isa<UndefValue>(Src0))
2263 return replaceInstUsesWith(*II, UndefValue::get(II->getType()));
2264
2265 if (isa<UndefValue>(Src1))
2266 return replaceInstUsesWith(*II, ConstantInt::get(II->getType(), false));
2267 break;
2268 }
2269
2270 uint32_t Mask = CMask->getZExtValue();
2271
2272 // If all tests are made, it doesn't matter what the value is.
2273 if ((Mask & FullMask) == FullMask)
2274 return replaceInstUsesWith(*II, ConstantInt::get(II->getType(), true));
2275
2276 if ((Mask & FullMask) == 0)
2277 return replaceInstUsesWith(*II, ConstantInt::get(II->getType(), false));
2278
2279 if (Mask == (S_NAN | Q_NAN)) {
2280 // Equivalent of isnan. Replace with standard fcmp.
2281 Value *FCmp = Builder->CreateFCmpUNO(Src0, Src0);
2282 FCmp->takeName(II);
2283 return replaceInstUsesWith(*II, FCmp);
2284 }
2285
2286 const ConstantFP *CVal = dyn_cast<ConstantFP>(Src0);
2287 if (!CVal) {
2288 if (isa<UndefValue>(Src0))
2289 return replaceInstUsesWith(*II, UndefValue::get(II->getType()));
2290
2291 // Clamp mask to used bits
2292 if ((Mask & FullMask) != Mask) {
2293 CallInst *NewCall = Builder->CreateCall(II->getCalledFunction(),
2294 { Src0, ConstantInt::get(Src1->getType(), Mask & FullMask) }
2295 );
2296
2297 NewCall->takeName(II);
2298 return replaceInstUsesWith(*II, NewCall);
2299 }
2300
2301 break;
2302 }
2303
2304 const APFloat &Val = CVal->getValueAPF();
2305
2306 bool Result =
2307 ((Mask & S_NAN) && Val.isNaN() && Val.isSignaling()) ||
2308 ((Mask & Q_NAN) && Val.isNaN() && !Val.isSignaling()) ||
2309 ((Mask & N_INFINITY) && Val.isInfinity() && Val.isNegative()) ||
2310 ((Mask & N_NORMAL) && Val.isNormal() && Val.isNegative()) ||
2311 ((Mask & N_SUBNORMAL) && Val.isDenormal() && Val.isNegative()) ||
2312 ((Mask & N_ZERO) && Val.isZero() && Val.isNegative()) ||
2313 ((Mask & P_ZERO) && Val.isZero() && !Val.isNegative()) ||
2314 ((Mask & P_SUBNORMAL) && Val.isDenormal() && !Val.isNegative()) ||
2315 ((Mask & P_NORMAL) && Val.isNormal() && !Val.isNegative()) ||
2316 ((Mask & P_INFINITY) && Val.isInfinity() && !Val.isNegative());
2317
2318 return replaceInstUsesWith(*II, ConstantInt::get(II->getType(), Result));
2319 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002320 case Intrinsic::stackrestore: {
2321 // If the save is right next to the restore, remove the restore. This can
2322 // happen when variable allocas are DCE'd.
Gabor Greif589a0b92010-06-24 12:58:35 +00002323 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getArgOperand(0))) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002324 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00002325 if (&*++SS->getIterator() == II)
Sanjay Patel4b198802016-02-01 22:23:39 +00002326 return eraseInstFromFunction(CI);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002327 }
2328 }
Jim Grosbach7815f562012-02-03 00:07:04 +00002329
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002330 // Scan down this block to see if there is another stack restore in the
2331 // same block without an intervening call/alloca.
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00002332 BasicBlock::iterator BI(II);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002333 TerminatorInst *TI = II->getParent()->getTerminator();
2334 bool CannotRemove = false;
2335 for (++BI; &*BI != TI; ++BI) {
Nuno Lopes55fff832012-06-21 15:45:28 +00002336 if (isa<AllocaInst>(BI)) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002337 CannotRemove = true;
2338 break;
2339 }
2340 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
2341 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
2342 // If there is a stackrestore below this one, remove this one.
2343 if (II->getIntrinsicID() == Intrinsic::stackrestore)
Sanjay Patel4b198802016-02-01 22:23:39 +00002344 return eraseInstFromFunction(CI);
Reid Kleckner892ae2e2016-02-27 00:53:54 +00002345
2346 // Bail if we cross over an intrinsic with side effects, such as
2347 // llvm.stacksave, llvm.read_register, or llvm.setjmp.
2348 if (II->mayHaveSideEffects()) {
2349 CannotRemove = true;
2350 break;
2351 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002352 } else {
2353 // If we found a non-intrinsic call, we can't remove the stack
2354 // restore.
2355 CannotRemove = true;
2356 break;
2357 }
2358 }
2359 }
Jim Grosbach7815f562012-02-03 00:07:04 +00002360
Bill Wendlingf891bf82011-07-31 06:30:59 +00002361 // If the stack restore is in a return, resume, or unwind block and if there
2362 // are no allocas or calls between the restore and the return, nuke the
2363 // restore.
Bill Wendlingd5d95b02012-02-06 21:16:41 +00002364 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<ResumeInst>(TI)))
Sanjay Patel4b198802016-02-01 22:23:39 +00002365 return eraseInstFromFunction(CI);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002366 break;
2367 }
Vitaly Bukaf0500b62016-07-28 22:50:48 +00002368 case Intrinsic::lifetime_start:
Vitaly Buka0ab23cf2016-07-28 22:59:03 +00002369 // Asan needs to poison memory to detect invalid access which is possible
2370 // even for empty lifetime range.
2371 if (II->getFunction()->hasFnAttribute(Attribute::SanitizeAddress))
2372 break;
2373
Arnaud A. de Grandmaison333ef382016-05-10 09:24:49 +00002374 if (removeTriviallyEmptyRange(*II, Intrinsic::lifetime_start,
2375 Intrinsic::lifetime_end, *this))
2376 return nullptr;
Arnaud A. de Grandmaison849f3bf2015-10-01 14:54:31 +00002377 break;
Hal Finkelf5867a72014-07-25 21:45:17 +00002378 case Intrinsic::assume: {
David Majnemerfcc58112016-04-08 16:37:12 +00002379 Value *IIOperand = II->getArgOperand(0);
2380 // Remove an assume if it is immediately followed by an identical assume.
2381 if (match(II->getNextNode(),
2382 m_Intrinsic<Intrinsic::assume>(m_Specific(IIOperand))))
2383 return eraseInstFromFunction(CI);
2384
Hal Finkelf5867a72014-07-25 21:45:17 +00002385 // Canonicalize assume(a && b) -> assume(a); assume(b);
Hal Finkel74c2f352014-09-07 12:44:26 +00002386 // Note: New assumption intrinsics created here are registered by
2387 // the InstCombineIRInserter object.
David Majnemerfcc58112016-04-08 16:37:12 +00002388 Value *AssumeIntrinsic = II->getCalledValue(), *A, *B;
Hal Finkelf5867a72014-07-25 21:45:17 +00002389 if (match(IIOperand, m_And(m_Value(A), m_Value(B)))) {
2390 Builder->CreateCall(AssumeIntrinsic, A, II->getName());
2391 Builder->CreateCall(AssumeIntrinsic, B, II->getName());
Sanjay Patel4b198802016-02-01 22:23:39 +00002392 return eraseInstFromFunction(*II);
Hal Finkelf5867a72014-07-25 21:45:17 +00002393 }
2394 // assume(!(a || b)) -> assume(!a); assume(!b);
2395 if (match(IIOperand, m_Not(m_Or(m_Value(A), m_Value(B))))) {
Hal Finkel74c2f352014-09-07 12:44:26 +00002396 Builder->CreateCall(AssumeIntrinsic, Builder->CreateNot(A),
2397 II->getName());
2398 Builder->CreateCall(AssumeIntrinsic, Builder->CreateNot(B),
2399 II->getName());
Sanjay Patel4b198802016-02-01 22:23:39 +00002400 return eraseInstFromFunction(*II);
Hal Finkelf5867a72014-07-25 21:45:17 +00002401 }
Hal Finkel04a15612014-10-04 21:27:06 +00002402
Philip Reames66c6de62014-11-11 23:33:19 +00002403 // assume( (load addr) != null ) -> add 'nonnull' metadata to load
2404 // (if assume is valid at the load)
2405 if (ICmpInst* ICmp = dyn_cast<ICmpInst>(IIOperand)) {
2406 Value *LHS = ICmp->getOperand(0);
2407 Value *RHS = ICmp->getOperand(1);
2408 if (ICmpInst::ICMP_NE == ICmp->getPredicate() &&
2409 isa<LoadInst>(LHS) &&
2410 isa<Constant>(RHS) &&
2411 RHS->getType()->isPointerTy() &&
2412 cast<Constant>(RHS)->isNullValue()) {
2413 LoadInst* LI = cast<LoadInst>(LHS);
Justin Bogner99798402016-08-05 01:06:44 +00002414 if (isValidAssumeForContext(II, LI, &DT)) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002415 MDNode *MD = MDNode::get(II->getContext(), None);
Philip Reames66c6de62014-11-11 23:33:19 +00002416 LI->setMetadata(LLVMContext::MD_nonnull, MD);
Sanjay Patel4b198802016-02-01 22:23:39 +00002417 return eraseInstFromFunction(*II);
Philip Reames66c6de62014-11-11 23:33:19 +00002418 }
2419 }
Chandler Carruth24969102015-02-10 08:07:32 +00002420 // TODO: apply nonnull return attributes to calls and invokes
Philip Reames66c6de62014-11-11 23:33:19 +00002421 // TODO: apply range metadata for range check patterns?
2422 }
Hal Finkel04a15612014-10-04 21:27:06 +00002423 // If there is a dominating assume with the same condition as this one,
2424 // then this one is redundant, and should be removed.
Hal Finkel45646882014-10-05 00:53:02 +00002425 APInt KnownZero(1, 0), KnownOne(1, 0);
2426 computeKnownBits(IIOperand, KnownZero, KnownOne, 0, II);
2427 if (KnownOne.isAllOnesValue())
Sanjay Patel4b198802016-02-01 22:23:39 +00002428 return eraseInstFromFunction(*II);
Hal Finkel04a15612014-10-04 21:27:06 +00002429
Hal Finkelf5867a72014-07-25 21:45:17 +00002430 break;
2431 }
Philip Reames9db26ff2014-12-29 23:27:30 +00002432 case Intrinsic::experimental_gc_relocate: {
2433 // Translate facts known about a pointer before relocating into
2434 // facts about the relocate value, while being careful to
2435 // preserve relocation semantics.
Manuel Jacob83eefa62016-01-05 04:03:00 +00002436 Value *DerivedPtr = cast<GCRelocateInst>(II)->getDerivedPtr();
Philip Reames9db26ff2014-12-29 23:27:30 +00002437
2438 // Remove the relocation if unused, note that this check is required
2439 // to prevent the cases below from looping forever.
2440 if (II->use_empty())
Sanjay Patel4b198802016-02-01 22:23:39 +00002441 return eraseInstFromFunction(*II);
Philip Reames9db26ff2014-12-29 23:27:30 +00002442
2443 // Undef is undef, even after relocation.
2444 // TODO: provide a hook for this in GCStrategy. This is clearly legal for
2445 // most practical collectors, but there was discussion in the review thread
2446 // about whether it was legal for all possible collectors.
Philip Reamesea4d8e82016-02-09 21:09:22 +00002447 if (isa<UndefValue>(DerivedPtr))
2448 // Use undef of gc_relocate's type to replace it.
2449 return replaceInstUsesWith(*II, UndefValue::get(II->getType()));
Philip Reames9db26ff2014-12-29 23:27:30 +00002450
Philip Reamesea4d8e82016-02-09 21:09:22 +00002451 if (auto *PT = dyn_cast<PointerType>(II->getType())) {
2452 // The relocation of null will be null for most any collector.
2453 // TODO: provide a hook for this in GCStrategy. There might be some
2454 // weird collector this property does not hold for.
2455 if (isa<ConstantPointerNull>(DerivedPtr))
2456 // Use null-pointer of gc_relocate's type to replace it.
2457 return replaceInstUsesWith(*II, ConstantPointerNull::get(PT));
Simon Pilgrimc0c56e72016-04-24 17:00:34 +00002458
Philip Reamesea4d8e82016-02-09 21:09:22 +00002459 // isKnownNonNull -> nonnull attribute
Justin Bogner99798402016-08-05 01:06:44 +00002460 if (isKnownNonNullAt(DerivedPtr, II, &DT))
Philip Reamesea4d8e82016-02-09 21:09:22 +00002461 II->addAttribute(AttributeSet::ReturnIndex, Attribute::NonNull);
Ramkumar Ramachandra8fcb4982015-02-14 19:37:54 +00002462 }
Philip Reames9db26ff2014-12-29 23:27:30 +00002463
2464 // TODO: bitcast(relocate(p)) -> relocate(bitcast(p))
2465 // Canonicalize on the type from the uses to the defs
Ramkumar Ramachandra8fcb4982015-02-14 19:37:54 +00002466
Philip Reames9db26ff2014-12-29 23:27:30 +00002467 // TODO: relocate((gep p, C, C2, ...)) -> gep(relocate(p), C, C2, ...)
Philip Reamesea4d8e82016-02-09 21:09:22 +00002468 break;
Philip Reames9db26ff2014-12-29 23:27:30 +00002469 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002470 }
2471
2472 return visitCallSite(II);
2473}
2474
2475// InvokeInst simplification
2476//
2477Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
2478 return visitCallSite(&II);
2479}
2480
Sanjay Patelcd4377c2016-01-20 22:24:38 +00002481/// If this cast does not affect the value passed through the varargs area, we
2482/// can eliminate the use of the cast.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002483static bool isSafeToEliminateVarargsCast(const CallSite CS,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002484 const DataLayout &DL,
2485 const CastInst *const CI,
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002486 const int ix) {
2487 if (!CI->isLosslessCast())
2488 return false;
2489
Philip Reames1a1bdb22014-12-02 18:50:36 +00002490 // If this is a GC intrinsic, avoid munging types. We need types for
2491 // statepoint reconstruction in SelectionDAG.
2492 // TODO: This is probably something which should be expanded to all
2493 // intrinsics since the entire point of intrinsics is that
2494 // they are understandable by the optimizer.
2495 if (isStatepoint(CS) || isGCRelocate(CS) || isGCResult(CS))
2496 return false;
2497
Reid Kleckner26af2ca2014-01-28 02:38:36 +00002498 // The size of ByVal or InAlloca arguments is derived from the type, so we
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002499 // can't change to a type with a different size. If the size were
2500 // passed explicitly we could avoid this check.
Reid Kleckner26af2ca2014-01-28 02:38:36 +00002501 if (!CS.isByValOrInAllocaArgument(ix))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002502 return true;
2503
Jim Grosbach7815f562012-02-03 00:07:04 +00002504 Type* SrcTy =
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002505 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
Chris Lattner229907c2011-07-18 04:54:35 +00002506 Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002507 if (!SrcTy->isSized() || !DstTy->isSized())
2508 return false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002509 if (DL.getTypeAllocSize(SrcTy) != DL.getTypeAllocSize(DstTy))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002510 return false;
2511 return true;
2512}
2513
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002514Instruction *InstCombiner::tryOptimizeCall(CallInst *CI) {
Craig Topperf40110f2014-04-25 05:29:35 +00002515 if (!CI->getCalledFunction()) return nullptr;
Eric Christophera7fb58f2010-03-06 10:50:38 +00002516
Chandler Carruthba4c5172015-01-21 11:23:40 +00002517 auto InstCombineRAUW = [this](Instruction *From, Value *With) {
Sanjay Patel4b198802016-02-01 22:23:39 +00002518 replaceInstUsesWith(*From, With);
Chandler Carruthba4c5172015-01-21 11:23:40 +00002519 };
Justin Bogner99798402016-08-05 01:06:44 +00002520 LibCallSimplifier Simplifier(DL, &TLI, InstCombineRAUW);
Chandler Carruthba4c5172015-01-21 11:23:40 +00002521 if (Value *With = Simplifier.optimizeCall(CI)) {
Meador Ingee3f2b262012-11-30 04:05:06 +00002522 ++NumSimplified;
Sanjay Patel4b198802016-02-01 22:23:39 +00002523 return CI->use_empty() ? CI : replaceInstUsesWith(*CI, With);
Meador Ingee3f2b262012-11-30 04:05:06 +00002524 }
Meador Ingedf796f82012-10-13 16:45:24 +00002525
Craig Topperf40110f2014-04-25 05:29:35 +00002526 return nullptr;
Eric Christophera7fb58f2010-03-06 10:50:38 +00002527}
2528
Sanjay Patel6038d3e2016-01-29 23:27:03 +00002529static IntrinsicInst *findInitTrampolineFromAlloca(Value *TrampMem) {
Duncan Sandsa0984362011-09-06 13:37:06 +00002530 // Strip off at most one level of pointer casts, looking for an alloca. This
2531 // is good enough in practice and simpler than handling any number of casts.
2532 Value *Underlying = TrampMem->stripPointerCasts();
2533 if (Underlying != TrampMem &&
Chandler Carruthcdf47882014-03-09 03:16:01 +00002534 (!Underlying->hasOneUse() || Underlying->user_back() != TrampMem))
Craig Topperf40110f2014-04-25 05:29:35 +00002535 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00002536 if (!isa<AllocaInst>(Underlying))
Craig Topperf40110f2014-04-25 05:29:35 +00002537 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00002538
Craig Topperf40110f2014-04-25 05:29:35 +00002539 IntrinsicInst *InitTrampoline = nullptr;
Chandler Carruthcdf47882014-03-09 03:16:01 +00002540 for (User *U : TrampMem->users()) {
2541 IntrinsicInst *II = dyn_cast<IntrinsicInst>(U);
Duncan Sandsa0984362011-09-06 13:37:06 +00002542 if (!II)
Craig Topperf40110f2014-04-25 05:29:35 +00002543 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00002544 if (II->getIntrinsicID() == Intrinsic::init_trampoline) {
2545 if (InitTrampoline)
2546 // More than one init_trampoline writes to this value. Give up.
Craig Topperf40110f2014-04-25 05:29:35 +00002547 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00002548 InitTrampoline = II;
2549 continue;
2550 }
2551 if (II->getIntrinsicID() == Intrinsic::adjust_trampoline)
2552 // Allow any number of calls to adjust.trampoline.
2553 continue;
Craig Topperf40110f2014-04-25 05:29:35 +00002554 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00002555 }
2556
2557 // No call to init.trampoline found.
2558 if (!InitTrampoline)
Craig Topperf40110f2014-04-25 05:29:35 +00002559 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00002560
2561 // Check that the alloca is being used in the expected way.
2562 if (InitTrampoline->getOperand(0) != TrampMem)
Craig Topperf40110f2014-04-25 05:29:35 +00002563 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00002564
2565 return InitTrampoline;
2566}
2567
Sanjay Patel6038d3e2016-01-29 23:27:03 +00002568static IntrinsicInst *findInitTrampolineFromBB(IntrinsicInst *AdjustTramp,
Duncan Sandsa0984362011-09-06 13:37:06 +00002569 Value *TrampMem) {
2570 // Visit all the previous instructions in the basic block, and try to find a
2571 // init.trampoline which has a direct path to the adjust.trampoline.
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00002572 for (BasicBlock::iterator I = AdjustTramp->getIterator(),
2573 E = AdjustTramp->getParent()->begin();
2574 I != E;) {
2575 Instruction *Inst = &*--I;
Duncan Sandsa0984362011-09-06 13:37:06 +00002576 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
2577 if (II->getIntrinsicID() == Intrinsic::init_trampoline &&
2578 II->getOperand(0) == TrampMem)
2579 return II;
2580 if (Inst->mayWriteToMemory())
Craig Topperf40110f2014-04-25 05:29:35 +00002581 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00002582 }
Craig Topperf40110f2014-04-25 05:29:35 +00002583 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00002584}
2585
2586// Given a call to llvm.adjust.trampoline, find and return the corresponding
2587// call to llvm.init.trampoline if the call to the trampoline can be optimized
2588// to a direct call to a function. Otherwise return NULL.
2589//
Sanjay Patel6038d3e2016-01-29 23:27:03 +00002590static IntrinsicInst *findInitTrampoline(Value *Callee) {
Duncan Sandsa0984362011-09-06 13:37:06 +00002591 Callee = Callee->stripPointerCasts();
2592 IntrinsicInst *AdjustTramp = dyn_cast<IntrinsicInst>(Callee);
2593 if (!AdjustTramp ||
2594 AdjustTramp->getIntrinsicID() != Intrinsic::adjust_trampoline)
Craig Topperf40110f2014-04-25 05:29:35 +00002595 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00002596
2597 Value *TrampMem = AdjustTramp->getOperand(0);
2598
Sanjay Patel6038d3e2016-01-29 23:27:03 +00002599 if (IntrinsicInst *IT = findInitTrampolineFromAlloca(TrampMem))
Duncan Sandsa0984362011-09-06 13:37:06 +00002600 return IT;
Sanjay Patel6038d3e2016-01-29 23:27:03 +00002601 if (IntrinsicInst *IT = findInitTrampolineFromBB(AdjustTramp, TrampMem))
Duncan Sandsa0984362011-09-06 13:37:06 +00002602 return IT;
Craig Topperf40110f2014-04-25 05:29:35 +00002603 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00002604}
2605
Sanjay Patelcd4377c2016-01-20 22:24:38 +00002606/// Improvements for call and invoke instructions.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002607Instruction *InstCombiner::visitCallSite(CallSite CS) {
Justin Bogner99798402016-08-05 01:06:44 +00002608 if (isAllocLikeFn(CS.getInstruction(), &TLI))
Nuno Lopes95cc4f32012-07-09 18:38:20 +00002609 return visitAllocSite(*CS.getInstruction());
Nuno Lopesdc6085e2012-06-21 21:25:05 +00002610
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002611 bool Changed = false;
2612
Philip Reamesc25df112015-06-16 20:24:25 +00002613 // Mark any parameters that are known to be non-null with the nonnull
2614 // attribute. This is helpful for inlining calls to functions with null
2615 // checks on their arguments.
Akira Hatanaka237916b2015-12-02 06:58:49 +00002616 SmallVector<unsigned, 4> Indices;
Philip Reamesc25df112015-06-16 20:24:25 +00002617 unsigned ArgNo = 0;
Akira Hatanaka237916b2015-12-02 06:58:49 +00002618
Philip Reamesc25df112015-06-16 20:24:25 +00002619 for (Value *V : CS.args()) {
Sanjay Patelf9f5d3c2016-01-29 23:14:58 +00002620 if (V->getType()->isPointerTy() &&
2621 !CS.paramHasAttr(ArgNo + 1, Attribute::NonNull) &&
Justin Bogner99798402016-08-05 01:06:44 +00002622 isKnownNonNullAt(V, CS.getInstruction(), &DT))
Akira Hatanaka237916b2015-12-02 06:58:49 +00002623 Indices.push_back(ArgNo + 1);
Philip Reamesc25df112015-06-16 20:24:25 +00002624 ArgNo++;
2625 }
Akira Hatanaka237916b2015-12-02 06:58:49 +00002626
Philip Reamesc25df112015-06-16 20:24:25 +00002627 assert(ArgNo == CS.arg_size() && "sanity check");
2628
Akira Hatanaka237916b2015-12-02 06:58:49 +00002629 if (!Indices.empty()) {
2630 AttributeSet AS = CS.getAttributes();
2631 LLVMContext &Ctx = CS.getInstruction()->getContext();
2632 AS = AS.addAttribute(Ctx, Indices,
2633 Attribute::get(Ctx, Attribute::NonNull));
2634 CS.setAttributes(AS);
2635 Changed = true;
2636 }
2637
Chris Lattner73989652010-12-20 08:25:06 +00002638 // If the callee is a pointer to a function, attempt to move any casts to the
2639 // arguments of the call/invoke.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002640 Value *Callee = CS.getCalledValue();
Chris Lattner73989652010-12-20 08:25:06 +00002641 if (!isa<Function>(Callee) && transformConstExprCastCall(CS))
Craig Topperf40110f2014-04-25 05:29:35 +00002642 return nullptr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002643
Justin Lebar9d943972016-03-14 20:18:54 +00002644 if (Function *CalleeF = dyn_cast<Function>(Callee)) {
2645 // Remove the convergent attr on calls when the callee is not convergent.
Matt Arsenault802ebcb2016-06-20 19:04:44 +00002646 if (CS.isConvergent() && !CalleeF->isConvergent() &&
2647 !CalleeF->isIntrinsic()) {
Justin Lebar9d943972016-03-14 20:18:54 +00002648 DEBUG(dbgs() << "Removing convergent attr from instr "
2649 << CS.getInstruction() << "\n");
2650 CS.setNotConvergent();
2651 return CS.getInstruction();
2652 }
2653
Chris Lattner846a52e2010-02-01 18:11:34 +00002654 // If the call and callee calling conventions don't match, this call must
2655 // be unreachable, as the call is undefined.
2656 if (CalleeF->getCallingConv() != CS.getCallingConv() &&
2657 // Only do this for calls to a function with a body. A prototype may
2658 // not actually end up matching the implementation's calling conv for a
2659 // variety of reasons (e.g. it may be written in assembly).
2660 !CalleeF->isDeclaration()) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002661 Instruction *OldCall = CS.getInstruction();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002662 new StoreInst(ConstantInt::getTrue(Callee->getContext()),
Jim Grosbach7815f562012-02-03 00:07:04 +00002663 UndefValue::get(Type::getInt1PtrTy(Callee->getContext())),
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002664 OldCall);
Chad Rosiere28ae302012-12-13 00:18:46 +00002665 // If OldCall does not return void then replaceAllUsesWith undef.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002666 // This allows ValueHandlers and custom metadata to adjust itself.
2667 if (!OldCall->getType()->isVoidTy())
Sanjay Patel4b198802016-02-01 22:23:39 +00002668 replaceInstUsesWith(*OldCall, UndefValue::get(OldCall->getType()));
Chris Lattner2cecedf2010-02-01 18:04:58 +00002669 if (isa<CallInst>(OldCall))
Sanjay Patel4b198802016-02-01 22:23:39 +00002670 return eraseInstFromFunction(*OldCall);
Jim Grosbach7815f562012-02-03 00:07:04 +00002671
Chris Lattner2cecedf2010-02-01 18:04:58 +00002672 // We cannot remove an invoke, because it would change the CFG, just
2673 // change the callee to a null pointer.
Gabor Greiffebf6ab2010-03-20 21:00:25 +00002674 cast<InvokeInst>(OldCall)->setCalledFunction(
Chris Lattner2cecedf2010-02-01 18:04:58 +00002675 Constant::getNullValue(CalleeF->getType()));
Craig Topperf40110f2014-04-25 05:29:35 +00002676 return nullptr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002677 }
Justin Lebar9d943972016-03-14 20:18:54 +00002678 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002679
2680 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
Gabor Greif589a0b92010-06-24 12:58:35 +00002681 // If CS does not return void then replaceAllUsesWith undef.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002682 // This allows ValueHandlers and custom metadata to adjust itself.
2683 if (!CS.getInstruction()->getType()->isVoidTy())
Sanjay Patel4b198802016-02-01 22:23:39 +00002684 replaceInstUsesWith(*CS.getInstruction(),
Eli Friedmanb9ed18f2011-05-18 00:32:01 +00002685 UndefValue::get(CS.getInstruction()->getType()));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002686
Nuno Lopes771e7bd2012-06-21 23:52:14 +00002687 if (isa<InvokeInst>(CS.getInstruction())) {
2688 // Can't remove an invoke because we cannot change the CFG.
Craig Topperf40110f2014-04-25 05:29:35 +00002689 return nullptr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002690 }
Nuno Lopes771e7bd2012-06-21 23:52:14 +00002691
2692 // This instruction is not reachable, just remove it. We insert a store to
2693 // undef so that we know that this code is not reachable, despite the fact
2694 // that we can't modify the CFG here.
2695 new StoreInst(ConstantInt::getTrue(Callee->getContext()),
2696 UndefValue::get(Type::getInt1PtrTy(Callee->getContext())),
2697 CS.getInstruction());
2698
Sanjay Patel4b198802016-02-01 22:23:39 +00002699 return eraseInstFromFunction(*CS.getInstruction());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002700 }
2701
Sanjay Patel6038d3e2016-01-29 23:27:03 +00002702 if (IntrinsicInst *II = findInitTrampoline(Callee))
Duncan Sandsa0984362011-09-06 13:37:06 +00002703 return transformCallThroughTrampoline(CS, II);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002704
Chris Lattner229907c2011-07-18 04:54:35 +00002705 PointerType *PTy = cast<PointerType>(Callee->getType());
2706 FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002707 if (FTy->isVarArg()) {
Eli Friedman7534b4682011-11-29 01:18:23 +00002708 int ix = FTy->getNumParams();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002709 // See if we can optimize any arguments passed through the varargs area of
2710 // the call.
Matt Arsenault5d2e85f2013-06-28 00:25:40 +00002711 for (CallSite::arg_iterator I = CS.arg_begin() + FTy->getNumParams(),
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002712 E = CS.arg_end(); I != E; ++I, ++ix) {
2713 CastInst *CI = dyn_cast<CastInst>(*I);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002714 if (CI && isSafeToEliminateVarargsCast(CS, DL, CI, ix)) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002715 *I = CI->getOperand(0);
2716 Changed = true;
2717 }
2718 }
2719 }
2720
2721 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
2722 // Inline asm calls cannot throw - mark them 'nounwind'.
2723 CS.setDoesNotThrow();
2724 Changed = true;
2725 }
2726
Micah Villmowcdfe20b2012-10-08 16:38:25 +00002727 // Try to optimize the call if possible, we require DataLayout for most of
Eric Christophera7fb58f2010-03-06 10:50:38 +00002728 // this. None of these calls are seen as possibly dead so go ahead and
2729 // delete the instruction now.
2730 if (CallInst *CI = dyn_cast<CallInst>(CS.getInstruction())) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002731 Instruction *I = tryOptimizeCall(CI);
Eric Christopher1810d772010-03-06 10:59:25 +00002732 // If we changed something return the result, etc. Otherwise let
2733 // the fallthrough check.
Sanjay Patel4b198802016-02-01 22:23:39 +00002734 if (I) return eraseInstFromFunction(*I);
Eric Christophera7fb58f2010-03-06 10:50:38 +00002735 }
2736
Craig Topperf40110f2014-04-25 05:29:35 +00002737 return Changed ? CS.getInstruction() : nullptr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002738}
2739
Sanjay Patelcd4377c2016-01-20 22:24:38 +00002740/// If the callee is a constexpr cast of a function, attempt to move the cast to
2741/// the arguments of the call/invoke.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002742bool InstCombiner::transformConstExprCastCall(CallSite CS) {
Sanjay Patele3c335c2016-08-11 15:21:21 +00002743 auto *Callee = dyn_cast<Function>(CS.getCalledValue()->stripPointerCasts());
Craig Topperf40110f2014-04-25 05:29:35 +00002744 if (!Callee)
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002745 return false;
Sanjay Patel38ae83d2016-08-11 15:23:56 +00002746
2747 // The prototype of a thunk is a lie. Don't directly call such a function.
David Majnemer4c0a6e92015-01-21 22:32:04 +00002748 if (Callee->hasFnAttribute("thunk"))
2749 return false;
Sanjay Patel38ae83d2016-08-11 15:23:56 +00002750
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002751 Instruction *Caller = CS.getInstruction();
Bill Wendlinge94d8432012-12-07 23:16:57 +00002752 const AttributeSet &CallerPAL = CS.getAttributes();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002753
2754 // Okay, this is a cast from a function to a different type. Unless doing so
2755 // would cause a type conversion of one of our arguments, change this call to
2756 // be a direct call with arguments casted to the appropriate types.
2757 //
Chris Lattner229907c2011-07-18 04:54:35 +00002758 FunctionType *FT = Callee->getFunctionType();
2759 Type *OldRetTy = Caller->getType();
2760 Type *NewRetTy = FT->getReturnType();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002761
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002762 // Check to see if we are changing the return type...
2763 if (OldRetTy != NewRetTy) {
Nick Lewyckya6a17d72014-01-18 22:47:12 +00002764
2765 if (NewRetTy->isStructTy())
2766 return false; // TODO: Handle multiple return values.
2767
David Majnemer9b6b8222015-01-06 08:41:31 +00002768 if (!CastInst::isBitOrNoopPointerCastable(NewRetTy, OldRetTy, DL)) {
Matt Arsenaulte6952f22013-09-17 21:10:14 +00002769 if (Callee->isDeclaration())
2770 return false; // Cannot transform this return value.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002771
Matt Arsenaulte6952f22013-09-17 21:10:14 +00002772 if (!Caller->use_empty() &&
2773 // void -> non-void is handled specially
2774 !NewRetTy->isVoidTy())
Frederic Rissc1892e22014-10-23 04:08:42 +00002775 return false; // Cannot transform this return value.
Matt Arsenaulte6952f22013-09-17 21:10:14 +00002776 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002777
2778 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Bill Wendling658d24d2013-01-18 21:53:16 +00002779 AttrBuilder RAttrs(CallerPAL, AttributeSet::ReturnIndex);
Pete Cooper2777d8872015-05-06 23:19:56 +00002780 if (RAttrs.overlaps(AttributeFuncs::typeIncompatible(NewRetTy)))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002781 return false; // Attribute not compatible with transformed value.
2782 }
2783
2784 // If the callsite is an invoke instruction, and the return value is used by
2785 // a PHI node in a successor, we cannot change the return type of the call
2786 // because there is no place to put the cast instruction (without breaking
2787 // the critical edge). Bail out in this case.
2788 if (!Caller->use_empty())
2789 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
Chandler Carruthcdf47882014-03-09 03:16:01 +00002790 for (User *U : II->users())
2791 if (PHINode *PN = dyn_cast<PHINode>(U))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002792 if (PN->getParent() == II->getNormalDest() ||
2793 PN->getParent() == II->getUnwindDest())
2794 return false;
2795 }
2796
Matt Arsenault5d2e85f2013-06-28 00:25:40 +00002797 unsigned NumActualArgs = CS.arg_size();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002798 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
2799
David Majnemer9b6b8222015-01-06 08:41:31 +00002800 // Prevent us turning:
2801 // declare void @takes_i32_inalloca(i32* inalloca)
2802 // call void bitcast (void (i32*)* @takes_i32_inalloca to void (i32)*)(i32 0)
2803 //
2804 // into:
2805 // call void @takes_i32_inalloca(i32* null)
David Majnemerd61a6fd2015-03-11 18:03:05 +00002806 //
2807 // Similarly, avoid folding away bitcasts of byval calls.
2808 if (Callee->getAttributes().hasAttrSomewhere(Attribute::InAlloca) ||
2809 Callee->getAttributes().hasAttrSomewhere(Attribute::ByVal))
David Majnemer9b6b8222015-01-06 08:41:31 +00002810 return false;
2811
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002812 CallSite::arg_iterator AI = CS.arg_begin();
2813 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
Chris Lattner229907c2011-07-18 04:54:35 +00002814 Type *ParamTy = FT->getParamType(i);
2815 Type *ActTy = (*AI)->getType();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002816
David Majnemer9b6b8222015-01-06 08:41:31 +00002817 if (!CastInst::isBitOrNoopPointerCastable(ActTy, ParamTy, DL))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002818 return false; // Cannot transform this parameter value.
2819
Bill Wendling49bc76c2013-01-23 06:14:59 +00002820 if (AttrBuilder(CallerPAL.getParamAttributes(i + 1), i + 1).
Pete Cooper2777d8872015-05-06 23:19:56 +00002821 overlaps(AttributeFuncs::typeIncompatible(ParamTy)))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002822 return false; // Attribute not compatible with transformed value.
Jim Grosbach7815f562012-02-03 00:07:04 +00002823
Reid Kleckner26af2ca2014-01-28 02:38:36 +00002824 if (CS.isInAllocaArgument(i))
2825 return false; // Cannot transform to and from inalloca.
2826
Chris Lattner27ca8eb2010-12-20 08:36:38 +00002827 // If the parameter is passed as a byval argument, then we have to have a
2828 // sized type and the sized type has to have the same size as the old type.
Bill Wendling49bc76c2013-01-23 06:14:59 +00002829 if (ParamTy != ActTy &&
2830 CallerPAL.getParamAttributes(i + 1).hasAttribute(i + 1,
2831 Attribute::ByVal)) {
Chris Lattner229907c2011-07-18 04:54:35 +00002832 PointerType *ParamPTy = dyn_cast<PointerType>(ParamTy);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002833 if (!ParamPTy || !ParamPTy->getElementType()->isSized())
Chris Lattner27ca8eb2010-12-20 08:36:38 +00002834 return false;
Jim Grosbach7815f562012-02-03 00:07:04 +00002835
Matt Arsenaultfa252722013-09-27 22:18:51 +00002836 Type *CurElTy = ActTy->getPointerElementType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002837 if (DL.getTypeAllocSize(CurElTy) !=
2838 DL.getTypeAllocSize(ParamPTy->getElementType()))
Chris Lattner27ca8eb2010-12-20 08:36:38 +00002839 return false;
2840 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002841 }
2842
Chris Lattneradf38b32011-02-24 05:10:56 +00002843 if (Callee->isDeclaration()) {
2844 // Do not delete arguments unless we have a function body.
2845 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg())
2846 return false;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002847
Chris Lattneradf38b32011-02-24 05:10:56 +00002848 // If the callee is just a declaration, don't change the varargsness of the
2849 // call. We don't want to introduce a varargs call where one doesn't
2850 // already exist.
Chris Lattner229907c2011-07-18 04:54:35 +00002851 PointerType *APTy = cast<PointerType>(CS.getCalledValue()->getType());
Chris Lattneradf38b32011-02-24 05:10:56 +00002852 if (FT->isVarArg()!=cast<FunctionType>(APTy->getElementType())->isVarArg())
2853 return false;
Jim Grosbache84ae7b2012-02-03 00:00:55 +00002854
2855 // If both the callee and the cast type are varargs, we still have to make
2856 // sure the number of fixed parameters are the same or we have the same
2857 // ABI issues as if we introduce a varargs call.
Jim Grosbach1df8cdc2012-02-03 00:26:07 +00002858 if (FT->isVarArg() &&
2859 cast<FunctionType>(APTy->getElementType())->isVarArg() &&
2860 FT->getNumParams() !=
Jim Grosbache84ae7b2012-02-03 00:00:55 +00002861 cast<FunctionType>(APTy->getElementType())->getNumParams())
2862 return false;
Chris Lattneradf38b32011-02-24 05:10:56 +00002863 }
Jim Grosbach7815f562012-02-03 00:07:04 +00002864
Jim Grosbach0ab54182012-02-03 00:00:50 +00002865 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
2866 !CallerPAL.isEmpty())
2867 // In this case we have more arguments than the new function type, but we
2868 // won't be dropping them. Check that these extra arguments have attributes
2869 // that are compatible with being a vararg call argument.
2870 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
Bill Wendling57625a42013-01-25 23:09:36 +00002871 unsigned Index = CallerPAL.getSlotIndex(i - 1);
2872 if (Index <= FT->getNumParams())
Jim Grosbach0ab54182012-02-03 00:00:50 +00002873 break;
Bill Wendling57625a42013-01-25 23:09:36 +00002874
Bill Wendlingd97b75d2012-12-19 08:57:40 +00002875 // Check if it has an attribute that's incompatible with varargs.
Bill Wendling57625a42013-01-25 23:09:36 +00002876 AttributeSet PAttrs = CallerPAL.getSlotAttributes(i - 1);
2877 if (PAttrs.hasAttribute(Index, Attribute::StructRet))
Jim Grosbach0ab54182012-02-03 00:00:50 +00002878 return false;
2879 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002880
Jim Grosbach7815f562012-02-03 00:07:04 +00002881
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002882 // Okay, we decided that this is a safe thing to do: go ahead and start
Chris Lattneradf38b32011-02-24 05:10:56 +00002883 // inserting cast instructions as necessary.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002884 std::vector<Value*> Args;
2885 Args.reserve(NumActualArgs);
Bill Wendling3575c8c2013-01-27 02:08:22 +00002886 SmallVector<AttributeSet, 8> attrVec;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002887 attrVec.reserve(NumCommonArgs);
2888
2889 // Get any return attributes.
Bill Wendling658d24d2013-01-18 21:53:16 +00002890 AttrBuilder RAttrs(CallerPAL, AttributeSet::ReturnIndex);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002891
2892 // If the return value is not being used, the type may not be compatible
2893 // with the existing attributes. Wipe out any problematic attributes.
Pete Cooper2777d8872015-05-06 23:19:56 +00002894 RAttrs.remove(AttributeFuncs::typeIncompatible(NewRetTy));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002895
2896 // Add the new return attributes.
Bill Wendling70f39172012-10-09 00:01:21 +00002897 if (RAttrs.hasAttributes())
Bill Wendling3575c8c2013-01-27 02:08:22 +00002898 attrVec.push_back(AttributeSet::get(Caller->getContext(),
2899 AttributeSet::ReturnIndex, RAttrs));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002900
2901 AI = CS.arg_begin();
2902 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
Chris Lattner229907c2011-07-18 04:54:35 +00002903 Type *ParamTy = FT->getParamType(i);
Matt Arsenaultcacbb232013-07-30 20:45:05 +00002904
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002905 if ((*AI)->getType() == ParamTy) {
2906 Args.push_back(*AI);
2907 } else {
David Majnemer9b6b8222015-01-06 08:41:31 +00002908 Args.push_back(Builder->CreateBitOrPointerCast(*AI, ParamTy));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002909 }
2910
2911 // Add any parameter attributes.
Bill Wendling49bc76c2013-01-23 06:14:59 +00002912 AttrBuilder PAttrs(CallerPAL.getParamAttributes(i + 1), i + 1);
Bill Wendling76d2cd22012-10-14 08:54:26 +00002913 if (PAttrs.hasAttributes())
Bill Wendling3575c8c2013-01-27 02:08:22 +00002914 attrVec.push_back(AttributeSet::get(Caller->getContext(), i + 1,
2915 PAttrs));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002916 }
2917
2918 // If the function takes more arguments than the call was taking, add them
2919 // now.
2920 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
2921 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
2922
2923 // If we are removing arguments to the function, emit an obnoxious warning.
2924 if (FT->getNumParams() < NumActualArgs) {
Nick Lewycky90053a12012-12-26 22:00:35 +00002925 // TODO: if (!FT->isVarArg()) this call may be unreachable. PR14722
2926 if (FT->isVarArg()) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002927 // Add all of the arguments in their promoted form to the arg list.
2928 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
Chris Lattner229907c2011-07-18 04:54:35 +00002929 Type *PTy = getPromotedType((*AI)->getType());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002930 if (PTy != (*AI)->getType()) {
2931 // Must promote to pass through va_arg area!
2932 Instruction::CastOps opcode =
2933 CastInst::getCastOpcode(*AI, false, PTy, false);
Benjamin Kramer547b6c52011-09-27 20:39:19 +00002934 Args.push_back(Builder->CreateCast(opcode, *AI, PTy));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002935 } else {
2936 Args.push_back(*AI);
2937 }
2938
2939 // Add any parameter attributes.
Bill Wendling49bc76c2013-01-23 06:14:59 +00002940 AttrBuilder PAttrs(CallerPAL.getParamAttributes(i + 1), i + 1);
Bill Wendling76d2cd22012-10-14 08:54:26 +00002941 if (PAttrs.hasAttributes())
Bill Wendling3575c8c2013-01-27 02:08:22 +00002942 attrVec.push_back(AttributeSet::get(FT->getContext(), i + 1,
2943 PAttrs));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002944 }
2945 }
2946 }
2947
Bill Wendlingbd4ea162013-01-21 21:57:28 +00002948 AttributeSet FnAttrs = CallerPAL.getFnAttributes();
Bill Wendling77543892013-01-18 21:11:39 +00002949 if (CallerPAL.hasAttributes(AttributeSet::FunctionIndex))
Bill Wendling3575c8c2013-01-27 02:08:22 +00002950 attrVec.push_back(AttributeSet::get(Callee->getContext(), FnAttrs));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002951
2952 if (NewRetTy->isVoidTy())
2953 Caller->setName(""); // Void type should not have a name.
2954
Bill Wendlinge94d8432012-12-07 23:16:57 +00002955 const AttributeSet &NewCallerPAL = AttributeSet::get(Callee->getContext(),
Bill Wendlingbd4ea162013-01-21 21:57:28 +00002956 attrVec);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002957
Sanjoy Das76293462015-11-25 00:42:19 +00002958 SmallVector<OperandBundleDef, 1> OpBundles;
Sanjoy Dasc521c7b2015-11-25 00:42:24 +00002959 CS.getOperandBundlesAsDefs(OpBundles);
Sanjoy Das76293462015-11-25 00:42:19 +00002960
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002961 Instruction *NC;
2962 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Sanjoy Das76293462015-11-25 00:42:19 +00002963 NC = Builder->CreateInvoke(Callee, II->getNormalDest(), II->getUnwindDest(),
2964 Args, OpBundles);
Eli Friedman96254a02011-05-18 01:28:27 +00002965 NC->takeName(II);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002966 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
2967 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
2968 } else {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002969 CallInst *CI = cast<CallInst>(Caller);
Sanjoy Das76293462015-11-25 00:42:19 +00002970 NC = Builder->CreateCall(Callee, Args, OpBundles);
Eli Friedman96254a02011-05-18 01:28:27 +00002971 NC->takeName(CI);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002972 if (CI->isTailCall())
2973 cast<CallInst>(NC)->setTailCall();
2974 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
2975 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
2976 }
2977
2978 // Insert a cast of the return type as necessary.
2979 Value *NV = NC;
2980 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
2981 if (!NV->getType()->isVoidTy()) {
David Majnemer9b6b8222015-01-06 08:41:31 +00002982 NV = NC = CastInst::CreateBitOrPointerCast(NC, OldRetTy);
Eli Friedman35211c62011-05-27 00:19:40 +00002983 NC->setDebugLoc(Caller->getDebugLoc());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002984
2985 // If this is an invoke instruction, we should insert it after the first
2986 // non-phi, instruction in the normal successor block.
2987 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Bill Wendling07efd6f2011-08-25 01:08:34 +00002988 BasicBlock::iterator I = II->getNormalDest()->getFirstInsertionPt();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002989 InsertNewInstBefore(NC, *I);
2990 } else {
Chris Lattner73989652010-12-20 08:25:06 +00002991 // Otherwise, it's a call, just insert cast right after the call.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002992 InsertNewInstBefore(NC, *Caller);
2993 }
2994 Worklist.AddUsersToWorkList(*Caller);
2995 } else {
2996 NV = UndefValue::get(Caller->getType());
2997 }
2998 }
2999
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003000 if (!Caller->use_empty())
Sanjay Patel4b198802016-02-01 22:23:39 +00003001 replaceInstUsesWith(*Caller, NV);
Frederic Rissc1892e22014-10-23 04:08:42 +00003002 else if (Caller->hasValueHandle()) {
3003 if (OldRetTy == NV->getType())
3004 ValueHandleBase::ValueIsRAUWd(Caller, NV);
3005 else
3006 // We cannot call ValueIsRAUWd with a different type, and the
3007 // actual tracked value will disappear.
3008 ValueHandleBase::ValueIsDeleted(Caller);
3009 }
Eli Friedmanb9ed18f2011-05-18 00:32:01 +00003010
Sanjay Patel4b198802016-02-01 22:23:39 +00003011 eraseInstFromFunction(*Caller);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003012 return true;
3013}
3014
Sanjay Patelcd4377c2016-01-20 22:24:38 +00003015/// Turn a call to a function created by init_trampoline / adjust_trampoline
3016/// intrinsic pair into a direct call to the underlying function.
Duncan Sandsa0984362011-09-06 13:37:06 +00003017Instruction *
3018InstCombiner::transformCallThroughTrampoline(CallSite CS,
3019 IntrinsicInst *Tramp) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003020 Value *Callee = CS.getCalledValue();
Chris Lattner229907c2011-07-18 04:54:35 +00003021 PointerType *PTy = cast<PointerType>(Callee->getType());
3022 FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Bill Wendlinge94d8432012-12-07 23:16:57 +00003023 const AttributeSet &Attrs = CS.getAttributes();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003024
3025 // If the call already has the 'nest' attribute somewhere then give up -
3026 // otherwise 'nest' would occur twice after splicing in the chain.
Bill Wendling6e95ae82012-12-31 00:49:59 +00003027 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Craig Topperf40110f2014-04-25 05:29:35 +00003028 return nullptr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003029
Duncan Sandsa0984362011-09-06 13:37:06 +00003030 assert(Tramp &&
3031 "transformCallThroughTrampoline called with incorrect CallSite.");
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003032
Gabor Greif3e44ea12010-07-22 10:37:47 +00003033 Function *NestF =cast<Function>(Tramp->getArgOperand(1)->stripPointerCasts());
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00003034 FunctionType *NestFTy = cast<FunctionType>(NestF->getValueType());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003035
Bill Wendlinge94d8432012-12-07 23:16:57 +00003036 const AttributeSet &NestAttrs = NestF->getAttributes();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003037 if (!NestAttrs.isEmpty()) {
3038 unsigned NestIdx = 1;
Craig Topperf40110f2014-04-25 05:29:35 +00003039 Type *NestTy = nullptr;
Bill Wendling49bc76c2013-01-23 06:14:59 +00003040 AttributeSet NestAttr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003041
3042 // Look for a parameter marked with the 'nest' attribute.
3043 for (FunctionType::param_iterator I = NestFTy->param_begin(),
3044 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Bill Wendling49bc76c2013-01-23 06:14:59 +00003045 if (NestAttrs.hasAttribute(NestIdx, Attribute::Nest)) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003046 // Record the parameter type and any other attributes.
3047 NestTy = *I;
3048 NestAttr = NestAttrs.getParamAttributes(NestIdx);
3049 break;
3050 }
3051
3052 if (NestTy) {
3053 Instruction *Caller = CS.getInstruction();
3054 std::vector<Value*> NewArgs;
Matt Arsenault5d2e85f2013-06-28 00:25:40 +00003055 NewArgs.reserve(CS.arg_size() + 1);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003056
Bill Wendling3575c8c2013-01-27 02:08:22 +00003057 SmallVector<AttributeSet, 8> NewAttrs;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003058 NewAttrs.reserve(Attrs.getNumSlots() + 1);
3059
3060 // Insert the nest argument into the call argument list, which may
3061 // mean appending it. Likewise for attributes.
3062
3063 // Add any result attributes.
Bill Wendling658d24d2013-01-18 21:53:16 +00003064 if (Attrs.hasAttributes(AttributeSet::ReturnIndex))
Bill Wendling3575c8c2013-01-27 02:08:22 +00003065 NewAttrs.push_back(AttributeSet::get(Caller->getContext(),
3066 Attrs.getRetAttributes()));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003067
3068 {
3069 unsigned Idx = 1;
3070 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
3071 do {
3072 if (Idx == NestIdx) {
3073 // Add the chain argument and attributes.
Gabor Greif589a0b92010-06-24 12:58:35 +00003074 Value *NestVal = Tramp->getArgOperand(2);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003075 if (NestVal->getType() != NestTy)
Eli Friedman41e509a2011-05-18 23:58:37 +00003076 NestVal = Builder->CreateBitCast(NestVal, NestTy, "nest");
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003077 NewArgs.push_back(NestVal);
Bill Wendling3575c8c2013-01-27 02:08:22 +00003078 NewAttrs.push_back(AttributeSet::get(Caller->getContext(),
3079 NestAttr));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003080 }
3081
3082 if (I == E)
3083 break;
3084
3085 // Add the original argument and attributes.
3086 NewArgs.push_back(*I);
Bill Wendling49bc76c2013-01-23 06:14:59 +00003087 AttributeSet Attr = Attrs.getParamAttributes(Idx);
3088 if (Attr.hasAttributes(Idx)) {
Bill Wendling3575c8c2013-01-27 02:08:22 +00003089 AttrBuilder B(Attr, Idx);
3090 NewAttrs.push_back(AttributeSet::get(Caller->getContext(),
3091 Idx + (Idx >= NestIdx), B));
Bill Wendling49bc76c2013-01-23 06:14:59 +00003092 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003093
Richard Trieu7a083812016-02-18 22:09:30 +00003094 ++Idx;
3095 ++I;
Eugene Zelenkocdc71612016-08-11 17:20:18 +00003096 } while (true);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003097 }
3098
3099 // Add any function attributes.
Bill Wendling77543892013-01-18 21:11:39 +00003100 if (Attrs.hasAttributes(AttributeSet::FunctionIndex))
Bill Wendling3575c8c2013-01-27 02:08:22 +00003101 NewAttrs.push_back(AttributeSet::get(FTy->getContext(),
3102 Attrs.getFnAttributes()));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003103
3104 // The trampoline may have been bitcast to a bogus type (FTy).
3105 // Handle this by synthesizing a new function type, equal to FTy
3106 // with the chain parameter inserted.
3107
Jay Foadb804a2b2011-07-12 14:06:48 +00003108 std::vector<Type*> NewTypes;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003109 NewTypes.reserve(FTy->getNumParams()+1);
3110
3111 // Insert the chain's type into the list of parameter types, which may
3112 // mean appending it.
3113 {
3114 unsigned Idx = 1;
3115 FunctionType::param_iterator I = FTy->param_begin(),
3116 E = FTy->param_end();
3117
3118 do {
3119 if (Idx == NestIdx)
3120 // Add the chain's type.
3121 NewTypes.push_back(NestTy);
3122
3123 if (I == E)
3124 break;
3125
3126 // Add the original type.
3127 NewTypes.push_back(*I);
3128
Richard Trieu7a083812016-02-18 22:09:30 +00003129 ++Idx;
3130 ++I;
Eugene Zelenkocdc71612016-08-11 17:20:18 +00003131 } while (true);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003132 }
3133
3134 // Replace the trampoline call with a direct call. Let the generic
3135 // code sort out any function type mismatches.
Jim Grosbach7815f562012-02-03 00:07:04 +00003136 FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003137 FTy->isVarArg());
3138 Constant *NewCallee =
3139 NestF->getType() == PointerType::getUnqual(NewFTy) ?
Jim Grosbach7815f562012-02-03 00:07:04 +00003140 NestF : ConstantExpr::getBitCast(NestF,
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003141 PointerType::getUnqual(NewFTy));
Jim Grosbachbdbd7342013-04-05 21:20:12 +00003142 const AttributeSet &NewPAL =
3143 AttributeSet::get(FTy->getContext(), NewAttrs);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003144
David Majnemer231a68c2016-04-29 08:07:20 +00003145 SmallVector<OperandBundleDef, 1> OpBundles;
3146 CS.getOperandBundlesAsDefs(OpBundles);
3147
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003148 Instruction *NewCaller;
3149 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
3150 NewCaller = InvokeInst::Create(NewCallee,
3151 II->getNormalDest(), II->getUnwindDest(),
David Majnemer231a68c2016-04-29 08:07:20 +00003152 NewArgs, OpBundles);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003153 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
3154 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
3155 } else {
David Majnemer231a68c2016-04-29 08:07:20 +00003156 NewCaller = CallInst::Create(NewCallee, NewArgs, OpBundles);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003157 if (cast<CallInst>(Caller)->isTailCall())
3158 cast<CallInst>(NewCaller)->setTailCall();
3159 cast<CallInst>(NewCaller)->
3160 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
3161 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
3162 }
Eli Friedman49346012011-05-18 19:57:14 +00003163
3164 return NewCaller;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003165 }
3166 }
3167
3168 // Replace the trampoline call with a direct call. Since there is no 'nest'
3169 // parameter, there is no need to adjust the argument list. Let the generic
3170 // code sort out any function type mismatches.
3171 Constant *NewCallee =
Jim Grosbach7815f562012-02-03 00:07:04 +00003172 NestF->getType() == PTy ? NestF :
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003173 ConstantExpr::getBitCast(NestF, PTy);
3174 CS.setCalledFunction(NewCallee);
3175 return CS.getInstruction();
3176}