blob: ca868f056f0e44e0499dce8d32732e4fa26bba0f [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);
Eli Friedman49346012011-05-18 19:57:14 +0000195 StoreInst *S = Builder->CreateStore(L, Dest, MI->isVolatile());
196 S->setAlignment(DstAlign);
Dan Gohman3f553c22012-09-13 21:51:01 +0000197 if (CopyMD)
198 S->setMetadata(LLVMContext::MD_tbaa, CopyMD);
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000199
200 // Set the size of the copy to 0, it will be deleted on the next iteration.
Gabor Greif5b1370e2010-06-28 16:50:57 +0000201 MI->setArgOperand(2, Constant::getNullValue(MemOpLength->getType()));
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000202 return MI;
203}
204
205Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
Justin Bogner99798402016-08-05 01:06:44 +0000206 unsigned Alignment = getKnownAlignment(MI->getDest(), DL, MI, &AC, &DT);
Pete Cooper67cf9a72015-11-19 05:56:52 +0000207 if (MI->getAlignment() < Alignment) {
208 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
209 Alignment, false));
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000210 return MI;
211 }
Jim Grosbach7815f562012-02-03 00:07:04 +0000212
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000213 // Extract the length and alignment and fill if they are constant.
214 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
215 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
Duncan Sands9dff9be2010-02-15 16:12:20 +0000216 if (!LenC || !FillC || !FillC->getType()->isIntegerTy(8))
Craig Topperf40110f2014-04-25 05:29:35 +0000217 return nullptr;
Michael Liao69e172a2012-08-15 03:49:59 +0000218 uint64_t Len = LenC->getLimitedValue();
Pete Cooper67cf9a72015-11-19 05:56:52 +0000219 Alignment = MI->getAlignment();
Michael Liao69e172a2012-08-15 03:49:59 +0000220 assert(Len && "0-sized memory setting should be removed already.");
Jim Grosbach7815f562012-02-03 00:07:04 +0000221
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000222 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
223 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
Chris Lattner229907c2011-07-18 04:54:35 +0000224 Type *ITy = IntegerType::get(MI->getContext(), Len*8); // n=1 -> i8.
Jim Grosbach7815f562012-02-03 00:07:04 +0000225
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000226 Value *Dest = MI->getDest();
Mon P Wang1991c472010-12-20 01:05:30 +0000227 unsigned DstAddrSp = cast<PointerType>(Dest->getType())->getAddressSpace();
228 Type *NewDstPtrTy = PointerType::get(ITy, DstAddrSp);
229 Dest = Builder->CreateBitCast(Dest, NewDstPtrTy);
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000230
231 // Alignment 0 is identity for alignment 1 for memset, but not store.
232 if (Alignment == 0) Alignment = 1;
Jim Grosbach7815f562012-02-03 00:07:04 +0000233
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000234 // Extract the fill value and store.
235 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
Eli Friedman49346012011-05-18 19:57:14 +0000236 StoreInst *S = Builder->CreateStore(ConstantInt::get(ITy, Fill), Dest,
237 MI->isVolatile());
238 S->setAlignment(Alignment);
Jim Grosbach7815f562012-02-03 00:07:04 +0000239
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000240 // Set the size of the copy to 0, it will be deleted on the next iteration.
241 MI->setLength(Constant::getNullValue(LenC->getType()));
242 return MI;
243 }
244
Simon Pilgrim18617d12015-08-05 08:18:00 +0000245 return nullptr;
246}
247
Sanjay Patel6038d3e2016-01-29 23:27:03 +0000248static Value *simplifyX86immShift(const IntrinsicInst &II,
Simon Pilgrimbecd5e82015-08-13 07:39:03 +0000249 InstCombiner::BuilderTy &Builder) {
250 bool LogicalShift = false;
251 bool ShiftLeft = false;
252
253 switch (II.getIntrinsicID()) {
254 default:
255 return nullptr;
256 case Intrinsic::x86_sse2_psra_d:
257 case Intrinsic::x86_sse2_psra_w:
258 case Intrinsic::x86_sse2_psrai_d:
259 case Intrinsic::x86_sse2_psrai_w:
260 case Intrinsic::x86_avx2_psra_d:
261 case Intrinsic::x86_avx2_psra_w:
262 case Intrinsic::x86_avx2_psrai_d:
263 case Intrinsic::x86_avx2_psrai_w:
264 LogicalShift = false; ShiftLeft = false;
265 break;
266 case Intrinsic::x86_sse2_psrl_d:
267 case Intrinsic::x86_sse2_psrl_q:
268 case Intrinsic::x86_sse2_psrl_w:
269 case Intrinsic::x86_sse2_psrli_d:
270 case Intrinsic::x86_sse2_psrli_q:
271 case Intrinsic::x86_sse2_psrli_w:
272 case Intrinsic::x86_avx2_psrl_d:
273 case Intrinsic::x86_avx2_psrl_q:
274 case Intrinsic::x86_avx2_psrl_w:
275 case Intrinsic::x86_avx2_psrli_d:
276 case Intrinsic::x86_avx2_psrli_q:
277 case Intrinsic::x86_avx2_psrli_w:
278 LogicalShift = true; ShiftLeft = false;
279 break;
280 case Intrinsic::x86_sse2_psll_d:
281 case Intrinsic::x86_sse2_psll_q:
282 case Intrinsic::x86_sse2_psll_w:
283 case Intrinsic::x86_sse2_pslli_d:
284 case Intrinsic::x86_sse2_pslli_q:
285 case Intrinsic::x86_sse2_pslli_w:
286 case Intrinsic::x86_avx2_psll_d:
287 case Intrinsic::x86_avx2_psll_q:
288 case Intrinsic::x86_avx2_psll_w:
289 case Intrinsic::x86_avx2_pslli_d:
290 case Intrinsic::x86_avx2_pslli_q:
291 case Intrinsic::x86_avx2_pslli_w:
292 LogicalShift = true; ShiftLeft = true;
293 break;
294 }
Simon Pilgrima3a72b42015-08-10 20:21:15 +0000295 assert((LogicalShift || !ShiftLeft) && "Only logical shifts can shift left");
296
Simon Pilgrim3815c162015-08-07 18:22:50 +0000297 // Simplify if count is constant.
298 auto Arg1 = II.getArgOperand(1);
299 auto CAZ = dyn_cast<ConstantAggregateZero>(Arg1);
300 auto CDV = dyn_cast<ConstantDataVector>(Arg1);
301 auto CInt = dyn_cast<ConstantInt>(Arg1);
302 if (!CAZ && !CDV && !CInt)
Simon Pilgrim18617d12015-08-05 08:18:00 +0000303 return nullptr;
Simon Pilgrim3815c162015-08-07 18:22:50 +0000304
305 APInt Count(64, 0);
306 if (CDV) {
307 // SSE2/AVX2 uses all the first 64-bits of the 128-bit vector
308 // operand to compute the shift amount.
309 auto VT = cast<VectorType>(CDV->getType());
310 unsigned BitWidth = VT->getElementType()->getPrimitiveSizeInBits();
311 assert((64 % BitWidth) == 0 && "Unexpected packed shift size");
312 unsigned NumSubElts = 64 / BitWidth;
313
314 // Concatenate the sub-elements to create the 64-bit value.
315 for (unsigned i = 0; i != NumSubElts; ++i) {
316 unsigned SubEltIdx = (NumSubElts - 1) - i;
317 auto SubElt = cast<ConstantInt>(CDV->getElementAsConstant(SubEltIdx));
318 Count = Count.shl(BitWidth);
319 Count |= SubElt->getValue().zextOrTrunc(64);
320 }
321 }
322 else if (CInt)
323 Count = CInt->getValue();
Simon Pilgrim18617d12015-08-05 08:18:00 +0000324
325 auto Vec = II.getArgOperand(0);
326 auto VT = cast<VectorType>(Vec->getType());
327 auto SVT = VT->getElementType();
Simon Pilgrim3815c162015-08-07 18:22:50 +0000328 unsigned VWidth = VT->getNumElements();
329 unsigned BitWidth = SVT->getPrimitiveSizeInBits();
330
331 // If shift-by-zero then just return the original value.
332 if (Count == 0)
333 return Vec;
334
Simon Pilgrima3a72b42015-08-10 20:21:15 +0000335 // Handle cases when Shift >= BitWidth.
336 if (Count.uge(BitWidth)) {
337 // If LogicalShift - just return zero.
338 if (LogicalShift)
339 return ConstantAggregateZero::get(VT);
340
341 // If ArithmeticShift - clamp Shift to (BitWidth - 1).
342 Count = APInt(64, BitWidth - 1);
343 }
Simon Pilgrim18617d12015-08-05 08:18:00 +0000344
Simon Pilgrim18617d12015-08-05 08:18:00 +0000345 // Get a constant vector of the same type as the first operand.
Simon Pilgrim3815c162015-08-07 18:22:50 +0000346 auto ShiftAmt = ConstantInt::get(SVT, Count.zextOrTrunc(BitWidth));
347 auto ShiftVec = Builder.CreateVectorSplat(VWidth, ShiftAmt);
Simon Pilgrim18617d12015-08-05 08:18:00 +0000348
349 if (ShiftLeft)
Simon Pilgrim3815c162015-08-07 18:22:50 +0000350 return Builder.CreateShl(Vec, ShiftVec);
Simon Pilgrim18617d12015-08-05 08:18:00 +0000351
Simon Pilgrima3a72b42015-08-10 20:21:15 +0000352 if (LogicalShift)
353 return Builder.CreateLShr(Vec, ShiftVec);
354
355 return Builder.CreateAShr(Vec, ShiftVec);
Simon Pilgrim18617d12015-08-05 08:18:00 +0000356}
357
Simon Pilgrimdb9893f2016-06-07 10:27:15 +0000358// Attempt to simplify AVX2 per-element shift intrinsics to a generic IR shift.
359// Unlike the generic IR shifts, the intrinsics have defined behaviour for out
360// of range shift amounts (logical - set to zero, arithmetic - splat sign bit).
361static Value *simplifyX86varShift(const IntrinsicInst &II,
362 InstCombiner::BuilderTy &Builder) {
363 bool LogicalShift = false;
364 bool ShiftLeft = false;
365
366 switch (II.getIntrinsicID()) {
367 default:
368 return nullptr;
369 case Intrinsic::x86_avx2_psrav_d:
370 case Intrinsic::x86_avx2_psrav_d_256:
371 LogicalShift = false;
372 ShiftLeft = false;
373 break;
374 case Intrinsic::x86_avx2_psrlv_d:
375 case Intrinsic::x86_avx2_psrlv_d_256:
376 case Intrinsic::x86_avx2_psrlv_q:
377 case Intrinsic::x86_avx2_psrlv_q_256:
378 LogicalShift = true;
379 ShiftLeft = false;
380 break;
381 case Intrinsic::x86_avx2_psllv_d:
382 case Intrinsic::x86_avx2_psllv_d_256:
383 case Intrinsic::x86_avx2_psllv_q:
384 case Intrinsic::x86_avx2_psllv_q_256:
385 LogicalShift = true;
386 ShiftLeft = true;
387 break;
388 }
389 assert((LogicalShift || !ShiftLeft) && "Only logical shifts can shift left");
390
391 // Simplify if all shift amounts are constant/undef.
392 auto *CShift = dyn_cast<Constant>(II.getArgOperand(1));
393 if (!CShift)
394 return nullptr;
395
396 auto Vec = II.getArgOperand(0);
397 auto VT = cast<VectorType>(II.getType());
398 auto SVT = VT->getVectorElementType();
399 int NumElts = VT->getNumElements();
400 int BitWidth = SVT->getIntegerBitWidth();
401
402 // Collect each element's shift amount.
403 // We also collect special cases: UNDEF = -1, OUT-OF-RANGE = BitWidth.
404 bool AnyOutOfRange = false;
405 SmallVector<int, 8> ShiftAmts;
406 for (int I = 0; I < NumElts; ++I) {
407 auto *CElt = CShift->getAggregateElement(I);
408 if (CElt && isa<UndefValue>(CElt)) {
409 ShiftAmts.push_back(-1);
410 continue;
411 }
412
413 auto *COp = dyn_cast_or_null<ConstantInt>(CElt);
414 if (!COp)
415 return nullptr;
416
417 // Handle out of range shifts.
418 // If LogicalShift - set to BitWidth (special case).
419 // If ArithmeticShift - set to (BitWidth - 1) (sign splat).
420 APInt ShiftVal = COp->getValue();
421 if (ShiftVal.uge(BitWidth)) {
422 AnyOutOfRange = LogicalShift;
423 ShiftAmts.push_back(LogicalShift ? BitWidth : BitWidth - 1);
424 continue;
425 }
426
427 ShiftAmts.push_back((int)ShiftVal.getZExtValue());
428 }
429
430 // If all elements out of range or UNDEF, return vector of zeros/undefs.
431 // ArithmeticShift should only hit this if they are all UNDEF.
432 auto OutOfRange = [&](int Idx) { return (Idx < 0) || (BitWidth <= Idx); };
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000433 if (all_of(ShiftAmts, OutOfRange)) {
Simon Pilgrimdb9893f2016-06-07 10:27:15 +0000434 SmallVector<Constant *, 8> ConstantVec;
435 for (int Idx : ShiftAmts) {
436 if (Idx < 0) {
437 ConstantVec.push_back(UndefValue::get(SVT));
438 } else {
439 assert(LogicalShift && "Logical shift expected");
440 ConstantVec.push_back(ConstantInt::getNullValue(SVT));
441 }
442 }
443 return ConstantVector::get(ConstantVec);
444 }
445
446 // We can't handle only some out of range values with generic logical shifts.
447 if (AnyOutOfRange)
448 return nullptr;
449
450 // Build the shift amount constant vector.
451 SmallVector<Constant *, 8> ShiftVecAmts;
452 for (int Idx : ShiftAmts) {
453 if (Idx < 0)
454 ShiftVecAmts.push_back(UndefValue::get(SVT));
455 else
456 ShiftVecAmts.push_back(ConstantInt::get(SVT, Idx));
457 }
458 auto ShiftVec = ConstantVector::get(ShiftVecAmts);
459
460 if (ShiftLeft)
461 return Builder.CreateShl(Vec, ShiftVec);
462
463 if (LogicalShift)
464 return Builder.CreateLShr(Vec, ShiftVec);
465
466 return Builder.CreateAShr(Vec, ShiftVec);
467}
468
Simon Pilgrim91e3ac82016-06-07 08:18:35 +0000469static Value *simplifyX86movmsk(const IntrinsicInst &II,
470 InstCombiner::BuilderTy &Builder) {
471 Value *Arg = II.getArgOperand(0);
472 Type *ResTy = II.getType();
473 Type *ArgTy = Arg->getType();
474
475 // movmsk(undef) -> zero as we must ensure the upper bits are zero.
476 if (isa<UndefValue>(Arg))
477 return Constant::getNullValue(ResTy);
478
479 // We can't easily peek through x86_mmx types.
480 if (!ArgTy->isVectorTy())
481 return nullptr;
482
483 auto *C = dyn_cast<Constant>(Arg);
484 if (!C)
485 return nullptr;
486
487 // Extract signbits of the vector input and pack into integer result.
488 APInt Result(ResTy->getPrimitiveSizeInBits(), 0);
489 for (unsigned I = 0, E = ArgTy->getVectorNumElements(); I != E; ++I) {
490 auto *COp = C->getAggregateElement(I);
491 if (!COp)
492 return nullptr;
493 if (isa<UndefValue>(COp))
494 continue;
495
496 auto *CInt = dyn_cast<ConstantInt>(COp);
497 auto *CFp = dyn_cast<ConstantFP>(COp);
498 if (!CInt && !CFp)
499 return nullptr;
500
501 if ((CInt && CInt->isNegative()) || (CFp && CFp->isNegative()))
502 Result.setBit(I);
503 }
504
505 return Constant::getIntegerValue(ResTy, Result);
506}
507
Sanjay Patel6038d3e2016-01-29 23:27:03 +0000508static Value *simplifyX86insertps(const IntrinsicInst &II,
Sanjay Patelc86867c2015-04-16 17:52:13 +0000509 InstCombiner::BuilderTy &Builder) {
Sanjay Patel03c03f52016-01-28 00:03:16 +0000510 auto *CInt = dyn_cast<ConstantInt>(II.getArgOperand(2));
511 if (!CInt)
512 return nullptr;
Simon Pilgrim54fcd622015-07-25 20:41:00 +0000513
Sanjay Patel03c03f52016-01-28 00:03:16 +0000514 VectorType *VecTy = cast<VectorType>(II.getType());
515 assert(VecTy->getNumElements() == 4 && "insertps with wrong vector type");
Sanjay Patelc86867c2015-04-16 17:52:13 +0000516
Sanjay Patel03c03f52016-01-28 00:03:16 +0000517 // The immediate permute control byte looks like this:
518 // [3:0] - zero mask for each 32-bit lane
519 // [5:4] - select one 32-bit destination lane
520 // [7:6] - select one 32-bit source lane
Sanjay Patelc86867c2015-04-16 17:52:13 +0000521
Sanjay Patel03c03f52016-01-28 00:03:16 +0000522 uint8_t Imm = CInt->getZExtValue();
523 uint8_t ZMask = Imm & 0xf;
524 uint8_t DestLane = (Imm >> 4) & 0x3;
525 uint8_t SourceLane = (Imm >> 6) & 0x3;
Sanjay Patelc1d20a32015-04-25 20:55:25 +0000526
Sanjay Patel03c03f52016-01-28 00:03:16 +0000527 ConstantAggregateZero *ZeroVector = ConstantAggregateZero::get(VecTy);
Sanjay Patelc86867c2015-04-16 17:52:13 +0000528
Sanjay Patel03c03f52016-01-28 00:03:16 +0000529 // If all zero mask bits are set, this was just a weird way to
530 // generate a zero vector.
531 if (ZMask == 0xf)
532 return ZeroVector;
Sanjay Patelc1d20a32015-04-25 20:55:25 +0000533
Sanjay Patel03c03f52016-01-28 00:03:16 +0000534 // Initialize by passing all of the first source bits through.
Craig Topper99d1eab2016-06-12 00:41:19 +0000535 uint32_t ShuffleMask[4] = { 0, 1, 2, 3 };
Sanjay Patelc1d20a32015-04-25 20:55:25 +0000536
Sanjay Patel03c03f52016-01-28 00:03:16 +0000537 // We may replace the second operand with the zero vector.
538 Value *V1 = II.getArgOperand(1);
539
540 if (ZMask) {
541 // If the zero mask is being used with a single input or the zero mask
542 // overrides the destination lane, this is a shuffle with the zero vector.
543 if ((II.getArgOperand(0) == II.getArgOperand(1)) ||
544 (ZMask & (1 << DestLane))) {
545 V1 = ZeroVector;
546 // We may still move 32-bits of the first source vector from one lane
547 // to another.
548 ShuffleMask[DestLane] = SourceLane;
549 // The zero mask may override the previous insert operation.
550 for (unsigned i = 0; i < 4; ++i)
551 if ((ZMask >> i) & 0x1)
552 ShuffleMask[i] = i + 4;
Sanjay Patelc1d20a32015-04-25 20:55:25 +0000553 } else {
Sanjay Patel03c03f52016-01-28 00:03:16 +0000554 // TODO: Model this case as 2 shuffles or a 'logical and' plus shuffle?
555 return nullptr;
Sanjay Patelc1d20a32015-04-25 20:55:25 +0000556 }
Sanjay Patel03c03f52016-01-28 00:03:16 +0000557 } else {
558 // Replace the selected destination lane with the selected source lane.
559 ShuffleMask[DestLane] = SourceLane + 4;
Sanjay Patelc86867c2015-04-16 17:52:13 +0000560 }
Sanjay Patel03c03f52016-01-28 00:03:16 +0000561
562 return Builder.CreateShuffleVector(II.getArgOperand(0), V1, ShuffleMask);
Sanjay Patelc86867c2015-04-16 17:52:13 +0000563}
564
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000565/// Attempt to simplify SSE4A EXTRQ/EXTRQI instructions using constant folding
566/// or conversion to a shuffle vector.
Sanjay Patel6038d3e2016-01-29 23:27:03 +0000567static Value *simplifyX86extrq(IntrinsicInst &II, Value *Op0,
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000568 ConstantInt *CILength, ConstantInt *CIIndex,
569 InstCombiner::BuilderTy &Builder) {
570 auto LowConstantHighUndef = [&](uint64_t Val) {
571 Type *IntTy64 = Type::getInt64Ty(II.getContext());
572 Constant *Args[] = {ConstantInt::get(IntTy64, Val),
573 UndefValue::get(IntTy64)};
574 return ConstantVector::get(Args);
575 };
576
577 // See if we're dealing with constant values.
578 Constant *C0 = dyn_cast<Constant>(Op0);
579 ConstantInt *CI0 =
580 C0 ? dyn_cast<ConstantInt>(C0->getAggregateElement((unsigned)0))
581 : nullptr;
582
583 // Attempt to constant fold.
584 if (CILength && CIIndex) {
585 // From AMD documentation: "The bit index and field length are each six
586 // bits in length other bits of the field are ignored."
587 APInt APIndex = CIIndex->getValue().zextOrTrunc(6);
588 APInt APLength = CILength->getValue().zextOrTrunc(6);
589
590 unsigned Index = APIndex.getZExtValue();
591
592 // From AMD documentation: "a value of zero in the field length is
593 // defined as length of 64".
594 unsigned Length = APLength == 0 ? 64 : APLength.getZExtValue();
595
596 // From AMD documentation: "If the sum of the bit index + length field
597 // is greater than 64, the results are undefined".
598 unsigned End = Index + Length;
599
600 // Note that both field index and field length are 8-bit quantities.
601 // Since variables 'Index' and 'Length' are unsigned values
602 // obtained from zero-extending field index and field length
603 // respectively, their sum should never wrap around.
604 if (End > 64)
605 return UndefValue::get(II.getType());
606
607 // If we are inserting whole bytes, we can convert this to a shuffle.
608 // Lowering can recognize EXTRQI shuffle masks.
609 if ((Length % 8) == 0 && (Index % 8) == 0) {
610 // Convert bit indices to byte indices.
611 Length /= 8;
612 Index /= 8;
613
614 Type *IntTy8 = Type::getInt8Ty(II.getContext());
615 Type *IntTy32 = Type::getInt32Ty(II.getContext());
616 VectorType *ShufTy = VectorType::get(IntTy8, 16);
617
618 SmallVector<Constant *, 16> ShuffleMask;
619 for (int i = 0; i != (int)Length; ++i)
620 ShuffleMask.push_back(
621 Constant::getIntegerValue(IntTy32, APInt(32, i + Index)));
622 for (int i = Length; i != 8; ++i)
623 ShuffleMask.push_back(
624 Constant::getIntegerValue(IntTy32, APInt(32, i + 16)));
625 for (int i = 8; i != 16; ++i)
626 ShuffleMask.push_back(UndefValue::get(IntTy32));
627
628 Value *SV = Builder.CreateShuffleVector(
629 Builder.CreateBitCast(Op0, ShufTy),
630 ConstantAggregateZero::get(ShufTy), ConstantVector::get(ShuffleMask));
631 return Builder.CreateBitCast(SV, II.getType());
632 }
633
634 // Constant Fold - shift Index'th bit to lowest position and mask off
635 // Length bits.
636 if (CI0) {
637 APInt Elt = CI0->getValue();
638 Elt = Elt.lshr(Index).zextOrTrunc(Length);
639 return LowConstantHighUndef(Elt.getZExtValue());
640 }
641
642 // If we were an EXTRQ call, we'll save registers if we convert to EXTRQI.
643 if (II.getIntrinsicID() == Intrinsic::x86_sse4a_extrq) {
644 Value *Args[] = {Op0, CILength, CIIndex};
Sanjay Patelaf674fb2015-12-14 17:24:23 +0000645 Module *M = II.getModule();
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000646 Value *F = Intrinsic::getDeclaration(M, Intrinsic::x86_sse4a_extrqi);
647 return Builder.CreateCall(F, Args);
648 }
649 }
650
651 // Constant Fold - extraction from zero is always {zero, undef}.
652 if (CI0 && CI0->equalsInt(0))
653 return LowConstantHighUndef(0);
654
655 return nullptr;
656}
657
658/// Attempt to simplify SSE4A INSERTQ/INSERTQI instructions using constant
659/// folding or conversion to a shuffle vector.
Sanjay Patel6038d3e2016-01-29 23:27:03 +0000660static Value *simplifyX86insertq(IntrinsicInst &II, Value *Op0, Value *Op1,
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000661 APInt APLength, APInt APIndex,
662 InstCombiner::BuilderTy &Builder) {
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000663 // From AMD documentation: "The bit index and field length are each six bits
664 // in length other bits of the field are ignored."
665 APIndex = APIndex.zextOrTrunc(6);
666 APLength = APLength.zextOrTrunc(6);
667
668 // Attempt to constant fold.
669 unsigned Index = APIndex.getZExtValue();
670
671 // From AMD documentation: "a value of zero in the field length is
672 // defined as length of 64".
673 unsigned Length = APLength == 0 ? 64 : APLength.getZExtValue();
674
675 // From AMD documentation: "If the sum of the bit index + length field
676 // is greater than 64, the results are undefined".
677 unsigned End = Index + Length;
678
679 // Note that both field index and field length are 8-bit quantities.
680 // Since variables 'Index' and 'Length' are unsigned values
681 // obtained from zero-extending field index and field length
682 // respectively, their sum should never wrap around.
683 if (End > 64)
684 return UndefValue::get(II.getType());
685
686 // If we are inserting whole bytes, we can convert this to a shuffle.
687 // Lowering can recognize INSERTQI shuffle masks.
688 if ((Length % 8) == 0 && (Index % 8) == 0) {
689 // Convert bit indices to byte indices.
690 Length /= 8;
691 Index /= 8;
692
693 Type *IntTy8 = Type::getInt8Ty(II.getContext());
694 Type *IntTy32 = Type::getInt32Ty(II.getContext());
695 VectorType *ShufTy = VectorType::get(IntTy8, 16);
696
697 SmallVector<Constant *, 16> ShuffleMask;
698 for (int i = 0; i != (int)Index; ++i)
699 ShuffleMask.push_back(Constant::getIntegerValue(IntTy32, APInt(32, i)));
700 for (int i = 0; i != (int)Length; ++i)
701 ShuffleMask.push_back(
702 Constant::getIntegerValue(IntTy32, APInt(32, i + 16)));
703 for (int i = Index + Length; i != 8; ++i)
704 ShuffleMask.push_back(Constant::getIntegerValue(IntTy32, APInt(32, i)));
705 for (int i = 8; i != 16; ++i)
706 ShuffleMask.push_back(UndefValue::get(IntTy32));
707
708 Value *SV = Builder.CreateShuffleVector(Builder.CreateBitCast(Op0, ShufTy),
709 Builder.CreateBitCast(Op1, ShufTy),
710 ConstantVector::get(ShuffleMask));
711 return Builder.CreateBitCast(SV, II.getType());
712 }
713
714 // See if we're dealing with constant values.
715 Constant *C0 = dyn_cast<Constant>(Op0);
716 Constant *C1 = dyn_cast<Constant>(Op1);
717 ConstantInt *CI00 =
718 C0 ? dyn_cast<ConstantInt>(C0->getAggregateElement((unsigned)0))
719 : nullptr;
720 ConstantInt *CI10 =
721 C1 ? dyn_cast<ConstantInt>(C1->getAggregateElement((unsigned)0))
722 : nullptr;
723
724 // Constant Fold - insert bottom Length bits starting at the Index'th bit.
725 if (CI00 && CI10) {
726 APInt V00 = CI00->getValue();
727 APInt V10 = CI10->getValue();
728 APInt Mask = APInt::getLowBitsSet(64, Length).shl(Index);
729 V00 = V00 & ~Mask;
730 V10 = V10.zextOrTrunc(Length).zextOrTrunc(64).shl(Index);
731 APInt Val = V00 | V10;
732 Type *IntTy64 = Type::getInt64Ty(II.getContext());
733 Constant *Args[] = {ConstantInt::get(IntTy64, Val.getZExtValue()),
734 UndefValue::get(IntTy64)};
735 return ConstantVector::get(Args);
736 }
737
738 // If we were an INSERTQ call, we'll save demanded elements if we convert to
739 // INSERTQI.
740 if (II.getIntrinsicID() == Intrinsic::x86_sse4a_insertq) {
741 Type *IntTy8 = Type::getInt8Ty(II.getContext());
742 Constant *CILength = ConstantInt::get(IntTy8, Length, false);
743 Constant *CIIndex = ConstantInt::get(IntTy8, Index, false);
744
745 Value *Args[] = {Op0, Op1, CILength, CIIndex};
Sanjay Patelaf674fb2015-12-14 17:24:23 +0000746 Module *M = II.getModule();
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000747 Value *F = Intrinsic::getDeclaration(M, Intrinsic::x86_sse4a_insertqi);
748 return Builder.CreateCall(F, Args);
749 }
750
751 return nullptr;
752}
753
Simon Pilgrimc0c56e72016-04-24 17:00:34 +0000754/// Attempt to convert pshufb* to shufflevector if the mask is constant.
755static Value *simplifyX86pshufb(const IntrinsicInst &II,
756 InstCombiner::BuilderTy &Builder) {
Simon Pilgrimbf60cc42016-04-29 21:34:54 +0000757 Constant *V = dyn_cast<Constant>(II.getArgOperand(1));
758 if (!V)
759 return nullptr;
760
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +0000761 auto *VecTy = cast<VectorType>(II.getType());
762 auto *MaskEltTy = Type::getInt32Ty(II.getContext());
763 unsigned NumElts = VecTy->getNumElements();
Simon Pilgrimc0c56e72016-04-24 17:00:34 +0000764 assert((NumElts == 16 || NumElts == 32) &&
765 "Unexpected number of elements in shuffle mask!");
Simon Pilgrimbf60cc42016-04-29 21:34:54 +0000766
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +0000767 // Construct a shuffle mask from constant integers or UNDEFs.
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000768 Constant *Indexes[32] = {nullptr};
Simon Pilgrimc0c56e72016-04-24 17:00:34 +0000769
Simon Pilgrimbf60cc42016-04-29 21:34:54 +0000770 // Each byte in the shuffle control mask forms an index to permute the
771 // corresponding byte in the destination operand.
772 for (unsigned I = 0; I < NumElts; ++I) {
773 Constant *COp = V->getAggregateElement(I);
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +0000774 if (!COp || (!isa<UndefValue>(COp) && !isa<ConstantInt>(COp)))
Simon Pilgrimbf60cc42016-04-29 21:34:54 +0000775 return nullptr;
Simon Pilgrimc0c56e72016-04-24 17:00:34 +0000776
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +0000777 if (isa<UndefValue>(COp)) {
778 Indexes[I] = UndefValue::get(MaskEltTy);
779 continue;
780 }
781
Simon Pilgrimbf60cc42016-04-29 21:34:54 +0000782 int8_t Index = cast<ConstantInt>(COp)->getValue().getZExtValue();
783
784 // If the most significant bit (bit[7]) of each byte of the shuffle
785 // control mask is set, then zero is written in the result byte.
786 // The zero vector is in the right-hand side of the resulting
787 // shufflevector.
788
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +0000789 // The value of each index for the high 128-bit lane is the least
790 // significant 4 bits of the respective shuffle control byte.
791 Index = ((Index < 0) ? NumElts : Index & 0x0F) + (I & 0xF0);
792 Indexes[I] = ConstantInt::get(MaskEltTy, Index);
Simon Pilgrimbf60cc42016-04-29 21:34:54 +0000793 }
Simon Pilgrimc0c56e72016-04-24 17:00:34 +0000794
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +0000795 auto ShuffleMask = ConstantVector::get(makeArrayRef(Indexes, NumElts));
Simon Pilgrimc0c56e72016-04-24 17:00:34 +0000796 auto V1 = II.getArgOperand(0);
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +0000797 auto V2 = Constant::getNullValue(VecTy);
Simon Pilgrimc0c56e72016-04-24 17:00:34 +0000798 return Builder.CreateShuffleVector(V1, V2, ShuffleMask);
799}
800
Simon Pilgrim2f6097d2016-04-24 17:23:46 +0000801/// Attempt to convert vpermilvar* to shufflevector if the mask is constant.
802static Value *simplifyX86vpermilvar(const IntrinsicInst &II,
803 InstCombiner::BuilderTy &Builder) {
Simon Pilgrim640f9962016-04-30 07:23:30 +0000804 Constant *V = dyn_cast<Constant>(II.getArgOperand(1));
805 if (!V)
806 return nullptr;
Simon Pilgrim2f6097d2016-04-24 17:23:46 +0000807
Simon Pilgrimeeacc402016-05-01 20:22:42 +0000808 auto *MaskEltTy = Type::getInt32Ty(II.getContext());
809 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
810 assert(NumElts == 8 || NumElts == 4 || NumElts == 2);
Simon Pilgrim2f6097d2016-04-24 17:23:46 +0000811
Simon Pilgrimeeacc402016-05-01 20:22:42 +0000812 // Construct a shuffle mask from constant integers or UNDEFs.
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000813 Constant *Indexes[8] = {nullptr};
Simon Pilgrim640f9962016-04-30 07:23:30 +0000814
815 // The intrinsics only read one or two bits, clear the rest.
Simon Pilgrimeeacc402016-05-01 20:22:42 +0000816 for (unsigned I = 0; I < NumElts; ++I) {
Simon Pilgrim640f9962016-04-30 07:23:30 +0000817 Constant *COp = V->getAggregateElement(I);
Simon Pilgrimeeacc402016-05-01 20:22:42 +0000818 if (!COp || (!isa<UndefValue>(COp) && !isa<ConstantInt>(COp)))
Simon Pilgrim640f9962016-04-30 07:23:30 +0000819 return nullptr;
820
Simon Pilgrimeeacc402016-05-01 20:22:42 +0000821 if (isa<UndefValue>(COp)) {
822 Indexes[I] = UndefValue::get(MaskEltTy);
823 continue;
824 }
825
826 APInt Index = cast<ConstantInt>(COp)->getValue();
827 Index = Index.zextOrTrunc(32).getLoBits(2);
Simon Pilgrim640f9962016-04-30 07:23:30 +0000828
829 // The PD variants uses bit 1 to select per-lane element index, so
830 // shift down to convert to generic shuffle mask index.
831 if (II.getIntrinsicID() == Intrinsic::x86_avx_vpermilvar_pd ||
832 II.getIntrinsicID() == Intrinsic::x86_avx_vpermilvar_pd_256)
Simon Pilgrimeeacc402016-05-01 20:22:42 +0000833 Index = Index.lshr(1);
834
835 // The _256 variants are a bit trickier since the mask bits always index
836 // into the corresponding 128 half. In order to convert to a generic
837 // shuffle, we have to make that explicit.
838 if ((II.getIntrinsicID() == Intrinsic::x86_avx_vpermilvar_ps_256 ||
839 II.getIntrinsicID() == Intrinsic::x86_avx_vpermilvar_pd_256) &&
840 ((NumElts / 2) <= I)) {
841 Index += APInt(32, NumElts / 2);
842 }
843
844 Indexes[I] = ConstantInt::get(MaskEltTy, Index);
Simon Pilgrim2f6097d2016-04-24 17:23:46 +0000845 }
846
Simon Pilgrimeeacc402016-05-01 20:22:42 +0000847 auto ShuffleMask = ConstantVector::get(makeArrayRef(Indexes, NumElts));
Simon Pilgrim2f6097d2016-04-24 17:23:46 +0000848 auto V1 = II.getArgOperand(0);
849 auto V2 = UndefValue::get(V1->getType());
850 return Builder.CreateShuffleVector(V1, V2, ShuffleMask);
851}
852
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +0000853/// Attempt to convert vpermd/vpermps to shufflevector if the mask is constant.
854static Value *simplifyX86vpermv(const IntrinsicInst &II,
855 InstCombiner::BuilderTy &Builder) {
856 auto *V = dyn_cast<Constant>(II.getArgOperand(1));
857 if (!V)
858 return nullptr;
859
Simon Pilgrimca140b12016-05-01 20:43:02 +0000860 auto *VecTy = cast<VectorType>(II.getType());
861 auto *MaskEltTy = Type::getInt32Ty(II.getContext());
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +0000862 unsigned Size = VecTy->getNumElements();
863 assert(Size == 8 && "Unexpected shuffle mask size");
864
Simon Pilgrimca140b12016-05-01 20:43:02 +0000865 // Construct a shuffle mask from constant integers or UNDEFs.
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000866 Constant *Indexes[8] = {nullptr};
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +0000867
868 for (unsigned I = 0; I < Size; ++I) {
869 Constant *COp = V->getAggregateElement(I);
Simon Pilgrimca140b12016-05-01 20:43:02 +0000870 if (!COp || (!isa<UndefValue>(COp) && !isa<ConstantInt>(COp)))
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +0000871 return nullptr;
872
Simon Pilgrimca140b12016-05-01 20:43:02 +0000873 if (isa<UndefValue>(COp)) {
874 Indexes[I] = UndefValue::get(MaskEltTy);
875 continue;
876 }
877
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +0000878 APInt Index = cast<ConstantInt>(COp)->getValue();
Simon Pilgrimca140b12016-05-01 20:43:02 +0000879 Index = Index.zextOrTrunc(32).getLoBits(3);
880 Indexes[I] = ConstantInt::get(MaskEltTy, Index);
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +0000881 }
882
Simon Pilgrimca140b12016-05-01 20:43:02 +0000883 auto ShuffleMask = ConstantVector::get(makeArrayRef(Indexes, Size));
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +0000884 auto V1 = II.getArgOperand(0);
885 auto V2 = UndefValue::get(VecTy);
886 return Builder.CreateShuffleVector(V1, V2, ShuffleMask);
887}
888
Sanjay Patelccf5f242015-03-20 21:47:56 +0000889/// The shuffle mask for a perm2*128 selects any two halves of two 256-bit
890/// source vectors, unless a zero bit is set. If a zero bit is set,
891/// then ignore that half of the mask and clear that half of the vector.
Sanjay Patel6038d3e2016-01-29 23:27:03 +0000892static Value *simplifyX86vperm2(const IntrinsicInst &II,
Sanjay Patelccf5f242015-03-20 21:47:56 +0000893 InstCombiner::BuilderTy &Builder) {
Sanjay Patel03c03f52016-01-28 00:03:16 +0000894 auto *CInt = dyn_cast<ConstantInt>(II.getArgOperand(2));
895 if (!CInt)
896 return nullptr;
Sanjay Patelccf5f242015-03-20 21:47:56 +0000897
Sanjay Patel03c03f52016-01-28 00:03:16 +0000898 VectorType *VecTy = cast<VectorType>(II.getType());
899 ConstantAggregateZero *ZeroVector = ConstantAggregateZero::get(VecTy);
Sanjay Patel43a87fd2015-03-24 20:36:42 +0000900
Sanjay Patel03c03f52016-01-28 00:03:16 +0000901 // The immediate permute control byte looks like this:
902 // [1:0] - select 128 bits from sources for low half of destination
903 // [2] - ignore
904 // [3] - zero low half of destination
905 // [5:4] - select 128 bits from sources for high half of destination
906 // [6] - ignore
907 // [7] - zero high half of destination
Sanjay Patel43a87fd2015-03-24 20:36:42 +0000908
Sanjay Patel03c03f52016-01-28 00:03:16 +0000909 uint8_t Imm = CInt->getZExtValue();
Sanjay Patel43a87fd2015-03-24 20:36:42 +0000910
Sanjay Patel03c03f52016-01-28 00:03:16 +0000911 bool LowHalfZero = Imm & 0x08;
912 bool HighHalfZero = Imm & 0x80;
Sanjay Patel43a87fd2015-03-24 20:36:42 +0000913
Sanjay Patel03c03f52016-01-28 00:03:16 +0000914 // If both zero mask bits are set, this was just a weird way to
915 // generate a zero vector.
916 if (LowHalfZero && HighHalfZero)
917 return ZeroVector;
Sanjay Patel43a87fd2015-03-24 20:36:42 +0000918
Sanjay Patel03c03f52016-01-28 00:03:16 +0000919 // If 0 or 1 zero mask bits are set, this is a simple shuffle.
920 unsigned NumElts = VecTy->getNumElements();
921 unsigned HalfSize = NumElts / 2;
Craig Topper99d1eab2016-06-12 00:41:19 +0000922 SmallVector<uint32_t, 8> ShuffleMask(NumElts);
Simon Pilgrim54fcd622015-07-25 20:41:00 +0000923
Sanjay Patel03c03f52016-01-28 00:03:16 +0000924 // The high bit of the selection field chooses the 1st or 2nd operand.
925 bool LowInputSelect = Imm & 0x02;
926 bool HighInputSelect = Imm & 0x20;
Sanjay Patelccf5f242015-03-20 21:47:56 +0000927
Sanjay Patel03c03f52016-01-28 00:03:16 +0000928 // The low bit of the selection field chooses the low or high half
929 // of the selected operand.
930 bool LowHalfSelect = Imm & 0x01;
931 bool HighHalfSelect = Imm & 0x10;
Simon Pilgrim54fcd622015-07-25 20:41:00 +0000932
Sanjay Patel03c03f52016-01-28 00:03:16 +0000933 // Determine which operand(s) are actually in use for this instruction.
934 Value *V0 = LowInputSelect ? II.getArgOperand(1) : II.getArgOperand(0);
935 Value *V1 = HighInputSelect ? II.getArgOperand(1) : II.getArgOperand(0);
Simon Pilgrim54fcd622015-07-25 20:41:00 +0000936
Sanjay Patel03c03f52016-01-28 00:03:16 +0000937 // If needed, replace operands based on zero mask.
938 V0 = LowHalfZero ? ZeroVector : V0;
939 V1 = HighHalfZero ? ZeroVector : V1;
Sanjay Patelccf5f242015-03-20 21:47:56 +0000940
Sanjay Patel03c03f52016-01-28 00:03:16 +0000941 // Permute low half of result.
942 unsigned StartIndex = LowHalfSelect ? HalfSize : 0;
943 for (unsigned i = 0; i < HalfSize; ++i)
944 ShuffleMask[i] = StartIndex + i;
Sanjay Patel43a87fd2015-03-24 20:36:42 +0000945
Sanjay Patel03c03f52016-01-28 00:03:16 +0000946 // Permute high half of result.
947 StartIndex = HighHalfSelect ? HalfSize : 0;
948 StartIndex += NumElts;
949 for (unsigned i = 0; i < HalfSize; ++i)
950 ShuffleMask[i + HalfSize] = StartIndex + i;
951
952 return Builder.CreateShuffleVector(V0, V1, ShuffleMask);
Sanjay Patelccf5f242015-03-20 21:47:56 +0000953}
954
Simon Pilgrim1d1c56e22015-10-11 14:38:34 +0000955/// Decode XOP integer vector comparison intrinsics.
Sanjay Patel6038d3e2016-01-29 23:27:03 +0000956static Value *simplifyX86vpcom(const IntrinsicInst &II,
Sanjay Patelf9f5d3c2016-01-29 23:14:58 +0000957 InstCombiner::BuilderTy &Builder,
958 bool IsSigned) {
Simon Pilgrim1d1c56e22015-10-11 14:38:34 +0000959 if (auto *CInt = dyn_cast<ConstantInt>(II.getArgOperand(2))) {
960 uint64_t Imm = CInt->getZExtValue() & 0x7;
961 VectorType *VecTy = cast<VectorType>(II.getType());
962 CmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
963
964 switch (Imm) {
965 case 0x0:
966 Pred = IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
967 break;
968 case 0x1:
969 Pred = IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
970 break;
971 case 0x2:
972 Pred = IsSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
973 break;
974 case 0x3:
975 Pred = IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
976 break;
977 case 0x4:
978 Pred = ICmpInst::ICMP_EQ; break;
979 case 0x5:
980 Pred = ICmpInst::ICMP_NE; break;
981 case 0x6:
982 return ConstantInt::getSigned(VecTy, 0); // FALSE
983 case 0x7:
984 return ConstantInt::getSigned(VecTy, -1); // TRUE
985 }
986
Sanjay Patelf9f5d3c2016-01-29 23:14:58 +0000987 if (Value *Cmp = Builder.CreateICmp(Pred, II.getArgOperand(0),
988 II.getArgOperand(1)))
Simon Pilgrim1d1c56e22015-10-11 14:38:34 +0000989 return Builder.CreateSExtOrTrunc(Cmp, VecTy);
990 }
991 return nullptr;
992}
993
Sanjay Patel0069f562016-01-31 16:35:23 +0000994static Value *simplifyMinnumMaxnum(const IntrinsicInst &II) {
995 Value *Arg0 = II.getArgOperand(0);
996 Value *Arg1 = II.getArgOperand(1);
997
998 // fmin(x, x) -> x
999 if (Arg0 == Arg1)
1000 return Arg0;
1001
1002 const auto *C1 = dyn_cast<ConstantFP>(Arg1);
1003
1004 // fmin(x, nan) -> x
1005 if (C1 && C1->isNaN())
1006 return Arg0;
1007
1008 // This is the value because if undef were NaN, we would return the other
1009 // value and cannot return a NaN unless both operands are.
1010 //
1011 // fmin(undef, x) -> x
1012 if (isa<UndefValue>(Arg0))
1013 return Arg1;
1014
1015 // fmin(x, undef) -> x
1016 if (isa<UndefValue>(Arg1))
1017 return Arg0;
1018
1019 Value *X = nullptr;
1020 Value *Y = nullptr;
1021 if (II.getIntrinsicID() == Intrinsic::minnum) {
1022 // fmin(x, fmin(x, y)) -> fmin(x, y)
1023 // fmin(y, fmin(x, y)) -> fmin(x, y)
1024 if (match(Arg1, m_FMin(m_Value(X), m_Value(Y)))) {
1025 if (Arg0 == X || Arg0 == Y)
1026 return Arg1;
1027 }
1028
1029 // fmin(fmin(x, y), x) -> fmin(x, y)
1030 // fmin(fmin(x, y), y) -> fmin(x, y)
1031 if (match(Arg0, m_FMin(m_Value(X), m_Value(Y)))) {
1032 if (Arg1 == X || Arg1 == Y)
1033 return Arg0;
1034 }
1035
1036 // TODO: fmin(nnan x, inf) -> x
1037 // TODO: fmin(nnan ninf x, flt_max) -> x
1038 if (C1 && C1->isInfinity()) {
1039 // fmin(x, -inf) -> -inf
1040 if (C1->isNegative())
1041 return Arg1;
1042 }
1043 } else {
1044 assert(II.getIntrinsicID() == Intrinsic::maxnum);
1045 // fmax(x, fmax(x, y)) -> fmax(x, y)
1046 // fmax(y, fmax(x, y)) -> fmax(x, y)
1047 if (match(Arg1, m_FMax(m_Value(X), m_Value(Y)))) {
1048 if (Arg0 == X || Arg0 == Y)
1049 return Arg1;
1050 }
1051
1052 // fmax(fmax(x, y), x) -> fmax(x, y)
1053 // fmax(fmax(x, y), y) -> fmax(x, y)
1054 if (match(Arg0, m_FMax(m_Value(X), m_Value(Y)))) {
1055 if (Arg1 == X || Arg1 == Y)
1056 return Arg0;
1057 }
1058
1059 // TODO: fmax(nnan x, -inf) -> x
1060 // TODO: fmax(nnan ninf x, -flt_max) -> x
1061 if (C1 && C1->isInfinity()) {
1062 // fmax(x, inf) -> inf
1063 if (!C1->isNegative())
1064 return Arg1;
1065 }
1066 }
1067 return nullptr;
1068}
1069
David Majnemer666aa942016-07-14 06:58:42 +00001070static bool maskIsAllOneOrUndef(Value *Mask) {
1071 auto *ConstMask = dyn_cast<Constant>(Mask);
1072 if (!ConstMask)
1073 return false;
1074 if (ConstMask->isAllOnesValue() || isa<UndefValue>(ConstMask))
1075 return true;
1076 for (unsigned I = 0, E = ConstMask->getType()->getVectorNumElements(); I != E;
1077 ++I) {
1078 if (auto *MaskElt = ConstMask->getAggregateElement(I))
1079 if (MaskElt->isAllOnesValue() || isa<UndefValue>(MaskElt))
1080 continue;
1081 return false;
1082 }
1083 return true;
1084}
1085
Sanjay Patelb695c552016-02-01 17:00:10 +00001086static Value *simplifyMaskedLoad(const IntrinsicInst &II,
1087 InstCombiner::BuilderTy &Builder) {
David Majnemer666aa942016-07-14 06:58:42 +00001088 // If the mask is all ones or undefs, this is a plain vector load of the 1st
1089 // argument.
1090 if (maskIsAllOneOrUndef(II.getArgOperand(2))) {
Sanjay Patelb695c552016-02-01 17:00:10 +00001091 Value *LoadPtr = II.getArgOperand(0);
1092 unsigned Alignment = cast<ConstantInt>(II.getArgOperand(1))->getZExtValue();
1093 return Builder.CreateAlignedLoad(LoadPtr, Alignment, "unmaskedload");
1094 }
1095
1096 return nullptr;
1097}
1098
Sanjay Patel04f792b2016-02-01 19:39:52 +00001099static Instruction *simplifyMaskedStore(IntrinsicInst &II, InstCombiner &IC) {
1100 auto *ConstMask = dyn_cast<Constant>(II.getArgOperand(3));
1101 if (!ConstMask)
1102 return nullptr;
1103
1104 // If the mask is all zeros, this instruction does nothing.
1105 if (ConstMask->isNullValue())
Sanjay Patel4b198802016-02-01 22:23:39 +00001106 return IC.eraseInstFromFunction(II);
Sanjay Patel04f792b2016-02-01 19:39:52 +00001107
1108 // If the mask is all ones, this is a plain vector store of the 1st argument.
1109 if (ConstMask->isAllOnesValue()) {
1110 Value *StorePtr = II.getArgOperand(1);
1111 unsigned Alignment = cast<ConstantInt>(II.getArgOperand(2))->getZExtValue();
1112 return new StoreInst(II.getArgOperand(0), StorePtr, false, Alignment);
1113 }
1114
1115 return nullptr;
1116}
1117
Sanjay Patel103ab7d2016-02-01 22:10:26 +00001118static Instruction *simplifyMaskedGather(IntrinsicInst &II, InstCombiner &IC) {
1119 // If the mask is all zeros, return the "passthru" argument of the gather.
1120 auto *ConstMask = dyn_cast<Constant>(II.getArgOperand(2));
1121 if (ConstMask && ConstMask->isNullValue())
Sanjay Patel4b198802016-02-01 22:23:39 +00001122 return IC.replaceInstUsesWith(II, II.getArgOperand(3));
Sanjay Patel103ab7d2016-02-01 22:10:26 +00001123
1124 return nullptr;
1125}
1126
1127static Instruction *simplifyMaskedScatter(IntrinsicInst &II, InstCombiner &IC) {
1128 // If the mask is all zeros, a scatter does nothing.
1129 auto *ConstMask = dyn_cast<Constant>(II.getArgOperand(3));
1130 if (ConstMask && ConstMask->isNullValue())
Sanjay Patel4b198802016-02-01 22:23:39 +00001131 return IC.eraseInstFromFunction(II);
Sanjay Patel103ab7d2016-02-01 22:10:26 +00001132
1133 return nullptr;
1134}
1135
Amaury Sechet763c59d2016-08-18 20:43:50 +00001136static Instruction *foldCttzCtlz(IntrinsicInst &II, InstCombiner &IC) {
1137 assert((II.getIntrinsicID() == Intrinsic::cttz ||
1138 II.getIntrinsicID() == Intrinsic::ctlz) &&
1139 "Expected cttz or ctlz intrinsic");
Sanjay Patel8e3ab172016-08-05 22:42:46 +00001140 Value *Op0 = II.getArgOperand(0);
1141 // FIXME: Try to simplify vectors of integers.
1142 auto *IT = dyn_cast<IntegerType>(Op0->getType());
1143 if (!IT)
1144 return nullptr;
1145
1146 unsigned BitWidth = IT->getBitWidth();
1147 APInt KnownZero(BitWidth, 0);
1148 APInt KnownOne(BitWidth, 0);
1149 IC.computeKnownBits(Op0, KnownZero, KnownOne, 0, &II);
1150
1151 // Create a mask for bits above (ctlz) or below (cttz) the first known one.
1152 bool IsTZ = II.getIntrinsicID() == Intrinsic::cttz;
1153 unsigned NumMaskBits = IsTZ ? KnownOne.countTrailingZeros()
1154 : KnownOne.countLeadingZeros();
1155 APInt Mask = IsTZ ? APInt::getLowBitsSet(BitWidth, NumMaskBits)
1156 : APInt::getHighBitsSet(BitWidth, NumMaskBits);
1157
1158 // If all bits above (ctlz) or below (cttz) the first known one are known
1159 // zero, this value is constant.
1160 // FIXME: This should be in InstSimplify because we're replacing an
1161 // instruction with a constant.
Amaury Sechet763c59d2016-08-18 20:43:50 +00001162 if ((Mask & KnownZero) == Mask) {
1163 auto *C = ConstantInt::get(IT, APInt(BitWidth, NumMaskBits));
1164 return IC.replaceInstUsesWith(II, C);
1165 }
1166
1167 // If the input to cttz/ctlz is known to be non-zero,
1168 // then change the 'ZeroIsUndef' parameter to 'true'
1169 // because we know the zero behavior can't affect the result.
1170 if (KnownOne != 0 || isKnownNonZero(Op0, IC.getDataLayout())) {
1171 if (!match(II.getArgOperand(1), m_One())) {
1172 II.setOperand(1, IC.Builder->getTrue());
1173 return &II;
1174 }
1175 }
Sanjay Patel8e3ab172016-08-05 22:42:46 +00001176
1177 return nullptr;
1178}
1179
Sanjay Patel1ace9932016-02-26 21:04:14 +00001180// TODO: If the x86 backend knew how to convert a bool vector mask back to an
1181// XMM register mask efficiently, we could transform all x86 masked intrinsics
1182// to LLVM masked intrinsics and remove the x86 masked intrinsic defs.
Sanjay Patel98a71502016-02-29 23:16:48 +00001183static Instruction *simplifyX86MaskedLoad(IntrinsicInst &II, InstCombiner &IC) {
1184 Value *Ptr = II.getOperand(0);
1185 Value *Mask = II.getOperand(1);
Sanjay Patel5e5056d2016-04-12 23:16:23 +00001186 Constant *ZeroVec = Constant::getNullValue(II.getType());
Sanjay Patel98a71502016-02-29 23:16:48 +00001187
1188 // Special case a zero mask since that's not a ConstantDataVector.
Sanjay Patel5e5056d2016-04-12 23:16:23 +00001189 // This masked load instruction creates a zero vector.
Sanjay Patel98a71502016-02-29 23:16:48 +00001190 if (isa<ConstantAggregateZero>(Mask))
Sanjay Patel5e5056d2016-04-12 23:16:23 +00001191 return IC.replaceInstUsesWith(II, ZeroVec);
Sanjay Patel98a71502016-02-29 23:16:48 +00001192
1193 auto *ConstMask = dyn_cast<ConstantDataVector>(Mask);
1194 if (!ConstMask)
1195 return nullptr;
1196
1197 // The mask is constant. Convert this x86 intrinsic to the LLVM instrinsic
1198 // to allow target-independent optimizations.
1199
1200 // First, cast the x86 intrinsic scalar pointer to a vector pointer to match
1201 // the LLVM intrinsic definition for the pointer argument.
1202 unsigned AddrSpace = cast<PointerType>(Ptr->getType())->getAddressSpace();
1203 PointerType *VecPtrTy = PointerType::get(II.getType(), AddrSpace);
1204 Value *PtrCast = IC.Builder->CreateBitCast(Ptr, VecPtrTy, "castvec");
1205
1206 // Second, convert the x86 XMM integer vector mask to a vector of bools based
1207 // on each element's most significant bit (the sign bit).
1208 Constant *BoolMask = getNegativeIsTrueBoolVec(ConstMask);
1209
Sanjay Patel5e5056d2016-04-12 23:16:23 +00001210 // The pass-through vector for an x86 masked load is a zero vector.
1211 CallInst *NewMaskedLoad =
1212 IC.Builder->CreateMaskedLoad(PtrCast, 1, BoolMask, ZeroVec);
Sanjay Patel98a71502016-02-29 23:16:48 +00001213 return IC.replaceInstUsesWith(II, NewMaskedLoad);
1214}
1215
1216// TODO: If the x86 backend knew how to convert a bool vector mask back to an
1217// XMM register mask efficiently, we could transform all x86 masked intrinsics
1218// to LLVM masked intrinsics and remove the x86 masked intrinsic defs.
Sanjay Patel1ace9932016-02-26 21:04:14 +00001219static bool simplifyX86MaskedStore(IntrinsicInst &II, InstCombiner &IC) {
1220 Value *Ptr = II.getOperand(0);
1221 Value *Mask = II.getOperand(1);
1222 Value *Vec = II.getOperand(2);
1223
1224 // Special case a zero mask since that's not a ConstantDataVector:
1225 // this masked store instruction does nothing.
1226 if (isa<ConstantAggregateZero>(Mask)) {
1227 IC.eraseInstFromFunction(II);
1228 return true;
1229 }
1230
Sanjay Patelc4acbae2016-03-12 15:16:59 +00001231 // The SSE2 version is too weird (eg, unaligned but non-temporal) to do
1232 // anything else at this level.
1233 if (II.getIntrinsicID() == Intrinsic::x86_sse2_maskmov_dqu)
1234 return false;
1235
Sanjay Patel1ace9932016-02-26 21:04:14 +00001236 auto *ConstMask = dyn_cast<ConstantDataVector>(Mask);
1237 if (!ConstMask)
1238 return false;
1239
1240 // The mask is constant. Convert this x86 intrinsic to the LLVM instrinsic
1241 // to allow target-independent optimizations.
1242
1243 // First, cast the x86 intrinsic scalar pointer to a vector pointer to match
1244 // the LLVM intrinsic definition for the pointer argument.
1245 unsigned AddrSpace = cast<PointerType>(Ptr->getType())->getAddressSpace();
1246 PointerType *VecPtrTy = PointerType::get(Vec->getType(), AddrSpace);
Sanjay Patel1ace9932016-02-26 21:04:14 +00001247 Value *PtrCast = IC.Builder->CreateBitCast(Ptr, VecPtrTy, "castvec");
1248
1249 // Second, convert the x86 XMM integer vector mask to a vector of bools based
1250 // on each element's most significant bit (the sign bit).
1251 Constant *BoolMask = getNegativeIsTrueBoolVec(ConstMask);
1252
1253 IC.Builder->CreateMaskedStore(Vec, PtrCast, 1, BoolMask);
1254
1255 // 'Replace uses' doesn't work for stores. Erase the original masked store.
1256 IC.eraseInstFromFunction(II);
1257 return true;
1258}
1259
Arnaud A. de Grandmaison333ef382016-05-10 09:24:49 +00001260// Returns true iff the 2 intrinsics have the same operands, limiting the
1261// comparison to the first NumOperands.
1262static bool haveSameOperands(const IntrinsicInst &I, const IntrinsicInst &E,
1263 unsigned NumOperands) {
1264 assert(I.getNumArgOperands() >= NumOperands && "Not enough operands");
1265 assert(E.getNumArgOperands() >= NumOperands && "Not enough operands");
1266 for (unsigned i = 0; i < NumOperands; i++)
1267 if (I.getArgOperand(i) != E.getArgOperand(i))
1268 return false;
1269 return true;
1270}
1271
1272// Remove trivially empty start/end intrinsic ranges, i.e. a start
1273// immediately followed by an end (ignoring debuginfo or other
1274// start/end intrinsics in between). As this handles only the most trivial
1275// cases, tracking the nesting level is not needed:
1276//
1277// call @llvm.foo.start(i1 0) ; &I
1278// call @llvm.foo.start(i1 0)
1279// call @llvm.foo.end(i1 0) ; This one will not be skipped: it will be removed
1280// call @llvm.foo.end(i1 0)
1281static bool removeTriviallyEmptyRange(IntrinsicInst &I, unsigned StartID,
1282 unsigned EndID, InstCombiner &IC) {
1283 assert(I.getIntrinsicID() == StartID &&
1284 "Start intrinsic does not have expected ID");
1285 BasicBlock::iterator BI(I), BE(I.getParent()->end());
1286 for (++BI; BI != BE; ++BI) {
1287 if (auto *E = dyn_cast<IntrinsicInst>(BI)) {
1288 if (isa<DbgInfoIntrinsic>(E) || E->getIntrinsicID() == StartID)
1289 continue;
1290 if (E->getIntrinsicID() == EndID &&
1291 haveSameOperands(I, *E, E->getNumArgOperands())) {
1292 IC.eraseInstFromFunction(*E);
1293 IC.eraseInstFromFunction(I);
1294 return true;
1295 }
1296 }
1297 break;
1298 }
1299
1300 return false;
1301}
1302
1303Instruction *InstCombiner::visitVAStartInst(VAStartInst &I) {
1304 removeTriviallyEmptyRange(I, Intrinsic::vastart, Intrinsic::vaend, *this);
1305 return nullptr;
1306}
1307
1308Instruction *InstCombiner::visitVACopyInst(VACopyInst &I) {
1309 removeTriviallyEmptyRange(I, Intrinsic::vacopy, Intrinsic::vaend, *this);
1310 return nullptr;
1311}
1312
Sanjay Patelcd4377c2016-01-20 22:24:38 +00001313/// CallInst simplification. This mostly only handles folding of intrinsic
1314/// instructions. For normal calls, it allows visitCallSite to do the heavy
1315/// lifting.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001316Instruction *InstCombiner::visitCallInst(CallInst &CI) {
David Majnemer15032582015-05-22 03:56:46 +00001317 auto Args = CI.arg_operands();
1318 if (Value *V = SimplifyCall(CI.getCalledValue(), Args.begin(), Args.end(), DL,
Justin Bogner99798402016-08-05 01:06:44 +00001319 &TLI, &DT, &AC))
Sanjay Patel4b198802016-02-01 22:23:39 +00001320 return replaceInstUsesWith(CI, V);
David Majnemer15032582015-05-22 03:56:46 +00001321
Justin Bogner99798402016-08-05 01:06:44 +00001322 if (isFreeCall(&CI, &TLI))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001323 return visitFree(CI);
1324
1325 // If the caller function is nounwind, mark the call as nounwind, even if the
1326 // callee isn't.
Sanjay Patel5a470952016-08-11 15:16:06 +00001327 if (CI.getFunction()->doesNotThrow() && !CI.doesNotThrow()) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001328 CI.setDoesNotThrow();
1329 return &CI;
1330 }
Jim Grosbach7815f562012-02-03 00:07:04 +00001331
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001332 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
1333 if (!II) return visitCallSite(&CI);
Gabor Greif589a0b92010-06-24 12:58:35 +00001334
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001335 // Intrinsics cannot occur in an invoke, so handle them here instead of in
1336 // visitCallSite.
1337 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
1338 bool Changed = false;
1339
1340 // memmove/cpy/set of zero bytes is a noop.
1341 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
Chris Lattnerc663a672010-10-01 05:51:02 +00001342 if (NumBytes->isNullValue())
Sanjay Patel4b198802016-02-01 22:23:39 +00001343 return eraseInstFromFunction(CI);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001344
1345 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
1346 if (CI->getZExtValue() == 1) {
1347 // Replace the instruction with just byte operations. We would
1348 // transform other cases to loads/stores, but we don't know if
1349 // alignment is sufficient.
1350 }
1351 }
Jim Grosbach7815f562012-02-03 00:07:04 +00001352
Chris Lattnerc663a672010-10-01 05:51:02 +00001353 // No other transformations apply to volatile transfers.
1354 if (MI->isVolatile())
Craig Topperf40110f2014-04-25 05:29:35 +00001355 return nullptr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001356
1357 // If we have a memmove and the source operation is a constant global,
1358 // then the source and dest pointers can't alias, so we can change this
1359 // into a call to memcpy.
1360 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
1361 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
1362 if (GVSrc->isConstant()) {
Sanjay Patelaf674fb2015-12-14 17:24:23 +00001363 Module *M = CI.getModule();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001364 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
Jay Foadb804a2b2011-07-12 14:06:48 +00001365 Type *Tys[3] = { CI.getArgOperand(0)->getType(),
1366 CI.getArgOperand(1)->getType(),
1367 CI.getArgOperand(2)->getType() };
Benjamin Kramere6e19332011-07-14 17:45:39 +00001368 CI.setCalledFunction(Intrinsic::getDeclaration(M, MemCpyID, Tys));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001369 Changed = true;
1370 }
1371 }
1372
1373 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) {
1374 // memmove(x,x,size) -> noop.
1375 if (MTI->getSource() == MTI->getDest())
Sanjay Patel4b198802016-02-01 22:23:39 +00001376 return eraseInstFromFunction(CI);
Eric Christopher7258dcd2010-04-16 23:37:20 +00001377 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001378
Eric Christopher7258dcd2010-04-16 23:37:20 +00001379 // If we can determine a pointer alignment that is bigger than currently
1380 // set, update the alignment.
Pete Cooper67cf9a72015-11-19 05:56:52 +00001381 if (isa<MemTransferInst>(MI)) {
1382 if (Instruction *I = SimplifyMemTransfer(MI))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001383 return I;
1384 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
1385 if (Instruction *I = SimplifyMemSet(MSI))
1386 return I;
1387 }
Gabor Greif590d95e2010-06-24 13:42:49 +00001388
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001389 if (Changed) return II;
1390 }
Jim Grosbach7815f562012-02-03 00:07:04 +00001391
Sanjay Patel1c600c62016-01-20 16:41:43 +00001392 auto SimplifyDemandedVectorEltsLow = [this](Value *Op, unsigned Width,
1393 unsigned DemandedWidth) {
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001394 APInt UndefElts(Width, 0);
1395 APInt DemandedElts = APInt::getLowBitsSet(Width, DemandedWidth);
1396 return SimplifyDemandedVectorElts(Op, DemandedElts, UndefElts);
1397 };
Simon Pilgrim424da162016-04-24 18:12:42 +00001398 auto SimplifyDemandedVectorEltsHigh = [this](Value *Op, unsigned Width,
1399 unsigned DemandedWidth) {
1400 APInt UndefElts(Width, 0);
1401 APInt DemandedElts = APInt::getHighBitsSet(Width, DemandedWidth);
1402 return SimplifyDemandedVectorElts(Op, DemandedElts, UndefElts);
1403 };
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001404
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001405 switch (II->getIntrinsicID()) {
1406 default: break;
Eric Christopher7b7028f2010-02-09 21:24:27 +00001407 case Intrinsic::objectsize: {
Nuno Lopes55fff832012-06-21 15:45:28 +00001408 uint64_t Size;
Justin Bogner99798402016-08-05 01:06:44 +00001409 if (getObjectSize(II->getArgOperand(0), Size, DL, &TLI)) {
George Burgess IV278199f2016-04-12 01:05:35 +00001410 APInt APSize(II->getType()->getIntegerBitWidth(), Size);
1411 // Equality check to be sure that `Size` can fit in a value of type
1412 // `II->getType()`
1413 if (APSize == Size)
1414 return replaceInstUsesWith(CI, ConstantInt::get(II->getType(), APSize));
1415 }
Craig Topperf40110f2014-04-25 05:29:35 +00001416 return nullptr;
Eric Christopher7b7028f2010-02-09 21:24:27 +00001417 }
Michael Ilseman536cc322012-12-13 03:13:36 +00001418 case Intrinsic::bswap: {
1419 Value *IIOperand = II->getArgOperand(0);
Craig Topperf40110f2014-04-25 05:29:35 +00001420 Value *X = nullptr;
Michael Ilseman536cc322012-12-13 03:13:36 +00001421
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001422 // bswap(bswap(x)) -> x
Michael Ilseman536cc322012-12-13 03:13:36 +00001423 if (match(IIOperand, m_BSwap(m_Value(X))))
Sanjay Patel4b198802016-02-01 22:23:39 +00001424 return replaceInstUsesWith(CI, X);
Jim Grosbach7815f562012-02-03 00:07:04 +00001425
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001426 // bswap(trunc(bswap(x))) -> trunc(lshr(x, c))
Michael Ilseman536cc322012-12-13 03:13:36 +00001427 if (match(IIOperand, m_Trunc(m_BSwap(m_Value(X))))) {
1428 unsigned C = X->getType()->getPrimitiveSizeInBits() -
1429 IIOperand->getType()->getPrimitiveSizeInBits();
1430 Value *CV = ConstantInt::get(X->getType(), C);
1431 Value *V = Builder->CreateLShr(X, CV);
1432 return new TruncInst(V, IIOperand->getType());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001433 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001434 break;
Michael Ilseman536cc322012-12-13 03:13:36 +00001435 }
1436
James Molloy2d09c002015-11-12 12:39:41 +00001437 case Intrinsic::bitreverse: {
1438 Value *IIOperand = II->getArgOperand(0);
1439 Value *X = nullptr;
1440
1441 // bitreverse(bitreverse(x)) -> x
1442 if (match(IIOperand, m_Intrinsic<Intrinsic::bitreverse>(m_Value(X))))
Sanjay Patel4b198802016-02-01 22:23:39 +00001443 return replaceInstUsesWith(CI, X);
James Molloy2d09c002015-11-12 12:39:41 +00001444 break;
1445 }
1446
Sanjay Patelb695c552016-02-01 17:00:10 +00001447 case Intrinsic::masked_load:
1448 if (Value *SimplifiedMaskedOp = simplifyMaskedLoad(*II, *Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00001449 return replaceInstUsesWith(CI, SimplifiedMaskedOp);
Sanjay Patelb695c552016-02-01 17:00:10 +00001450 break;
Sanjay Patel04f792b2016-02-01 19:39:52 +00001451 case Intrinsic::masked_store:
1452 return simplifyMaskedStore(*II, *this);
Sanjay Patel103ab7d2016-02-01 22:10:26 +00001453 case Intrinsic::masked_gather:
1454 return simplifyMaskedGather(*II, *this);
1455 case Intrinsic::masked_scatter:
1456 return simplifyMaskedScatter(*II, *this);
Sanjay Patelb695c552016-02-01 17:00:10 +00001457
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001458 case Intrinsic::powi:
Gabor Greif589a0b92010-06-24 12:58:35 +00001459 if (ConstantInt *Power = dyn_cast<ConstantInt>(II->getArgOperand(1))) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001460 // powi(x, 0) -> 1.0
1461 if (Power->isZero())
Sanjay Patel4b198802016-02-01 22:23:39 +00001462 return replaceInstUsesWith(CI, ConstantFP::get(CI.getType(), 1.0));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001463 // powi(x, 1) -> x
1464 if (Power->isOne())
Sanjay Patel4b198802016-02-01 22:23:39 +00001465 return replaceInstUsesWith(CI, II->getArgOperand(0));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001466 // powi(x, -1) -> 1/x
1467 if (Power->isAllOnesValue())
1468 return BinaryOperator::CreateFDiv(ConstantFP::get(CI.getType(), 1.0),
Gabor Greif589a0b92010-06-24 12:58:35 +00001469 II->getArgOperand(0));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001470 }
1471 break;
Jim Grosbach7815f562012-02-03 00:07:04 +00001472
Sanjay Patel8e3ab172016-08-05 22:42:46 +00001473 case Intrinsic::cttz:
1474 case Intrinsic::ctlz:
Amaury Sechet763c59d2016-08-18 20:43:50 +00001475 if (auto *I = foldCttzCtlz(*II, *this))
1476 return I;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001477 break;
Sanjoy Dasb0984472015-04-08 04:27:22 +00001478
Nick Lewyckyabe2cc12015-04-13 19:17:37 +00001479 case Intrinsic::uadd_with_overflow:
1480 case Intrinsic::sadd_with_overflow:
1481 case Intrinsic::umul_with_overflow:
1482 case Intrinsic::smul_with_overflow:
Gabor Greif5b1370e2010-06-28 16:50:57 +00001483 if (isa<Constant>(II->getArgOperand(0)) &&
1484 !isa<Constant>(II->getArgOperand(1))) {
Sanjoy Dasb0984472015-04-08 04:27:22 +00001485 // Canonicalize constants into the RHS.
Gabor Greif5b1370e2010-06-28 16:50:57 +00001486 Value *LHS = II->getArgOperand(0);
1487 II->setArgOperand(0, II->getArgOperand(1));
1488 II->setArgOperand(1, LHS);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001489 return II;
1490 }
Justin Bognercd1d5aa2016-08-17 20:30:52 +00001491 LLVM_FALLTHROUGH;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001492
Nick Lewyckyabe2cc12015-04-13 19:17:37 +00001493 case Intrinsic::usub_with_overflow:
1494 case Intrinsic::ssub_with_overflow: {
Sanjoy Dasb0984472015-04-08 04:27:22 +00001495 OverflowCheckFlavor OCF =
1496 IntrinsicIDToOverflowCheckFlavor(II->getIntrinsicID());
1497 assert(OCF != OCF_INVALID && "unexpected!");
Jim Grosbach7815f562012-02-03 00:07:04 +00001498
Sanjoy Dasb0984472015-04-08 04:27:22 +00001499 Value *OperationResult = nullptr;
1500 Constant *OverflowResult = nullptr;
1501 if (OptimizeOverflowCheck(OCF, II->getArgOperand(0), II->getArgOperand(1),
1502 *II, OperationResult, OverflowResult))
1503 return CreateOverflowTuple(II, OperationResult, OverflowResult);
Benjamin Kramera420df22014-07-04 10:22:21 +00001504
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001505 break;
Erik Eckstein096ff7d2014-12-11 08:02:30 +00001506 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001507
Matt Arsenaultd6511b42014-10-21 23:00:20 +00001508 case Intrinsic::minnum:
1509 case Intrinsic::maxnum: {
1510 Value *Arg0 = II->getArgOperand(0);
1511 Value *Arg1 = II->getArgOperand(1);
Sanjay Patel0069f562016-01-31 16:35:23 +00001512 // Canonicalize constants to the RHS.
1513 if (isa<ConstantFP>(Arg0) && !isa<ConstantFP>(Arg1)) {
Matt Arsenaultd6511b42014-10-21 23:00:20 +00001514 II->setArgOperand(0, Arg1);
1515 II->setArgOperand(1, Arg0);
1516 return II;
1517 }
Sanjay Patel0069f562016-01-31 16:35:23 +00001518 if (Value *V = simplifyMinnumMaxnum(*II))
Sanjay Patel4b198802016-02-01 22:23:39 +00001519 return replaceInstUsesWith(*II, V);
Matt Arsenaultd6511b42014-10-21 23:00:20 +00001520 break;
1521 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001522 case Intrinsic::ppc_altivec_lvx:
1523 case Intrinsic::ppc_altivec_lvxl:
Bill Wendlingb902f1d2011-04-13 00:36:11 +00001524 // Turn PPC lvx -> load if the pointer is known aligned.
Justin Bogner99798402016-08-05 01:06:44 +00001525 if (getOrEnforceKnownAlignment(II->getArgOperand(0), 16, DL, II, &AC,
1526 &DT) >= 16) {
Gabor Greif589a0b92010-06-24 12:58:35 +00001527 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(0),
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001528 PointerType::getUnqual(II->getType()));
1529 return new LoadInst(Ptr);
1530 }
1531 break;
Bill Schmidt72954782014-11-12 04:19:40 +00001532 case Intrinsic::ppc_vsx_lxvw4x:
1533 case Intrinsic::ppc_vsx_lxvd2x: {
1534 // Turn PPC VSX loads into normal loads.
1535 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(0),
1536 PointerType::getUnqual(II->getType()));
1537 return new LoadInst(Ptr, Twine(""), false, 1);
1538 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001539 case Intrinsic::ppc_altivec_stvx:
1540 case Intrinsic::ppc_altivec_stvxl:
1541 // Turn stvx -> store if the pointer is known aligned.
Justin Bogner99798402016-08-05 01:06:44 +00001542 if (getOrEnforceKnownAlignment(II->getArgOperand(1), 16, DL, II, &AC,
1543 &DT) >= 16) {
Jim Grosbach7815f562012-02-03 00:07:04 +00001544 Type *OpPtrTy =
Gabor Greifa6d75e22010-06-24 15:51:11 +00001545 PointerType::getUnqual(II->getArgOperand(0)->getType());
1546 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(1), OpPtrTy);
1547 return new StoreInst(II->getArgOperand(0), Ptr);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001548 }
1549 break;
Bill Schmidt72954782014-11-12 04:19:40 +00001550 case Intrinsic::ppc_vsx_stxvw4x:
1551 case Intrinsic::ppc_vsx_stxvd2x: {
1552 // Turn PPC VSX stores into normal stores.
1553 Type *OpPtrTy = PointerType::getUnqual(II->getArgOperand(0)->getType());
1554 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(1), OpPtrTy);
1555 return new StoreInst(II->getArgOperand(0), Ptr, false, 1);
1556 }
Hal Finkel221f4672015-02-26 18:56:03 +00001557 case Intrinsic::ppc_qpx_qvlfs:
1558 // Turn PPC QPX qvlfs -> load if the pointer is known aligned.
Justin Bogner99798402016-08-05 01:06:44 +00001559 if (getOrEnforceKnownAlignment(II->getArgOperand(0), 16, DL, II, &AC,
1560 &DT) >= 16) {
Hal Finkelf0d68d72015-05-11 06:37:03 +00001561 Type *VTy = VectorType::get(Builder->getFloatTy(),
1562 II->getType()->getVectorNumElements());
Hal Finkel221f4672015-02-26 18:56:03 +00001563 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(0),
Hal Finkelf0d68d72015-05-11 06:37:03 +00001564 PointerType::getUnqual(VTy));
1565 Value *Load = Builder->CreateLoad(Ptr);
1566 return new FPExtInst(Load, II->getType());
Hal Finkel221f4672015-02-26 18:56:03 +00001567 }
1568 break;
1569 case Intrinsic::ppc_qpx_qvlfd:
1570 // Turn PPC QPX qvlfd -> load if the pointer is known aligned.
Justin Bogner99798402016-08-05 01:06:44 +00001571 if (getOrEnforceKnownAlignment(II->getArgOperand(0), 32, DL, II, &AC,
1572 &DT) >= 32) {
Hal Finkel221f4672015-02-26 18:56:03 +00001573 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(0),
1574 PointerType::getUnqual(II->getType()));
1575 return new LoadInst(Ptr);
1576 }
1577 break;
1578 case Intrinsic::ppc_qpx_qvstfs:
1579 // Turn PPC QPX qvstfs -> store if the pointer is known aligned.
Justin Bogner99798402016-08-05 01:06:44 +00001580 if (getOrEnforceKnownAlignment(II->getArgOperand(1), 16, DL, II, &AC,
1581 &DT) >= 16) {
Hal Finkelf0d68d72015-05-11 06:37:03 +00001582 Type *VTy = VectorType::get(Builder->getFloatTy(),
1583 II->getArgOperand(0)->getType()->getVectorNumElements());
1584 Value *TOp = Builder->CreateFPTrunc(II->getArgOperand(0), VTy);
1585 Type *OpPtrTy = PointerType::getUnqual(VTy);
Hal Finkel221f4672015-02-26 18:56:03 +00001586 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(1), OpPtrTy);
Hal Finkelf0d68d72015-05-11 06:37:03 +00001587 return new StoreInst(TOp, Ptr);
Hal Finkel221f4672015-02-26 18:56:03 +00001588 }
1589 break;
1590 case Intrinsic::ppc_qpx_qvstfd:
1591 // Turn PPC QPX qvstfd -> store if the pointer is known aligned.
Justin Bogner99798402016-08-05 01:06:44 +00001592 if (getOrEnforceKnownAlignment(II->getArgOperand(1), 32, DL, II, &AC,
1593 &DT) >= 32) {
Hal Finkel221f4672015-02-26 18:56:03 +00001594 Type *OpPtrTy =
1595 PointerType::getUnqual(II->getArgOperand(0)->getType());
1596 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(1), OpPtrTy);
1597 return new StoreInst(II->getArgOperand(0), Ptr);
1598 }
1599 break;
Simon Pilgrim20c607b2015-09-12 13:39:53 +00001600
Simon Pilgrim20c607b2015-09-12 13:39:53 +00001601 case Intrinsic::x86_vcvtph2ps_128:
1602 case Intrinsic::x86_vcvtph2ps_256: {
1603 auto Arg = II->getArgOperand(0);
1604 auto ArgType = cast<VectorType>(Arg->getType());
1605 auto RetType = cast<VectorType>(II->getType());
1606 unsigned ArgWidth = ArgType->getNumElements();
1607 unsigned RetWidth = RetType->getNumElements();
1608 assert(RetWidth <= ArgWidth && "Unexpected input/return vector widths");
1609 assert(ArgType->isIntOrIntVectorTy() &&
1610 ArgType->getScalarSizeInBits() == 16 &&
1611 "CVTPH2PS input type should be 16-bit integer vector");
1612 assert(RetType->getScalarType()->isFloatTy() &&
1613 "CVTPH2PS output type should be 32-bit float vector");
1614
1615 // Constant folding: Convert to generic half to single conversion.
Simon Pilgrim48ffca02015-09-12 14:00:17 +00001616 if (isa<ConstantAggregateZero>(Arg))
Sanjay Patel4b198802016-02-01 22:23:39 +00001617 return replaceInstUsesWith(*II, ConstantAggregateZero::get(RetType));
Simon Pilgrim20c607b2015-09-12 13:39:53 +00001618
Simon Pilgrim48ffca02015-09-12 14:00:17 +00001619 if (isa<ConstantDataVector>(Arg)) {
Simon Pilgrim20c607b2015-09-12 13:39:53 +00001620 auto VectorHalfAsShorts = Arg;
1621 if (RetWidth < ArgWidth) {
Craig Topper99d1eab2016-06-12 00:41:19 +00001622 SmallVector<uint32_t, 8> SubVecMask;
Simon Pilgrim20c607b2015-09-12 13:39:53 +00001623 for (unsigned i = 0; i != RetWidth; ++i)
1624 SubVecMask.push_back((int)i);
1625 VectorHalfAsShorts = Builder->CreateShuffleVector(
1626 Arg, UndefValue::get(ArgType), SubVecMask);
1627 }
1628
1629 auto VectorHalfType =
1630 VectorType::get(Type::getHalfTy(II->getContext()), RetWidth);
1631 auto VectorHalfs =
1632 Builder->CreateBitCast(VectorHalfAsShorts, VectorHalfType);
1633 auto VectorFloats = Builder->CreateFPExt(VectorHalfs, RetType);
Sanjay Patel4b198802016-02-01 22:23:39 +00001634 return replaceInstUsesWith(*II, VectorFloats);
Simon Pilgrim20c607b2015-09-12 13:39:53 +00001635 }
1636
1637 // We only use the lowest lanes of the argument.
Simon Pilgrim996725e2015-09-19 11:41:53 +00001638 if (Value *V = SimplifyDemandedVectorEltsLow(Arg, ArgWidth, RetWidth)) {
Simon Pilgrim20c607b2015-09-12 13:39:53 +00001639 II->setArgOperand(0, V);
1640 return II;
1641 }
1642 break;
1643 }
1644
Chandler Carruthcf414cf2011-01-10 07:19:37 +00001645 case Intrinsic::x86_sse_cvtss2si:
1646 case Intrinsic::x86_sse_cvtss2si64:
1647 case Intrinsic::x86_sse_cvttss2si:
1648 case Intrinsic::x86_sse_cvttss2si64:
1649 case Intrinsic::x86_sse2_cvtsd2si:
1650 case Intrinsic::x86_sse2_cvtsd2si64:
1651 case Intrinsic::x86_sse2_cvttsd2si:
1652 case Intrinsic::x86_sse2_cvttsd2si64: {
1653 // These intrinsics only demand the 0th element of their input vectors. If
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001654 // we can simplify the input based on that, do so now.
Simon Pilgrim996725e2015-09-19 11:41:53 +00001655 Value *Arg = II->getArgOperand(0);
1656 unsigned VWidth = Arg->getType()->getVectorNumElements();
1657 if (Value *V = SimplifyDemandedVectorEltsLow(Arg, VWidth, 1)) {
Gabor Greif5b1370e2010-06-28 16:50:57 +00001658 II->setArgOperand(0, V);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001659 return II;
1660 }
Simon Pilgrim18617d12015-08-05 08:18:00 +00001661 break;
1662 }
1663
Simon Pilgrim91e3ac82016-06-07 08:18:35 +00001664 case Intrinsic::x86_mmx_pmovmskb:
1665 case Intrinsic::x86_sse_movmsk_ps:
1666 case Intrinsic::x86_sse2_movmsk_pd:
1667 case Intrinsic::x86_sse2_pmovmskb_128:
1668 case Intrinsic::x86_avx_movmsk_pd_256:
1669 case Intrinsic::x86_avx_movmsk_ps_256:
1670 case Intrinsic::x86_avx2_pmovmskb: {
1671 if (Value *V = simplifyX86movmsk(*II, *Builder))
1672 return replaceInstUsesWith(*II, V);
1673 break;
1674 }
1675
Simon Pilgrim471efd22016-02-20 23:17:35 +00001676 case Intrinsic::x86_sse_comieq_ss:
1677 case Intrinsic::x86_sse_comige_ss:
1678 case Intrinsic::x86_sse_comigt_ss:
1679 case Intrinsic::x86_sse_comile_ss:
1680 case Intrinsic::x86_sse_comilt_ss:
1681 case Intrinsic::x86_sse_comineq_ss:
1682 case Intrinsic::x86_sse_ucomieq_ss:
1683 case Intrinsic::x86_sse_ucomige_ss:
1684 case Intrinsic::x86_sse_ucomigt_ss:
1685 case Intrinsic::x86_sse_ucomile_ss:
1686 case Intrinsic::x86_sse_ucomilt_ss:
1687 case Intrinsic::x86_sse_ucomineq_ss:
1688 case Intrinsic::x86_sse2_comieq_sd:
1689 case Intrinsic::x86_sse2_comige_sd:
1690 case Intrinsic::x86_sse2_comigt_sd:
1691 case Intrinsic::x86_sse2_comile_sd:
1692 case Intrinsic::x86_sse2_comilt_sd:
1693 case Intrinsic::x86_sse2_comineq_sd:
1694 case Intrinsic::x86_sse2_ucomieq_sd:
1695 case Intrinsic::x86_sse2_ucomige_sd:
1696 case Intrinsic::x86_sse2_ucomigt_sd:
1697 case Intrinsic::x86_sse2_ucomile_sd:
1698 case Intrinsic::x86_sse2_ucomilt_sd:
1699 case Intrinsic::x86_sse2_ucomineq_sd: {
1700 // These intrinsics only demand the 0th element of their input vectors. If
1701 // we can simplify the input based on that, do so now.
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00001702 bool MadeChange = false;
Simon Pilgrim471efd22016-02-20 23:17:35 +00001703 Value *Arg0 = II->getArgOperand(0);
1704 Value *Arg1 = II->getArgOperand(1);
1705 unsigned VWidth = Arg0->getType()->getVectorNumElements();
1706 if (Value *V = SimplifyDemandedVectorEltsLow(Arg0, VWidth, 1)) {
1707 II->setArgOperand(0, V);
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00001708 MadeChange = true;
Simon Pilgrim471efd22016-02-20 23:17:35 +00001709 }
1710 if (Value *V = SimplifyDemandedVectorEltsLow(Arg1, VWidth, 1)) {
1711 II->setArgOperand(1, V);
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00001712 MadeChange = true;
Simon Pilgrim471efd22016-02-20 23:17:35 +00001713 }
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00001714 if (MadeChange)
1715 return II;
Simon Pilgrim471efd22016-02-20 23:17:35 +00001716 break;
1717 }
1718
Simon Pilgrim424da162016-04-24 18:12:42 +00001719 case Intrinsic::x86_sse_add_ss:
1720 case Intrinsic::x86_sse_sub_ss:
1721 case Intrinsic::x86_sse_mul_ss:
1722 case Intrinsic::x86_sse_div_ss:
1723 case Intrinsic::x86_sse_min_ss:
1724 case Intrinsic::x86_sse_max_ss:
1725 case Intrinsic::x86_sse_cmp_ss:
1726 case Intrinsic::x86_sse2_add_sd:
1727 case Intrinsic::x86_sse2_sub_sd:
1728 case Intrinsic::x86_sse2_mul_sd:
1729 case Intrinsic::x86_sse2_div_sd:
1730 case Intrinsic::x86_sse2_min_sd:
1731 case Intrinsic::x86_sse2_max_sd:
1732 case Intrinsic::x86_sse2_cmp_sd: {
1733 // These intrinsics only demand the lowest element of the second input
1734 // vector.
1735 Value *Arg1 = II->getArgOperand(1);
1736 unsigned VWidth = Arg1->getType()->getVectorNumElements();
1737 if (Value *V = SimplifyDemandedVectorEltsLow(Arg1, VWidth, 1)) {
1738 II->setArgOperand(1, V);
1739 return II;
1740 }
1741 break;
1742 }
1743
1744 case Intrinsic::x86_sse41_round_ss:
1745 case Intrinsic::x86_sse41_round_sd: {
1746 // These intrinsics demand the upper elements of the first input vector and
1747 // the lowest element of the second input vector.
1748 bool MadeChange = false;
1749 Value *Arg0 = II->getArgOperand(0);
1750 Value *Arg1 = II->getArgOperand(1);
1751 unsigned VWidth = Arg0->getType()->getVectorNumElements();
1752 if (Value *V = SimplifyDemandedVectorEltsHigh(Arg0, VWidth, VWidth - 1)) {
1753 II->setArgOperand(0, V);
1754 MadeChange = true;
1755 }
1756 if (Value *V = SimplifyDemandedVectorEltsLow(Arg1, VWidth, 1)) {
1757 II->setArgOperand(1, V);
1758 MadeChange = true;
1759 }
1760 if (MadeChange)
1761 return II;
1762 break;
1763 }
1764
Simon Pilgrima3a72b42015-08-10 20:21:15 +00001765 // Constant fold ashr( <A x Bi>, Ci ).
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00001766 // Constant fold lshr( <A x Bi>, Ci ).
1767 // Constant fold shl( <A x Bi>, Ci ).
Simon Pilgrima3a72b42015-08-10 20:21:15 +00001768 case Intrinsic::x86_sse2_psrai_d:
1769 case Intrinsic::x86_sse2_psrai_w:
Simon Pilgrima3a72b42015-08-10 20:21:15 +00001770 case Intrinsic::x86_avx2_psrai_d:
1771 case Intrinsic::x86_avx2_psrai_w:
Simon Pilgrim18617d12015-08-05 08:18:00 +00001772 case Intrinsic::x86_sse2_psrli_d:
1773 case Intrinsic::x86_sse2_psrli_q:
1774 case Intrinsic::x86_sse2_psrli_w:
Simon Pilgrim18617d12015-08-05 08:18:00 +00001775 case Intrinsic::x86_avx2_psrli_d:
1776 case Intrinsic::x86_avx2_psrli_q:
1777 case Intrinsic::x86_avx2_psrli_w:
Michael J. Spencerdee4b2c2014-04-24 00:58:18 +00001778 case Intrinsic::x86_sse2_pslli_d:
1779 case Intrinsic::x86_sse2_pslli_q:
1780 case Intrinsic::x86_sse2_pslli_w:
Simon Pilgrim18617d12015-08-05 08:18:00 +00001781 case Intrinsic::x86_avx2_pslli_d:
1782 case Intrinsic::x86_avx2_pslli_q:
1783 case Intrinsic::x86_avx2_pslli_w:
Sanjay Patel6038d3e2016-01-29 23:27:03 +00001784 if (Value *V = simplifyX86immShift(*II, *Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00001785 return replaceInstUsesWith(*II, V);
Simon Pilgrim18617d12015-08-05 08:18:00 +00001786 break;
1787
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00001788 case Intrinsic::x86_sse2_psra_d:
1789 case Intrinsic::x86_sse2_psra_w:
1790 case Intrinsic::x86_avx2_psra_d:
1791 case Intrinsic::x86_avx2_psra_w:
1792 case Intrinsic::x86_sse2_psrl_d:
1793 case Intrinsic::x86_sse2_psrl_q:
1794 case Intrinsic::x86_sse2_psrl_w:
1795 case Intrinsic::x86_avx2_psrl_d:
1796 case Intrinsic::x86_avx2_psrl_q:
1797 case Intrinsic::x86_avx2_psrl_w:
1798 case Intrinsic::x86_sse2_psll_d:
1799 case Intrinsic::x86_sse2_psll_q:
1800 case Intrinsic::x86_sse2_psll_w:
1801 case Intrinsic::x86_avx2_psll_d:
1802 case Intrinsic::x86_avx2_psll_q:
1803 case Intrinsic::x86_avx2_psll_w: {
Sanjay Patel6038d3e2016-01-29 23:27:03 +00001804 if (Value *V = simplifyX86immShift(*II, *Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00001805 return replaceInstUsesWith(*II, V);
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00001806
1807 // SSE2/AVX2 uses only the first 64-bits of the 128-bit vector
1808 // operand to compute the shift amount.
Simon Pilgrim996725e2015-09-19 11:41:53 +00001809 Value *Arg1 = II->getArgOperand(1);
1810 assert(Arg1->getType()->getPrimitiveSizeInBits() == 128 &&
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00001811 "Unexpected packed shift size");
Simon Pilgrim996725e2015-09-19 11:41:53 +00001812 unsigned VWidth = Arg1->getType()->getVectorNumElements();
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00001813
Simon Pilgrim996725e2015-09-19 11:41:53 +00001814 if (Value *V = SimplifyDemandedVectorEltsLow(Arg1, VWidth, VWidth / 2)) {
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00001815 II->setArgOperand(1, V);
1816 return II;
1817 }
1818 break;
1819 }
1820
Simon Pilgrimdb9893f2016-06-07 10:27:15 +00001821 case Intrinsic::x86_avx2_psllv_d:
1822 case Intrinsic::x86_avx2_psllv_d_256:
1823 case Intrinsic::x86_avx2_psllv_q:
1824 case Intrinsic::x86_avx2_psllv_q_256:
1825 case Intrinsic::x86_avx2_psrav_d:
1826 case Intrinsic::x86_avx2_psrav_d_256:
1827 case Intrinsic::x86_avx2_psrlv_d:
1828 case Intrinsic::x86_avx2_psrlv_d_256:
1829 case Intrinsic::x86_avx2_psrlv_q:
1830 case Intrinsic::x86_avx2_psrlv_q_256:
1831 if (Value *V = simplifyX86varShift(*II, *Builder))
1832 return replaceInstUsesWith(*II, V);
1833 break;
1834
Sanjay Patelc86867c2015-04-16 17:52:13 +00001835 case Intrinsic::x86_sse41_insertps:
Sanjay Patel6038d3e2016-01-29 23:27:03 +00001836 if (Value *V = simplifyX86insertps(*II, *Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00001837 return replaceInstUsesWith(*II, V);
Sanjay Patelc86867c2015-04-16 17:52:13 +00001838 break;
Simon Pilgrim54fcd622015-07-25 20:41:00 +00001839
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001840 case Intrinsic::x86_sse4a_extrq: {
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001841 Value *Op0 = II->getArgOperand(0);
1842 Value *Op1 = II->getArgOperand(1);
1843 unsigned VWidth0 = Op0->getType()->getVectorNumElements();
1844 unsigned VWidth1 = Op1->getType()->getVectorNumElements();
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00001845 assert(Op0->getType()->getPrimitiveSizeInBits() == 128 &&
1846 Op1->getType()->getPrimitiveSizeInBits() == 128 && VWidth0 == 2 &&
1847 VWidth1 == 16 && "Unexpected operand sizes");
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001848
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00001849 // See if we're dealing with constant values.
1850 Constant *C1 = dyn_cast<Constant>(Op1);
1851 ConstantInt *CILength =
1852 C1 ? dyn_cast<ConstantInt>(C1->getAggregateElement((unsigned)0))
1853 : nullptr;
1854 ConstantInt *CIIndex =
1855 C1 ? dyn_cast<ConstantInt>(C1->getAggregateElement((unsigned)1))
1856 : nullptr;
1857
1858 // Attempt to simplify to a constant, shuffle vector or EXTRQI call.
Sanjay Patel6038d3e2016-01-29 23:27:03 +00001859 if (Value *V = simplifyX86extrq(*II, Op0, CILength, CIIndex, *Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00001860 return replaceInstUsesWith(*II, V);
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00001861
1862 // EXTRQ only uses the lowest 64-bits of the first 128-bit vector
1863 // operands and the lowest 16-bits of the second.
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00001864 bool MadeChange = false;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001865 if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth0, 1)) {
1866 II->setArgOperand(0, V);
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00001867 MadeChange = true;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001868 }
1869 if (Value *V = SimplifyDemandedVectorEltsLow(Op1, VWidth1, 2)) {
1870 II->setArgOperand(1, V);
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00001871 MadeChange = true;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001872 }
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00001873 if (MadeChange)
1874 return II;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001875 break;
1876 }
1877
1878 case Intrinsic::x86_sse4a_extrqi: {
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00001879 // EXTRQI: Extract Length bits starting from Index. Zero pad the remaining
1880 // bits of the lower 64-bits. The upper 64-bits are undefined.
1881 Value *Op0 = II->getArgOperand(0);
1882 unsigned VWidth = Op0->getType()->getVectorNumElements();
1883 assert(Op0->getType()->getPrimitiveSizeInBits() == 128 && VWidth == 2 &&
1884 "Unexpected operand size");
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001885
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00001886 // See if we're dealing with constant values.
1887 ConstantInt *CILength = dyn_cast<ConstantInt>(II->getArgOperand(1));
1888 ConstantInt *CIIndex = dyn_cast<ConstantInt>(II->getArgOperand(2));
1889
1890 // Attempt to simplify to a constant or shuffle vector.
Sanjay Patel6038d3e2016-01-29 23:27:03 +00001891 if (Value *V = simplifyX86extrq(*II, Op0, CILength, CIIndex, *Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00001892 return replaceInstUsesWith(*II, V);
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00001893
1894 // EXTRQI only uses the lowest 64-bits of the first 128-bit vector
1895 // operand.
1896 if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth, 1)) {
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001897 II->setArgOperand(0, V);
1898 return II;
1899 }
1900 break;
1901 }
1902
1903 case Intrinsic::x86_sse4a_insertq: {
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00001904 Value *Op0 = II->getArgOperand(0);
1905 Value *Op1 = II->getArgOperand(1);
1906 unsigned VWidth = Op0->getType()->getVectorNumElements();
1907 assert(Op0->getType()->getPrimitiveSizeInBits() == 128 &&
1908 Op1->getType()->getPrimitiveSizeInBits() == 128 && VWidth == 2 &&
1909 Op1->getType()->getVectorNumElements() == 2 &&
1910 "Unexpected operand size");
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001911
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00001912 // See if we're dealing with constant values.
1913 Constant *C1 = dyn_cast<Constant>(Op1);
1914 ConstantInt *CI11 =
1915 C1 ? dyn_cast<ConstantInt>(C1->getAggregateElement((unsigned)1))
1916 : nullptr;
1917
1918 // Attempt to simplify to a constant, shuffle vector or INSERTQI call.
1919 if (CI11) {
Benjamin Kramer46e38f32016-06-08 10:01:20 +00001920 const APInt &V11 = CI11->getValue();
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00001921 APInt Len = V11.zextOrTrunc(6);
1922 APInt Idx = V11.lshr(8).zextOrTrunc(6);
Sanjay Patel6038d3e2016-01-29 23:27:03 +00001923 if (Value *V = simplifyX86insertq(*II, Op0, Op1, Len, Idx, *Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00001924 return replaceInstUsesWith(*II, V);
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00001925 }
1926
1927 // INSERTQ only uses the lowest 64-bits of the first 128-bit vector
1928 // operand.
1929 if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth, 1)) {
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001930 II->setArgOperand(0, V);
1931 return II;
1932 }
1933 break;
1934 }
1935
Filipe Cabecinhas1a805952014-04-24 00:38:14 +00001936 case Intrinsic::x86_sse4a_insertqi: {
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00001937 // INSERTQI: Extract lowest Length bits from lower half of second source and
1938 // insert over first source starting at Index bit. The upper 64-bits are
1939 // undefined.
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001940 Value *Op0 = II->getArgOperand(0);
1941 Value *Op1 = II->getArgOperand(1);
1942 unsigned VWidth0 = Op0->getType()->getVectorNumElements();
1943 unsigned VWidth1 = Op1->getType()->getVectorNumElements();
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00001944 assert(Op0->getType()->getPrimitiveSizeInBits() == 128 &&
1945 Op1->getType()->getPrimitiveSizeInBits() == 128 && VWidth0 == 2 &&
1946 VWidth1 == 2 && "Unexpected operand sizes");
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001947
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00001948 // See if we're dealing with constant values.
1949 ConstantInt *CILength = dyn_cast<ConstantInt>(II->getArgOperand(2));
1950 ConstantInt *CIIndex = dyn_cast<ConstantInt>(II->getArgOperand(3));
1951
1952 // Attempt to simplify to a constant or shuffle vector.
1953 if (CILength && CIIndex) {
1954 APInt Len = CILength->getValue().zextOrTrunc(6);
1955 APInt Idx = CIIndex->getValue().zextOrTrunc(6);
Sanjay Patel6038d3e2016-01-29 23:27:03 +00001956 if (Value *V = simplifyX86insertq(*II, Op0, Op1, Len, Idx, *Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00001957 return replaceInstUsesWith(*II, V);
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00001958 }
1959
1960 // INSERTQI only uses the lowest 64-bits of the first two 128-bit vector
1961 // operands.
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00001962 bool MadeChange = false;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001963 if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth0, 1)) {
1964 II->setArgOperand(0, V);
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00001965 MadeChange = true;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001966 }
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001967 if (Value *V = SimplifyDemandedVectorEltsLow(Op1, VWidth1, 1)) {
1968 II->setArgOperand(1, V);
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00001969 MadeChange = true;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001970 }
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00001971 if (MadeChange)
1972 return II;
Filipe Cabecinhas1a805952014-04-24 00:38:14 +00001973 break;
1974 }
1975
Filipe Cabecinhas82ac07c2014-05-27 03:42:20 +00001976 case Intrinsic::x86_sse41_pblendvb:
1977 case Intrinsic::x86_sse41_blendvps:
1978 case Intrinsic::x86_sse41_blendvpd:
1979 case Intrinsic::x86_avx_blendv_ps_256:
1980 case Intrinsic::x86_avx_blendv_pd_256:
1981 case Intrinsic::x86_avx2_pblendvb: {
1982 // Convert blendv* to vector selects if the mask is constant.
1983 // This optimization is convoluted because the intrinsic is defined as
1984 // getting a vector of floats or doubles for the ps and pd versions.
1985 // FIXME: That should be changed.
Simon Pilgrim8c049d52015-08-12 08:08:56 +00001986
1987 Value *Op0 = II->getArgOperand(0);
1988 Value *Op1 = II->getArgOperand(1);
Filipe Cabecinhas82ac07c2014-05-27 03:42:20 +00001989 Value *Mask = II->getArgOperand(2);
Simon Pilgrim8c049d52015-08-12 08:08:56 +00001990
1991 // fold (blend A, A, Mask) -> A
1992 if (Op0 == Op1)
Sanjay Patel4b198802016-02-01 22:23:39 +00001993 return replaceInstUsesWith(CI, Op0);
Simon Pilgrim8c049d52015-08-12 08:08:56 +00001994
1995 // Zero Mask - select 1st argument.
Simon Pilgrim93f59f52015-08-12 08:23:36 +00001996 if (isa<ConstantAggregateZero>(Mask))
Sanjay Patel4b198802016-02-01 22:23:39 +00001997 return replaceInstUsesWith(CI, Op0);
Simon Pilgrim8c049d52015-08-12 08:08:56 +00001998
1999 // Constant Mask - select 1st/2nd argument lane based on top bit of mask.
Sanjay Patel368ac5d2016-02-21 17:29:33 +00002000 if (auto *ConstantMask = dyn_cast<ConstantDataVector>(Mask)) {
2001 Constant *NewSelector = getNegativeIsTrueBoolVec(ConstantMask);
Simon Pilgrim8c049d52015-08-12 08:08:56 +00002002 return SelectInst::Create(NewSelector, Op1, Op0, "blendv");
Filipe Cabecinhas82ac07c2014-05-27 03:42:20 +00002003 }
Simon Pilgrim8c049d52015-08-12 08:08:56 +00002004 break;
Filipe Cabecinhas82ac07c2014-05-27 03:42:20 +00002005 }
2006
Andrea Di Biagio0594e2a2015-09-30 16:44:39 +00002007 case Intrinsic::x86_ssse3_pshuf_b_128:
Simon Pilgrimc0c56e72016-04-24 17:00:34 +00002008 case Intrinsic::x86_avx2_pshuf_b:
2009 if (Value *V = simplifyX86pshufb(*II, *Builder))
2010 return replaceInstUsesWith(*II, V);
2011 break;
Andrea Di Biagio0594e2a2015-09-30 16:44:39 +00002012
Rafael Espindolabad3f772014-04-21 22:06:04 +00002013 case Intrinsic::x86_avx_vpermilvar_ps:
2014 case Intrinsic::x86_avx_vpermilvar_ps_256:
2015 case Intrinsic::x86_avx_vpermilvar_pd:
Simon Pilgrim2f6097d2016-04-24 17:23:46 +00002016 case Intrinsic::x86_avx_vpermilvar_pd_256:
2017 if (Value *V = simplifyX86vpermilvar(*II, *Builder))
2018 return replaceInstUsesWith(*II, V);
2019 break;
Rafael Espindolabad3f772014-04-21 22:06:04 +00002020
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +00002021 case Intrinsic::x86_avx2_permd:
2022 case Intrinsic::x86_avx2_permps:
2023 if (Value *V = simplifyX86vpermv(*II, *Builder))
2024 return replaceInstUsesWith(*II, V);
2025 break;
2026
Sanjay Patelccf5f242015-03-20 21:47:56 +00002027 case Intrinsic::x86_avx_vperm2f128_pd_256:
2028 case Intrinsic::x86_avx_vperm2f128_ps_256:
2029 case Intrinsic::x86_avx_vperm2f128_si_256:
Sanjay Patele304bea2015-03-24 22:39:29 +00002030 case Intrinsic::x86_avx2_vperm2i128:
Sanjay Patel6038d3e2016-01-29 23:27:03 +00002031 if (Value *V = simplifyX86vperm2(*II, *Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00002032 return replaceInstUsesWith(*II, V);
Sanjay Patelccf5f242015-03-20 21:47:56 +00002033 break;
2034
Sanjay Patel98a71502016-02-29 23:16:48 +00002035 case Intrinsic::x86_avx_maskload_ps:
Sanjay Patel6f2c01f2016-02-29 23:59:00 +00002036 case Intrinsic::x86_avx_maskload_pd:
2037 case Intrinsic::x86_avx_maskload_ps_256:
2038 case Intrinsic::x86_avx_maskload_pd_256:
2039 case Intrinsic::x86_avx2_maskload_d:
2040 case Intrinsic::x86_avx2_maskload_q:
2041 case Intrinsic::x86_avx2_maskload_d_256:
2042 case Intrinsic::x86_avx2_maskload_q_256:
Sanjay Patel98a71502016-02-29 23:16:48 +00002043 if (Instruction *I = simplifyX86MaskedLoad(*II, *this))
2044 return I;
2045 break;
2046
Sanjay Patelc4acbae2016-03-12 15:16:59 +00002047 case Intrinsic::x86_sse2_maskmov_dqu:
Sanjay Patel1ace9932016-02-26 21:04:14 +00002048 case Intrinsic::x86_avx_maskstore_ps:
2049 case Intrinsic::x86_avx_maskstore_pd:
2050 case Intrinsic::x86_avx_maskstore_ps_256:
2051 case Intrinsic::x86_avx_maskstore_pd_256:
Sanjay Patelfc7e7eb2016-02-26 21:51:44 +00002052 case Intrinsic::x86_avx2_maskstore_d:
2053 case Intrinsic::x86_avx2_maskstore_q:
2054 case Intrinsic::x86_avx2_maskstore_d_256:
2055 case Intrinsic::x86_avx2_maskstore_q_256:
Sanjay Patel1ace9932016-02-26 21:04:14 +00002056 if (simplifyX86MaskedStore(*II, *this))
2057 return nullptr;
2058 break;
2059
Simon Pilgrim1d1c56e22015-10-11 14:38:34 +00002060 case Intrinsic::x86_xop_vpcomb:
2061 case Intrinsic::x86_xop_vpcomd:
2062 case Intrinsic::x86_xop_vpcomq:
2063 case Intrinsic::x86_xop_vpcomw:
Sanjay Patel6038d3e2016-01-29 23:27:03 +00002064 if (Value *V = simplifyX86vpcom(*II, *Builder, true))
Sanjay Patel4b198802016-02-01 22:23:39 +00002065 return replaceInstUsesWith(*II, V);
Simon Pilgrim1d1c56e22015-10-11 14:38:34 +00002066 break;
2067
2068 case Intrinsic::x86_xop_vpcomub:
2069 case Intrinsic::x86_xop_vpcomud:
2070 case Intrinsic::x86_xop_vpcomuq:
2071 case Intrinsic::x86_xop_vpcomuw:
Sanjay Patel6038d3e2016-01-29 23:27:03 +00002072 if (Value *V = simplifyX86vpcom(*II, *Builder, false))
Sanjay Patel4b198802016-02-01 22:23:39 +00002073 return replaceInstUsesWith(*II, V);
Simon Pilgrim1d1c56e22015-10-11 14:38:34 +00002074 break;
2075
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002076 case Intrinsic::ppc_altivec_vperm:
2077 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
Bill Schmidta1184632014-06-05 19:46:04 +00002078 // Note that ppc_altivec_vperm has a big-endian bias, so when creating
2079 // a vectorshuffle for little endian, we must undo the transformation
2080 // performed on vec_perm in altivec.h. That is, we must complement
2081 // the permutation mask with respect to 31 and reverse the order of
2082 // V1 and V2.
Chris Lattner0256be92012-01-27 03:08:05 +00002083 if (Constant *Mask = dyn_cast<Constant>(II->getArgOperand(2))) {
2084 assert(Mask->getType()->getVectorNumElements() == 16 &&
2085 "Bad type for intrinsic!");
Jim Grosbach7815f562012-02-03 00:07:04 +00002086
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002087 // Check that all of the elements are integer constants or undefs.
2088 bool AllEltsOk = true;
2089 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0256be92012-01-27 03:08:05 +00002090 Constant *Elt = Mask->getAggregateElement(i);
Craig Topperf40110f2014-04-25 05:29:35 +00002091 if (!Elt || !(isa<ConstantInt>(Elt) || isa<UndefValue>(Elt))) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002092 AllEltsOk = false;
2093 break;
2094 }
2095 }
Jim Grosbach7815f562012-02-03 00:07:04 +00002096
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002097 if (AllEltsOk) {
2098 // Cast the input vectors to byte vectors.
Gabor Greif3e44ea12010-07-22 10:37:47 +00002099 Value *Op0 = Builder->CreateBitCast(II->getArgOperand(0),
2100 Mask->getType());
2101 Value *Op1 = Builder->CreateBitCast(II->getArgOperand(1),
2102 Mask->getType());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002103 Value *Result = UndefValue::get(Op0->getType());
Jim Grosbach7815f562012-02-03 00:07:04 +00002104
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002105 // Only extract each element once.
2106 Value *ExtractedElts[32];
2107 memset(ExtractedElts, 0, sizeof(ExtractedElts));
Jim Grosbach7815f562012-02-03 00:07:04 +00002108
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002109 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0256be92012-01-27 03:08:05 +00002110 if (isa<UndefValue>(Mask->getAggregateElement(i)))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002111 continue;
Jim Grosbach7815f562012-02-03 00:07:04 +00002112 unsigned Idx =
Chris Lattner0256be92012-01-27 03:08:05 +00002113 cast<ConstantInt>(Mask->getAggregateElement(i))->getZExtValue();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002114 Idx &= 31; // Match the hardware behavior.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002115 if (DL.isLittleEndian())
Bill Schmidta1184632014-06-05 19:46:04 +00002116 Idx = 31 - Idx;
Jim Grosbach7815f562012-02-03 00:07:04 +00002117
Craig Topperf40110f2014-04-25 05:29:35 +00002118 if (!ExtractedElts[Idx]) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002119 Value *Op0ToUse = (DL.isLittleEndian()) ? Op1 : Op0;
2120 Value *Op1ToUse = (DL.isLittleEndian()) ? Op0 : Op1;
Jim Grosbach7815f562012-02-03 00:07:04 +00002121 ExtractedElts[Idx] =
Bill Schmidta1184632014-06-05 19:46:04 +00002122 Builder->CreateExtractElement(Idx < 16 ? Op0ToUse : Op1ToUse,
Benjamin Kramer547b6c52011-09-27 20:39:19 +00002123 Builder->getInt32(Idx&15));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002124 }
Jim Grosbach7815f562012-02-03 00:07:04 +00002125
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002126 // Insert this value into the result vector.
2127 Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
Benjamin Kramer547b6c52011-09-27 20:39:19 +00002128 Builder->getInt32(i));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002129 }
2130 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
2131 }
2132 }
2133 break;
2134
Bob Wilsona4e231c2010-10-22 21:41:48 +00002135 case Intrinsic::arm_neon_vld1:
2136 case Intrinsic::arm_neon_vld2:
2137 case Intrinsic::arm_neon_vld3:
2138 case Intrinsic::arm_neon_vld4:
2139 case Intrinsic::arm_neon_vld2lane:
2140 case Intrinsic::arm_neon_vld3lane:
2141 case Intrinsic::arm_neon_vld4lane:
2142 case Intrinsic::arm_neon_vst1:
2143 case Intrinsic::arm_neon_vst2:
2144 case Intrinsic::arm_neon_vst3:
2145 case Intrinsic::arm_neon_vst4:
2146 case Intrinsic::arm_neon_vst2lane:
2147 case Intrinsic::arm_neon_vst3lane:
2148 case Intrinsic::arm_neon_vst4lane: {
Justin Bogner99798402016-08-05 01:06:44 +00002149 unsigned MemAlign =
2150 getKnownAlignment(II->getArgOperand(0), DL, II, &AC, &DT);
Bob Wilsona4e231c2010-10-22 21:41:48 +00002151 unsigned AlignArg = II->getNumArgOperands() - 1;
2152 ConstantInt *IntrAlign = dyn_cast<ConstantInt>(II->getArgOperand(AlignArg));
2153 if (IntrAlign && IntrAlign->getZExtValue() < MemAlign) {
2154 II->setArgOperand(AlignArg,
2155 ConstantInt::get(Type::getInt32Ty(II->getContext()),
2156 MemAlign, false));
2157 return II;
2158 }
2159 break;
2160 }
2161
Lang Hames3a90fab2012-05-01 00:20:38 +00002162 case Intrinsic::arm_neon_vmulls:
Tim Northover00ed9962014-03-29 10:18:08 +00002163 case Intrinsic::arm_neon_vmullu:
Tim Northover3b0846e2014-05-24 12:50:23 +00002164 case Intrinsic::aarch64_neon_smull:
2165 case Intrinsic::aarch64_neon_umull: {
Lang Hames3a90fab2012-05-01 00:20:38 +00002166 Value *Arg0 = II->getArgOperand(0);
2167 Value *Arg1 = II->getArgOperand(1);
2168
2169 // Handle mul by zero first:
2170 if (isa<ConstantAggregateZero>(Arg0) || isa<ConstantAggregateZero>(Arg1)) {
Sanjay Patel4b198802016-02-01 22:23:39 +00002171 return replaceInstUsesWith(CI, ConstantAggregateZero::get(II->getType()));
Lang Hames3a90fab2012-05-01 00:20:38 +00002172 }
2173
2174 // Check for constant LHS & RHS - in this case we just simplify.
Tim Northover00ed9962014-03-29 10:18:08 +00002175 bool Zext = (II->getIntrinsicID() == Intrinsic::arm_neon_vmullu ||
Tim Northover3b0846e2014-05-24 12:50:23 +00002176 II->getIntrinsicID() == Intrinsic::aarch64_neon_umull);
Lang Hames3a90fab2012-05-01 00:20:38 +00002177 VectorType *NewVT = cast<VectorType>(II->getType());
Benjamin Kramer92040952014-02-13 18:23:24 +00002178 if (Constant *CV0 = dyn_cast<Constant>(Arg0)) {
2179 if (Constant *CV1 = dyn_cast<Constant>(Arg1)) {
2180 CV0 = ConstantExpr::getIntegerCast(CV0, NewVT, /*isSigned=*/!Zext);
2181 CV1 = ConstantExpr::getIntegerCast(CV1, NewVT, /*isSigned=*/!Zext);
2182
Sanjay Patel4b198802016-02-01 22:23:39 +00002183 return replaceInstUsesWith(CI, ConstantExpr::getMul(CV0, CV1));
Lang Hames3a90fab2012-05-01 00:20:38 +00002184 }
2185
Alp Tokercb402912014-01-24 17:20:08 +00002186 // Couldn't simplify - canonicalize constant to the RHS.
Lang Hames3a90fab2012-05-01 00:20:38 +00002187 std::swap(Arg0, Arg1);
2188 }
2189
2190 // Handle mul by one:
Benjamin Kramer92040952014-02-13 18:23:24 +00002191 if (Constant *CV1 = dyn_cast<Constant>(Arg1))
Lang Hames3a90fab2012-05-01 00:20:38 +00002192 if (ConstantInt *Splat =
Benjamin Kramer92040952014-02-13 18:23:24 +00002193 dyn_cast_or_null<ConstantInt>(CV1->getSplatValue()))
2194 if (Splat->isOne())
2195 return CastInst::CreateIntegerCast(Arg0, II->getType(),
2196 /*isSigned=*/!Zext);
Lang Hames3a90fab2012-05-01 00:20:38 +00002197
2198 break;
2199 }
2200
Matt Arsenaultbef34e22016-01-22 21:30:34 +00002201 case Intrinsic::amdgcn_rcp: {
Matt Arsenaulta0050b02014-06-19 01:19:19 +00002202 if (const ConstantFP *C = dyn_cast<ConstantFP>(II->getArgOperand(0))) {
2203 const APFloat &ArgVal = C->getValueAPF();
2204 APFloat Val(ArgVal.getSemantics(), 1.0);
2205 APFloat::opStatus Status = Val.divide(ArgVal,
2206 APFloat::rmNearestTiesToEven);
2207 // Only do this if it was exact and therefore not dependent on the
2208 // rounding mode.
2209 if (Status == APFloat::opOK)
Sanjay Patel4b198802016-02-01 22:23:39 +00002210 return replaceInstUsesWith(CI, ConstantFP::get(II->getContext(), Val));
Matt Arsenaulta0050b02014-06-19 01:19:19 +00002211 }
2212
2213 break;
2214 }
Matt Arsenault2fe4fbc2016-03-30 22:28:52 +00002215 case Intrinsic::amdgcn_frexp_mant:
2216 case Intrinsic::amdgcn_frexp_exp: {
Matt Arsenault5cd4f8f2016-03-30 22:28:26 +00002217 Value *Src = II->getArgOperand(0);
2218 if (const ConstantFP *C = dyn_cast<ConstantFP>(Src)) {
2219 int Exp;
2220 APFloat Significand = frexp(C->getValueAPF(), Exp,
2221 APFloat::rmNearestTiesToEven);
2222
Matt Arsenault2fe4fbc2016-03-30 22:28:52 +00002223 if (II->getIntrinsicID() == Intrinsic::amdgcn_frexp_mant) {
2224 return replaceInstUsesWith(CI, ConstantFP::get(II->getContext(),
2225 Significand));
2226 }
2227
2228 // Match instruction special case behavior.
2229 if (Exp == APFloat::IEK_NaN || Exp == APFloat::IEK_Inf)
2230 Exp = 0;
2231
2232 return replaceInstUsesWith(CI, ConstantInt::get(II->getType(), Exp));
2233 }
2234
2235 if (isa<UndefValue>(Src))
2236 return replaceInstUsesWith(CI, UndefValue::get(II->getType()));
Matt Arsenault5cd4f8f2016-03-30 22:28:26 +00002237
2238 break;
2239 }
Matt Arsenault46a03822016-09-03 07:06:58 +00002240 case Intrinsic::amdgcn_class: {
2241 enum {
2242 S_NAN = 1 << 0, // Signaling NaN
2243 Q_NAN = 1 << 1, // Quiet NaN
2244 N_INFINITY = 1 << 2, // Negative infinity
2245 N_NORMAL = 1 << 3, // Negative normal
2246 N_SUBNORMAL = 1 << 4, // Negative subnormal
2247 N_ZERO = 1 << 5, // Negative zero
2248 P_ZERO = 1 << 6, // Positive zero
2249 P_SUBNORMAL = 1 << 7, // Positive subnormal
2250 P_NORMAL = 1 << 8, // Positive normal
2251 P_INFINITY = 1 << 9 // Positive infinity
2252 };
2253
2254 const uint32_t FullMask = S_NAN | Q_NAN | N_INFINITY | N_NORMAL |
2255 N_SUBNORMAL | N_ZERO | P_ZERO | P_SUBNORMAL | P_NORMAL | P_INFINITY;
2256
2257 Value *Src0 = II->getArgOperand(0);
2258 Value *Src1 = II->getArgOperand(1);
2259 const ConstantInt *CMask = dyn_cast<ConstantInt>(Src1);
2260 if (!CMask) {
2261 if (isa<UndefValue>(Src0))
2262 return replaceInstUsesWith(*II, UndefValue::get(II->getType()));
2263
2264 if (isa<UndefValue>(Src1))
2265 return replaceInstUsesWith(*II, ConstantInt::get(II->getType(), false));
2266 break;
2267 }
2268
2269 uint32_t Mask = CMask->getZExtValue();
2270
2271 // If all tests are made, it doesn't matter what the value is.
2272 if ((Mask & FullMask) == FullMask)
2273 return replaceInstUsesWith(*II, ConstantInt::get(II->getType(), true));
2274
2275 if ((Mask & FullMask) == 0)
2276 return replaceInstUsesWith(*II, ConstantInt::get(II->getType(), false));
2277
2278 if (Mask == (S_NAN | Q_NAN)) {
2279 // Equivalent of isnan. Replace with standard fcmp.
2280 Value *FCmp = Builder->CreateFCmpUNO(Src0, Src0);
2281 FCmp->takeName(II);
2282 return replaceInstUsesWith(*II, FCmp);
2283 }
2284
2285 const ConstantFP *CVal = dyn_cast<ConstantFP>(Src0);
2286 if (!CVal) {
2287 if (isa<UndefValue>(Src0))
2288 return replaceInstUsesWith(*II, UndefValue::get(II->getType()));
2289
2290 // Clamp mask to used bits
2291 if ((Mask & FullMask) != Mask) {
2292 CallInst *NewCall = Builder->CreateCall(II->getCalledFunction(),
2293 { Src0, ConstantInt::get(Src1->getType(), Mask & FullMask) }
2294 );
2295
2296 NewCall->takeName(II);
2297 return replaceInstUsesWith(*II, NewCall);
2298 }
2299
2300 break;
2301 }
2302
2303 const APFloat &Val = CVal->getValueAPF();
2304
2305 bool Result =
2306 ((Mask & S_NAN) && Val.isNaN() && Val.isSignaling()) ||
2307 ((Mask & Q_NAN) && Val.isNaN() && !Val.isSignaling()) ||
2308 ((Mask & N_INFINITY) && Val.isInfinity() && Val.isNegative()) ||
2309 ((Mask & N_NORMAL) && Val.isNormal() && Val.isNegative()) ||
2310 ((Mask & N_SUBNORMAL) && Val.isDenormal() && Val.isNegative()) ||
2311 ((Mask & N_ZERO) && Val.isZero() && Val.isNegative()) ||
2312 ((Mask & P_ZERO) && Val.isZero() && !Val.isNegative()) ||
2313 ((Mask & P_SUBNORMAL) && Val.isDenormal() && !Val.isNegative()) ||
2314 ((Mask & P_NORMAL) && Val.isNormal() && !Val.isNegative()) ||
2315 ((Mask & P_INFINITY) && Val.isInfinity() && !Val.isNegative());
2316
2317 return replaceInstUsesWith(*II, ConstantInt::get(II->getType(), Result));
2318 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002319 case Intrinsic::stackrestore: {
2320 // If the save is right next to the restore, remove the restore. This can
2321 // happen when variable allocas are DCE'd.
Gabor Greif589a0b92010-06-24 12:58:35 +00002322 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getArgOperand(0))) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002323 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00002324 if (&*++SS->getIterator() == II)
Sanjay Patel4b198802016-02-01 22:23:39 +00002325 return eraseInstFromFunction(CI);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002326 }
2327 }
Jim Grosbach7815f562012-02-03 00:07:04 +00002328
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002329 // Scan down this block to see if there is another stack restore in the
2330 // same block without an intervening call/alloca.
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00002331 BasicBlock::iterator BI(II);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002332 TerminatorInst *TI = II->getParent()->getTerminator();
2333 bool CannotRemove = false;
2334 for (++BI; &*BI != TI; ++BI) {
Nuno Lopes55fff832012-06-21 15:45:28 +00002335 if (isa<AllocaInst>(BI)) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002336 CannotRemove = true;
2337 break;
2338 }
2339 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
2340 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
2341 // If there is a stackrestore below this one, remove this one.
2342 if (II->getIntrinsicID() == Intrinsic::stackrestore)
Sanjay Patel4b198802016-02-01 22:23:39 +00002343 return eraseInstFromFunction(CI);
Reid Kleckner892ae2e2016-02-27 00:53:54 +00002344
2345 // Bail if we cross over an intrinsic with side effects, such as
2346 // llvm.stacksave, llvm.read_register, or llvm.setjmp.
2347 if (II->mayHaveSideEffects()) {
2348 CannotRemove = true;
2349 break;
2350 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002351 } else {
2352 // If we found a non-intrinsic call, we can't remove the stack
2353 // restore.
2354 CannotRemove = true;
2355 break;
2356 }
2357 }
2358 }
Jim Grosbach7815f562012-02-03 00:07:04 +00002359
Bill Wendlingf891bf82011-07-31 06:30:59 +00002360 // If the stack restore is in a return, resume, or unwind block and if there
2361 // are no allocas or calls between the restore and the return, nuke the
2362 // restore.
Bill Wendlingd5d95b02012-02-06 21:16:41 +00002363 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<ResumeInst>(TI)))
Sanjay Patel4b198802016-02-01 22:23:39 +00002364 return eraseInstFromFunction(CI);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002365 break;
2366 }
Vitaly Bukaf0500b62016-07-28 22:50:48 +00002367 case Intrinsic::lifetime_start:
Vitaly Buka0ab23cf2016-07-28 22:59:03 +00002368 // Asan needs to poison memory to detect invalid access which is possible
2369 // even for empty lifetime range.
2370 if (II->getFunction()->hasFnAttribute(Attribute::SanitizeAddress))
2371 break;
2372
Arnaud A. de Grandmaison333ef382016-05-10 09:24:49 +00002373 if (removeTriviallyEmptyRange(*II, Intrinsic::lifetime_start,
2374 Intrinsic::lifetime_end, *this))
2375 return nullptr;
Arnaud A. de Grandmaison849f3bf2015-10-01 14:54:31 +00002376 break;
Hal Finkelf5867a72014-07-25 21:45:17 +00002377 case Intrinsic::assume: {
David Majnemerfcc58112016-04-08 16:37:12 +00002378 Value *IIOperand = II->getArgOperand(0);
2379 // Remove an assume if it is immediately followed by an identical assume.
2380 if (match(II->getNextNode(),
2381 m_Intrinsic<Intrinsic::assume>(m_Specific(IIOperand))))
2382 return eraseInstFromFunction(CI);
2383
Hal Finkelf5867a72014-07-25 21:45:17 +00002384 // Canonicalize assume(a && b) -> assume(a); assume(b);
Hal Finkel74c2f352014-09-07 12:44:26 +00002385 // Note: New assumption intrinsics created here are registered by
2386 // the InstCombineIRInserter object.
David Majnemerfcc58112016-04-08 16:37:12 +00002387 Value *AssumeIntrinsic = II->getCalledValue(), *A, *B;
Hal Finkelf5867a72014-07-25 21:45:17 +00002388 if (match(IIOperand, m_And(m_Value(A), m_Value(B)))) {
2389 Builder->CreateCall(AssumeIntrinsic, A, II->getName());
2390 Builder->CreateCall(AssumeIntrinsic, B, II->getName());
Sanjay Patel4b198802016-02-01 22:23:39 +00002391 return eraseInstFromFunction(*II);
Hal Finkelf5867a72014-07-25 21:45:17 +00002392 }
2393 // assume(!(a || b)) -> assume(!a); assume(!b);
2394 if (match(IIOperand, m_Not(m_Or(m_Value(A), m_Value(B))))) {
Hal Finkel74c2f352014-09-07 12:44:26 +00002395 Builder->CreateCall(AssumeIntrinsic, Builder->CreateNot(A),
2396 II->getName());
2397 Builder->CreateCall(AssumeIntrinsic, Builder->CreateNot(B),
2398 II->getName());
Sanjay Patel4b198802016-02-01 22:23:39 +00002399 return eraseInstFromFunction(*II);
Hal Finkelf5867a72014-07-25 21:45:17 +00002400 }
Hal Finkel04a15612014-10-04 21:27:06 +00002401
Philip Reames66c6de62014-11-11 23:33:19 +00002402 // assume( (load addr) != null ) -> add 'nonnull' metadata to load
2403 // (if assume is valid at the load)
2404 if (ICmpInst* ICmp = dyn_cast<ICmpInst>(IIOperand)) {
2405 Value *LHS = ICmp->getOperand(0);
2406 Value *RHS = ICmp->getOperand(1);
2407 if (ICmpInst::ICMP_NE == ICmp->getPredicate() &&
2408 isa<LoadInst>(LHS) &&
2409 isa<Constant>(RHS) &&
2410 RHS->getType()->isPointerTy() &&
2411 cast<Constant>(RHS)->isNullValue()) {
2412 LoadInst* LI = cast<LoadInst>(LHS);
Justin Bogner99798402016-08-05 01:06:44 +00002413 if (isValidAssumeForContext(II, LI, &DT)) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002414 MDNode *MD = MDNode::get(II->getContext(), None);
Philip Reames66c6de62014-11-11 23:33:19 +00002415 LI->setMetadata(LLVMContext::MD_nonnull, MD);
Sanjay Patel4b198802016-02-01 22:23:39 +00002416 return eraseInstFromFunction(*II);
Philip Reames66c6de62014-11-11 23:33:19 +00002417 }
2418 }
Chandler Carruth24969102015-02-10 08:07:32 +00002419 // TODO: apply nonnull return attributes to calls and invokes
Philip Reames66c6de62014-11-11 23:33:19 +00002420 // TODO: apply range metadata for range check patterns?
2421 }
Hal Finkel04a15612014-10-04 21:27:06 +00002422 // If there is a dominating assume with the same condition as this one,
2423 // then this one is redundant, and should be removed.
Hal Finkel45646882014-10-05 00:53:02 +00002424 APInt KnownZero(1, 0), KnownOne(1, 0);
2425 computeKnownBits(IIOperand, KnownZero, KnownOne, 0, II);
2426 if (KnownOne.isAllOnesValue())
Sanjay Patel4b198802016-02-01 22:23:39 +00002427 return eraseInstFromFunction(*II);
Hal Finkel04a15612014-10-04 21:27:06 +00002428
Hal Finkelf5867a72014-07-25 21:45:17 +00002429 break;
2430 }
Philip Reames9db26ff2014-12-29 23:27:30 +00002431 case Intrinsic::experimental_gc_relocate: {
2432 // Translate facts known about a pointer before relocating into
2433 // facts about the relocate value, while being careful to
2434 // preserve relocation semantics.
Manuel Jacob83eefa62016-01-05 04:03:00 +00002435 Value *DerivedPtr = cast<GCRelocateInst>(II)->getDerivedPtr();
Philip Reames9db26ff2014-12-29 23:27:30 +00002436
2437 // Remove the relocation if unused, note that this check is required
2438 // to prevent the cases below from looping forever.
2439 if (II->use_empty())
Sanjay Patel4b198802016-02-01 22:23:39 +00002440 return eraseInstFromFunction(*II);
Philip Reames9db26ff2014-12-29 23:27:30 +00002441
2442 // Undef is undef, even after relocation.
2443 // TODO: provide a hook for this in GCStrategy. This is clearly legal for
2444 // most practical collectors, but there was discussion in the review thread
2445 // about whether it was legal for all possible collectors.
Philip Reamesea4d8e82016-02-09 21:09:22 +00002446 if (isa<UndefValue>(DerivedPtr))
2447 // Use undef of gc_relocate's type to replace it.
2448 return replaceInstUsesWith(*II, UndefValue::get(II->getType()));
Philip Reames9db26ff2014-12-29 23:27:30 +00002449
Philip Reamesea4d8e82016-02-09 21:09:22 +00002450 if (auto *PT = dyn_cast<PointerType>(II->getType())) {
2451 // The relocation of null will be null for most any collector.
2452 // TODO: provide a hook for this in GCStrategy. There might be some
2453 // weird collector this property does not hold for.
2454 if (isa<ConstantPointerNull>(DerivedPtr))
2455 // Use null-pointer of gc_relocate's type to replace it.
2456 return replaceInstUsesWith(*II, ConstantPointerNull::get(PT));
Simon Pilgrimc0c56e72016-04-24 17:00:34 +00002457
Philip Reamesea4d8e82016-02-09 21:09:22 +00002458 // isKnownNonNull -> nonnull attribute
Justin Bogner99798402016-08-05 01:06:44 +00002459 if (isKnownNonNullAt(DerivedPtr, II, &DT))
Philip Reamesea4d8e82016-02-09 21:09:22 +00002460 II->addAttribute(AttributeSet::ReturnIndex, Attribute::NonNull);
Ramkumar Ramachandra8fcb4982015-02-14 19:37:54 +00002461 }
Philip Reames9db26ff2014-12-29 23:27:30 +00002462
2463 // TODO: bitcast(relocate(p)) -> relocate(bitcast(p))
2464 // Canonicalize on the type from the uses to the defs
Ramkumar Ramachandra8fcb4982015-02-14 19:37:54 +00002465
Philip Reames9db26ff2014-12-29 23:27:30 +00002466 // TODO: relocate((gep p, C, C2, ...)) -> gep(relocate(p), C, C2, ...)
Philip Reamesea4d8e82016-02-09 21:09:22 +00002467 break;
Philip Reames9db26ff2014-12-29 23:27:30 +00002468 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002469 }
2470
2471 return visitCallSite(II);
2472}
2473
2474// InvokeInst simplification
2475//
2476Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
2477 return visitCallSite(&II);
2478}
2479
Sanjay Patelcd4377c2016-01-20 22:24:38 +00002480/// If this cast does not affect the value passed through the varargs area, we
2481/// can eliminate the use of the cast.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002482static bool isSafeToEliminateVarargsCast(const CallSite CS,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002483 const DataLayout &DL,
2484 const CastInst *const CI,
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002485 const int ix) {
2486 if (!CI->isLosslessCast())
2487 return false;
2488
Philip Reames1a1bdb22014-12-02 18:50:36 +00002489 // If this is a GC intrinsic, avoid munging types. We need types for
2490 // statepoint reconstruction in SelectionDAG.
2491 // TODO: This is probably something which should be expanded to all
2492 // intrinsics since the entire point of intrinsics is that
2493 // they are understandable by the optimizer.
2494 if (isStatepoint(CS) || isGCRelocate(CS) || isGCResult(CS))
2495 return false;
2496
Reid Kleckner26af2ca2014-01-28 02:38:36 +00002497 // The size of ByVal or InAlloca arguments is derived from the type, so we
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002498 // can't change to a type with a different size. If the size were
2499 // passed explicitly we could avoid this check.
Reid Kleckner26af2ca2014-01-28 02:38:36 +00002500 if (!CS.isByValOrInAllocaArgument(ix))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002501 return true;
2502
Jim Grosbach7815f562012-02-03 00:07:04 +00002503 Type* SrcTy =
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002504 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
Chris Lattner229907c2011-07-18 04:54:35 +00002505 Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002506 if (!SrcTy->isSized() || !DstTy->isSized())
2507 return false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002508 if (DL.getTypeAllocSize(SrcTy) != DL.getTypeAllocSize(DstTy))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002509 return false;
2510 return true;
2511}
2512
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002513Instruction *InstCombiner::tryOptimizeCall(CallInst *CI) {
Craig Topperf40110f2014-04-25 05:29:35 +00002514 if (!CI->getCalledFunction()) return nullptr;
Eric Christophera7fb58f2010-03-06 10:50:38 +00002515
Chandler Carruthba4c5172015-01-21 11:23:40 +00002516 auto InstCombineRAUW = [this](Instruction *From, Value *With) {
Sanjay Patel4b198802016-02-01 22:23:39 +00002517 replaceInstUsesWith(*From, With);
Chandler Carruthba4c5172015-01-21 11:23:40 +00002518 };
Justin Bogner99798402016-08-05 01:06:44 +00002519 LibCallSimplifier Simplifier(DL, &TLI, InstCombineRAUW);
Chandler Carruthba4c5172015-01-21 11:23:40 +00002520 if (Value *With = Simplifier.optimizeCall(CI)) {
Meador Ingee3f2b262012-11-30 04:05:06 +00002521 ++NumSimplified;
Sanjay Patel4b198802016-02-01 22:23:39 +00002522 return CI->use_empty() ? CI : replaceInstUsesWith(*CI, With);
Meador Ingee3f2b262012-11-30 04:05:06 +00002523 }
Meador Ingedf796f82012-10-13 16:45:24 +00002524
Craig Topperf40110f2014-04-25 05:29:35 +00002525 return nullptr;
Eric Christophera7fb58f2010-03-06 10:50:38 +00002526}
2527
Sanjay Patel6038d3e2016-01-29 23:27:03 +00002528static IntrinsicInst *findInitTrampolineFromAlloca(Value *TrampMem) {
Duncan Sandsa0984362011-09-06 13:37:06 +00002529 // Strip off at most one level of pointer casts, looking for an alloca. This
2530 // is good enough in practice and simpler than handling any number of casts.
2531 Value *Underlying = TrampMem->stripPointerCasts();
2532 if (Underlying != TrampMem &&
Chandler Carruthcdf47882014-03-09 03:16:01 +00002533 (!Underlying->hasOneUse() || Underlying->user_back() != TrampMem))
Craig Topperf40110f2014-04-25 05:29:35 +00002534 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00002535 if (!isa<AllocaInst>(Underlying))
Craig Topperf40110f2014-04-25 05:29:35 +00002536 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00002537
Craig Topperf40110f2014-04-25 05:29:35 +00002538 IntrinsicInst *InitTrampoline = nullptr;
Chandler Carruthcdf47882014-03-09 03:16:01 +00002539 for (User *U : TrampMem->users()) {
2540 IntrinsicInst *II = dyn_cast<IntrinsicInst>(U);
Duncan Sandsa0984362011-09-06 13:37:06 +00002541 if (!II)
Craig Topperf40110f2014-04-25 05:29:35 +00002542 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00002543 if (II->getIntrinsicID() == Intrinsic::init_trampoline) {
2544 if (InitTrampoline)
2545 // More than one init_trampoline writes to this value. Give up.
Craig Topperf40110f2014-04-25 05:29:35 +00002546 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00002547 InitTrampoline = II;
2548 continue;
2549 }
2550 if (II->getIntrinsicID() == Intrinsic::adjust_trampoline)
2551 // Allow any number of calls to adjust.trampoline.
2552 continue;
Craig Topperf40110f2014-04-25 05:29:35 +00002553 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00002554 }
2555
2556 // No call to init.trampoline found.
2557 if (!InitTrampoline)
Craig Topperf40110f2014-04-25 05:29:35 +00002558 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00002559
2560 // Check that the alloca is being used in the expected way.
2561 if (InitTrampoline->getOperand(0) != TrampMem)
Craig Topperf40110f2014-04-25 05:29:35 +00002562 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00002563
2564 return InitTrampoline;
2565}
2566
Sanjay Patel6038d3e2016-01-29 23:27:03 +00002567static IntrinsicInst *findInitTrampolineFromBB(IntrinsicInst *AdjustTramp,
Duncan Sandsa0984362011-09-06 13:37:06 +00002568 Value *TrampMem) {
2569 // Visit all the previous instructions in the basic block, and try to find a
2570 // init.trampoline which has a direct path to the adjust.trampoline.
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00002571 for (BasicBlock::iterator I = AdjustTramp->getIterator(),
2572 E = AdjustTramp->getParent()->begin();
2573 I != E;) {
2574 Instruction *Inst = &*--I;
Duncan Sandsa0984362011-09-06 13:37:06 +00002575 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
2576 if (II->getIntrinsicID() == Intrinsic::init_trampoline &&
2577 II->getOperand(0) == TrampMem)
2578 return II;
2579 if (Inst->mayWriteToMemory())
Craig Topperf40110f2014-04-25 05:29:35 +00002580 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00002581 }
Craig Topperf40110f2014-04-25 05:29:35 +00002582 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00002583}
2584
2585// Given a call to llvm.adjust.trampoline, find and return the corresponding
2586// call to llvm.init.trampoline if the call to the trampoline can be optimized
2587// to a direct call to a function. Otherwise return NULL.
2588//
Sanjay Patel6038d3e2016-01-29 23:27:03 +00002589static IntrinsicInst *findInitTrampoline(Value *Callee) {
Duncan Sandsa0984362011-09-06 13:37:06 +00002590 Callee = Callee->stripPointerCasts();
2591 IntrinsicInst *AdjustTramp = dyn_cast<IntrinsicInst>(Callee);
2592 if (!AdjustTramp ||
2593 AdjustTramp->getIntrinsicID() != Intrinsic::adjust_trampoline)
Craig Topperf40110f2014-04-25 05:29:35 +00002594 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00002595
2596 Value *TrampMem = AdjustTramp->getOperand(0);
2597
Sanjay Patel6038d3e2016-01-29 23:27:03 +00002598 if (IntrinsicInst *IT = findInitTrampolineFromAlloca(TrampMem))
Duncan Sandsa0984362011-09-06 13:37:06 +00002599 return IT;
Sanjay Patel6038d3e2016-01-29 23:27:03 +00002600 if (IntrinsicInst *IT = findInitTrampolineFromBB(AdjustTramp, TrampMem))
Duncan Sandsa0984362011-09-06 13:37:06 +00002601 return IT;
Craig Topperf40110f2014-04-25 05:29:35 +00002602 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00002603}
2604
Sanjay Patelcd4377c2016-01-20 22:24:38 +00002605/// Improvements for call and invoke instructions.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002606Instruction *InstCombiner::visitCallSite(CallSite CS) {
Justin Bogner99798402016-08-05 01:06:44 +00002607 if (isAllocLikeFn(CS.getInstruction(), &TLI))
Nuno Lopes95cc4f32012-07-09 18:38:20 +00002608 return visitAllocSite(*CS.getInstruction());
Nuno Lopesdc6085e2012-06-21 21:25:05 +00002609
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002610 bool Changed = false;
2611
Philip Reamesc25df112015-06-16 20:24:25 +00002612 // Mark any parameters that are known to be non-null with the nonnull
2613 // attribute. This is helpful for inlining calls to functions with null
2614 // checks on their arguments.
Akira Hatanaka237916b2015-12-02 06:58:49 +00002615 SmallVector<unsigned, 4> Indices;
Philip Reamesc25df112015-06-16 20:24:25 +00002616 unsigned ArgNo = 0;
Akira Hatanaka237916b2015-12-02 06:58:49 +00002617
Philip Reamesc25df112015-06-16 20:24:25 +00002618 for (Value *V : CS.args()) {
Sanjay Patelf9f5d3c2016-01-29 23:14:58 +00002619 if (V->getType()->isPointerTy() &&
2620 !CS.paramHasAttr(ArgNo + 1, Attribute::NonNull) &&
Justin Bogner99798402016-08-05 01:06:44 +00002621 isKnownNonNullAt(V, CS.getInstruction(), &DT))
Akira Hatanaka237916b2015-12-02 06:58:49 +00002622 Indices.push_back(ArgNo + 1);
Philip Reamesc25df112015-06-16 20:24:25 +00002623 ArgNo++;
2624 }
Akira Hatanaka237916b2015-12-02 06:58:49 +00002625
Philip Reamesc25df112015-06-16 20:24:25 +00002626 assert(ArgNo == CS.arg_size() && "sanity check");
2627
Akira Hatanaka237916b2015-12-02 06:58:49 +00002628 if (!Indices.empty()) {
2629 AttributeSet AS = CS.getAttributes();
2630 LLVMContext &Ctx = CS.getInstruction()->getContext();
2631 AS = AS.addAttribute(Ctx, Indices,
2632 Attribute::get(Ctx, Attribute::NonNull));
2633 CS.setAttributes(AS);
2634 Changed = true;
2635 }
2636
Chris Lattner73989652010-12-20 08:25:06 +00002637 // If the callee is a pointer to a function, attempt to move any casts to the
2638 // arguments of the call/invoke.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002639 Value *Callee = CS.getCalledValue();
Chris Lattner73989652010-12-20 08:25:06 +00002640 if (!isa<Function>(Callee) && transformConstExprCastCall(CS))
Craig Topperf40110f2014-04-25 05:29:35 +00002641 return nullptr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002642
Justin Lebar9d943972016-03-14 20:18:54 +00002643 if (Function *CalleeF = dyn_cast<Function>(Callee)) {
2644 // Remove the convergent attr on calls when the callee is not convergent.
Matt Arsenault802ebcb2016-06-20 19:04:44 +00002645 if (CS.isConvergent() && !CalleeF->isConvergent() &&
2646 !CalleeF->isIntrinsic()) {
Justin Lebar9d943972016-03-14 20:18:54 +00002647 DEBUG(dbgs() << "Removing convergent attr from instr "
2648 << CS.getInstruction() << "\n");
2649 CS.setNotConvergent();
2650 return CS.getInstruction();
2651 }
2652
Chris Lattner846a52e2010-02-01 18:11:34 +00002653 // If the call and callee calling conventions don't match, this call must
2654 // be unreachable, as the call is undefined.
2655 if (CalleeF->getCallingConv() != CS.getCallingConv() &&
2656 // Only do this for calls to a function with a body. A prototype may
2657 // not actually end up matching the implementation's calling conv for a
2658 // variety of reasons (e.g. it may be written in assembly).
2659 !CalleeF->isDeclaration()) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002660 Instruction *OldCall = CS.getInstruction();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002661 new StoreInst(ConstantInt::getTrue(Callee->getContext()),
Jim Grosbach7815f562012-02-03 00:07:04 +00002662 UndefValue::get(Type::getInt1PtrTy(Callee->getContext())),
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002663 OldCall);
Chad Rosiere28ae302012-12-13 00:18:46 +00002664 // If OldCall does not return void then replaceAllUsesWith undef.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002665 // This allows ValueHandlers and custom metadata to adjust itself.
2666 if (!OldCall->getType()->isVoidTy())
Sanjay Patel4b198802016-02-01 22:23:39 +00002667 replaceInstUsesWith(*OldCall, UndefValue::get(OldCall->getType()));
Chris Lattner2cecedf2010-02-01 18:04:58 +00002668 if (isa<CallInst>(OldCall))
Sanjay Patel4b198802016-02-01 22:23:39 +00002669 return eraseInstFromFunction(*OldCall);
Jim Grosbach7815f562012-02-03 00:07:04 +00002670
Chris Lattner2cecedf2010-02-01 18:04:58 +00002671 // We cannot remove an invoke, because it would change the CFG, just
2672 // change the callee to a null pointer.
Gabor Greiffebf6ab2010-03-20 21:00:25 +00002673 cast<InvokeInst>(OldCall)->setCalledFunction(
Chris Lattner2cecedf2010-02-01 18:04:58 +00002674 Constant::getNullValue(CalleeF->getType()));
Craig Topperf40110f2014-04-25 05:29:35 +00002675 return nullptr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002676 }
Justin Lebar9d943972016-03-14 20:18:54 +00002677 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002678
2679 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
Gabor Greif589a0b92010-06-24 12:58:35 +00002680 // If CS does not return void then replaceAllUsesWith undef.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002681 // This allows ValueHandlers and custom metadata to adjust itself.
2682 if (!CS.getInstruction()->getType()->isVoidTy())
Sanjay Patel4b198802016-02-01 22:23:39 +00002683 replaceInstUsesWith(*CS.getInstruction(),
Eli Friedmanb9ed18f2011-05-18 00:32:01 +00002684 UndefValue::get(CS.getInstruction()->getType()));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002685
Nuno Lopes771e7bd2012-06-21 23:52:14 +00002686 if (isa<InvokeInst>(CS.getInstruction())) {
2687 // Can't remove an invoke because we cannot change the CFG.
Craig Topperf40110f2014-04-25 05:29:35 +00002688 return nullptr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002689 }
Nuno Lopes771e7bd2012-06-21 23:52:14 +00002690
2691 // This instruction is not reachable, just remove it. We insert a store to
2692 // undef so that we know that this code is not reachable, despite the fact
2693 // that we can't modify the CFG here.
2694 new StoreInst(ConstantInt::getTrue(Callee->getContext()),
2695 UndefValue::get(Type::getInt1PtrTy(Callee->getContext())),
2696 CS.getInstruction());
2697
Sanjay Patel4b198802016-02-01 22:23:39 +00002698 return eraseInstFromFunction(*CS.getInstruction());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002699 }
2700
Sanjay Patel6038d3e2016-01-29 23:27:03 +00002701 if (IntrinsicInst *II = findInitTrampoline(Callee))
Duncan Sandsa0984362011-09-06 13:37:06 +00002702 return transformCallThroughTrampoline(CS, II);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002703
Chris Lattner229907c2011-07-18 04:54:35 +00002704 PointerType *PTy = cast<PointerType>(Callee->getType());
2705 FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002706 if (FTy->isVarArg()) {
Eli Friedman7534b4682011-11-29 01:18:23 +00002707 int ix = FTy->getNumParams();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002708 // See if we can optimize any arguments passed through the varargs area of
2709 // the call.
Matt Arsenault5d2e85f2013-06-28 00:25:40 +00002710 for (CallSite::arg_iterator I = CS.arg_begin() + FTy->getNumParams(),
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002711 E = CS.arg_end(); I != E; ++I, ++ix) {
2712 CastInst *CI = dyn_cast<CastInst>(*I);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002713 if (CI && isSafeToEliminateVarargsCast(CS, DL, CI, ix)) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002714 *I = CI->getOperand(0);
2715 Changed = true;
2716 }
2717 }
2718 }
2719
2720 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
2721 // Inline asm calls cannot throw - mark them 'nounwind'.
2722 CS.setDoesNotThrow();
2723 Changed = true;
2724 }
2725
Micah Villmowcdfe20b2012-10-08 16:38:25 +00002726 // Try to optimize the call if possible, we require DataLayout for most of
Eric Christophera7fb58f2010-03-06 10:50:38 +00002727 // this. None of these calls are seen as possibly dead so go ahead and
2728 // delete the instruction now.
2729 if (CallInst *CI = dyn_cast<CallInst>(CS.getInstruction())) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002730 Instruction *I = tryOptimizeCall(CI);
Eric Christopher1810d772010-03-06 10:59:25 +00002731 // If we changed something return the result, etc. Otherwise let
2732 // the fallthrough check.
Sanjay Patel4b198802016-02-01 22:23:39 +00002733 if (I) return eraseInstFromFunction(*I);
Eric Christophera7fb58f2010-03-06 10:50:38 +00002734 }
2735
Craig Topperf40110f2014-04-25 05:29:35 +00002736 return Changed ? CS.getInstruction() : nullptr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002737}
2738
Sanjay Patelcd4377c2016-01-20 22:24:38 +00002739/// If the callee is a constexpr cast of a function, attempt to move the cast to
2740/// the arguments of the call/invoke.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002741bool InstCombiner::transformConstExprCastCall(CallSite CS) {
Sanjay Patele3c335c2016-08-11 15:21:21 +00002742 auto *Callee = dyn_cast<Function>(CS.getCalledValue()->stripPointerCasts());
Craig Topperf40110f2014-04-25 05:29:35 +00002743 if (!Callee)
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002744 return false;
Sanjay Patel38ae83d2016-08-11 15:23:56 +00002745
2746 // The prototype of a thunk is a lie. Don't directly call such a function.
David Majnemer4c0a6e92015-01-21 22:32:04 +00002747 if (Callee->hasFnAttribute("thunk"))
2748 return false;
Sanjay Patel38ae83d2016-08-11 15:23:56 +00002749
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002750 Instruction *Caller = CS.getInstruction();
Bill Wendlinge94d8432012-12-07 23:16:57 +00002751 const AttributeSet &CallerPAL = CS.getAttributes();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002752
2753 // Okay, this is a cast from a function to a different type. Unless doing so
2754 // would cause a type conversion of one of our arguments, change this call to
2755 // be a direct call with arguments casted to the appropriate types.
2756 //
Chris Lattner229907c2011-07-18 04:54:35 +00002757 FunctionType *FT = Callee->getFunctionType();
2758 Type *OldRetTy = Caller->getType();
2759 Type *NewRetTy = FT->getReturnType();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002760
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002761 // Check to see if we are changing the return type...
2762 if (OldRetTy != NewRetTy) {
Nick Lewyckya6a17d72014-01-18 22:47:12 +00002763
2764 if (NewRetTy->isStructTy())
2765 return false; // TODO: Handle multiple return values.
2766
David Majnemer9b6b8222015-01-06 08:41:31 +00002767 if (!CastInst::isBitOrNoopPointerCastable(NewRetTy, OldRetTy, DL)) {
Matt Arsenaulte6952f22013-09-17 21:10:14 +00002768 if (Callee->isDeclaration())
2769 return false; // Cannot transform this return value.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002770
Matt Arsenaulte6952f22013-09-17 21:10:14 +00002771 if (!Caller->use_empty() &&
2772 // void -> non-void is handled specially
2773 !NewRetTy->isVoidTy())
Frederic Rissc1892e22014-10-23 04:08:42 +00002774 return false; // Cannot transform this return value.
Matt Arsenaulte6952f22013-09-17 21:10:14 +00002775 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002776
2777 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Bill Wendling658d24d2013-01-18 21:53:16 +00002778 AttrBuilder RAttrs(CallerPAL, AttributeSet::ReturnIndex);
Pete Cooper2777d8872015-05-06 23:19:56 +00002779 if (RAttrs.overlaps(AttributeFuncs::typeIncompatible(NewRetTy)))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002780 return false; // Attribute not compatible with transformed value.
2781 }
2782
2783 // If the callsite is an invoke instruction, and the return value is used by
2784 // a PHI node in a successor, we cannot change the return type of the call
2785 // because there is no place to put the cast instruction (without breaking
2786 // the critical edge). Bail out in this case.
2787 if (!Caller->use_empty())
2788 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
Chandler Carruthcdf47882014-03-09 03:16:01 +00002789 for (User *U : II->users())
2790 if (PHINode *PN = dyn_cast<PHINode>(U))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002791 if (PN->getParent() == II->getNormalDest() ||
2792 PN->getParent() == II->getUnwindDest())
2793 return false;
2794 }
2795
Matt Arsenault5d2e85f2013-06-28 00:25:40 +00002796 unsigned NumActualArgs = CS.arg_size();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002797 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
2798
David Majnemer9b6b8222015-01-06 08:41:31 +00002799 // Prevent us turning:
2800 // declare void @takes_i32_inalloca(i32* inalloca)
2801 // call void bitcast (void (i32*)* @takes_i32_inalloca to void (i32)*)(i32 0)
2802 //
2803 // into:
2804 // call void @takes_i32_inalloca(i32* null)
David Majnemerd61a6fd2015-03-11 18:03:05 +00002805 //
2806 // Similarly, avoid folding away bitcasts of byval calls.
2807 if (Callee->getAttributes().hasAttrSomewhere(Attribute::InAlloca) ||
2808 Callee->getAttributes().hasAttrSomewhere(Attribute::ByVal))
David Majnemer9b6b8222015-01-06 08:41:31 +00002809 return false;
2810
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002811 CallSite::arg_iterator AI = CS.arg_begin();
2812 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
Chris Lattner229907c2011-07-18 04:54:35 +00002813 Type *ParamTy = FT->getParamType(i);
2814 Type *ActTy = (*AI)->getType();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002815
David Majnemer9b6b8222015-01-06 08:41:31 +00002816 if (!CastInst::isBitOrNoopPointerCastable(ActTy, ParamTy, DL))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002817 return false; // Cannot transform this parameter value.
2818
Bill Wendling49bc76c2013-01-23 06:14:59 +00002819 if (AttrBuilder(CallerPAL.getParamAttributes(i + 1), i + 1).
Pete Cooper2777d8872015-05-06 23:19:56 +00002820 overlaps(AttributeFuncs::typeIncompatible(ParamTy)))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002821 return false; // Attribute not compatible with transformed value.
Jim Grosbach7815f562012-02-03 00:07:04 +00002822
Reid Kleckner26af2ca2014-01-28 02:38:36 +00002823 if (CS.isInAllocaArgument(i))
2824 return false; // Cannot transform to and from inalloca.
2825
Chris Lattner27ca8eb2010-12-20 08:36:38 +00002826 // If the parameter is passed as a byval argument, then we have to have a
2827 // sized type and the sized type has to have the same size as the old type.
Bill Wendling49bc76c2013-01-23 06:14:59 +00002828 if (ParamTy != ActTy &&
2829 CallerPAL.getParamAttributes(i + 1).hasAttribute(i + 1,
2830 Attribute::ByVal)) {
Chris Lattner229907c2011-07-18 04:54:35 +00002831 PointerType *ParamPTy = dyn_cast<PointerType>(ParamTy);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002832 if (!ParamPTy || !ParamPTy->getElementType()->isSized())
Chris Lattner27ca8eb2010-12-20 08:36:38 +00002833 return false;
Jim Grosbach7815f562012-02-03 00:07:04 +00002834
Matt Arsenaultfa252722013-09-27 22:18:51 +00002835 Type *CurElTy = ActTy->getPointerElementType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002836 if (DL.getTypeAllocSize(CurElTy) !=
2837 DL.getTypeAllocSize(ParamPTy->getElementType()))
Chris Lattner27ca8eb2010-12-20 08:36:38 +00002838 return false;
2839 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002840 }
2841
Chris Lattneradf38b32011-02-24 05:10:56 +00002842 if (Callee->isDeclaration()) {
2843 // Do not delete arguments unless we have a function body.
2844 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg())
2845 return false;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002846
Chris Lattneradf38b32011-02-24 05:10:56 +00002847 // If the callee is just a declaration, don't change the varargsness of the
2848 // call. We don't want to introduce a varargs call where one doesn't
2849 // already exist.
Chris Lattner229907c2011-07-18 04:54:35 +00002850 PointerType *APTy = cast<PointerType>(CS.getCalledValue()->getType());
Chris Lattneradf38b32011-02-24 05:10:56 +00002851 if (FT->isVarArg()!=cast<FunctionType>(APTy->getElementType())->isVarArg())
2852 return false;
Jim Grosbache84ae7b2012-02-03 00:00:55 +00002853
2854 // If both the callee and the cast type are varargs, we still have to make
2855 // sure the number of fixed parameters are the same or we have the same
2856 // ABI issues as if we introduce a varargs call.
Jim Grosbach1df8cdc2012-02-03 00:26:07 +00002857 if (FT->isVarArg() &&
2858 cast<FunctionType>(APTy->getElementType())->isVarArg() &&
2859 FT->getNumParams() !=
Jim Grosbache84ae7b2012-02-03 00:00:55 +00002860 cast<FunctionType>(APTy->getElementType())->getNumParams())
2861 return false;
Chris Lattneradf38b32011-02-24 05:10:56 +00002862 }
Jim Grosbach7815f562012-02-03 00:07:04 +00002863
Jim Grosbach0ab54182012-02-03 00:00:50 +00002864 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
2865 !CallerPAL.isEmpty())
2866 // In this case we have more arguments than the new function type, but we
2867 // won't be dropping them. Check that these extra arguments have attributes
2868 // that are compatible with being a vararg call argument.
2869 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
Bill Wendling57625a42013-01-25 23:09:36 +00002870 unsigned Index = CallerPAL.getSlotIndex(i - 1);
2871 if (Index <= FT->getNumParams())
Jim Grosbach0ab54182012-02-03 00:00:50 +00002872 break;
Bill Wendling57625a42013-01-25 23:09:36 +00002873
Bill Wendlingd97b75d2012-12-19 08:57:40 +00002874 // Check if it has an attribute that's incompatible with varargs.
Bill Wendling57625a42013-01-25 23:09:36 +00002875 AttributeSet PAttrs = CallerPAL.getSlotAttributes(i - 1);
2876 if (PAttrs.hasAttribute(Index, Attribute::StructRet))
Jim Grosbach0ab54182012-02-03 00:00:50 +00002877 return false;
2878 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002879
Jim Grosbach7815f562012-02-03 00:07:04 +00002880
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002881 // Okay, we decided that this is a safe thing to do: go ahead and start
Chris Lattneradf38b32011-02-24 05:10:56 +00002882 // inserting cast instructions as necessary.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002883 std::vector<Value*> Args;
2884 Args.reserve(NumActualArgs);
Bill Wendling3575c8c2013-01-27 02:08:22 +00002885 SmallVector<AttributeSet, 8> attrVec;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002886 attrVec.reserve(NumCommonArgs);
2887
2888 // Get any return attributes.
Bill Wendling658d24d2013-01-18 21:53:16 +00002889 AttrBuilder RAttrs(CallerPAL, AttributeSet::ReturnIndex);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002890
2891 // If the return value is not being used, the type may not be compatible
2892 // with the existing attributes. Wipe out any problematic attributes.
Pete Cooper2777d8872015-05-06 23:19:56 +00002893 RAttrs.remove(AttributeFuncs::typeIncompatible(NewRetTy));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002894
2895 // Add the new return attributes.
Bill Wendling70f39172012-10-09 00:01:21 +00002896 if (RAttrs.hasAttributes())
Bill Wendling3575c8c2013-01-27 02:08:22 +00002897 attrVec.push_back(AttributeSet::get(Caller->getContext(),
2898 AttributeSet::ReturnIndex, RAttrs));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002899
2900 AI = CS.arg_begin();
2901 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
Chris Lattner229907c2011-07-18 04:54:35 +00002902 Type *ParamTy = FT->getParamType(i);
Matt Arsenaultcacbb232013-07-30 20:45:05 +00002903
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002904 if ((*AI)->getType() == ParamTy) {
2905 Args.push_back(*AI);
2906 } else {
David Majnemer9b6b8222015-01-06 08:41:31 +00002907 Args.push_back(Builder->CreateBitOrPointerCast(*AI, ParamTy));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002908 }
2909
2910 // Add any parameter attributes.
Bill Wendling49bc76c2013-01-23 06:14:59 +00002911 AttrBuilder PAttrs(CallerPAL.getParamAttributes(i + 1), i + 1);
Bill Wendling76d2cd22012-10-14 08:54:26 +00002912 if (PAttrs.hasAttributes())
Bill Wendling3575c8c2013-01-27 02:08:22 +00002913 attrVec.push_back(AttributeSet::get(Caller->getContext(), i + 1,
2914 PAttrs));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002915 }
2916
2917 // If the function takes more arguments than the call was taking, add them
2918 // now.
2919 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
2920 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
2921
2922 // If we are removing arguments to the function, emit an obnoxious warning.
2923 if (FT->getNumParams() < NumActualArgs) {
Nick Lewycky90053a12012-12-26 22:00:35 +00002924 // TODO: if (!FT->isVarArg()) this call may be unreachable. PR14722
2925 if (FT->isVarArg()) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002926 // Add all of the arguments in their promoted form to the arg list.
2927 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
Chris Lattner229907c2011-07-18 04:54:35 +00002928 Type *PTy = getPromotedType((*AI)->getType());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002929 if (PTy != (*AI)->getType()) {
2930 // Must promote to pass through va_arg area!
2931 Instruction::CastOps opcode =
2932 CastInst::getCastOpcode(*AI, false, PTy, false);
Benjamin Kramer547b6c52011-09-27 20:39:19 +00002933 Args.push_back(Builder->CreateCast(opcode, *AI, PTy));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002934 } else {
2935 Args.push_back(*AI);
2936 }
2937
2938 // Add any parameter attributes.
Bill Wendling49bc76c2013-01-23 06:14:59 +00002939 AttrBuilder PAttrs(CallerPAL.getParamAttributes(i + 1), i + 1);
Bill Wendling76d2cd22012-10-14 08:54:26 +00002940 if (PAttrs.hasAttributes())
Bill Wendling3575c8c2013-01-27 02:08:22 +00002941 attrVec.push_back(AttributeSet::get(FT->getContext(), i + 1,
2942 PAttrs));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002943 }
2944 }
2945 }
2946
Bill Wendlingbd4ea162013-01-21 21:57:28 +00002947 AttributeSet FnAttrs = CallerPAL.getFnAttributes();
Bill Wendling77543892013-01-18 21:11:39 +00002948 if (CallerPAL.hasAttributes(AttributeSet::FunctionIndex))
Bill Wendling3575c8c2013-01-27 02:08:22 +00002949 attrVec.push_back(AttributeSet::get(Callee->getContext(), FnAttrs));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002950
2951 if (NewRetTy->isVoidTy())
2952 Caller->setName(""); // Void type should not have a name.
2953
Bill Wendlinge94d8432012-12-07 23:16:57 +00002954 const AttributeSet &NewCallerPAL = AttributeSet::get(Callee->getContext(),
Bill Wendlingbd4ea162013-01-21 21:57:28 +00002955 attrVec);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002956
Sanjoy Das76293462015-11-25 00:42:19 +00002957 SmallVector<OperandBundleDef, 1> OpBundles;
Sanjoy Dasc521c7b2015-11-25 00:42:24 +00002958 CS.getOperandBundlesAsDefs(OpBundles);
Sanjoy Das76293462015-11-25 00:42:19 +00002959
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002960 Instruction *NC;
2961 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Sanjoy Das76293462015-11-25 00:42:19 +00002962 NC = Builder->CreateInvoke(Callee, II->getNormalDest(), II->getUnwindDest(),
2963 Args, OpBundles);
Eli Friedman96254a02011-05-18 01:28:27 +00002964 NC->takeName(II);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002965 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
2966 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
2967 } else {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002968 CallInst *CI = cast<CallInst>(Caller);
Sanjoy Das76293462015-11-25 00:42:19 +00002969 NC = Builder->CreateCall(Callee, Args, OpBundles);
Eli Friedman96254a02011-05-18 01:28:27 +00002970 NC->takeName(CI);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002971 if (CI->isTailCall())
2972 cast<CallInst>(NC)->setTailCall();
2973 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
2974 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
2975 }
2976
2977 // Insert a cast of the return type as necessary.
2978 Value *NV = NC;
2979 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
2980 if (!NV->getType()->isVoidTy()) {
David Majnemer9b6b8222015-01-06 08:41:31 +00002981 NV = NC = CastInst::CreateBitOrPointerCast(NC, OldRetTy);
Eli Friedman35211c62011-05-27 00:19:40 +00002982 NC->setDebugLoc(Caller->getDebugLoc());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002983
2984 // If this is an invoke instruction, we should insert it after the first
2985 // non-phi, instruction in the normal successor block.
2986 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Bill Wendling07efd6f2011-08-25 01:08:34 +00002987 BasicBlock::iterator I = II->getNormalDest()->getFirstInsertionPt();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002988 InsertNewInstBefore(NC, *I);
2989 } else {
Chris Lattner73989652010-12-20 08:25:06 +00002990 // Otherwise, it's a call, just insert cast right after the call.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002991 InsertNewInstBefore(NC, *Caller);
2992 }
2993 Worklist.AddUsersToWorkList(*Caller);
2994 } else {
2995 NV = UndefValue::get(Caller->getType());
2996 }
2997 }
2998
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002999 if (!Caller->use_empty())
Sanjay Patel4b198802016-02-01 22:23:39 +00003000 replaceInstUsesWith(*Caller, NV);
Frederic Rissc1892e22014-10-23 04:08:42 +00003001 else if (Caller->hasValueHandle()) {
3002 if (OldRetTy == NV->getType())
3003 ValueHandleBase::ValueIsRAUWd(Caller, NV);
3004 else
3005 // We cannot call ValueIsRAUWd with a different type, and the
3006 // actual tracked value will disappear.
3007 ValueHandleBase::ValueIsDeleted(Caller);
3008 }
Eli Friedmanb9ed18f2011-05-18 00:32:01 +00003009
Sanjay Patel4b198802016-02-01 22:23:39 +00003010 eraseInstFromFunction(*Caller);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003011 return true;
3012}
3013
Sanjay Patelcd4377c2016-01-20 22:24:38 +00003014/// Turn a call to a function created by init_trampoline / adjust_trampoline
3015/// intrinsic pair into a direct call to the underlying function.
Duncan Sandsa0984362011-09-06 13:37:06 +00003016Instruction *
3017InstCombiner::transformCallThroughTrampoline(CallSite CS,
3018 IntrinsicInst *Tramp) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003019 Value *Callee = CS.getCalledValue();
Chris Lattner229907c2011-07-18 04:54:35 +00003020 PointerType *PTy = cast<PointerType>(Callee->getType());
3021 FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Bill Wendlinge94d8432012-12-07 23:16:57 +00003022 const AttributeSet &Attrs = CS.getAttributes();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003023
3024 // If the call already has the 'nest' attribute somewhere then give up -
3025 // otherwise 'nest' would occur twice after splicing in the chain.
Bill Wendling6e95ae82012-12-31 00:49:59 +00003026 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Craig Topperf40110f2014-04-25 05:29:35 +00003027 return nullptr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003028
Duncan Sandsa0984362011-09-06 13:37:06 +00003029 assert(Tramp &&
3030 "transformCallThroughTrampoline called with incorrect CallSite.");
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003031
Gabor Greif3e44ea12010-07-22 10:37:47 +00003032 Function *NestF =cast<Function>(Tramp->getArgOperand(1)->stripPointerCasts());
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00003033 FunctionType *NestFTy = cast<FunctionType>(NestF->getValueType());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003034
Bill Wendlinge94d8432012-12-07 23:16:57 +00003035 const AttributeSet &NestAttrs = NestF->getAttributes();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003036 if (!NestAttrs.isEmpty()) {
3037 unsigned NestIdx = 1;
Craig Topperf40110f2014-04-25 05:29:35 +00003038 Type *NestTy = nullptr;
Bill Wendling49bc76c2013-01-23 06:14:59 +00003039 AttributeSet NestAttr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003040
3041 // Look for a parameter marked with the 'nest' attribute.
3042 for (FunctionType::param_iterator I = NestFTy->param_begin(),
3043 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Bill Wendling49bc76c2013-01-23 06:14:59 +00003044 if (NestAttrs.hasAttribute(NestIdx, Attribute::Nest)) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003045 // Record the parameter type and any other attributes.
3046 NestTy = *I;
3047 NestAttr = NestAttrs.getParamAttributes(NestIdx);
3048 break;
3049 }
3050
3051 if (NestTy) {
3052 Instruction *Caller = CS.getInstruction();
3053 std::vector<Value*> NewArgs;
Matt Arsenault5d2e85f2013-06-28 00:25:40 +00003054 NewArgs.reserve(CS.arg_size() + 1);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003055
Bill Wendling3575c8c2013-01-27 02:08:22 +00003056 SmallVector<AttributeSet, 8> NewAttrs;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003057 NewAttrs.reserve(Attrs.getNumSlots() + 1);
3058
3059 // Insert the nest argument into the call argument list, which may
3060 // mean appending it. Likewise for attributes.
3061
3062 // Add any result attributes.
Bill Wendling658d24d2013-01-18 21:53:16 +00003063 if (Attrs.hasAttributes(AttributeSet::ReturnIndex))
Bill Wendling3575c8c2013-01-27 02:08:22 +00003064 NewAttrs.push_back(AttributeSet::get(Caller->getContext(),
3065 Attrs.getRetAttributes()));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003066
3067 {
3068 unsigned Idx = 1;
3069 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
3070 do {
3071 if (Idx == NestIdx) {
3072 // Add the chain argument and attributes.
Gabor Greif589a0b92010-06-24 12:58:35 +00003073 Value *NestVal = Tramp->getArgOperand(2);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003074 if (NestVal->getType() != NestTy)
Eli Friedman41e509a2011-05-18 23:58:37 +00003075 NestVal = Builder->CreateBitCast(NestVal, NestTy, "nest");
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003076 NewArgs.push_back(NestVal);
Bill Wendling3575c8c2013-01-27 02:08:22 +00003077 NewAttrs.push_back(AttributeSet::get(Caller->getContext(),
3078 NestAttr));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003079 }
3080
3081 if (I == E)
3082 break;
3083
3084 // Add the original argument and attributes.
3085 NewArgs.push_back(*I);
Bill Wendling49bc76c2013-01-23 06:14:59 +00003086 AttributeSet Attr = Attrs.getParamAttributes(Idx);
3087 if (Attr.hasAttributes(Idx)) {
Bill Wendling3575c8c2013-01-27 02:08:22 +00003088 AttrBuilder B(Attr, Idx);
3089 NewAttrs.push_back(AttributeSet::get(Caller->getContext(),
3090 Idx + (Idx >= NestIdx), B));
Bill Wendling49bc76c2013-01-23 06:14:59 +00003091 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003092
Richard Trieu7a083812016-02-18 22:09:30 +00003093 ++Idx;
3094 ++I;
Eugene Zelenkocdc71612016-08-11 17:20:18 +00003095 } while (true);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003096 }
3097
3098 // Add any function attributes.
Bill Wendling77543892013-01-18 21:11:39 +00003099 if (Attrs.hasAttributes(AttributeSet::FunctionIndex))
Bill Wendling3575c8c2013-01-27 02:08:22 +00003100 NewAttrs.push_back(AttributeSet::get(FTy->getContext(),
3101 Attrs.getFnAttributes()));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003102
3103 // The trampoline may have been bitcast to a bogus type (FTy).
3104 // Handle this by synthesizing a new function type, equal to FTy
3105 // with the chain parameter inserted.
3106
Jay Foadb804a2b2011-07-12 14:06:48 +00003107 std::vector<Type*> NewTypes;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003108 NewTypes.reserve(FTy->getNumParams()+1);
3109
3110 // Insert the chain's type into the list of parameter types, which may
3111 // mean appending it.
3112 {
3113 unsigned Idx = 1;
3114 FunctionType::param_iterator I = FTy->param_begin(),
3115 E = FTy->param_end();
3116
3117 do {
3118 if (Idx == NestIdx)
3119 // Add the chain's type.
3120 NewTypes.push_back(NestTy);
3121
3122 if (I == E)
3123 break;
3124
3125 // Add the original type.
3126 NewTypes.push_back(*I);
3127
Richard Trieu7a083812016-02-18 22:09:30 +00003128 ++Idx;
3129 ++I;
Eugene Zelenkocdc71612016-08-11 17:20:18 +00003130 } while (true);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003131 }
3132
3133 // Replace the trampoline call with a direct call. Let the generic
3134 // code sort out any function type mismatches.
Jim Grosbach7815f562012-02-03 00:07:04 +00003135 FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003136 FTy->isVarArg());
3137 Constant *NewCallee =
3138 NestF->getType() == PointerType::getUnqual(NewFTy) ?
Jim Grosbach7815f562012-02-03 00:07:04 +00003139 NestF : ConstantExpr::getBitCast(NestF,
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003140 PointerType::getUnqual(NewFTy));
Jim Grosbachbdbd7342013-04-05 21:20:12 +00003141 const AttributeSet &NewPAL =
3142 AttributeSet::get(FTy->getContext(), NewAttrs);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003143
David Majnemer231a68c2016-04-29 08:07:20 +00003144 SmallVector<OperandBundleDef, 1> OpBundles;
3145 CS.getOperandBundlesAsDefs(OpBundles);
3146
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003147 Instruction *NewCaller;
3148 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
3149 NewCaller = InvokeInst::Create(NewCallee,
3150 II->getNormalDest(), II->getUnwindDest(),
David Majnemer231a68c2016-04-29 08:07:20 +00003151 NewArgs, OpBundles);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003152 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
3153 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
3154 } else {
David Majnemer231a68c2016-04-29 08:07:20 +00003155 NewCaller = CallInst::Create(NewCallee, NewArgs, OpBundles);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003156 if (cast<CallInst>(Caller)->isTailCall())
3157 cast<CallInst>(NewCaller)->setTailCall();
3158 cast<CallInst>(NewCaller)->
3159 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
3160 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
3161 }
Eli Friedman49346012011-05-18 19:57:14 +00003162
3163 return NewCaller;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003164 }
3165 }
3166
3167 // Replace the trampoline call with a direct call. Since there is no 'nest'
3168 // parameter, there is no need to adjust the argument list. Let the generic
3169 // code sort out any function type mismatches.
3170 Constant *NewCallee =
Jim Grosbach7815f562012-02-03 00:07:04 +00003171 NestF->getType() == PTy ? NestF :
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003172 ConstantExpr::getBitCast(NestF, PTy);
3173 CS.setCalledFunction(NewCallee);
3174 return CS.getInstruction();
3175}