blob: 38d6f299847f3fca7af33de5e6492fd08ed27734 [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"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000019#include "llvm/ADT/Optional.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000020#include "llvm/ADT/STLExtras.h"
21#include "llvm/ADT/SmallVector.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000022#include "llvm/ADT/Statistic.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000023#include "llvm/ADT/Twine.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000024#include "llvm/Analysis/AssumptionCache.h"
David Majnemer15032582015-05-22 03:56:46 +000025#include "llvm/Analysis/InstructionSimplify.h"
Chris Lattner7a9e47a2010-01-05 07:32:13 +000026#include "llvm/Analysis/MemoryBuiltins.h"
David Blaikie31b98d22018-06-04 21:23:21 +000027#include "llvm/Transforms/Utils/Local.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000028#include "llvm/Analysis/ValueTracking.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000029#include "llvm/IR/Attributes.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000030#include "llvm/IR/BasicBlock.h"
Chandler Carruth219b89b2014-03-04 11:01:28 +000031#include "llvm/IR/CallSite.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000032#include "llvm/IR/Constant.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000033#include "llvm/IR/Constants.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000034#include "llvm/IR/DataLayout.h"
35#include "llvm/IR/DerivedTypes.h"
36#include "llvm/IR/Function.h"
37#include "llvm/IR/GlobalVariable.h"
38#include "llvm/IR/InstrTypes.h"
39#include "llvm/IR/Instruction.h"
40#include "llvm/IR/Instructions.h"
41#include "llvm/IR/IntrinsicInst.h"
42#include "llvm/IR/Intrinsics.h"
43#include "llvm/IR/LLVMContext.h"
44#include "llvm/IR/Metadata.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000045#include "llvm/IR/PatternMatch.h"
Philip Reames1a1bdb22014-12-02 18:50:36 +000046#include "llvm/IR/Statepoint.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000047#include "llvm/IR/Type.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000048#include "llvm/IR/User.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000049#include "llvm/IR/Value.h"
50#include "llvm/IR/ValueHandle.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000051#include "llvm/Support/AtomicOrdering.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000052#include "llvm/Support/Casting.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000053#include "llvm/Support/CommandLine.h"
54#include "llvm/Support/Compiler.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000055#include "llvm/Support/Debug.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000056#include "llvm/Support/ErrorHandling.h"
Craig Topperb45eabc2017-04-26 16:39:58 +000057#include "llvm/Support/KnownBits.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000058#include "llvm/Support/MathExtras.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000059#include "llvm/Support/raw_ostream.h"
60#include "llvm/Transforms/InstCombine/InstCombineWorklist.h"
Chandler Carruthba4c5172015-01-21 11:23:40 +000061#include "llvm/Transforms/Utils/SimplifyLibCalls.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000062#include <algorithm>
63#include <cassert>
64#include <cstdint>
65#include <cstring>
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000066#include <utility>
Eugene Zelenkocdc71612016-08-11 17:20:18 +000067#include <vector>
68
Chris Lattner7a9e47a2010-01-05 07:32:13 +000069using namespace llvm;
Michael Ilseman536cc322012-12-13 03:13:36 +000070using namespace PatternMatch;
Chris Lattner7a9e47a2010-01-05 07:32:13 +000071
Chandler Carruth964daaa2014-04-22 02:55:47 +000072#define DEBUG_TYPE "instcombine"
73
Meador Ingee3f2b262012-11-30 04:05:06 +000074STATISTIC(NumSimplified, "Number of library calls simplified");
75
Philip Reames79e917d2018-05-09 22:56:32 +000076static cl::opt<unsigned> GuardWideningWindow(
77 "instcombine-guard-widening-window",
78 cl::init(3),
79 cl::desc("How wide an instruction window to bypass looking for "
80 "another guard"));
81
Sanjay Patelcd4377c2016-01-20 22:24:38 +000082/// Return the specified type promoted as it would be to pass though a va_arg
83/// area.
Chris Lattner229907c2011-07-18 04:54:35 +000084static Type *getPromotedType(Type *Ty) {
85 if (IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +000086 if (ITy->getBitWidth() < 32)
87 return Type::getInt32Ty(Ty->getContext());
88 }
89 return Ty;
90}
91
Sanjay Patel368ac5d2016-02-21 17:29:33 +000092/// Return a constant boolean vector that has true elements in all positions
Sanjay Patel24401302016-02-21 17:33:31 +000093/// where the input constant data vector has an element with the sign bit set.
Sanjay Patel368ac5d2016-02-21 17:29:33 +000094static Constant *getNegativeIsTrueBoolVec(ConstantDataVector *V) {
95 SmallVector<Constant *, 32> BoolVec;
96 IntegerType *BoolTy = Type::getInt1Ty(V->getContext());
97 for (unsigned I = 0, E = V->getNumElements(); I != E; ++I) {
98 Constant *Elt = V->getElementAsConstant(I);
99 assert((isa<ConstantInt>(Elt) || isa<ConstantFP>(Elt)) &&
100 "Unexpected constant data vector element type");
101 bool Sign = V->getElementType()->isIntegerTy()
102 ? cast<ConstantInt>(Elt)->isNegative()
103 : cast<ConstantFP>(Elt)->isNegative();
104 BoolVec.push_back(ConstantInt::get(BoolTy, Sign));
105 }
106 return ConstantVector::get(BoolVec);
107}
108
Daniel Neilson8f30ec62018-05-11 14:30:02 +0000109Instruction *InstCombiner::SimplifyAnyMemTransfer(AnyMemTransferInst *MI) {
Daniel Neilson2363da92018-02-12 23:06:55 +0000110 unsigned DstAlign = getKnownAlignment(MI->getRawDest(), DL, MI, &AC, &DT);
111 unsigned CopyDstAlign = MI->getDestAlignment();
112 if (CopyDstAlign < DstAlign){
113 MI->setDestAlignment(DstAlign);
114 return MI;
115 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000116
Daniel Neilson8f30ec62018-05-11 14:30:02 +0000117 unsigned SrcAlign = getKnownAlignment(MI->getRawSource(), DL, MI, &AC, &DT);
118 unsigned CopySrcAlign = MI->getSourceAlignment();
Daniel Neilson2363da92018-02-12 23:06:55 +0000119 if (CopySrcAlign < SrcAlign) {
Daniel Neilson8f30ec62018-05-11 14:30:02 +0000120 MI->setSourceAlignment(SrcAlign);
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000121 return MI;
122 }
Jim Grosbach7815f562012-02-03 00:07:04 +0000123
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000124 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
125 // load/store.
Daniel Neilson8f30ec62018-05-11 14:30:02 +0000126 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getLength());
Craig Topperf40110f2014-04-25 05:29:35 +0000127 if (!MemOpLength) return nullptr;
Jim Grosbach7815f562012-02-03 00:07:04 +0000128
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000129 // Source and destination pointer types are always "i8*" for intrinsic. See
130 // if the size is something we can handle with a single primitive load/store.
131 // A single load+store correctly handles overlapping memory in the memmove
132 // case.
Michael Liao69e172a2012-08-15 03:49:59 +0000133 uint64_t Size = MemOpLength->getLimitedValue();
Alp Tokercb402912014-01-24 17:20:08 +0000134 assert(Size && "0-sized memory transferring should be removed already.");
Jim Grosbach7815f562012-02-03 00:07:04 +0000135
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000136 if (Size > 8 || (Size&(Size-1)))
Craig Topperf40110f2014-04-25 05:29:35 +0000137 return nullptr; // If not 1/2/4/8 bytes, exit.
Jim Grosbach7815f562012-02-03 00:07:04 +0000138
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000139 // Use an integer load+store unless we can find something better.
Mon P Wangc576ee92010-04-04 03:10:48 +0000140 unsigned SrcAddrSp =
Gabor Greif0a136c92010-06-24 13:54:33 +0000141 cast<PointerType>(MI->getArgOperand(1)->getType())->getAddressSpace();
Gabor Greiff3755202010-04-16 15:33:14 +0000142 unsigned DstAddrSp =
Gabor Greif0a136c92010-06-24 13:54:33 +0000143 cast<PointerType>(MI->getArgOperand(0)->getType())->getAddressSpace();
Mon P Wangc576ee92010-04-04 03:10:48 +0000144
Chris Lattner229907c2011-07-18 04:54:35 +0000145 IntegerType* IntType = IntegerType::get(MI->getContext(), Size<<3);
Mon P Wangc576ee92010-04-04 03:10:48 +0000146 Type *NewSrcPtrTy = PointerType::get(IntType, SrcAddrSp);
147 Type *NewDstPtrTy = PointerType::get(IntType, DstAddrSp);
Jim Grosbach7815f562012-02-03 00:07:04 +0000148
Mikael Holmen760dc9a2017-03-01 06:45:20 +0000149 // If the memcpy has metadata describing the members, see if we can get the
150 // TBAA tag describing our copy.
Craig Topperf40110f2014-04-25 05:29:35 +0000151 MDNode *CopyMD = nullptr;
Ivan A. Kosarevf03f5792018-02-19 12:10:20 +0000152 if (MDNode *M = MI->getMetadata(LLVMContext::MD_tbaa)) {
153 CopyMD = M;
154 } else if (MDNode *M = MI->getMetadata(LLVMContext::MD_tbaa_struct)) {
Mikael Holmen760dc9a2017-03-01 06:45:20 +0000155 if (M->getNumOperands() == 3 && M->getOperand(0) &&
156 mdconst::hasa<ConstantInt>(M->getOperand(0)) &&
Craig Topper79ab6432017-07-06 18:39:47 +0000157 mdconst::extract<ConstantInt>(M->getOperand(0))->isZero() &&
Mikael Holmen760dc9a2017-03-01 06:45:20 +0000158 M->getOperand(1) &&
159 mdconst::hasa<ConstantInt>(M->getOperand(1)) &&
160 mdconst::extract<ConstantInt>(M->getOperand(1))->getValue() ==
161 Size &&
162 M->getOperand(2) && isa<MDNode>(M->getOperand(2)))
163 CopyMD = cast<MDNode>(M->getOperand(2));
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000164 }
Jim Grosbach7815f562012-02-03 00:07:04 +0000165
Craig Topperbb4069e2017-07-07 23:16:26 +0000166 Value *Src = Builder.CreateBitCast(MI->getArgOperand(1), NewSrcPtrTy);
167 Value *Dest = Builder.CreateBitCast(MI->getArgOperand(0), NewDstPtrTy);
Daniel Neilson8f30ec62018-05-11 14:30:02 +0000168 LoadInst *L = Builder.CreateLoad(Src);
Daniel Neilson2363da92018-02-12 23:06:55 +0000169 // Alignment from the mem intrinsic will be better, so use it.
170 L->setAlignment(CopySrcAlign);
Dan Gohman3f553c22012-09-13 21:51:01 +0000171 if (CopyMD)
172 L->setMetadata(LLVMContext::MD_tbaa, CopyMD);
Dorit Nuzmanabd15f62016-09-04 07:49:39 +0000173 MDNode *LoopMemParallelMD =
174 MI->getMetadata(LLVMContext::MD_mem_parallel_loop_access);
175 if (LoopMemParallelMD)
176 L->setMetadata(LLVMContext::MD_mem_parallel_loop_access, LoopMemParallelMD);
Dorit Nuzman7673ba72016-09-04 07:06:00 +0000177
Daniel Neilson8f30ec62018-05-11 14:30:02 +0000178 StoreInst *S = Builder.CreateStore(L, Dest);
Daniel Neilson2363da92018-02-12 23:06:55 +0000179 // Alignment from the mem intrinsic will be better, so use it.
180 S->setAlignment(CopyDstAlign);
Dan Gohman3f553c22012-09-13 21:51:01 +0000181 if (CopyMD)
182 S->setMetadata(LLVMContext::MD_tbaa, CopyMD);
Dorit Nuzmanabd15f62016-09-04 07:49:39 +0000183 if (LoopMemParallelMD)
184 S->setMetadata(LLVMContext::MD_mem_parallel_loop_access, LoopMemParallelMD);
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000185
Daniel Neilson8f30ec62018-05-11 14:30:02 +0000186 if (auto *MT = dyn_cast<MemTransferInst>(MI)) {
187 // non-atomics can be volatile
188 L->setVolatile(MT->isVolatile());
189 S->setVolatile(MT->isVolatile());
190 }
191 if (isa<AtomicMemTransferInst>(MI)) {
192 // atomics have to be unordered
193 L->setOrdering(AtomicOrdering::Unordered);
194 S->setOrdering(AtomicOrdering::Unordered);
195 }
196
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000197 // Set the size of the copy to 0, it will be deleted on the next iteration.
Daniel Neilson8f30ec62018-05-11 14:30:02 +0000198 MI->setLength(Constant::getNullValue(MemOpLength->getType()));
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000199 return MI;
200}
201
Daniel Neilsonf6651d42018-05-11 20:04:50 +0000202Instruction *InstCombiner::SimplifyAnyMemSet(AnyMemSetInst *MI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000203 unsigned Alignment = getKnownAlignment(MI->getDest(), DL, MI, &AC, &DT);
Daniel Neilson38af2ee2018-02-02 22:03:03 +0000204 if (MI->getDestAlignment() < Alignment) {
205 MI->setDestAlignment(Alignment);
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000206 return MI;
207 }
Jim Grosbach7815f562012-02-03 00:07:04 +0000208
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000209 // Extract the length and alignment and fill if they are constant.
210 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
211 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
Duncan Sands9dff9be2010-02-15 16:12:20 +0000212 if (!LenC || !FillC || !FillC->getType()->isIntegerTy(8))
Craig Topperf40110f2014-04-25 05:29:35 +0000213 return nullptr;
Michael Liao69e172a2012-08-15 03:49:59 +0000214 uint64_t Len = LenC->getLimitedValue();
Daniel Neilson710d7b92018-03-22 18:36:15 +0000215 Alignment = MI->getDestAlignment();
Michael Liao69e172a2012-08-15 03:49:59 +0000216 assert(Len && "0-sized memory setting should be removed already.");
Jim Grosbach7815f562012-02-03 00:07:04 +0000217
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000218 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
219 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
Chris Lattner229907c2011-07-18 04:54:35 +0000220 Type *ITy = IntegerType::get(MI->getContext(), Len*8); // n=1 -> i8.
Jim Grosbach7815f562012-02-03 00:07:04 +0000221
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000222 Value *Dest = MI->getDest();
Mon P Wang1991c472010-12-20 01:05:30 +0000223 unsigned DstAddrSp = cast<PointerType>(Dest->getType())->getAddressSpace();
224 Type *NewDstPtrTy = PointerType::get(ITy, DstAddrSp);
Craig Topperbb4069e2017-07-07 23:16:26 +0000225 Dest = Builder.CreateBitCast(Dest, NewDstPtrTy);
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000226
227 // Alignment 0 is identity for alignment 1 for memset, but not store.
228 if (Alignment == 0) Alignment = 1;
Jim Grosbach7815f562012-02-03 00:07:04 +0000229
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000230 // Extract the fill value and store.
231 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
Craig Topperbb4069e2017-07-07 23:16:26 +0000232 StoreInst *S = Builder.CreateStore(ConstantInt::get(ITy, Fill), Dest,
233 MI->isVolatile());
Eli Friedman49346012011-05-18 19:57:14 +0000234 S->setAlignment(Alignment);
Daniel Neilsonf6651d42018-05-11 20:04:50 +0000235 if (isa<AtomicMemSetInst>(MI))
236 S->setOrdering(AtomicOrdering::Unordered);
Jim Grosbach7815f562012-02-03 00:07:04 +0000237
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000238 // Set the size of the copy to 0, it will be deleted on the next iteration.
239 MI->setLength(Constant::getNullValue(LenC->getType()));
240 return MI;
241 }
242
Simon Pilgrim18617d12015-08-05 08:18:00 +0000243 return nullptr;
244}
245
Tomasz Krupae766e5f2018-08-14 09:04:01 +0000246static Value *simplifyX86AddsSubs(const IntrinsicInst &II,
247 InstCombiner::BuilderTy &Builder) {
248 bool IsAddition = false;
249 bool IsMasked = false;
250
251 switch (II.getIntrinsicID()) {
252 default: llvm_unreachable("Unexpected intrinsic!");
253 case Intrinsic::x86_sse2_padds_b:
254 case Intrinsic::x86_sse2_padds_w:
255 case Intrinsic::x86_avx2_padds_b:
256 case Intrinsic::x86_avx2_padds_w:
257 IsAddition = true; IsMasked = false;
258 break;
259 case Intrinsic::x86_sse2_psubs_b:
260 case Intrinsic::x86_sse2_psubs_w:
261 case Intrinsic::x86_avx2_psubs_b:
262 case Intrinsic::x86_avx2_psubs_w:
263 IsAddition = false; IsMasked = false;
264 break;
265 case Intrinsic::x86_avx512_mask_padds_b_512:
266 case Intrinsic::x86_avx512_mask_padds_w_512:
267 IsAddition = true; IsMasked = true;
268 break;
269 case Intrinsic::x86_avx512_mask_psubs_b_512:
270 case Intrinsic::x86_avx512_mask_psubs_w_512:
271 IsAddition = false; IsMasked = true;
272 break;
273 }
274
275 auto *Arg0 = dyn_cast<Constant>(II.getOperand(0));
276 auto *Arg1 = dyn_cast<Constant>(II.getOperand(1));
277 auto VT = cast<VectorType>(II.getType());
278 auto SVT = VT->getElementType();
279 unsigned NumElems = VT->getNumElements();
280
281 if (!Arg0 || !Arg1 || (IsMasked && !isa<Constant>(II.getOperand(2))))
282 return nullptr;
283
284 SmallVector<Constant *, 64> Result;
285
286 APInt MaxValue = APInt::getSignedMaxValue(SVT->getIntegerBitWidth());
287 APInt MinValue = APInt::getSignedMinValue(SVT->getIntegerBitWidth());
288 for (unsigned i = 0; i < NumElems; ++i) {
289 auto *Elt0 = Arg0->getAggregateElement(i);
290 auto *Elt1 = Arg1->getAggregateElement(i);
291 if (isa<UndefValue>(Elt0) || isa<UndefValue>(Elt1)) {
292 Result.push_back(UndefValue::get(SVT));
293 continue;
294 }
295
296 if (!isa<ConstantInt>(Elt0) || !isa<ConstantInt>(Elt1))
297 return nullptr;
298
299 const APInt &Val0 = cast<ConstantInt>(Elt0)->getValue();
300 const APInt &Val1 = cast<ConstantInt>(Elt1)->getValue();
301 bool Overflow = false;
302 APInt ResultElem = IsAddition ? Val0.sadd_ov(Val1, Overflow)
303 : Val0.ssub_ov(Val1, Overflow);
304 if (Overflow)
305 ResultElem = Val0.isNegative() ? MinValue : MaxValue;
306 Result.push_back(Constant::getIntegerValue(SVT, ResultElem));
307 }
308
309 Value *ResultVec = ConstantVector::get(Result);
310
311 if (II.getNumArgOperands() == 4) { // For masked intrinsics.
312 Value *Src = II.getOperand(2);
313 auto Mask = II.getOperand(3);
314 if (auto *C = dyn_cast<Constant>(Mask))
315 if (C->isAllOnesValue())
316 return ResultVec;
317 auto *MaskTy = VectorType::get(
318 Builder.getInt1Ty(), cast<IntegerType>(Mask->getType())->getBitWidth());
319 Mask = Builder.CreateBitCast(Mask, MaskTy);
320 ResultVec = Builder.CreateSelect(Mask, ResultVec, Src);
321 }
322
323 return ResultVec;
324}
325
Sanjay Patel6038d3e2016-01-29 23:27:03 +0000326static Value *simplifyX86immShift(const IntrinsicInst &II,
Simon Pilgrimbecd5e82015-08-13 07:39:03 +0000327 InstCombiner::BuilderTy &Builder) {
328 bool LogicalShift = false;
329 bool ShiftLeft = false;
330
331 switch (II.getIntrinsicID()) {
Craig Topperb4173a52016-11-13 07:26:19 +0000332 default: llvm_unreachable("Unexpected intrinsic!");
Simon Pilgrimbecd5e82015-08-13 07:39:03 +0000333 case Intrinsic::x86_sse2_psra_d:
334 case Intrinsic::x86_sse2_psra_w:
335 case Intrinsic::x86_sse2_psrai_d:
336 case Intrinsic::x86_sse2_psrai_w:
337 case Intrinsic::x86_avx2_psra_d:
338 case Intrinsic::x86_avx2_psra_w:
339 case Intrinsic::x86_avx2_psrai_d:
340 case Intrinsic::x86_avx2_psrai_w:
Craig Topper8b831cb2016-11-13 01:51:55 +0000341 case Intrinsic::x86_avx512_psra_q_128:
342 case Intrinsic::x86_avx512_psrai_q_128:
343 case Intrinsic::x86_avx512_psra_q_256:
344 case Intrinsic::x86_avx512_psrai_q_256:
345 case Intrinsic::x86_avx512_psra_d_512:
346 case Intrinsic::x86_avx512_psra_q_512:
347 case Intrinsic::x86_avx512_psra_w_512:
348 case Intrinsic::x86_avx512_psrai_d_512:
349 case Intrinsic::x86_avx512_psrai_q_512:
350 case Intrinsic::x86_avx512_psrai_w_512:
Simon Pilgrimbecd5e82015-08-13 07:39:03 +0000351 LogicalShift = false; ShiftLeft = false;
352 break;
353 case Intrinsic::x86_sse2_psrl_d:
354 case Intrinsic::x86_sse2_psrl_q:
355 case Intrinsic::x86_sse2_psrl_w:
356 case Intrinsic::x86_sse2_psrli_d:
357 case Intrinsic::x86_sse2_psrli_q:
358 case Intrinsic::x86_sse2_psrli_w:
359 case Intrinsic::x86_avx2_psrl_d:
360 case Intrinsic::x86_avx2_psrl_q:
361 case Intrinsic::x86_avx2_psrl_w:
362 case Intrinsic::x86_avx2_psrli_d:
363 case Intrinsic::x86_avx2_psrli_q:
364 case Intrinsic::x86_avx2_psrli_w:
Craig Topper8b831cb2016-11-13 01:51:55 +0000365 case Intrinsic::x86_avx512_psrl_d_512:
366 case Intrinsic::x86_avx512_psrl_q_512:
367 case Intrinsic::x86_avx512_psrl_w_512:
368 case Intrinsic::x86_avx512_psrli_d_512:
369 case Intrinsic::x86_avx512_psrli_q_512:
370 case Intrinsic::x86_avx512_psrli_w_512:
Simon Pilgrimbecd5e82015-08-13 07:39:03 +0000371 LogicalShift = true; ShiftLeft = false;
372 break;
373 case Intrinsic::x86_sse2_psll_d:
374 case Intrinsic::x86_sse2_psll_q:
375 case Intrinsic::x86_sse2_psll_w:
376 case Intrinsic::x86_sse2_pslli_d:
377 case Intrinsic::x86_sse2_pslli_q:
378 case Intrinsic::x86_sse2_pslli_w:
379 case Intrinsic::x86_avx2_psll_d:
380 case Intrinsic::x86_avx2_psll_q:
381 case Intrinsic::x86_avx2_psll_w:
382 case Intrinsic::x86_avx2_pslli_d:
383 case Intrinsic::x86_avx2_pslli_q:
384 case Intrinsic::x86_avx2_pslli_w:
Craig Topper8b831cb2016-11-13 01:51:55 +0000385 case Intrinsic::x86_avx512_psll_d_512:
386 case Intrinsic::x86_avx512_psll_q_512:
387 case Intrinsic::x86_avx512_psll_w_512:
388 case Intrinsic::x86_avx512_pslli_d_512:
389 case Intrinsic::x86_avx512_pslli_q_512:
390 case Intrinsic::x86_avx512_pslli_w_512:
Simon Pilgrimbecd5e82015-08-13 07:39:03 +0000391 LogicalShift = true; ShiftLeft = true;
392 break;
393 }
Simon Pilgrima3a72b42015-08-10 20:21:15 +0000394 assert((LogicalShift || !ShiftLeft) && "Only logical shifts can shift left");
395
Simon Pilgrim3815c162015-08-07 18:22:50 +0000396 // Simplify if count is constant.
397 auto Arg1 = II.getArgOperand(1);
398 auto CAZ = dyn_cast<ConstantAggregateZero>(Arg1);
399 auto CDV = dyn_cast<ConstantDataVector>(Arg1);
400 auto CInt = dyn_cast<ConstantInt>(Arg1);
401 if (!CAZ && !CDV && !CInt)
Simon Pilgrim18617d12015-08-05 08:18:00 +0000402 return nullptr;
Simon Pilgrim3815c162015-08-07 18:22:50 +0000403
404 APInt Count(64, 0);
405 if (CDV) {
406 // SSE2/AVX2 uses all the first 64-bits of the 128-bit vector
407 // operand to compute the shift amount.
408 auto VT = cast<VectorType>(CDV->getType());
409 unsigned BitWidth = VT->getElementType()->getPrimitiveSizeInBits();
410 assert((64 % BitWidth) == 0 && "Unexpected packed shift size");
411 unsigned NumSubElts = 64 / BitWidth;
412
413 // Concatenate the sub-elements to create the 64-bit value.
414 for (unsigned i = 0; i != NumSubElts; ++i) {
415 unsigned SubEltIdx = (NumSubElts - 1) - i;
416 auto SubElt = cast<ConstantInt>(CDV->getElementAsConstant(SubEltIdx));
Craig Topper24e71012017-04-28 03:36:24 +0000417 Count <<= BitWidth;
Simon Pilgrim3815c162015-08-07 18:22:50 +0000418 Count |= SubElt->getValue().zextOrTrunc(64);
419 }
420 }
421 else if (CInt)
422 Count = CInt->getValue();
Simon Pilgrim18617d12015-08-05 08:18:00 +0000423
424 auto Vec = II.getArgOperand(0);
425 auto VT = cast<VectorType>(Vec->getType());
426 auto SVT = VT->getElementType();
Simon Pilgrim3815c162015-08-07 18:22:50 +0000427 unsigned VWidth = VT->getNumElements();
428 unsigned BitWidth = SVT->getPrimitiveSizeInBits();
429
430 // If shift-by-zero then just return the original value.
Craig Topper73ba1c82017-06-07 07:40:37 +0000431 if (Count.isNullValue())
Simon Pilgrim3815c162015-08-07 18:22:50 +0000432 return Vec;
433
Simon Pilgrima3a72b42015-08-10 20:21:15 +0000434 // Handle cases when Shift >= BitWidth.
435 if (Count.uge(BitWidth)) {
436 // If LogicalShift - just return zero.
437 if (LogicalShift)
438 return ConstantAggregateZero::get(VT);
439
440 // If ArithmeticShift - clamp Shift to (BitWidth - 1).
441 Count = APInt(64, BitWidth - 1);
442 }
Simon Pilgrim18617d12015-08-05 08:18:00 +0000443
Simon Pilgrim18617d12015-08-05 08:18:00 +0000444 // Get a constant vector of the same type as the first operand.
Simon Pilgrim3815c162015-08-07 18:22:50 +0000445 auto ShiftAmt = ConstantInt::get(SVT, Count.zextOrTrunc(BitWidth));
446 auto ShiftVec = Builder.CreateVectorSplat(VWidth, ShiftAmt);
Simon Pilgrim18617d12015-08-05 08:18:00 +0000447
448 if (ShiftLeft)
Simon Pilgrim3815c162015-08-07 18:22:50 +0000449 return Builder.CreateShl(Vec, ShiftVec);
Simon Pilgrim18617d12015-08-05 08:18:00 +0000450
Simon Pilgrima3a72b42015-08-10 20:21:15 +0000451 if (LogicalShift)
452 return Builder.CreateLShr(Vec, ShiftVec);
453
454 return Builder.CreateAShr(Vec, ShiftVec);
Simon Pilgrim18617d12015-08-05 08:18:00 +0000455}
456
Simon Pilgrimdb9893f2016-06-07 10:27:15 +0000457// Attempt to simplify AVX2 per-element shift intrinsics to a generic IR shift.
458// Unlike the generic IR shifts, the intrinsics have defined behaviour for out
459// of range shift amounts (logical - set to zero, arithmetic - splat sign bit).
460static Value *simplifyX86varShift(const IntrinsicInst &II,
461 InstCombiner::BuilderTy &Builder) {
462 bool LogicalShift = false;
463 bool ShiftLeft = false;
464
465 switch (II.getIntrinsicID()) {
Craig Topperb4173a52016-11-13 07:26:19 +0000466 default: llvm_unreachable("Unexpected intrinsic!");
Simon Pilgrimdb9893f2016-06-07 10:27:15 +0000467 case Intrinsic::x86_avx2_psrav_d:
468 case Intrinsic::x86_avx2_psrav_d_256:
Craig Topperb4173a52016-11-13 07:26:19 +0000469 case Intrinsic::x86_avx512_psrav_q_128:
470 case Intrinsic::x86_avx512_psrav_q_256:
471 case Intrinsic::x86_avx512_psrav_d_512:
472 case Intrinsic::x86_avx512_psrav_q_512:
Craig Topper1de753f2016-11-18 06:04:33 +0000473 case Intrinsic::x86_avx512_psrav_w_128:
474 case Intrinsic::x86_avx512_psrav_w_256:
475 case Intrinsic::x86_avx512_psrav_w_512:
Simon Pilgrimdb9893f2016-06-07 10:27:15 +0000476 LogicalShift = false;
477 ShiftLeft = false;
478 break;
479 case Intrinsic::x86_avx2_psrlv_d:
480 case Intrinsic::x86_avx2_psrlv_d_256:
481 case Intrinsic::x86_avx2_psrlv_q:
482 case Intrinsic::x86_avx2_psrlv_q_256:
Craig Topperb4173a52016-11-13 07:26:19 +0000483 case Intrinsic::x86_avx512_psrlv_d_512:
484 case Intrinsic::x86_avx512_psrlv_q_512:
Craig Topper1de753f2016-11-18 06:04:33 +0000485 case Intrinsic::x86_avx512_psrlv_w_128:
486 case Intrinsic::x86_avx512_psrlv_w_256:
487 case Intrinsic::x86_avx512_psrlv_w_512:
Simon Pilgrimdb9893f2016-06-07 10:27:15 +0000488 LogicalShift = true;
489 ShiftLeft = false;
490 break;
491 case Intrinsic::x86_avx2_psllv_d:
492 case Intrinsic::x86_avx2_psllv_d_256:
493 case Intrinsic::x86_avx2_psllv_q:
494 case Intrinsic::x86_avx2_psllv_q_256:
Craig Topperb4173a52016-11-13 07:26:19 +0000495 case Intrinsic::x86_avx512_psllv_d_512:
496 case Intrinsic::x86_avx512_psllv_q_512:
Craig Topper1de753f2016-11-18 06:04:33 +0000497 case Intrinsic::x86_avx512_psllv_w_128:
498 case Intrinsic::x86_avx512_psllv_w_256:
499 case Intrinsic::x86_avx512_psllv_w_512:
Simon Pilgrimdb9893f2016-06-07 10:27:15 +0000500 LogicalShift = true;
501 ShiftLeft = true;
502 break;
503 }
504 assert((LogicalShift || !ShiftLeft) && "Only logical shifts can shift left");
505
506 // Simplify if all shift amounts are constant/undef.
507 auto *CShift = dyn_cast<Constant>(II.getArgOperand(1));
508 if (!CShift)
509 return nullptr;
510
511 auto Vec = II.getArgOperand(0);
512 auto VT = cast<VectorType>(II.getType());
513 auto SVT = VT->getVectorElementType();
514 int NumElts = VT->getNumElements();
515 int BitWidth = SVT->getIntegerBitWidth();
516
517 // Collect each element's shift amount.
518 // We also collect special cases: UNDEF = -1, OUT-OF-RANGE = BitWidth.
519 bool AnyOutOfRange = false;
520 SmallVector<int, 8> ShiftAmts;
521 for (int I = 0; I < NumElts; ++I) {
522 auto *CElt = CShift->getAggregateElement(I);
523 if (CElt && isa<UndefValue>(CElt)) {
524 ShiftAmts.push_back(-1);
525 continue;
526 }
527
528 auto *COp = dyn_cast_or_null<ConstantInt>(CElt);
529 if (!COp)
530 return nullptr;
531
532 // Handle out of range shifts.
533 // If LogicalShift - set to BitWidth (special case).
534 // If ArithmeticShift - set to (BitWidth - 1) (sign splat).
535 APInt ShiftVal = COp->getValue();
536 if (ShiftVal.uge(BitWidth)) {
537 AnyOutOfRange = LogicalShift;
538 ShiftAmts.push_back(LogicalShift ? BitWidth : BitWidth - 1);
539 continue;
540 }
541
542 ShiftAmts.push_back((int)ShiftVal.getZExtValue());
543 }
544
545 // If all elements out of range or UNDEF, return vector of zeros/undefs.
546 // ArithmeticShift should only hit this if they are all UNDEF.
547 auto OutOfRange = [&](int Idx) { return (Idx < 0) || (BitWidth <= Idx); };
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000548 if (llvm::all_of(ShiftAmts, OutOfRange)) {
Simon Pilgrimdb9893f2016-06-07 10:27:15 +0000549 SmallVector<Constant *, 8> ConstantVec;
550 for (int Idx : ShiftAmts) {
551 if (Idx < 0) {
552 ConstantVec.push_back(UndefValue::get(SVT));
553 } else {
554 assert(LogicalShift && "Logical shift expected");
555 ConstantVec.push_back(ConstantInt::getNullValue(SVT));
556 }
557 }
558 return ConstantVector::get(ConstantVec);
559 }
560
561 // We can't handle only some out of range values with generic logical shifts.
562 if (AnyOutOfRange)
563 return nullptr;
564
565 // Build the shift amount constant vector.
566 SmallVector<Constant *, 8> ShiftVecAmts;
567 for (int Idx : ShiftAmts) {
568 if (Idx < 0)
569 ShiftVecAmts.push_back(UndefValue::get(SVT));
570 else
571 ShiftVecAmts.push_back(ConstantInt::get(SVT, Idx));
572 }
573 auto ShiftVec = ConstantVector::get(ShiftVecAmts);
574
575 if (ShiftLeft)
576 return Builder.CreateShl(Vec, ShiftVec);
577
578 if (LogicalShift)
579 return Builder.CreateLShr(Vec, ShiftVec);
580
581 return Builder.CreateAShr(Vec, ShiftVec);
582}
583
Craig Topper4853c432017-07-06 23:18:42 +0000584static Value *simplifyX86pack(IntrinsicInst &II, bool IsSigned) {
Simon Pilgrim6f6b2792017-01-25 14:37:24 +0000585 Value *Arg0 = II.getArgOperand(0);
586 Value *Arg1 = II.getArgOperand(1);
587 Type *ResTy = II.getType();
588
589 // Fast all undef handling.
590 if (isa<UndefValue>(Arg0) && isa<UndefValue>(Arg1))
591 return UndefValue::get(ResTy);
592
593 Type *ArgTy = Arg0->getType();
594 unsigned NumLanes = ResTy->getPrimitiveSizeInBits() / 128;
595 unsigned NumDstElts = ResTy->getVectorNumElements();
596 unsigned NumSrcElts = ArgTy->getVectorNumElements();
597 assert(NumDstElts == (2 * NumSrcElts) && "Unexpected packing types");
598
599 unsigned NumDstEltsPerLane = NumDstElts / NumLanes;
600 unsigned NumSrcEltsPerLane = NumSrcElts / NumLanes;
601 unsigned DstScalarSizeInBits = ResTy->getScalarSizeInBits();
602 assert(ArgTy->getScalarSizeInBits() == (2 * DstScalarSizeInBits) &&
603 "Unexpected packing types");
604
605 // Constant folding.
606 auto *Cst0 = dyn_cast<Constant>(Arg0);
607 auto *Cst1 = dyn_cast<Constant>(Arg1);
608 if (!Cst0 || !Cst1)
609 return nullptr;
610
611 SmallVector<Constant *, 32> Vals;
612 for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
613 for (unsigned Elt = 0; Elt != NumDstEltsPerLane; ++Elt) {
614 unsigned SrcIdx = Lane * NumSrcEltsPerLane + Elt % NumSrcEltsPerLane;
615 auto *Cst = (Elt >= NumSrcEltsPerLane) ? Cst1 : Cst0;
616 auto *COp = Cst->getAggregateElement(SrcIdx);
617 if (COp && isa<UndefValue>(COp)) {
618 Vals.push_back(UndefValue::get(ResTy->getScalarType()));
619 continue;
620 }
621
622 auto *CInt = dyn_cast_or_null<ConstantInt>(COp);
623 if (!CInt)
624 return nullptr;
625
626 APInt Val = CInt->getValue();
627 assert(Val.getBitWidth() == ArgTy->getScalarSizeInBits() &&
628 "Unexpected constant bitwidth");
629
630 if (IsSigned) {
631 // PACKSS: Truncate signed value with signed saturation.
632 // Source values less than dst minint are saturated to minint.
633 // Source values greater than dst maxint are saturated to maxint.
634 if (Val.isSignedIntN(DstScalarSizeInBits))
635 Val = Val.trunc(DstScalarSizeInBits);
636 else if (Val.isNegative())
637 Val = APInt::getSignedMinValue(DstScalarSizeInBits);
638 else
639 Val = APInt::getSignedMaxValue(DstScalarSizeInBits);
640 } else {
641 // PACKUS: Truncate signed value with unsigned saturation.
642 // Source values less than zero are saturated to zero.
643 // Source values greater than dst maxuint are saturated to maxuint.
644 if (Val.isIntN(DstScalarSizeInBits))
645 Val = Val.trunc(DstScalarSizeInBits);
646 else if (Val.isNegative())
647 Val = APInt::getNullValue(DstScalarSizeInBits);
648 else
649 Val = APInt::getAllOnesValue(DstScalarSizeInBits);
650 }
651
652 Vals.push_back(ConstantInt::get(ResTy->getScalarType(), Val));
653 }
654 }
655
656 return ConstantVector::get(Vals);
657}
658
Mikhail Dvoretckii8393f902018-06-19 10:49:12 +0000659// Replace X86-specific intrinsics with generic floor-ceil where applicable.
660static Value *simplifyX86round(IntrinsicInst &II,
661 InstCombiner::BuilderTy &Builder) {
662 ConstantInt *Arg = nullptr;
663 Intrinsic::ID IntrinsicID = II.getIntrinsicID();
664
665 if (IntrinsicID == Intrinsic::x86_sse41_round_ss ||
666 IntrinsicID == Intrinsic::x86_sse41_round_sd)
667 Arg = dyn_cast<ConstantInt>(II.getArgOperand(2));
668 else if (IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_ss ||
669 IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_sd)
670 Arg = dyn_cast<ConstantInt>(II.getArgOperand(4));
671 else
672 Arg = dyn_cast<ConstantInt>(II.getArgOperand(1));
673 if (!Arg)
674 return nullptr;
675 unsigned RoundControl = Arg->getZExtValue();
676
677 Arg = nullptr;
678 unsigned SAE = 0;
679 if (IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_ps_512 ||
680 IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_pd_512)
681 Arg = dyn_cast<ConstantInt>(II.getArgOperand(4));
682 else if (IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_ss ||
683 IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_sd)
684 Arg = dyn_cast<ConstantInt>(II.getArgOperand(5));
685 else
686 SAE = 4;
687 if (!SAE) {
688 if (!Arg)
689 return nullptr;
690 SAE = Arg->getZExtValue();
691 }
692
693 if (SAE != 4 || (RoundControl != 2 /*ceil*/ && RoundControl != 1 /*floor*/))
694 return nullptr;
695
696 Value *Src, *Dst, *Mask;
697 bool IsScalar = false;
698 if (IntrinsicID == Intrinsic::x86_sse41_round_ss ||
699 IntrinsicID == Intrinsic::x86_sse41_round_sd ||
700 IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_ss ||
701 IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_sd) {
702 IsScalar = true;
703 if (IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_ss ||
704 IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_sd) {
705 Mask = II.getArgOperand(3);
706 Value *Zero = Constant::getNullValue(Mask->getType());
707 Mask = Builder.CreateAnd(Mask, 1);
708 Mask = Builder.CreateICmp(ICmpInst::ICMP_NE, Mask, Zero);
709 Dst = II.getArgOperand(2);
710 } else
711 Dst = II.getArgOperand(0);
712 Src = Builder.CreateExtractElement(II.getArgOperand(1), (uint64_t)0);
713 } else {
714 Src = II.getArgOperand(0);
715 if (IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_ps_128 ||
716 IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_ps_256 ||
717 IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_ps_512 ||
718 IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_pd_128 ||
719 IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_pd_256 ||
720 IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_pd_512) {
721 Dst = II.getArgOperand(2);
722 Mask = II.getArgOperand(3);
723 } else {
724 Dst = Src;
725 Mask = ConstantInt::getAllOnesValue(
726 Builder.getIntNTy(Src->getType()->getVectorNumElements()));
727 }
728 }
729
730 Intrinsic::ID ID = (RoundControl == 2) ? Intrinsic::ceil : Intrinsic::floor;
731 Value *Res = Builder.CreateIntrinsic(ID, {Src}, &II);
732 if (!IsScalar) {
733 if (auto *C = dyn_cast<Constant>(Mask))
734 if (C->isAllOnesValue())
735 return Res;
736 auto *MaskTy = VectorType::get(
737 Builder.getInt1Ty(), cast<IntegerType>(Mask->getType())->getBitWidth());
738 Mask = Builder.CreateBitCast(Mask, MaskTy);
739 unsigned Width = Src->getType()->getVectorNumElements();
740 if (MaskTy->getVectorNumElements() > Width) {
741 uint32_t Indices[4];
742 for (unsigned i = 0; i != Width; ++i)
743 Indices[i] = i;
744 Mask = Builder.CreateShuffleVector(Mask, Mask,
745 makeArrayRef(Indices, Width));
746 }
747 return Builder.CreateSelect(Mask, Res, Dst);
748 }
749 if (IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_ss ||
750 IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_sd) {
751 Dst = Builder.CreateExtractElement(Dst, (uint64_t)0);
752 Res = Builder.CreateSelect(Mask, Res, Dst);
753 Dst = II.getArgOperand(0);
754 }
755 return Builder.CreateInsertElement(Dst, Res, (uint64_t)0);
756}
757
Craig Topper4853c432017-07-06 23:18:42 +0000758static Value *simplifyX86movmsk(const IntrinsicInst &II) {
Simon Pilgrim91e3ac82016-06-07 08:18:35 +0000759 Value *Arg = II.getArgOperand(0);
760 Type *ResTy = II.getType();
761 Type *ArgTy = Arg->getType();
762
763 // movmsk(undef) -> zero as we must ensure the upper bits are zero.
764 if (isa<UndefValue>(Arg))
765 return Constant::getNullValue(ResTy);
766
767 // We can't easily peek through x86_mmx types.
768 if (!ArgTy->isVectorTy())
769 return nullptr;
770
771 auto *C = dyn_cast<Constant>(Arg);
772 if (!C)
773 return nullptr;
774
775 // Extract signbits of the vector input and pack into integer result.
776 APInt Result(ResTy->getPrimitiveSizeInBits(), 0);
777 for (unsigned I = 0, E = ArgTy->getVectorNumElements(); I != E; ++I) {
778 auto *COp = C->getAggregateElement(I);
779 if (!COp)
780 return nullptr;
781 if (isa<UndefValue>(COp))
782 continue;
783
784 auto *CInt = dyn_cast<ConstantInt>(COp);
785 auto *CFp = dyn_cast<ConstantFP>(COp);
786 if (!CInt && !CFp)
787 return nullptr;
788
789 if ((CInt && CInt->isNegative()) || (CFp && CFp->isNegative()))
790 Result.setBit(I);
791 }
792
793 return Constant::getIntegerValue(ResTy, Result);
794}
795
Sanjay Patel6038d3e2016-01-29 23:27:03 +0000796static Value *simplifyX86insertps(const IntrinsicInst &II,
Sanjay Patelc86867c2015-04-16 17:52:13 +0000797 InstCombiner::BuilderTy &Builder) {
Sanjay Patel03c03f52016-01-28 00:03:16 +0000798 auto *CInt = dyn_cast<ConstantInt>(II.getArgOperand(2));
799 if (!CInt)
800 return nullptr;
Simon Pilgrim54fcd622015-07-25 20:41:00 +0000801
Sanjay Patel03c03f52016-01-28 00:03:16 +0000802 VectorType *VecTy = cast<VectorType>(II.getType());
803 assert(VecTy->getNumElements() == 4 && "insertps with wrong vector type");
Sanjay Patelc86867c2015-04-16 17:52:13 +0000804
Sanjay Patel03c03f52016-01-28 00:03:16 +0000805 // The immediate permute control byte looks like this:
806 // [3:0] - zero mask for each 32-bit lane
807 // [5:4] - select one 32-bit destination lane
808 // [7:6] - select one 32-bit source lane
Sanjay Patelc86867c2015-04-16 17:52:13 +0000809
Sanjay Patel03c03f52016-01-28 00:03:16 +0000810 uint8_t Imm = CInt->getZExtValue();
811 uint8_t ZMask = Imm & 0xf;
812 uint8_t DestLane = (Imm >> 4) & 0x3;
813 uint8_t SourceLane = (Imm >> 6) & 0x3;
Sanjay Patelc1d20a32015-04-25 20:55:25 +0000814
Sanjay Patel03c03f52016-01-28 00:03:16 +0000815 ConstantAggregateZero *ZeroVector = ConstantAggregateZero::get(VecTy);
Sanjay Patelc86867c2015-04-16 17:52:13 +0000816
Sanjay Patel03c03f52016-01-28 00:03:16 +0000817 // If all zero mask bits are set, this was just a weird way to
818 // generate a zero vector.
819 if (ZMask == 0xf)
820 return ZeroVector;
Sanjay Patelc1d20a32015-04-25 20:55:25 +0000821
Sanjay Patel03c03f52016-01-28 00:03:16 +0000822 // Initialize by passing all of the first source bits through.
Craig Topper99d1eab2016-06-12 00:41:19 +0000823 uint32_t ShuffleMask[4] = { 0, 1, 2, 3 };
Sanjay Patelc1d20a32015-04-25 20:55:25 +0000824
Sanjay Patel03c03f52016-01-28 00:03:16 +0000825 // We may replace the second operand with the zero vector.
826 Value *V1 = II.getArgOperand(1);
827
828 if (ZMask) {
829 // If the zero mask is being used with a single input or the zero mask
830 // overrides the destination lane, this is a shuffle with the zero vector.
831 if ((II.getArgOperand(0) == II.getArgOperand(1)) ||
832 (ZMask & (1 << DestLane))) {
833 V1 = ZeroVector;
834 // We may still move 32-bits of the first source vector from one lane
835 // to another.
836 ShuffleMask[DestLane] = SourceLane;
837 // The zero mask may override the previous insert operation.
838 for (unsigned i = 0; i < 4; ++i)
839 if ((ZMask >> i) & 0x1)
840 ShuffleMask[i] = i + 4;
Sanjay Patelc1d20a32015-04-25 20:55:25 +0000841 } else {
Sanjay Patel03c03f52016-01-28 00:03:16 +0000842 // TODO: Model this case as 2 shuffles or a 'logical and' plus shuffle?
843 return nullptr;
Sanjay Patelc1d20a32015-04-25 20:55:25 +0000844 }
Sanjay Patel03c03f52016-01-28 00:03:16 +0000845 } else {
846 // Replace the selected destination lane with the selected source lane.
847 ShuffleMask[DestLane] = SourceLane + 4;
Sanjay Patelc86867c2015-04-16 17:52:13 +0000848 }
Sanjay Patel03c03f52016-01-28 00:03:16 +0000849
850 return Builder.CreateShuffleVector(II.getArgOperand(0), V1, ShuffleMask);
Sanjay Patelc86867c2015-04-16 17:52:13 +0000851}
852
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000853/// Attempt to simplify SSE4A EXTRQ/EXTRQI instructions using constant folding
854/// or conversion to a shuffle vector.
Sanjay Patel6038d3e2016-01-29 23:27:03 +0000855static Value *simplifyX86extrq(IntrinsicInst &II, Value *Op0,
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000856 ConstantInt *CILength, ConstantInt *CIIndex,
857 InstCombiner::BuilderTy &Builder) {
858 auto LowConstantHighUndef = [&](uint64_t Val) {
859 Type *IntTy64 = Type::getInt64Ty(II.getContext());
860 Constant *Args[] = {ConstantInt::get(IntTy64, Val),
861 UndefValue::get(IntTy64)};
862 return ConstantVector::get(Args);
863 };
864
865 // See if we're dealing with constant values.
866 Constant *C0 = dyn_cast<Constant>(Op0);
867 ConstantInt *CI0 =
Andrea Di Biagio8df5b9c2016-09-07 12:03:03 +0000868 C0 ? dyn_cast_or_null<ConstantInt>(C0->getAggregateElement((unsigned)0))
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000869 : nullptr;
870
871 // Attempt to constant fold.
872 if (CILength && CIIndex) {
873 // From AMD documentation: "The bit index and field length are each six
874 // bits in length other bits of the field are ignored."
875 APInt APIndex = CIIndex->getValue().zextOrTrunc(6);
876 APInt APLength = CILength->getValue().zextOrTrunc(6);
877
878 unsigned Index = APIndex.getZExtValue();
879
880 // From AMD documentation: "a value of zero in the field length is
881 // defined as length of 64".
882 unsigned Length = APLength == 0 ? 64 : APLength.getZExtValue();
883
884 // From AMD documentation: "If the sum of the bit index + length field
885 // is greater than 64, the results are undefined".
886 unsigned End = Index + Length;
887
888 // Note that both field index and field length are 8-bit quantities.
889 // Since variables 'Index' and 'Length' are unsigned values
890 // obtained from zero-extending field index and field length
891 // respectively, their sum should never wrap around.
892 if (End > 64)
893 return UndefValue::get(II.getType());
894
895 // If we are inserting whole bytes, we can convert this to a shuffle.
896 // Lowering can recognize EXTRQI shuffle masks.
897 if ((Length % 8) == 0 && (Index % 8) == 0) {
898 // Convert bit indices to byte indices.
899 Length /= 8;
900 Index /= 8;
901
902 Type *IntTy8 = Type::getInt8Ty(II.getContext());
903 Type *IntTy32 = Type::getInt32Ty(II.getContext());
904 VectorType *ShufTy = VectorType::get(IntTy8, 16);
905
906 SmallVector<Constant *, 16> ShuffleMask;
907 for (int i = 0; i != (int)Length; ++i)
908 ShuffleMask.push_back(
909 Constant::getIntegerValue(IntTy32, APInt(32, i + Index)));
910 for (int i = Length; i != 8; ++i)
911 ShuffleMask.push_back(
912 Constant::getIntegerValue(IntTy32, APInt(32, i + 16)));
913 for (int i = 8; i != 16; ++i)
914 ShuffleMask.push_back(UndefValue::get(IntTy32));
915
916 Value *SV = Builder.CreateShuffleVector(
917 Builder.CreateBitCast(Op0, ShufTy),
918 ConstantAggregateZero::get(ShufTy), ConstantVector::get(ShuffleMask));
919 return Builder.CreateBitCast(SV, II.getType());
920 }
921
922 // Constant Fold - shift Index'th bit to lowest position and mask off
923 // Length bits.
924 if (CI0) {
925 APInt Elt = CI0->getValue();
Craig Topperfc947bc2017-04-18 17:14:21 +0000926 Elt.lshrInPlace(Index);
927 Elt = Elt.zextOrTrunc(Length);
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000928 return LowConstantHighUndef(Elt.getZExtValue());
929 }
930
931 // If we were an EXTRQ call, we'll save registers if we convert to EXTRQI.
932 if (II.getIntrinsicID() == Intrinsic::x86_sse4a_extrq) {
933 Value *Args[] = {Op0, CILength, CIIndex};
Sanjay Patelaf674fb2015-12-14 17:24:23 +0000934 Module *M = II.getModule();
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000935 Value *F = Intrinsic::getDeclaration(M, Intrinsic::x86_sse4a_extrqi);
936 return Builder.CreateCall(F, Args);
937 }
938 }
939
940 // Constant Fold - extraction from zero is always {zero, undef}.
Craig Topperca2c8762017-07-06 18:39:49 +0000941 if (CI0 && CI0->isZero())
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000942 return LowConstantHighUndef(0);
943
944 return nullptr;
945}
946
947/// Attempt to simplify SSE4A INSERTQ/INSERTQI instructions using constant
948/// folding or conversion to a shuffle vector.
Sanjay Patel6038d3e2016-01-29 23:27:03 +0000949static Value *simplifyX86insertq(IntrinsicInst &II, Value *Op0, Value *Op1,
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000950 APInt APLength, APInt APIndex,
951 InstCombiner::BuilderTy &Builder) {
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000952 // From AMD documentation: "The bit index and field length are each six bits
953 // in length other bits of the field are ignored."
954 APIndex = APIndex.zextOrTrunc(6);
955 APLength = APLength.zextOrTrunc(6);
956
957 // Attempt to constant fold.
958 unsigned Index = APIndex.getZExtValue();
959
960 // From AMD documentation: "a value of zero in the field length is
961 // defined as length of 64".
962 unsigned Length = APLength == 0 ? 64 : APLength.getZExtValue();
963
964 // From AMD documentation: "If the sum of the bit index + length field
965 // is greater than 64, the results are undefined".
966 unsigned End = Index + Length;
967
968 // Note that both field index and field length are 8-bit quantities.
969 // Since variables 'Index' and 'Length' are unsigned values
970 // obtained from zero-extending field index and field length
971 // respectively, their sum should never wrap around.
972 if (End > 64)
973 return UndefValue::get(II.getType());
974
975 // If we are inserting whole bytes, we can convert this to a shuffle.
976 // Lowering can recognize INSERTQI shuffle masks.
977 if ((Length % 8) == 0 && (Index % 8) == 0) {
978 // Convert bit indices to byte indices.
979 Length /= 8;
980 Index /= 8;
981
982 Type *IntTy8 = Type::getInt8Ty(II.getContext());
983 Type *IntTy32 = Type::getInt32Ty(II.getContext());
984 VectorType *ShufTy = VectorType::get(IntTy8, 16);
985
986 SmallVector<Constant *, 16> ShuffleMask;
987 for (int i = 0; i != (int)Index; ++i)
988 ShuffleMask.push_back(Constant::getIntegerValue(IntTy32, APInt(32, i)));
989 for (int i = 0; i != (int)Length; ++i)
990 ShuffleMask.push_back(
991 Constant::getIntegerValue(IntTy32, APInt(32, i + 16)));
992 for (int i = Index + Length; i != 8; ++i)
993 ShuffleMask.push_back(Constant::getIntegerValue(IntTy32, APInt(32, i)));
994 for (int i = 8; i != 16; ++i)
995 ShuffleMask.push_back(UndefValue::get(IntTy32));
996
997 Value *SV = Builder.CreateShuffleVector(Builder.CreateBitCast(Op0, ShufTy),
998 Builder.CreateBitCast(Op1, ShufTy),
999 ConstantVector::get(ShuffleMask));
1000 return Builder.CreateBitCast(SV, II.getType());
1001 }
1002
1003 // See if we're dealing with constant values.
1004 Constant *C0 = dyn_cast<Constant>(Op0);
1005 Constant *C1 = dyn_cast<Constant>(Op1);
1006 ConstantInt *CI00 =
Andrea Di Biagiof3fd3162016-09-07 12:47:53 +00001007 C0 ? dyn_cast_or_null<ConstantInt>(C0->getAggregateElement((unsigned)0))
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00001008 : nullptr;
1009 ConstantInt *CI10 =
Andrea Di Biagiof3fd3162016-09-07 12:47:53 +00001010 C1 ? dyn_cast_or_null<ConstantInt>(C1->getAggregateElement((unsigned)0))
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00001011 : nullptr;
1012
1013 // Constant Fold - insert bottom Length bits starting at the Index'th bit.
1014 if (CI00 && CI10) {
1015 APInt V00 = CI00->getValue();
1016 APInt V10 = CI10->getValue();
1017 APInt Mask = APInt::getLowBitsSet(64, Length).shl(Index);
1018 V00 = V00 & ~Mask;
1019 V10 = V10.zextOrTrunc(Length).zextOrTrunc(64).shl(Index);
1020 APInt Val = V00 | V10;
1021 Type *IntTy64 = Type::getInt64Ty(II.getContext());
1022 Constant *Args[] = {ConstantInt::get(IntTy64, Val.getZExtValue()),
1023 UndefValue::get(IntTy64)};
1024 return ConstantVector::get(Args);
1025 }
1026
1027 // If we were an INSERTQ call, we'll save demanded elements if we convert to
1028 // INSERTQI.
1029 if (II.getIntrinsicID() == Intrinsic::x86_sse4a_insertq) {
1030 Type *IntTy8 = Type::getInt8Ty(II.getContext());
1031 Constant *CILength = ConstantInt::get(IntTy8, Length, false);
1032 Constant *CIIndex = ConstantInt::get(IntTy8, Index, false);
1033
1034 Value *Args[] = {Op0, Op1, CILength, CIIndex};
Sanjay Patelaf674fb2015-12-14 17:24:23 +00001035 Module *M = II.getModule();
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00001036 Value *F = Intrinsic::getDeclaration(M, Intrinsic::x86_sse4a_insertqi);
1037 return Builder.CreateCall(F, Args);
1038 }
1039
1040 return nullptr;
1041}
1042
Simon Pilgrimc0c56e72016-04-24 17:00:34 +00001043/// Attempt to convert pshufb* to shufflevector if the mask is constant.
1044static Value *simplifyX86pshufb(const IntrinsicInst &II,
1045 InstCombiner::BuilderTy &Builder) {
Simon Pilgrimbf60cc42016-04-29 21:34:54 +00001046 Constant *V = dyn_cast<Constant>(II.getArgOperand(1));
1047 if (!V)
1048 return nullptr;
1049
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +00001050 auto *VecTy = cast<VectorType>(II.getType());
1051 auto *MaskEltTy = Type::getInt32Ty(II.getContext());
1052 unsigned NumElts = VecTy->getNumElements();
Craig Topper9a63d7a2016-12-11 00:23:50 +00001053 assert((NumElts == 16 || NumElts == 32 || NumElts == 64) &&
Simon Pilgrimc0c56e72016-04-24 17:00:34 +00001054 "Unexpected number of elements in shuffle mask!");
Simon Pilgrimbf60cc42016-04-29 21:34:54 +00001055
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +00001056 // Construct a shuffle mask from constant integers or UNDEFs.
Craig Topper9a63d7a2016-12-11 00:23:50 +00001057 Constant *Indexes[64] = {nullptr};
Simon Pilgrimc0c56e72016-04-24 17:00:34 +00001058
Simon Pilgrimbf60cc42016-04-29 21:34:54 +00001059 // Each byte in the shuffle control mask forms an index to permute the
1060 // corresponding byte in the destination operand.
1061 for (unsigned I = 0; I < NumElts; ++I) {
1062 Constant *COp = V->getAggregateElement(I);
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +00001063 if (!COp || (!isa<UndefValue>(COp) && !isa<ConstantInt>(COp)))
Simon Pilgrimbf60cc42016-04-29 21:34:54 +00001064 return nullptr;
Simon Pilgrimc0c56e72016-04-24 17:00:34 +00001065
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +00001066 if (isa<UndefValue>(COp)) {
1067 Indexes[I] = UndefValue::get(MaskEltTy);
1068 continue;
1069 }
1070
Simon Pilgrimbf60cc42016-04-29 21:34:54 +00001071 int8_t Index = cast<ConstantInt>(COp)->getValue().getZExtValue();
1072
1073 // If the most significant bit (bit[7]) of each byte of the shuffle
1074 // control mask is set, then zero is written in the result byte.
1075 // The zero vector is in the right-hand side of the resulting
1076 // shufflevector.
1077
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +00001078 // The value of each index for the high 128-bit lane is the least
1079 // significant 4 bits of the respective shuffle control byte.
1080 Index = ((Index < 0) ? NumElts : Index & 0x0F) + (I & 0xF0);
1081 Indexes[I] = ConstantInt::get(MaskEltTy, Index);
Simon Pilgrimbf60cc42016-04-29 21:34:54 +00001082 }
Simon Pilgrimc0c56e72016-04-24 17:00:34 +00001083
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +00001084 auto ShuffleMask = ConstantVector::get(makeArrayRef(Indexes, NumElts));
Simon Pilgrimc0c56e72016-04-24 17:00:34 +00001085 auto V1 = II.getArgOperand(0);
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +00001086 auto V2 = Constant::getNullValue(VecTy);
Simon Pilgrimc0c56e72016-04-24 17:00:34 +00001087 return Builder.CreateShuffleVector(V1, V2, ShuffleMask);
1088}
1089
Simon Pilgrim2f6097d2016-04-24 17:23:46 +00001090/// Attempt to convert vpermilvar* to shufflevector if the mask is constant.
1091static Value *simplifyX86vpermilvar(const IntrinsicInst &II,
1092 InstCombiner::BuilderTy &Builder) {
Simon Pilgrim640f9962016-04-30 07:23:30 +00001093 Constant *V = dyn_cast<Constant>(II.getArgOperand(1));
1094 if (!V)
1095 return nullptr;
Simon Pilgrim2f6097d2016-04-24 17:23:46 +00001096
Craig Topper58917f32016-12-11 01:59:36 +00001097 auto *VecTy = cast<VectorType>(II.getType());
Simon Pilgrimeeacc402016-05-01 20:22:42 +00001098 auto *MaskEltTy = Type::getInt32Ty(II.getContext());
Craig Topper58917f32016-12-11 01:59:36 +00001099 unsigned NumElts = VecTy->getVectorNumElements();
1100 bool IsPD = VecTy->getScalarType()->isDoubleTy();
1101 unsigned NumLaneElts = IsPD ? 2 : 4;
1102 assert(NumElts == 16 || NumElts == 8 || NumElts == 4 || NumElts == 2);
Simon Pilgrim2f6097d2016-04-24 17:23:46 +00001103
Simon Pilgrimeeacc402016-05-01 20:22:42 +00001104 // Construct a shuffle mask from constant integers or UNDEFs.
Craig Topper58917f32016-12-11 01:59:36 +00001105 Constant *Indexes[16] = {nullptr};
Simon Pilgrim640f9962016-04-30 07:23:30 +00001106
1107 // The intrinsics only read one or two bits, clear the rest.
Simon Pilgrimeeacc402016-05-01 20:22:42 +00001108 for (unsigned I = 0; I < NumElts; ++I) {
Simon Pilgrim640f9962016-04-30 07:23:30 +00001109 Constant *COp = V->getAggregateElement(I);
Simon Pilgrimeeacc402016-05-01 20:22:42 +00001110 if (!COp || (!isa<UndefValue>(COp) && !isa<ConstantInt>(COp)))
Simon Pilgrim640f9962016-04-30 07:23:30 +00001111 return nullptr;
1112
Simon Pilgrimeeacc402016-05-01 20:22:42 +00001113 if (isa<UndefValue>(COp)) {
1114 Indexes[I] = UndefValue::get(MaskEltTy);
1115 continue;
1116 }
1117
1118 APInt Index = cast<ConstantInt>(COp)->getValue();
1119 Index = Index.zextOrTrunc(32).getLoBits(2);
Simon Pilgrim640f9962016-04-30 07:23:30 +00001120
1121 // The PD variants uses bit 1 to select per-lane element index, so
1122 // shift down to convert to generic shuffle mask index.
Craig Topper58917f32016-12-11 01:59:36 +00001123 if (IsPD)
Craig Topperfc947bc2017-04-18 17:14:21 +00001124 Index.lshrInPlace(1);
Simon Pilgrimeeacc402016-05-01 20:22:42 +00001125
1126 // The _256 variants are a bit trickier since the mask bits always index
1127 // into the corresponding 128 half. In order to convert to a generic
1128 // shuffle, we have to make that explicit.
Craig Topper58917f32016-12-11 01:59:36 +00001129 Index += APInt(32, (I / NumLaneElts) * NumLaneElts);
Simon Pilgrimeeacc402016-05-01 20:22:42 +00001130
1131 Indexes[I] = ConstantInt::get(MaskEltTy, Index);
Simon Pilgrim2f6097d2016-04-24 17:23:46 +00001132 }
1133
Simon Pilgrimeeacc402016-05-01 20:22:42 +00001134 auto ShuffleMask = ConstantVector::get(makeArrayRef(Indexes, NumElts));
Simon Pilgrim2f6097d2016-04-24 17:23:46 +00001135 auto V1 = II.getArgOperand(0);
1136 auto V2 = UndefValue::get(V1->getType());
1137 return Builder.CreateShuffleVector(V1, V2, ShuffleMask);
1138}
1139
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +00001140/// Attempt to convert vpermd/vpermps to shufflevector if the mask is constant.
1141static Value *simplifyX86vpermv(const IntrinsicInst &II,
1142 InstCombiner::BuilderTy &Builder) {
1143 auto *V = dyn_cast<Constant>(II.getArgOperand(1));
1144 if (!V)
1145 return nullptr;
1146
Simon Pilgrimca140b12016-05-01 20:43:02 +00001147 auto *VecTy = cast<VectorType>(II.getType());
1148 auto *MaskEltTy = Type::getInt32Ty(II.getContext());
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +00001149 unsigned Size = VecTy->getNumElements();
Craig Toppere3280452016-12-25 23:58:57 +00001150 assert((Size == 4 || Size == 8 || Size == 16 || Size == 32 || Size == 64) &&
1151 "Unexpected shuffle mask size");
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +00001152
Simon Pilgrimca140b12016-05-01 20:43:02 +00001153 // Construct a shuffle mask from constant integers or UNDEFs.
Craig Toppere3280452016-12-25 23:58:57 +00001154 Constant *Indexes[64] = {nullptr};
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +00001155
1156 for (unsigned I = 0; I < Size; ++I) {
1157 Constant *COp = V->getAggregateElement(I);
Simon Pilgrimca140b12016-05-01 20:43:02 +00001158 if (!COp || (!isa<UndefValue>(COp) && !isa<ConstantInt>(COp)))
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +00001159 return nullptr;
1160
Simon Pilgrimca140b12016-05-01 20:43:02 +00001161 if (isa<UndefValue>(COp)) {
1162 Indexes[I] = UndefValue::get(MaskEltTy);
1163 continue;
1164 }
1165
Craig Toppere3280452016-12-25 23:58:57 +00001166 uint32_t Index = cast<ConstantInt>(COp)->getZExtValue();
1167 Index &= Size - 1;
Simon Pilgrimca140b12016-05-01 20:43:02 +00001168 Indexes[I] = ConstantInt::get(MaskEltTy, Index);
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +00001169 }
1170
Simon Pilgrimca140b12016-05-01 20:43:02 +00001171 auto ShuffleMask = ConstantVector::get(makeArrayRef(Indexes, Size));
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +00001172 auto V1 = II.getArgOperand(0);
1173 auto V2 = UndefValue::get(VecTy);
1174 return Builder.CreateShuffleVector(V1, V2, ShuffleMask);
1175}
1176
Simon Pilgrim1d1c56e22015-10-11 14:38:34 +00001177/// Decode XOP integer vector comparison intrinsics.
Sanjay Patel6038d3e2016-01-29 23:27:03 +00001178static Value *simplifyX86vpcom(const IntrinsicInst &II,
Sanjay Patelf9f5d3c2016-01-29 23:14:58 +00001179 InstCombiner::BuilderTy &Builder,
1180 bool IsSigned) {
Simon Pilgrim1d1c56e22015-10-11 14:38:34 +00001181 if (auto *CInt = dyn_cast<ConstantInt>(II.getArgOperand(2))) {
1182 uint64_t Imm = CInt->getZExtValue() & 0x7;
1183 VectorType *VecTy = cast<VectorType>(II.getType());
1184 CmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
1185
1186 switch (Imm) {
1187 case 0x0:
1188 Pred = IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1189 break;
1190 case 0x1:
1191 Pred = IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
1192 break;
1193 case 0x2:
1194 Pred = IsSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1195 break;
1196 case 0x3:
1197 Pred = IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
1198 break;
1199 case 0x4:
1200 Pred = ICmpInst::ICMP_EQ; break;
1201 case 0x5:
1202 Pred = ICmpInst::ICMP_NE; break;
1203 case 0x6:
1204 return ConstantInt::getSigned(VecTy, 0); // FALSE
1205 case 0x7:
1206 return ConstantInt::getSigned(VecTy, -1); // TRUE
1207 }
1208
Sanjay Patelf9f5d3c2016-01-29 23:14:58 +00001209 if (Value *Cmp = Builder.CreateICmp(Pred, II.getArgOperand(0),
1210 II.getArgOperand(1)))
Simon Pilgrim1d1c56e22015-10-11 14:38:34 +00001211 return Builder.CreateSExtOrTrunc(Cmp, VecTy);
1212 }
1213 return nullptr;
1214}
1215
David Majnemer666aa942016-07-14 06:58:42 +00001216static bool maskIsAllOneOrUndef(Value *Mask) {
1217 auto *ConstMask = dyn_cast<Constant>(Mask);
1218 if (!ConstMask)
1219 return false;
1220 if (ConstMask->isAllOnesValue() || isa<UndefValue>(ConstMask))
1221 return true;
1222 for (unsigned I = 0, E = ConstMask->getType()->getVectorNumElements(); I != E;
1223 ++I) {
1224 if (auto *MaskElt = ConstMask->getAggregateElement(I))
1225 if (MaskElt->isAllOnesValue() || isa<UndefValue>(MaskElt))
1226 continue;
1227 return false;
1228 }
1229 return true;
1230}
1231
Sanjay Patelb695c552016-02-01 17:00:10 +00001232static Value *simplifyMaskedLoad(const IntrinsicInst &II,
1233 InstCombiner::BuilderTy &Builder) {
David Majnemer666aa942016-07-14 06:58:42 +00001234 // If the mask is all ones or undefs, this is a plain vector load of the 1st
1235 // argument.
1236 if (maskIsAllOneOrUndef(II.getArgOperand(2))) {
Sanjay Patelb695c552016-02-01 17:00:10 +00001237 Value *LoadPtr = II.getArgOperand(0);
1238 unsigned Alignment = cast<ConstantInt>(II.getArgOperand(1))->getZExtValue();
1239 return Builder.CreateAlignedLoad(LoadPtr, Alignment, "unmaskedload");
1240 }
1241
1242 return nullptr;
1243}
1244
Sanjay Patel04f792b2016-02-01 19:39:52 +00001245static Instruction *simplifyMaskedStore(IntrinsicInst &II, InstCombiner &IC) {
1246 auto *ConstMask = dyn_cast<Constant>(II.getArgOperand(3));
1247 if (!ConstMask)
1248 return nullptr;
1249
1250 // If the mask is all zeros, this instruction does nothing.
1251 if (ConstMask->isNullValue())
Sanjay Patel4b198802016-02-01 22:23:39 +00001252 return IC.eraseInstFromFunction(II);
Sanjay Patel04f792b2016-02-01 19:39:52 +00001253
1254 // If the mask is all ones, this is a plain vector store of the 1st argument.
1255 if (ConstMask->isAllOnesValue()) {
1256 Value *StorePtr = II.getArgOperand(1);
1257 unsigned Alignment = cast<ConstantInt>(II.getArgOperand(2))->getZExtValue();
1258 return new StoreInst(II.getArgOperand(0), StorePtr, false, Alignment);
1259 }
1260
1261 return nullptr;
1262}
1263
Sanjay Patel103ab7d2016-02-01 22:10:26 +00001264static Instruction *simplifyMaskedGather(IntrinsicInst &II, InstCombiner &IC) {
1265 // If the mask is all zeros, return the "passthru" argument of the gather.
1266 auto *ConstMask = dyn_cast<Constant>(II.getArgOperand(2));
1267 if (ConstMask && ConstMask->isNullValue())
Sanjay Patel4b198802016-02-01 22:23:39 +00001268 return IC.replaceInstUsesWith(II, II.getArgOperand(3));
Sanjay Patel103ab7d2016-02-01 22:10:26 +00001269
1270 return nullptr;
1271}
1272
Piotr Padlewskic63b4922018-07-12 23:55:20 +00001273/// This function transforms launder.invariant.group and strip.invariant.group
1274/// like:
1275/// launder(launder(%x)) -> launder(%x) (the result is not the argument)
1276/// launder(strip(%x)) -> launder(%x)
1277/// strip(strip(%x)) -> strip(%x) (the result is not the argument)
1278/// strip(launder(%x)) -> strip(%x)
1279/// This is legal because it preserves the most recent information about
1280/// the presence or absence of invariant.group.
1281static Instruction *simplifyInvariantGroupIntrinsic(IntrinsicInst &II,
1282 InstCombiner &IC) {
1283 auto *Arg = II.getArgOperand(0);
1284 auto *StrippedArg = Arg->stripPointerCasts();
1285 auto *StrippedInvariantGroupsArg = Arg->stripPointerCastsAndInvariantGroups();
1286 if (StrippedArg == StrippedInvariantGroupsArg)
1287 return nullptr; // No launders/strips to remove.
1288
1289 Value *Result = nullptr;
1290
1291 if (II.getIntrinsicID() == Intrinsic::launder_invariant_group)
1292 Result = IC.Builder.CreateLaunderInvariantGroup(StrippedInvariantGroupsArg);
1293 else if (II.getIntrinsicID() == Intrinsic::strip_invariant_group)
1294 Result = IC.Builder.CreateStripInvariantGroup(StrippedInvariantGroupsArg);
1295 else
1296 llvm_unreachable(
1297 "simplifyInvariantGroupIntrinsic only handles launder and strip");
1298 if (Result->getType()->getPointerAddressSpace() !=
1299 II.getType()->getPointerAddressSpace())
1300 Result = IC.Builder.CreateAddrSpaceCast(Result, II.getType());
1301 if (Result->getType() != II.getType())
1302 Result = IC.Builder.CreateBitCast(Result, II.getType());
1303
1304 return cast<Instruction>(Result);
1305}
1306
Sanjay Patel103ab7d2016-02-01 22:10:26 +00001307static Instruction *simplifyMaskedScatter(IntrinsicInst &II, InstCombiner &IC) {
1308 // If the mask is all zeros, a scatter does nothing.
1309 auto *ConstMask = dyn_cast<Constant>(II.getArgOperand(3));
1310 if (ConstMask && ConstMask->isNullValue())
Sanjay Patel4b198802016-02-01 22:23:39 +00001311 return IC.eraseInstFromFunction(II);
Sanjay Patel103ab7d2016-02-01 22:10:26 +00001312
1313 return nullptr;
1314}
1315
Amaury Sechet763c59d2016-08-18 20:43:50 +00001316static Instruction *foldCttzCtlz(IntrinsicInst &II, InstCombiner &IC) {
1317 assert((II.getIntrinsicID() == Intrinsic::cttz ||
1318 II.getIntrinsicID() == Intrinsic::ctlz) &&
1319 "Expected cttz or ctlz intrinsic");
Sanjay Patel8e3ab172016-08-05 22:42:46 +00001320 Value *Op0 = II.getArgOperand(0);
Sanjay Patel8e3ab172016-08-05 22:42:46 +00001321
Craig Topper8205a1a2017-05-24 16:53:07 +00001322 KnownBits Known = IC.computeKnownBits(Op0, 0, &II);
Sanjay Patel8e3ab172016-08-05 22:42:46 +00001323
1324 // Create a mask for bits above (ctlz) or below (cttz) the first known one.
1325 bool IsTZ = II.getIntrinsicID() == Intrinsic::cttz;
Craig Topper8df66c62017-05-12 17:20:30 +00001326 unsigned PossibleZeros = IsTZ ? Known.countMaxTrailingZeros()
1327 : Known.countMaxLeadingZeros();
1328 unsigned DefiniteZeros = IsTZ ? Known.countMinTrailingZeros()
1329 : Known.countMinLeadingZeros();
Sanjay Patel8e3ab172016-08-05 22:42:46 +00001330
1331 // If all bits above (ctlz) or below (cttz) the first known one are known
1332 // zero, this value is constant.
1333 // FIXME: This should be in InstSimplify because we're replacing an
1334 // instruction with a constant.
Craig Topper9474e9b2017-04-27 04:51:25 +00001335 if (PossibleZeros == DefiniteZeros) {
Craig Topper0799ff92017-06-03 18:50:32 +00001336 auto *C = ConstantInt::get(Op0->getType(), DefiniteZeros);
Amaury Sechet763c59d2016-08-18 20:43:50 +00001337 return IC.replaceInstUsesWith(II, C);
1338 }
1339
1340 // If the input to cttz/ctlz is known to be non-zero,
1341 // then change the 'ZeroIsUndef' parameter to 'true'
1342 // because we know the zero behavior can't affect the result.
Craig Topper73ba1c82017-06-07 07:40:37 +00001343 if (!Known.One.isNullValue() ||
Craig Topperd45185f2017-05-26 18:23:57 +00001344 isKnownNonZero(Op0, IC.getDataLayout(), 0, &IC.getAssumptionCache(), &II,
1345 &IC.getDominatorTree())) {
Amaury Sechet763c59d2016-08-18 20:43:50 +00001346 if (!match(II.getArgOperand(1), m_One())) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001347 II.setOperand(1, IC.Builder.getTrue());
Amaury Sechet763c59d2016-08-18 20:43:50 +00001348 return &II;
1349 }
1350 }
Sanjay Patel8e3ab172016-08-05 22:42:46 +00001351
Craig Topper5b173f22017-06-21 16:32:35 +00001352 // Add range metadata since known bits can't completely reflect what we know.
1353 // TODO: Handle splat vectors.
1354 auto *IT = dyn_cast<IntegerType>(Op0->getType());
1355 if (IT && IT->getBitWidth() != 1 && !II.getMetadata(LLVMContext::MD_range)) {
1356 Metadata *LowAndHigh[] = {
1357 ConstantAsMetadata::get(ConstantInt::get(IT, DefiniteZeros)),
1358 ConstantAsMetadata::get(ConstantInt::get(IT, PossibleZeros + 1))};
1359 II.setMetadata(LLVMContext::MD_range,
1360 MDNode::get(II.getContext(), LowAndHigh));
1361 return &II;
1362 }
1363
1364 return nullptr;
1365}
1366
1367static Instruction *foldCtpop(IntrinsicInst &II, InstCombiner &IC) {
1368 assert(II.getIntrinsicID() == Intrinsic::ctpop &&
1369 "Expected ctpop intrinsic");
1370 Value *Op0 = II.getArgOperand(0);
1371 // FIXME: Try to simplify vectors of integers.
1372 auto *IT = dyn_cast<IntegerType>(Op0->getType());
1373 if (!IT)
1374 return nullptr;
1375
1376 unsigned BitWidth = IT->getBitWidth();
1377 KnownBits Known(BitWidth);
1378 IC.computeKnownBits(Op0, Known, 0, &II);
1379
1380 unsigned MinCount = Known.countMinPopulation();
1381 unsigned MaxCount = Known.countMaxPopulation();
1382
1383 // Add range metadata since known bits can't completely reflect what we know.
1384 if (IT->getBitWidth() != 1 && !II.getMetadata(LLVMContext::MD_range)) {
1385 Metadata *LowAndHigh[] = {
1386 ConstantAsMetadata::get(ConstantInt::get(IT, MinCount)),
1387 ConstantAsMetadata::get(ConstantInt::get(IT, MaxCount + 1))};
1388 II.setMetadata(LLVMContext::MD_range,
1389 MDNode::get(II.getContext(), LowAndHigh));
1390 return &II;
1391 }
1392
Sanjay Patel8e3ab172016-08-05 22:42:46 +00001393 return nullptr;
1394}
1395
Sanjay Patel1ace9932016-02-26 21:04:14 +00001396// TODO: If the x86 backend knew how to convert a bool vector mask back to an
1397// XMM register mask efficiently, we could transform all x86 masked intrinsics
1398// to LLVM masked intrinsics and remove the x86 masked intrinsic defs.
Sanjay Patel98a71502016-02-29 23:16:48 +00001399static Instruction *simplifyX86MaskedLoad(IntrinsicInst &II, InstCombiner &IC) {
1400 Value *Ptr = II.getOperand(0);
1401 Value *Mask = II.getOperand(1);
Sanjay Patel5e5056d2016-04-12 23:16:23 +00001402 Constant *ZeroVec = Constant::getNullValue(II.getType());
Sanjay Patel98a71502016-02-29 23:16:48 +00001403
1404 // Special case a zero mask since that's not a ConstantDataVector.
Sanjay Patel5e5056d2016-04-12 23:16:23 +00001405 // This masked load instruction creates a zero vector.
Sanjay Patel98a71502016-02-29 23:16:48 +00001406 if (isa<ConstantAggregateZero>(Mask))
Sanjay Patel5e5056d2016-04-12 23:16:23 +00001407 return IC.replaceInstUsesWith(II, ZeroVec);
Sanjay Patel98a71502016-02-29 23:16:48 +00001408
1409 auto *ConstMask = dyn_cast<ConstantDataVector>(Mask);
1410 if (!ConstMask)
1411 return nullptr;
1412
1413 // The mask is constant. Convert this x86 intrinsic to the LLVM instrinsic
1414 // to allow target-independent optimizations.
1415
1416 // First, cast the x86 intrinsic scalar pointer to a vector pointer to match
1417 // the LLVM intrinsic definition for the pointer argument.
1418 unsigned AddrSpace = cast<PointerType>(Ptr->getType())->getAddressSpace();
1419 PointerType *VecPtrTy = PointerType::get(II.getType(), AddrSpace);
Craig Topperbb4069e2017-07-07 23:16:26 +00001420 Value *PtrCast = IC.Builder.CreateBitCast(Ptr, VecPtrTy, "castvec");
Sanjay Patel98a71502016-02-29 23:16:48 +00001421
1422 // Second, convert the x86 XMM integer vector mask to a vector of bools based
1423 // on each element's most significant bit (the sign bit).
1424 Constant *BoolMask = getNegativeIsTrueBoolVec(ConstMask);
1425
Sanjay Patel5e5056d2016-04-12 23:16:23 +00001426 // The pass-through vector for an x86 masked load is a zero vector.
1427 CallInst *NewMaskedLoad =
Craig Topperbb4069e2017-07-07 23:16:26 +00001428 IC.Builder.CreateMaskedLoad(PtrCast, 1, BoolMask, ZeroVec);
Sanjay Patel98a71502016-02-29 23:16:48 +00001429 return IC.replaceInstUsesWith(II, NewMaskedLoad);
1430}
1431
1432// TODO: If the x86 backend knew how to convert a bool vector mask back to an
1433// XMM register mask efficiently, we could transform all x86 masked intrinsics
1434// to LLVM masked intrinsics and remove the x86 masked intrinsic defs.
Sanjay Patel1ace9932016-02-26 21:04:14 +00001435static bool simplifyX86MaskedStore(IntrinsicInst &II, InstCombiner &IC) {
1436 Value *Ptr = II.getOperand(0);
1437 Value *Mask = II.getOperand(1);
1438 Value *Vec = II.getOperand(2);
1439
1440 // Special case a zero mask since that's not a ConstantDataVector:
1441 // this masked store instruction does nothing.
1442 if (isa<ConstantAggregateZero>(Mask)) {
1443 IC.eraseInstFromFunction(II);
1444 return true;
1445 }
1446
Sanjay Patelc4acbae2016-03-12 15:16:59 +00001447 // The SSE2 version is too weird (eg, unaligned but non-temporal) to do
1448 // anything else at this level.
1449 if (II.getIntrinsicID() == Intrinsic::x86_sse2_maskmov_dqu)
1450 return false;
1451
Sanjay Patel1ace9932016-02-26 21:04:14 +00001452 auto *ConstMask = dyn_cast<ConstantDataVector>(Mask);
1453 if (!ConstMask)
1454 return false;
1455
1456 // The mask is constant. Convert this x86 intrinsic to the LLVM instrinsic
1457 // to allow target-independent optimizations.
1458
1459 // First, cast the x86 intrinsic scalar pointer to a vector pointer to match
1460 // the LLVM intrinsic definition for the pointer argument.
1461 unsigned AddrSpace = cast<PointerType>(Ptr->getType())->getAddressSpace();
1462 PointerType *VecPtrTy = PointerType::get(Vec->getType(), AddrSpace);
Craig Topperbb4069e2017-07-07 23:16:26 +00001463 Value *PtrCast = IC.Builder.CreateBitCast(Ptr, VecPtrTy, "castvec");
Sanjay Patel1ace9932016-02-26 21:04:14 +00001464
1465 // Second, convert the x86 XMM integer vector mask to a vector of bools based
1466 // on each element's most significant bit (the sign bit).
1467 Constant *BoolMask = getNegativeIsTrueBoolVec(ConstMask);
1468
Craig Topperbb4069e2017-07-07 23:16:26 +00001469 IC.Builder.CreateMaskedStore(Vec, PtrCast, 1, BoolMask);
Sanjay Patel1ace9932016-02-26 21:04:14 +00001470
1471 // 'Replace uses' doesn't work for stores. Erase the original masked store.
1472 IC.eraseInstFromFunction(II);
1473 return true;
1474}
1475
Matt Arsenaultcdb468c2017-02-27 23:08:49 +00001476// Constant fold llvm.amdgcn.fmed3 intrinsics for standard inputs.
1477//
1478// A single NaN input is folded to minnum, so we rely on that folding for
1479// handling NaNs.
1480static APFloat fmed3AMDGCN(const APFloat &Src0, const APFloat &Src1,
1481 const APFloat &Src2) {
1482 APFloat Max3 = maxnum(maxnum(Src0, Src1), Src2);
1483
1484 APFloat::cmpResult Cmp0 = Max3.compare(Src0);
1485 assert(Cmp0 != APFloat::cmpUnordered && "nans handled separately");
1486 if (Cmp0 == APFloat::cmpEqual)
1487 return maxnum(Src1, Src2);
1488
1489 APFloat::cmpResult Cmp1 = Max3.compare(Src1);
1490 assert(Cmp1 != APFloat::cmpUnordered && "nans handled separately");
1491 if (Cmp1 == APFloat::cmpEqual)
1492 return maxnum(Src0, Src2);
1493
1494 return maxnum(Src0, Src1);
1495}
1496
Alexandros Lamprineas52457d32018-05-30 14:38:50 +00001497/// Convert a table lookup to shufflevector if the mask is constant.
1498/// This could benefit tbl1 if the mask is { 7,6,5,4,3,2,1,0 }, in
1499/// which case we could lower the shufflevector with rev64 instructions
1500/// as it's actually a byte reverse.
1501static Value *simplifyNeonTbl1(const IntrinsicInst &II,
1502 InstCombiner::BuilderTy &Builder) {
1503 // Bail out if the mask is not a constant.
1504 auto *C = dyn_cast<Constant>(II.getArgOperand(1));
1505 if (!C)
1506 return nullptr;
1507
1508 auto *VecTy = cast<VectorType>(II.getType());
1509 unsigned NumElts = VecTy->getNumElements();
1510
1511 // Only perform this transformation for <8 x i8> vector types.
1512 if (!VecTy->getElementType()->isIntegerTy(8) || NumElts != 8)
1513 return nullptr;
1514
1515 uint32_t Indexes[8];
1516
1517 for (unsigned I = 0; I < NumElts; ++I) {
1518 Constant *COp = C->getAggregateElement(I);
1519
1520 if (!COp || !isa<ConstantInt>(COp))
1521 return nullptr;
1522
1523 Indexes[I] = cast<ConstantInt>(COp)->getLimitedValue();
1524
1525 // Make sure the mask indices are in range.
1526 if (Indexes[I] >= NumElts)
1527 return nullptr;
1528 }
1529
1530 auto *ShuffleMask = ConstantDataVector::get(II.getContext(),
1531 makeArrayRef(Indexes));
1532 auto *V1 = II.getArgOperand(0);
1533 auto *V2 = Constant::getNullValue(V1->getType());
1534 return Builder.CreateShuffleVector(V1, V2, ShuffleMask);
1535}
1536
Alexandros Lamprineas61f0ba12018-05-31 12:19:18 +00001537/// Convert a vector load intrinsic into a simple llvm load instruction.
1538/// This is beneficial when the underlying object being addressed comes
1539/// from a constant, since we get constant-folding for free.
1540static Value *simplifyNeonVld1(const IntrinsicInst &II,
1541 unsigned MemAlign,
1542 InstCombiner::BuilderTy &Builder) {
1543 auto *IntrAlign = dyn_cast<ConstantInt>(II.getArgOperand(1));
1544
1545 if (!IntrAlign)
1546 return nullptr;
1547
1548 unsigned Alignment = IntrAlign->getLimitedValue() < MemAlign ?
1549 MemAlign : IntrAlign->getLimitedValue();
1550
1551 if (!isPowerOf2_32(Alignment))
1552 return nullptr;
1553
1554 auto *BCastInst = Builder.CreateBitCast(II.getArgOperand(0),
1555 PointerType::get(II.getType(), 0));
1556 return Builder.CreateAlignedLoad(BCastInst, Alignment);
1557}
1558
Arnaud A. de Grandmaison333ef382016-05-10 09:24:49 +00001559// Returns true iff the 2 intrinsics have the same operands, limiting the
1560// comparison to the first NumOperands.
1561static bool haveSameOperands(const IntrinsicInst &I, const IntrinsicInst &E,
1562 unsigned NumOperands) {
1563 assert(I.getNumArgOperands() >= NumOperands && "Not enough operands");
1564 assert(E.getNumArgOperands() >= NumOperands && "Not enough operands");
1565 for (unsigned i = 0; i < NumOperands; i++)
1566 if (I.getArgOperand(i) != E.getArgOperand(i))
1567 return false;
1568 return true;
1569}
1570
1571// Remove trivially empty start/end intrinsic ranges, i.e. a start
1572// immediately followed by an end (ignoring debuginfo or other
1573// start/end intrinsics in between). As this handles only the most trivial
1574// cases, tracking the nesting level is not needed:
1575//
1576// call @llvm.foo.start(i1 0) ; &I
1577// call @llvm.foo.start(i1 0)
1578// call @llvm.foo.end(i1 0) ; This one will not be skipped: it will be removed
1579// call @llvm.foo.end(i1 0)
1580static bool removeTriviallyEmptyRange(IntrinsicInst &I, unsigned StartID,
1581 unsigned EndID, InstCombiner &IC) {
1582 assert(I.getIntrinsicID() == StartID &&
1583 "Start intrinsic does not have expected ID");
1584 BasicBlock::iterator BI(I), BE(I.getParent()->end());
1585 for (++BI; BI != BE; ++BI) {
1586 if (auto *E = dyn_cast<IntrinsicInst>(BI)) {
1587 if (isa<DbgInfoIntrinsic>(E) || E->getIntrinsicID() == StartID)
1588 continue;
1589 if (E->getIntrinsicID() == EndID &&
1590 haveSameOperands(I, *E, E->getNumArgOperands())) {
1591 IC.eraseInstFromFunction(*E);
1592 IC.eraseInstFromFunction(I);
1593 return true;
1594 }
1595 }
1596 break;
1597 }
1598
1599 return false;
1600}
1601
Justin Lebar698c31b2017-01-27 00:58:58 +00001602// Convert NVVM intrinsics to target-generic LLVM code where possible.
1603static Instruction *SimplifyNVVMIntrinsic(IntrinsicInst *II, InstCombiner &IC) {
1604 // Each NVVM intrinsic we can simplify can be replaced with one of:
1605 //
1606 // * an LLVM intrinsic,
1607 // * an LLVM cast operation,
1608 // * an LLVM binary operation, or
1609 // * ad-hoc LLVM IR for the particular operation.
1610
1611 // Some transformations are only valid when the module's
1612 // flush-denormals-to-zero (ftz) setting is true/false, whereas other
1613 // transformations are valid regardless of the module's ftz setting.
1614 enum FtzRequirementTy {
1615 FTZ_Any, // Any ftz setting is ok.
1616 FTZ_MustBeOn, // Transformation is valid only if ftz is on.
1617 FTZ_MustBeOff, // Transformation is valid only if ftz is off.
1618 };
1619 // Classes of NVVM intrinsics that can't be replaced one-to-one with a
1620 // target-generic intrinsic, cast op, or binary op but that we can nonetheless
1621 // simplify.
1622 enum SpecialCase {
1623 SPC_Reciprocal,
1624 };
1625
1626 // SimplifyAction is a poor-man's variant (plus an additional flag) that
1627 // represents how to replace an NVVM intrinsic with target-generic LLVM IR.
1628 struct SimplifyAction {
1629 // Invariant: At most one of these Optionals has a value.
1630 Optional<Intrinsic::ID> IID;
1631 Optional<Instruction::CastOps> CastOp;
1632 Optional<Instruction::BinaryOps> BinaryOp;
1633 Optional<SpecialCase> Special;
1634
1635 FtzRequirementTy FtzRequirement = FTZ_Any;
1636
1637 SimplifyAction() = default;
1638
1639 SimplifyAction(Intrinsic::ID IID, FtzRequirementTy FtzReq)
1640 : IID(IID), FtzRequirement(FtzReq) {}
1641
1642 // Cast operations don't have anything to do with FTZ, so we skip that
1643 // argument.
1644 SimplifyAction(Instruction::CastOps CastOp) : CastOp(CastOp) {}
1645
1646 SimplifyAction(Instruction::BinaryOps BinaryOp, FtzRequirementTy FtzReq)
1647 : BinaryOp(BinaryOp), FtzRequirement(FtzReq) {}
1648
1649 SimplifyAction(SpecialCase Special, FtzRequirementTy FtzReq)
1650 : Special(Special), FtzRequirement(FtzReq) {}
1651 };
1652
1653 // Try to generate a SimplifyAction describing how to replace our
1654 // IntrinsicInstr with target-generic LLVM IR.
1655 const SimplifyAction Action = [II]() -> SimplifyAction {
1656 switch (II->getIntrinsicID()) {
Justin Lebar698c31b2017-01-27 00:58:58 +00001657 // NVVM intrinsics that map directly to LLVM intrinsics.
1658 case Intrinsic::nvvm_ceil_d:
1659 return {Intrinsic::ceil, FTZ_Any};
1660 case Intrinsic::nvvm_ceil_f:
1661 return {Intrinsic::ceil, FTZ_MustBeOff};
1662 case Intrinsic::nvvm_ceil_ftz_f:
1663 return {Intrinsic::ceil, FTZ_MustBeOn};
1664 case Intrinsic::nvvm_fabs_d:
1665 return {Intrinsic::fabs, FTZ_Any};
1666 case Intrinsic::nvvm_fabs_f:
1667 return {Intrinsic::fabs, FTZ_MustBeOff};
1668 case Intrinsic::nvvm_fabs_ftz_f:
1669 return {Intrinsic::fabs, FTZ_MustBeOn};
1670 case Intrinsic::nvvm_floor_d:
1671 return {Intrinsic::floor, FTZ_Any};
1672 case Intrinsic::nvvm_floor_f:
1673 return {Intrinsic::floor, FTZ_MustBeOff};
1674 case Intrinsic::nvvm_floor_ftz_f:
1675 return {Intrinsic::floor, FTZ_MustBeOn};
1676 case Intrinsic::nvvm_fma_rn_d:
1677 return {Intrinsic::fma, FTZ_Any};
1678 case Intrinsic::nvvm_fma_rn_f:
1679 return {Intrinsic::fma, FTZ_MustBeOff};
1680 case Intrinsic::nvvm_fma_rn_ftz_f:
1681 return {Intrinsic::fma, FTZ_MustBeOn};
1682 case Intrinsic::nvvm_fmax_d:
1683 return {Intrinsic::maxnum, FTZ_Any};
1684 case Intrinsic::nvvm_fmax_f:
1685 return {Intrinsic::maxnum, FTZ_MustBeOff};
1686 case Intrinsic::nvvm_fmax_ftz_f:
1687 return {Intrinsic::maxnum, FTZ_MustBeOn};
1688 case Intrinsic::nvvm_fmin_d:
1689 return {Intrinsic::minnum, FTZ_Any};
1690 case Intrinsic::nvvm_fmin_f:
1691 return {Intrinsic::minnum, FTZ_MustBeOff};
1692 case Intrinsic::nvvm_fmin_ftz_f:
1693 return {Intrinsic::minnum, FTZ_MustBeOn};
1694 case Intrinsic::nvvm_round_d:
1695 return {Intrinsic::round, FTZ_Any};
1696 case Intrinsic::nvvm_round_f:
1697 return {Intrinsic::round, FTZ_MustBeOff};
1698 case Intrinsic::nvvm_round_ftz_f:
1699 return {Intrinsic::round, FTZ_MustBeOn};
1700 case Intrinsic::nvvm_sqrt_rn_d:
1701 return {Intrinsic::sqrt, FTZ_Any};
1702 case Intrinsic::nvvm_sqrt_f:
1703 // nvvm_sqrt_f is a special case. For most intrinsics, foo_ftz_f is the
1704 // ftz version, and foo_f is the non-ftz version. But nvvm_sqrt_f adopts
1705 // the ftz-ness of the surrounding code. sqrt_rn_f and sqrt_rn_ftz_f are
1706 // the versions with explicit ftz-ness.
1707 return {Intrinsic::sqrt, FTZ_Any};
1708 case Intrinsic::nvvm_sqrt_rn_f:
1709 return {Intrinsic::sqrt, FTZ_MustBeOff};
1710 case Intrinsic::nvvm_sqrt_rn_ftz_f:
1711 return {Intrinsic::sqrt, FTZ_MustBeOn};
1712 case Intrinsic::nvvm_trunc_d:
1713 return {Intrinsic::trunc, FTZ_Any};
1714 case Intrinsic::nvvm_trunc_f:
1715 return {Intrinsic::trunc, FTZ_MustBeOff};
1716 case Intrinsic::nvvm_trunc_ftz_f:
1717 return {Intrinsic::trunc, FTZ_MustBeOn};
1718
1719 // NVVM intrinsics that map to LLVM cast operations.
1720 //
1721 // Note that llvm's target-generic conversion operators correspond to the rz
1722 // (round to zero) versions of the nvvm conversion intrinsics, even though
1723 // most everything else here uses the rn (round to nearest even) nvvm ops.
1724 case Intrinsic::nvvm_d2i_rz:
1725 case Intrinsic::nvvm_f2i_rz:
1726 case Intrinsic::nvvm_d2ll_rz:
1727 case Intrinsic::nvvm_f2ll_rz:
1728 return {Instruction::FPToSI};
1729 case Intrinsic::nvvm_d2ui_rz:
1730 case Intrinsic::nvvm_f2ui_rz:
1731 case Intrinsic::nvvm_d2ull_rz:
1732 case Intrinsic::nvvm_f2ull_rz:
1733 return {Instruction::FPToUI};
1734 case Intrinsic::nvvm_i2d_rz:
1735 case Intrinsic::nvvm_i2f_rz:
1736 case Intrinsic::nvvm_ll2d_rz:
1737 case Intrinsic::nvvm_ll2f_rz:
1738 return {Instruction::SIToFP};
1739 case Intrinsic::nvvm_ui2d_rz:
1740 case Intrinsic::nvvm_ui2f_rz:
1741 case Intrinsic::nvvm_ull2d_rz:
1742 case Intrinsic::nvvm_ull2f_rz:
1743 return {Instruction::UIToFP};
1744
1745 // NVVM intrinsics that map to LLVM binary ops.
1746 case Intrinsic::nvvm_add_rn_d:
1747 return {Instruction::FAdd, FTZ_Any};
1748 case Intrinsic::nvvm_add_rn_f:
1749 return {Instruction::FAdd, FTZ_MustBeOff};
1750 case Intrinsic::nvvm_add_rn_ftz_f:
1751 return {Instruction::FAdd, FTZ_MustBeOn};
1752 case Intrinsic::nvvm_mul_rn_d:
1753 return {Instruction::FMul, FTZ_Any};
1754 case Intrinsic::nvvm_mul_rn_f:
1755 return {Instruction::FMul, FTZ_MustBeOff};
1756 case Intrinsic::nvvm_mul_rn_ftz_f:
1757 return {Instruction::FMul, FTZ_MustBeOn};
1758 case Intrinsic::nvvm_div_rn_d:
1759 return {Instruction::FDiv, FTZ_Any};
1760 case Intrinsic::nvvm_div_rn_f:
1761 return {Instruction::FDiv, FTZ_MustBeOff};
1762 case Intrinsic::nvvm_div_rn_ftz_f:
1763 return {Instruction::FDiv, FTZ_MustBeOn};
1764
1765 // The remainder of cases are NVVM intrinsics that map to LLVM idioms, but
1766 // need special handling.
1767 //
Hiroshi Inoue0ca79dc2017-07-11 06:04:59 +00001768 // We seem to be missing intrinsics for rcp.approx.{ftz.}f32, which is just
Justin Lebar698c31b2017-01-27 00:58:58 +00001769 // as well.
1770 case Intrinsic::nvvm_rcp_rn_d:
1771 return {SPC_Reciprocal, FTZ_Any};
1772 case Intrinsic::nvvm_rcp_rn_f:
1773 return {SPC_Reciprocal, FTZ_MustBeOff};
1774 case Intrinsic::nvvm_rcp_rn_ftz_f:
1775 return {SPC_Reciprocal, FTZ_MustBeOn};
1776
1777 // We do not currently simplify intrinsics that give an approximate answer.
1778 // These include:
1779 //
1780 // - nvvm_cos_approx_{f,ftz_f}
1781 // - nvvm_ex2_approx_{d,f,ftz_f}
1782 // - nvvm_lg2_approx_{d,f,ftz_f}
1783 // - nvvm_sin_approx_{f,ftz_f}
1784 // - nvvm_sqrt_approx_{f,ftz_f}
1785 // - nvvm_rsqrt_approx_{d,f,ftz_f}
1786 // - nvvm_div_approx_{ftz_d,ftz_f,f}
1787 // - nvvm_rcp_approx_ftz_d
1788 //
1789 // Ideally we'd encode them as e.g. "fast call @llvm.cos", where "fast"
1790 // means that fastmath is enabled in the intrinsic. Unfortunately only
1791 // binary operators (currently) have a fastmath bit in SelectionDAG, so this
1792 // information gets lost and we can't select on it.
1793 //
1794 // TODO: div and rcp are lowered to a binary op, so these we could in theory
1795 // lower them to "fast fdiv".
1796
1797 default:
1798 return {};
1799 }
1800 }();
1801
1802 // If Action.FtzRequirementTy is not satisfied by the module's ftz state, we
1803 // can bail out now. (Notice that in the case that IID is not an NVVM
1804 // intrinsic, we don't have to look up any module metadata, as
1805 // FtzRequirementTy will be FTZ_Any.)
1806 if (Action.FtzRequirement != FTZ_Any) {
1807 bool FtzEnabled =
1808 II->getFunction()->getFnAttribute("nvptx-f32ftz").getValueAsString() ==
1809 "true";
1810
1811 if (FtzEnabled != (Action.FtzRequirement == FTZ_MustBeOn))
1812 return nullptr;
1813 }
1814
1815 // Simplify to target-generic intrinsic.
1816 if (Action.IID) {
1817 SmallVector<Value *, 4> Args(II->arg_operands());
1818 // All the target-generic intrinsics currently of interest to us have one
1819 // type argument, equal to that of the nvvm intrinsic's argument.
Justin Lebare3ac0fb2017-01-27 01:49:39 +00001820 Type *Tys[] = {II->getArgOperand(0)->getType()};
Justin Lebar698c31b2017-01-27 00:58:58 +00001821 return CallInst::Create(
1822 Intrinsic::getDeclaration(II->getModule(), *Action.IID, Tys), Args);
1823 }
1824
1825 // Simplify to target-generic binary op.
1826 if (Action.BinaryOp)
1827 return BinaryOperator::Create(*Action.BinaryOp, II->getArgOperand(0),
1828 II->getArgOperand(1), II->getName());
1829
1830 // Simplify to target-generic cast op.
1831 if (Action.CastOp)
1832 return CastInst::Create(*Action.CastOp, II->getArgOperand(0), II->getType(),
1833 II->getName());
1834
1835 // All that's left are the special cases.
1836 if (!Action.Special)
1837 return nullptr;
1838
1839 switch (*Action.Special) {
1840 case SPC_Reciprocal:
1841 // Simplify reciprocal.
1842 return BinaryOperator::Create(
1843 Instruction::FDiv, ConstantFP::get(II->getArgOperand(0)->getType(), 1),
1844 II->getArgOperand(0), II->getName());
1845 }
Justin Lebar25ebe2d2017-01-27 02:04:07 +00001846 llvm_unreachable("All SpecialCase enumerators should be handled in switch.");
Justin Lebar698c31b2017-01-27 00:58:58 +00001847}
1848
Arnaud A. de Grandmaison333ef382016-05-10 09:24:49 +00001849Instruction *InstCombiner::visitVAStartInst(VAStartInst &I) {
1850 removeTriviallyEmptyRange(I, Intrinsic::vastart, Intrinsic::vaend, *this);
1851 return nullptr;
1852}
1853
1854Instruction *InstCombiner::visitVACopyInst(VACopyInst &I) {
1855 removeTriviallyEmptyRange(I, Intrinsic::vacopy, Intrinsic::vaend, *this);
1856 return nullptr;
1857}
1858
Sanjay Patelcd4377c2016-01-20 22:24:38 +00001859/// CallInst simplification. This mostly only handles folding of intrinsic
1860/// instructions. For normal calls, it allows visitCallSite to do the heavy
1861/// lifting.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001862Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Philip Reames7a6db4f2017-12-27 00:16:12 +00001863 if (Value *V = SimplifyCall(&CI, SQ.getWithInstruction(&CI)))
Sanjay Patel4b198802016-02-01 22:23:39 +00001864 return replaceInstUsesWith(CI, V);
David Majnemer15032582015-05-22 03:56:46 +00001865
Justin Bogner99798402016-08-05 01:06:44 +00001866 if (isFreeCall(&CI, &TLI))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001867 return visitFree(CI);
1868
1869 // If the caller function is nounwind, mark the call as nounwind, even if the
1870 // callee isn't.
Sanjay Patel5a470952016-08-11 15:16:06 +00001871 if (CI.getFunction()->doesNotThrow() && !CI.doesNotThrow()) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001872 CI.setDoesNotThrow();
1873 return &CI;
1874 }
Jim Grosbach7815f562012-02-03 00:07:04 +00001875
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001876 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
1877 if (!II) return visitCallSite(&CI);
Gabor Greif589a0b92010-06-24 12:58:35 +00001878
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001879 // Intrinsics cannot occur in an invoke, so handle them here instead of in
1880 // visitCallSite.
Daniel Neilson8f30ec62018-05-11 14:30:02 +00001881 if (auto *MI = dyn_cast<AnyMemIntrinsic>(II)) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001882 bool Changed = false;
1883
1884 // memmove/cpy/set of zero bytes is a noop.
1885 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
Chris Lattnerc663a672010-10-01 05:51:02 +00001886 if (NumBytes->isNullValue())
Sanjay Patel4b198802016-02-01 22:23:39 +00001887 return eraseInstFromFunction(CI);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001888
1889 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
1890 if (CI->getZExtValue() == 1) {
1891 // Replace the instruction with just byte operations. We would
1892 // transform other cases to loads/stores, but we don't know if
1893 // alignment is sufficient.
1894 }
1895 }
Jim Grosbach7815f562012-02-03 00:07:04 +00001896
Chris Lattnerc663a672010-10-01 05:51:02 +00001897 // No other transformations apply to volatile transfers.
Daniel Neilson8f30ec62018-05-11 14:30:02 +00001898 if (auto *M = dyn_cast<MemIntrinsic>(MI))
1899 if (M->isVolatile())
1900 return nullptr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001901
1902 // If we have a memmove and the source operation is a constant global,
1903 // then the source and dest pointers can't alias, so we can change this
1904 // into a call to memcpy.
Daniel Neilson8f30ec62018-05-11 14:30:02 +00001905 if (auto *MMI = dyn_cast<AnyMemMoveInst>(MI)) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001906 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
1907 if (GVSrc->isConstant()) {
Sanjay Patelaf674fb2015-12-14 17:24:23 +00001908 Module *M = CI.getModule();
Daniel Neilson8f30ec62018-05-11 14:30:02 +00001909 Intrinsic::ID MemCpyID =
1910 isa<AtomicMemMoveInst>(MMI)
1911 ? Intrinsic::memcpy_element_unordered_atomic
1912 : Intrinsic::memcpy;
Jay Foadb804a2b2011-07-12 14:06:48 +00001913 Type *Tys[3] = { CI.getArgOperand(0)->getType(),
1914 CI.getArgOperand(1)->getType(),
1915 CI.getArgOperand(2)->getType() };
Benjamin Kramere6e19332011-07-14 17:45:39 +00001916 CI.setCalledFunction(Intrinsic::getDeclaration(M, MemCpyID, Tys));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001917 Changed = true;
1918 }
1919 }
1920
Daniel Neilson8f30ec62018-05-11 14:30:02 +00001921 if (AnyMemTransferInst *MTI = dyn_cast<AnyMemTransferInst>(MI)) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001922 // memmove(x,x,size) -> noop.
1923 if (MTI->getSource() == MTI->getDest())
Sanjay Patel4b198802016-02-01 22:23:39 +00001924 return eraseInstFromFunction(CI);
Eric Christopher7258dcd2010-04-16 23:37:20 +00001925 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001926
Eric Christopher7258dcd2010-04-16 23:37:20 +00001927 // If we can determine a pointer alignment that is bigger than currently
1928 // set, update the alignment.
Daniel Neilson8f30ec62018-05-11 14:30:02 +00001929 if (auto *MTI = dyn_cast<AnyMemTransferInst>(MI)) {
1930 if (Instruction *I = SimplifyAnyMemTransfer(MTI))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001931 return I;
Daniel Neilsonf6651d42018-05-11 20:04:50 +00001932 } else if (auto *MSI = dyn_cast<AnyMemSetInst>(MI)) {
1933 if (Instruction *I = SimplifyAnyMemSet(MSI))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001934 return I;
1935 }
Gabor Greif590d95e2010-06-24 13:42:49 +00001936
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001937 if (Changed) return II;
1938 }
Jim Grosbach7815f562012-02-03 00:07:04 +00001939
Justin Lebar698c31b2017-01-27 00:58:58 +00001940 if (Instruction *I = SimplifyNVVMIntrinsic(II, *this))
1941 return I;
1942
Sanjay Patel1c600c62016-01-20 16:41:43 +00001943 auto SimplifyDemandedVectorEltsLow = [this](Value *Op, unsigned Width,
1944 unsigned DemandedWidth) {
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001945 APInt UndefElts(Width, 0);
1946 APInt DemandedElts = APInt::getLowBitsSet(Width, DemandedWidth);
1947 return SimplifyDemandedVectorElts(Op, DemandedElts, UndefElts);
1948 };
1949
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001950 switch (II->getIntrinsicID()) {
1951 default: break;
George Burgess IV3f089142016-12-20 23:46:36 +00001952 case Intrinsic::objectsize:
1953 if (ConstantInt *N =
1954 lowerObjectSizeCall(II, DL, &TLI, /*MustSucceed=*/false))
1955 return replaceInstUsesWith(CI, N);
Craig Topperf40110f2014-04-25 05:29:35 +00001956 return nullptr;
Michael Ilseman536cc322012-12-13 03:13:36 +00001957 case Intrinsic::bswap: {
1958 Value *IIOperand = II->getArgOperand(0);
Craig Topperf40110f2014-04-25 05:29:35 +00001959 Value *X = nullptr;
Michael Ilseman536cc322012-12-13 03:13:36 +00001960
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001961 // bswap(trunc(bswap(x))) -> trunc(lshr(x, c))
Michael Ilseman536cc322012-12-13 03:13:36 +00001962 if (match(IIOperand, m_Trunc(m_BSwap(m_Value(X))))) {
1963 unsigned C = X->getType()->getPrimitiveSizeInBits() -
1964 IIOperand->getType()->getPrimitiveSizeInBits();
1965 Value *CV = ConstantInt::get(X->getType(), C);
Craig Topperbb4069e2017-07-07 23:16:26 +00001966 Value *V = Builder.CreateLShr(X, CV);
Michael Ilseman536cc322012-12-13 03:13:36 +00001967 return new TruncInst(V, IIOperand->getType());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001968 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001969 break;
Michael Ilseman536cc322012-12-13 03:13:36 +00001970 }
Sanjay Patelb695c552016-02-01 17:00:10 +00001971 case Intrinsic::masked_load:
Craig Topperbb4069e2017-07-07 23:16:26 +00001972 if (Value *SimplifiedMaskedOp = simplifyMaskedLoad(*II, Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00001973 return replaceInstUsesWith(CI, SimplifiedMaskedOp);
Sanjay Patelb695c552016-02-01 17:00:10 +00001974 break;
Sanjay Patel04f792b2016-02-01 19:39:52 +00001975 case Intrinsic::masked_store:
1976 return simplifyMaskedStore(*II, *this);
Sanjay Patel103ab7d2016-02-01 22:10:26 +00001977 case Intrinsic::masked_gather:
1978 return simplifyMaskedGather(*II, *this);
1979 case Intrinsic::masked_scatter:
1980 return simplifyMaskedScatter(*II, *this);
Piotr Padlewskic63b4922018-07-12 23:55:20 +00001981 case Intrinsic::launder_invariant_group:
1982 case Intrinsic::strip_invariant_group:
1983 if (auto *SkippedBarrier = simplifyInvariantGroupIntrinsic(*II, *this))
1984 return replaceInstUsesWith(*II, SkippedBarrier);
1985 break;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001986 case Intrinsic::powi:
Gabor Greif589a0b92010-06-24 12:58:35 +00001987 if (ConstantInt *Power = dyn_cast<ConstantInt>(II->getArgOperand(1))) {
Philip Reames5000ba62017-12-27 01:14:30 +00001988 // 0 and 1 are handled in instsimplify
1989
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001990 // powi(x, -1) -> 1/x
Craig Topper79ab6432017-07-06 18:39:47 +00001991 if (Power->isMinusOne())
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001992 return BinaryOperator::CreateFDiv(ConstantFP::get(CI.getType(), 1.0),
Gabor Greif589a0b92010-06-24 12:58:35 +00001993 II->getArgOperand(0));
Philip Reamescd13a662017-12-27 01:30:12 +00001994 // powi(x, 2) -> x*x
1995 if (Power->equalsInt(2))
1996 return BinaryOperator::CreateFMul(II->getArgOperand(0),
1997 II->getArgOperand(0));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001998 }
1999 break;
Jim Grosbach7815f562012-02-03 00:07:04 +00002000
Sanjay Patel8e3ab172016-08-05 22:42:46 +00002001 case Intrinsic::cttz:
2002 case Intrinsic::ctlz:
Amaury Sechet763c59d2016-08-18 20:43:50 +00002003 if (auto *I = foldCttzCtlz(*II, *this))
2004 return I;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002005 break;
Sanjoy Dasb0984472015-04-08 04:27:22 +00002006
Craig Topper5b173f22017-06-21 16:32:35 +00002007 case Intrinsic::ctpop:
2008 if (auto *I = foldCtpop(*II, *this))
2009 return I;
2010 break;
2011
Nick Lewyckyabe2cc12015-04-13 19:17:37 +00002012 case Intrinsic::uadd_with_overflow:
2013 case Intrinsic::sadd_with_overflow:
2014 case Intrinsic::umul_with_overflow:
2015 case Intrinsic::smul_with_overflow:
Gabor Greif5b1370e2010-06-28 16:50:57 +00002016 if (isa<Constant>(II->getArgOperand(0)) &&
2017 !isa<Constant>(II->getArgOperand(1))) {
Sanjoy Dasb0984472015-04-08 04:27:22 +00002018 // Canonicalize constants into the RHS.
Gabor Greif5b1370e2010-06-28 16:50:57 +00002019 Value *LHS = II->getArgOperand(0);
2020 II->setArgOperand(0, II->getArgOperand(1));
2021 II->setArgOperand(1, LHS);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002022 return II;
2023 }
Justin Bognercd1d5aa2016-08-17 20:30:52 +00002024 LLVM_FALLTHROUGH;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002025
Nick Lewyckyabe2cc12015-04-13 19:17:37 +00002026 case Intrinsic::usub_with_overflow:
2027 case Intrinsic::ssub_with_overflow: {
Sanjoy Dasb0984472015-04-08 04:27:22 +00002028 OverflowCheckFlavor OCF =
2029 IntrinsicIDToOverflowCheckFlavor(II->getIntrinsicID());
2030 assert(OCF != OCF_INVALID && "unexpected!");
Jim Grosbach7815f562012-02-03 00:07:04 +00002031
Sanjoy Dasb0984472015-04-08 04:27:22 +00002032 Value *OperationResult = nullptr;
2033 Constant *OverflowResult = nullptr;
2034 if (OptimizeOverflowCheck(OCF, II->getArgOperand(0), II->getArgOperand(1),
2035 *II, OperationResult, OverflowResult))
2036 return CreateOverflowTuple(II, OperationResult, OverflowResult);
Benjamin Kramera420df22014-07-04 10:22:21 +00002037
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002038 break;
Erik Eckstein096ff7d2014-12-11 08:02:30 +00002039 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002040
Matt Arsenaultd6511b42014-10-21 23:00:20 +00002041 case Intrinsic::minnum:
2042 case Intrinsic::maxnum: {
2043 Value *Arg0 = II->getArgOperand(0);
2044 Value *Arg1 = II->getArgOperand(1);
Sanjay Patel0069f562016-01-31 16:35:23 +00002045 // Canonicalize constants to the RHS.
2046 if (isa<ConstantFP>(Arg0) && !isa<ConstantFP>(Arg1)) {
Matt Arsenaultd6511b42014-10-21 23:00:20 +00002047 II->setArgOperand(0, Arg1);
2048 II->setArgOperand(1, Arg0);
2049 return II;
2050 }
Sanjay Patelc7bb1432018-05-10 20:03:13 +00002051
Sanjay Patelc7bb1432018-05-10 20:03:13 +00002052 Value *X, *Y;
2053 if (match(Arg0, m_FNeg(m_Value(X))) && match(Arg1, m_FNeg(m_Value(Y))) &&
2054 (Arg0->hasOneUse() || Arg1->hasOneUse())) {
2055 // If both operands are negated, invert the call and negate the result:
2056 // minnum(-X, -Y) --> -(maxnum(X, Y))
2057 // maxnum(-X, -Y) --> -(minnum(X, Y))
2058 Intrinsic::ID NewIID = II->getIntrinsicID() == Intrinsic::maxnum ?
2059 Intrinsic::minnum : Intrinsic::maxnum;
2060 Value *NewCall = Builder.CreateIntrinsic(NewIID, { X, Y }, II);
2061 Instruction *FNeg = BinaryOperator::CreateFNeg(NewCall);
2062 FNeg->copyIRFlags(II);
2063 return FNeg;
2064 }
Matt Arsenaultd6511b42014-10-21 23:00:20 +00002065 break;
2066 }
Matt Arsenault1cc294c2017-01-03 04:32:31 +00002067 case Intrinsic::fmuladd: {
Matt Arsenault92057602017-02-16 18:46:24 +00002068 // Canonicalize fast fmuladd to the separate fmul + fadd.
Sanjay Patel629c4112017-11-06 16:27:15 +00002069 if (II->isFast()) {
Craig Topperbb4069e2017-07-07 23:16:26 +00002070 BuilderTy::FastMathFlagGuard Guard(Builder);
2071 Builder.setFastMathFlags(II->getFastMathFlags());
2072 Value *Mul = Builder.CreateFMul(II->getArgOperand(0),
2073 II->getArgOperand(1));
2074 Value *Add = Builder.CreateFAdd(Mul, II->getArgOperand(2));
Matt Arsenault92057602017-02-16 18:46:24 +00002075 Add->takeName(II);
2076 return replaceInstUsesWith(*II, Add);
2077 }
2078
2079 LLVM_FALLTHROUGH;
2080 }
2081 case Intrinsic::fma: {
Matt Arsenault1cc294c2017-01-03 04:32:31 +00002082 Value *Src0 = II->getArgOperand(0);
2083 Value *Src1 = II->getArgOperand(1);
2084
Sanjay Patel236442e2018-04-05 13:24:26 +00002085 // Canonicalize constant multiply operand to Src1.
Matt Arsenaultb264c942017-01-03 04:32:35 +00002086 if (isa<Constant>(Src0) && !isa<Constant>(Src1)) {
2087 II->setArgOperand(0, Src1);
2088 II->setArgOperand(1, Src0);
2089 std::swap(Src0, Src1);
2090 }
2091
Matt Arsenault1cc294c2017-01-03 04:32:31 +00002092 // fma fneg(x), fneg(y), z -> fma x, y, z
Sanjay Patel236442e2018-04-05 13:24:26 +00002093 Value *X, *Y;
2094 if (match(Src0, m_FNeg(m_Value(X))) && match(Src1, m_FNeg(m_Value(Y)))) {
2095 II->setArgOperand(0, X);
2096 II->setArgOperand(1, Y);
Matt Arsenault3f509042017-01-10 23:17:52 +00002097 return II;
Matt Arsenault1cc294c2017-01-03 04:32:31 +00002098 }
2099
2100 // fma fabs(x), fabs(x), z -> fma x, x, z
Matt Arsenaultd1496502018-07-27 09:04:35 +00002101 if (match(Src0, m_FAbs(m_Value(X))) &&
2102 match(Src1, m_FAbs(m_Specific(X)))) {
Sanjay Patel236442e2018-04-05 13:24:26 +00002103 II->setArgOperand(0, X);
2104 II->setArgOperand(1, X);
Matt Arsenault3f509042017-01-10 23:17:52 +00002105 return II;
Matt Arsenault1cc294c2017-01-03 04:32:31 +00002106 }
2107
Matt Arsenaultb264c942017-01-03 04:32:35 +00002108 // fma x, 1, z -> fadd x, z
2109 if (match(Src1, m_FPOne())) {
Sanjay Patel236442e2018-04-05 13:24:26 +00002110 auto *FAdd = BinaryOperator::CreateFAdd(Src0, II->getArgOperand(2));
2111 FAdd->copyFastMathFlags(II);
2112 return FAdd;
Matt Arsenaultb264c942017-01-03 04:32:35 +00002113 }
2114
Matt Arsenault1cc294c2017-01-03 04:32:31 +00002115 break;
2116 }
Matt Arsenault56ff4832017-01-03 22:40:34 +00002117 case Intrinsic::fabs: {
2118 Value *Cond;
2119 Constant *LHS, *RHS;
2120 if (match(II->getArgOperand(0),
2121 m_Select(m_Value(Cond), m_Constant(LHS), m_Constant(RHS)))) {
Craig Topperbb4069e2017-07-07 23:16:26 +00002122 CallInst *Call0 = Builder.CreateCall(II->getCalledFunction(), {LHS});
2123 CallInst *Call1 = Builder.CreateCall(II->getCalledFunction(), {RHS});
Matt Arsenault56ff4832017-01-03 22:40:34 +00002124 return SelectInst::Create(Cond, Call0, Call1);
2125 }
2126
Matt Arsenault954a6242017-01-23 23:55:08 +00002127 LLVM_FALLTHROUGH;
2128 }
2129 case Intrinsic::ceil:
2130 case Intrinsic::floor:
2131 case Intrinsic::round:
2132 case Intrinsic::nearbyint:
Joerg Sonnenberger28bed102017-03-31 19:58:07 +00002133 case Intrinsic::rint:
Matt Arsenault954a6242017-01-23 23:55:08 +00002134 case Intrinsic::trunc: {
Matt Arsenault72333442017-01-17 00:10:40 +00002135 Value *ExtSrc;
Sanjay Patel32381d72018-03-23 21:18:12 +00002136 if (match(II->getArgOperand(0), m_OneUse(m_FPExt(m_Value(ExtSrc))))) {
2137 // Narrow the call: intrinsic (fpext x) -> fpext (intrinsic x)
2138 Value *NarrowII = Builder.CreateIntrinsic(II->getIntrinsicID(),
2139 { ExtSrc }, II);
2140 return new FPExtInst(NarrowII, II->getType());
Matt Arsenault72333442017-01-17 00:10:40 +00002141 }
Matt Arsenault56ff4832017-01-03 22:40:34 +00002142 break;
2143 }
Matt Arsenault3bdd75d2017-01-04 22:49:03 +00002144 case Intrinsic::cos:
2145 case Intrinsic::amdgcn_cos: {
2146 Value *SrcSrc;
2147 Value *Src = II->getArgOperand(0);
2148 if (match(Src, m_FNeg(m_Value(SrcSrc))) ||
Matt Arsenaultd1496502018-07-27 09:04:35 +00002149 match(Src, m_FAbs(m_Value(SrcSrc)))) {
Matt Arsenault3bdd75d2017-01-04 22:49:03 +00002150 // cos(-x) -> cos(x)
2151 // cos(fabs(x)) -> cos(x)
2152 II->setArgOperand(0, SrcSrc);
2153 return II;
2154 }
2155
2156 break;
2157 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002158 case Intrinsic::ppc_altivec_lvx:
2159 case Intrinsic::ppc_altivec_lvxl:
Bill Wendlingb902f1d2011-04-13 00:36:11 +00002160 // Turn PPC lvx -> load if the pointer is known aligned.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002161 if (getOrEnforceKnownAlignment(II->getArgOperand(0), 16, DL, II, &AC,
Justin Bogner99798402016-08-05 01:06:44 +00002162 &DT) >= 16) {
Craig Topperbb4069e2017-07-07 23:16:26 +00002163 Value *Ptr = Builder.CreateBitCast(II->getArgOperand(0),
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002164 PointerType::getUnqual(II->getType()));
2165 return new LoadInst(Ptr);
2166 }
2167 break;
Bill Schmidt72954782014-11-12 04:19:40 +00002168 case Intrinsic::ppc_vsx_lxvw4x:
2169 case Intrinsic::ppc_vsx_lxvd2x: {
2170 // Turn PPC VSX loads into normal loads.
Craig Topperbb4069e2017-07-07 23:16:26 +00002171 Value *Ptr = Builder.CreateBitCast(II->getArgOperand(0),
2172 PointerType::getUnqual(II->getType()));
Bill Schmidt72954782014-11-12 04:19:40 +00002173 return new LoadInst(Ptr, Twine(""), false, 1);
2174 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002175 case Intrinsic::ppc_altivec_stvx:
2176 case Intrinsic::ppc_altivec_stvxl:
2177 // Turn stvx -> store if the pointer is known aligned.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002178 if (getOrEnforceKnownAlignment(II->getArgOperand(1), 16, DL, II, &AC,
Justin Bogner99798402016-08-05 01:06:44 +00002179 &DT) >= 16) {
Jim Grosbach7815f562012-02-03 00:07:04 +00002180 Type *OpPtrTy =
Gabor Greifa6d75e22010-06-24 15:51:11 +00002181 PointerType::getUnqual(II->getArgOperand(0)->getType());
Craig Topperbb4069e2017-07-07 23:16:26 +00002182 Value *Ptr = Builder.CreateBitCast(II->getArgOperand(1), OpPtrTy);
Gabor Greifa6d75e22010-06-24 15:51:11 +00002183 return new StoreInst(II->getArgOperand(0), Ptr);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002184 }
2185 break;
Bill Schmidt72954782014-11-12 04:19:40 +00002186 case Intrinsic::ppc_vsx_stxvw4x:
2187 case Intrinsic::ppc_vsx_stxvd2x: {
2188 // Turn PPC VSX stores into normal stores.
2189 Type *OpPtrTy = PointerType::getUnqual(II->getArgOperand(0)->getType());
Craig Topperbb4069e2017-07-07 23:16:26 +00002190 Value *Ptr = Builder.CreateBitCast(II->getArgOperand(1), OpPtrTy);
Bill Schmidt72954782014-11-12 04:19:40 +00002191 return new StoreInst(II->getArgOperand(0), Ptr, false, 1);
2192 }
Hal Finkel221f4672015-02-26 18:56:03 +00002193 case Intrinsic::ppc_qpx_qvlfs:
2194 // Turn PPC QPX qvlfs -> load if the pointer is known aligned.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002195 if (getOrEnforceKnownAlignment(II->getArgOperand(0), 16, DL, II, &AC,
Justin Bogner99798402016-08-05 01:06:44 +00002196 &DT) >= 16) {
Craig Topperbb4069e2017-07-07 23:16:26 +00002197 Type *VTy = VectorType::get(Builder.getFloatTy(),
Hal Finkelf0d68d72015-05-11 06:37:03 +00002198 II->getType()->getVectorNumElements());
Craig Topperbb4069e2017-07-07 23:16:26 +00002199 Value *Ptr = Builder.CreateBitCast(II->getArgOperand(0),
Hal Finkelf0d68d72015-05-11 06:37:03 +00002200 PointerType::getUnqual(VTy));
Craig Topperbb4069e2017-07-07 23:16:26 +00002201 Value *Load = Builder.CreateLoad(Ptr);
Hal Finkelf0d68d72015-05-11 06:37:03 +00002202 return new FPExtInst(Load, II->getType());
Hal Finkel221f4672015-02-26 18:56:03 +00002203 }
2204 break;
2205 case Intrinsic::ppc_qpx_qvlfd:
2206 // Turn PPC QPX qvlfd -> load if the pointer is known aligned.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002207 if (getOrEnforceKnownAlignment(II->getArgOperand(0), 32, DL, II, &AC,
Justin Bogner99798402016-08-05 01:06:44 +00002208 &DT) >= 32) {
Craig Topperbb4069e2017-07-07 23:16:26 +00002209 Value *Ptr = Builder.CreateBitCast(II->getArgOperand(0),
Hal Finkel221f4672015-02-26 18:56:03 +00002210 PointerType::getUnqual(II->getType()));
2211 return new LoadInst(Ptr);
2212 }
2213 break;
2214 case Intrinsic::ppc_qpx_qvstfs:
2215 // Turn PPC QPX qvstfs -> store if the pointer is known aligned.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002216 if (getOrEnforceKnownAlignment(II->getArgOperand(1), 16, DL, II, &AC,
Justin Bogner99798402016-08-05 01:06:44 +00002217 &DT) >= 16) {
Craig Topperbb4069e2017-07-07 23:16:26 +00002218 Type *VTy = VectorType::get(Builder.getFloatTy(),
Hal Finkelf0d68d72015-05-11 06:37:03 +00002219 II->getArgOperand(0)->getType()->getVectorNumElements());
Craig Topperbb4069e2017-07-07 23:16:26 +00002220 Value *TOp = Builder.CreateFPTrunc(II->getArgOperand(0), VTy);
Hal Finkelf0d68d72015-05-11 06:37:03 +00002221 Type *OpPtrTy = PointerType::getUnqual(VTy);
Craig Topperbb4069e2017-07-07 23:16:26 +00002222 Value *Ptr = Builder.CreateBitCast(II->getArgOperand(1), OpPtrTy);
Hal Finkelf0d68d72015-05-11 06:37:03 +00002223 return new StoreInst(TOp, Ptr);
Hal Finkel221f4672015-02-26 18:56:03 +00002224 }
2225 break;
2226 case Intrinsic::ppc_qpx_qvstfd:
2227 // Turn PPC QPX qvstfd -> store if the pointer is known aligned.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002228 if (getOrEnforceKnownAlignment(II->getArgOperand(1), 32, DL, II, &AC,
Justin Bogner99798402016-08-05 01:06:44 +00002229 &DT) >= 32) {
Hal Finkel221f4672015-02-26 18:56:03 +00002230 Type *OpPtrTy =
2231 PointerType::getUnqual(II->getArgOperand(0)->getType());
Craig Topperbb4069e2017-07-07 23:16:26 +00002232 Value *Ptr = Builder.CreateBitCast(II->getArgOperand(1), OpPtrTy);
Hal Finkel221f4672015-02-26 18:56:03 +00002233 return new StoreInst(II->getArgOperand(0), Ptr);
2234 }
2235 break;
Simon Pilgrim20c607b2015-09-12 13:39:53 +00002236
Craig Topper83240032017-07-31 18:52:13 +00002237 case Intrinsic::x86_bmi_bextr_32:
2238 case Intrinsic::x86_bmi_bextr_64:
2239 case Intrinsic::x86_tbm_bextri_u32:
2240 case Intrinsic::x86_tbm_bextri_u64:
2241 // If the RHS is a constant we can try some simplifications.
2242 if (auto *C = dyn_cast<ConstantInt>(II->getArgOperand(1))) {
2243 uint64_t Shift = C->getZExtValue();
2244 uint64_t Length = (Shift >> 8) & 0xff;
2245 Shift &= 0xff;
2246 unsigned BitWidth = II->getType()->getIntegerBitWidth();
2247 // If the length is 0 or the shift is out of range, replace with zero.
2248 if (Length == 0 || Shift >= BitWidth)
2249 return replaceInstUsesWith(CI, ConstantInt::get(II->getType(), 0));
2250 // If the LHS is also a constant, we can completely constant fold this.
2251 if (auto *InC = dyn_cast<ConstantInt>(II->getArgOperand(0))) {
2252 uint64_t Result = InC->getZExtValue() >> Shift;
2253 if (Length > BitWidth)
2254 Length = BitWidth;
2255 Result &= maskTrailingOnes<uint64_t>(Length);
2256 return replaceInstUsesWith(CI, ConstantInt::get(II->getType(), Result));
2257 }
2258 // TODO should we turn this into 'and' if shift is 0? Or 'shl' if we
2259 // are only masking bits that a shift already cleared?
2260 }
2261 break;
2262
Craig Topper317a51e2017-07-31 18:52:15 +00002263 case Intrinsic::x86_bmi_bzhi_32:
2264 case Intrinsic::x86_bmi_bzhi_64:
2265 // If the RHS is a constant we can try some simplifications.
2266 if (auto *C = dyn_cast<ConstantInt>(II->getArgOperand(1))) {
2267 uint64_t Index = C->getZExtValue() & 0xff;
2268 unsigned BitWidth = II->getType()->getIntegerBitWidth();
2269 if (Index >= BitWidth)
2270 return replaceInstUsesWith(CI, II->getArgOperand(0));
2271 if (Index == 0)
2272 return replaceInstUsesWith(CI, ConstantInt::get(II->getType(), 0));
2273 // If the LHS is also a constant, we can completely constant fold this.
2274 if (auto *InC = dyn_cast<ConstantInt>(II->getArgOperand(0))) {
2275 uint64_t Result = InC->getZExtValue();
2276 Result &= maskTrailingOnes<uint64_t>(Index);
2277 return replaceInstUsesWith(CI, ConstantInt::get(II->getType(), Result));
2278 }
2279 // TODO should we convert this to an AND if the RHS is constant?
2280 }
2281 break;
2282
Simon Pilgrim20c607b2015-09-12 13:39:53 +00002283 case Intrinsic::x86_vcvtph2ps_128:
2284 case Intrinsic::x86_vcvtph2ps_256: {
2285 auto Arg = II->getArgOperand(0);
2286 auto ArgType = cast<VectorType>(Arg->getType());
2287 auto RetType = cast<VectorType>(II->getType());
2288 unsigned ArgWidth = ArgType->getNumElements();
2289 unsigned RetWidth = RetType->getNumElements();
2290 assert(RetWidth <= ArgWidth && "Unexpected input/return vector widths");
2291 assert(ArgType->isIntOrIntVectorTy() &&
2292 ArgType->getScalarSizeInBits() == 16 &&
2293 "CVTPH2PS input type should be 16-bit integer vector");
2294 assert(RetType->getScalarType()->isFloatTy() &&
2295 "CVTPH2PS output type should be 32-bit float vector");
2296
2297 // Constant folding: Convert to generic half to single conversion.
Simon Pilgrim48ffca02015-09-12 14:00:17 +00002298 if (isa<ConstantAggregateZero>(Arg))
Sanjay Patel4b198802016-02-01 22:23:39 +00002299 return replaceInstUsesWith(*II, ConstantAggregateZero::get(RetType));
Simon Pilgrim20c607b2015-09-12 13:39:53 +00002300
Simon Pilgrim48ffca02015-09-12 14:00:17 +00002301 if (isa<ConstantDataVector>(Arg)) {
Simon Pilgrim20c607b2015-09-12 13:39:53 +00002302 auto VectorHalfAsShorts = Arg;
2303 if (RetWidth < ArgWidth) {
Craig Topper99d1eab2016-06-12 00:41:19 +00002304 SmallVector<uint32_t, 8> SubVecMask;
Simon Pilgrim20c607b2015-09-12 13:39:53 +00002305 for (unsigned i = 0; i != RetWidth; ++i)
2306 SubVecMask.push_back((int)i);
Craig Topperbb4069e2017-07-07 23:16:26 +00002307 VectorHalfAsShorts = Builder.CreateShuffleVector(
Simon Pilgrim20c607b2015-09-12 13:39:53 +00002308 Arg, UndefValue::get(ArgType), SubVecMask);
2309 }
2310
2311 auto VectorHalfType =
2312 VectorType::get(Type::getHalfTy(II->getContext()), RetWidth);
2313 auto VectorHalfs =
Craig Topperbb4069e2017-07-07 23:16:26 +00002314 Builder.CreateBitCast(VectorHalfAsShorts, VectorHalfType);
2315 auto VectorFloats = Builder.CreateFPExt(VectorHalfs, RetType);
Sanjay Patel4b198802016-02-01 22:23:39 +00002316 return replaceInstUsesWith(*II, VectorFloats);
Simon Pilgrim20c607b2015-09-12 13:39:53 +00002317 }
2318
2319 // We only use the lowest lanes of the argument.
Simon Pilgrim996725e2015-09-19 11:41:53 +00002320 if (Value *V = SimplifyDemandedVectorEltsLow(Arg, ArgWidth, RetWidth)) {
Simon Pilgrim20c607b2015-09-12 13:39:53 +00002321 II->setArgOperand(0, V);
2322 return II;
2323 }
2324 break;
2325 }
2326
Chandler Carruthcf414cf2011-01-10 07:19:37 +00002327 case Intrinsic::x86_sse_cvtss2si:
2328 case Intrinsic::x86_sse_cvtss2si64:
2329 case Intrinsic::x86_sse_cvttss2si:
2330 case Intrinsic::x86_sse_cvttss2si64:
2331 case Intrinsic::x86_sse2_cvtsd2si:
2332 case Intrinsic::x86_sse2_cvtsd2si64:
2333 case Intrinsic::x86_sse2_cvttsd2si:
Craig Topperaeaa52c2016-12-14 07:46:12 +00002334 case Intrinsic::x86_sse2_cvttsd2si64:
2335 case Intrinsic::x86_avx512_vcvtss2si32:
2336 case Intrinsic::x86_avx512_vcvtss2si64:
2337 case Intrinsic::x86_avx512_vcvtss2usi32:
2338 case Intrinsic::x86_avx512_vcvtss2usi64:
2339 case Intrinsic::x86_avx512_vcvtsd2si32:
2340 case Intrinsic::x86_avx512_vcvtsd2si64:
2341 case Intrinsic::x86_avx512_vcvtsd2usi32:
2342 case Intrinsic::x86_avx512_vcvtsd2usi64:
2343 case Intrinsic::x86_avx512_cvttss2si:
2344 case Intrinsic::x86_avx512_cvttss2si64:
2345 case Intrinsic::x86_avx512_cvttss2usi:
2346 case Intrinsic::x86_avx512_cvttss2usi64:
2347 case Intrinsic::x86_avx512_cvttsd2si:
2348 case Intrinsic::x86_avx512_cvttsd2si64:
2349 case Intrinsic::x86_avx512_cvttsd2usi:
2350 case Intrinsic::x86_avx512_cvttsd2usi64: {
Chandler Carruthcf414cf2011-01-10 07:19:37 +00002351 // These intrinsics only demand the 0th element of their input vectors. If
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002352 // we can simplify the input based on that, do so now.
Simon Pilgrim996725e2015-09-19 11:41:53 +00002353 Value *Arg = II->getArgOperand(0);
2354 unsigned VWidth = Arg->getType()->getVectorNumElements();
2355 if (Value *V = SimplifyDemandedVectorEltsLow(Arg, VWidth, 1)) {
Gabor Greif5b1370e2010-06-28 16:50:57 +00002356 II->setArgOperand(0, V);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002357 return II;
2358 }
Simon Pilgrim18617d12015-08-05 08:18:00 +00002359 break;
2360 }
2361
Mikhail Dvoretckii8393f902018-06-19 10:49:12 +00002362 case Intrinsic::x86_sse41_round_ps:
2363 case Intrinsic::x86_sse41_round_pd:
2364 case Intrinsic::x86_avx_round_ps_256:
2365 case Intrinsic::x86_avx_round_pd_256:
2366 case Intrinsic::x86_avx512_mask_rndscale_ps_128:
2367 case Intrinsic::x86_avx512_mask_rndscale_ps_256:
2368 case Intrinsic::x86_avx512_mask_rndscale_ps_512:
2369 case Intrinsic::x86_avx512_mask_rndscale_pd_128:
2370 case Intrinsic::x86_avx512_mask_rndscale_pd_256:
2371 case Intrinsic::x86_avx512_mask_rndscale_pd_512:
2372 case Intrinsic::x86_avx512_mask_rndscale_ss:
2373 case Intrinsic::x86_avx512_mask_rndscale_sd:
2374 if (Value *V = simplifyX86round(*II, Builder))
2375 return replaceInstUsesWith(*II, V);
2376 break;
2377
Simon Pilgrim91e3ac82016-06-07 08:18:35 +00002378 case Intrinsic::x86_mmx_pmovmskb:
2379 case Intrinsic::x86_sse_movmsk_ps:
2380 case Intrinsic::x86_sse2_movmsk_pd:
2381 case Intrinsic::x86_sse2_pmovmskb_128:
2382 case Intrinsic::x86_avx_movmsk_pd_256:
2383 case Intrinsic::x86_avx_movmsk_ps_256:
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +00002384 case Intrinsic::x86_avx2_pmovmskb:
Craig Topper4853c432017-07-06 23:18:42 +00002385 if (Value *V = simplifyX86movmsk(*II))
Simon Pilgrim91e3ac82016-06-07 08:18:35 +00002386 return replaceInstUsesWith(*II, V);
2387 break;
Simon Pilgrim91e3ac82016-06-07 08:18:35 +00002388
Simon Pilgrim471efd22016-02-20 23:17:35 +00002389 case Intrinsic::x86_sse_comieq_ss:
2390 case Intrinsic::x86_sse_comige_ss:
2391 case Intrinsic::x86_sse_comigt_ss:
2392 case Intrinsic::x86_sse_comile_ss:
2393 case Intrinsic::x86_sse_comilt_ss:
2394 case Intrinsic::x86_sse_comineq_ss:
2395 case Intrinsic::x86_sse_ucomieq_ss:
2396 case Intrinsic::x86_sse_ucomige_ss:
2397 case Intrinsic::x86_sse_ucomigt_ss:
2398 case Intrinsic::x86_sse_ucomile_ss:
2399 case Intrinsic::x86_sse_ucomilt_ss:
2400 case Intrinsic::x86_sse_ucomineq_ss:
2401 case Intrinsic::x86_sse2_comieq_sd:
2402 case Intrinsic::x86_sse2_comige_sd:
2403 case Intrinsic::x86_sse2_comigt_sd:
2404 case Intrinsic::x86_sse2_comile_sd:
2405 case Intrinsic::x86_sse2_comilt_sd:
2406 case Intrinsic::x86_sse2_comineq_sd:
2407 case Intrinsic::x86_sse2_ucomieq_sd:
2408 case Intrinsic::x86_sse2_ucomige_sd:
2409 case Intrinsic::x86_sse2_ucomigt_sd:
2410 case Intrinsic::x86_sse2_ucomile_sd:
2411 case Intrinsic::x86_sse2_ucomilt_sd:
Craig Topperd9639532016-12-11 07:42:04 +00002412 case Intrinsic::x86_sse2_ucomineq_sd:
Craig Topperd00db692016-12-31 00:45:06 +00002413 case Intrinsic::x86_avx512_vcomi_ss:
2414 case Intrinsic::x86_avx512_vcomi_sd:
Craig Topperd9639532016-12-11 07:42:04 +00002415 case Intrinsic::x86_avx512_mask_cmp_ss:
2416 case Intrinsic::x86_avx512_mask_cmp_sd: {
Simon Pilgrim471efd22016-02-20 23:17:35 +00002417 // These intrinsics only demand the 0th element of their input vectors. If
2418 // we can simplify the input based on that, do so now.
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002419 bool MadeChange = false;
Simon Pilgrim471efd22016-02-20 23:17:35 +00002420 Value *Arg0 = II->getArgOperand(0);
2421 Value *Arg1 = II->getArgOperand(1);
2422 unsigned VWidth = Arg0->getType()->getVectorNumElements();
2423 if (Value *V = SimplifyDemandedVectorEltsLow(Arg0, VWidth, 1)) {
2424 II->setArgOperand(0, V);
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002425 MadeChange = true;
Simon Pilgrim471efd22016-02-20 23:17:35 +00002426 }
2427 if (Value *V = SimplifyDemandedVectorEltsLow(Arg1, VWidth, 1)) {
2428 II->setArgOperand(1, V);
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002429 MadeChange = true;
Simon Pilgrim471efd22016-02-20 23:17:35 +00002430 }
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002431 if (MadeChange)
2432 return II;
Simon Pilgrim471efd22016-02-20 23:17:35 +00002433 break;
2434 }
Craig Topper31cbe752018-06-27 15:57:53 +00002435 case Intrinsic::x86_avx512_cmp_pd_128:
2436 case Intrinsic::x86_avx512_cmp_pd_256:
2437 case Intrinsic::x86_avx512_cmp_pd_512:
2438 case Intrinsic::x86_avx512_cmp_ps_128:
2439 case Intrinsic::x86_avx512_cmp_ps_256:
2440 case Intrinsic::x86_avx512_cmp_ps_512: {
Michael Zuckerman16b20d22017-04-16 13:26:08 +00002441 // Folding cmp(sub(a,b),0) -> cmp(a,b) and cmp(0,sub(a,b)) -> cmp(b,a)
2442 Value *Arg0 = II->getArgOperand(0);
2443 Value *Arg1 = II->getArgOperand(1);
Sanjay Patel93e64dd2018-03-25 21:16:33 +00002444 bool Arg0IsZero = match(Arg0, m_PosZeroFP());
Michael Zuckerman16b20d22017-04-16 13:26:08 +00002445 if (Arg0IsZero)
2446 std::swap(Arg0, Arg1);
2447 Value *A, *B;
2448 // This fold requires only the NINF(not +/- inf) since inf minus
2449 // inf is nan.
2450 // NSZ(No Signed Zeros) is not needed because zeros of any sign are
2451 // equal for both compares.
2452 // NNAN is not needed because nans compare the same for both compares.
2453 // The compare intrinsic uses the above assumptions and therefore
2454 // doesn't require additional flags.
2455 if ((match(Arg0, m_OneUse(m_FSub(m_Value(A), m_Value(B)))) &&
Sanjay Patel93e64dd2018-03-25 21:16:33 +00002456 match(Arg1, m_PosZeroFP()) && isa<Instruction>(Arg0) &&
Michael Zuckerman16b20d22017-04-16 13:26:08 +00002457 cast<Instruction>(Arg0)->getFastMathFlags().noInfs())) {
2458 if (Arg0IsZero)
2459 std::swap(A, B);
2460 II->setArgOperand(0, A);
2461 II->setArgOperand(1, B);
2462 return II;
2463 }
2464 break;
2465 }
Simon Pilgrim471efd22016-02-20 23:17:35 +00002466
Craig Topper98a79932018-06-10 06:01:36 +00002467 case Intrinsic::x86_avx512_add_ps_512:
2468 case Intrinsic::x86_avx512_div_ps_512:
2469 case Intrinsic::x86_avx512_mul_ps_512:
2470 case Intrinsic::x86_avx512_sub_ps_512:
2471 case Intrinsic::x86_avx512_add_pd_512:
2472 case Intrinsic::x86_avx512_div_pd_512:
2473 case Intrinsic::x86_avx512_mul_pd_512:
2474 case Intrinsic::x86_avx512_sub_pd_512:
Craig Topper020b2282016-12-27 00:23:16 +00002475 // If the rounding mode is CUR_DIRECTION(4) we can turn these into regular
2476 // IR operations.
Craig Topper98a79932018-06-10 06:01:36 +00002477 if (auto *R = dyn_cast<ConstantInt>(II->getArgOperand(2))) {
Craig Topper020b2282016-12-27 00:23:16 +00002478 if (R->getValue() == 4) {
2479 Value *Arg0 = II->getArgOperand(0);
2480 Value *Arg1 = II->getArgOperand(1);
2481
2482 Value *V;
2483 switch (II->getIntrinsicID()) {
2484 default: llvm_unreachable("Case stmts out of sync!");
Craig Topper98a79932018-06-10 06:01:36 +00002485 case Intrinsic::x86_avx512_add_ps_512:
2486 case Intrinsic::x86_avx512_add_pd_512:
Craig Topperbb4069e2017-07-07 23:16:26 +00002487 V = Builder.CreateFAdd(Arg0, Arg1);
Craig Topper020b2282016-12-27 00:23:16 +00002488 break;
Craig Topper98a79932018-06-10 06:01:36 +00002489 case Intrinsic::x86_avx512_sub_ps_512:
2490 case Intrinsic::x86_avx512_sub_pd_512:
Craig Topperbb4069e2017-07-07 23:16:26 +00002491 V = Builder.CreateFSub(Arg0, Arg1);
Craig Topper020b2282016-12-27 00:23:16 +00002492 break;
Craig Topper98a79932018-06-10 06:01:36 +00002493 case Intrinsic::x86_avx512_mul_ps_512:
2494 case Intrinsic::x86_avx512_mul_pd_512:
Craig Topperbb4069e2017-07-07 23:16:26 +00002495 V = Builder.CreateFMul(Arg0, Arg1);
Craig Topper020b2282016-12-27 00:23:16 +00002496 break;
Craig Topper98a79932018-06-10 06:01:36 +00002497 case Intrinsic::x86_avx512_div_ps_512:
2498 case Intrinsic::x86_avx512_div_pd_512:
Craig Topperbb4069e2017-07-07 23:16:26 +00002499 V = Builder.CreateFDiv(Arg0, Arg1);
Craig Topper020b2282016-12-27 00:23:16 +00002500 break;
2501 }
2502
Craig Topper020b2282016-12-27 00:23:16 +00002503 return replaceInstUsesWith(*II, V);
2504 }
2505 }
2506 break;
2507
Craig Topper790d0fa2016-12-11 07:42:01 +00002508 case Intrinsic::x86_avx512_mask_add_ss_round:
2509 case Intrinsic::x86_avx512_mask_div_ss_round:
2510 case Intrinsic::x86_avx512_mask_mul_ss_round:
2511 case Intrinsic::x86_avx512_mask_sub_ss_round:
Craig Topper790d0fa2016-12-11 07:42:01 +00002512 case Intrinsic::x86_avx512_mask_add_sd_round:
2513 case Intrinsic::x86_avx512_mask_div_sd_round:
2514 case Intrinsic::x86_avx512_mask_mul_sd_round:
2515 case Intrinsic::x86_avx512_mask_sub_sd_round:
Craig Topper7b788ada2016-12-26 06:33:19 +00002516 // If the rounding mode is CUR_DIRECTION(4) we can turn these into regular
2517 // IR operations.
2518 if (auto *R = dyn_cast<ConstantInt>(II->getArgOperand(4))) {
2519 if (R->getValue() == 4) {
Craig Topper7f8540b2016-12-27 01:56:30 +00002520 // Extract the element as scalars.
2521 Value *Arg0 = II->getArgOperand(0);
2522 Value *Arg1 = II->getArgOperand(1);
Craig Topperbb4069e2017-07-07 23:16:26 +00002523 Value *LHS = Builder.CreateExtractElement(Arg0, (uint64_t)0);
2524 Value *RHS = Builder.CreateExtractElement(Arg1, (uint64_t)0);
Craig Topper7b788ada2016-12-26 06:33:19 +00002525
Craig Topper7f8540b2016-12-27 01:56:30 +00002526 Value *V;
2527 switch (II->getIntrinsicID()) {
2528 default: llvm_unreachable("Case stmts out of sync!");
2529 case Intrinsic::x86_avx512_mask_add_ss_round:
2530 case Intrinsic::x86_avx512_mask_add_sd_round:
Craig Topperbb4069e2017-07-07 23:16:26 +00002531 V = Builder.CreateFAdd(LHS, RHS);
Craig Topper7f8540b2016-12-27 01:56:30 +00002532 break;
2533 case Intrinsic::x86_avx512_mask_sub_ss_round:
2534 case Intrinsic::x86_avx512_mask_sub_sd_round:
Craig Topperbb4069e2017-07-07 23:16:26 +00002535 V = Builder.CreateFSub(LHS, RHS);
Craig Topper7f8540b2016-12-27 01:56:30 +00002536 break;
2537 case Intrinsic::x86_avx512_mask_mul_ss_round:
2538 case Intrinsic::x86_avx512_mask_mul_sd_round:
Craig Topperbb4069e2017-07-07 23:16:26 +00002539 V = Builder.CreateFMul(LHS, RHS);
Craig Topper7f8540b2016-12-27 01:56:30 +00002540 break;
2541 case Intrinsic::x86_avx512_mask_div_ss_round:
2542 case Intrinsic::x86_avx512_mask_div_sd_round:
Craig Topperbb4069e2017-07-07 23:16:26 +00002543 V = Builder.CreateFDiv(LHS, RHS);
Craig Topper7f8540b2016-12-27 01:56:30 +00002544 break;
Craig Topper7b788ada2016-12-26 06:33:19 +00002545 }
Craig Topper7f8540b2016-12-27 01:56:30 +00002546
2547 // Handle the masking aspect of the intrinsic.
Craig Topper7f8540b2016-12-27 01:56:30 +00002548 Value *Mask = II->getArgOperand(3);
Craig Topper99163632016-12-30 23:06:28 +00002549 auto *C = dyn_cast<ConstantInt>(Mask);
2550 // We don't need a select if we know the mask bit is a 1.
2551 if (!C || !C->getValue()[0]) {
2552 // Cast the mask to an i1 vector and then extract the lowest element.
Craig Topperbb4069e2017-07-07 23:16:26 +00002553 auto *MaskTy = VectorType::get(Builder.getInt1Ty(),
Craig Topper7f8540b2016-12-27 01:56:30 +00002554 cast<IntegerType>(Mask->getType())->getBitWidth());
Craig Topperbb4069e2017-07-07 23:16:26 +00002555 Mask = Builder.CreateBitCast(Mask, MaskTy);
2556 Mask = Builder.CreateExtractElement(Mask, (uint64_t)0);
Craig Topper99163632016-12-30 23:06:28 +00002557 // Extract the lowest element from the passthru operand.
Craig Topperbb4069e2017-07-07 23:16:26 +00002558 Value *Passthru = Builder.CreateExtractElement(II->getArgOperand(2),
Craig Topper99163632016-12-30 23:06:28 +00002559 (uint64_t)0);
Craig Topperbb4069e2017-07-07 23:16:26 +00002560 V = Builder.CreateSelect(Mask, V, Passthru);
Craig Topper99163632016-12-30 23:06:28 +00002561 }
Craig Topper7f8540b2016-12-27 01:56:30 +00002562
2563 // Insert the result back into the original argument 0.
Craig Topperbb4069e2017-07-07 23:16:26 +00002564 V = Builder.CreateInsertElement(Arg0, V, (uint64_t)0);
Craig Topper7f8540b2016-12-27 01:56:30 +00002565
2566 return replaceInstUsesWith(*II, V);
Craig Topper7b788ada2016-12-26 06:33:19 +00002567 }
2568 }
2569 LLVM_FALLTHROUGH;
2570
2571 // X86 scalar intrinsics simplified with SimplifyDemandedVectorElts.
2572 case Intrinsic::x86_avx512_mask_max_ss_round:
2573 case Intrinsic::x86_avx512_mask_min_ss_round:
Craig Topper790d0fa2016-12-11 07:42:01 +00002574 case Intrinsic::x86_avx512_mask_max_sd_round:
Craig Topper268b3ab2016-12-14 06:06:58 +00002575 case Intrinsic::x86_avx512_mask_min_sd_round:
Craig Toppera0372de2016-12-14 03:17:27 +00002576 case Intrinsic::x86_sse_cmp_ss:
2577 case Intrinsic::x86_sse_min_ss:
2578 case Intrinsic::x86_sse_max_ss:
2579 case Intrinsic::x86_sse2_cmp_sd:
2580 case Intrinsic::x86_sse2_min_sd:
2581 case Intrinsic::x86_sse2_max_sd:
Craig Topperac75bca2016-12-13 07:45:45 +00002582 case Intrinsic::x86_xop_vfrcz_ss:
2583 case Intrinsic::x86_xop_vfrcz_sd: {
2584 unsigned VWidth = II->getType()->getVectorNumElements();
2585 APInt UndefElts(VWidth, 0);
2586 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
2587 if (Value *V = SimplifyDemandedVectorElts(II, AllOnesEltMask, UndefElts)) {
2588 if (V != II)
2589 return replaceInstUsesWith(*II, V);
2590 return II;
2591 }
2592 break;
2593 }
Mikhail Dvoretckii8393f902018-06-19 10:49:12 +00002594 case Intrinsic::x86_sse41_round_ss:
2595 case Intrinsic::x86_sse41_round_sd: {
2596 unsigned VWidth = II->getType()->getVectorNumElements();
2597 APInt UndefElts(VWidth, 0);
2598 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
2599 if (Value *V = SimplifyDemandedVectorElts(II, AllOnesEltMask, UndefElts)) {
2600 if (V != II)
2601 return replaceInstUsesWith(*II, V);
2602 return II;
2603 } else if (Value *V = simplifyX86round(*II, Builder))
2604 return replaceInstUsesWith(*II, V);
2605 break;
2606 }
Craig Topperac75bca2016-12-13 07:45:45 +00002607
Tomasz Krupae766e5f2018-08-14 09:04:01 +00002608 // Constant fold add/sub with saturation intrinsics.
2609 case Intrinsic::x86_sse2_padds_b:
2610 case Intrinsic::x86_sse2_padds_w:
2611 case Intrinsic::x86_sse2_psubs_b:
2612 case Intrinsic::x86_sse2_psubs_w:
2613 case Intrinsic::x86_avx2_padds_b:
2614 case Intrinsic::x86_avx2_padds_w:
2615 case Intrinsic::x86_avx2_psubs_b:
2616 case Intrinsic::x86_avx2_psubs_w:
2617 case Intrinsic::x86_avx512_mask_padds_b_512:
2618 case Intrinsic::x86_avx512_mask_padds_w_512:
2619 case Intrinsic::x86_avx512_mask_psubs_b_512:
2620 case Intrinsic::x86_avx512_mask_psubs_w_512:
2621 if (Value *V = simplifyX86AddsSubs(*II, Builder))
2622 return replaceInstUsesWith(*II, V);
2623 break;
2624
2625
Simon Pilgrima3a72b42015-08-10 20:21:15 +00002626 // Constant fold ashr( <A x Bi>, Ci ).
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00002627 // Constant fold lshr( <A x Bi>, Ci ).
2628 // Constant fold shl( <A x Bi>, Ci ).
Simon Pilgrima3a72b42015-08-10 20:21:15 +00002629 case Intrinsic::x86_sse2_psrai_d:
2630 case Intrinsic::x86_sse2_psrai_w:
Simon Pilgrima3a72b42015-08-10 20:21:15 +00002631 case Intrinsic::x86_avx2_psrai_d:
2632 case Intrinsic::x86_avx2_psrai_w:
Craig Topper8b831cb2016-11-13 01:51:55 +00002633 case Intrinsic::x86_avx512_psrai_q_128:
2634 case Intrinsic::x86_avx512_psrai_q_256:
2635 case Intrinsic::x86_avx512_psrai_d_512:
2636 case Intrinsic::x86_avx512_psrai_q_512:
2637 case Intrinsic::x86_avx512_psrai_w_512:
Simon Pilgrim18617d12015-08-05 08:18:00 +00002638 case Intrinsic::x86_sse2_psrli_d:
2639 case Intrinsic::x86_sse2_psrli_q:
2640 case Intrinsic::x86_sse2_psrli_w:
Simon Pilgrim18617d12015-08-05 08:18:00 +00002641 case Intrinsic::x86_avx2_psrli_d:
2642 case Intrinsic::x86_avx2_psrli_q:
2643 case Intrinsic::x86_avx2_psrli_w:
Craig Topper8b831cb2016-11-13 01:51:55 +00002644 case Intrinsic::x86_avx512_psrli_d_512:
2645 case Intrinsic::x86_avx512_psrli_q_512:
2646 case Intrinsic::x86_avx512_psrli_w_512:
Michael J. Spencerdee4b2c2014-04-24 00:58:18 +00002647 case Intrinsic::x86_sse2_pslli_d:
2648 case Intrinsic::x86_sse2_pslli_q:
2649 case Intrinsic::x86_sse2_pslli_w:
Simon Pilgrim18617d12015-08-05 08:18:00 +00002650 case Intrinsic::x86_avx2_pslli_d:
2651 case Intrinsic::x86_avx2_pslli_q:
2652 case Intrinsic::x86_avx2_pslli_w:
Craig Topper8b831cb2016-11-13 01:51:55 +00002653 case Intrinsic::x86_avx512_pslli_d_512:
2654 case Intrinsic::x86_avx512_pslli_q_512:
2655 case Intrinsic::x86_avx512_pslli_w_512:
Craig Topperbb4069e2017-07-07 23:16:26 +00002656 if (Value *V = simplifyX86immShift(*II, Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00002657 return replaceInstUsesWith(*II, V);
Simon Pilgrim18617d12015-08-05 08:18:00 +00002658 break;
2659
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00002660 case Intrinsic::x86_sse2_psra_d:
2661 case Intrinsic::x86_sse2_psra_w:
2662 case Intrinsic::x86_avx2_psra_d:
2663 case Intrinsic::x86_avx2_psra_w:
Craig Topper8b831cb2016-11-13 01:51:55 +00002664 case Intrinsic::x86_avx512_psra_q_128:
2665 case Intrinsic::x86_avx512_psra_q_256:
2666 case Intrinsic::x86_avx512_psra_d_512:
2667 case Intrinsic::x86_avx512_psra_q_512:
2668 case Intrinsic::x86_avx512_psra_w_512:
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00002669 case Intrinsic::x86_sse2_psrl_d:
2670 case Intrinsic::x86_sse2_psrl_q:
2671 case Intrinsic::x86_sse2_psrl_w:
2672 case Intrinsic::x86_avx2_psrl_d:
2673 case Intrinsic::x86_avx2_psrl_q:
2674 case Intrinsic::x86_avx2_psrl_w:
Craig Topper8b831cb2016-11-13 01:51:55 +00002675 case Intrinsic::x86_avx512_psrl_d_512:
2676 case Intrinsic::x86_avx512_psrl_q_512:
2677 case Intrinsic::x86_avx512_psrl_w_512:
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00002678 case Intrinsic::x86_sse2_psll_d:
2679 case Intrinsic::x86_sse2_psll_q:
2680 case Intrinsic::x86_sse2_psll_w:
2681 case Intrinsic::x86_avx2_psll_d:
2682 case Intrinsic::x86_avx2_psll_q:
Craig Topper8b831cb2016-11-13 01:51:55 +00002683 case Intrinsic::x86_avx2_psll_w:
2684 case Intrinsic::x86_avx512_psll_d_512:
2685 case Intrinsic::x86_avx512_psll_q_512:
2686 case Intrinsic::x86_avx512_psll_w_512: {
Craig Topperbb4069e2017-07-07 23:16:26 +00002687 if (Value *V = simplifyX86immShift(*II, Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00002688 return replaceInstUsesWith(*II, V);
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00002689
2690 // SSE2/AVX2 uses only the first 64-bits of the 128-bit vector
2691 // operand to compute the shift amount.
Simon Pilgrim996725e2015-09-19 11:41:53 +00002692 Value *Arg1 = II->getArgOperand(1);
2693 assert(Arg1->getType()->getPrimitiveSizeInBits() == 128 &&
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00002694 "Unexpected packed shift size");
Simon Pilgrim996725e2015-09-19 11:41:53 +00002695 unsigned VWidth = Arg1->getType()->getVectorNumElements();
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00002696
Simon Pilgrim996725e2015-09-19 11:41:53 +00002697 if (Value *V = SimplifyDemandedVectorEltsLow(Arg1, VWidth, VWidth / 2)) {
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00002698 II->setArgOperand(1, V);
2699 return II;
2700 }
2701 break;
2702 }
2703
Simon Pilgrimdb9893f2016-06-07 10:27:15 +00002704 case Intrinsic::x86_avx2_psllv_d:
2705 case Intrinsic::x86_avx2_psllv_d_256:
2706 case Intrinsic::x86_avx2_psllv_q:
2707 case Intrinsic::x86_avx2_psllv_q_256:
Craig Topperb4173a52016-11-13 07:26:19 +00002708 case Intrinsic::x86_avx512_psllv_d_512:
2709 case Intrinsic::x86_avx512_psllv_q_512:
Craig Topper1de753f2016-11-18 06:04:33 +00002710 case Intrinsic::x86_avx512_psllv_w_128:
2711 case Intrinsic::x86_avx512_psllv_w_256:
2712 case Intrinsic::x86_avx512_psllv_w_512:
Simon Pilgrimdb9893f2016-06-07 10:27:15 +00002713 case Intrinsic::x86_avx2_psrav_d:
2714 case Intrinsic::x86_avx2_psrav_d_256:
Craig Topperb4173a52016-11-13 07:26:19 +00002715 case Intrinsic::x86_avx512_psrav_q_128:
2716 case Intrinsic::x86_avx512_psrav_q_256:
2717 case Intrinsic::x86_avx512_psrav_d_512:
2718 case Intrinsic::x86_avx512_psrav_q_512:
Craig Topper1de753f2016-11-18 06:04:33 +00002719 case Intrinsic::x86_avx512_psrav_w_128:
2720 case Intrinsic::x86_avx512_psrav_w_256:
2721 case Intrinsic::x86_avx512_psrav_w_512:
Simon Pilgrimdb9893f2016-06-07 10:27:15 +00002722 case Intrinsic::x86_avx2_psrlv_d:
2723 case Intrinsic::x86_avx2_psrlv_d_256:
2724 case Intrinsic::x86_avx2_psrlv_q:
2725 case Intrinsic::x86_avx2_psrlv_q_256:
Craig Topperb4173a52016-11-13 07:26:19 +00002726 case Intrinsic::x86_avx512_psrlv_d_512:
2727 case Intrinsic::x86_avx512_psrlv_q_512:
Craig Topper1de753f2016-11-18 06:04:33 +00002728 case Intrinsic::x86_avx512_psrlv_w_128:
2729 case Intrinsic::x86_avx512_psrlv_w_256:
2730 case Intrinsic::x86_avx512_psrlv_w_512:
Craig Topperbb4069e2017-07-07 23:16:26 +00002731 if (Value *V = simplifyX86varShift(*II, Builder))
Simon Pilgrimdb9893f2016-06-07 10:27:15 +00002732 return replaceInstUsesWith(*II, V);
2733 break;
2734
Simon Pilgrim6f6b2792017-01-25 14:37:24 +00002735 case Intrinsic::x86_sse2_packssdw_128:
2736 case Intrinsic::x86_sse2_packsswb_128:
2737 case Intrinsic::x86_avx2_packssdw:
2738 case Intrinsic::x86_avx2_packsswb:
Craig Topper3731f4d2017-02-16 07:35:23 +00002739 case Intrinsic::x86_avx512_packssdw_512:
2740 case Intrinsic::x86_avx512_packsswb_512:
Craig Topper4853c432017-07-06 23:18:42 +00002741 if (Value *V = simplifyX86pack(*II, true))
Simon Pilgrim6f6b2792017-01-25 14:37:24 +00002742 return replaceInstUsesWith(*II, V);
2743 break;
2744
2745 case Intrinsic::x86_sse2_packuswb_128:
2746 case Intrinsic::x86_sse41_packusdw:
2747 case Intrinsic::x86_avx2_packusdw:
2748 case Intrinsic::x86_avx2_packuswb:
Craig Topper3731f4d2017-02-16 07:35:23 +00002749 case Intrinsic::x86_avx512_packusdw_512:
2750 case Intrinsic::x86_avx512_packuswb_512:
Craig Topper4853c432017-07-06 23:18:42 +00002751 if (Value *V = simplifyX86pack(*II, false))
Simon Pilgrim6f6b2792017-01-25 14:37:24 +00002752 return replaceInstUsesWith(*II, V);
2753 break;
2754
Craig Topper911025b2018-05-13 21:56:32 +00002755 case Intrinsic::x86_pclmulqdq:
2756 case Intrinsic::x86_pclmulqdq_256:
2757 case Intrinsic::x86_pclmulqdq_512: {
Craig Topperb6122122017-01-26 05:17:13 +00002758 if (auto *C = dyn_cast<ConstantInt>(II->getArgOperand(2))) {
2759 unsigned Imm = C->getZExtValue();
2760
2761 bool MadeChange = false;
2762 Value *Arg0 = II->getArgOperand(0);
2763 Value *Arg1 = II->getArgOperand(1);
2764 unsigned VWidth = Arg0->getType()->getVectorNumElements();
Craig Topperb6122122017-01-26 05:17:13 +00002765
2766 APInt UndefElts1(VWidth, 0);
Craig Topper911025b2018-05-13 21:56:32 +00002767 APInt DemandedElts1 = APInt::getSplat(VWidth,
2768 APInt(2, (Imm & 0x01) ? 2 : 1));
2769 if (Value *V = SimplifyDemandedVectorElts(Arg0, DemandedElts1,
Craig Topperb6122122017-01-26 05:17:13 +00002770 UndefElts1)) {
2771 II->setArgOperand(0, V);
2772 MadeChange = true;
2773 }
2774
2775 APInt UndefElts2(VWidth, 0);
Craig Topper911025b2018-05-13 21:56:32 +00002776 APInt DemandedElts2 = APInt::getSplat(VWidth,
2777 APInt(2, (Imm & 0x10) ? 2 : 1));
2778 if (Value *V = SimplifyDemandedVectorElts(Arg1, DemandedElts2,
Craig Topperb6122122017-01-26 05:17:13 +00002779 UndefElts2)) {
2780 II->setArgOperand(1, V);
2781 MadeChange = true;
2782 }
2783
Craig Topper911025b2018-05-13 21:56:32 +00002784 // If either input elements are undef, the result is zero.
2785 if (DemandedElts1.isSubsetOf(UndefElts1) ||
2786 DemandedElts2.isSubsetOf(UndefElts2))
Craig Topperb6122122017-01-26 05:17:13 +00002787 return replaceInstUsesWith(*II,
2788 ConstantAggregateZero::get(II->getType()));
2789
2790 if (MadeChange)
2791 return II;
2792 }
2793 break;
2794 }
2795
Sanjay Patelc86867c2015-04-16 17:52:13 +00002796 case Intrinsic::x86_sse41_insertps:
Craig Topperbb4069e2017-07-07 23:16:26 +00002797 if (Value *V = simplifyX86insertps(*II, Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00002798 return replaceInstUsesWith(*II, V);
Sanjay Patelc86867c2015-04-16 17:52:13 +00002799 break;
Simon Pilgrim54fcd622015-07-25 20:41:00 +00002800
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002801 case Intrinsic::x86_sse4a_extrq: {
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002802 Value *Op0 = II->getArgOperand(0);
2803 Value *Op1 = II->getArgOperand(1);
2804 unsigned VWidth0 = Op0->getType()->getVectorNumElements();
2805 unsigned VWidth1 = Op1->getType()->getVectorNumElements();
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002806 assert(Op0->getType()->getPrimitiveSizeInBits() == 128 &&
2807 Op1->getType()->getPrimitiveSizeInBits() == 128 && VWidth0 == 2 &&
2808 VWidth1 == 16 && "Unexpected operand sizes");
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002809
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002810 // See if we're dealing with constant values.
2811 Constant *C1 = dyn_cast<Constant>(Op1);
2812 ConstantInt *CILength =
Andrea Di Biagio8df5b9c2016-09-07 12:03:03 +00002813 C1 ? dyn_cast_or_null<ConstantInt>(C1->getAggregateElement((unsigned)0))
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002814 : nullptr;
2815 ConstantInt *CIIndex =
Andrea Di Biagio8df5b9c2016-09-07 12:03:03 +00002816 C1 ? dyn_cast_or_null<ConstantInt>(C1->getAggregateElement((unsigned)1))
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002817 : nullptr;
2818
2819 // Attempt to simplify to a constant, shuffle vector or EXTRQI call.
Craig Topperbb4069e2017-07-07 23:16:26 +00002820 if (Value *V = simplifyX86extrq(*II, Op0, CILength, CIIndex, Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00002821 return replaceInstUsesWith(*II, V);
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002822
2823 // EXTRQ only uses the lowest 64-bits of the first 128-bit vector
2824 // operands and the lowest 16-bits of the second.
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002825 bool MadeChange = false;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002826 if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth0, 1)) {
2827 II->setArgOperand(0, V);
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002828 MadeChange = true;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002829 }
2830 if (Value *V = SimplifyDemandedVectorEltsLow(Op1, VWidth1, 2)) {
2831 II->setArgOperand(1, V);
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002832 MadeChange = true;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002833 }
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002834 if (MadeChange)
2835 return II;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002836 break;
2837 }
2838
2839 case Intrinsic::x86_sse4a_extrqi: {
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002840 // EXTRQI: Extract Length bits starting from Index. Zero pad the remaining
2841 // bits of the lower 64-bits. The upper 64-bits are undefined.
2842 Value *Op0 = II->getArgOperand(0);
2843 unsigned VWidth = Op0->getType()->getVectorNumElements();
2844 assert(Op0->getType()->getPrimitiveSizeInBits() == 128 && VWidth == 2 &&
2845 "Unexpected operand size");
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002846
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002847 // See if we're dealing with constant values.
2848 ConstantInt *CILength = dyn_cast<ConstantInt>(II->getArgOperand(1));
2849 ConstantInt *CIIndex = dyn_cast<ConstantInt>(II->getArgOperand(2));
2850
2851 // Attempt to simplify to a constant or shuffle vector.
Craig Topperbb4069e2017-07-07 23:16:26 +00002852 if (Value *V = simplifyX86extrq(*II, Op0, CILength, CIIndex, Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00002853 return replaceInstUsesWith(*II, V);
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002854
2855 // EXTRQI only uses the lowest 64-bits of the first 128-bit vector
2856 // operand.
2857 if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth, 1)) {
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002858 II->setArgOperand(0, V);
2859 return II;
2860 }
2861 break;
2862 }
2863
2864 case Intrinsic::x86_sse4a_insertq: {
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002865 Value *Op0 = II->getArgOperand(0);
2866 Value *Op1 = II->getArgOperand(1);
2867 unsigned VWidth = Op0->getType()->getVectorNumElements();
2868 assert(Op0->getType()->getPrimitiveSizeInBits() == 128 &&
2869 Op1->getType()->getPrimitiveSizeInBits() == 128 && VWidth == 2 &&
2870 Op1->getType()->getVectorNumElements() == 2 &&
2871 "Unexpected operand size");
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002872
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002873 // See if we're dealing with constant values.
2874 Constant *C1 = dyn_cast<Constant>(Op1);
2875 ConstantInt *CI11 =
Andrea Di Biagiof3fd3162016-09-07 12:47:53 +00002876 C1 ? dyn_cast_or_null<ConstantInt>(C1->getAggregateElement((unsigned)1))
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002877 : nullptr;
2878
2879 // Attempt to simplify to a constant, shuffle vector or INSERTQI call.
2880 if (CI11) {
Benjamin Kramer46e38f32016-06-08 10:01:20 +00002881 const APInt &V11 = CI11->getValue();
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002882 APInt Len = V11.zextOrTrunc(6);
2883 APInt Idx = V11.lshr(8).zextOrTrunc(6);
Craig Topperbb4069e2017-07-07 23:16:26 +00002884 if (Value *V = simplifyX86insertq(*II, Op0, Op1, Len, Idx, Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00002885 return replaceInstUsesWith(*II, V);
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002886 }
2887
2888 // INSERTQ only uses the lowest 64-bits of the first 128-bit vector
2889 // operand.
2890 if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth, 1)) {
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002891 II->setArgOperand(0, V);
2892 return II;
2893 }
2894 break;
2895 }
2896
Filipe Cabecinhas1a805952014-04-24 00:38:14 +00002897 case Intrinsic::x86_sse4a_insertqi: {
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002898 // INSERTQI: Extract lowest Length bits from lower half of second source and
2899 // insert over first source starting at Index bit. The upper 64-bits are
2900 // undefined.
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002901 Value *Op0 = II->getArgOperand(0);
2902 Value *Op1 = II->getArgOperand(1);
2903 unsigned VWidth0 = Op0->getType()->getVectorNumElements();
2904 unsigned VWidth1 = Op1->getType()->getVectorNumElements();
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002905 assert(Op0->getType()->getPrimitiveSizeInBits() == 128 &&
2906 Op1->getType()->getPrimitiveSizeInBits() == 128 && VWidth0 == 2 &&
2907 VWidth1 == 2 && "Unexpected operand sizes");
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002908
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002909 // See if we're dealing with constant values.
2910 ConstantInt *CILength = dyn_cast<ConstantInt>(II->getArgOperand(2));
2911 ConstantInt *CIIndex = dyn_cast<ConstantInt>(II->getArgOperand(3));
2912
2913 // Attempt to simplify to a constant or shuffle vector.
2914 if (CILength && CIIndex) {
2915 APInt Len = CILength->getValue().zextOrTrunc(6);
2916 APInt Idx = CIIndex->getValue().zextOrTrunc(6);
Craig Topperbb4069e2017-07-07 23:16:26 +00002917 if (Value *V = simplifyX86insertq(*II, Op0, Op1, Len, Idx, Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00002918 return replaceInstUsesWith(*II, V);
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002919 }
2920
2921 // INSERTQI only uses the lowest 64-bits of the first two 128-bit vector
2922 // operands.
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002923 bool MadeChange = false;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002924 if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth0, 1)) {
2925 II->setArgOperand(0, V);
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002926 MadeChange = true;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002927 }
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002928 if (Value *V = SimplifyDemandedVectorEltsLow(Op1, VWidth1, 1)) {
2929 II->setArgOperand(1, V);
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002930 MadeChange = true;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002931 }
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002932 if (MadeChange)
2933 return II;
Filipe Cabecinhas1a805952014-04-24 00:38:14 +00002934 break;
2935 }
2936
Filipe Cabecinhas82ac07c2014-05-27 03:42:20 +00002937 case Intrinsic::x86_sse41_pblendvb:
2938 case Intrinsic::x86_sse41_blendvps:
2939 case Intrinsic::x86_sse41_blendvpd:
2940 case Intrinsic::x86_avx_blendv_ps_256:
2941 case Intrinsic::x86_avx_blendv_pd_256:
2942 case Intrinsic::x86_avx2_pblendvb: {
2943 // Convert blendv* to vector selects if the mask is constant.
2944 // This optimization is convoluted because the intrinsic is defined as
2945 // getting a vector of floats or doubles for the ps and pd versions.
2946 // FIXME: That should be changed.
Simon Pilgrim8c049d52015-08-12 08:08:56 +00002947
2948 Value *Op0 = II->getArgOperand(0);
2949 Value *Op1 = II->getArgOperand(1);
Filipe Cabecinhas82ac07c2014-05-27 03:42:20 +00002950 Value *Mask = II->getArgOperand(2);
Simon Pilgrim8c049d52015-08-12 08:08:56 +00002951
2952 // fold (blend A, A, Mask) -> A
2953 if (Op0 == Op1)
Sanjay Patel4b198802016-02-01 22:23:39 +00002954 return replaceInstUsesWith(CI, Op0);
Simon Pilgrim8c049d52015-08-12 08:08:56 +00002955
2956 // Zero Mask - select 1st argument.
Simon Pilgrim93f59f52015-08-12 08:23:36 +00002957 if (isa<ConstantAggregateZero>(Mask))
Sanjay Patel4b198802016-02-01 22:23:39 +00002958 return replaceInstUsesWith(CI, Op0);
Simon Pilgrim8c049d52015-08-12 08:08:56 +00002959
2960 // Constant Mask - select 1st/2nd argument lane based on top bit of mask.
Sanjay Patel368ac5d2016-02-21 17:29:33 +00002961 if (auto *ConstantMask = dyn_cast<ConstantDataVector>(Mask)) {
2962 Constant *NewSelector = getNegativeIsTrueBoolVec(ConstantMask);
Simon Pilgrim8c049d52015-08-12 08:08:56 +00002963 return SelectInst::Create(NewSelector, Op1, Op0, "blendv");
Filipe Cabecinhas82ac07c2014-05-27 03:42:20 +00002964 }
Simon Pilgrim8c049d52015-08-12 08:08:56 +00002965 break;
Filipe Cabecinhas82ac07c2014-05-27 03:42:20 +00002966 }
2967
Andrea Di Biagio0594e2a2015-09-30 16:44:39 +00002968 case Intrinsic::x86_ssse3_pshuf_b_128:
Simon Pilgrimc0c56e72016-04-24 17:00:34 +00002969 case Intrinsic::x86_avx2_pshuf_b:
Simon Pilgrima22c3a12017-01-18 13:44:04 +00002970 case Intrinsic::x86_avx512_pshuf_b_512:
Craig Topperbb4069e2017-07-07 23:16:26 +00002971 if (Value *V = simplifyX86pshufb(*II, Builder))
Simon Pilgrimc0c56e72016-04-24 17:00:34 +00002972 return replaceInstUsesWith(*II, V);
2973 break;
Andrea Di Biagio0594e2a2015-09-30 16:44:39 +00002974
Rafael Espindolabad3f772014-04-21 22:06:04 +00002975 case Intrinsic::x86_avx_vpermilvar_ps:
2976 case Intrinsic::x86_avx_vpermilvar_ps_256:
Craig Topper58917f32016-12-11 01:59:36 +00002977 case Intrinsic::x86_avx512_vpermilvar_ps_512:
Rafael Espindolabad3f772014-04-21 22:06:04 +00002978 case Intrinsic::x86_avx_vpermilvar_pd:
Simon Pilgrim2f6097d2016-04-24 17:23:46 +00002979 case Intrinsic::x86_avx_vpermilvar_pd_256:
Simon Pilgrima22c3a12017-01-18 13:44:04 +00002980 case Intrinsic::x86_avx512_vpermilvar_pd_512:
Craig Topperbb4069e2017-07-07 23:16:26 +00002981 if (Value *V = simplifyX86vpermilvar(*II, Builder))
Simon Pilgrim2f6097d2016-04-24 17:23:46 +00002982 return replaceInstUsesWith(*II, V);
2983 break;
Rafael Espindolabad3f772014-04-21 22:06:04 +00002984
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +00002985 case Intrinsic::x86_avx2_permd:
2986 case Intrinsic::x86_avx2_permps:
Craig Toppere4c045b2018-05-20 23:34:04 +00002987 case Intrinsic::x86_avx512_permvar_df_256:
2988 case Intrinsic::x86_avx512_permvar_df_512:
2989 case Intrinsic::x86_avx512_permvar_di_256:
2990 case Intrinsic::x86_avx512_permvar_di_512:
2991 case Intrinsic::x86_avx512_permvar_hi_128:
2992 case Intrinsic::x86_avx512_permvar_hi_256:
2993 case Intrinsic::x86_avx512_permvar_hi_512:
2994 case Intrinsic::x86_avx512_permvar_qi_128:
2995 case Intrinsic::x86_avx512_permvar_qi_256:
2996 case Intrinsic::x86_avx512_permvar_qi_512:
2997 case Intrinsic::x86_avx512_permvar_sf_512:
2998 case Intrinsic::x86_avx512_permvar_si_512:
Craig Topperbb4069e2017-07-07 23:16:26 +00002999 if (Value *V = simplifyX86vpermv(*II, Builder))
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +00003000 return replaceInstUsesWith(*II, V);
3001 break;
3002
Sanjay Patel98a71502016-02-29 23:16:48 +00003003 case Intrinsic::x86_avx_maskload_ps:
Sanjay Patel6f2c01f2016-02-29 23:59:00 +00003004 case Intrinsic::x86_avx_maskload_pd:
3005 case Intrinsic::x86_avx_maskload_ps_256:
3006 case Intrinsic::x86_avx_maskload_pd_256:
3007 case Intrinsic::x86_avx2_maskload_d:
3008 case Intrinsic::x86_avx2_maskload_q:
3009 case Intrinsic::x86_avx2_maskload_d_256:
3010 case Intrinsic::x86_avx2_maskload_q_256:
Sanjay Patel98a71502016-02-29 23:16:48 +00003011 if (Instruction *I = simplifyX86MaskedLoad(*II, *this))
3012 return I;
3013 break;
3014
Sanjay Patelc4acbae2016-03-12 15:16:59 +00003015 case Intrinsic::x86_sse2_maskmov_dqu:
Sanjay Patel1ace9932016-02-26 21:04:14 +00003016 case Intrinsic::x86_avx_maskstore_ps:
3017 case Intrinsic::x86_avx_maskstore_pd:
3018 case Intrinsic::x86_avx_maskstore_ps_256:
3019 case Intrinsic::x86_avx_maskstore_pd_256:
Sanjay Patelfc7e7eb2016-02-26 21:51:44 +00003020 case Intrinsic::x86_avx2_maskstore_d:
3021 case Intrinsic::x86_avx2_maskstore_q:
3022 case Intrinsic::x86_avx2_maskstore_d_256:
3023 case Intrinsic::x86_avx2_maskstore_q_256:
Sanjay Patel1ace9932016-02-26 21:04:14 +00003024 if (simplifyX86MaskedStore(*II, *this))
3025 return nullptr;
3026 break;
3027
Simon Pilgrim1d1c56e22015-10-11 14:38:34 +00003028 case Intrinsic::x86_xop_vpcomb:
3029 case Intrinsic::x86_xop_vpcomd:
3030 case Intrinsic::x86_xop_vpcomq:
3031 case Intrinsic::x86_xop_vpcomw:
Craig Topperbb4069e2017-07-07 23:16:26 +00003032 if (Value *V = simplifyX86vpcom(*II, Builder, true))
Sanjay Patel4b198802016-02-01 22:23:39 +00003033 return replaceInstUsesWith(*II, V);
Simon Pilgrim1d1c56e22015-10-11 14:38:34 +00003034 break;
3035
3036 case Intrinsic::x86_xop_vpcomub:
3037 case Intrinsic::x86_xop_vpcomud:
3038 case Intrinsic::x86_xop_vpcomuq:
3039 case Intrinsic::x86_xop_vpcomuw:
Craig Topperbb4069e2017-07-07 23:16:26 +00003040 if (Value *V = simplifyX86vpcom(*II, Builder, false))
Sanjay Patel4b198802016-02-01 22:23:39 +00003041 return replaceInstUsesWith(*II, V);
Simon Pilgrim1d1c56e22015-10-11 14:38:34 +00003042 break;
3043
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003044 case Intrinsic::ppc_altivec_vperm:
3045 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
Bill Schmidta1184632014-06-05 19:46:04 +00003046 // Note that ppc_altivec_vperm has a big-endian bias, so when creating
3047 // a vectorshuffle for little endian, we must undo the transformation
3048 // performed on vec_perm in altivec.h. That is, we must complement
3049 // the permutation mask with respect to 31 and reverse the order of
3050 // V1 and V2.
Chris Lattner0256be92012-01-27 03:08:05 +00003051 if (Constant *Mask = dyn_cast<Constant>(II->getArgOperand(2))) {
3052 assert(Mask->getType()->getVectorNumElements() == 16 &&
3053 "Bad type for intrinsic!");
Jim Grosbach7815f562012-02-03 00:07:04 +00003054
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003055 // Check that all of the elements are integer constants or undefs.
3056 bool AllEltsOk = true;
3057 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0256be92012-01-27 03:08:05 +00003058 Constant *Elt = Mask->getAggregateElement(i);
Craig Topperf40110f2014-04-25 05:29:35 +00003059 if (!Elt || !(isa<ConstantInt>(Elt) || isa<UndefValue>(Elt))) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003060 AllEltsOk = false;
3061 break;
3062 }
3063 }
Jim Grosbach7815f562012-02-03 00:07:04 +00003064
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003065 if (AllEltsOk) {
3066 // Cast the input vectors to byte vectors.
Craig Topperbb4069e2017-07-07 23:16:26 +00003067 Value *Op0 = Builder.CreateBitCast(II->getArgOperand(0),
3068 Mask->getType());
3069 Value *Op1 = Builder.CreateBitCast(II->getArgOperand(1),
3070 Mask->getType());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003071 Value *Result = UndefValue::get(Op0->getType());
Jim Grosbach7815f562012-02-03 00:07:04 +00003072
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003073 // Only extract each element once.
3074 Value *ExtractedElts[32];
3075 memset(ExtractedElts, 0, sizeof(ExtractedElts));
Jim Grosbach7815f562012-02-03 00:07:04 +00003076
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003077 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0256be92012-01-27 03:08:05 +00003078 if (isa<UndefValue>(Mask->getAggregateElement(i)))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003079 continue;
Jim Grosbach7815f562012-02-03 00:07:04 +00003080 unsigned Idx =
Chris Lattner0256be92012-01-27 03:08:05 +00003081 cast<ConstantInt>(Mask->getAggregateElement(i))->getZExtValue();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003082 Idx &= 31; // Match the hardware behavior.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003083 if (DL.isLittleEndian())
Bill Schmidta1184632014-06-05 19:46:04 +00003084 Idx = 31 - Idx;
Jim Grosbach7815f562012-02-03 00:07:04 +00003085
Craig Topperf40110f2014-04-25 05:29:35 +00003086 if (!ExtractedElts[Idx]) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003087 Value *Op0ToUse = (DL.isLittleEndian()) ? Op1 : Op0;
3088 Value *Op1ToUse = (DL.isLittleEndian()) ? Op0 : Op1;
Jim Grosbach7815f562012-02-03 00:07:04 +00003089 ExtractedElts[Idx] =
Craig Topperbb4069e2017-07-07 23:16:26 +00003090 Builder.CreateExtractElement(Idx < 16 ? Op0ToUse : Op1ToUse,
3091 Builder.getInt32(Idx&15));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003092 }
Jim Grosbach7815f562012-02-03 00:07:04 +00003093
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003094 // Insert this value into the result vector.
Craig Topperbb4069e2017-07-07 23:16:26 +00003095 Result = Builder.CreateInsertElement(Result, ExtractedElts[Idx],
3096 Builder.getInt32(i));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003097 }
3098 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
3099 }
3100 }
3101 break;
3102
Alexandros Lamprineas61f0ba12018-05-31 12:19:18 +00003103 case Intrinsic::arm_neon_vld1: {
3104 unsigned MemAlign = getKnownAlignment(II->getArgOperand(0),
3105 DL, II, &AC, &DT);
3106 if (Value *V = simplifyNeonVld1(*II, MemAlign, Builder))
3107 return replaceInstUsesWith(*II, V);
3108 break;
3109 }
3110
Bob Wilsona4e231c2010-10-22 21:41:48 +00003111 case Intrinsic::arm_neon_vld2:
3112 case Intrinsic::arm_neon_vld3:
3113 case Intrinsic::arm_neon_vld4:
3114 case Intrinsic::arm_neon_vld2lane:
3115 case Intrinsic::arm_neon_vld3lane:
3116 case Intrinsic::arm_neon_vld4lane:
3117 case Intrinsic::arm_neon_vst1:
3118 case Intrinsic::arm_neon_vst2:
3119 case Intrinsic::arm_neon_vst3:
3120 case Intrinsic::arm_neon_vst4:
3121 case Intrinsic::arm_neon_vst2lane:
3122 case Intrinsic::arm_neon_vst3lane:
3123 case Intrinsic::arm_neon_vst4lane: {
Justin Bogner99798402016-08-05 01:06:44 +00003124 unsigned MemAlign =
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003125 getKnownAlignment(II->getArgOperand(0), DL, II, &AC, &DT);
Bob Wilsona4e231c2010-10-22 21:41:48 +00003126 unsigned AlignArg = II->getNumArgOperands() - 1;
3127 ConstantInt *IntrAlign = dyn_cast<ConstantInt>(II->getArgOperand(AlignArg));
3128 if (IntrAlign && IntrAlign->getZExtValue() < MemAlign) {
3129 II->setArgOperand(AlignArg,
3130 ConstantInt::get(Type::getInt32Ty(II->getContext()),
3131 MemAlign, false));
3132 return II;
3133 }
3134 break;
3135 }
3136
Alexandros Lamprineas52457d32018-05-30 14:38:50 +00003137 case Intrinsic::arm_neon_vtbl1:
3138 case Intrinsic::aarch64_neon_tbl1:
3139 if (Value *V = simplifyNeonTbl1(*II, Builder))
3140 return replaceInstUsesWith(*II, V);
3141 break;
3142
Lang Hames3a90fab2012-05-01 00:20:38 +00003143 case Intrinsic::arm_neon_vmulls:
Tim Northover00ed9962014-03-29 10:18:08 +00003144 case Intrinsic::arm_neon_vmullu:
Tim Northover3b0846e2014-05-24 12:50:23 +00003145 case Intrinsic::aarch64_neon_smull:
3146 case Intrinsic::aarch64_neon_umull: {
Lang Hames3a90fab2012-05-01 00:20:38 +00003147 Value *Arg0 = II->getArgOperand(0);
3148 Value *Arg1 = II->getArgOperand(1);
3149
3150 // Handle mul by zero first:
3151 if (isa<ConstantAggregateZero>(Arg0) || isa<ConstantAggregateZero>(Arg1)) {
Sanjay Patel4b198802016-02-01 22:23:39 +00003152 return replaceInstUsesWith(CI, ConstantAggregateZero::get(II->getType()));
Lang Hames3a90fab2012-05-01 00:20:38 +00003153 }
3154
3155 // Check for constant LHS & RHS - in this case we just simplify.
Tim Northover00ed9962014-03-29 10:18:08 +00003156 bool Zext = (II->getIntrinsicID() == Intrinsic::arm_neon_vmullu ||
Tim Northover3b0846e2014-05-24 12:50:23 +00003157 II->getIntrinsicID() == Intrinsic::aarch64_neon_umull);
Lang Hames3a90fab2012-05-01 00:20:38 +00003158 VectorType *NewVT = cast<VectorType>(II->getType());
Benjamin Kramer92040952014-02-13 18:23:24 +00003159 if (Constant *CV0 = dyn_cast<Constant>(Arg0)) {
3160 if (Constant *CV1 = dyn_cast<Constant>(Arg1)) {
3161 CV0 = ConstantExpr::getIntegerCast(CV0, NewVT, /*isSigned=*/!Zext);
3162 CV1 = ConstantExpr::getIntegerCast(CV1, NewVT, /*isSigned=*/!Zext);
3163
Sanjay Patel4b198802016-02-01 22:23:39 +00003164 return replaceInstUsesWith(CI, ConstantExpr::getMul(CV0, CV1));
Lang Hames3a90fab2012-05-01 00:20:38 +00003165 }
3166
Alp Tokercb402912014-01-24 17:20:08 +00003167 // Couldn't simplify - canonicalize constant to the RHS.
Lang Hames3a90fab2012-05-01 00:20:38 +00003168 std::swap(Arg0, Arg1);
3169 }
3170
3171 // Handle mul by one:
Benjamin Kramer92040952014-02-13 18:23:24 +00003172 if (Constant *CV1 = dyn_cast<Constant>(Arg1))
Lang Hames3a90fab2012-05-01 00:20:38 +00003173 if (ConstantInt *Splat =
Benjamin Kramer92040952014-02-13 18:23:24 +00003174 dyn_cast_or_null<ConstantInt>(CV1->getSplatValue()))
3175 if (Splat->isOne())
3176 return CastInst::CreateIntegerCast(Arg0, II->getType(),
3177 /*isSigned=*/!Zext);
Lang Hames3a90fab2012-05-01 00:20:38 +00003178
3179 break;
3180 }
Chad Rosier274d72f2018-05-24 15:26:42 +00003181 case Intrinsic::arm_neon_aesd:
3182 case Intrinsic::arm_neon_aese:
3183 case Intrinsic::aarch64_crypto_aesd:
3184 case Intrinsic::aarch64_crypto_aese: {
3185 Value *DataArg = II->getArgOperand(0);
3186 Value *KeyArg = II->getArgOperand(1);
3187
3188 // Try to use the builtin XOR in AESE and AESD to eliminate a prior XOR
3189 Value *Data, *Key;
3190 if (match(KeyArg, m_ZeroInt()) &&
3191 match(DataArg, m_Xor(m_Value(Data), m_Value(Key)))) {
3192 II->setArgOperand(0, Data);
3193 II->setArgOperand(1, Key);
3194 return II;
3195 }
3196 break;
3197 }
Matt Arsenaultbef34e22016-01-22 21:30:34 +00003198 case Intrinsic::amdgcn_rcp: {
Matt Arsenault4c7795d2017-03-24 19:04:57 +00003199 Value *Src = II->getArgOperand(0);
3200
3201 // TODO: Move to ConstantFolding/InstSimplify?
3202 if (isa<UndefValue>(Src))
3203 return replaceInstUsesWith(CI, Src);
3204
3205 if (const ConstantFP *C = dyn_cast<ConstantFP>(Src)) {
Matt Arsenaulta0050b02014-06-19 01:19:19 +00003206 const APFloat &ArgVal = C->getValueAPF();
3207 APFloat Val(ArgVal.getSemantics(), 1.0);
3208 APFloat::opStatus Status = Val.divide(ArgVal,
3209 APFloat::rmNearestTiesToEven);
3210 // Only do this if it was exact and therefore not dependent on the
3211 // rounding mode.
3212 if (Status == APFloat::opOK)
Sanjay Patel4b198802016-02-01 22:23:39 +00003213 return replaceInstUsesWith(CI, ConstantFP::get(II->getContext(), Val));
Matt Arsenaulta0050b02014-06-19 01:19:19 +00003214 }
3215
3216 break;
3217 }
Matt Arsenault4c7795d2017-03-24 19:04:57 +00003218 case Intrinsic::amdgcn_rsq: {
3219 Value *Src = II->getArgOperand(0);
3220
3221 // TODO: Move to ConstantFolding/InstSimplify?
3222 if (isa<UndefValue>(Src))
3223 return replaceInstUsesWith(CI, Src);
3224 break;
3225 }
Matt Arsenault2fe4fbc2016-03-30 22:28:52 +00003226 case Intrinsic::amdgcn_frexp_mant:
3227 case Intrinsic::amdgcn_frexp_exp: {
Matt Arsenault5cd4f8f2016-03-30 22:28:26 +00003228 Value *Src = II->getArgOperand(0);
3229 if (const ConstantFP *C = dyn_cast<ConstantFP>(Src)) {
3230 int Exp;
3231 APFloat Significand = frexp(C->getValueAPF(), Exp,
3232 APFloat::rmNearestTiesToEven);
3233
Matt Arsenault2fe4fbc2016-03-30 22:28:52 +00003234 if (II->getIntrinsicID() == Intrinsic::amdgcn_frexp_mant) {
3235 return replaceInstUsesWith(CI, ConstantFP::get(II->getContext(),
3236 Significand));
3237 }
3238
3239 // Match instruction special case behavior.
3240 if (Exp == APFloat::IEK_NaN || Exp == APFloat::IEK_Inf)
3241 Exp = 0;
3242
3243 return replaceInstUsesWith(CI, ConstantInt::get(II->getType(), Exp));
3244 }
3245
3246 if (isa<UndefValue>(Src))
3247 return replaceInstUsesWith(CI, UndefValue::get(II->getType()));
Matt Arsenault5cd4f8f2016-03-30 22:28:26 +00003248
3249 break;
3250 }
Matt Arsenault46a03822016-09-03 07:06:58 +00003251 case Intrinsic::amdgcn_class: {
3252 enum {
3253 S_NAN = 1 << 0, // Signaling NaN
3254 Q_NAN = 1 << 1, // Quiet NaN
3255 N_INFINITY = 1 << 2, // Negative infinity
3256 N_NORMAL = 1 << 3, // Negative normal
3257 N_SUBNORMAL = 1 << 4, // Negative subnormal
3258 N_ZERO = 1 << 5, // Negative zero
3259 P_ZERO = 1 << 6, // Positive zero
3260 P_SUBNORMAL = 1 << 7, // Positive subnormal
3261 P_NORMAL = 1 << 8, // Positive normal
3262 P_INFINITY = 1 << 9 // Positive infinity
3263 };
3264
3265 const uint32_t FullMask = S_NAN | Q_NAN | N_INFINITY | N_NORMAL |
3266 N_SUBNORMAL | N_ZERO | P_ZERO | P_SUBNORMAL | P_NORMAL | P_INFINITY;
3267
3268 Value *Src0 = II->getArgOperand(0);
3269 Value *Src1 = II->getArgOperand(1);
3270 const ConstantInt *CMask = dyn_cast<ConstantInt>(Src1);
3271 if (!CMask) {
3272 if (isa<UndefValue>(Src0))
3273 return replaceInstUsesWith(*II, UndefValue::get(II->getType()));
3274
3275 if (isa<UndefValue>(Src1))
3276 return replaceInstUsesWith(*II, ConstantInt::get(II->getType(), false));
3277 break;
3278 }
3279
3280 uint32_t Mask = CMask->getZExtValue();
3281
3282 // If all tests are made, it doesn't matter what the value is.
3283 if ((Mask & FullMask) == FullMask)
3284 return replaceInstUsesWith(*II, ConstantInt::get(II->getType(), true));
3285
3286 if ((Mask & FullMask) == 0)
3287 return replaceInstUsesWith(*II, ConstantInt::get(II->getType(), false));
3288
3289 if (Mask == (S_NAN | Q_NAN)) {
3290 // Equivalent of isnan. Replace with standard fcmp.
Craig Topperbb4069e2017-07-07 23:16:26 +00003291 Value *FCmp = Builder.CreateFCmpUNO(Src0, Src0);
Matt Arsenault46a03822016-09-03 07:06:58 +00003292 FCmp->takeName(II);
3293 return replaceInstUsesWith(*II, FCmp);
3294 }
3295
Matt Arsenaultd35f46c2018-08-10 18:58:49 +00003296 if (Mask == (N_ZERO | P_ZERO)) {
3297 // Equivalent of == 0.
3298 Value *FCmp = Builder.CreateFCmpOEQ(
3299 Src0, ConstantFP::get(Src0->getType(), 0.0));
3300
3301 FCmp->takeName(II);
3302 return replaceInstUsesWith(*II, FCmp);
3303 }
3304
Matt Arsenault46a03822016-09-03 07:06:58 +00003305 const ConstantFP *CVal = dyn_cast<ConstantFP>(Src0);
3306 if (!CVal) {
3307 if (isa<UndefValue>(Src0))
3308 return replaceInstUsesWith(*II, UndefValue::get(II->getType()));
3309
3310 // Clamp mask to used bits
3311 if ((Mask & FullMask) != Mask) {
Craig Topperbb4069e2017-07-07 23:16:26 +00003312 CallInst *NewCall = Builder.CreateCall(II->getCalledFunction(),
Matt Arsenault46a03822016-09-03 07:06:58 +00003313 { Src0, ConstantInt::get(Src1->getType(), Mask & FullMask) }
3314 );
3315
3316 NewCall->takeName(II);
3317 return replaceInstUsesWith(*II, NewCall);
3318 }
3319
3320 break;
3321 }
3322
3323 const APFloat &Val = CVal->getValueAPF();
3324
3325 bool Result =
3326 ((Mask & S_NAN) && Val.isNaN() && Val.isSignaling()) ||
3327 ((Mask & Q_NAN) && Val.isNaN() && !Val.isSignaling()) ||
3328 ((Mask & N_INFINITY) && Val.isInfinity() && Val.isNegative()) ||
3329 ((Mask & N_NORMAL) && Val.isNormal() && Val.isNegative()) ||
3330 ((Mask & N_SUBNORMAL) && Val.isDenormal() && Val.isNegative()) ||
3331 ((Mask & N_ZERO) && Val.isZero() && Val.isNegative()) ||
3332 ((Mask & P_ZERO) && Val.isZero() && !Val.isNegative()) ||
3333 ((Mask & P_SUBNORMAL) && Val.isDenormal() && !Val.isNegative()) ||
3334 ((Mask & P_NORMAL) && Val.isNormal() && !Val.isNegative()) ||
3335 ((Mask & P_INFINITY) && Val.isInfinity() && !Val.isNegative());
3336
3337 return replaceInstUsesWith(*II, ConstantInt::get(II->getType(), Result));
3338 }
Matt Arsenault1f17c662017-02-22 00:27:34 +00003339 case Intrinsic::amdgcn_cvt_pkrtz: {
3340 Value *Src0 = II->getArgOperand(0);
3341 Value *Src1 = II->getArgOperand(1);
3342 if (const ConstantFP *C0 = dyn_cast<ConstantFP>(Src0)) {
3343 if (const ConstantFP *C1 = dyn_cast<ConstantFP>(Src1)) {
3344 const fltSemantics &HalfSem
3345 = II->getType()->getScalarType()->getFltSemantics();
3346 bool LosesInfo;
3347 APFloat Val0 = C0->getValueAPF();
3348 APFloat Val1 = C1->getValueAPF();
3349 Val0.convert(HalfSem, APFloat::rmTowardZero, &LosesInfo);
3350 Val1.convert(HalfSem, APFloat::rmTowardZero, &LosesInfo);
3351
3352 Constant *Folded = ConstantVector::get({
3353 ConstantFP::get(II->getContext(), Val0),
3354 ConstantFP::get(II->getContext(), Val1) });
3355 return replaceInstUsesWith(*II, Folded);
3356 }
3357 }
3358
3359 if (isa<UndefValue>(Src0) && isa<UndefValue>(Src1))
3360 return replaceInstUsesWith(*II, UndefValue::get(II->getType()));
3361
3362 break;
3363 }
Marek Olsak13e47412018-01-31 20:18:04 +00003364 case Intrinsic::amdgcn_cvt_pknorm_i16:
3365 case Intrinsic::amdgcn_cvt_pknorm_u16:
3366 case Intrinsic::amdgcn_cvt_pk_i16:
3367 case Intrinsic::amdgcn_cvt_pk_u16: {
3368 Value *Src0 = II->getArgOperand(0);
3369 Value *Src1 = II->getArgOperand(1);
3370
3371 if (isa<UndefValue>(Src0) && isa<UndefValue>(Src1))
3372 return replaceInstUsesWith(*II, UndefValue::get(II->getType()));
3373
3374 break;
3375 }
Matt Arsenaultf5262252017-02-22 23:04:58 +00003376 case Intrinsic::amdgcn_ubfe:
3377 case Intrinsic::amdgcn_sbfe: {
3378 // Decompose simple cases into standard shifts.
3379 Value *Src = II->getArgOperand(0);
3380 if (isa<UndefValue>(Src))
3381 return replaceInstUsesWith(*II, Src);
3382
3383 unsigned Width;
3384 Type *Ty = II->getType();
3385 unsigned IntSize = Ty->getIntegerBitWidth();
3386
3387 ConstantInt *CWidth = dyn_cast<ConstantInt>(II->getArgOperand(2));
3388 if (CWidth) {
3389 Width = CWidth->getZExtValue();
3390 if ((Width & (IntSize - 1)) == 0)
3391 return replaceInstUsesWith(*II, ConstantInt::getNullValue(Ty));
3392
3393 if (Width >= IntSize) {
3394 // Hardware ignores high bits, so remove those.
3395 II->setArgOperand(2, ConstantInt::get(CWidth->getType(),
3396 Width & (IntSize - 1)));
3397 return II;
3398 }
3399 }
3400
3401 unsigned Offset;
3402 ConstantInt *COffset = dyn_cast<ConstantInt>(II->getArgOperand(1));
3403 if (COffset) {
3404 Offset = COffset->getZExtValue();
3405 if (Offset >= IntSize) {
3406 II->setArgOperand(1, ConstantInt::get(COffset->getType(),
3407 Offset & (IntSize - 1)));
3408 return II;
3409 }
3410 }
3411
3412 bool Signed = II->getIntrinsicID() == Intrinsic::amdgcn_sbfe;
3413
3414 // TODO: Also emit sub if only width is constant.
3415 if (!CWidth && COffset && Offset == 0) {
3416 Constant *KSize = ConstantInt::get(COffset->getType(), IntSize);
Craig Topperbb4069e2017-07-07 23:16:26 +00003417 Value *ShiftVal = Builder.CreateSub(KSize, II->getArgOperand(2));
3418 ShiftVal = Builder.CreateZExt(ShiftVal, II->getType());
Matt Arsenaultf5262252017-02-22 23:04:58 +00003419
Craig Topperbb4069e2017-07-07 23:16:26 +00003420 Value *Shl = Builder.CreateShl(Src, ShiftVal);
3421 Value *RightShift = Signed ? Builder.CreateAShr(Shl, ShiftVal)
3422 : Builder.CreateLShr(Shl, ShiftVal);
Matt Arsenaultf5262252017-02-22 23:04:58 +00003423 RightShift->takeName(II);
3424 return replaceInstUsesWith(*II, RightShift);
3425 }
3426
3427 if (!CWidth || !COffset)
3428 break;
3429
3430 // TODO: This allows folding to undef when the hardware has specific
3431 // behavior?
3432 if (Offset + Width < IntSize) {
Craig Topperbb4069e2017-07-07 23:16:26 +00003433 Value *Shl = Builder.CreateShl(Src, IntSize - Offset - Width);
3434 Value *RightShift = Signed ? Builder.CreateAShr(Shl, IntSize - Width)
3435 : Builder.CreateLShr(Shl, IntSize - Width);
Matt Arsenaultf5262252017-02-22 23:04:58 +00003436 RightShift->takeName(II);
3437 return replaceInstUsesWith(*II, RightShift);
3438 }
3439
Craig Topperbb4069e2017-07-07 23:16:26 +00003440 Value *RightShift = Signed ? Builder.CreateAShr(Src, Offset)
3441 : Builder.CreateLShr(Src, Offset);
Matt Arsenaultf5262252017-02-22 23:04:58 +00003442
3443 RightShift->takeName(II);
3444 return replaceInstUsesWith(*II, RightShift);
3445 }
Matt Arsenaultd4bca1e2017-02-23 00:44:03 +00003446 case Intrinsic::amdgcn_exp:
3447 case Intrinsic::amdgcn_exp_compr: {
3448 ConstantInt *En = dyn_cast<ConstantInt>(II->getArgOperand(1));
3449 if (!En) // Illegal.
3450 break;
3451
3452 unsigned EnBits = En->getZExtValue();
3453 if (EnBits == 0xf)
3454 break; // All inputs enabled.
3455
3456 bool IsCompr = II->getIntrinsicID() == Intrinsic::amdgcn_exp_compr;
3457 bool Changed = false;
3458 for (int I = 0; I < (IsCompr ? 2 : 4); ++I) {
3459 if ((!IsCompr && (EnBits & (1 << I)) == 0) ||
3460 (IsCompr && ((EnBits & (0x3 << (2 * I))) == 0))) {
3461 Value *Src = II->getArgOperand(I + 2);
3462 if (!isa<UndefValue>(Src)) {
3463 II->setArgOperand(I + 2, UndefValue::get(Src->getType()));
3464 Changed = true;
3465 }
3466 }
3467 }
3468
3469 if (Changed)
3470 return II;
3471
3472 break;
Matt Arsenaultcdb468c2017-02-27 23:08:49 +00003473 }
3474 case Intrinsic::amdgcn_fmed3: {
3475 // Note this does not preserve proper sNaN behavior if IEEE-mode is enabled
3476 // for the shader.
3477
3478 Value *Src0 = II->getArgOperand(0);
3479 Value *Src1 = II->getArgOperand(1);
3480 Value *Src2 = II->getArgOperand(2);
3481
Matt Arsenault24ce89b2018-07-05 17:05:36 +00003482 // Checking for NaN before canonicalization provides better fidelity when
3483 // mapping other operations onto fmed3 since the order of operands is
3484 // unchanged.
3485 CallInst *NewCall = nullptr;
3486 if (match(Src0, m_NaN()) || isa<UndefValue>(Src0)) {
3487 NewCall = Builder.CreateMinNum(Src1, Src2);
3488 } else if (match(Src1, m_NaN()) || isa<UndefValue>(Src1)) {
3489 NewCall = Builder.CreateMinNum(Src0, Src2);
3490 } else if (match(Src2, m_NaN()) || isa<UndefValue>(Src2)) {
3491 NewCall = Builder.CreateMaxNum(Src0, Src1);
3492 }
3493
3494 if (NewCall) {
3495 NewCall->copyFastMathFlags(II);
3496 NewCall->takeName(II);
3497 return replaceInstUsesWith(*II, NewCall);
3498 }
3499
Matt Arsenaultcdb468c2017-02-27 23:08:49 +00003500 bool Swap = false;
3501 // Canonicalize constants to RHS operands.
3502 //
3503 // fmed3(c0, x, c1) -> fmed3(x, c0, c1)
3504 if (isa<Constant>(Src0) && !isa<Constant>(Src1)) {
3505 std::swap(Src0, Src1);
3506 Swap = true;
3507 }
3508
3509 if (isa<Constant>(Src1) && !isa<Constant>(Src2)) {
3510 std::swap(Src1, Src2);
3511 Swap = true;
3512 }
3513
3514 if (isa<Constant>(Src0) && !isa<Constant>(Src1)) {
3515 std::swap(Src0, Src1);
3516 Swap = true;
3517 }
3518
3519 if (Swap) {
3520 II->setArgOperand(0, Src0);
3521 II->setArgOperand(1, Src1);
3522 II->setArgOperand(2, Src2);
3523 return II;
3524 }
3525
Matt Arsenaultcdb468c2017-02-27 23:08:49 +00003526 if (const ConstantFP *C0 = dyn_cast<ConstantFP>(Src0)) {
3527 if (const ConstantFP *C1 = dyn_cast<ConstantFP>(Src1)) {
3528 if (const ConstantFP *C2 = dyn_cast<ConstantFP>(Src2)) {
3529 APFloat Result = fmed3AMDGCN(C0->getValueAPF(), C1->getValueAPF(),
3530 C2->getValueAPF());
3531 return replaceInstUsesWith(*II,
Craig Topperbb4069e2017-07-07 23:16:26 +00003532 ConstantFP::get(Builder.getContext(), Result));
Matt Arsenaultcdb468c2017-02-27 23:08:49 +00003533 }
3534 }
3535 }
3536
3537 break;
Matt Arsenaultd4bca1e2017-02-23 00:44:03 +00003538 }
Matt Arsenaultd81f5572017-03-13 18:14:02 +00003539 case Intrinsic::amdgcn_icmp:
3540 case Intrinsic::amdgcn_fcmp: {
3541 const ConstantInt *CC = dyn_cast<ConstantInt>(II->getArgOperand(2));
3542 if (!CC)
3543 break;
3544
3545 // Guard against invalid arguments.
3546 int64_t CCVal = CC->getZExtValue();
3547 bool IsInteger = II->getIntrinsicID() == Intrinsic::amdgcn_icmp;
3548 if ((IsInteger && (CCVal < CmpInst::FIRST_ICMP_PREDICATE ||
3549 CCVal > CmpInst::LAST_ICMP_PREDICATE)) ||
3550 (!IsInteger && (CCVal < CmpInst::FIRST_FCMP_PREDICATE ||
3551 CCVal > CmpInst::LAST_FCMP_PREDICATE)))
3552 break;
3553
3554 Value *Src0 = II->getArgOperand(0);
3555 Value *Src1 = II->getArgOperand(1);
3556
3557 if (auto *CSrc0 = dyn_cast<Constant>(Src0)) {
3558 if (auto *CSrc1 = dyn_cast<Constant>(Src1)) {
3559 Constant *CCmp = ConstantExpr::getCompare(CCVal, CSrc0, CSrc1);
Nicolai Haehnle9c661852017-04-24 17:08:43 +00003560 if (CCmp->isNullValue()) {
3561 return replaceInstUsesWith(
3562 *II, ConstantExpr::getSExt(CCmp, II->getType()));
3563 }
3564
3565 // The result of V_ICMP/V_FCMP assembly instructions (which this
3566 // intrinsic exposes) is one bit per thread, masked with the EXEC
3567 // register (which contains the bitmask of live threads). So a
3568 // comparison that always returns true is the same as a read of the
3569 // EXEC register.
3570 Value *NewF = Intrinsic::getDeclaration(
3571 II->getModule(), Intrinsic::read_register, II->getType());
3572 Metadata *MDArgs[] = {MDString::get(II->getContext(), "exec")};
3573 MDNode *MD = MDNode::get(II->getContext(), MDArgs);
3574 Value *Args[] = {MetadataAsValue::get(II->getContext(), MD)};
Craig Topperbb4069e2017-07-07 23:16:26 +00003575 CallInst *NewCall = Builder.CreateCall(NewF, Args);
Nicolai Haehnle9c661852017-04-24 17:08:43 +00003576 NewCall->addAttribute(AttributeList::FunctionIndex,
3577 Attribute::Convergent);
3578 NewCall->takeName(II);
3579 return replaceInstUsesWith(*II, NewCall);
Matt Arsenaultd81f5572017-03-13 18:14:02 +00003580 }
3581
3582 // Canonicalize constants to RHS.
3583 CmpInst::Predicate SwapPred
3584 = CmpInst::getSwappedPredicate(static_cast<CmpInst::Predicate>(CCVal));
3585 II->setArgOperand(0, Src1);
3586 II->setArgOperand(1, Src0);
3587 II->setArgOperand(2, ConstantInt::get(CC->getType(),
3588 static_cast<int>(SwapPred)));
3589 return II;
3590 }
3591
3592 if (CCVal != CmpInst::ICMP_EQ && CCVal != CmpInst::ICMP_NE)
3593 break;
3594
3595 // Canonicalize compare eq with true value to compare != 0
3596 // llvm.amdgcn.icmp(zext (i1 x), 1, eq)
3597 // -> llvm.amdgcn.icmp(zext (i1 x), 0, ne)
3598 // llvm.amdgcn.icmp(sext (i1 x), -1, eq)
3599 // -> llvm.amdgcn.icmp(sext (i1 x), 0, ne)
3600 Value *ExtSrc;
3601 if (CCVal == CmpInst::ICMP_EQ &&
3602 ((match(Src1, m_One()) && match(Src0, m_ZExt(m_Value(ExtSrc)))) ||
3603 (match(Src1, m_AllOnes()) && match(Src0, m_SExt(m_Value(ExtSrc))))) &&
3604 ExtSrc->getType()->isIntegerTy(1)) {
3605 II->setArgOperand(1, ConstantInt::getNullValue(Src1->getType()));
3606 II->setArgOperand(2, ConstantInt::get(CC->getType(), CmpInst::ICMP_NE));
3607 return II;
3608 }
3609
3610 CmpInst::Predicate SrcPred;
3611 Value *SrcLHS;
3612 Value *SrcRHS;
3613
3614 // Fold compare eq/ne with 0 from a compare result as the predicate to the
3615 // intrinsic. The typical use is a wave vote function in the library, which
3616 // will be fed from a user code condition compared with 0. Fold in the
3617 // redundant compare.
3618
3619 // llvm.amdgcn.icmp([sz]ext ([if]cmp pred a, b), 0, ne)
3620 // -> llvm.amdgcn.[if]cmp(a, b, pred)
3621 //
3622 // llvm.amdgcn.icmp([sz]ext ([if]cmp pred a, b), 0, eq)
3623 // -> llvm.amdgcn.[if]cmp(a, b, inv pred)
3624 if (match(Src1, m_Zero()) &&
3625 match(Src0,
3626 m_ZExtOrSExt(m_Cmp(SrcPred, m_Value(SrcLHS), m_Value(SrcRHS))))) {
3627 if (CCVal == CmpInst::ICMP_EQ)
3628 SrcPred = CmpInst::getInversePredicate(SrcPred);
3629
3630 Intrinsic::ID NewIID = CmpInst::isFPPredicate(SrcPred) ?
3631 Intrinsic::amdgcn_fcmp : Intrinsic::amdgcn_icmp;
3632
3633 Value *NewF = Intrinsic::getDeclaration(II->getModule(), NewIID,
3634 SrcLHS->getType());
3635 Value *Args[] = { SrcLHS, SrcRHS,
3636 ConstantInt::get(CC->getType(), SrcPred) };
Craig Topperbb4069e2017-07-07 23:16:26 +00003637 CallInst *NewCall = Builder.CreateCall(NewF, Args);
Matt Arsenaultd81f5572017-03-13 18:14:02 +00003638 NewCall->takeName(II);
3639 return replaceInstUsesWith(*II, NewCall);
3640 }
3641
3642 break;
3643 }
Marek Olsak2114fc32017-10-24 10:26:59 +00003644 case Intrinsic::amdgcn_wqm_vote: {
3645 // wqm_vote is identity when the argument is constant.
3646 if (!isa<Constant>(II->getArgOperand(0)))
3647 break;
3648
3649 return replaceInstUsesWith(*II, II->getArgOperand(0));
3650 }
Marek Olsakce76ea02017-10-24 10:27:13 +00003651 case Intrinsic::amdgcn_kill: {
3652 const ConstantInt *C = dyn_cast<ConstantInt>(II->getArgOperand(0));
3653 if (!C || !C->getZExtValue())
3654 break;
3655
3656 // amdgcn.kill(i1 1) is a no-op
3657 return eraseInstFromFunction(CI);
3658 }
Stanislav Mekhanoshin0e132dc2018-05-22 08:04:33 +00003659 case Intrinsic::amdgcn_update_dpp: {
3660 Value *Old = II->getArgOperand(0);
3661
3662 auto BC = dyn_cast<ConstantInt>(II->getArgOperand(5));
3663 auto RM = dyn_cast<ConstantInt>(II->getArgOperand(3));
3664 auto BM = dyn_cast<ConstantInt>(II->getArgOperand(4));
3665 if (!BC || !RM || !BM ||
3666 BC->isZeroValue() ||
3667 RM->getZExtValue() != 0xF ||
3668 BM->getZExtValue() != 0xF ||
3669 isa<UndefValue>(Old))
3670 break;
3671
3672 // If bound_ctrl = 1, row mask = bank mask = 0xf we can omit old value.
3673 II->setOperand(0, UndefValue::get(Old->getType()));
3674 return II;
3675 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003676 case Intrinsic::stackrestore: {
3677 // If the save is right next to the restore, remove the restore. This can
3678 // happen when variable allocas are DCE'd.
Gabor Greif589a0b92010-06-24 12:58:35 +00003679 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getArgOperand(0))) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003680 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
Vedant Kumarf01827f2018-06-19 23:42:17 +00003681 // Skip over debug info.
3682 if (SS->getNextNonDebugInstruction() == II) {
Sanjay Patel4b198802016-02-01 22:23:39 +00003683 return eraseInstFromFunction(CI);
Davide Italiano189c2cf2018-06-08 20:42:36 +00003684 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003685 }
3686 }
Jim Grosbach7815f562012-02-03 00:07:04 +00003687
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003688 // Scan down this block to see if there is another stack restore in the
3689 // same block without an intervening call/alloca.
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00003690 BasicBlock::iterator BI(II);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003691 TerminatorInst *TI = II->getParent()->getTerminator();
3692 bool CannotRemove = false;
3693 for (++BI; &*BI != TI; ++BI) {
Nuno Lopes55fff832012-06-21 15:45:28 +00003694 if (isa<AllocaInst>(BI)) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003695 CannotRemove = true;
3696 break;
3697 }
3698 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
3699 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
3700 // If there is a stackrestore below this one, remove this one.
3701 if (II->getIntrinsicID() == Intrinsic::stackrestore)
Sanjay Patel4b198802016-02-01 22:23:39 +00003702 return eraseInstFromFunction(CI);
Reid Kleckner892ae2e2016-02-27 00:53:54 +00003703
3704 // Bail if we cross over an intrinsic with side effects, such as
3705 // llvm.stacksave, llvm.read_register, or llvm.setjmp.
3706 if (II->mayHaveSideEffects()) {
3707 CannotRemove = true;
3708 break;
3709 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003710 } else {
3711 // If we found a non-intrinsic call, we can't remove the stack
3712 // restore.
3713 CannotRemove = true;
3714 break;
3715 }
3716 }
3717 }
Jim Grosbach7815f562012-02-03 00:07:04 +00003718
Bill Wendlingf891bf82011-07-31 06:30:59 +00003719 // If the stack restore is in a return, resume, or unwind block and if there
3720 // are no allocas or calls between the restore and the return, nuke the
3721 // restore.
Bill Wendlingd5d95b02012-02-06 21:16:41 +00003722 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<ResumeInst>(TI)))
Sanjay Patel4b198802016-02-01 22:23:39 +00003723 return eraseInstFromFunction(CI);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003724 break;
3725 }
Vitaly Bukaf0500b62016-07-28 22:50:48 +00003726 case Intrinsic::lifetime_start:
Vitaly Buka0ab23cf2016-07-28 22:59:03 +00003727 // Asan needs to poison memory to detect invalid access which is possible
3728 // even for empty lifetime range.
Evgeniy Stepanovc667c1f2017-12-09 00:21:41 +00003729 if (II->getFunction()->hasFnAttribute(Attribute::SanitizeAddress) ||
3730 II->getFunction()->hasFnAttribute(Attribute::SanitizeHWAddress))
Vitaly Buka0ab23cf2016-07-28 22:59:03 +00003731 break;
3732
Arnaud A. de Grandmaison333ef382016-05-10 09:24:49 +00003733 if (removeTriviallyEmptyRange(*II, Intrinsic::lifetime_start,
3734 Intrinsic::lifetime_end, *this))
3735 return nullptr;
Arnaud A. de Grandmaison849f3bf2015-10-01 14:54:31 +00003736 break;
Hal Finkelf5867a72014-07-25 21:45:17 +00003737 case Intrinsic::assume: {
David Majnemerfcc58112016-04-08 16:37:12 +00003738 Value *IIOperand = II->getArgOperand(0);
Sanjay Patel825a4fa2018-06-20 13:22:26 +00003739 // Remove an assume if it is followed by an identical assume.
3740 // TODO: Do we need this? Unless there are conflicting assumptions, the
3741 // computeKnownBits(IIOperand) below here eliminates redundant assumes.
3742 Instruction *Next = II->getNextNonDebugInstruction();
3743 if (match(Next, m_Intrinsic<Intrinsic::assume>(m_Specific(IIOperand))))
David Majnemerfcc58112016-04-08 16:37:12 +00003744 return eraseInstFromFunction(CI);
3745
Hal Finkelf5867a72014-07-25 21:45:17 +00003746 // Canonicalize assume(a && b) -> assume(a); assume(b);
Hal Finkel74c2f352014-09-07 12:44:26 +00003747 // Note: New assumption intrinsics created here are registered by
3748 // the InstCombineIRInserter object.
David Majnemerfcc58112016-04-08 16:37:12 +00003749 Value *AssumeIntrinsic = II->getCalledValue(), *A, *B;
Hal Finkelf5867a72014-07-25 21:45:17 +00003750 if (match(IIOperand, m_And(m_Value(A), m_Value(B)))) {
Craig Topperbb4069e2017-07-07 23:16:26 +00003751 Builder.CreateCall(AssumeIntrinsic, A, II->getName());
3752 Builder.CreateCall(AssumeIntrinsic, B, II->getName());
Sanjay Patel4b198802016-02-01 22:23:39 +00003753 return eraseInstFromFunction(*II);
Hal Finkelf5867a72014-07-25 21:45:17 +00003754 }
3755 // assume(!(a || b)) -> assume(!a); assume(!b);
3756 if (match(IIOperand, m_Not(m_Or(m_Value(A), m_Value(B))))) {
Craig Topperbb4069e2017-07-07 23:16:26 +00003757 Builder.CreateCall(AssumeIntrinsic, Builder.CreateNot(A), II->getName());
3758 Builder.CreateCall(AssumeIntrinsic, Builder.CreateNot(B), II->getName());
Sanjay Patel4b198802016-02-01 22:23:39 +00003759 return eraseInstFromFunction(*II);
Hal Finkelf5867a72014-07-25 21:45:17 +00003760 }
Hal Finkel04a15612014-10-04 21:27:06 +00003761
Philip Reames66c6de62014-11-11 23:33:19 +00003762 // assume( (load addr) != null ) -> add 'nonnull' metadata to load
3763 // (if assume is valid at the load)
Sanjay Patelf0d1e7732017-01-03 22:25:31 +00003764 CmpInst::Predicate Pred;
3765 Instruction *LHS;
3766 if (match(IIOperand, m_ICmp(Pred, m_Instruction(LHS), m_Zero())) &&
3767 Pred == ICmpInst::ICMP_NE && LHS->getOpcode() == Instruction::Load &&
3768 LHS->getType()->isPointerTy() &&
3769 isValidAssumeForContext(II, LHS, &DT)) {
3770 MDNode *MD = MDNode::get(II->getContext(), None);
3771 LHS->setMetadata(LLVMContext::MD_nonnull, MD);
3772 return eraseInstFromFunction(*II);
3773
Chandler Carruth24969102015-02-10 08:07:32 +00003774 // TODO: apply nonnull return attributes to calls and invokes
Philip Reames66c6de62014-11-11 23:33:19 +00003775 // TODO: apply range metadata for range check patterns?
3776 }
Sanjay Patelf0d1e7732017-01-03 22:25:31 +00003777
Hal Finkel04a15612014-10-04 21:27:06 +00003778 // If there is a dominating assume with the same condition as this one,
3779 // then this one is redundant, and should be removed.
Craig Topperb45eabc2017-04-26 16:39:58 +00003780 KnownBits Known(1);
3781 computeKnownBits(IIOperand, Known, 0, II);
Craig Topperf0aeee02017-05-05 17:36:09 +00003782 if (Known.isAllOnes())
Sanjay Patel4b198802016-02-01 22:23:39 +00003783 return eraseInstFromFunction(*II);
Hal Finkel04a15612014-10-04 21:27:06 +00003784
Hal Finkel8a9a7832017-01-11 13:24:24 +00003785 // Update the cache of affected values for this assumption (we might be
3786 // here because we just simplified the condition).
3787 AC.updateAffectedValues(II);
Hal Finkelf5867a72014-07-25 21:45:17 +00003788 break;
3789 }
Philip Reames9db26ff2014-12-29 23:27:30 +00003790 case Intrinsic::experimental_gc_relocate: {
3791 // Translate facts known about a pointer before relocating into
3792 // facts about the relocate value, while being careful to
3793 // preserve relocation semantics.
Manuel Jacob83eefa62016-01-05 04:03:00 +00003794 Value *DerivedPtr = cast<GCRelocateInst>(II)->getDerivedPtr();
Philip Reames9db26ff2014-12-29 23:27:30 +00003795
3796 // Remove the relocation if unused, note that this check is required
3797 // to prevent the cases below from looping forever.
3798 if (II->use_empty())
Sanjay Patel4b198802016-02-01 22:23:39 +00003799 return eraseInstFromFunction(*II);
Philip Reames9db26ff2014-12-29 23:27:30 +00003800
3801 // Undef is undef, even after relocation.
3802 // TODO: provide a hook for this in GCStrategy. This is clearly legal for
3803 // most practical collectors, but there was discussion in the review thread
3804 // about whether it was legal for all possible collectors.
Philip Reamesea4d8e82016-02-09 21:09:22 +00003805 if (isa<UndefValue>(DerivedPtr))
3806 // Use undef of gc_relocate's type to replace it.
3807 return replaceInstUsesWith(*II, UndefValue::get(II->getType()));
Philip Reames9db26ff2014-12-29 23:27:30 +00003808
Philip Reamesea4d8e82016-02-09 21:09:22 +00003809 if (auto *PT = dyn_cast<PointerType>(II->getType())) {
3810 // The relocation of null will be null for most any collector.
3811 // TODO: provide a hook for this in GCStrategy. There might be some
3812 // weird collector this property does not hold for.
3813 if (isa<ConstantPointerNull>(DerivedPtr))
3814 // Use null-pointer of gc_relocate's type to replace it.
3815 return replaceInstUsesWith(*II, ConstantPointerNull::get(PT));
Simon Pilgrimc0c56e72016-04-24 17:00:34 +00003816
Philip Reamesea4d8e82016-02-09 21:09:22 +00003817 // isKnownNonNull -> nonnull attribute
Nuno Lopes404f1062017-09-09 18:23:11 +00003818 if (isKnownNonZero(DerivedPtr, DL, 0, &AC, II, &DT))
Reid Klecknerb5180542017-03-21 16:57:19 +00003819 II->addAttribute(AttributeList::ReturnIndex, Attribute::NonNull);
Ramkumar Ramachandra8fcb4982015-02-14 19:37:54 +00003820 }
Philip Reames9db26ff2014-12-29 23:27:30 +00003821
3822 // TODO: bitcast(relocate(p)) -> relocate(bitcast(p))
3823 // Canonicalize on the type from the uses to the defs
Ramkumar Ramachandra8fcb4982015-02-14 19:37:54 +00003824
Philip Reames9db26ff2014-12-29 23:27:30 +00003825 // TODO: relocate((gep p, C, C2, ...)) -> gep(relocate(p), C, C2, ...)
Philip Reamesea4d8e82016-02-09 21:09:22 +00003826 break;
Philip Reames9db26ff2014-12-29 23:27:30 +00003827 }
Artur Pilipenkoe812ca02017-01-25 14:12:12 +00003828
3829 case Intrinsic::experimental_guard: {
Philip Reames79e917d2018-05-09 22:56:32 +00003830 // Is this guard followed by another guard? We scan forward over a small
3831 // fixed window of instructions to handle common cases with conditions
3832 // computed between guards.
Sanjoy Dase0e57952017-02-01 16:34:55 +00003833 Instruction *NextInst = II->getNextNode();
Philip Reames913a7792018-05-10 00:05:29 +00003834 for (unsigned i = 0; i < GuardWideningWindow; i++) {
Philip Reames79e917d2018-05-09 22:56:32 +00003835 // Note: Using context-free form to avoid compile time blow up
3836 if (!isSafeToSpeculativelyExecute(NextInst))
3837 break;
3838 NextInst = NextInst->getNextNode();
3839 }
Sanjoy Dase0e57952017-02-01 16:34:55 +00003840 Value *NextCond = nullptr;
3841 if (match(NextInst,
3842 m_Intrinsic<Intrinsic::experimental_guard>(m_Value(NextCond)))) {
3843 Value *CurrCond = II->getArgOperand(0);
Artur Pilipenkoe812ca02017-01-25 14:12:12 +00003844
Simon Pilgrim68168d12017-03-30 12:59:53 +00003845 // Remove a guard that it is immediately preceded by an identical guard.
Sanjoy Dase0e57952017-02-01 16:34:55 +00003846 if (CurrCond == NextCond)
3847 return eraseInstFromFunction(*NextInst);
3848
3849 // Otherwise canonicalize guard(a); guard(b) -> guard(a & b).
Philip Reames79e917d2018-05-09 22:56:32 +00003850 Instruction* MoveI = II->getNextNode();
3851 while (MoveI != NextInst) {
3852 auto *Temp = MoveI;
3853 MoveI = MoveI->getNextNode();
3854 Temp->moveBefore(II);
3855 }
Craig Topperbb4069e2017-07-07 23:16:26 +00003856 II->setArgOperand(0, Builder.CreateAnd(CurrCond, NextCond));
Sanjoy Dase0e57952017-02-01 16:34:55 +00003857 return eraseInstFromFunction(*NextInst);
3858 }
Artur Pilipenkoe812ca02017-01-25 14:12:12 +00003859 break;
3860 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003861 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003862 return visitCallSite(II);
3863}
3864
Davide Italianoaec46172017-01-31 18:09:05 +00003865// Fence instruction simplification
3866Instruction *InstCombiner::visitFenceInst(FenceInst &FI) {
3867 // Remove identical consecutive fences.
Vedant Kumarf01827f2018-06-19 23:42:17 +00003868 Instruction *Next = FI.getNextNonDebugInstruction();
Tim Northover9b800602018-06-06 12:46:02 +00003869 if (auto *NFI = dyn_cast<FenceInst>(Next))
Davide Italianoaec46172017-01-31 18:09:05 +00003870 if (FI.isIdenticalTo(NFI))
3871 return eraseInstFromFunction(FI);
3872 return nullptr;
3873}
3874
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003875// InvokeInst simplification
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003876Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
3877 return visitCallSite(&II);
3878}
3879
Sanjay Patelcd4377c2016-01-20 22:24:38 +00003880/// If this cast does not affect the value passed through the varargs area, we
3881/// can eliminate the use of the cast.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003882static bool isSafeToEliminateVarargsCast(const CallSite CS,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003883 const DataLayout &DL,
3884 const CastInst *const CI,
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003885 const int ix) {
3886 if (!CI->isLosslessCast())
3887 return false;
3888
Philip Reames1a1bdb22014-12-02 18:50:36 +00003889 // If this is a GC intrinsic, avoid munging types. We need types for
3890 // statepoint reconstruction in SelectionDAG.
3891 // TODO: This is probably something which should be expanded to all
3892 // intrinsics since the entire point of intrinsics is that
3893 // they are understandable by the optimizer.
3894 if (isStatepoint(CS) || isGCRelocate(CS) || isGCResult(CS))
3895 return false;
3896
Reid Kleckner26af2ca2014-01-28 02:38:36 +00003897 // The size of ByVal or InAlloca arguments is derived from the type, so we
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003898 // can't change to a type with a different size. If the size were
3899 // passed explicitly we could avoid this check.
Reid Kleckner26af2ca2014-01-28 02:38:36 +00003900 if (!CS.isByValOrInAllocaArgument(ix))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003901 return true;
3902
Jim Grosbach7815f562012-02-03 00:07:04 +00003903 Type* SrcTy =
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003904 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
Chris Lattner229907c2011-07-18 04:54:35 +00003905 Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003906 if (!SrcTy->isSized() || !DstTy->isSized())
3907 return false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003908 if (DL.getTypeAllocSize(SrcTy) != DL.getTypeAllocSize(DstTy))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003909 return false;
3910 return true;
3911}
3912
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003913Instruction *InstCombiner::tryOptimizeCall(CallInst *CI) {
Craig Topperf40110f2014-04-25 05:29:35 +00003914 if (!CI->getCalledFunction()) return nullptr;
Eric Christophera7fb58f2010-03-06 10:50:38 +00003915
Chandler Carruthba4c5172015-01-21 11:23:40 +00003916 auto InstCombineRAUW = [this](Instruction *From, Value *With) {
Sanjay Patel4b198802016-02-01 22:23:39 +00003917 replaceInstUsesWith(*From, With);
Chandler Carruthba4c5172015-01-21 11:23:40 +00003918 };
Adam Nemetea06e6e2017-07-26 19:03:18 +00003919 LibCallSimplifier Simplifier(DL, &TLI, ORE, InstCombineRAUW);
Chandler Carruthba4c5172015-01-21 11:23:40 +00003920 if (Value *With = Simplifier.optimizeCall(CI)) {
Meador Ingee3f2b262012-11-30 04:05:06 +00003921 ++NumSimplified;
Sanjay Patel4b198802016-02-01 22:23:39 +00003922 return CI->use_empty() ? CI : replaceInstUsesWith(*CI, With);
Meador Ingee3f2b262012-11-30 04:05:06 +00003923 }
Meador Ingedf796f82012-10-13 16:45:24 +00003924
Craig Topperf40110f2014-04-25 05:29:35 +00003925 return nullptr;
Eric Christophera7fb58f2010-03-06 10:50:38 +00003926}
3927
Sanjay Patel6038d3e2016-01-29 23:27:03 +00003928static IntrinsicInst *findInitTrampolineFromAlloca(Value *TrampMem) {
Duncan Sandsa0984362011-09-06 13:37:06 +00003929 // Strip off at most one level of pointer casts, looking for an alloca. This
3930 // is good enough in practice and simpler than handling any number of casts.
3931 Value *Underlying = TrampMem->stripPointerCasts();
3932 if (Underlying != TrampMem &&
Chandler Carruthcdf47882014-03-09 03:16:01 +00003933 (!Underlying->hasOneUse() || Underlying->user_back() != TrampMem))
Craig Topperf40110f2014-04-25 05:29:35 +00003934 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00003935 if (!isa<AllocaInst>(Underlying))
Craig Topperf40110f2014-04-25 05:29:35 +00003936 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00003937
Craig Topperf40110f2014-04-25 05:29:35 +00003938 IntrinsicInst *InitTrampoline = nullptr;
Chandler Carruthcdf47882014-03-09 03:16:01 +00003939 for (User *U : TrampMem->users()) {
3940 IntrinsicInst *II = dyn_cast<IntrinsicInst>(U);
Duncan Sandsa0984362011-09-06 13:37:06 +00003941 if (!II)
Craig Topperf40110f2014-04-25 05:29:35 +00003942 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00003943 if (II->getIntrinsicID() == Intrinsic::init_trampoline) {
3944 if (InitTrampoline)
3945 // More than one init_trampoline writes to this value. Give up.
Craig Topperf40110f2014-04-25 05:29:35 +00003946 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00003947 InitTrampoline = II;
3948 continue;
3949 }
3950 if (II->getIntrinsicID() == Intrinsic::adjust_trampoline)
3951 // Allow any number of calls to adjust.trampoline.
3952 continue;
Craig Topperf40110f2014-04-25 05:29:35 +00003953 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00003954 }
3955
3956 // No call to init.trampoline found.
3957 if (!InitTrampoline)
Craig Topperf40110f2014-04-25 05:29:35 +00003958 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00003959
3960 // Check that the alloca is being used in the expected way.
3961 if (InitTrampoline->getOperand(0) != TrampMem)
Craig Topperf40110f2014-04-25 05:29:35 +00003962 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00003963
3964 return InitTrampoline;
3965}
3966
Sanjay Patel6038d3e2016-01-29 23:27:03 +00003967static IntrinsicInst *findInitTrampolineFromBB(IntrinsicInst *AdjustTramp,
Duncan Sandsa0984362011-09-06 13:37:06 +00003968 Value *TrampMem) {
3969 // Visit all the previous instructions in the basic block, and try to find a
3970 // init.trampoline which has a direct path to the adjust.trampoline.
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00003971 for (BasicBlock::iterator I = AdjustTramp->getIterator(),
3972 E = AdjustTramp->getParent()->begin();
3973 I != E;) {
3974 Instruction *Inst = &*--I;
Duncan Sandsa0984362011-09-06 13:37:06 +00003975 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
3976 if (II->getIntrinsicID() == Intrinsic::init_trampoline &&
3977 II->getOperand(0) == TrampMem)
3978 return II;
3979 if (Inst->mayWriteToMemory())
Craig Topperf40110f2014-04-25 05:29:35 +00003980 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00003981 }
Craig Topperf40110f2014-04-25 05:29:35 +00003982 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00003983}
3984
3985// Given a call to llvm.adjust.trampoline, find and return the corresponding
3986// call to llvm.init.trampoline if the call to the trampoline can be optimized
3987// to a direct call to a function. Otherwise return NULL.
Sanjay Patel6038d3e2016-01-29 23:27:03 +00003988static IntrinsicInst *findInitTrampoline(Value *Callee) {
Duncan Sandsa0984362011-09-06 13:37:06 +00003989 Callee = Callee->stripPointerCasts();
3990 IntrinsicInst *AdjustTramp = dyn_cast<IntrinsicInst>(Callee);
3991 if (!AdjustTramp ||
3992 AdjustTramp->getIntrinsicID() != Intrinsic::adjust_trampoline)
Craig Topperf40110f2014-04-25 05:29:35 +00003993 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00003994
3995 Value *TrampMem = AdjustTramp->getOperand(0);
3996
Sanjay Patel6038d3e2016-01-29 23:27:03 +00003997 if (IntrinsicInst *IT = findInitTrampolineFromAlloca(TrampMem))
Duncan Sandsa0984362011-09-06 13:37:06 +00003998 return IT;
Sanjay Patel6038d3e2016-01-29 23:27:03 +00003999 if (IntrinsicInst *IT = findInitTrampolineFromBB(AdjustTramp, TrampMem))
Duncan Sandsa0984362011-09-06 13:37:06 +00004000 return IT;
Craig Topperf40110f2014-04-25 05:29:35 +00004001 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00004002}
4003
Sanjay Patelcd4377c2016-01-20 22:24:38 +00004004/// Improvements for call and invoke instructions.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004005Instruction *InstCombiner::visitCallSite(CallSite CS) {
Justin Bogner99798402016-08-05 01:06:44 +00004006 if (isAllocLikeFn(CS.getInstruction(), &TLI))
Nuno Lopes95cc4f32012-07-09 18:38:20 +00004007 return visitAllocSite(*CS.getInstruction());
Nuno Lopesdc6085e2012-06-21 21:25:05 +00004008
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004009 bool Changed = false;
4010
Philip Reamesc25df112015-06-16 20:24:25 +00004011 // Mark any parameters that are known to be non-null with the nonnull
4012 // attribute. This is helpful for inlining calls to functions with null
4013 // checks on their arguments.
Reid Kleckner5fbdd172017-05-31 19:23:09 +00004014 SmallVector<unsigned, 4> ArgNos;
Philip Reamesc25df112015-06-16 20:24:25 +00004015 unsigned ArgNo = 0;
Akira Hatanaka237916b2015-12-02 06:58:49 +00004016
Philip Reamesc25df112015-06-16 20:24:25 +00004017 for (Value *V : CS.args()) {
Sanjay Patelf9f5d3c2016-01-29 23:14:58 +00004018 if (V->getType()->isPointerTy() &&
Reid Klecknerfb502d22017-04-14 20:19:02 +00004019 !CS.paramHasAttr(ArgNo, Attribute::NonNull) &&
Nuno Lopes404f1062017-09-09 18:23:11 +00004020 isKnownNonZero(V, DL, 0, &AC, CS.getInstruction(), &DT))
Reid Kleckner5fbdd172017-05-31 19:23:09 +00004021 ArgNos.push_back(ArgNo);
Philip Reamesc25df112015-06-16 20:24:25 +00004022 ArgNo++;
4023 }
Akira Hatanaka237916b2015-12-02 06:58:49 +00004024
Philip Reamesc25df112015-06-16 20:24:25 +00004025 assert(ArgNo == CS.arg_size() && "sanity check");
4026
Reid Kleckner5fbdd172017-05-31 19:23:09 +00004027 if (!ArgNos.empty()) {
Reid Klecknerb5180542017-03-21 16:57:19 +00004028 AttributeList AS = CS.getAttributes();
Akira Hatanaka237916b2015-12-02 06:58:49 +00004029 LLVMContext &Ctx = CS.getInstruction()->getContext();
Reid Kleckner5fbdd172017-05-31 19:23:09 +00004030 AS = AS.addParamAttribute(Ctx, ArgNos,
4031 Attribute::get(Ctx, Attribute::NonNull));
Akira Hatanaka237916b2015-12-02 06:58:49 +00004032 CS.setAttributes(AS);
4033 Changed = true;
4034 }
4035
Chris Lattner73989652010-12-20 08:25:06 +00004036 // If the callee is a pointer to a function, attempt to move any casts to the
4037 // arguments of the call/invoke.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004038 Value *Callee = CS.getCalledValue();
Chris Lattner73989652010-12-20 08:25:06 +00004039 if (!isa<Function>(Callee) && transformConstExprCastCall(CS))
Craig Topperf40110f2014-04-25 05:29:35 +00004040 return nullptr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004041
Justin Lebar9d943972016-03-14 20:18:54 +00004042 if (Function *CalleeF = dyn_cast<Function>(Callee)) {
4043 // Remove the convergent attr on calls when the callee is not convergent.
Matt Arsenault802ebcb2016-06-20 19:04:44 +00004044 if (CS.isConvergent() && !CalleeF->isConvergent() &&
4045 !CalleeF->isIntrinsic()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004046 LLVM_DEBUG(dbgs() << "Removing convergent attr from instr "
4047 << CS.getInstruction() << "\n");
Justin Lebar9d943972016-03-14 20:18:54 +00004048 CS.setNotConvergent();
4049 return CS.getInstruction();
4050 }
4051
Chris Lattner846a52e2010-02-01 18:11:34 +00004052 // If the call and callee calling conventions don't match, this call must
4053 // be unreachable, as the call is undefined.
4054 if (CalleeF->getCallingConv() != CS.getCallingConv() &&
4055 // Only do this for calls to a function with a body. A prototype may
4056 // not actually end up matching the implementation's calling conv for a
4057 // variety of reasons (e.g. it may be written in assembly).
4058 !CalleeF->isDeclaration()) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004059 Instruction *OldCall = CS.getInstruction();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004060 new StoreInst(ConstantInt::getTrue(Callee->getContext()),
Jim Grosbach7815f562012-02-03 00:07:04 +00004061 UndefValue::get(Type::getInt1PtrTy(Callee->getContext())),
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004062 OldCall);
Chad Rosiere28ae302012-12-13 00:18:46 +00004063 // If OldCall does not return void then replaceAllUsesWith undef.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004064 // This allows ValueHandlers and custom metadata to adjust itself.
4065 if (!OldCall->getType()->isVoidTy())
Sanjay Patel4b198802016-02-01 22:23:39 +00004066 replaceInstUsesWith(*OldCall, UndefValue::get(OldCall->getType()));
Chris Lattner2cecedf2010-02-01 18:04:58 +00004067 if (isa<CallInst>(OldCall))
Sanjay Patel4b198802016-02-01 22:23:39 +00004068 return eraseInstFromFunction(*OldCall);
Jim Grosbach7815f562012-02-03 00:07:04 +00004069
Chris Lattner2cecedf2010-02-01 18:04:58 +00004070 // We cannot remove an invoke, because it would change the CFG, just
4071 // change the callee to a null pointer.
Gabor Greiffebf6ab2010-03-20 21:00:25 +00004072 cast<InvokeInst>(OldCall)->setCalledFunction(
Chris Lattner2cecedf2010-02-01 18:04:58 +00004073 Constant::getNullValue(CalleeF->getType()));
Craig Topperf40110f2014-04-25 05:29:35 +00004074 return nullptr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004075 }
Justin Lebar9d943972016-03-14 20:18:54 +00004076 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004077
Manoj Gupta77eeac32018-07-09 22:27:23 +00004078 if ((isa<ConstantPointerNull>(Callee) &&
4079 !NullPointerIsDefined(CS.getInstruction()->getFunction())) ||
4080 isa<UndefValue>(Callee)) {
Gabor Greif589a0b92010-06-24 12:58:35 +00004081 // If CS does not return void then replaceAllUsesWith undef.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004082 // This allows ValueHandlers and custom metadata to adjust itself.
4083 if (!CS.getInstruction()->getType()->isVoidTy())
Sanjay Patel4b198802016-02-01 22:23:39 +00004084 replaceInstUsesWith(*CS.getInstruction(),
Eli Friedmanb9ed18f2011-05-18 00:32:01 +00004085 UndefValue::get(CS.getInstruction()->getType()));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004086
Nuno Lopes771e7bd2012-06-21 23:52:14 +00004087 if (isa<InvokeInst>(CS.getInstruction())) {
4088 // Can't remove an invoke because we cannot change the CFG.
Craig Topperf40110f2014-04-25 05:29:35 +00004089 return nullptr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004090 }
Nuno Lopes771e7bd2012-06-21 23:52:14 +00004091
4092 // This instruction is not reachable, just remove it. We insert a store to
4093 // undef so that we know that this code is not reachable, despite the fact
4094 // that we can't modify the CFG here.
4095 new StoreInst(ConstantInt::getTrue(Callee->getContext()),
4096 UndefValue::get(Type::getInt1PtrTy(Callee->getContext())),
4097 CS.getInstruction());
4098
Sanjay Patel4b198802016-02-01 22:23:39 +00004099 return eraseInstFromFunction(*CS.getInstruction());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004100 }
4101
Sanjay Patel6038d3e2016-01-29 23:27:03 +00004102 if (IntrinsicInst *II = findInitTrampoline(Callee))
Duncan Sandsa0984362011-09-06 13:37:06 +00004103 return transformCallThroughTrampoline(CS, II);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004104
Chris Lattner229907c2011-07-18 04:54:35 +00004105 PointerType *PTy = cast<PointerType>(Callee->getType());
4106 FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004107 if (FTy->isVarArg()) {
Eli Friedman7534b4682011-11-29 01:18:23 +00004108 int ix = FTy->getNumParams();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004109 // See if we can optimize any arguments passed through the varargs area of
4110 // the call.
Matt Arsenault5d2e85f2013-06-28 00:25:40 +00004111 for (CallSite::arg_iterator I = CS.arg_begin() + FTy->getNumParams(),
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004112 E = CS.arg_end(); I != E; ++I, ++ix) {
4113 CastInst *CI = dyn_cast<CastInst>(*I);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004114 if (CI && isSafeToEliminateVarargsCast(CS, DL, CI, ix)) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004115 *I = CI->getOperand(0);
4116 Changed = true;
4117 }
4118 }
4119 }
4120
4121 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
4122 // Inline asm calls cannot throw - mark them 'nounwind'.
4123 CS.setDoesNotThrow();
4124 Changed = true;
4125 }
4126
Micah Villmowcdfe20b2012-10-08 16:38:25 +00004127 // Try to optimize the call if possible, we require DataLayout for most of
Eric Christophera7fb58f2010-03-06 10:50:38 +00004128 // this. None of these calls are seen as possibly dead so go ahead and
4129 // delete the instruction now.
4130 if (CallInst *CI = dyn_cast<CallInst>(CS.getInstruction())) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004131 Instruction *I = tryOptimizeCall(CI);
Eric Christopher1810d772010-03-06 10:59:25 +00004132 // If we changed something return the result, etc. Otherwise let
4133 // the fallthrough check.
Sanjay Patel4b198802016-02-01 22:23:39 +00004134 if (I) return eraseInstFromFunction(*I);
Eric Christophera7fb58f2010-03-06 10:50:38 +00004135 }
4136
Craig Topperf40110f2014-04-25 05:29:35 +00004137 return Changed ? CS.getInstruction() : nullptr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004138}
4139
Sanjay Patelcd4377c2016-01-20 22:24:38 +00004140/// If the callee is a constexpr cast of a function, attempt to move the cast to
4141/// the arguments of the call/invoke.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004142bool InstCombiner::transformConstExprCastCall(CallSite CS) {
Sanjay Patele3c335c2016-08-11 15:21:21 +00004143 auto *Callee = dyn_cast<Function>(CS.getCalledValue()->stripPointerCasts());
Craig Topperf40110f2014-04-25 05:29:35 +00004144 if (!Callee)
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004145 return false;
Sanjay Patel38ae83d2016-08-11 15:23:56 +00004146
Reid Kleckner298ffc62018-04-02 22:49:44 +00004147 // If this is a call to a thunk function, don't remove the cast. Thunks are
4148 // used to transparently forward all incoming parameters and outgoing return
4149 // values, so it's important to leave the cast in place.
David Majnemer4c0a6e92015-01-21 22:32:04 +00004150 if (Callee->hasFnAttribute("thunk"))
4151 return false;
Sanjay Patel38ae83d2016-08-11 15:23:56 +00004152
Reid Kleckner298ffc62018-04-02 22:49:44 +00004153 // If this is a musttail call, the callee's prototype must match the caller's
4154 // prototype with the exception of pointee types. The code below doesn't
4155 // implement that, so we can't do this transform.
4156 // TODO: Do the transform if it only requires adding pointer casts.
4157 if (CS.isMustTailCall())
4158 return false;
4159
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004160 Instruction *Caller = CS.getInstruction();
Reid Klecknerb5180542017-03-21 16:57:19 +00004161 const AttributeList &CallerPAL = CS.getAttributes();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004162
4163 // Okay, this is a cast from a function to a different type. Unless doing so
4164 // would cause a type conversion of one of our arguments, change this call to
4165 // be a direct call with arguments casted to the appropriate types.
Chris Lattner229907c2011-07-18 04:54:35 +00004166 FunctionType *FT = Callee->getFunctionType();
4167 Type *OldRetTy = Caller->getType();
4168 Type *NewRetTy = FT->getReturnType();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004169
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004170 // Check to see if we are changing the return type...
4171 if (OldRetTy != NewRetTy) {
Nick Lewyckya6a17d72014-01-18 22:47:12 +00004172
4173 if (NewRetTy->isStructTy())
4174 return false; // TODO: Handle multiple return values.
4175
David Majnemer9b6b8222015-01-06 08:41:31 +00004176 if (!CastInst::isBitOrNoopPointerCastable(NewRetTy, OldRetTy, DL)) {
Matt Arsenaulte6952f22013-09-17 21:10:14 +00004177 if (Callee->isDeclaration())
4178 return false; // Cannot transform this return value.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004179
Matt Arsenaulte6952f22013-09-17 21:10:14 +00004180 if (!Caller->use_empty() &&
4181 // void -> non-void is handled specially
4182 !NewRetTy->isVoidTy())
Frederic Rissc1892e22014-10-23 04:08:42 +00004183 return false; // Cannot transform this return value.
Matt Arsenaulte6952f22013-09-17 21:10:14 +00004184 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004185
4186 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Reid Klecknerb5180542017-03-21 16:57:19 +00004187 AttrBuilder RAttrs(CallerPAL, AttributeList::ReturnIndex);
Pete Cooper2777d8872015-05-06 23:19:56 +00004188 if (RAttrs.overlaps(AttributeFuncs::typeIncompatible(NewRetTy)))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004189 return false; // Attribute not compatible with transformed value.
4190 }
4191
4192 // If the callsite is an invoke instruction, and the return value is used by
4193 // a PHI node in a successor, we cannot change the return type of the call
4194 // because there is no place to put the cast instruction (without breaking
4195 // the critical edge). Bail out in this case.
4196 if (!Caller->use_empty())
4197 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
Chandler Carruthcdf47882014-03-09 03:16:01 +00004198 for (User *U : II->users())
4199 if (PHINode *PN = dyn_cast<PHINode>(U))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004200 if (PN->getParent() == II->getNormalDest() ||
4201 PN->getParent() == II->getUnwindDest())
4202 return false;
4203 }
4204
Matt Arsenault5d2e85f2013-06-28 00:25:40 +00004205 unsigned NumActualArgs = CS.arg_size();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004206 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
4207
David Majnemer9b6b8222015-01-06 08:41:31 +00004208 // Prevent us turning:
4209 // declare void @takes_i32_inalloca(i32* inalloca)
4210 // call void bitcast (void (i32*)* @takes_i32_inalloca to void (i32)*)(i32 0)
4211 //
4212 // into:
4213 // call void @takes_i32_inalloca(i32* null)
David Majnemerd61a6fd2015-03-11 18:03:05 +00004214 //
4215 // Similarly, avoid folding away bitcasts of byval calls.
4216 if (Callee->getAttributes().hasAttrSomewhere(Attribute::InAlloca) ||
4217 Callee->getAttributes().hasAttrSomewhere(Attribute::ByVal))
David Majnemer9b6b8222015-01-06 08:41:31 +00004218 return false;
4219
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004220 CallSite::arg_iterator AI = CS.arg_begin();
4221 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
Chris Lattner229907c2011-07-18 04:54:35 +00004222 Type *ParamTy = FT->getParamType(i);
4223 Type *ActTy = (*AI)->getType();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004224
David Majnemer9b6b8222015-01-06 08:41:31 +00004225 if (!CastInst::isBitOrNoopPointerCastable(ActTy, ParamTy, DL))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004226 return false; // Cannot transform this parameter value.
4227
Reid Klecknerf021fab2017-04-13 23:12:13 +00004228 if (AttrBuilder(CallerPAL.getParamAttributes(i))
4229 .overlaps(AttributeFuncs::typeIncompatible(ParamTy)))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004230 return false; // Attribute not compatible with transformed value.
Jim Grosbach7815f562012-02-03 00:07:04 +00004231
Reid Kleckner26af2ca2014-01-28 02:38:36 +00004232 if (CS.isInAllocaArgument(i))
4233 return false; // Cannot transform to and from inalloca.
4234
Chris Lattner27ca8eb2010-12-20 08:36:38 +00004235 // If the parameter is passed as a byval argument, then we have to have a
4236 // sized type and the sized type has to have the same size as the old type.
Reid Klecknerf021fab2017-04-13 23:12:13 +00004237 if (ParamTy != ActTy && CallerPAL.hasParamAttribute(i, Attribute::ByVal)) {
Chris Lattner229907c2011-07-18 04:54:35 +00004238 PointerType *ParamPTy = dyn_cast<PointerType>(ParamTy);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004239 if (!ParamPTy || !ParamPTy->getElementType()->isSized())
Chris Lattner27ca8eb2010-12-20 08:36:38 +00004240 return false;
Jim Grosbach7815f562012-02-03 00:07:04 +00004241
Matt Arsenaultfa252722013-09-27 22:18:51 +00004242 Type *CurElTy = ActTy->getPointerElementType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004243 if (DL.getTypeAllocSize(CurElTy) !=
4244 DL.getTypeAllocSize(ParamPTy->getElementType()))
Chris Lattner27ca8eb2010-12-20 08:36:38 +00004245 return false;
4246 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004247 }
4248
Chris Lattneradf38b32011-02-24 05:10:56 +00004249 if (Callee->isDeclaration()) {
4250 // Do not delete arguments unless we have a function body.
4251 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg())
4252 return false;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004253
Chris Lattneradf38b32011-02-24 05:10:56 +00004254 // If the callee is just a declaration, don't change the varargsness of the
4255 // call. We don't want to introduce a varargs call where one doesn't
4256 // already exist.
Chris Lattner229907c2011-07-18 04:54:35 +00004257 PointerType *APTy = cast<PointerType>(CS.getCalledValue()->getType());
Chris Lattneradf38b32011-02-24 05:10:56 +00004258 if (FT->isVarArg()!=cast<FunctionType>(APTy->getElementType())->isVarArg())
4259 return false;
Jim Grosbache84ae7b2012-02-03 00:00:55 +00004260
4261 // If both the callee and the cast type are varargs, we still have to make
4262 // sure the number of fixed parameters are the same or we have the same
4263 // ABI issues as if we introduce a varargs call.
Jim Grosbach1df8cdc2012-02-03 00:26:07 +00004264 if (FT->isVarArg() &&
4265 cast<FunctionType>(APTy->getElementType())->isVarArg() &&
4266 FT->getNumParams() !=
Jim Grosbache84ae7b2012-02-03 00:00:55 +00004267 cast<FunctionType>(APTy->getElementType())->getNumParams())
4268 return false;
Chris Lattneradf38b32011-02-24 05:10:56 +00004269 }
Jim Grosbach7815f562012-02-03 00:07:04 +00004270
Jim Grosbach0ab54182012-02-03 00:00:50 +00004271 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
Reid Kleckneraa0cec72017-04-19 23:17:47 +00004272 !CallerPAL.isEmpty()) {
Jim Grosbach0ab54182012-02-03 00:00:50 +00004273 // In this case we have more arguments than the new function type, but we
4274 // won't be dropping them. Check that these extra arguments have attributes
4275 // that are compatible with being a vararg call argument.
Reid Kleckneraa0cec72017-04-19 23:17:47 +00004276 unsigned SRetIdx;
4277 if (CallerPAL.hasAttrSomewhere(Attribute::StructRet, &SRetIdx) &&
4278 SRetIdx > FT->getNumParams())
4279 return false;
4280 }
Jim Grosbach7815f562012-02-03 00:07:04 +00004281
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004282 // Okay, we decided that this is a safe thing to do: go ahead and start
Chris Lattneradf38b32011-02-24 05:10:56 +00004283 // inserting cast instructions as necessary.
Reid Klecknerc3fae792017-04-13 18:11:03 +00004284 SmallVector<Value *, 8> Args;
4285 SmallVector<AttributeSet, 8> ArgAttrs;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004286 Args.reserve(NumActualArgs);
Reid Klecknerc3fae792017-04-13 18:11:03 +00004287 ArgAttrs.reserve(NumActualArgs);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004288
4289 // Get any return attributes.
Reid Klecknerb5180542017-03-21 16:57:19 +00004290 AttrBuilder RAttrs(CallerPAL, AttributeList::ReturnIndex);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004291
4292 // If the return value is not being used, the type may not be compatible
4293 // with the existing attributes. Wipe out any problematic attributes.
Pete Cooper2777d8872015-05-06 23:19:56 +00004294 RAttrs.remove(AttributeFuncs::typeIncompatible(NewRetTy));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004295
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004296 AI = CS.arg_begin();
4297 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
Chris Lattner229907c2011-07-18 04:54:35 +00004298 Type *ParamTy = FT->getParamType(i);
Matt Arsenaultcacbb232013-07-30 20:45:05 +00004299
Reid Klecknerc3fae792017-04-13 18:11:03 +00004300 Value *NewArg = *AI;
4301 if ((*AI)->getType() != ParamTy)
Craig Topperbb4069e2017-07-07 23:16:26 +00004302 NewArg = Builder.CreateBitOrPointerCast(*AI, ParamTy);
Reid Klecknerc3fae792017-04-13 18:11:03 +00004303 Args.push_back(NewArg);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004304
4305 // Add any parameter attributes.
Reid Klecknerf021fab2017-04-13 23:12:13 +00004306 ArgAttrs.push_back(CallerPAL.getParamAttributes(i));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004307 }
4308
4309 // If the function takes more arguments than the call was taking, add them
4310 // now.
Reid Klecknerc3fae792017-04-13 18:11:03 +00004311 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004312 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
Reid Klecknerc3fae792017-04-13 18:11:03 +00004313 ArgAttrs.push_back(AttributeSet());
4314 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004315
4316 // If we are removing arguments to the function, emit an obnoxious warning.
4317 if (FT->getNumParams() < NumActualArgs) {
Nick Lewycky90053a12012-12-26 22:00:35 +00004318 // TODO: if (!FT->isVarArg()) this call may be unreachable. PR14722
4319 if (FT->isVarArg()) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004320 // Add all of the arguments in their promoted form to the arg list.
4321 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
Chris Lattner229907c2011-07-18 04:54:35 +00004322 Type *PTy = getPromotedType((*AI)->getType());
Reid Klecknerc3fae792017-04-13 18:11:03 +00004323 Value *NewArg = *AI;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004324 if (PTy != (*AI)->getType()) {
4325 // Must promote to pass through va_arg area!
4326 Instruction::CastOps opcode =
4327 CastInst::getCastOpcode(*AI, false, PTy, false);
Craig Topperbb4069e2017-07-07 23:16:26 +00004328 NewArg = Builder.CreateCast(opcode, *AI, PTy);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004329 }
Reid Klecknerc3fae792017-04-13 18:11:03 +00004330 Args.push_back(NewArg);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004331
4332 // Add any parameter attributes.
Reid Klecknerf021fab2017-04-13 23:12:13 +00004333 ArgAttrs.push_back(CallerPAL.getParamAttributes(i));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004334 }
4335 }
4336 }
4337
Reid Klecknerc2cb5602017-04-12 00:38:00 +00004338 AttributeSet FnAttrs = CallerPAL.getFnAttributes();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004339
4340 if (NewRetTy->isVoidTy())
4341 Caller->setName(""); // Void type should not have a name.
4342
Reid Klecknerc3fae792017-04-13 18:11:03 +00004343 assert((ArgAttrs.size() == FT->getNumParams() || FT->isVarArg()) &&
4344 "missing argument attributes");
4345 LLVMContext &Ctx = Callee->getContext();
4346 AttributeList NewCallerPAL = AttributeList::get(
4347 Ctx, FnAttrs, AttributeSet::get(Ctx, RAttrs), ArgAttrs);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004348
Sanjoy Das76293462015-11-25 00:42:19 +00004349 SmallVector<OperandBundleDef, 1> OpBundles;
Sanjoy Dasc521c7b2015-11-25 00:42:24 +00004350 CS.getOperandBundlesAsDefs(OpBundles);
Sanjoy Das76293462015-11-25 00:42:19 +00004351
Reid Kleckner257cb4e2017-04-13 20:26:38 +00004352 CallSite NewCS;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004353 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Craig Topperbb4069e2017-07-07 23:16:26 +00004354 NewCS = Builder.CreateInvoke(Callee, II->getNormalDest(),
4355 II->getUnwindDest(), Args, OpBundles);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004356 } else {
Craig Topperbb4069e2017-07-07 23:16:26 +00004357 NewCS = Builder.CreateCall(Callee, Args, OpBundles);
Reid Kleckner257cb4e2017-04-13 20:26:38 +00004358 cast<CallInst>(NewCS.getInstruction())
4359 ->setTailCallKind(cast<CallInst>(Caller)->getTailCallKind());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004360 }
Reid Kleckner257cb4e2017-04-13 20:26:38 +00004361 NewCS->takeName(Caller);
4362 NewCS.setCallingConv(CS.getCallingConv());
4363 NewCS.setAttributes(NewCallerPAL);
4364
4365 // Preserve the weight metadata for the new call instruction. The metadata
4366 // is used by SamplePGO to check callsite's hotness.
4367 uint64_t W;
4368 if (Caller->extractProfTotalWeight(W))
4369 NewCS->setProfWeight(W);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004370
4371 // Insert a cast of the return type as necessary.
Reid Kleckner257cb4e2017-04-13 20:26:38 +00004372 Instruction *NC = NewCS.getInstruction();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004373 Value *NV = NC;
4374 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
4375 if (!NV->getType()->isVoidTy()) {
David Majnemer9b6b8222015-01-06 08:41:31 +00004376 NV = NC = CastInst::CreateBitOrPointerCast(NC, OldRetTy);
Eli Friedman35211c62011-05-27 00:19:40 +00004377 NC->setDebugLoc(Caller->getDebugLoc());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004378
4379 // If this is an invoke instruction, we should insert it after the first
4380 // non-phi, instruction in the normal successor block.
4381 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Bill Wendling07efd6f2011-08-25 01:08:34 +00004382 BasicBlock::iterator I = II->getNormalDest()->getFirstInsertionPt();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004383 InsertNewInstBefore(NC, *I);
4384 } else {
Chris Lattner73989652010-12-20 08:25:06 +00004385 // Otherwise, it's a call, just insert cast right after the call.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004386 InsertNewInstBefore(NC, *Caller);
4387 }
4388 Worklist.AddUsersToWorkList(*Caller);
4389 } else {
4390 NV = UndefValue::get(Caller->getType());
4391 }
4392 }
4393
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004394 if (!Caller->use_empty())
Sanjay Patel4b198802016-02-01 22:23:39 +00004395 replaceInstUsesWith(*Caller, NV);
Frederic Rissc1892e22014-10-23 04:08:42 +00004396 else if (Caller->hasValueHandle()) {
4397 if (OldRetTy == NV->getType())
4398 ValueHandleBase::ValueIsRAUWd(Caller, NV);
4399 else
4400 // We cannot call ValueIsRAUWd with a different type, and the
4401 // actual tracked value will disappear.
4402 ValueHandleBase::ValueIsDeleted(Caller);
4403 }
Eli Friedmanb9ed18f2011-05-18 00:32:01 +00004404
Sanjay Patel4b198802016-02-01 22:23:39 +00004405 eraseInstFromFunction(*Caller);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004406 return true;
4407}
4408
Sanjay Patelcd4377c2016-01-20 22:24:38 +00004409/// Turn a call to a function created by init_trampoline / adjust_trampoline
4410/// intrinsic pair into a direct call to the underlying function.
Duncan Sandsa0984362011-09-06 13:37:06 +00004411Instruction *
4412InstCombiner::transformCallThroughTrampoline(CallSite CS,
4413 IntrinsicInst *Tramp) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004414 Value *Callee = CS.getCalledValue();
Chris Lattner229907c2011-07-18 04:54:35 +00004415 PointerType *PTy = cast<PointerType>(Callee->getType());
4416 FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00004417 AttributeList Attrs = CS.getAttributes();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004418
4419 // If the call already has the 'nest' attribute somewhere then give up -
4420 // otherwise 'nest' would occur twice after splicing in the chain.
Bill Wendling6e95ae82012-12-31 00:49:59 +00004421 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Craig Topperf40110f2014-04-25 05:29:35 +00004422 return nullptr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004423
Duncan Sandsa0984362011-09-06 13:37:06 +00004424 assert(Tramp &&
4425 "transformCallThroughTrampoline called with incorrect CallSite.");
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004426
Gabor Greif3e44ea12010-07-22 10:37:47 +00004427 Function *NestF =cast<Function>(Tramp->getArgOperand(1)->stripPointerCasts());
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00004428 FunctionType *NestFTy = cast<FunctionType>(NestF->getValueType());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004429
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00004430 AttributeList NestAttrs = NestF->getAttributes();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004431 if (!NestAttrs.isEmpty()) {
Reid Klecknerf021fab2017-04-13 23:12:13 +00004432 unsigned NestArgNo = 0;
Craig Topperf40110f2014-04-25 05:29:35 +00004433 Type *NestTy = nullptr;
Reid Klecknerc2cb5602017-04-12 00:38:00 +00004434 AttributeSet NestAttr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004435
4436 // Look for a parameter marked with the 'nest' attribute.
4437 for (FunctionType::param_iterator I = NestFTy->param_begin(),
Reid Klecknerf021fab2017-04-13 23:12:13 +00004438 E = NestFTy->param_end();
4439 I != E; ++NestArgNo, ++I) {
4440 AttributeSet AS = NestAttrs.getParamAttributes(NestArgNo);
4441 if (AS.hasAttribute(Attribute::Nest)) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004442 // Record the parameter type and any other attributes.
4443 NestTy = *I;
Reid Klecknerf021fab2017-04-13 23:12:13 +00004444 NestAttr = AS;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004445 break;
4446 }
Reid Klecknerf021fab2017-04-13 23:12:13 +00004447 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004448
4449 if (NestTy) {
4450 Instruction *Caller = CS.getInstruction();
4451 std::vector<Value*> NewArgs;
Reid Kleckner7f720332017-04-13 00:58:09 +00004452 std::vector<AttributeSet> NewArgAttrs;
Matt Arsenault5d2e85f2013-06-28 00:25:40 +00004453 NewArgs.reserve(CS.arg_size() + 1);
Reid Kleckner7f720332017-04-13 00:58:09 +00004454 NewArgAttrs.reserve(CS.arg_size());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004455
4456 // Insert the nest argument into the call argument list, which may
4457 // mean appending it. Likewise for attributes.
4458
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004459 {
Reid Klecknerf021fab2017-04-13 23:12:13 +00004460 unsigned ArgNo = 0;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004461 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
4462 do {
Reid Klecknerf021fab2017-04-13 23:12:13 +00004463 if (ArgNo == NestArgNo) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004464 // Add the chain argument and attributes.
Gabor Greif589a0b92010-06-24 12:58:35 +00004465 Value *NestVal = Tramp->getArgOperand(2);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004466 if (NestVal->getType() != NestTy)
Craig Topperbb4069e2017-07-07 23:16:26 +00004467 NestVal = Builder.CreateBitCast(NestVal, NestTy, "nest");
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004468 NewArgs.push_back(NestVal);
Reid Kleckner7f720332017-04-13 00:58:09 +00004469 NewArgAttrs.push_back(NestAttr);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004470 }
4471
4472 if (I == E)
4473 break;
4474
4475 // Add the original argument and attributes.
4476 NewArgs.push_back(*I);
Reid Klecknerf021fab2017-04-13 23:12:13 +00004477 NewArgAttrs.push_back(Attrs.getParamAttributes(ArgNo));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004478
Reid Klecknerf021fab2017-04-13 23:12:13 +00004479 ++ArgNo;
Richard Trieu7a083812016-02-18 22:09:30 +00004480 ++I;
Eugene Zelenkocdc71612016-08-11 17:20:18 +00004481 } while (true);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004482 }
4483
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004484 // The trampoline may have been bitcast to a bogus type (FTy).
4485 // Handle this by synthesizing a new function type, equal to FTy
4486 // with the chain parameter inserted.
4487
Jay Foadb804a2b2011-07-12 14:06:48 +00004488 std::vector<Type*> NewTypes;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004489 NewTypes.reserve(FTy->getNumParams()+1);
4490
4491 // Insert the chain's type into the list of parameter types, which may
4492 // mean appending it.
4493 {
Reid Klecknerf021fab2017-04-13 23:12:13 +00004494 unsigned ArgNo = 0;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004495 FunctionType::param_iterator I = FTy->param_begin(),
4496 E = FTy->param_end();
4497
4498 do {
Reid Klecknerf021fab2017-04-13 23:12:13 +00004499 if (ArgNo == NestArgNo)
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004500 // Add the chain's type.
4501 NewTypes.push_back(NestTy);
4502
4503 if (I == E)
4504 break;
4505
4506 // Add the original type.
4507 NewTypes.push_back(*I);
4508
Reid Klecknerf021fab2017-04-13 23:12:13 +00004509 ++ArgNo;
Richard Trieu7a083812016-02-18 22:09:30 +00004510 ++I;
Eugene Zelenkocdc71612016-08-11 17:20:18 +00004511 } while (true);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004512 }
4513
4514 // Replace the trampoline call with a direct call. Let the generic
4515 // code sort out any function type mismatches.
Jim Grosbach7815f562012-02-03 00:07:04 +00004516 FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004517 FTy->isVarArg());
4518 Constant *NewCallee =
4519 NestF->getType() == PointerType::getUnqual(NewFTy) ?
Jim Grosbach7815f562012-02-03 00:07:04 +00004520 NestF : ConstantExpr::getBitCast(NestF,
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004521 PointerType::getUnqual(NewFTy));
Reid Kleckner7f720332017-04-13 00:58:09 +00004522 AttributeList NewPAL =
4523 AttributeList::get(FTy->getContext(), Attrs.getFnAttributes(),
4524 Attrs.getRetAttributes(), NewArgAttrs);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004525
David Majnemer231a68c2016-04-29 08:07:20 +00004526 SmallVector<OperandBundleDef, 1> OpBundles;
4527 CS.getOperandBundlesAsDefs(OpBundles);
4528
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004529 Instruction *NewCaller;
4530 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
4531 NewCaller = InvokeInst::Create(NewCallee,
4532 II->getNormalDest(), II->getUnwindDest(),
David Majnemer231a68c2016-04-29 08:07:20 +00004533 NewArgs, OpBundles);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004534 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
4535 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
4536 } else {
David Majnemer231a68c2016-04-29 08:07:20 +00004537 NewCaller = CallInst::Create(NewCallee, NewArgs, OpBundles);
David Majnemerd5648c72016-11-25 22:35:09 +00004538 cast<CallInst>(NewCaller)->setTailCallKind(
4539 cast<CallInst>(Caller)->getTailCallKind());
4540 cast<CallInst>(NewCaller)->setCallingConv(
4541 cast<CallInst>(Caller)->getCallingConv());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004542 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
4543 }
Florian Hahn012c8f92017-12-20 17:16:59 +00004544 NewCaller->setDebugLoc(Caller->getDebugLoc());
Eli Friedman49346012011-05-18 19:57:14 +00004545
4546 return NewCaller;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004547 }
4548 }
4549
4550 // Replace the trampoline call with a direct call. Since there is no 'nest'
4551 // parameter, there is no need to adjust the argument list. Let the generic
4552 // code sort out any function type mismatches.
4553 Constant *NewCallee =
Jim Grosbach7815f562012-02-03 00:07:04 +00004554 NestF->getType() == PTy ? NestF :
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004555 ConstantExpr::getBitCast(NestF, PTy);
4556 CS.setCalledFunction(NewCallee);
4557 return CS.getInstruction();
4558}