blob: 2cc2e824cfbd4747e58e43e3a3e734b13672579b [file] [log] [blame]
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001//===- InstCombineCalls.cpp -----------------------------------------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Chris Lattner7a9e47a2010-01-05 07:32:13 +00006//
7//===----------------------------------------------------------------------===//
8//
Craig Topper784929d2019-02-08 20:48:56 +00009// This file implements the visitCall, visitInvoke, and visitCallBr functions.
Chris Lattner7a9e47a2010-01-05 07:32:13 +000010//
11//===----------------------------------------------------------------------===//
12
Chandler Carrutha9174582015-01-22 05:25:13 +000013#include "InstCombineInternal.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000014#include "llvm/ADT/APFloat.h"
15#include "llvm/ADT/APInt.h"
16#include "llvm/ADT/ArrayRef.h"
17#include "llvm/ADT/None.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000018#include "llvm/ADT/Optional.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000019#include "llvm/ADT/STLExtras.h"
20#include "llvm/ADT/SmallVector.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000021#include "llvm/ADT/Statistic.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000022#include "llvm/ADT/Twine.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000023#include "llvm/Analysis/AssumptionCache.h"
David Majnemer15032582015-05-22 03:56:46 +000024#include "llvm/Analysis/InstructionSimplify.h"
Chris Lattner7a9e47a2010-01-05 07:32:13 +000025#include "llvm/Analysis/MemoryBuiltins.h"
David Blaikie31b98d22018-06-04 21:23:21 +000026#include "llvm/Transforms/Utils/Local.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000027#include "llvm/Analysis/ValueTracking.h"
Philip Reamese4588bb2019-03-20 18:44:58 +000028#include "llvm/Analysis/VectorUtils.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"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000031#include "llvm/IR/Constant.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000032#include "llvm/IR/Constants.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000033#include "llvm/IR/DataLayout.h"
34#include "llvm/IR/DerivedTypes.h"
35#include "llvm/IR/Function.h"
36#include "llvm/IR/GlobalVariable.h"
37#include "llvm/IR/InstrTypes.h"
38#include "llvm/IR/Instruction.h"
39#include "llvm/IR/Instructions.h"
40#include "llvm/IR/IntrinsicInst.h"
41#include "llvm/IR/Intrinsics.h"
42#include "llvm/IR/LLVMContext.h"
43#include "llvm/IR/Metadata.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000044#include "llvm/IR/PatternMatch.h"
Philip Reames1a1bdb22014-12-02 18:50:36 +000045#include "llvm/IR/Statepoint.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000046#include "llvm/IR/Type.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000047#include "llvm/IR/User.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000048#include "llvm/IR/Value.h"
49#include "llvm/IR/ValueHandle.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000050#include "llvm/Support/AtomicOrdering.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000051#include "llvm/Support/Casting.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000052#include "llvm/Support/CommandLine.h"
53#include "llvm/Support/Compiler.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000054#include "llvm/Support/Debug.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000055#include "llvm/Support/ErrorHandling.h"
Craig Topperb45eabc2017-04-26 16:39:58 +000056#include "llvm/Support/KnownBits.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000057#include "llvm/Support/MathExtras.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000058#include "llvm/Support/raw_ostream.h"
59#include "llvm/Transforms/InstCombine/InstCombineWorklist.h"
Chandler Carruthba4c5172015-01-21 11:23:40 +000060#include "llvm/Transforms/Utils/SimplifyLibCalls.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000061#include <algorithm>
62#include <cassert>
63#include <cstdint>
64#include <cstring>
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000065#include <utility>
Eugene Zelenkocdc71612016-08-11 17:20:18 +000066#include <vector>
67
Chris Lattner7a9e47a2010-01-05 07:32:13 +000068using namespace llvm;
Michael Ilseman536cc322012-12-13 03:13:36 +000069using namespace PatternMatch;
Chris Lattner7a9e47a2010-01-05 07:32:13 +000070
Chandler Carruth964daaa2014-04-22 02:55:47 +000071#define DEBUG_TYPE "instcombine"
72
Meador Ingee3f2b262012-11-30 04:05:06 +000073STATISTIC(NumSimplified, "Number of library calls simplified");
74
Philip Reames79e917d2018-05-09 22:56:32 +000075static cl::opt<unsigned> GuardWideningWindow(
76 "instcombine-guard-widening-window",
77 cl::init(3),
78 cl::desc("How wide an instruction window to bypass looking for "
79 "another guard"));
80
Sanjay Patelcd4377c2016-01-20 22:24:38 +000081/// Return the specified type promoted as it would be to pass though a va_arg
82/// area.
Chris Lattner229907c2011-07-18 04:54:35 +000083static Type *getPromotedType(Type *Ty) {
84 if (IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +000085 if (ITy->getBitWidth() < 32)
86 return Type::getInt32Ty(Ty->getContext());
87 }
88 return Ty;
89}
90
Sanjay Patel368ac5d2016-02-21 17:29:33 +000091/// Return a constant boolean vector that has true elements in all positions
Sanjay Patel24401302016-02-21 17:33:31 +000092/// where the input constant data vector has an element with the sign bit set.
Sanjay Patel368ac5d2016-02-21 17:29:33 +000093static Constant *getNegativeIsTrueBoolVec(ConstantDataVector *V) {
94 SmallVector<Constant *, 32> BoolVec;
95 IntegerType *BoolTy = Type::getInt1Ty(V->getContext());
96 for (unsigned I = 0, E = V->getNumElements(); I != E; ++I) {
97 Constant *Elt = V->getElementAsConstant(I);
98 assert((isa<ConstantInt>(Elt) || isa<ConstantFP>(Elt)) &&
99 "Unexpected constant data vector element type");
100 bool Sign = V->getElementType()->isIntegerTy()
101 ? cast<ConstantInt>(Elt)->isNegative()
102 : cast<ConstantFP>(Elt)->isNegative();
103 BoolVec.push_back(ConstantInt::get(BoolTy, Sign));
104 }
105 return ConstantVector::get(BoolVec);
106}
107
Daniel Neilson8f30ec62018-05-11 14:30:02 +0000108Instruction *InstCombiner::SimplifyAnyMemTransfer(AnyMemTransferInst *MI) {
Daniel Neilson2363da92018-02-12 23:06:55 +0000109 unsigned DstAlign = getKnownAlignment(MI->getRawDest(), DL, MI, &AC, &DT);
110 unsigned CopyDstAlign = MI->getDestAlignment();
111 if (CopyDstAlign < DstAlign){
112 MI->setDestAlignment(DstAlign);
113 return MI;
114 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000115
Daniel Neilson8f30ec62018-05-11 14:30:02 +0000116 unsigned SrcAlign = getKnownAlignment(MI->getRawSource(), DL, MI, &AC, &DT);
117 unsigned CopySrcAlign = MI->getSourceAlignment();
Daniel Neilson2363da92018-02-12 23:06:55 +0000118 if (CopySrcAlign < SrcAlign) {
Daniel Neilson8f30ec62018-05-11 14:30:02 +0000119 MI->setSourceAlignment(SrcAlign);
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000120 return MI;
121 }
Jim Grosbach7815f562012-02-03 00:07:04 +0000122
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000123 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
124 // load/store.
Daniel Neilson8f30ec62018-05-11 14:30:02 +0000125 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getLength());
Craig Topperf40110f2014-04-25 05:29:35 +0000126 if (!MemOpLength) return nullptr;
Jim Grosbach7815f562012-02-03 00:07:04 +0000127
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000128 // Source and destination pointer types are always "i8*" for intrinsic. See
129 // if the size is something we can handle with a single primitive load/store.
130 // A single load+store correctly handles overlapping memory in the memmove
131 // case.
Michael Liao69e172a2012-08-15 03:49:59 +0000132 uint64_t Size = MemOpLength->getLimitedValue();
Alp Tokercb402912014-01-24 17:20:08 +0000133 assert(Size && "0-sized memory transferring should be removed already.");
Jim Grosbach7815f562012-02-03 00:07:04 +0000134
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000135 if (Size > 8 || (Size&(Size-1)))
Craig Topperf40110f2014-04-25 05:29:35 +0000136 return nullptr; // If not 1/2/4/8 bytes, exit.
Jim Grosbach7815f562012-02-03 00:07:04 +0000137
Serguei Katkova5b0e552019-01-16 04:36:26 +0000138 // If it is an atomic and alignment is less than the size then we will
139 // introduce the unaligned memory access which will be later transformed
140 // into libcall in CodeGen. This is not evident performance gain so disable
141 // it now.
142 if (isa<AtomicMemTransferInst>(MI))
143 if (CopyDstAlign < Size || CopySrcAlign < Size)
144 return nullptr;
145
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000146 // Use an integer load+store unless we can find something better.
Mon P Wangc576ee92010-04-04 03:10:48 +0000147 unsigned SrcAddrSp =
Gabor Greif0a136c92010-06-24 13:54:33 +0000148 cast<PointerType>(MI->getArgOperand(1)->getType())->getAddressSpace();
Gabor Greiff3755202010-04-16 15:33:14 +0000149 unsigned DstAddrSp =
Gabor Greif0a136c92010-06-24 13:54:33 +0000150 cast<PointerType>(MI->getArgOperand(0)->getType())->getAddressSpace();
Mon P Wangc576ee92010-04-04 03:10:48 +0000151
Chris Lattner229907c2011-07-18 04:54:35 +0000152 IntegerType* IntType = IntegerType::get(MI->getContext(), Size<<3);
Mon P Wangc576ee92010-04-04 03:10:48 +0000153 Type *NewSrcPtrTy = PointerType::get(IntType, SrcAddrSp);
154 Type *NewDstPtrTy = PointerType::get(IntType, DstAddrSp);
Jim Grosbach7815f562012-02-03 00:07:04 +0000155
Mikael Holmen760dc9a2017-03-01 06:45:20 +0000156 // If the memcpy has metadata describing the members, see if we can get the
157 // TBAA tag describing our copy.
Craig Topperf40110f2014-04-25 05:29:35 +0000158 MDNode *CopyMD = nullptr;
Ivan A. Kosarevf03f5792018-02-19 12:10:20 +0000159 if (MDNode *M = MI->getMetadata(LLVMContext::MD_tbaa)) {
160 CopyMD = M;
161 } else if (MDNode *M = MI->getMetadata(LLVMContext::MD_tbaa_struct)) {
Mikael Holmen760dc9a2017-03-01 06:45:20 +0000162 if (M->getNumOperands() == 3 && M->getOperand(0) &&
163 mdconst::hasa<ConstantInt>(M->getOperand(0)) &&
Craig Topper79ab6432017-07-06 18:39:47 +0000164 mdconst::extract<ConstantInt>(M->getOperand(0))->isZero() &&
Mikael Holmen760dc9a2017-03-01 06:45:20 +0000165 M->getOperand(1) &&
166 mdconst::hasa<ConstantInt>(M->getOperand(1)) &&
167 mdconst::extract<ConstantInt>(M->getOperand(1))->getValue() ==
168 Size &&
169 M->getOperand(2) && isa<MDNode>(M->getOperand(2)))
170 CopyMD = cast<MDNode>(M->getOperand(2));
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000171 }
Jim Grosbach7815f562012-02-03 00:07:04 +0000172
Craig Topperbb4069e2017-07-07 23:16:26 +0000173 Value *Src = Builder.CreateBitCast(MI->getArgOperand(1), NewSrcPtrTy);
174 Value *Dest = Builder.CreateBitCast(MI->getArgOperand(0), NewDstPtrTy);
James Y Knight14359ef2019-02-01 20:44:24 +0000175 LoadInst *L = Builder.CreateLoad(IntType, Src);
Daniel Neilson2363da92018-02-12 23:06:55 +0000176 // Alignment from the mem intrinsic will be better, so use it.
177 L->setAlignment(CopySrcAlign);
Dan Gohman3f553c22012-09-13 21:51:01 +0000178 if (CopyMD)
179 L->setMetadata(LLVMContext::MD_tbaa, CopyMD);
Dorit Nuzmanabd15f62016-09-04 07:49:39 +0000180 MDNode *LoopMemParallelMD =
181 MI->getMetadata(LLVMContext::MD_mem_parallel_loop_access);
182 if (LoopMemParallelMD)
183 L->setMetadata(LLVMContext::MD_mem_parallel_loop_access, LoopMemParallelMD);
Michael Kruse978ba612018-12-20 04:58:07 +0000184 MDNode *AccessGroupMD = MI->getMetadata(LLVMContext::MD_access_group);
185 if (AccessGroupMD)
186 L->setMetadata(LLVMContext::MD_access_group, AccessGroupMD);
Dorit Nuzman7673ba72016-09-04 07:06:00 +0000187
Daniel Neilson8f30ec62018-05-11 14:30:02 +0000188 StoreInst *S = Builder.CreateStore(L, Dest);
Daniel Neilson2363da92018-02-12 23:06:55 +0000189 // Alignment from the mem intrinsic will be better, so use it.
190 S->setAlignment(CopyDstAlign);
Dan Gohman3f553c22012-09-13 21:51:01 +0000191 if (CopyMD)
192 S->setMetadata(LLVMContext::MD_tbaa, CopyMD);
Dorit Nuzmanabd15f62016-09-04 07:49:39 +0000193 if (LoopMemParallelMD)
194 S->setMetadata(LLVMContext::MD_mem_parallel_loop_access, LoopMemParallelMD);
Michael Kruse978ba612018-12-20 04:58:07 +0000195 if (AccessGroupMD)
196 S->setMetadata(LLVMContext::MD_access_group, AccessGroupMD);
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000197
Daniel Neilson8f30ec62018-05-11 14:30:02 +0000198 if (auto *MT = dyn_cast<MemTransferInst>(MI)) {
199 // non-atomics can be volatile
200 L->setVolatile(MT->isVolatile());
201 S->setVolatile(MT->isVolatile());
202 }
203 if (isa<AtomicMemTransferInst>(MI)) {
204 // atomics have to be unordered
205 L->setOrdering(AtomicOrdering::Unordered);
206 S->setOrdering(AtomicOrdering::Unordered);
207 }
208
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000209 // Set the size of the copy to 0, it will be deleted on the next iteration.
Daniel Neilson8f30ec62018-05-11 14:30:02 +0000210 MI->setLength(Constant::getNullValue(MemOpLength->getType()));
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000211 return MI;
212}
213
Daniel Neilsonf6651d42018-05-11 20:04:50 +0000214Instruction *InstCombiner::SimplifyAnyMemSet(AnyMemSetInst *MI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000215 unsigned Alignment = getKnownAlignment(MI->getDest(), DL, MI, &AC, &DT);
Daniel Neilson38af2ee2018-02-02 22:03:03 +0000216 if (MI->getDestAlignment() < Alignment) {
217 MI->setDestAlignment(Alignment);
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000218 return MI;
219 }
Jim Grosbach7815f562012-02-03 00:07:04 +0000220
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000221 // Extract the length and alignment and fill if they are constant.
222 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
223 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
Duncan Sands9dff9be2010-02-15 16:12:20 +0000224 if (!LenC || !FillC || !FillC->getType()->isIntegerTy(8))
Craig Topperf40110f2014-04-25 05:29:35 +0000225 return nullptr;
Michael Liao69e172a2012-08-15 03:49:59 +0000226 uint64_t Len = LenC->getLimitedValue();
Daniel Neilson710d7b92018-03-22 18:36:15 +0000227 Alignment = MI->getDestAlignment();
Michael Liao69e172a2012-08-15 03:49:59 +0000228 assert(Len && "0-sized memory setting should be removed already.");
Jim Grosbach7815f562012-02-03 00:07:04 +0000229
Serguei Katkova5b0e552019-01-16 04:36:26 +0000230 // Alignment 0 is identity for alignment 1 for memset, but not store.
231 if (Alignment == 0)
232 Alignment = 1;
233
234 // If it is an atomic and alignment is less than the size then we will
235 // introduce the unaligned memory access which will be later transformed
236 // into libcall in CodeGen. This is not evident performance gain so disable
237 // it now.
238 if (isa<AtomicMemSetInst>(MI))
239 if (Alignment < Len)
240 return nullptr;
241
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000242 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
243 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
Chris Lattner229907c2011-07-18 04:54:35 +0000244 Type *ITy = IntegerType::get(MI->getContext(), Len*8); // n=1 -> i8.
Jim Grosbach7815f562012-02-03 00:07:04 +0000245
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000246 Value *Dest = MI->getDest();
Mon P Wang1991c472010-12-20 01:05:30 +0000247 unsigned DstAddrSp = cast<PointerType>(Dest->getType())->getAddressSpace();
248 Type *NewDstPtrTy = PointerType::get(ITy, DstAddrSp);
Craig Topperbb4069e2017-07-07 23:16:26 +0000249 Dest = Builder.CreateBitCast(Dest, NewDstPtrTy);
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000250
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000251 // Extract the fill value and store.
252 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
Craig Topperbb4069e2017-07-07 23:16:26 +0000253 StoreInst *S = Builder.CreateStore(ConstantInt::get(ITy, Fill), Dest,
254 MI->isVolatile());
Eli Friedman49346012011-05-18 19:57:14 +0000255 S->setAlignment(Alignment);
Daniel Neilsonf6651d42018-05-11 20:04:50 +0000256 if (isa<AtomicMemSetInst>(MI))
257 S->setOrdering(AtomicOrdering::Unordered);
Jim Grosbach7815f562012-02-03 00:07:04 +0000258
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000259 // Set the size of the copy to 0, it will be deleted on the next iteration.
260 MI->setLength(Constant::getNullValue(LenC->getType()));
261 return MI;
262 }
263
Simon Pilgrim18617d12015-08-05 08:18:00 +0000264 return nullptr;
265}
266
Sanjay Patel6038d3e2016-01-29 23:27:03 +0000267static Value *simplifyX86immShift(const IntrinsicInst &II,
Simon Pilgrimbecd5e82015-08-13 07:39:03 +0000268 InstCombiner::BuilderTy &Builder) {
269 bool LogicalShift = false;
270 bool ShiftLeft = false;
271
272 switch (II.getIntrinsicID()) {
Craig Topperb4173a52016-11-13 07:26:19 +0000273 default: llvm_unreachable("Unexpected intrinsic!");
Simon Pilgrimbecd5e82015-08-13 07:39:03 +0000274 case Intrinsic::x86_sse2_psra_d:
275 case Intrinsic::x86_sse2_psra_w:
276 case Intrinsic::x86_sse2_psrai_d:
277 case Intrinsic::x86_sse2_psrai_w:
278 case Intrinsic::x86_avx2_psra_d:
279 case Intrinsic::x86_avx2_psra_w:
280 case Intrinsic::x86_avx2_psrai_d:
281 case Intrinsic::x86_avx2_psrai_w:
Craig Topper8b831cb2016-11-13 01:51:55 +0000282 case Intrinsic::x86_avx512_psra_q_128:
283 case Intrinsic::x86_avx512_psrai_q_128:
284 case Intrinsic::x86_avx512_psra_q_256:
285 case Intrinsic::x86_avx512_psrai_q_256:
286 case Intrinsic::x86_avx512_psra_d_512:
287 case Intrinsic::x86_avx512_psra_q_512:
288 case Intrinsic::x86_avx512_psra_w_512:
289 case Intrinsic::x86_avx512_psrai_d_512:
290 case Intrinsic::x86_avx512_psrai_q_512:
291 case Intrinsic::x86_avx512_psrai_w_512:
Simon Pilgrimbecd5e82015-08-13 07:39:03 +0000292 LogicalShift = false; ShiftLeft = false;
293 break;
294 case Intrinsic::x86_sse2_psrl_d:
295 case Intrinsic::x86_sse2_psrl_q:
296 case Intrinsic::x86_sse2_psrl_w:
297 case Intrinsic::x86_sse2_psrli_d:
298 case Intrinsic::x86_sse2_psrli_q:
299 case Intrinsic::x86_sse2_psrli_w:
300 case Intrinsic::x86_avx2_psrl_d:
301 case Intrinsic::x86_avx2_psrl_q:
302 case Intrinsic::x86_avx2_psrl_w:
303 case Intrinsic::x86_avx2_psrli_d:
304 case Intrinsic::x86_avx2_psrli_q:
305 case Intrinsic::x86_avx2_psrli_w:
Craig Topper8b831cb2016-11-13 01:51:55 +0000306 case Intrinsic::x86_avx512_psrl_d_512:
307 case Intrinsic::x86_avx512_psrl_q_512:
308 case Intrinsic::x86_avx512_psrl_w_512:
309 case Intrinsic::x86_avx512_psrli_d_512:
310 case Intrinsic::x86_avx512_psrli_q_512:
311 case Intrinsic::x86_avx512_psrli_w_512:
Simon Pilgrimbecd5e82015-08-13 07:39:03 +0000312 LogicalShift = true; ShiftLeft = false;
313 break;
314 case Intrinsic::x86_sse2_psll_d:
315 case Intrinsic::x86_sse2_psll_q:
316 case Intrinsic::x86_sse2_psll_w:
317 case Intrinsic::x86_sse2_pslli_d:
318 case Intrinsic::x86_sse2_pslli_q:
319 case Intrinsic::x86_sse2_pslli_w:
320 case Intrinsic::x86_avx2_psll_d:
321 case Intrinsic::x86_avx2_psll_q:
322 case Intrinsic::x86_avx2_psll_w:
323 case Intrinsic::x86_avx2_pslli_d:
324 case Intrinsic::x86_avx2_pslli_q:
325 case Intrinsic::x86_avx2_pslli_w:
Craig Topper8b831cb2016-11-13 01:51:55 +0000326 case Intrinsic::x86_avx512_psll_d_512:
327 case Intrinsic::x86_avx512_psll_q_512:
328 case Intrinsic::x86_avx512_psll_w_512:
329 case Intrinsic::x86_avx512_pslli_d_512:
330 case Intrinsic::x86_avx512_pslli_q_512:
331 case Intrinsic::x86_avx512_pslli_w_512:
Simon Pilgrimbecd5e82015-08-13 07:39:03 +0000332 LogicalShift = true; ShiftLeft = true;
333 break;
334 }
Simon Pilgrima3a72b42015-08-10 20:21:15 +0000335 assert((LogicalShift || !ShiftLeft) && "Only logical shifts can shift left");
336
Simon Pilgrim3815c162015-08-07 18:22:50 +0000337 // Simplify if count is constant.
338 auto Arg1 = II.getArgOperand(1);
339 auto CAZ = dyn_cast<ConstantAggregateZero>(Arg1);
340 auto CDV = dyn_cast<ConstantDataVector>(Arg1);
341 auto CInt = dyn_cast<ConstantInt>(Arg1);
342 if (!CAZ && !CDV && !CInt)
Simon Pilgrim18617d12015-08-05 08:18:00 +0000343 return nullptr;
Simon Pilgrim3815c162015-08-07 18:22:50 +0000344
345 APInt Count(64, 0);
346 if (CDV) {
347 // SSE2/AVX2 uses all the first 64-bits of the 128-bit vector
348 // operand to compute the shift amount.
349 auto VT = cast<VectorType>(CDV->getType());
350 unsigned BitWidth = VT->getElementType()->getPrimitiveSizeInBits();
351 assert((64 % BitWidth) == 0 && "Unexpected packed shift size");
352 unsigned NumSubElts = 64 / BitWidth;
353
354 // Concatenate the sub-elements to create the 64-bit value.
355 for (unsigned i = 0; i != NumSubElts; ++i) {
356 unsigned SubEltIdx = (NumSubElts - 1) - i;
357 auto SubElt = cast<ConstantInt>(CDV->getElementAsConstant(SubEltIdx));
Craig Topper24e71012017-04-28 03:36:24 +0000358 Count <<= BitWidth;
Simon Pilgrim3815c162015-08-07 18:22:50 +0000359 Count |= SubElt->getValue().zextOrTrunc(64);
360 }
361 }
362 else if (CInt)
363 Count = CInt->getValue();
Simon Pilgrim18617d12015-08-05 08:18:00 +0000364
365 auto Vec = II.getArgOperand(0);
366 auto VT = cast<VectorType>(Vec->getType());
367 auto SVT = VT->getElementType();
Simon Pilgrim3815c162015-08-07 18:22:50 +0000368 unsigned VWidth = VT->getNumElements();
369 unsigned BitWidth = SVT->getPrimitiveSizeInBits();
370
371 // If shift-by-zero then just return the original value.
Craig Topper73ba1c82017-06-07 07:40:37 +0000372 if (Count.isNullValue())
Simon Pilgrim3815c162015-08-07 18:22:50 +0000373 return Vec;
374
Simon Pilgrima3a72b42015-08-10 20:21:15 +0000375 // Handle cases when Shift >= BitWidth.
376 if (Count.uge(BitWidth)) {
377 // If LogicalShift - just return zero.
378 if (LogicalShift)
379 return ConstantAggregateZero::get(VT);
380
381 // If ArithmeticShift - clamp Shift to (BitWidth - 1).
382 Count = APInt(64, BitWidth - 1);
383 }
Simon Pilgrim18617d12015-08-05 08:18:00 +0000384
Simon Pilgrim18617d12015-08-05 08:18:00 +0000385 // Get a constant vector of the same type as the first operand.
Simon Pilgrim3815c162015-08-07 18:22:50 +0000386 auto ShiftAmt = ConstantInt::get(SVT, Count.zextOrTrunc(BitWidth));
387 auto ShiftVec = Builder.CreateVectorSplat(VWidth, ShiftAmt);
Simon Pilgrim18617d12015-08-05 08:18:00 +0000388
389 if (ShiftLeft)
Simon Pilgrim3815c162015-08-07 18:22:50 +0000390 return Builder.CreateShl(Vec, ShiftVec);
Simon Pilgrim18617d12015-08-05 08:18:00 +0000391
Simon Pilgrima3a72b42015-08-10 20:21:15 +0000392 if (LogicalShift)
393 return Builder.CreateLShr(Vec, ShiftVec);
394
395 return Builder.CreateAShr(Vec, ShiftVec);
Simon Pilgrim18617d12015-08-05 08:18:00 +0000396}
397
Simon Pilgrimdb9893f2016-06-07 10:27:15 +0000398// Attempt to simplify AVX2 per-element shift intrinsics to a generic IR shift.
399// Unlike the generic IR shifts, the intrinsics have defined behaviour for out
400// of range shift amounts (logical - set to zero, arithmetic - splat sign bit).
401static Value *simplifyX86varShift(const IntrinsicInst &II,
402 InstCombiner::BuilderTy &Builder) {
403 bool LogicalShift = false;
404 bool ShiftLeft = false;
405
406 switch (II.getIntrinsicID()) {
Craig Topperb4173a52016-11-13 07:26:19 +0000407 default: llvm_unreachable("Unexpected intrinsic!");
Simon Pilgrimdb9893f2016-06-07 10:27:15 +0000408 case Intrinsic::x86_avx2_psrav_d:
409 case Intrinsic::x86_avx2_psrav_d_256:
Craig Topperb4173a52016-11-13 07:26:19 +0000410 case Intrinsic::x86_avx512_psrav_q_128:
411 case Intrinsic::x86_avx512_psrav_q_256:
412 case Intrinsic::x86_avx512_psrav_d_512:
413 case Intrinsic::x86_avx512_psrav_q_512:
Craig Topper1de753f2016-11-18 06:04:33 +0000414 case Intrinsic::x86_avx512_psrav_w_128:
415 case Intrinsic::x86_avx512_psrav_w_256:
416 case Intrinsic::x86_avx512_psrav_w_512:
Simon Pilgrimdb9893f2016-06-07 10:27:15 +0000417 LogicalShift = false;
418 ShiftLeft = false;
419 break;
420 case Intrinsic::x86_avx2_psrlv_d:
421 case Intrinsic::x86_avx2_psrlv_d_256:
422 case Intrinsic::x86_avx2_psrlv_q:
423 case Intrinsic::x86_avx2_psrlv_q_256:
Craig Topperb4173a52016-11-13 07:26:19 +0000424 case Intrinsic::x86_avx512_psrlv_d_512:
425 case Intrinsic::x86_avx512_psrlv_q_512:
Craig Topper1de753f2016-11-18 06:04:33 +0000426 case Intrinsic::x86_avx512_psrlv_w_128:
427 case Intrinsic::x86_avx512_psrlv_w_256:
428 case Intrinsic::x86_avx512_psrlv_w_512:
Simon Pilgrimdb9893f2016-06-07 10:27:15 +0000429 LogicalShift = true;
430 ShiftLeft = false;
431 break;
432 case Intrinsic::x86_avx2_psllv_d:
433 case Intrinsic::x86_avx2_psllv_d_256:
434 case Intrinsic::x86_avx2_psllv_q:
435 case Intrinsic::x86_avx2_psllv_q_256:
Craig Topperb4173a52016-11-13 07:26:19 +0000436 case Intrinsic::x86_avx512_psllv_d_512:
437 case Intrinsic::x86_avx512_psllv_q_512:
Craig Topper1de753f2016-11-18 06:04:33 +0000438 case Intrinsic::x86_avx512_psllv_w_128:
439 case Intrinsic::x86_avx512_psllv_w_256:
440 case Intrinsic::x86_avx512_psllv_w_512:
Simon Pilgrimdb9893f2016-06-07 10:27:15 +0000441 LogicalShift = true;
442 ShiftLeft = true;
443 break;
444 }
445 assert((LogicalShift || !ShiftLeft) && "Only logical shifts can shift left");
446
447 // Simplify if all shift amounts are constant/undef.
448 auto *CShift = dyn_cast<Constant>(II.getArgOperand(1));
449 if (!CShift)
450 return nullptr;
451
452 auto Vec = II.getArgOperand(0);
453 auto VT = cast<VectorType>(II.getType());
454 auto SVT = VT->getVectorElementType();
455 int NumElts = VT->getNumElements();
456 int BitWidth = SVT->getIntegerBitWidth();
457
458 // Collect each element's shift amount.
459 // We also collect special cases: UNDEF = -1, OUT-OF-RANGE = BitWidth.
460 bool AnyOutOfRange = false;
461 SmallVector<int, 8> ShiftAmts;
462 for (int I = 0; I < NumElts; ++I) {
463 auto *CElt = CShift->getAggregateElement(I);
464 if (CElt && isa<UndefValue>(CElt)) {
465 ShiftAmts.push_back(-1);
466 continue;
467 }
468
469 auto *COp = dyn_cast_or_null<ConstantInt>(CElt);
470 if (!COp)
471 return nullptr;
472
473 // Handle out of range shifts.
474 // If LogicalShift - set to BitWidth (special case).
475 // If ArithmeticShift - set to (BitWidth - 1) (sign splat).
476 APInt ShiftVal = COp->getValue();
477 if (ShiftVal.uge(BitWidth)) {
478 AnyOutOfRange = LogicalShift;
479 ShiftAmts.push_back(LogicalShift ? BitWidth : BitWidth - 1);
480 continue;
481 }
482
483 ShiftAmts.push_back((int)ShiftVal.getZExtValue());
484 }
485
486 // If all elements out of range or UNDEF, return vector of zeros/undefs.
487 // ArithmeticShift should only hit this if they are all UNDEF.
488 auto OutOfRange = [&](int Idx) { return (Idx < 0) || (BitWidth <= Idx); };
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000489 if (llvm::all_of(ShiftAmts, OutOfRange)) {
Simon Pilgrimdb9893f2016-06-07 10:27:15 +0000490 SmallVector<Constant *, 8> ConstantVec;
491 for (int Idx : ShiftAmts) {
492 if (Idx < 0) {
493 ConstantVec.push_back(UndefValue::get(SVT));
494 } else {
495 assert(LogicalShift && "Logical shift expected");
496 ConstantVec.push_back(ConstantInt::getNullValue(SVT));
497 }
498 }
499 return ConstantVector::get(ConstantVec);
500 }
501
502 // We can't handle only some out of range values with generic logical shifts.
503 if (AnyOutOfRange)
504 return nullptr;
505
506 // Build the shift amount constant vector.
507 SmallVector<Constant *, 8> ShiftVecAmts;
508 for (int Idx : ShiftAmts) {
509 if (Idx < 0)
510 ShiftVecAmts.push_back(UndefValue::get(SVT));
511 else
512 ShiftVecAmts.push_back(ConstantInt::get(SVT, Idx));
513 }
514 auto ShiftVec = ConstantVector::get(ShiftVecAmts);
515
516 if (ShiftLeft)
517 return Builder.CreateShl(Vec, ShiftVec);
518
519 if (LogicalShift)
520 return Builder.CreateLShr(Vec, ShiftVec);
521
522 return Builder.CreateAShr(Vec, ShiftVec);
523}
524
Craig Topper4853c432017-07-06 23:18:42 +0000525static Value *simplifyX86pack(IntrinsicInst &II, bool IsSigned) {
Simon Pilgrim6f6b2792017-01-25 14:37:24 +0000526 Value *Arg0 = II.getArgOperand(0);
527 Value *Arg1 = II.getArgOperand(1);
528 Type *ResTy = II.getType();
529
530 // Fast all undef handling.
531 if (isa<UndefValue>(Arg0) && isa<UndefValue>(Arg1))
532 return UndefValue::get(ResTy);
533
534 Type *ArgTy = Arg0->getType();
535 unsigned NumLanes = ResTy->getPrimitiveSizeInBits() / 128;
536 unsigned NumDstElts = ResTy->getVectorNumElements();
537 unsigned NumSrcElts = ArgTy->getVectorNumElements();
538 assert(NumDstElts == (2 * NumSrcElts) && "Unexpected packing types");
539
540 unsigned NumDstEltsPerLane = NumDstElts / NumLanes;
541 unsigned NumSrcEltsPerLane = NumSrcElts / NumLanes;
542 unsigned DstScalarSizeInBits = ResTy->getScalarSizeInBits();
543 assert(ArgTy->getScalarSizeInBits() == (2 * DstScalarSizeInBits) &&
544 "Unexpected packing types");
545
546 // Constant folding.
547 auto *Cst0 = dyn_cast<Constant>(Arg0);
548 auto *Cst1 = dyn_cast<Constant>(Arg1);
549 if (!Cst0 || !Cst1)
550 return nullptr;
551
552 SmallVector<Constant *, 32> Vals;
553 for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
554 for (unsigned Elt = 0; Elt != NumDstEltsPerLane; ++Elt) {
555 unsigned SrcIdx = Lane * NumSrcEltsPerLane + Elt % NumSrcEltsPerLane;
556 auto *Cst = (Elt >= NumSrcEltsPerLane) ? Cst1 : Cst0;
557 auto *COp = Cst->getAggregateElement(SrcIdx);
558 if (COp && isa<UndefValue>(COp)) {
559 Vals.push_back(UndefValue::get(ResTy->getScalarType()));
560 continue;
561 }
562
563 auto *CInt = dyn_cast_or_null<ConstantInt>(COp);
564 if (!CInt)
565 return nullptr;
566
567 APInt Val = CInt->getValue();
568 assert(Val.getBitWidth() == ArgTy->getScalarSizeInBits() &&
569 "Unexpected constant bitwidth");
570
571 if (IsSigned) {
572 // PACKSS: Truncate signed value with signed saturation.
573 // Source values less than dst minint are saturated to minint.
574 // Source values greater than dst maxint are saturated to maxint.
575 if (Val.isSignedIntN(DstScalarSizeInBits))
576 Val = Val.trunc(DstScalarSizeInBits);
577 else if (Val.isNegative())
578 Val = APInt::getSignedMinValue(DstScalarSizeInBits);
579 else
580 Val = APInt::getSignedMaxValue(DstScalarSizeInBits);
581 } else {
582 // PACKUS: Truncate signed value with unsigned saturation.
583 // Source values less than zero are saturated to zero.
584 // Source values greater than dst maxuint are saturated to maxuint.
585 if (Val.isIntN(DstScalarSizeInBits))
586 Val = Val.trunc(DstScalarSizeInBits);
587 else if (Val.isNegative())
588 Val = APInt::getNullValue(DstScalarSizeInBits);
589 else
590 Val = APInt::getAllOnesValue(DstScalarSizeInBits);
591 }
592
593 Vals.push_back(ConstantInt::get(ResTy->getScalarType(), Val));
594 }
595 }
596
597 return ConstantVector::get(Vals);
598}
599
Mikhail Dvoretckii8393f902018-06-19 10:49:12 +0000600// Replace X86-specific intrinsics with generic floor-ceil where applicable.
601static Value *simplifyX86round(IntrinsicInst &II,
602 InstCombiner::BuilderTy &Builder) {
603 ConstantInt *Arg = nullptr;
604 Intrinsic::ID IntrinsicID = II.getIntrinsicID();
605
606 if (IntrinsicID == Intrinsic::x86_sse41_round_ss ||
607 IntrinsicID == Intrinsic::x86_sse41_round_sd)
608 Arg = dyn_cast<ConstantInt>(II.getArgOperand(2));
609 else if (IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_ss ||
610 IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_sd)
611 Arg = dyn_cast<ConstantInt>(II.getArgOperand(4));
612 else
613 Arg = dyn_cast<ConstantInt>(II.getArgOperand(1));
614 if (!Arg)
615 return nullptr;
616 unsigned RoundControl = Arg->getZExtValue();
617
618 Arg = nullptr;
619 unsigned SAE = 0;
620 if (IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_ps_512 ||
621 IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_pd_512)
622 Arg = dyn_cast<ConstantInt>(II.getArgOperand(4));
623 else if (IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_ss ||
624 IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_sd)
625 Arg = dyn_cast<ConstantInt>(II.getArgOperand(5));
626 else
627 SAE = 4;
628 if (!SAE) {
629 if (!Arg)
630 return nullptr;
631 SAE = Arg->getZExtValue();
632 }
633
634 if (SAE != 4 || (RoundControl != 2 /*ceil*/ && RoundControl != 1 /*floor*/))
635 return nullptr;
636
637 Value *Src, *Dst, *Mask;
638 bool IsScalar = false;
639 if (IntrinsicID == Intrinsic::x86_sse41_round_ss ||
640 IntrinsicID == Intrinsic::x86_sse41_round_sd ||
641 IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_ss ||
642 IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_sd) {
643 IsScalar = true;
644 if (IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_ss ||
645 IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_sd) {
646 Mask = II.getArgOperand(3);
647 Value *Zero = Constant::getNullValue(Mask->getType());
648 Mask = Builder.CreateAnd(Mask, 1);
649 Mask = Builder.CreateICmp(ICmpInst::ICMP_NE, Mask, Zero);
650 Dst = II.getArgOperand(2);
651 } else
652 Dst = II.getArgOperand(0);
653 Src = Builder.CreateExtractElement(II.getArgOperand(1), (uint64_t)0);
654 } else {
655 Src = II.getArgOperand(0);
656 if (IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_ps_128 ||
657 IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_ps_256 ||
658 IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_ps_512 ||
659 IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_pd_128 ||
660 IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_pd_256 ||
661 IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_pd_512) {
662 Dst = II.getArgOperand(2);
663 Mask = II.getArgOperand(3);
664 } else {
665 Dst = Src;
666 Mask = ConstantInt::getAllOnesValue(
667 Builder.getIntNTy(Src->getType()->getVectorNumElements()));
668 }
669 }
670
671 Intrinsic::ID ID = (RoundControl == 2) ? Intrinsic::ceil : Intrinsic::floor;
Neil Henning57f5d0a2018-10-08 10:32:33 +0000672 Value *Res = Builder.CreateUnaryIntrinsic(ID, Src, &II);
Mikhail Dvoretckii8393f902018-06-19 10:49:12 +0000673 if (!IsScalar) {
674 if (auto *C = dyn_cast<Constant>(Mask))
675 if (C->isAllOnesValue())
676 return Res;
677 auto *MaskTy = VectorType::get(
678 Builder.getInt1Ty(), cast<IntegerType>(Mask->getType())->getBitWidth());
679 Mask = Builder.CreateBitCast(Mask, MaskTy);
680 unsigned Width = Src->getType()->getVectorNumElements();
681 if (MaskTy->getVectorNumElements() > Width) {
682 uint32_t Indices[4];
683 for (unsigned i = 0; i != Width; ++i)
684 Indices[i] = i;
685 Mask = Builder.CreateShuffleVector(Mask, Mask,
686 makeArrayRef(Indices, Width));
687 }
688 return Builder.CreateSelect(Mask, Res, Dst);
689 }
690 if (IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_ss ||
691 IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_sd) {
692 Dst = Builder.CreateExtractElement(Dst, (uint64_t)0);
693 Res = Builder.CreateSelect(Mask, Res, Dst);
694 Dst = II.getArgOperand(0);
695 }
696 return Builder.CreateInsertElement(Dst, Res, (uint64_t)0);
697}
698
Sanjay Patel2aa2dc72018-12-11 16:38:03 +0000699static Value *simplifyX86movmsk(const IntrinsicInst &II,
700 InstCombiner::BuilderTy &Builder) {
Simon Pilgrim91e3ac82016-06-07 08:18:35 +0000701 Value *Arg = II.getArgOperand(0);
702 Type *ResTy = II.getType();
703 Type *ArgTy = Arg->getType();
704
705 // movmsk(undef) -> zero as we must ensure the upper bits are zero.
706 if (isa<UndefValue>(Arg))
707 return Constant::getNullValue(ResTy);
708
709 // We can't easily peek through x86_mmx types.
710 if (!ArgTy->isVectorTy())
711 return nullptr;
712
Simon Pilgrimb4f1bfa2019-04-08 13:17:51 +0000713 // Expand MOVMSK to compare/bitcast/zext:
714 // e.g. PMOVMSKB(v16i8 x):
715 // %cmp = icmp slt <16 x i8> %x, zeroinitializer
716 // %int = bitcast <16 x i1> %cmp to i16
717 // %res = zext i16 %int to i32
718 unsigned NumElts = ArgTy->getVectorNumElements();
719 Type *IntegerVecTy = VectorType::getInteger(cast<VectorType>(ArgTy));
720 Type *IntegerTy = Builder.getIntNTy(NumElts);
Simon Pilgrim91e3ac82016-06-07 08:18:35 +0000721
Simon Pilgrimb4f1bfa2019-04-08 13:17:51 +0000722 Value *Res = Builder.CreateBitCast(Arg, IntegerVecTy);
723 Res = Builder.CreateICmpSLT(Res, Constant::getNullValue(IntegerVecTy));
724 Res = Builder.CreateBitCast(Res, IntegerTy);
725 Res = Builder.CreateZExtOrTrunc(Res, ResTy);
726 return Res;
Simon Pilgrim91e3ac82016-06-07 08:18:35 +0000727}
728
Sanjay Patelbe23a912019-02-01 14:14:47 +0000729static Value *simplifyX86addcarry(const IntrinsicInst &II,
730 InstCombiner::BuilderTy &Builder) {
731 Value *CarryIn = II.getArgOperand(0);
732 Value *Op1 = II.getArgOperand(1);
733 Value *Op2 = II.getArgOperand(2);
734 Type *RetTy = II.getType();
735 Type *OpTy = Op1->getType();
736 assert(RetTy->getStructElementType(0)->isIntegerTy(8) &&
737 RetTy->getStructElementType(1) == OpTy && OpTy == Op2->getType() &&
738 "Unexpected types for x86 addcarry");
739
740 // If carry-in is zero, this is just an unsigned add with overflow.
741 if (match(CarryIn, m_ZeroInt())) {
742 Value *UAdd = Builder.CreateIntrinsic(Intrinsic::uadd_with_overflow, OpTy,
743 { Op1, Op2 });
744 // The types have to be adjusted to match the x86 call types.
745 Value *UAddResult = Builder.CreateExtractValue(UAdd, 0);
746 Value *UAddOV = Builder.CreateZExt(Builder.CreateExtractValue(UAdd, 1),
747 Builder.getInt8Ty());
Sanjay Patelfbcbac72019-02-01 14:37:49 +0000748 Value *Res = UndefValue::get(RetTy);
Sanjay Patelbe23a912019-02-01 14:14:47 +0000749 Res = Builder.CreateInsertValue(Res, UAddOV, 0);
750 return Builder.CreateInsertValue(Res, UAddResult, 1);
751 }
752
753 return nullptr;
754}
755
Sanjay Patel6038d3e2016-01-29 23:27:03 +0000756static Value *simplifyX86insertps(const IntrinsicInst &II,
Sanjay Patelc86867c2015-04-16 17:52:13 +0000757 InstCombiner::BuilderTy &Builder) {
Sanjay Patel03c03f52016-01-28 00:03:16 +0000758 auto *CInt = dyn_cast<ConstantInt>(II.getArgOperand(2));
759 if (!CInt)
760 return nullptr;
Simon Pilgrim54fcd622015-07-25 20:41:00 +0000761
Sanjay Patel03c03f52016-01-28 00:03:16 +0000762 VectorType *VecTy = cast<VectorType>(II.getType());
763 assert(VecTy->getNumElements() == 4 && "insertps with wrong vector type");
Sanjay Patelc86867c2015-04-16 17:52:13 +0000764
Sanjay Patel03c03f52016-01-28 00:03:16 +0000765 // The immediate permute control byte looks like this:
766 // [3:0] - zero mask for each 32-bit lane
767 // [5:4] - select one 32-bit destination lane
768 // [7:6] - select one 32-bit source lane
Sanjay Patelc86867c2015-04-16 17:52:13 +0000769
Sanjay Patel03c03f52016-01-28 00:03:16 +0000770 uint8_t Imm = CInt->getZExtValue();
771 uint8_t ZMask = Imm & 0xf;
772 uint8_t DestLane = (Imm >> 4) & 0x3;
773 uint8_t SourceLane = (Imm >> 6) & 0x3;
Sanjay Patelc1d20a32015-04-25 20:55:25 +0000774
Sanjay Patel03c03f52016-01-28 00:03:16 +0000775 ConstantAggregateZero *ZeroVector = ConstantAggregateZero::get(VecTy);
Sanjay Patelc86867c2015-04-16 17:52:13 +0000776
Sanjay Patel03c03f52016-01-28 00:03:16 +0000777 // If all zero mask bits are set, this was just a weird way to
778 // generate a zero vector.
779 if (ZMask == 0xf)
780 return ZeroVector;
Sanjay Patelc1d20a32015-04-25 20:55:25 +0000781
Sanjay Patel03c03f52016-01-28 00:03:16 +0000782 // Initialize by passing all of the first source bits through.
Craig Topper99d1eab2016-06-12 00:41:19 +0000783 uint32_t ShuffleMask[4] = { 0, 1, 2, 3 };
Sanjay Patelc1d20a32015-04-25 20:55:25 +0000784
Sanjay Patel03c03f52016-01-28 00:03:16 +0000785 // We may replace the second operand with the zero vector.
786 Value *V1 = II.getArgOperand(1);
787
788 if (ZMask) {
789 // If the zero mask is being used with a single input or the zero mask
790 // overrides the destination lane, this is a shuffle with the zero vector.
791 if ((II.getArgOperand(0) == II.getArgOperand(1)) ||
792 (ZMask & (1 << DestLane))) {
793 V1 = ZeroVector;
794 // We may still move 32-bits of the first source vector from one lane
795 // to another.
796 ShuffleMask[DestLane] = SourceLane;
797 // The zero mask may override the previous insert operation.
798 for (unsigned i = 0; i < 4; ++i)
799 if ((ZMask >> i) & 0x1)
800 ShuffleMask[i] = i + 4;
Sanjay Patelc1d20a32015-04-25 20:55:25 +0000801 } else {
Sanjay Patel03c03f52016-01-28 00:03:16 +0000802 // TODO: Model this case as 2 shuffles or a 'logical and' plus shuffle?
803 return nullptr;
Sanjay Patelc1d20a32015-04-25 20:55:25 +0000804 }
Sanjay Patel03c03f52016-01-28 00:03:16 +0000805 } else {
806 // Replace the selected destination lane with the selected source lane.
807 ShuffleMask[DestLane] = SourceLane + 4;
Sanjay Patelc86867c2015-04-16 17:52:13 +0000808 }
Sanjay Patel03c03f52016-01-28 00:03:16 +0000809
810 return Builder.CreateShuffleVector(II.getArgOperand(0), V1, ShuffleMask);
Sanjay Patelc86867c2015-04-16 17:52:13 +0000811}
812
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000813/// Attempt to simplify SSE4A EXTRQ/EXTRQI instructions using constant folding
814/// or conversion to a shuffle vector.
Sanjay Patel6038d3e2016-01-29 23:27:03 +0000815static Value *simplifyX86extrq(IntrinsicInst &II, Value *Op0,
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000816 ConstantInt *CILength, ConstantInt *CIIndex,
817 InstCombiner::BuilderTy &Builder) {
818 auto LowConstantHighUndef = [&](uint64_t Val) {
819 Type *IntTy64 = Type::getInt64Ty(II.getContext());
820 Constant *Args[] = {ConstantInt::get(IntTy64, Val),
821 UndefValue::get(IntTy64)};
822 return ConstantVector::get(Args);
823 };
824
825 // See if we're dealing with constant values.
826 Constant *C0 = dyn_cast<Constant>(Op0);
827 ConstantInt *CI0 =
Andrea Di Biagio8df5b9c2016-09-07 12:03:03 +0000828 C0 ? dyn_cast_or_null<ConstantInt>(C0->getAggregateElement((unsigned)0))
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000829 : nullptr;
830
831 // Attempt to constant fold.
832 if (CILength && CIIndex) {
833 // From AMD documentation: "The bit index and field length are each six
834 // bits in length other bits of the field are ignored."
835 APInt APIndex = CIIndex->getValue().zextOrTrunc(6);
836 APInt APLength = CILength->getValue().zextOrTrunc(6);
837
838 unsigned Index = APIndex.getZExtValue();
839
840 // From AMD documentation: "a value of zero in the field length is
841 // defined as length of 64".
842 unsigned Length = APLength == 0 ? 64 : APLength.getZExtValue();
843
844 // From AMD documentation: "If the sum of the bit index + length field
845 // is greater than 64, the results are undefined".
846 unsigned End = Index + Length;
847
848 // Note that both field index and field length are 8-bit quantities.
849 // Since variables 'Index' and 'Length' are unsigned values
850 // obtained from zero-extending field index and field length
851 // respectively, their sum should never wrap around.
852 if (End > 64)
853 return UndefValue::get(II.getType());
854
855 // If we are inserting whole bytes, we can convert this to a shuffle.
856 // Lowering can recognize EXTRQI shuffle masks.
857 if ((Length % 8) == 0 && (Index % 8) == 0) {
858 // Convert bit indices to byte indices.
859 Length /= 8;
860 Index /= 8;
861
862 Type *IntTy8 = Type::getInt8Ty(II.getContext());
863 Type *IntTy32 = Type::getInt32Ty(II.getContext());
864 VectorType *ShufTy = VectorType::get(IntTy8, 16);
865
866 SmallVector<Constant *, 16> ShuffleMask;
867 for (int i = 0; i != (int)Length; ++i)
868 ShuffleMask.push_back(
869 Constant::getIntegerValue(IntTy32, APInt(32, i + Index)));
870 for (int i = Length; i != 8; ++i)
871 ShuffleMask.push_back(
872 Constant::getIntegerValue(IntTy32, APInt(32, i + 16)));
873 for (int i = 8; i != 16; ++i)
874 ShuffleMask.push_back(UndefValue::get(IntTy32));
875
876 Value *SV = Builder.CreateShuffleVector(
877 Builder.CreateBitCast(Op0, ShufTy),
878 ConstantAggregateZero::get(ShufTy), ConstantVector::get(ShuffleMask));
879 return Builder.CreateBitCast(SV, II.getType());
880 }
881
882 // Constant Fold - shift Index'th bit to lowest position and mask off
883 // Length bits.
884 if (CI0) {
885 APInt Elt = CI0->getValue();
Craig Topperfc947bc2017-04-18 17:14:21 +0000886 Elt.lshrInPlace(Index);
887 Elt = Elt.zextOrTrunc(Length);
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000888 return LowConstantHighUndef(Elt.getZExtValue());
889 }
890
891 // If we were an EXTRQ call, we'll save registers if we convert to EXTRQI.
892 if (II.getIntrinsicID() == Intrinsic::x86_sse4a_extrq) {
893 Value *Args[] = {Op0, CILength, CIIndex};
Sanjay Patelaf674fb2015-12-14 17:24:23 +0000894 Module *M = II.getModule();
James Y Knight7976eb52019-02-01 20:43:25 +0000895 Function *F = Intrinsic::getDeclaration(M, Intrinsic::x86_sse4a_extrqi);
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000896 return Builder.CreateCall(F, Args);
897 }
898 }
899
900 // Constant Fold - extraction from zero is always {zero, undef}.
Craig Topperca2c8762017-07-06 18:39:49 +0000901 if (CI0 && CI0->isZero())
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000902 return LowConstantHighUndef(0);
903
904 return nullptr;
905}
906
907/// Attempt to simplify SSE4A INSERTQ/INSERTQI instructions using constant
908/// folding or conversion to a shuffle vector.
Sanjay Patel6038d3e2016-01-29 23:27:03 +0000909static Value *simplifyX86insertq(IntrinsicInst &II, Value *Op0, Value *Op1,
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000910 APInt APLength, APInt APIndex,
911 InstCombiner::BuilderTy &Builder) {
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000912 // From AMD documentation: "The bit index and field length are each six bits
913 // in length other bits of the field are ignored."
914 APIndex = APIndex.zextOrTrunc(6);
915 APLength = APLength.zextOrTrunc(6);
916
917 // Attempt to constant fold.
918 unsigned Index = APIndex.getZExtValue();
919
920 // From AMD documentation: "a value of zero in the field length is
921 // defined as length of 64".
922 unsigned Length = APLength == 0 ? 64 : APLength.getZExtValue();
923
924 // From AMD documentation: "If the sum of the bit index + length field
925 // is greater than 64, the results are undefined".
926 unsigned End = Index + Length;
927
928 // Note that both field index and field length are 8-bit quantities.
929 // Since variables 'Index' and 'Length' are unsigned values
930 // obtained from zero-extending field index and field length
931 // respectively, their sum should never wrap around.
932 if (End > 64)
933 return UndefValue::get(II.getType());
934
935 // If we are inserting whole bytes, we can convert this to a shuffle.
936 // Lowering can recognize INSERTQI shuffle masks.
937 if ((Length % 8) == 0 && (Index % 8) == 0) {
938 // Convert bit indices to byte indices.
939 Length /= 8;
940 Index /= 8;
941
942 Type *IntTy8 = Type::getInt8Ty(II.getContext());
943 Type *IntTy32 = Type::getInt32Ty(II.getContext());
944 VectorType *ShufTy = VectorType::get(IntTy8, 16);
945
946 SmallVector<Constant *, 16> ShuffleMask;
947 for (int i = 0; i != (int)Index; ++i)
948 ShuffleMask.push_back(Constant::getIntegerValue(IntTy32, APInt(32, i)));
949 for (int i = 0; i != (int)Length; ++i)
950 ShuffleMask.push_back(
951 Constant::getIntegerValue(IntTy32, APInt(32, i + 16)));
952 for (int i = Index + Length; i != 8; ++i)
953 ShuffleMask.push_back(Constant::getIntegerValue(IntTy32, APInt(32, i)));
954 for (int i = 8; i != 16; ++i)
955 ShuffleMask.push_back(UndefValue::get(IntTy32));
956
957 Value *SV = Builder.CreateShuffleVector(Builder.CreateBitCast(Op0, ShufTy),
958 Builder.CreateBitCast(Op1, ShufTy),
959 ConstantVector::get(ShuffleMask));
960 return Builder.CreateBitCast(SV, II.getType());
961 }
962
963 // See if we're dealing with constant values.
964 Constant *C0 = dyn_cast<Constant>(Op0);
965 Constant *C1 = dyn_cast<Constant>(Op1);
966 ConstantInt *CI00 =
Andrea Di Biagiof3fd3162016-09-07 12:47:53 +0000967 C0 ? dyn_cast_or_null<ConstantInt>(C0->getAggregateElement((unsigned)0))
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000968 : nullptr;
969 ConstantInt *CI10 =
Andrea Di Biagiof3fd3162016-09-07 12:47:53 +0000970 C1 ? dyn_cast_or_null<ConstantInt>(C1->getAggregateElement((unsigned)0))
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000971 : nullptr;
972
973 // Constant Fold - insert bottom Length bits starting at the Index'th bit.
974 if (CI00 && CI10) {
975 APInt V00 = CI00->getValue();
976 APInt V10 = CI10->getValue();
977 APInt Mask = APInt::getLowBitsSet(64, Length).shl(Index);
978 V00 = V00 & ~Mask;
979 V10 = V10.zextOrTrunc(Length).zextOrTrunc(64).shl(Index);
980 APInt Val = V00 | V10;
981 Type *IntTy64 = Type::getInt64Ty(II.getContext());
982 Constant *Args[] = {ConstantInt::get(IntTy64, Val.getZExtValue()),
983 UndefValue::get(IntTy64)};
984 return ConstantVector::get(Args);
985 }
986
987 // If we were an INSERTQ call, we'll save demanded elements if we convert to
988 // INSERTQI.
989 if (II.getIntrinsicID() == Intrinsic::x86_sse4a_insertq) {
990 Type *IntTy8 = Type::getInt8Ty(II.getContext());
991 Constant *CILength = ConstantInt::get(IntTy8, Length, false);
992 Constant *CIIndex = ConstantInt::get(IntTy8, Index, false);
993
994 Value *Args[] = {Op0, Op1, CILength, CIIndex};
Sanjay Patelaf674fb2015-12-14 17:24:23 +0000995 Module *M = II.getModule();
James Y Knight7976eb52019-02-01 20:43:25 +0000996 Function *F = Intrinsic::getDeclaration(M, Intrinsic::x86_sse4a_insertqi);
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000997 return Builder.CreateCall(F, Args);
998 }
999
1000 return nullptr;
1001}
1002
Simon Pilgrimc0c56e72016-04-24 17:00:34 +00001003/// Attempt to convert pshufb* to shufflevector if the mask is constant.
1004static Value *simplifyX86pshufb(const IntrinsicInst &II,
1005 InstCombiner::BuilderTy &Builder) {
Simon Pilgrimbf60cc42016-04-29 21:34:54 +00001006 Constant *V = dyn_cast<Constant>(II.getArgOperand(1));
1007 if (!V)
1008 return nullptr;
1009
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +00001010 auto *VecTy = cast<VectorType>(II.getType());
1011 auto *MaskEltTy = Type::getInt32Ty(II.getContext());
1012 unsigned NumElts = VecTy->getNumElements();
Craig Topper9a63d7a2016-12-11 00:23:50 +00001013 assert((NumElts == 16 || NumElts == 32 || NumElts == 64) &&
Simon Pilgrimc0c56e72016-04-24 17:00:34 +00001014 "Unexpected number of elements in shuffle mask!");
Simon Pilgrimbf60cc42016-04-29 21:34:54 +00001015
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +00001016 // Construct a shuffle mask from constant integers or UNDEFs.
Craig Topper9a63d7a2016-12-11 00:23:50 +00001017 Constant *Indexes[64] = {nullptr};
Simon Pilgrimc0c56e72016-04-24 17:00:34 +00001018
Simon Pilgrimbf60cc42016-04-29 21:34:54 +00001019 // Each byte in the shuffle control mask forms an index to permute the
1020 // corresponding byte in the destination operand.
1021 for (unsigned I = 0; I < NumElts; ++I) {
1022 Constant *COp = V->getAggregateElement(I);
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +00001023 if (!COp || (!isa<UndefValue>(COp) && !isa<ConstantInt>(COp)))
Simon Pilgrimbf60cc42016-04-29 21:34:54 +00001024 return nullptr;
Simon Pilgrimc0c56e72016-04-24 17:00:34 +00001025
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +00001026 if (isa<UndefValue>(COp)) {
1027 Indexes[I] = UndefValue::get(MaskEltTy);
1028 continue;
1029 }
1030
Simon Pilgrimbf60cc42016-04-29 21:34:54 +00001031 int8_t Index = cast<ConstantInt>(COp)->getValue().getZExtValue();
1032
1033 // If the most significant bit (bit[7]) of each byte of the shuffle
1034 // control mask is set, then zero is written in the result byte.
1035 // The zero vector is in the right-hand side of the resulting
1036 // shufflevector.
1037
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +00001038 // The value of each index for the high 128-bit lane is the least
1039 // significant 4 bits of the respective shuffle control byte.
1040 Index = ((Index < 0) ? NumElts : Index & 0x0F) + (I & 0xF0);
1041 Indexes[I] = ConstantInt::get(MaskEltTy, Index);
Simon Pilgrimbf60cc42016-04-29 21:34:54 +00001042 }
Simon Pilgrimc0c56e72016-04-24 17:00:34 +00001043
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +00001044 auto ShuffleMask = ConstantVector::get(makeArrayRef(Indexes, NumElts));
Simon Pilgrimc0c56e72016-04-24 17:00:34 +00001045 auto V1 = II.getArgOperand(0);
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +00001046 auto V2 = Constant::getNullValue(VecTy);
Simon Pilgrimc0c56e72016-04-24 17:00:34 +00001047 return Builder.CreateShuffleVector(V1, V2, ShuffleMask);
1048}
1049
Simon Pilgrim2f6097d2016-04-24 17:23:46 +00001050/// Attempt to convert vpermilvar* to shufflevector if the mask is constant.
1051static Value *simplifyX86vpermilvar(const IntrinsicInst &II,
1052 InstCombiner::BuilderTy &Builder) {
Simon Pilgrim640f9962016-04-30 07:23:30 +00001053 Constant *V = dyn_cast<Constant>(II.getArgOperand(1));
1054 if (!V)
1055 return nullptr;
Simon Pilgrim2f6097d2016-04-24 17:23:46 +00001056
Craig Topper58917f32016-12-11 01:59:36 +00001057 auto *VecTy = cast<VectorType>(II.getType());
Simon Pilgrimeeacc402016-05-01 20:22:42 +00001058 auto *MaskEltTy = Type::getInt32Ty(II.getContext());
Craig Topper58917f32016-12-11 01:59:36 +00001059 unsigned NumElts = VecTy->getVectorNumElements();
1060 bool IsPD = VecTy->getScalarType()->isDoubleTy();
1061 unsigned NumLaneElts = IsPD ? 2 : 4;
1062 assert(NumElts == 16 || NumElts == 8 || NumElts == 4 || NumElts == 2);
Simon Pilgrim2f6097d2016-04-24 17:23:46 +00001063
Simon Pilgrimeeacc402016-05-01 20:22:42 +00001064 // Construct a shuffle mask from constant integers or UNDEFs.
Craig Topper58917f32016-12-11 01:59:36 +00001065 Constant *Indexes[16] = {nullptr};
Simon Pilgrim640f9962016-04-30 07:23:30 +00001066
1067 // The intrinsics only read one or two bits, clear the rest.
Simon Pilgrimeeacc402016-05-01 20:22:42 +00001068 for (unsigned I = 0; I < NumElts; ++I) {
Simon Pilgrim640f9962016-04-30 07:23:30 +00001069 Constant *COp = V->getAggregateElement(I);
Simon Pilgrimeeacc402016-05-01 20:22:42 +00001070 if (!COp || (!isa<UndefValue>(COp) && !isa<ConstantInt>(COp)))
Simon Pilgrim640f9962016-04-30 07:23:30 +00001071 return nullptr;
1072
Simon Pilgrimeeacc402016-05-01 20:22:42 +00001073 if (isa<UndefValue>(COp)) {
1074 Indexes[I] = UndefValue::get(MaskEltTy);
1075 continue;
1076 }
1077
1078 APInt Index = cast<ConstantInt>(COp)->getValue();
1079 Index = Index.zextOrTrunc(32).getLoBits(2);
Simon Pilgrim640f9962016-04-30 07:23:30 +00001080
1081 // The PD variants uses bit 1 to select per-lane element index, so
1082 // shift down to convert to generic shuffle mask index.
Craig Topper58917f32016-12-11 01:59:36 +00001083 if (IsPD)
Craig Topperfc947bc2017-04-18 17:14:21 +00001084 Index.lshrInPlace(1);
Simon Pilgrimeeacc402016-05-01 20:22:42 +00001085
1086 // The _256 variants are a bit trickier since the mask bits always index
1087 // into the corresponding 128 half. In order to convert to a generic
1088 // shuffle, we have to make that explicit.
Craig Topper58917f32016-12-11 01:59:36 +00001089 Index += APInt(32, (I / NumLaneElts) * NumLaneElts);
Simon Pilgrimeeacc402016-05-01 20:22:42 +00001090
1091 Indexes[I] = ConstantInt::get(MaskEltTy, Index);
Simon Pilgrim2f6097d2016-04-24 17:23:46 +00001092 }
1093
Simon Pilgrimeeacc402016-05-01 20:22:42 +00001094 auto ShuffleMask = ConstantVector::get(makeArrayRef(Indexes, NumElts));
Simon Pilgrim2f6097d2016-04-24 17:23:46 +00001095 auto V1 = II.getArgOperand(0);
1096 auto V2 = UndefValue::get(V1->getType());
1097 return Builder.CreateShuffleVector(V1, V2, ShuffleMask);
1098}
1099
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +00001100/// Attempt to convert vpermd/vpermps to shufflevector if the mask is constant.
1101static Value *simplifyX86vpermv(const IntrinsicInst &II,
1102 InstCombiner::BuilderTy &Builder) {
1103 auto *V = dyn_cast<Constant>(II.getArgOperand(1));
1104 if (!V)
1105 return nullptr;
1106
Simon Pilgrimca140b12016-05-01 20:43:02 +00001107 auto *VecTy = cast<VectorType>(II.getType());
1108 auto *MaskEltTy = Type::getInt32Ty(II.getContext());
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +00001109 unsigned Size = VecTy->getNumElements();
Craig Toppere3280452016-12-25 23:58:57 +00001110 assert((Size == 4 || Size == 8 || Size == 16 || Size == 32 || Size == 64) &&
1111 "Unexpected shuffle mask size");
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +00001112
Simon Pilgrimca140b12016-05-01 20:43:02 +00001113 // Construct a shuffle mask from constant integers or UNDEFs.
Craig Toppere3280452016-12-25 23:58:57 +00001114 Constant *Indexes[64] = {nullptr};
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +00001115
1116 for (unsigned I = 0; I < Size; ++I) {
1117 Constant *COp = V->getAggregateElement(I);
Simon Pilgrimca140b12016-05-01 20:43:02 +00001118 if (!COp || (!isa<UndefValue>(COp) && !isa<ConstantInt>(COp)))
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +00001119 return nullptr;
1120
Simon Pilgrimca140b12016-05-01 20:43:02 +00001121 if (isa<UndefValue>(COp)) {
1122 Indexes[I] = UndefValue::get(MaskEltTy);
1123 continue;
1124 }
1125
Craig Toppere3280452016-12-25 23:58:57 +00001126 uint32_t Index = cast<ConstantInt>(COp)->getZExtValue();
1127 Index &= Size - 1;
Simon Pilgrimca140b12016-05-01 20:43:02 +00001128 Indexes[I] = ConstantInt::get(MaskEltTy, Index);
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +00001129 }
1130
Simon Pilgrimca140b12016-05-01 20:43:02 +00001131 auto ShuffleMask = ConstantVector::get(makeArrayRef(Indexes, Size));
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +00001132 auto V1 = II.getArgOperand(0);
1133 auto V2 = UndefValue::get(VecTy);
1134 return Builder.CreateShuffleVector(V1, V2, ShuffleMask);
1135}
1136
David Majnemer666aa942016-07-14 06:58:42 +00001137static bool maskIsAllOneOrUndef(Value *Mask) {
1138 auto *ConstMask = dyn_cast<Constant>(Mask);
1139 if (!ConstMask)
1140 return false;
1141 if (ConstMask->isAllOnesValue() || isa<UndefValue>(ConstMask))
1142 return true;
1143 for (unsigned I = 0, E = ConstMask->getType()->getVectorNumElements(); I != E;
1144 ++I) {
1145 if (auto *MaskElt = ConstMask->getAggregateElement(I))
1146 if (MaskElt->isAllOnesValue() || isa<UndefValue>(MaskElt))
1147 continue;
1148 return false;
1149 }
1150 return true;
1151}
1152
Philip Reamese4588bb2019-03-20 18:44:58 +00001153/// Given a mask vector <Y x i1>, return an APInt (of bitwidth Y) for each lane
1154/// which may be active. TODO: This is a lot like known bits, but for
1155/// vectors. Is there something we can common this with?
1156static APInt possiblyDemandedEltsInMask(Value *Mask) {
1157
1158 const unsigned VWidth = cast<VectorType>(Mask->getType())->getNumElements();
1159 APInt DemandedElts = APInt::getAllOnesValue(VWidth);
1160 if (auto *CV = dyn_cast<ConstantVector>(Mask))
1161 for (unsigned i = 0; i < VWidth; i++)
1162 if (CV->getAggregateElement(i)->isNullValue())
1163 DemandedElts.clearBit(i);
1164 return DemandedElts;
1165}
1166
Philip Reames484d07c2019-03-20 03:36:05 +00001167// TODO, Obvious Missing Transforms:
1168// * Dereferenceable address -> speculative load/select
1169// * Narrow width by halfs excluding zero/undef lanes
Sanjay Patelb695c552016-02-01 17:00:10 +00001170static Value *simplifyMaskedLoad(const IntrinsicInst &II,
1171 InstCombiner::BuilderTy &Builder) {
David Majnemer666aa942016-07-14 06:58:42 +00001172 // If the mask is all ones or undefs, this is a plain vector load of the 1st
1173 // argument.
1174 if (maskIsAllOneOrUndef(II.getArgOperand(2))) {
Sanjay Patelb695c552016-02-01 17:00:10 +00001175 Value *LoadPtr = II.getArgOperand(0);
1176 unsigned Alignment = cast<ConstantInt>(II.getArgOperand(1))->getZExtValue();
James Y Knight14359ef2019-02-01 20:44:24 +00001177 return Builder.CreateAlignedLoad(II.getType(), LoadPtr, Alignment,
1178 "unmaskedload");
Sanjay Patelb695c552016-02-01 17:00:10 +00001179 }
1180
1181 return nullptr;
1182}
1183
Philip Reames484d07c2019-03-20 03:36:05 +00001184// TODO, Obvious Missing Transforms:
Philip Reames484d07c2019-03-20 03:36:05 +00001185// * Single constant active lane -> store
1186// * Narrow width by halfs excluding zero/undef lanes
Philip Reamese4588bb2019-03-20 18:44:58 +00001187Instruction *InstCombiner::simplifyMaskedStore(IntrinsicInst &II) {
Sanjay Patel04f792b2016-02-01 19:39:52 +00001188 auto *ConstMask = dyn_cast<Constant>(II.getArgOperand(3));
1189 if (!ConstMask)
1190 return nullptr;
1191
1192 // If the mask is all zeros, this instruction does nothing.
1193 if (ConstMask->isNullValue())
Philip Reamese4588bb2019-03-20 18:44:58 +00001194 return eraseInstFromFunction(II);
Sanjay Patel04f792b2016-02-01 19:39:52 +00001195
1196 // If the mask is all ones, this is a plain vector store of the 1st argument.
1197 if (ConstMask->isAllOnesValue()) {
1198 Value *StorePtr = II.getArgOperand(1);
1199 unsigned Alignment = cast<ConstantInt>(II.getArgOperand(2))->getZExtValue();
1200 return new StoreInst(II.getArgOperand(0), StorePtr, false, Alignment);
1201 }
1202
Philip Reamese4588bb2019-03-20 18:44:58 +00001203 // Use masked off lanes to simplify operands via SimplifyDemandedVectorElts
1204 APInt DemandedElts = possiblyDemandedEltsInMask(ConstMask);
1205 APInt UndefElts(DemandedElts.getBitWidth(), 0);
1206 if (Value *V = SimplifyDemandedVectorElts(II.getOperand(0),
1207 DemandedElts, UndefElts)) {
1208 II.setOperand(0, V);
1209 return &II;
1210 }
1211
Sanjay Patel04f792b2016-02-01 19:39:52 +00001212 return nullptr;
1213}
1214
Philip Reames484d07c2019-03-20 03:36:05 +00001215// TODO, Obvious Missing Transforms:
1216// * Single constant active lane load -> load
1217// * Dereferenceable address & few lanes -> scalarize speculative load/selects
1218// * Adjacent vector addresses -> masked.load
1219// * Narrow width by halfs excluding zero/undef lanes
Philip Reames60212be2019-03-21 03:23:40 +00001220// * Vector splat address w/known mask -> scalar load
1221// * Vector incrementing address -> vector masked load
Sanjay Patel103ab7d2016-02-01 22:10:26 +00001222static Instruction *simplifyMaskedGather(IntrinsicInst &II, InstCombiner &IC) {
1223 // If the mask is all zeros, return the "passthru" argument of the gather.
1224 auto *ConstMask = dyn_cast<Constant>(II.getArgOperand(2));
1225 if (ConstMask && ConstMask->isNullValue())
Sanjay Patel4b198802016-02-01 22:23:39 +00001226 return IC.replaceInstUsesWith(II, II.getArgOperand(3));
Sanjay Patel103ab7d2016-02-01 22:10:26 +00001227
1228 return nullptr;
1229}
1230
Philip Reames60212be2019-03-21 03:23:40 +00001231// TODO, Obvious Missing Transforms:
1232// * Single constant active lane -> store
1233// * Adjacent vector addresses -> masked.store
1234// * Narrow store width by halfs excluding zero/undef lanes
1235// * Vector splat address w/known mask -> scalar store
1236// * Vector incrementing address -> vector masked store
1237Instruction *InstCombiner::simplifyMaskedScatter(IntrinsicInst &II) {
1238 auto *ConstMask = dyn_cast<Constant>(II.getArgOperand(3));
1239 if (!ConstMask)
1240 return nullptr;
1241
1242 // If the mask is all zeros, a scatter does nothing.
1243 if (ConstMask->isNullValue())
1244 return eraseInstFromFunction(II);
1245
1246 // Use masked off lanes to simplify operands via SimplifyDemandedVectorElts
1247 APInt DemandedElts = possiblyDemandedEltsInMask(ConstMask);
1248 APInt UndefElts(DemandedElts.getBitWidth(), 0);
1249 if (Value *V = SimplifyDemandedVectorElts(II.getOperand(0),
1250 DemandedElts, UndefElts)) {
1251 II.setOperand(0, V);
1252 return &II;
1253 }
1254 if (Value *V = SimplifyDemandedVectorElts(II.getOperand(1),
1255 DemandedElts, UndefElts)) {
1256 II.setOperand(1, V);
1257 return &II;
1258 }
1259
1260 return nullptr;
1261}
1262
Piotr Padlewskic63b4922018-07-12 23:55:20 +00001263/// This function transforms launder.invariant.group and strip.invariant.group
1264/// like:
1265/// launder(launder(%x)) -> launder(%x) (the result is not the argument)
1266/// launder(strip(%x)) -> launder(%x)
1267/// strip(strip(%x)) -> strip(%x) (the result is not the argument)
1268/// strip(launder(%x)) -> strip(%x)
1269/// This is legal because it preserves the most recent information about
1270/// the presence or absence of invariant.group.
1271static Instruction *simplifyInvariantGroupIntrinsic(IntrinsicInst &II,
1272 InstCombiner &IC) {
1273 auto *Arg = II.getArgOperand(0);
1274 auto *StrippedArg = Arg->stripPointerCasts();
1275 auto *StrippedInvariantGroupsArg = Arg->stripPointerCastsAndInvariantGroups();
1276 if (StrippedArg == StrippedInvariantGroupsArg)
1277 return nullptr; // No launders/strips to remove.
1278
1279 Value *Result = nullptr;
1280
1281 if (II.getIntrinsicID() == Intrinsic::launder_invariant_group)
1282 Result = IC.Builder.CreateLaunderInvariantGroup(StrippedInvariantGroupsArg);
1283 else if (II.getIntrinsicID() == Intrinsic::strip_invariant_group)
1284 Result = IC.Builder.CreateStripInvariantGroup(StrippedInvariantGroupsArg);
1285 else
1286 llvm_unreachable(
1287 "simplifyInvariantGroupIntrinsic only handles launder and strip");
1288 if (Result->getType()->getPointerAddressSpace() !=
1289 II.getType()->getPointerAddressSpace())
1290 Result = IC.Builder.CreateAddrSpaceCast(Result, II.getType());
1291 if (Result->getType() != II.getType())
1292 Result = IC.Builder.CreateBitCast(Result, II.getType());
1293
1294 return cast<Instruction>(Result);
1295}
1296
Amaury Sechet763c59d2016-08-18 20:43:50 +00001297static Instruction *foldCttzCtlz(IntrinsicInst &II, InstCombiner &IC) {
1298 assert((II.getIntrinsicID() == Intrinsic::cttz ||
1299 II.getIntrinsicID() == Intrinsic::ctlz) &&
1300 "Expected cttz or ctlz intrinsic");
David Bolvansky5ba60b22019-04-02 20:13:28 +00001301 bool IsTZ = II.getIntrinsicID() == Intrinsic::cttz;
Sanjay Patel8e3ab172016-08-05 22:42:46 +00001302 Value *Op0 = II.getArgOperand(0);
David Bolvansky5ba60b22019-04-02 20:13:28 +00001303 Value *X;
1304 // ctlz(bitreverse(x)) -> cttz(x)
1305 // cttz(bitreverse(x)) -> ctlz(x)
1306 if (match(Op0, m_BitReverse(m_Value(X)))) {
1307 Intrinsic::ID ID = IsTZ ? Intrinsic::ctlz : Intrinsic::cttz;
1308 Function *F = Intrinsic::getDeclaration(II.getModule(), ID, II.getType());
1309 return CallInst::Create(F, {X, II.getArgOperand(1)});
1310 }
Sanjay Patel8e3ab172016-08-05 22:42:46 +00001311
Craig Topper8205a1a2017-05-24 16:53:07 +00001312 KnownBits Known = IC.computeKnownBits(Op0, 0, &II);
Sanjay Patel8e3ab172016-08-05 22:42:46 +00001313
1314 // Create a mask for bits above (ctlz) or below (cttz) the first known one.
Craig Topper8df66c62017-05-12 17:20:30 +00001315 unsigned PossibleZeros = IsTZ ? Known.countMaxTrailingZeros()
1316 : Known.countMaxLeadingZeros();
1317 unsigned DefiniteZeros = IsTZ ? Known.countMinTrailingZeros()
1318 : Known.countMinLeadingZeros();
Sanjay Patel8e3ab172016-08-05 22:42:46 +00001319
1320 // If all bits above (ctlz) or below (cttz) the first known one are known
1321 // zero, this value is constant.
1322 // FIXME: This should be in InstSimplify because we're replacing an
1323 // instruction with a constant.
Craig Topper9474e9b2017-04-27 04:51:25 +00001324 if (PossibleZeros == DefiniteZeros) {
Craig Topper0799ff92017-06-03 18:50:32 +00001325 auto *C = ConstantInt::get(Op0->getType(), DefiniteZeros);
Amaury Sechet763c59d2016-08-18 20:43:50 +00001326 return IC.replaceInstUsesWith(II, C);
1327 }
1328
1329 // If the input to cttz/ctlz is known to be non-zero,
1330 // then change the 'ZeroIsUndef' parameter to 'true'
1331 // because we know the zero behavior can't affect the result.
Craig Topper73ba1c82017-06-07 07:40:37 +00001332 if (!Known.One.isNullValue() ||
Craig Topperd45185f2017-05-26 18:23:57 +00001333 isKnownNonZero(Op0, IC.getDataLayout(), 0, &IC.getAssumptionCache(), &II,
1334 &IC.getDominatorTree())) {
Amaury Sechet763c59d2016-08-18 20:43:50 +00001335 if (!match(II.getArgOperand(1), m_One())) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001336 II.setOperand(1, IC.Builder.getTrue());
Amaury Sechet763c59d2016-08-18 20:43:50 +00001337 return &II;
1338 }
1339 }
Sanjay Patel8e3ab172016-08-05 22:42:46 +00001340
Craig Topper5b173f22017-06-21 16:32:35 +00001341 // Add range metadata since known bits can't completely reflect what we know.
1342 // TODO: Handle splat vectors.
1343 auto *IT = dyn_cast<IntegerType>(Op0->getType());
1344 if (IT && IT->getBitWidth() != 1 && !II.getMetadata(LLVMContext::MD_range)) {
1345 Metadata *LowAndHigh[] = {
1346 ConstantAsMetadata::get(ConstantInt::get(IT, DefiniteZeros)),
1347 ConstantAsMetadata::get(ConstantInt::get(IT, PossibleZeros + 1))};
1348 II.setMetadata(LLVMContext::MD_range,
1349 MDNode::get(II.getContext(), LowAndHigh));
1350 return &II;
1351 }
1352
1353 return nullptr;
1354}
1355
1356static Instruction *foldCtpop(IntrinsicInst &II, InstCombiner &IC) {
1357 assert(II.getIntrinsicID() == Intrinsic::ctpop &&
1358 "Expected ctpop intrinsic");
1359 Value *Op0 = II.getArgOperand(0);
David Bolvansky937720e2019-04-03 08:08:44 +00001360 Value *X;
1361 // ctpop(bitreverse(x)) -> ctpop(x)
1362 // ctpop(bswap(x)) -> ctpop(x)
1363 if (match(Op0, m_BitReverse(m_Value(X))) || match(Op0, m_BSwap(m_Value(X)))) {
1364 II.setOperand(0, X);
1365 return &II;
1366 }
1367
Craig Topper5b173f22017-06-21 16:32:35 +00001368 // FIXME: Try to simplify vectors of integers.
1369 auto *IT = dyn_cast<IntegerType>(Op0->getType());
1370 if (!IT)
1371 return nullptr;
1372
1373 unsigned BitWidth = IT->getBitWidth();
1374 KnownBits Known(BitWidth);
1375 IC.computeKnownBits(Op0, Known, 0, &II);
1376
1377 unsigned MinCount = Known.countMinPopulation();
1378 unsigned MaxCount = Known.countMaxPopulation();
1379
1380 // Add range metadata since known bits can't completely reflect what we know.
1381 if (IT->getBitWidth() != 1 && !II.getMetadata(LLVMContext::MD_range)) {
1382 Metadata *LowAndHigh[] = {
1383 ConstantAsMetadata::get(ConstantInt::get(IT, MinCount)),
1384 ConstantAsMetadata::get(ConstantInt::get(IT, MaxCount + 1))};
1385 II.setMetadata(LLVMContext::MD_range,
1386 MDNode::get(II.getContext(), LowAndHigh));
1387 return &II;
1388 }
1389
Sanjay Patel8e3ab172016-08-05 22:42:46 +00001390 return nullptr;
1391}
1392
Sanjay Patel1ace9932016-02-26 21:04:14 +00001393// TODO: If the x86 backend knew how to convert a bool vector mask back to an
1394// XMM register mask efficiently, we could transform all x86 masked intrinsics
1395// to LLVM masked intrinsics and remove the x86 masked intrinsic defs.
Sanjay Patel98a71502016-02-29 23:16:48 +00001396static Instruction *simplifyX86MaskedLoad(IntrinsicInst &II, InstCombiner &IC) {
1397 Value *Ptr = II.getOperand(0);
1398 Value *Mask = II.getOperand(1);
Sanjay Patel5e5056d2016-04-12 23:16:23 +00001399 Constant *ZeroVec = Constant::getNullValue(II.getType());
Sanjay Patel98a71502016-02-29 23:16:48 +00001400
1401 // Special case a zero mask since that's not a ConstantDataVector.
Sanjay Patel5e5056d2016-04-12 23:16:23 +00001402 // This masked load instruction creates a zero vector.
Sanjay Patel98a71502016-02-29 23:16:48 +00001403 if (isa<ConstantAggregateZero>(Mask))
Sanjay Patel5e5056d2016-04-12 23:16:23 +00001404 return IC.replaceInstUsesWith(II, ZeroVec);
Sanjay Patel98a71502016-02-29 23:16:48 +00001405
1406 auto *ConstMask = dyn_cast<ConstantDataVector>(Mask);
1407 if (!ConstMask)
1408 return nullptr;
1409
1410 // The mask is constant. Convert this x86 intrinsic to the LLVM instrinsic
1411 // to allow target-independent optimizations.
1412
1413 // First, cast the x86 intrinsic scalar pointer to a vector pointer to match
1414 // the LLVM intrinsic definition for the pointer argument.
1415 unsigned AddrSpace = cast<PointerType>(Ptr->getType())->getAddressSpace();
1416 PointerType *VecPtrTy = PointerType::get(II.getType(), AddrSpace);
Craig Topperbb4069e2017-07-07 23:16:26 +00001417 Value *PtrCast = IC.Builder.CreateBitCast(Ptr, VecPtrTy, "castvec");
Sanjay Patel98a71502016-02-29 23:16:48 +00001418
1419 // Second, convert the x86 XMM integer vector mask to a vector of bools based
1420 // on each element's most significant bit (the sign bit).
1421 Constant *BoolMask = getNegativeIsTrueBoolVec(ConstMask);
1422
Sanjay Patel5e5056d2016-04-12 23:16:23 +00001423 // The pass-through vector for an x86 masked load is a zero vector.
1424 CallInst *NewMaskedLoad =
Craig Topperbb4069e2017-07-07 23:16:26 +00001425 IC.Builder.CreateMaskedLoad(PtrCast, 1, BoolMask, ZeroVec);
Sanjay Patel98a71502016-02-29 23:16:48 +00001426 return IC.replaceInstUsesWith(II, NewMaskedLoad);
1427}
1428
1429// TODO: If the x86 backend knew how to convert a bool vector mask back to an
1430// XMM register mask efficiently, we could transform all x86 masked intrinsics
1431// to LLVM masked intrinsics and remove the x86 masked intrinsic defs.
Sanjay Patel1ace9932016-02-26 21:04:14 +00001432static bool simplifyX86MaskedStore(IntrinsicInst &II, InstCombiner &IC) {
1433 Value *Ptr = II.getOperand(0);
1434 Value *Mask = II.getOperand(1);
1435 Value *Vec = II.getOperand(2);
1436
1437 // Special case a zero mask since that's not a ConstantDataVector:
1438 // this masked store instruction does nothing.
1439 if (isa<ConstantAggregateZero>(Mask)) {
1440 IC.eraseInstFromFunction(II);
1441 return true;
1442 }
1443
Sanjay Patelc4acbae2016-03-12 15:16:59 +00001444 // The SSE2 version is too weird (eg, unaligned but non-temporal) to do
1445 // anything else at this level.
1446 if (II.getIntrinsicID() == Intrinsic::x86_sse2_maskmov_dqu)
1447 return false;
1448
Sanjay Patel1ace9932016-02-26 21:04:14 +00001449 auto *ConstMask = dyn_cast<ConstantDataVector>(Mask);
1450 if (!ConstMask)
1451 return false;
1452
1453 // The mask is constant. Convert this x86 intrinsic to the LLVM instrinsic
1454 // to allow target-independent optimizations.
1455
1456 // First, cast the x86 intrinsic scalar pointer to a vector pointer to match
1457 // the LLVM intrinsic definition for the pointer argument.
1458 unsigned AddrSpace = cast<PointerType>(Ptr->getType())->getAddressSpace();
1459 PointerType *VecPtrTy = PointerType::get(Vec->getType(), AddrSpace);
Craig Topperbb4069e2017-07-07 23:16:26 +00001460 Value *PtrCast = IC.Builder.CreateBitCast(Ptr, VecPtrTy, "castvec");
Sanjay Patel1ace9932016-02-26 21:04:14 +00001461
1462 // Second, convert the x86 XMM integer vector mask to a vector of bools based
1463 // on each element's most significant bit (the sign bit).
1464 Constant *BoolMask = getNegativeIsTrueBoolVec(ConstMask);
1465
Craig Topperbb4069e2017-07-07 23:16:26 +00001466 IC.Builder.CreateMaskedStore(Vec, PtrCast, 1, BoolMask);
Sanjay Patel1ace9932016-02-26 21:04:14 +00001467
1468 // 'Replace uses' doesn't work for stores. Erase the original masked store.
1469 IC.eraseInstFromFunction(II);
1470 return true;
1471}
1472
Matt Arsenaultcdb468c2017-02-27 23:08:49 +00001473// Constant fold llvm.amdgcn.fmed3 intrinsics for standard inputs.
1474//
1475// A single NaN input is folded to minnum, so we rely on that folding for
1476// handling NaNs.
1477static APFloat fmed3AMDGCN(const APFloat &Src0, const APFloat &Src1,
1478 const APFloat &Src2) {
1479 APFloat Max3 = maxnum(maxnum(Src0, Src1), Src2);
1480
1481 APFloat::cmpResult Cmp0 = Max3.compare(Src0);
1482 assert(Cmp0 != APFloat::cmpUnordered && "nans handled separately");
1483 if (Cmp0 == APFloat::cmpEqual)
1484 return maxnum(Src1, Src2);
1485
1486 APFloat::cmpResult Cmp1 = Max3.compare(Src1);
1487 assert(Cmp1 != APFloat::cmpUnordered && "nans handled separately");
1488 if (Cmp1 == APFloat::cmpEqual)
1489 return maxnum(Src0, Src2);
1490
1491 return maxnum(Src0, Src1);
1492}
1493
Alexandros Lamprineas52457d32018-05-30 14:38:50 +00001494/// Convert a table lookup to shufflevector if the mask is constant.
1495/// This could benefit tbl1 if the mask is { 7,6,5,4,3,2,1,0 }, in
1496/// which case we could lower the shufflevector with rev64 instructions
1497/// as it's actually a byte reverse.
1498static Value *simplifyNeonTbl1(const IntrinsicInst &II,
1499 InstCombiner::BuilderTy &Builder) {
1500 // Bail out if the mask is not a constant.
1501 auto *C = dyn_cast<Constant>(II.getArgOperand(1));
1502 if (!C)
1503 return nullptr;
1504
1505 auto *VecTy = cast<VectorType>(II.getType());
1506 unsigned NumElts = VecTy->getNumElements();
1507
1508 // Only perform this transformation for <8 x i8> vector types.
1509 if (!VecTy->getElementType()->isIntegerTy(8) || NumElts != 8)
1510 return nullptr;
1511
1512 uint32_t Indexes[8];
1513
1514 for (unsigned I = 0; I < NumElts; ++I) {
1515 Constant *COp = C->getAggregateElement(I);
1516
1517 if (!COp || !isa<ConstantInt>(COp))
1518 return nullptr;
1519
1520 Indexes[I] = cast<ConstantInt>(COp)->getLimitedValue();
1521
1522 // Make sure the mask indices are in range.
1523 if (Indexes[I] >= NumElts)
1524 return nullptr;
1525 }
1526
1527 auto *ShuffleMask = ConstantDataVector::get(II.getContext(),
1528 makeArrayRef(Indexes));
1529 auto *V1 = II.getArgOperand(0);
1530 auto *V2 = Constant::getNullValue(V1->getType());
1531 return Builder.CreateShuffleVector(V1, V2, ShuffleMask);
1532}
1533
Alexandros Lamprineas61f0ba12018-05-31 12:19:18 +00001534/// Convert a vector load intrinsic into a simple llvm load instruction.
1535/// This is beneficial when the underlying object being addressed comes
1536/// from a constant, since we get constant-folding for free.
1537static Value *simplifyNeonVld1(const IntrinsicInst &II,
1538 unsigned MemAlign,
1539 InstCombiner::BuilderTy &Builder) {
1540 auto *IntrAlign = dyn_cast<ConstantInt>(II.getArgOperand(1));
1541
1542 if (!IntrAlign)
1543 return nullptr;
1544
1545 unsigned Alignment = IntrAlign->getLimitedValue() < MemAlign ?
1546 MemAlign : IntrAlign->getLimitedValue();
1547
1548 if (!isPowerOf2_32(Alignment))
1549 return nullptr;
1550
1551 auto *BCastInst = Builder.CreateBitCast(II.getArgOperand(0),
1552 PointerType::get(II.getType(), 0));
James Y Knight14359ef2019-02-01 20:44:24 +00001553 return Builder.CreateAlignedLoad(II.getType(), BCastInst, Alignment);
Alexandros Lamprineas61f0ba12018-05-31 12:19:18 +00001554}
1555
Arnaud A. de Grandmaison333ef382016-05-10 09:24:49 +00001556// Returns true iff the 2 intrinsics have the same operands, limiting the
1557// comparison to the first NumOperands.
1558static bool haveSameOperands(const IntrinsicInst &I, const IntrinsicInst &E,
1559 unsigned NumOperands) {
1560 assert(I.getNumArgOperands() >= NumOperands && "Not enough operands");
1561 assert(E.getNumArgOperands() >= NumOperands && "Not enough operands");
1562 for (unsigned i = 0; i < NumOperands; i++)
1563 if (I.getArgOperand(i) != E.getArgOperand(i))
1564 return false;
1565 return true;
1566}
1567
1568// Remove trivially empty start/end intrinsic ranges, i.e. a start
1569// immediately followed by an end (ignoring debuginfo or other
1570// start/end intrinsics in between). As this handles only the most trivial
1571// cases, tracking the nesting level is not needed:
1572//
1573// call @llvm.foo.start(i1 0) ; &I
1574// call @llvm.foo.start(i1 0)
1575// call @llvm.foo.end(i1 0) ; This one will not be skipped: it will be removed
1576// call @llvm.foo.end(i1 0)
1577static bool removeTriviallyEmptyRange(IntrinsicInst &I, unsigned StartID,
1578 unsigned EndID, InstCombiner &IC) {
1579 assert(I.getIntrinsicID() == StartID &&
1580 "Start intrinsic does not have expected ID");
1581 BasicBlock::iterator BI(I), BE(I.getParent()->end());
1582 for (++BI; BI != BE; ++BI) {
1583 if (auto *E = dyn_cast<IntrinsicInst>(BI)) {
1584 if (isa<DbgInfoIntrinsic>(E) || E->getIntrinsicID() == StartID)
1585 continue;
1586 if (E->getIntrinsicID() == EndID &&
1587 haveSameOperands(I, *E, E->getNumArgOperands())) {
1588 IC.eraseInstFromFunction(*E);
1589 IC.eraseInstFromFunction(I);
1590 return true;
1591 }
1592 }
1593 break;
1594 }
1595
1596 return false;
1597}
1598
Justin Lebar698c31b2017-01-27 00:58:58 +00001599// Convert NVVM intrinsics to target-generic LLVM code where possible.
1600static Instruction *SimplifyNVVMIntrinsic(IntrinsicInst *II, InstCombiner &IC) {
1601 // Each NVVM intrinsic we can simplify can be replaced with one of:
1602 //
1603 // * an LLVM intrinsic,
1604 // * an LLVM cast operation,
1605 // * an LLVM binary operation, or
1606 // * ad-hoc LLVM IR for the particular operation.
1607
1608 // Some transformations are only valid when the module's
1609 // flush-denormals-to-zero (ftz) setting is true/false, whereas other
1610 // transformations are valid regardless of the module's ftz setting.
1611 enum FtzRequirementTy {
1612 FTZ_Any, // Any ftz setting is ok.
1613 FTZ_MustBeOn, // Transformation is valid only if ftz is on.
1614 FTZ_MustBeOff, // Transformation is valid only if ftz is off.
1615 };
1616 // Classes of NVVM intrinsics that can't be replaced one-to-one with a
1617 // target-generic intrinsic, cast op, or binary op but that we can nonetheless
1618 // simplify.
1619 enum SpecialCase {
1620 SPC_Reciprocal,
1621 };
1622
1623 // SimplifyAction is a poor-man's variant (plus an additional flag) that
1624 // represents how to replace an NVVM intrinsic with target-generic LLVM IR.
1625 struct SimplifyAction {
1626 // Invariant: At most one of these Optionals has a value.
1627 Optional<Intrinsic::ID> IID;
1628 Optional<Instruction::CastOps> CastOp;
1629 Optional<Instruction::BinaryOps> BinaryOp;
1630 Optional<SpecialCase> Special;
1631
1632 FtzRequirementTy FtzRequirement = FTZ_Any;
1633
1634 SimplifyAction() = default;
1635
1636 SimplifyAction(Intrinsic::ID IID, FtzRequirementTy FtzReq)
1637 : IID(IID), FtzRequirement(FtzReq) {}
1638
1639 // Cast operations don't have anything to do with FTZ, so we skip that
1640 // argument.
1641 SimplifyAction(Instruction::CastOps CastOp) : CastOp(CastOp) {}
1642
1643 SimplifyAction(Instruction::BinaryOps BinaryOp, FtzRequirementTy FtzReq)
1644 : BinaryOp(BinaryOp), FtzRequirement(FtzReq) {}
1645
1646 SimplifyAction(SpecialCase Special, FtzRequirementTy FtzReq)
1647 : Special(Special), FtzRequirement(FtzReq) {}
1648 };
1649
1650 // Try to generate a SimplifyAction describing how to replace our
1651 // IntrinsicInstr with target-generic LLVM IR.
1652 const SimplifyAction Action = [II]() -> SimplifyAction {
1653 switch (II->getIntrinsicID()) {
Justin Lebar698c31b2017-01-27 00:58:58 +00001654 // NVVM intrinsics that map directly to LLVM intrinsics.
1655 case Intrinsic::nvvm_ceil_d:
1656 return {Intrinsic::ceil, FTZ_Any};
1657 case Intrinsic::nvvm_ceil_f:
1658 return {Intrinsic::ceil, FTZ_MustBeOff};
1659 case Intrinsic::nvvm_ceil_ftz_f:
1660 return {Intrinsic::ceil, FTZ_MustBeOn};
1661 case Intrinsic::nvvm_fabs_d:
1662 return {Intrinsic::fabs, FTZ_Any};
1663 case Intrinsic::nvvm_fabs_f:
1664 return {Intrinsic::fabs, FTZ_MustBeOff};
1665 case Intrinsic::nvvm_fabs_ftz_f:
1666 return {Intrinsic::fabs, FTZ_MustBeOn};
1667 case Intrinsic::nvvm_floor_d:
1668 return {Intrinsic::floor, FTZ_Any};
1669 case Intrinsic::nvvm_floor_f:
1670 return {Intrinsic::floor, FTZ_MustBeOff};
1671 case Intrinsic::nvvm_floor_ftz_f:
1672 return {Intrinsic::floor, FTZ_MustBeOn};
1673 case Intrinsic::nvvm_fma_rn_d:
1674 return {Intrinsic::fma, FTZ_Any};
1675 case Intrinsic::nvvm_fma_rn_f:
1676 return {Intrinsic::fma, FTZ_MustBeOff};
1677 case Intrinsic::nvvm_fma_rn_ftz_f:
1678 return {Intrinsic::fma, FTZ_MustBeOn};
1679 case Intrinsic::nvvm_fmax_d:
1680 return {Intrinsic::maxnum, FTZ_Any};
1681 case Intrinsic::nvvm_fmax_f:
1682 return {Intrinsic::maxnum, FTZ_MustBeOff};
1683 case Intrinsic::nvvm_fmax_ftz_f:
1684 return {Intrinsic::maxnum, FTZ_MustBeOn};
1685 case Intrinsic::nvvm_fmin_d:
1686 return {Intrinsic::minnum, FTZ_Any};
1687 case Intrinsic::nvvm_fmin_f:
1688 return {Intrinsic::minnum, FTZ_MustBeOff};
1689 case Intrinsic::nvvm_fmin_ftz_f:
1690 return {Intrinsic::minnum, FTZ_MustBeOn};
1691 case Intrinsic::nvvm_round_d:
1692 return {Intrinsic::round, FTZ_Any};
1693 case Intrinsic::nvvm_round_f:
1694 return {Intrinsic::round, FTZ_MustBeOff};
1695 case Intrinsic::nvvm_round_ftz_f:
1696 return {Intrinsic::round, FTZ_MustBeOn};
1697 case Intrinsic::nvvm_sqrt_rn_d:
1698 return {Intrinsic::sqrt, FTZ_Any};
1699 case Intrinsic::nvvm_sqrt_f:
1700 // nvvm_sqrt_f is a special case. For most intrinsics, foo_ftz_f is the
1701 // ftz version, and foo_f is the non-ftz version. But nvvm_sqrt_f adopts
1702 // the ftz-ness of the surrounding code. sqrt_rn_f and sqrt_rn_ftz_f are
1703 // the versions with explicit ftz-ness.
1704 return {Intrinsic::sqrt, FTZ_Any};
1705 case Intrinsic::nvvm_sqrt_rn_f:
1706 return {Intrinsic::sqrt, FTZ_MustBeOff};
1707 case Intrinsic::nvvm_sqrt_rn_ftz_f:
1708 return {Intrinsic::sqrt, FTZ_MustBeOn};
1709 case Intrinsic::nvvm_trunc_d:
1710 return {Intrinsic::trunc, FTZ_Any};
1711 case Intrinsic::nvvm_trunc_f:
1712 return {Intrinsic::trunc, FTZ_MustBeOff};
1713 case Intrinsic::nvvm_trunc_ftz_f:
1714 return {Intrinsic::trunc, FTZ_MustBeOn};
1715
1716 // NVVM intrinsics that map to LLVM cast operations.
1717 //
1718 // Note that llvm's target-generic conversion operators correspond to the rz
1719 // (round to zero) versions of the nvvm conversion intrinsics, even though
1720 // most everything else here uses the rn (round to nearest even) nvvm ops.
1721 case Intrinsic::nvvm_d2i_rz:
1722 case Intrinsic::nvvm_f2i_rz:
1723 case Intrinsic::nvvm_d2ll_rz:
1724 case Intrinsic::nvvm_f2ll_rz:
1725 return {Instruction::FPToSI};
1726 case Intrinsic::nvvm_d2ui_rz:
1727 case Intrinsic::nvvm_f2ui_rz:
1728 case Intrinsic::nvvm_d2ull_rz:
1729 case Intrinsic::nvvm_f2ull_rz:
1730 return {Instruction::FPToUI};
1731 case Intrinsic::nvvm_i2d_rz:
1732 case Intrinsic::nvvm_i2f_rz:
1733 case Intrinsic::nvvm_ll2d_rz:
1734 case Intrinsic::nvvm_ll2f_rz:
1735 return {Instruction::SIToFP};
1736 case Intrinsic::nvvm_ui2d_rz:
1737 case Intrinsic::nvvm_ui2f_rz:
1738 case Intrinsic::nvvm_ull2d_rz:
1739 case Intrinsic::nvvm_ull2f_rz:
1740 return {Instruction::UIToFP};
1741
1742 // NVVM intrinsics that map to LLVM binary ops.
1743 case Intrinsic::nvvm_add_rn_d:
1744 return {Instruction::FAdd, FTZ_Any};
1745 case Intrinsic::nvvm_add_rn_f:
1746 return {Instruction::FAdd, FTZ_MustBeOff};
1747 case Intrinsic::nvvm_add_rn_ftz_f:
1748 return {Instruction::FAdd, FTZ_MustBeOn};
1749 case Intrinsic::nvvm_mul_rn_d:
1750 return {Instruction::FMul, FTZ_Any};
1751 case Intrinsic::nvvm_mul_rn_f:
1752 return {Instruction::FMul, FTZ_MustBeOff};
1753 case Intrinsic::nvvm_mul_rn_ftz_f:
1754 return {Instruction::FMul, FTZ_MustBeOn};
1755 case Intrinsic::nvvm_div_rn_d:
1756 return {Instruction::FDiv, FTZ_Any};
1757 case Intrinsic::nvvm_div_rn_f:
1758 return {Instruction::FDiv, FTZ_MustBeOff};
1759 case Intrinsic::nvvm_div_rn_ftz_f:
1760 return {Instruction::FDiv, FTZ_MustBeOn};
1761
1762 // The remainder of cases are NVVM intrinsics that map to LLVM idioms, but
1763 // need special handling.
1764 //
Hiroshi Inoue0ca79dc2017-07-11 06:04:59 +00001765 // We seem to be missing intrinsics for rcp.approx.{ftz.}f32, which is just
Justin Lebar698c31b2017-01-27 00:58:58 +00001766 // as well.
1767 case Intrinsic::nvvm_rcp_rn_d:
1768 return {SPC_Reciprocal, FTZ_Any};
1769 case Intrinsic::nvvm_rcp_rn_f:
1770 return {SPC_Reciprocal, FTZ_MustBeOff};
1771 case Intrinsic::nvvm_rcp_rn_ftz_f:
1772 return {SPC_Reciprocal, FTZ_MustBeOn};
1773
1774 // We do not currently simplify intrinsics that give an approximate answer.
1775 // These include:
1776 //
1777 // - nvvm_cos_approx_{f,ftz_f}
1778 // - nvvm_ex2_approx_{d,f,ftz_f}
1779 // - nvvm_lg2_approx_{d,f,ftz_f}
1780 // - nvvm_sin_approx_{f,ftz_f}
1781 // - nvvm_sqrt_approx_{f,ftz_f}
1782 // - nvvm_rsqrt_approx_{d,f,ftz_f}
1783 // - nvvm_div_approx_{ftz_d,ftz_f,f}
1784 // - nvvm_rcp_approx_ftz_d
1785 //
1786 // Ideally we'd encode them as e.g. "fast call @llvm.cos", where "fast"
1787 // means that fastmath is enabled in the intrinsic. Unfortunately only
1788 // binary operators (currently) have a fastmath bit in SelectionDAG, so this
1789 // information gets lost and we can't select on it.
1790 //
1791 // TODO: div and rcp are lowered to a binary op, so these we could in theory
1792 // lower them to "fast fdiv".
1793
1794 default:
1795 return {};
1796 }
1797 }();
1798
1799 // If Action.FtzRequirementTy is not satisfied by the module's ftz state, we
1800 // can bail out now. (Notice that in the case that IID is not an NVVM
1801 // intrinsic, we don't have to look up any module metadata, as
1802 // FtzRequirementTy will be FTZ_Any.)
1803 if (Action.FtzRequirement != FTZ_Any) {
1804 bool FtzEnabled =
1805 II->getFunction()->getFnAttribute("nvptx-f32ftz").getValueAsString() ==
1806 "true";
1807
1808 if (FtzEnabled != (Action.FtzRequirement == FTZ_MustBeOn))
1809 return nullptr;
1810 }
1811
1812 // Simplify to target-generic intrinsic.
1813 if (Action.IID) {
1814 SmallVector<Value *, 4> Args(II->arg_operands());
1815 // All the target-generic intrinsics currently of interest to us have one
1816 // type argument, equal to that of the nvvm intrinsic's argument.
Justin Lebare3ac0fb2017-01-27 01:49:39 +00001817 Type *Tys[] = {II->getArgOperand(0)->getType()};
Justin Lebar698c31b2017-01-27 00:58:58 +00001818 return CallInst::Create(
1819 Intrinsic::getDeclaration(II->getModule(), *Action.IID, Tys), Args);
1820 }
1821
1822 // Simplify to target-generic binary op.
1823 if (Action.BinaryOp)
1824 return BinaryOperator::Create(*Action.BinaryOp, II->getArgOperand(0),
1825 II->getArgOperand(1), II->getName());
1826
1827 // Simplify to target-generic cast op.
1828 if (Action.CastOp)
1829 return CastInst::Create(*Action.CastOp, II->getArgOperand(0), II->getType(),
1830 II->getName());
1831
1832 // All that's left are the special cases.
1833 if (!Action.Special)
1834 return nullptr;
1835
1836 switch (*Action.Special) {
1837 case SPC_Reciprocal:
1838 // Simplify reciprocal.
1839 return BinaryOperator::Create(
1840 Instruction::FDiv, ConstantFP::get(II->getArgOperand(0)->getType(), 1),
1841 II->getArgOperand(0), II->getName());
1842 }
Justin Lebar25ebe2d2017-01-27 02:04:07 +00001843 llvm_unreachable("All SpecialCase enumerators should be handled in switch.");
Justin Lebar698c31b2017-01-27 00:58:58 +00001844}
1845
Arnaud A. de Grandmaison333ef382016-05-10 09:24:49 +00001846Instruction *InstCombiner::visitVAStartInst(VAStartInst &I) {
1847 removeTriviallyEmptyRange(I, Intrinsic::vastart, Intrinsic::vaend, *this);
1848 return nullptr;
1849}
1850
1851Instruction *InstCombiner::visitVACopyInst(VACopyInst &I) {
1852 removeTriviallyEmptyRange(I, Intrinsic::vacopy, Intrinsic::vaend, *this);
1853 return nullptr;
1854}
1855
Sanjay Patel790af912018-11-26 22:00:41 +00001856static Instruction *canonicalizeConstantArg0ToArg1(CallInst &Call) {
1857 assert(Call.getNumArgOperands() > 1 && "Need at least 2 args to swap");
1858 Value *Arg0 = Call.getArgOperand(0), *Arg1 = Call.getArgOperand(1);
1859 if (isa<Constant>(Arg0) && !isa<Constant>(Arg1)) {
1860 Call.setArgOperand(0, Arg1);
1861 Call.setArgOperand(1, Arg0);
1862 return &Call;
1863 }
1864 return nullptr;
1865}
1866
Nikita Popov884feb12019-03-06 18:30:00 +00001867Instruction *InstCombiner::foldIntrinsicWithOverflowCommon(IntrinsicInst *II) {
1868 OverflowCheckFlavor OCF =
1869 IntrinsicIDToOverflowCheckFlavor(II->getIntrinsicID());
1870 assert(OCF != OCF_INVALID && "unexpected!");
1871
1872 Value *OperationResult = nullptr;
1873 Constant *OverflowResult = nullptr;
1874 if (OptimizeOverflowCheck(OCF, II->getArgOperand(0), II->getArgOperand(1),
1875 *II, OperationResult, OverflowResult))
1876 return CreateOverflowTuple(II, OperationResult, OverflowResult);
1877 return nullptr;
1878}
1879
Sanjay Patelcd4377c2016-01-20 22:24:38 +00001880/// CallInst simplification. This mostly only handles folding of intrinsic
Craig Topperc1892ec2019-01-31 17:23:29 +00001881/// instructions. For normal calls, it allows visitCallBase to do the heavy
Sanjay Patelcd4377c2016-01-20 22:24:38 +00001882/// lifting.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001883Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Philip Reames7a6db4f2017-12-27 00:16:12 +00001884 if (Value *V = SimplifyCall(&CI, SQ.getWithInstruction(&CI)))
Sanjay Patel4b198802016-02-01 22:23:39 +00001885 return replaceInstUsesWith(CI, V);
David Majnemer15032582015-05-22 03:56:46 +00001886
Justin Bogner99798402016-08-05 01:06:44 +00001887 if (isFreeCall(&CI, &TLI))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001888 return visitFree(CI);
1889
1890 // If the caller function is nounwind, mark the call as nounwind, even if the
1891 // callee isn't.
Sanjay Patel5a470952016-08-11 15:16:06 +00001892 if (CI.getFunction()->doesNotThrow() && !CI.doesNotThrow()) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001893 CI.setDoesNotThrow();
1894 return &CI;
1895 }
Jim Grosbach7815f562012-02-03 00:07:04 +00001896
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001897 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
Craig Topperc1892ec2019-01-31 17:23:29 +00001898 if (!II) return visitCallBase(CI);
Gabor Greif589a0b92010-06-24 12:58:35 +00001899
Craig Topper784929d2019-02-08 20:48:56 +00001900 // Intrinsics cannot occur in an invoke or a callbr, so handle them here
1901 // instead of in visitCallBase.
Daniel Neilson8f30ec62018-05-11 14:30:02 +00001902 if (auto *MI = dyn_cast<AnyMemIntrinsic>(II)) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001903 bool Changed = false;
1904
1905 // memmove/cpy/set of zero bytes is a noop.
1906 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
Chris Lattnerc663a672010-10-01 05:51:02 +00001907 if (NumBytes->isNullValue())
Sanjay Patel4b198802016-02-01 22:23:39 +00001908 return eraseInstFromFunction(CI);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001909
1910 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
1911 if (CI->getZExtValue() == 1) {
1912 // Replace the instruction with just byte operations. We would
1913 // transform other cases to loads/stores, but we don't know if
1914 // alignment is sufficient.
1915 }
1916 }
Jim Grosbach7815f562012-02-03 00:07:04 +00001917
Chris Lattnerc663a672010-10-01 05:51:02 +00001918 // No other transformations apply to volatile transfers.
Daniel Neilson8f30ec62018-05-11 14:30:02 +00001919 if (auto *M = dyn_cast<MemIntrinsic>(MI))
1920 if (M->isVolatile())
1921 return nullptr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001922
1923 // If we have a memmove and the source operation is a constant global,
1924 // then the source and dest pointers can't alias, so we can change this
1925 // into a call to memcpy.
Daniel Neilson8f30ec62018-05-11 14:30:02 +00001926 if (auto *MMI = dyn_cast<AnyMemMoveInst>(MI)) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001927 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
1928 if (GVSrc->isConstant()) {
Sanjay Patelaf674fb2015-12-14 17:24:23 +00001929 Module *M = CI.getModule();
Daniel Neilson8f30ec62018-05-11 14:30:02 +00001930 Intrinsic::ID MemCpyID =
1931 isa<AtomicMemMoveInst>(MMI)
1932 ? Intrinsic::memcpy_element_unordered_atomic
1933 : Intrinsic::memcpy;
Jay Foadb804a2b2011-07-12 14:06:48 +00001934 Type *Tys[3] = { CI.getArgOperand(0)->getType(),
1935 CI.getArgOperand(1)->getType(),
1936 CI.getArgOperand(2)->getType() };
Benjamin Kramere6e19332011-07-14 17:45:39 +00001937 CI.setCalledFunction(Intrinsic::getDeclaration(M, MemCpyID, Tys));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001938 Changed = true;
1939 }
1940 }
1941
Daniel Neilson8f30ec62018-05-11 14:30:02 +00001942 if (AnyMemTransferInst *MTI = dyn_cast<AnyMemTransferInst>(MI)) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001943 // memmove(x,x,size) -> noop.
1944 if (MTI->getSource() == MTI->getDest())
Sanjay Patel4b198802016-02-01 22:23:39 +00001945 return eraseInstFromFunction(CI);
Eric Christopher7258dcd2010-04-16 23:37:20 +00001946 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001947
Eric Christopher7258dcd2010-04-16 23:37:20 +00001948 // If we can determine a pointer alignment that is bigger than currently
1949 // set, update the alignment.
Daniel Neilson8f30ec62018-05-11 14:30:02 +00001950 if (auto *MTI = dyn_cast<AnyMemTransferInst>(MI)) {
1951 if (Instruction *I = SimplifyAnyMemTransfer(MTI))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001952 return I;
Daniel Neilsonf6651d42018-05-11 20:04:50 +00001953 } else if (auto *MSI = dyn_cast<AnyMemSetInst>(MI)) {
1954 if (Instruction *I = SimplifyAnyMemSet(MSI))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001955 return I;
1956 }
Gabor Greif590d95e2010-06-24 13:42:49 +00001957
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001958 if (Changed) return II;
1959 }
Jim Grosbach7815f562012-02-03 00:07:04 +00001960
Philip Reames68a2e4d2019-03-15 19:54:06 +00001961 // For vector result intrinsics, use the generic demanded vector support.
Philip Reamesc71e9962019-01-30 19:21:11 +00001962 if (II->getType()->isVectorTy()) {
1963 auto VWidth = II->getType()->getVectorNumElements();
1964 APInt UndefElts(VWidth, 0);
1965 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
1966 if (Value *V = SimplifyDemandedVectorElts(II, AllOnesEltMask, UndefElts)) {
1967 if (V != II)
1968 return replaceInstUsesWith(*II, V);
1969 return II;
1970 }
1971 }
1972
Justin Lebar698c31b2017-01-27 00:58:58 +00001973 if (Instruction *I = SimplifyNVVMIntrinsic(II, *this))
1974 return I;
1975
Sanjay Patel1c600c62016-01-20 16:41:43 +00001976 auto SimplifyDemandedVectorEltsLow = [this](Value *Op, unsigned Width,
1977 unsigned DemandedWidth) {
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001978 APInt UndefElts(Width, 0);
1979 APInt DemandedElts = APInt::getLowBitsSet(Width, DemandedWidth);
1980 return SimplifyDemandedVectorElts(Op, DemandedElts, UndefElts);
1981 };
1982
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001983 switch (II->getIntrinsicID()) {
1984 default: break;
George Burgess IV3f089142016-12-20 23:46:36 +00001985 case Intrinsic::objectsize:
Erik Pilkington600e9de2019-01-30 20:34:35 +00001986 if (Value *V = lowerObjectSizeCall(II, DL, &TLI, /*MustSucceed=*/false))
1987 return replaceInstUsesWith(CI, V);
Craig Topperf40110f2014-04-25 05:29:35 +00001988 return nullptr;
Michael Ilseman536cc322012-12-13 03:13:36 +00001989 case Intrinsic::bswap: {
1990 Value *IIOperand = II->getArgOperand(0);
Craig Topperf40110f2014-04-25 05:29:35 +00001991 Value *X = nullptr;
Michael Ilseman536cc322012-12-13 03:13:36 +00001992
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001993 // bswap(trunc(bswap(x))) -> trunc(lshr(x, c))
Michael Ilseman536cc322012-12-13 03:13:36 +00001994 if (match(IIOperand, m_Trunc(m_BSwap(m_Value(X))))) {
1995 unsigned C = X->getType()->getPrimitiveSizeInBits() -
1996 IIOperand->getType()->getPrimitiveSizeInBits();
1997 Value *CV = ConstantInt::get(X->getType(), C);
Craig Topperbb4069e2017-07-07 23:16:26 +00001998 Value *V = Builder.CreateLShr(X, CV);
Michael Ilseman536cc322012-12-13 03:13:36 +00001999 return new TruncInst(V, IIOperand->getType());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002000 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002001 break;
Michael Ilseman536cc322012-12-13 03:13:36 +00002002 }
Sanjay Patelb695c552016-02-01 17:00:10 +00002003 case Intrinsic::masked_load:
Craig Topperbb4069e2017-07-07 23:16:26 +00002004 if (Value *SimplifiedMaskedOp = simplifyMaskedLoad(*II, Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00002005 return replaceInstUsesWith(CI, SimplifiedMaskedOp);
Sanjay Patelb695c552016-02-01 17:00:10 +00002006 break;
Sanjay Patel04f792b2016-02-01 19:39:52 +00002007 case Intrinsic::masked_store:
Philip Reamese4588bb2019-03-20 18:44:58 +00002008 return simplifyMaskedStore(*II);
Sanjay Patel103ab7d2016-02-01 22:10:26 +00002009 case Intrinsic::masked_gather:
2010 return simplifyMaskedGather(*II, *this);
2011 case Intrinsic::masked_scatter:
Philip Reamese4588bb2019-03-20 18:44:58 +00002012 return simplifyMaskedScatter(*II);
Piotr Padlewskic63b4922018-07-12 23:55:20 +00002013 case Intrinsic::launder_invariant_group:
2014 case Intrinsic::strip_invariant_group:
2015 if (auto *SkippedBarrier = simplifyInvariantGroupIntrinsic(*II, *this))
2016 return replaceInstUsesWith(*II, SkippedBarrier);
2017 break;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002018 case Intrinsic::powi:
Gabor Greif589a0b92010-06-24 12:58:35 +00002019 if (ConstantInt *Power = dyn_cast<ConstantInt>(II->getArgOperand(1))) {
Philip Reames5000ba62017-12-27 01:14:30 +00002020 // 0 and 1 are handled in instsimplify
2021
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002022 // powi(x, -1) -> 1/x
Craig Topper79ab6432017-07-06 18:39:47 +00002023 if (Power->isMinusOne())
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002024 return BinaryOperator::CreateFDiv(ConstantFP::get(CI.getType(), 1.0),
Gabor Greif589a0b92010-06-24 12:58:35 +00002025 II->getArgOperand(0));
Philip Reamescd13a662017-12-27 01:30:12 +00002026 // powi(x, 2) -> x*x
2027 if (Power->equalsInt(2))
2028 return BinaryOperator::CreateFMul(II->getArgOperand(0),
2029 II->getArgOperand(0));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002030 }
2031 break;
Jim Grosbach7815f562012-02-03 00:07:04 +00002032
Sanjay Patel8e3ab172016-08-05 22:42:46 +00002033 case Intrinsic::cttz:
2034 case Intrinsic::ctlz:
Amaury Sechet763c59d2016-08-18 20:43:50 +00002035 if (auto *I = foldCttzCtlz(*II, *this))
2036 return I;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002037 break;
Sanjoy Dasb0984472015-04-08 04:27:22 +00002038
Craig Topper5b173f22017-06-21 16:32:35 +00002039 case Intrinsic::ctpop:
2040 if (auto *I = foldCtpop(*II, *this))
2041 return I;
2042 break;
2043
Sanjay Patela1395642018-11-13 23:27:23 +00002044 case Intrinsic::fshl:
2045 case Intrinsic::fshr: {
Sanjay Patelb3bcd952019-03-17 19:08:00 +00002046 Value *Op0 = II->getArgOperand(0), *Op1 = II->getArgOperand(1);
2047 Type *Ty = II->getType();
2048 unsigned BitWidth = Ty->getScalarSizeInBits();
Sanjay Patelde1d5d32019-03-14 19:22:08 +00002049 Constant *ShAmtC;
2050 if (match(II->getArgOperand(2), m_Constant(ShAmtC)) &&
2051 !isa<ConstantExpr>(ShAmtC) && !ShAmtC->containsConstantExpression()) {
Sanjay Patelb3bcd952019-03-17 19:08:00 +00002052 // Canonicalize a shift amount constant operand to modulo the bit-width.
2053 Constant *WidthC = ConstantInt::get(Ty, BitWidth);
Sanjay Patelde1d5d32019-03-14 19:22:08 +00002054 Constant *ModuloC = ConstantExpr::getURem(ShAmtC, WidthC);
2055 if (ModuloC != ShAmtC) {
2056 II->setArgOperand(2, ModuloC);
2057 return II;
2058 }
Sanjay Patel60633932019-03-18 14:27:51 +00002059 assert(ConstantExpr::getICmp(ICmpInst::ICMP_UGT, WidthC, ShAmtC) ==
2060 ConstantInt::getTrue(CmpInst::makeCmpResultType(Ty)) &&
2061 "Shift amount expected to be modulo bitwidth");
2062
Sanjay Patel84de8a32019-03-18 14:10:11 +00002063 // Canonicalize funnel shift right by constant to funnel shift left. This
2064 // is not entirely arbitrary. For historical reasons, the backend may
2065 // recognize rotate left patterns but miss rotate right patterns.
2066 if (II->getIntrinsicID() == Intrinsic::fshr) {
2067 // fshr X, Y, C --> fshl X, Y, (BitWidth - C)
Sanjay Patelb3bcd952019-03-17 19:08:00 +00002068 Constant *LeftShiftC = ConstantExpr::getSub(WidthC, ShAmtC);
2069 Module *Mod = II->getModule();
2070 Function *Fshl = Intrinsic::getDeclaration(Mod, Intrinsic::fshl, Ty);
Sanjay Patel84de8a32019-03-18 14:10:11 +00002071 return CallInst::Create(Fshl, { Op0, Op1, LeftShiftC });
Sanjay Patelb3bcd952019-03-17 19:08:00 +00002072 }
Sanjay Patel84de8a32019-03-18 14:10:11 +00002073 assert(II->getIntrinsicID() == Intrinsic::fshl &&
2074 "All funnel shifts by simple constants should go left");
Nikita Popov6e81d422018-11-23 22:45:08 +00002075
Sanjay Patel60633932019-03-18 14:27:51 +00002076 // fshl(X, 0, C) --> shl X, C
2077 // fshl(X, undef, C) --> shl X, C
2078 if (match(Op1, m_ZeroInt()) || match(Op1, m_Undef()))
2079 return BinaryOperator::CreateShl(Op0, ShAmtC);
Nikita Popov6e81d422018-11-23 22:45:08 +00002080
Sanjay Patel60633932019-03-18 14:27:51 +00002081 // fshl(0, X, C) --> lshr X, (BW-C)
2082 // fshl(undef, X, C) --> lshr X, (BW-C)
2083 if (match(Op0, m_ZeroInt()) || match(Op0, m_Undef()))
2084 return BinaryOperator::CreateLShr(Op1,
2085 ConstantExpr::getSub(WidthC, ShAmtC));
Nikita Popov6e81d422018-11-23 22:45:08 +00002086 }
2087
Sanjay Patela1395642018-11-13 23:27:23 +00002088 // The shift amount (operand 2) of a funnel shift is modulo the bitwidth,
2089 // so only the low bits of the shift amount are demanded if the bitwidth is
2090 // a power-of-2.
Sanjay Patela1395642018-11-13 23:27:23 +00002091 if (!isPowerOf2_32(BitWidth))
2092 break;
2093 APInt Op2Demanded = APInt::getLowBitsSet(BitWidth, Log2_32_Ceil(BitWidth));
2094 KnownBits Op2Known(BitWidth);
2095 if (SimplifyDemandedBits(II, 2, Op2Demanded, Op2Known))
2096 return &CI;
2097 break;
2098 }
Nikita Popov37cf25c2019-03-20 18:00:27 +00002099 case Intrinsic::uadd_with_overflow:
Nikita Popov884feb12019-03-06 18:30:00 +00002100 case Intrinsic::sadd_with_overflow: {
2101 if (Instruction *I = canonicalizeConstantArg0ToArg1(CI))
2102 return I;
2103 if (Instruction *I = foldIntrinsicWithOverflowCommon(II))
2104 return I;
2105
2106 // Given 2 constant operands whose sum does not overflow:
Nikita Popov37cf25c2019-03-20 18:00:27 +00002107 // uaddo (X +nuw C0), C1 -> uaddo X, C0 + C1
Nikita Popov884feb12019-03-06 18:30:00 +00002108 // saddo (X +nsw C0), C1 -> saddo X, C0 + C1
2109 Value *X;
2110 const APInt *C0, *C1;
2111 Value *Arg0 = II->getArgOperand(0);
2112 Value *Arg1 = II->getArgOperand(1);
Nikita Popov37cf25c2019-03-20 18:00:27 +00002113 bool IsSigned = II->getIntrinsicID() == Intrinsic::sadd_with_overflow;
2114 bool HasNWAdd = IsSigned ? match(Arg0, m_NSWAdd(m_Value(X), m_APInt(C0)))
2115 : match(Arg0, m_NUWAdd(m_Value(X), m_APInt(C0)));
2116 if (HasNWAdd && match(Arg1, m_APInt(C1))) {
Nikita Popov884feb12019-03-06 18:30:00 +00002117 bool Overflow;
Nikita Popov37cf25c2019-03-20 18:00:27 +00002118 APInt NewC =
2119 IsSigned ? C1->sadd_ov(*C0, Overflow) : C1->uadd_ov(*C0, Overflow);
Nikita Popov884feb12019-03-06 18:30:00 +00002120 if (!Overflow)
2121 return replaceInstUsesWith(
2122 *II, Builder.CreateBinaryIntrinsic(
Nikita Popov37cf25c2019-03-20 18:00:27 +00002123 II->getIntrinsicID(), X,
Nikita Popov884feb12019-03-06 18:30:00 +00002124 ConstantInt::get(Arg1->getType(), NewC)));
2125 }
Nikita Popov884feb12019-03-06 18:30:00 +00002126 break;
2127 }
Nikita Popov7a543c32019-04-10 16:27:36 +00002128
Nick Lewyckyabe2cc12015-04-13 19:17:37 +00002129 case Intrinsic::umul_with_overflow:
2130 case Intrinsic::smul_with_overflow:
Sanjay Patel790af912018-11-26 22:00:41 +00002131 if (Instruction *I = canonicalizeConstantArg0ToArg1(CI))
2132 return I;
Justin Bognercd1d5aa2016-08-17 20:30:52 +00002133 LLVM_FALLTHROUGH;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002134
Nick Lewyckyabe2cc12015-04-13 19:17:37 +00002135 case Intrinsic::usub_with_overflow:
Nikita Popov7a543c32019-04-10 16:27:36 +00002136 if (Instruction *I = foldIntrinsicWithOverflowCommon(II))
2137 return I;
2138 break;
2139
Nick Lewyckyabe2cc12015-04-13 19:17:37 +00002140 case Intrinsic::ssub_with_overflow: {
Nikita Popov884feb12019-03-06 18:30:00 +00002141 if (Instruction *I = foldIntrinsicWithOverflowCommon(II))
2142 return I;
Benjamin Kramera420df22014-07-04 10:22:21 +00002143
Nikita Popov7a543c32019-04-10 16:27:36 +00002144 Constant *C;
2145 Value *Arg0 = II->getArgOperand(0);
2146 Value *Arg1 = II->getArgOperand(1);
2147 // Given a constant C that is not the minimum signed value
2148 // for an integer of a given bit width:
2149 //
2150 // ssubo X, C -> saddo X, -C
2151 if (match(Arg1, m_Constant(C)) && C->isNotMinSignedValue()) {
2152 Value *NegVal = ConstantExpr::getNeg(C);
2153 // Build a saddo call that is equivalent to the discovered
2154 // ssubo call.
2155 return replaceInstUsesWith(
2156 *II, Builder.CreateBinaryIntrinsic(Intrinsic::sadd_with_overflow,
2157 Arg0, NegVal));
2158 }
2159
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002160 break;
Erik Eckstein096ff7d2014-12-11 08:02:30 +00002161 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002162
Nikita Popov085d24a2018-11-28 16:36:52 +00002163 case Intrinsic::uadd_sat:
2164 case Intrinsic::sadd_sat:
2165 if (Instruction *I = canonicalizeConstantArg0ToArg1(CI))
2166 return I;
Nikita Popov78a92952018-11-28 16:36:59 +00002167 LLVM_FALLTHROUGH;
2168 case Intrinsic::usub_sat:
2169 case Intrinsic::ssub_sat: {
2170 Value *Arg0 = II->getArgOperand(0);
2171 Value *Arg1 = II->getArgOperand(1);
2172 Intrinsic::ID IID = II->getIntrinsicID();
2173
2174 // Make use of known overflow information.
2175 OverflowResult OR;
2176 switch (IID) {
2177 default:
2178 llvm_unreachable("Unexpected intrinsic!");
2179 case Intrinsic::uadd_sat:
2180 OR = computeOverflowForUnsignedAdd(Arg0, Arg1, II);
2181 if (OR == OverflowResult::NeverOverflows)
2182 return BinaryOperator::CreateNUWAdd(Arg0, Arg1);
2183 if (OR == OverflowResult::AlwaysOverflows)
2184 return replaceInstUsesWith(*II,
2185 ConstantInt::getAllOnesValue(II->getType()));
2186 break;
2187 case Intrinsic::usub_sat:
2188 OR = computeOverflowForUnsignedSub(Arg0, Arg1, II);
2189 if (OR == OverflowResult::NeverOverflows)
2190 return BinaryOperator::CreateNUWSub(Arg0, Arg1);
2191 if (OR == OverflowResult::AlwaysOverflows)
2192 return replaceInstUsesWith(*II,
2193 ConstantInt::getNullValue(II->getType()));
2194 break;
2195 case Intrinsic::sadd_sat:
2196 if (willNotOverflowSignedAdd(Arg0, Arg1, *II))
2197 return BinaryOperator::CreateNSWAdd(Arg0, Arg1);
2198 break;
2199 case Intrinsic::ssub_sat:
2200 if (willNotOverflowSignedSub(Arg0, Arg1, *II))
2201 return BinaryOperator::CreateNSWSub(Arg0, Arg1);
2202 break;
2203 }
Nikita Popov42f89982018-11-28 16:37:09 +00002204
2205 // ssub.sat(X, C) -> sadd.sat(X, -C) if C != MIN
Nikita Popov0c5d6cc2018-12-01 10:58:34 +00002206 Constant *C;
2207 if (IID == Intrinsic::ssub_sat && match(Arg1, m_Constant(C)) &&
2208 C->isNotMinSignedValue()) {
2209 Value *NegVal = ConstantExpr::getNeg(C);
Nikita Popov42f89982018-11-28 16:37:09 +00002210 return replaceInstUsesWith(
2211 *II, Builder.CreateBinaryIntrinsic(
2212 Intrinsic::sadd_sat, Arg0, NegVal));
2213 }
Nikita Popov8d63aed2018-11-28 16:37:15 +00002214
2215 // sat(sat(X + Val2) + Val) -> sat(X + (Val+Val2))
2216 // sat(sat(X - Val2) - Val) -> sat(X - (Val+Val2))
2217 // if Val and Val2 have the same sign
2218 if (auto *Other = dyn_cast<IntrinsicInst>(Arg0)) {
2219 Value *X;
2220 const APInt *Val, *Val2;
2221 APInt NewVal;
2222 bool IsUnsigned =
2223 IID == Intrinsic::uadd_sat || IID == Intrinsic::usub_sat;
2224 if (Other->getIntrinsicID() == II->getIntrinsicID() &&
2225 match(Arg1, m_APInt(Val)) &&
2226 match(Other->getArgOperand(0), m_Value(X)) &&
2227 match(Other->getArgOperand(1), m_APInt(Val2))) {
2228 if (IsUnsigned)
2229 NewVal = Val->uadd_sat(*Val2);
2230 else if (Val->isNonNegative() == Val2->isNonNegative()) {
2231 bool Overflow;
2232 NewVal = Val->sadd_ov(*Val2, Overflow);
2233 if (Overflow) {
2234 // Both adds together may add more than SignedMaxValue
2235 // without saturating the final result.
2236 break;
2237 }
2238 } else {
2239 // Cannot fold saturated addition with different signs.
2240 break;
2241 }
2242
2243 return replaceInstUsesWith(
2244 *II, Builder.CreateBinaryIntrinsic(
2245 IID, X, ConstantInt::get(II->getType(), NewVal)));
2246 }
2247 }
Nikita Popov085d24a2018-11-28 16:36:52 +00002248 break;
Nikita Popov78a92952018-11-28 16:36:59 +00002249 }
Nikita Popov085d24a2018-11-28 16:36:52 +00002250
Matt Arsenaultd6511b42014-10-21 23:00:20 +00002251 case Intrinsic::minnum:
Thomas Livelyc3392502018-10-19 19:01:26 +00002252 case Intrinsic::maxnum:
2253 case Intrinsic::minimum:
2254 case Intrinsic::maximum: {
Sanjay Patel790af912018-11-26 22:00:41 +00002255 if (Instruction *I = canonicalizeConstantArg0ToArg1(CI))
2256 return I;
Matt Arsenaultd6511b42014-10-21 23:00:20 +00002257 Value *Arg0 = II->getArgOperand(0);
2258 Value *Arg1 = II->getArgOperand(1);
Volkan Keles3ca146d2018-10-31 17:50:52 +00002259 Intrinsic::ID IID = II->getIntrinsicID();
Sanjay Patelc7bb1432018-05-10 20:03:13 +00002260 Value *X, *Y;
2261 if (match(Arg0, m_FNeg(m_Value(X))) && match(Arg1, m_FNeg(m_Value(Y))) &&
2262 (Arg0->hasOneUse() || Arg1->hasOneUse())) {
2263 // If both operands are negated, invert the call and negate the result:
Thomas Livelyc3392502018-10-19 19:01:26 +00002264 // min(-X, -Y) --> -(max(X, Y))
2265 // max(-X, -Y) --> -(min(X, Y))
2266 Intrinsic::ID NewIID;
Volkan Keles3ca146d2018-10-31 17:50:52 +00002267 switch (IID) {
Thomas Livelyc3392502018-10-19 19:01:26 +00002268 case Intrinsic::maxnum:
2269 NewIID = Intrinsic::minnum;
2270 break;
2271 case Intrinsic::minnum:
2272 NewIID = Intrinsic::maxnum;
2273 break;
2274 case Intrinsic::maximum:
2275 NewIID = Intrinsic::minimum;
2276 break;
2277 case Intrinsic::minimum:
2278 NewIID = Intrinsic::maximum;
2279 break;
2280 default:
2281 llvm_unreachable("unexpected intrinsic ID");
2282 }
Neil Henning57f5d0a2018-10-08 10:32:33 +00002283 Value *NewCall = Builder.CreateBinaryIntrinsic(NewIID, X, Y, II);
Sanjay Patelc7bb1432018-05-10 20:03:13 +00002284 Instruction *FNeg = BinaryOperator::CreateFNeg(NewCall);
2285 FNeg->copyIRFlags(II);
2286 return FNeg;
2287 }
Volkan Keles3ca146d2018-10-31 17:50:52 +00002288
2289 // m(m(X, C2), C1) -> m(X, C)
2290 const APFloat *C1, *C2;
2291 if (auto *M = dyn_cast<IntrinsicInst>(Arg0)) {
2292 if (M->getIntrinsicID() == IID && match(Arg1, m_APFloat(C1)) &&
2293 ((match(M->getArgOperand(0), m_Value(X)) &&
2294 match(M->getArgOperand(1), m_APFloat(C2))) ||
2295 (match(M->getArgOperand(1), m_Value(X)) &&
2296 match(M->getArgOperand(0), m_APFloat(C2))))) {
2297 APFloat Res(0.0);
2298 switch (IID) {
2299 case Intrinsic::maxnum:
2300 Res = maxnum(*C1, *C2);
2301 break;
2302 case Intrinsic::minnum:
2303 Res = minnum(*C1, *C2);
2304 break;
2305 case Intrinsic::maximum:
2306 Res = maximum(*C1, *C2);
2307 break;
2308 case Intrinsic::minimum:
2309 Res = minimum(*C1, *C2);
2310 break;
2311 default:
2312 llvm_unreachable("unexpected intrinsic ID");
2313 }
2314 Instruction *NewCall = Builder.CreateBinaryIntrinsic(
2315 IID, X, ConstantFP::get(Arg0->getType(), Res));
2316 NewCall->copyIRFlags(II);
2317 return replaceInstUsesWith(*II, NewCall);
2318 }
2319 }
2320
Matt Arsenaultd6511b42014-10-21 23:00:20 +00002321 break;
2322 }
Matt Arsenault1cc294c2017-01-03 04:32:31 +00002323 case Intrinsic::fmuladd: {
Matt Arsenault92057602017-02-16 18:46:24 +00002324 // Canonicalize fast fmuladd to the separate fmul + fadd.
Sanjay Patel629c4112017-11-06 16:27:15 +00002325 if (II->isFast()) {
Craig Topperbb4069e2017-07-07 23:16:26 +00002326 BuilderTy::FastMathFlagGuard Guard(Builder);
2327 Builder.setFastMathFlags(II->getFastMathFlags());
2328 Value *Mul = Builder.CreateFMul(II->getArgOperand(0),
2329 II->getArgOperand(1));
2330 Value *Add = Builder.CreateFAdd(Mul, II->getArgOperand(2));
Matt Arsenault92057602017-02-16 18:46:24 +00002331 Add->takeName(II);
2332 return replaceInstUsesWith(*II, Add);
2333 }
2334
2335 LLVM_FALLTHROUGH;
2336 }
2337 case Intrinsic::fma: {
Sanjay Patel790af912018-11-26 22:00:41 +00002338 if (Instruction *I = canonicalizeConstantArg0ToArg1(CI))
2339 return I;
Matt Arsenaultb264c942017-01-03 04:32:35 +00002340
Matt Arsenault1cc294c2017-01-03 04:32:31 +00002341 // fma fneg(x), fneg(y), z -> fma x, y, z
Sanjay Patel790af912018-11-26 22:00:41 +00002342 Value *Src0 = II->getArgOperand(0);
2343 Value *Src1 = II->getArgOperand(1);
Sanjay Patel236442e2018-04-05 13:24:26 +00002344 Value *X, *Y;
2345 if (match(Src0, m_FNeg(m_Value(X))) && match(Src1, m_FNeg(m_Value(Y)))) {
2346 II->setArgOperand(0, X);
2347 II->setArgOperand(1, Y);
Matt Arsenault3f509042017-01-10 23:17:52 +00002348 return II;
Matt Arsenault1cc294c2017-01-03 04:32:31 +00002349 }
2350
2351 // fma fabs(x), fabs(x), z -> fma x, x, z
Matt Arsenaultd1496502018-07-27 09:04:35 +00002352 if (match(Src0, m_FAbs(m_Value(X))) &&
2353 match(Src1, m_FAbs(m_Specific(X)))) {
Sanjay Patel236442e2018-04-05 13:24:26 +00002354 II->setArgOperand(0, X);
2355 II->setArgOperand(1, X);
Matt Arsenault3f509042017-01-10 23:17:52 +00002356 return II;
Matt Arsenault1cc294c2017-01-03 04:32:31 +00002357 }
2358
Matt Arsenaultb264c942017-01-03 04:32:35 +00002359 // fma x, 1, z -> fadd x, z
2360 if (match(Src1, m_FPOne())) {
Sanjay Patel236442e2018-04-05 13:24:26 +00002361 auto *FAdd = BinaryOperator::CreateFAdd(Src0, II->getArgOperand(2));
2362 FAdd->copyFastMathFlags(II);
2363 return FAdd;
Matt Arsenaultb264c942017-01-03 04:32:35 +00002364 }
2365
Matt Arsenault1cc294c2017-01-03 04:32:31 +00002366 break;
2367 }
Matt Arsenault56ff4832017-01-03 22:40:34 +00002368 case Intrinsic::fabs: {
2369 Value *Cond;
2370 Constant *LHS, *RHS;
2371 if (match(II->getArgOperand(0),
2372 m_Select(m_Value(Cond), m_Constant(LHS), m_Constant(RHS)))) {
Craig Topperbb4069e2017-07-07 23:16:26 +00002373 CallInst *Call0 = Builder.CreateCall(II->getCalledFunction(), {LHS});
2374 CallInst *Call1 = Builder.CreateCall(II->getCalledFunction(), {RHS});
Matt Arsenault56ff4832017-01-03 22:40:34 +00002375 return SelectInst::Create(Cond, Call0, Call1);
2376 }
2377
Matt Arsenault954a6242017-01-23 23:55:08 +00002378 LLVM_FALLTHROUGH;
2379 }
2380 case Intrinsic::ceil:
2381 case Intrinsic::floor:
2382 case Intrinsic::round:
2383 case Intrinsic::nearbyint:
Joerg Sonnenberger28bed102017-03-31 19:58:07 +00002384 case Intrinsic::rint:
Matt Arsenault954a6242017-01-23 23:55:08 +00002385 case Intrinsic::trunc: {
Matt Arsenault72333442017-01-17 00:10:40 +00002386 Value *ExtSrc;
Sanjay Patel32381d72018-03-23 21:18:12 +00002387 if (match(II->getArgOperand(0), m_OneUse(m_FPExt(m_Value(ExtSrc))))) {
2388 // Narrow the call: intrinsic (fpext x) -> fpext (intrinsic x)
Neil Henning57f5d0a2018-10-08 10:32:33 +00002389 Value *NarrowII =
2390 Builder.CreateUnaryIntrinsic(II->getIntrinsicID(), ExtSrc, II);
Sanjay Patel32381d72018-03-23 21:18:12 +00002391 return new FPExtInst(NarrowII, II->getType());
Matt Arsenault72333442017-01-17 00:10:40 +00002392 }
Matt Arsenault56ff4832017-01-03 22:40:34 +00002393 break;
2394 }
Matt Arsenault3bdd75d2017-01-04 22:49:03 +00002395 case Intrinsic::cos:
2396 case Intrinsic::amdgcn_cos: {
Sanjay Patel0f29e952018-08-29 18:27:49 +00002397 Value *X;
Matt Arsenault3bdd75d2017-01-04 22:49:03 +00002398 Value *Src = II->getArgOperand(0);
Sanjay Patel0f29e952018-08-29 18:27:49 +00002399 if (match(Src, m_FNeg(m_Value(X))) || match(Src, m_FAbs(m_Value(X)))) {
Matt Arsenault3bdd75d2017-01-04 22:49:03 +00002400 // cos(-x) -> cos(x)
2401 // cos(fabs(x)) -> cos(x)
Sanjay Patel0f29e952018-08-29 18:27:49 +00002402 II->setArgOperand(0, X);
Matt Arsenault3bdd75d2017-01-04 22:49:03 +00002403 return II;
2404 }
Sanjay Patel0f29e952018-08-29 18:27:49 +00002405 break;
2406 }
2407 case Intrinsic::sin: {
2408 Value *X;
2409 if (match(II->getArgOperand(0), m_OneUse(m_FNeg(m_Value(X))))) {
2410 // sin(-x) --> -sin(x)
Neil Henning57f5d0a2018-10-08 10:32:33 +00002411 Value *NewSin = Builder.CreateUnaryIntrinsic(Intrinsic::sin, X, II);
Sanjay Patel0f29e952018-08-29 18:27:49 +00002412 Instruction *FNeg = BinaryOperator::CreateFNeg(NewSin);
2413 FNeg->copyFastMathFlags(II);
2414 return FNeg;
2415 }
Matt Arsenault3bdd75d2017-01-04 22:49:03 +00002416 break;
2417 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002418 case Intrinsic::ppc_altivec_lvx:
2419 case Intrinsic::ppc_altivec_lvxl:
Bill Wendlingb902f1d2011-04-13 00:36:11 +00002420 // Turn PPC lvx -> load if the pointer is known aligned.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002421 if (getOrEnforceKnownAlignment(II->getArgOperand(0), 16, DL, II, &AC,
Justin Bogner99798402016-08-05 01:06:44 +00002422 &DT) >= 16) {
Craig Topperbb4069e2017-07-07 23:16:26 +00002423 Value *Ptr = Builder.CreateBitCast(II->getArgOperand(0),
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002424 PointerType::getUnqual(II->getType()));
James Y Knight14359ef2019-02-01 20:44:24 +00002425 return new LoadInst(II->getType(), Ptr);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002426 }
2427 break;
Bill Schmidt72954782014-11-12 04:19:40 +00002428 case Intrinsic::ppc_vsx_lxvw4x:
2429 case Intrinsic::ppc_vsx_lxvd2x: {
2430 // Turn PPC VSX loads into normal loads.
Craig Topperbb4069e2017-07-07 23:16:26 +00002431 Value *Ptr = Builder.CreateBitCast(II->getArgOperand(0),
2432 PointerType::getUnqual(II->getType()));
James Y Knight14359ef2019-02-01 20:44:24 +00002433 return new LoadInst(II->getType(), Ptr, Twine(""), false, 1);
Bill Schmidt72954782014-11-12 04:19:40 +00002434 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002435 case Intrinsic::ppc_altivec_stvx:
2436 case Intrinsic::ppc_altivec_stvxl:
2437 // Turn stvx -> store if the pointer is known aligned.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002438 if (getOrEnforceKnownAlignment(II->getArgOperand(1), 16, DL, II, &AC,
Justin Bogner99798402016-08-05 01:06:44 +00002439 &DT) >= 16) {
Jim Grosbach7815f562012-02-03 00:07:04 +00002440 Type *OpPtrTy =
Gabor Greifa6d75e22010-06-24 15:51:11 +00002441 PointerType::getUnqual(II->getArgOperand(0)->getType());
Craig Topperbb4069e2017-07-07 23:16:26 +00002442 Value *Ptr = Builder.CreateBitCast(II->getArgOperand(1), OpPtrTy);
Gabor Greifa6d75e22010-06-24 15:51:11 +00002443 return new StoreInst(II->getArgOperand(0), Ptr);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002444 }
2445 break;
Bill Schmidt72954782014-11-12 04:19:40 +00002446 case Intrinsic::ppc_vsx_stxvw4x:
2447 case Intrinsic::ppc_vsx_stxvd2x: {
2448 // Turn PPC VSX stores into normal stores.
2449 Type *OpPtrTy = PointerType::getUnqual(II->getArgOperand(0)->getType());
Craig Topperbb4069e2017-07-07 23:16:26 +00002450 Value *Ptr = Builder.CreateBitCast(II->getArgOperand(1), OpPtrTy);
Bill Schmidt72954782014-11-12 04:19:40 +00002451 return new StoreInst(II->getArgOperand(0), Ptr, false, 1);
2452 }
Hal Finkel221f4672015-02-26 18:56:03 +00002453 case Intrinsic::ppc_qpx_qvlfs:
2454 // Turn PPC QPX qvlfs -> load if the pointer is known aligned.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002455 if (getOrEnforceKnownAlignment(II->getArgOperand(0), 16, DL, II, &AC,
Justin Bogner99798402016-08-05 01:06:44 +00002456 &DT) >= 16) {
Craig Topperbb4069e2017-07-07 23:16:26 +00002457 Type *VTy = VectorType::get(Builder.getFloatTy(),
Hal Finkelf0d68d72015-05-11 06:37:03 +00002458 II->getType()->getVectorNumElements());
Craig Topperbb4069e2017-07-07 23:16:26 +00002459 Value *Ptr = Builder.CreateBitCast(II->getArgOperand(0),
Hal Finkelf0d68d72015-05-11 06:37:03 +00002460 PointerType::getUnqual(VTy));
James Y Knight14359ef2019-02-01 20:44:24 +00002461 Value *Load = Builder.CreateLoad(VTy, Ptr);
Hal Finkelf0d68d72015-05-11 06:37:03 +00002462 return new FPExtInst(Load, II->getType());
Hal Finkel221f4672015-02-26 18:56:03 +00002463 }
2464 break;
2465 case Intrinsic::ppc_qpx_qvlfd:
2466 // Turn PPC QPX qvlfd -> load if the pointer is known aligned.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002467 if (getOrEnforceKnownAlignment(II->getArgOperand(0), 32, DL, II, &AC,
Justin Bogner99798402016-08-05 01:06:44 +00002468 &DT) >= 32) {
Craig Topperbb4069e2017-07-07 23:16:26 +00002469 Value *Ptr = Builder.CreateBitCast(II->getArgOperand(0),
Hal Finkel221f4672015-02-26 18:56:03 +00002470 PointerType::getUnqual(II->getType()));
James Y Knight14359ef2019-02-01 20:44:24 +00002471 return new LoadInst(II->getType(), Ptr);
Hal Finkel221f4672015-02-26 18:56:03 +00002472 }
2473 break;
2474 case Intrinsic::ppc_qpx_qvstfs:
2475 // Turn PPC QPX qvstfs -> store if the pointer is known aligned.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002476 if (getOrEnforceKnownAlignment(II->getArgOperand(1), 16, DL, II, &AC,
Justin Bogner99798402016-08-05 01:06:44 +00002477 &DT) >= 16) {
Craig Topperbb4069e2017-07-07 23:16:26 +00002478 Type *VTy = VectorType::get(Builder.getFloatTy(),
Hal Finkelf0d68d72015-05-11 06:37:03 +00002479 II->getArgOperand(0)->getType()->getVectorNumElements());
Craig Topperbb4069e2017-07-07 23:16:26 +00002480 Value *TOp = Builder.CreateFPTrunc(II->getArgOperand(0), VTy);
Hal Finkelf0d68d72015-05-11 06:37:03 +00002481 Type *OpPtrTy = PointerType::getUnqual(VTy);
Craig Topperbb4069e2017-07-07 23:16:26 +00002482 Value *Ptr = Builder.CreateBitCast(II->getArgOperand(1), OpPtrTy);
Hal Finkelf0d68d72015-05-11 06:37:03 +00002483 return new StoreInst(TOp, Ptr);
Hal Finkel221f4672015-02-26 18:56:03 +00002484 }
2485 break;
2486 case Intrinsic::ppc_qpx_qvstfd:
2487 // Turn PPC QPX qvstfd -> store if the pointer is known aligned.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002488 if (getOrEnforceKnownAlignment(II->getArgOperand(1), 32, DL, II, &AC,
Justin Bogner99798402016-08-05 01:06:44 +00002489 &DT) >= 32) {
Hal Finkel221f4672015-02-26 18:56:03 +00002490 Type *OpPtrTy =
2491 PointerType::getUnqual(II->getArgOperand(0)->getType());
Craig Topperbb4069e2017-07-07 23:16:26 +00002492 Value *Ptr = Builder.CreateBitCast(II->getArgOperand(1), OpPtrTy);
Hal Finkel221f4672015-02-26 18:56:03 +00002493 return new StoreInst(II->getArgOperand(0), Ptr);
2494 }
2495 break;
Simon Pilgrim20c607b2015-09-12 13:39:53 +00002496
Craig Topper83240032017-07-31 18:52:13 +00002497 case Intrinsic::x86_bmi_bextr_32:
2498 case Intrinsic::x86_bmi_bextr_64:
2499 case Intrinsic::x86_tbm_bextri_u32:
2500 case Intrinsic::x86_tbm_bextri_u64:
2501 // If the RHS is a constant we can try some simplifications.
2502 if (auto *C = dyn_cast<ConstantInt>(II->getArgOperand(1))) {
2503 uint64_t Shift = C->getZExtValue();
2504 uint64_t Length = (Shift >> 8) & 0xff;
2505 Shift &= 0xff;
2506 unsigned BitWidth = II->getType()->getIntegerBitWidth();
2507 // If the length is 0 or the shift is out of range, replace with zero.
2508 if (Length == 0 || Shift >= BitWidth)
2509 return replaceInstUsesWith(CI, ConstantInt::get(II->getType(), 0));
2510 // If the LHS is also a constant, we can completely constant fold this.
2511 if (auto *InC = dyn_cast<ConstantInt>(II->getArgOperand(0))) {
2512 uint64_t Result = InC->getZExtValue() >> Shift;
2513 if (Length > BitWidth)
2514 Length = BitWidth;
2515 Result &= maskTrailingOnes<uint64_t>(Length);
2516 return replaceInstUsesWith(CI, ConstantInt::get(II->getType(), Result));
2517 }
2518 // TODO should we turn this into 'and' if shift is 0? Or 'shl' if we
2519 // are only masking bits that a shift already cleared?
2520 }
2521 break;
2522
Craig Topper317a51e2017-07-31 18:52:15 +00002523 case Intrinsic::x86_bmi_bzhi_32:
2524 case Intrinsic::x86_bmi_bzhi_64:
2525 // If the RHS is a constant we can try some simplifications.
2526 if (auto *C = dyn_cast<ConstantInt>(II->getArgOperand(1))) {
2527 uint64_t Index = C->getZExtValue() & 0xff;
2528 unsigned BitWidth = II->getType()->getIntegerBitWidth();
2529 if (Index >= BitWidth)
2530 return replaceInstUsesWith(CI, II->getArgOperand(0));
2531 if (Index == 0)
2532 return replaceInstUsesWith(CI, ConstantInt::get(II->getType(), 0));
2533 // If the LHS is also a constant, we can completely constant fold this.
2534 if (auto *InC = dyn_cast<ConstantInt>(II->getArgOperand(0))) {
2535 uint64_t Result = InC->getZExtValue();
2536 Result &= maskTrailingOnes<uint64_t>(Index);
2537 return replaceInstUsesWith(CI, ConstantInt::get(II->getType(), Result));
2538 }
2539 // TODO should we convert this to an AND if the RHS is constant?
2540 }
2541 break;
2542
Simon Pilgrim20c607b2015-09-12 13:39:53 +00002543 case Intrinsic::x86_vcvtph2ps_128:
2544 case Intrinsic::x86_vcvtph2ps_256: {
2545 auto Arg = II->getArgOperand(0);
2546 auto ArgType = cast<VectorType>(Arg->getType());
2547 auto RetType = cast<VectorType>(II->getType());
2548 unsigned ArgWidth = ArgType->getNumElements();
2549 unsigned RetWidth = RetType->getNumElements();
2550 assert(RetWidth <= ArgWidth && "Unexpected input/return vector widths");
2551 assert(ArgType->isIntOrIntVectorTy() &&
2552 ArgType->getScalarSizeInBits() == 16 &&
2553 "CVTPH2PS input type should be 16-bit integer vector");
2554 assert(RetType->getScalarType()->isFloatTy() &&
2555 "CVTPH2PS output type should be 32-bit float vector");
2556
2557 // Constant folding: Convert to generic half to single conversion.
Simon Pilgrim48ffca02015-09-12 14:00:17 +00002558 if (isa<ConstantAggregateZero>(Arg))
Sanjay Patel4b198802016-02-01 22:23:39 +00002559 return replaceInstUsesWith(*II, ConstantAggregateZero::get(RetType));
Simon Pilgrim20c607b2015-09-12 13:39:53 +00002560
Simon Pilgrim48ffca02015-09-12 14:00:17 +00002561 if (isa<ConstantDataVector>(Arg)) {
Simon Pilgrim20c607b2015-09-12 13:39:53 +00002562 auto VectorHalfAsShorts = Arg;
2563 if (RetWidth < ArgWidth) {
Craig Topper99d1eab2016-06-12 00:41:19 +00002564 SmallVector<uint32_t, 8> SubVecMask;
Simon Pilgrim20c607b2015-09-12 13:39:53 +00002565 for (unsigned i = 0; i != RetWidth; ++i)
2566 SubVecMask.push_back((int)i);
Craig Topperbb4069e2017-07-07 23:16:26 +00002567 VectorHalfAsShorts = Builder.CreateShuffleVector(
Simon Pilgrim20c607b2015-09-12 13:39:53 +00002568 Arg, UndefValue::get(ArgType), SubVecMask);
2569 }
2570
2571 auto VectorHalfType =
2572 VectorType::get(Type::getHalfTy(II->getContext()), RetWidth);
2573 auto VectorHalfs =
Craig Topperbb4069e2017-07-07 23:16:26 +00002574 Builder.CreateBitCast(VectorHalfAsShorts, VectorHalfType);
2575 auto VectorFloats = Builder.CreateFPExt(VectorHalfs, RetType);
Sanjay Patel4b198802016-02-01 22:23:39 +00002576 return replaceInstUsesWith(*II, VectorFloats);
Simon Pilgrim20c607b2015-09-12 13:39:53 +00002577 }
2578
2579 // We only use the lowest lanes of the argument.
Simon Pilgrim996725e2015-09-19 11:41:53 +00002580 if (Value *V = SimplifyDemandedVectorEltsLow(Arg, ArgWidth, RetWidth)) {
Simon Pilgrim20c607b2015-09-12 13:39:53 +00002581 II->setArgOperand(0, V);
2582 return II;
2583 }
2584 break;
2585 }
2586
Chandler Carruthcf414cf2011-01-10 07:19:37 +00002587 case Intrinsic::x86_sse_cvtss2si:
2588 case Intrinsic::x86_sse_cvtss2si64:
2589 case Intrinsic::x86_sse_cvttss2si:
2590 case Intrinsic::x86_sse_cvttss2si64:
2591 case Intrinsic::x86_sse2_cvtsd2si:
2592 case Intrinsic::x86_sse2_cvtsd2si64:
2593 case Intrinsic::x86_sse2_cvttsd2si:
Craig Topperaeaa52c2016-12-14 07:46:12 +00002594 case Intrinsic::x86_sse2_cvttsd2si64:
2595 case Intrinsic::x86_avx512_vcvtss2si32:
2596 case Intrinsic::x86_avx512_vcvtss2si64:
2597 case Intrinsic::x86_avx512_vcvtss2usi32:
2598 case Intrinsic::x86_avx512_vcvtss2usi64:
2599 case Intrinsic::x86_avx512_vcvtsd2si32:
2600 case Intrinsic::x86_avx512_vcvtsd2si64:
2601 case Intrinsic::x86_avx512_vcvtsd2usi32:
2602 case Intrinsic::x86_avx512_vcvtsd2usi64:
2603 case Intrinsic::x86_avx512_cvttss2si:
2604 case Intrinsic::x86_avx512_cvttss2si64:
2605 case Intrinsic::x86_avx512_cvttss2usi:
2606 case Intrinsic::x86_avx512_cvttss2usi64:
2607 case Intrinsic::x86_avx512_cvttsd2si:
2608 case Intrinsic::x86_avx512_cvttsd2si64:
2609 case Intrinsic::x86_avx512_cvttsd2usi:
2610 case Intrinsic::x86_avx512_cvttsd2usi64: {
Chandler Carruthcf414cf2011-01-10 07:19:37 +00002611 // These intrinsics only demand the 0th element of their input vectors. If
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002612 // we can simplify the input based on that, do so now.
Simon Pilgrim996725e2015-09-19 11:41:53 +00002613 Value *Arg = II->getArgOperand(0);
2614 unsigned VWidth = Arg->getType()->getVectorNumElements();
2615 if (Value *V = SimplifyDemandedVectorEltsLow(Arg, VWidth, 1)) {
Gabor Greif5b1370e2010-06-28 16:50:57 +00002616 II->setArgOperand(0, V);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002617 return II;
2618 }
Simon Pilgrim18617d12015-08-05 08:18:00 +00002619 break;
2620 }
2621
Mikhail Dvoretckii8393f902018-06-19 10:49:12 +00002622 case Intrinsic::x86_sse41_round_ps:
2623 case Intrinsic::x86_sse41_round_pd:
2624 case Intrinsic::x86_avx_round_ps_256:
2625 case Intrinsic::x86_avx_round_pd_256:
2626 case Intrinsic::x86_avx512_mask_rndscale_ps_128:
2627 case Intrinsic::x86_avx512_mask_rndscale_ps_256:
2628 case Intrinsic::x86_avx512_mask_rndscale_ps_512:
2629 case Intrinsic::x86_avx512_mask_rndscale_pd_128:
2630 case Intrinsic::x86_avx512_mask_rndscale_pd_256:
2631 case Intrinsic::x86_avx512_mask_rndscale_pd_512:
2632 case Intrinsic::x86_avx512_mask_rndscale_ss:
2633 case Intrinsic::x86_avx512_mask_rndscale_sd:
2634 if (Value *V = simplifyX86round(*II, Builder))
2635 return replaceInstUsesWith(*II, V);
2636 break;
2637
Simon Pilgrim91e3ac82016-06-07 08:18:35 +00002638 case Intrinsic::x86_mmx_pmovmskb:
2639 case Intrinsic::x86_sse_movmsk_ps:
2640 case Intrinsic::x86_sse2_movmsk_pd:
2641 case Intrinsic::x86_sse2_pmovmskb_128:
2642 case Intrinsic::x86_avx_movmsk_pd_256:
2643 case Intrinsic::x86_avx_movmsk_ps_256:
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +00002644 case Intrinsic::x86_avx2_pmovmskb:
Sanjay Patel2aa2dc72018-12-11 16:38:03 +00002645 if (Value *V = simplifyX86movmsk(*II, Builder))
Simon Pilgrim91e3ac82016-06-07 08:18:35 +00002646 return replaceInstUsesWith(*II, V);
2647 break;
Simon Pilgrim91e3ac82016-06-07 08:18:35 +00002648
Simon Pilgrim471efd22016-02-20 23:17:35 +00002649 case Intrinsic::x86_sse_comieq_ss:
2650 case Intrinsic::x86_sse_comige_ss:
2651 case Intrinsic::x86_sse_comigt_ss:
2652 case Intrinsic::x86_sse_comile_ss:
2653 case Intrinsic::x86_sse_comilt_ss:
2654 case Intrinsic::x86_sse_comineq_ss:
2655 case Intrinsic::x86_sse_ucomieq_ss:
2656 case Intrinsic::x86_sse_ucomige_ss:
2657 case Intrinsic::x86_sse_ucomigt_ss:
2658 case Intrinsic::x86_sse_ucomile_ss:
2659 case Intrinsic::x86_sse_ucomilt_ss:
2660 case Intrinsic::x86_sse_ucomineq_ss:
2661 case Intrinsic::x86_sse2_comieq_sd:
2662 case Intrinsic::x86_sse2_comige_sd:
2663 case Intrinsic::x86_sse2_comigt_sd:
2664 case Intrinsic::x86_sse2_comile_sd:
2665 case Intrinsic::x86_sse2_comilt_sd:
2666 case Intrinsic::x86_sse2_comineq_sd:
2667 case Intrinsic::x86_sse2_ucomieq_sd:
2668 case Intrinsic::x86_sse2_ucomige_sd:
2669 case Intrinsic::x86_sse2_ucomigt_sd:
2670 case Intrinsic::x86_sse2_ucomile_sd:
2671 case Intrinsic::x86_sse2_ucomilt_sd:
Craig Topperd9639532016-12-11 07:42:04 +00002672 case Intrinsic::x86_sse2_ucomineq_sd:
Craig Topperd00db692016-12-31 00:45:06 +00002673 case Intrinsic::x86_avx512_vcomi_ss:
2674 case Intrinsic::x86_avx512_vcomi_sd:
Craig Topperd9639532016-12-11 07:42:04 +00002675 case Intrinsic::x86_avx512_mask_cmp_ss:
2676 case Intrinsic::x86_avx512_mask_cmp_sd: {
Simon Pilgrim471efd22016-02-20 23:17:35 +00002677 // These intrinsics only demand the 0th element of their input vectors. If
2678 // we can simplify the input based on that, do so now.
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002679 bool MadeChange = false;
Simon Pilgrim471efd22016-02-20 23:17:35 +00002680 Value *Arg0 = II->getArgOperand(0);
2681 Value *Arg1 = II->getArgOperand(1);
2682 unsigned VWidth = Arg0->getType()->getVectorNumElements();
2683 if (Value *V = SimplifyDemandedVectorEltsLow(Arg0, VWidth, 1)) {
2684 II->setArgOperand(0, V);
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002685 MadeChange = true;
Simon Pilgrim471efd22016-02-20 23:17:35 +00002686 }
2687 if (Value *V = SimplifyDemandedVectorEltsLow(Arg1, VWidth, 1)) {
2688 II->setArgOperand(1, V);
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002689 MadeChange = true;
Simon Pilgrim471efd22016-02-20 23:17:35 +00002690 }
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002691 if (MadeChange)
2692 return II;
Simon Pilgrim471efd22016-02-20 23:17:35 +00002693 break;
2694 }
Craig Topper31cbe752018-06-27 15:57:53 +00002695 case Intrinsic::x86_avx512_cmp_pd_128:
2696 case Intrinsic::x86_avx512_cmp_pd_256:
2697 case Intrinsic::x86_avx512_cmp_pd_512:
2698 case Intrinsic::x86_avx512_cmp_ps_128:
2699 case Intrinsic::x86_avx512_cmp_ps_256:
2700 case Intrinsic::x86_avx512_cmp_ps_512: {
Michael Zuckerman16b20d22017-04-16 13:26:08 +00002701 // Folding cmp(sub(a,b),0) -> cmp(a,b) and cmp(0,sub(a,b)) -> cmp(b,a)
2702 Value *Arg0 = II->getArgOperand(0);
2703 Value *Arg1 = II->getArgOperand(1);
Sanjay Patel93e64dd2018-03-25 21:16:33 +00002704 bool Arg0IsZero = match(Arg0, m_PosZeroFP());
Michael Zuckerman16b20d22017-04-16 13:26:08 +00002705 if (Arg0IsZero)
2706 std::swap(Arg0, Arg1);
2707 Value *A, *B;
2708 // This fold requires only the NINF(not +/- inf) since inf minus
2709 // inf is nan.
2710 // NSZ(No Signed Zeros) is not needed because zeros of any sign are
2711 // equal for both compares.
2712 // NNAN is not needed because nans compare the same for both compares.
2713 // The compare intrinsic uses the above assumptions and therefore
2714 // doesn't require additional flags.
2715 if ((match(Arg0, m_OneUse(m_FSub(m_Value(A), m_Value(B)))) &&
Sanjay Patel93e64dd2018-03-25 21:16:33 +00002716 match(Arg1, m_PosZeroFP()) && isa<Instruction>(Arg0) &&
Michael Zuckerman16b20d22017-04-16 13:26:08 +00002717 cast<Instruction>(Arg0)->getFastMathFlags().noInfs())) {
2718 if (Arg0IsZero)
2719 std::swap(A, B);
2720 II->setArgOperand(0, A);
2721 II->setArgOperand(1, B);
2722 return II;
2723 }
2724 break;
2725 }
Simon Pilgrim471efd22016-02-20 23:17:35 +00002726
Craig Topper98a79932018-06-10 06:01:36 +00002727 case Intrinsic::x86_avx512_add_ps_512:
2728 case Intrinsic::x86_avx512_div_ps_512:
2729 case Intrinsic::x86_avx512_mul_ps_512:
2730 case Intrinsic::x86_avx512_sub_ps_512:
2731 case Intrinsic::x86_avx512_add_pd_512:
2732 case Intrinsic::x86_avx512_div_pd_512:
2733 case Intrinsic::x86_avx512_mul_pd_512:
2734 case Intrinsic::x86_avx512_sub_pd_512:
Craig Topper020b2282016-12-27 00:23:16 +00002735 // If the rounding mode is CUR_DIRECTION(4) we can turn these into regular
2736 // IR operations.
Craig Topper98a79932018-06-10 06:01:36 +00002737 if (auto *R = dyn_cast<ConstantInt>(II->getArgOperand(2))) {
Craig Topper020b2282016-12-27 00:23:16 +00002738 if (R->getValue() == 4) {
2739 Value *Arg0 = II->getArgOperand(0);
2740 Value *Arg1 = II->getArgOperand(1);
2741
2742 Value *V;
2743 switch (II->getIntrinsicID()) {
2744 default: llvm_unreachable("Case stmts out of sync!");
Craig Topper98a79932018-06-10 06:01:36 +00002745 case Intrinsic::x86_avx512_add_ps_512:
2746 case Intrinsic::x86_avx512_add_pd_512:
Craig Topperbb4069e2017-07-07 23:16:26 +00002747 V = Builder.CreateFAdd(Arg0, Arg1);
Craig Topper020b2282016-12-27 00:23:16 +00002748 break;
Craig Topper98a79932018-06-10 06:01:36 +00002749 case Intrinsic::x86_avx512_sub_ps_512:
2750 case Intrinsic::x86_avx512_sub_pd_512:
Craig Topperbb4069e2017-07-07 23:16:26 +00002751 V = Builder.CreateFSub(Arg0, Arg1);
Craig Topper020b2282016-12-27 00:23:16 +00002752 break;
Craig Topper98a79932018-06-10 06:01:36 +00002753 case Intrinsic::x86_avx512_mul_ps_512:
2754 case Intrinsic::x86_avx512_mul_pd_512:
Craig Topperbb4069e2017-07-07 23:16:26 +00002755 V = Builder.CreateFMul(Arg0, Arg1);
Craig Topper020b2282016-12-27 00:23:16 +00002756 break;
Craig Topper98a79932018-06-10 06:01:36 +00002757 case Intrinsic::x86_avx512_div_ps_512:
2758 case Intrinsic::x86_avx512_div_pd_512:
Craig Topperbb4069e2017-07-07 23:16:26 +00002759 V = Builder.CreateFDiv(Arg0, Arg1);
Craig Topper020b2282016-12-27 00:23:16 +00002760 break;
2761 }
2762
Craig Topper020b2282016-12-27 00:23:16 +00002763 return replaceInstUsesWith(*II, V);
2764 }
2765 }
2766 break;
2767
Craig Topper790d0fa2016-12-11 07:42:01 +00002768 case Intrinsic::x86_avx512_mask_add_ss_round:
2769 case Intrinsic::x86_avx512_mask_div_ss_round:
2770 case Intrinsic::x86_avx512_mask_mul_ss_round:
2771 case Intrinsic::x86_avx512_mask_sub_ss_round:
Craig Topper790d0fa2016-12-11 07:42:01 +00002772 case Intrinsic::x86_avx512_mask_add_sd_round:
2773 case Intrinsic::x86_avx512_mask_div_sd_round:
2774 case Intrinsic::x86_avx512_mask_mul_sd_round:
2775 case Intrinsic::x86_avx512_mask_sub_sd_round:
Craig Topper7b788ada2016-12-26 06:33:19 +00002776 // If the rounding mode is CUR_DIRECTION(4) we can turn these into regular
2777 // IR operations.
2778 if (auto *R = dyn_cast<ConstantInt>(II->getArgOperand(4))) {
2779 if (R->getValue() == 4) {
Craig Topper7f8540b2016-12-27 01:56:30 +00002780 // Extract the element as scalars.
2781 Value *Arg0 = II->getArgOperand(0);
2782 Value *Arg1 = II->getArgOperand(1);
Craig Topperbb4069e2017-07-07 23:16:26 +00002783 Value *LHS = Builder.CreateExtractElement(Arg0, (uint64_t)0);
2784 Value *RHS = Builder.CreateExtractElement(Arg1, (uint64_t)0);
Craig Topper7b788ada2016-12-26 06:33:19 +00002785
Craig Topper7f8540b2016-12-27 01:56:30 +00002786 Value *V;
2787 switch (II->getIntrinsicID()) {
2788 default: llvm_unreachable("Case stmts out of sync!");
2789 case Intrinsic::x86_avx512_mask_add_ss_round:
2790 case Intrinsic::x86_avx512_mask_add_sd_round:
Craig Topperbb4069e2017-07-07 23:16:26 +00002791 V = Builder.CreateFAdd(LHS, RHS);
Craig Topper7f8540b2016-12-27 01:56:30 +00002792 break;
2793 case Intrinsic::x86_avx512_mask_sub_ss_round:
2794 case Intrinsic::x86_avx512_mask_sub_sd_round:
Craig Topperbb4069e2017-07-07 23:16:26 +00002795 V = Builder.CreateFSub(LHS, RHS);
Craig Topper7f8540b2016-12-27 01:56:30 +00002796 break;
2797 case Intrinsic::x86_avx512_mask_mul_ss_round:
2798 case Intrinsic::x86_avx512_mask_mul_sd_round:
Craig Topperbb4069e2017-07-07 23:16:26 +00002799 V = Builder.CreateFMul(LHS, RHS);
Craig Topper7f8540b2016-12-27 01:56:30 +00002800 break;
2801 case Intrinsic::x86_avx512_mask_div_ss_round:
2802 case Intrinsic::x86_avx512_mask_div_sd_round:
Craig Topperbb4069e2017-07-07 23:16:26 +00002803 V = Builder.CreateFDiv(LHS, RHS);
Craig Topper7f8540b2016-12-27 01:56:30 +00002804 break;
Craig Topper7b788ada2016-12-26 06:33:19 +00002805 }
Craig Topper7f8540b2016-12-27 01:56:30 +00002806
2807 // Handle the masking aspect of the intrinsic.
Craig Topper7f8540b2016-12-27 01:56:30 +00002808 Value *Mask = II->getArgOperand(3);
Craig Topper99163632016-12-30 23:06:28 +00002809 auto *C = dyn_cast<ConstantInt>(Mask);
2810 // We don't need a select if we know the mask bit is a 1.
2811 if (!C || !C->getValue()[0]) {
2812 // Cast the mask to an i1 vector and then extract the lowest element.
Craig Topperbb4069e2017-07-07 23:16:26 +00002813 auto *MaskTy = VectorType::get(Builder.getInt1Ty(),
Craig Topper7f8540b2016-12-27 01:56:30 +00002814 cast<IntegerType>(Mask->getType())->getBitWidth());
Craig Topperbb4069e2017-07-07 23:16:26 +00002815 Mask = Builder.CreateBitCast(Mask, MaskTy);
2816 Mask = Builder.CreateExtractElement(Mask, (uint64_t)0);
Craig Topper99163632016-12-30 23:06:28 +00002817 // Extract the lowest element from the passthru operand.
Craig Topperbb4069e2017-07-07 23:16:26 +00002818 Value *Passthru = Builder.CreateExtractElement(II->getArgOperand(2),
Craig Topper99163632016-12-30 23:06:28 +00002819 (uint64_t)0);
Craig Topperbb4069e2017-07-07 23:16:26 +00002820 V = Builder.CreateSelect(Mask, V, Passthru);
Craig Topper99163632016-12-30 23:06:28 +00002821 }
Craig Topper7f8540b2016-12-27 01:56:30 +00002822
2823 // Insert the result back into the original argument 0.
Craig Topperbb4069e2017-07-07 23:16:26 +00002824 V = Builder.CreateInsertElement(Arg0, V, (uint64_t)0);
Craig Topper7f8540b2016-12-27 01:56:30 +00002825
2826 return replaceInstUsesWith(*II, V);
Craig Topper7b788ada2016-12-26 06:33:19 +00002827 }
2828 }
Philip Reamesc71e9962019-01-30 19:21:11 +00002829 break;
Craig Topper7b788ada2016-12-26 06:33:19 +00002830
Mikhail Dvoretckii8393f902018-06-19 10:49:12 +00002831 case Intrinsic::x86_sse41_round_ss:
2832 case Intrinsic::x86_sse41_round_sd: {
Philip Reamesc71e9962019-01-30 19:21:11 +00002833 if (Value *V = simplifyX86round(*II, Builder))
Mikhail Dvoretckii8393f902018-06-19 10:49:12 +00002834 return replaceInstUsesWith(*II, V);
2835 break;
2836 }
Craig Topperac75bca2016-12-13 07:45:45 +00002837
Simon Pilgrima3a72b42015-08-10 20:21:15 +00002838 // Constant fold ashr( <A x Bi>, Ci ).
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00002839 // Constant fold lshr( <A x Bi>, Ci ).
2840 // Constant fold shl( <A x Bi>, Ci ).
Simon Pilgrima3a72b42015-08-10 20:21:15 +00002841 case Intrinsic::x86_sse2_psrai_d:
2842 case Intrinsic::x86_sse2_psrai_w:
Simon Pilgrima3a72b42015-08-10 20:21:15 +00002843 case Intrinsic::x86_avx2_psrai_d:
2844 case Intrinsic::x86_avx2_psrai_w:
Craig Topper8b831cb2016-11-13 01:51:55 +00002845 case Intrinsic::x86_avx512_psrai_q_128:
2846 case Intrinsic::x86_avx512_psrai_q_256:
2847 case Intrinsic::x86_avx512_psrai_d_512:
2848 case Intrinsic::x86_avx512_psrai_q_512:
2849 case Intrinsic::x86_avx512_psrai_w_512:
Simon Pilgrim18617d12015-08-05 08:18:00 +00002850 case Intrinsic::x86_sse2_psrli_d:
2851 case Intrinsic::x86_sse2_psrli_q:
2852 case Intrinsic::x86_sse2_psrli_w:
Simon Pilgrim18617d12015-08-05 08:18:00 +00002853 case Intrinsic::x86_avx2_psrli_d:
2854 case Intrinsic::x86_avx2_psrli_q:
2855 case Intrinsic::x86_avx2_psrli_w:
Craig Topper8b831cb2016-11-13 01:51:55 +00002856 case Intrinsic::x86_avx512_psrli_d_512:
2857 case Intrinsic::x86_avx512_psrli_q_512:
2858 case Intrinsic::x86_avx512_psrli_w_512:
Michael J. Spencerdee4b2c2014-04-24 00:58:18 +00002859 case Intrinsic::x86_sse2_pslli_d:
2860 case Intrinsic::x86_sse2_pslli_q:
2861 case Intrinsic::x86_sse2_pslli_w:
Simon Pilgrim18617d12015-08-05 08:18:00 +00002862 case Intrinsic::x86_avx2_pslli_d:
2863 case Intrinsic::x86_avx2_pslli_q:
2864 case Intrinsic::x86_avx2_pslli_w:
Craig Topper8b831cb2016-11-13 01:51:55 +00002865 case Intrinsic::x86_avx512_pslli_d_512:
2866 case Intrinsic::x86_avx512_pslli_q_512:
2867 case Intrinsic::x86_avx512_pslli_w_512:
Craig Topperbb4069e2017-07-07 23:16:26 +00002868 if (Value *V = simplifyX86immShift(*II, Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00002869 return replaceInstUsesWith(*II, V);
Simon Pilgrim18617d12015-08-05 08:18:00 +00002870 break;
2871
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00002872 case Intrinsic::x86_sse2_psra_d:
2873 case Intrinsic::x86_sse2_psra_w:
2874 case Intrinsic::x86_avx2_psra_d:
2875 case Intrinsic::x86_avx2_psra_w:
Craig Topper8b831cb2016-11-13 01:51:55 +00002876 case Intrinsic::x86_avx512_psra_q_128:
2877 case Intrinsic::x86_avx512_psra_q_256:
2878 case Intrinsic::x86_avx512_psra_d_512:
2879 case Intrinsic::x86_avx512_psra_q_512:
2880 case Intrinsic::x86_avx512_psra_w_512:
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00002881 case Intrinsic::x86_sse2_psrl_d:
2882 case Intrinsic::x86_sse2_psrl_q:
2883 case Intrinsic::x86_sse2_psrl_w:
2884 case Intrinsic::x86_avx2_psrl_d:
2885 case Intrinsic::x86_avx2_psrl_q:
2886 case Intrinsic::x86_avx2_psrl_w:
Craig Topper8b831cb2016-11-13 01:51:55 +00002887 case Intrinsic::x86_avx512_psrl_d_512:
2888 case Intrinsic::x86_avx512_psrl_q_512:
2889 case Intrinsic::x86_avx512_psrl_w_512:
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00002890 case Intrinsic::x86_sse2_psll_d:
2891 case Intrinsic::x86_sse2_psll_q:
2892 case Intrinsic::x86_sse2_psll_w:
2893 case Intrinsic::x86_avx2_psll_d:
2894 case Intrinsic::x86_avx2_psll_q:
Craig Topper8b831cb2016-11-13 01:51:55 +00002895 case Intrinsic::x86_avx2_psll_w:
2896 case Intrinsic::x86_avx512_psll_d_512:
2897 case Intrinsic::x86_avx512_psll_q_512:
2898 case Intrinsic::x86_avx512_psll_w_512: {
Craig Topperbb4069e2017-07-07 23:16:26 +00002899 if (Value *V = simplifyX86immShift(*II, Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00002900 return replaceInstUsesWith(*II, V);
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00002901
2902 // SSE2/AVX2 uses only the first 64-bits of the 128-bit vector
2903 // operand to compute the shift amount.
Simon Pilgrim996725e2015-09-19 11:41:53 +00002904 Value *Arg1 = II->getArgOperand(1);
2905 assert(Arg1->getType()->getPrimitiveSizeInBits() == 128 &&
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00002906 "Unexpected packed shift size");
Simon Pilgrim996725e2015-09-19 11:41:53 +00002907 unsigned VWidth = Arg1->getType()->getVectorNumElements();
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00002908
Simon Pilgrim996725e2015-09-19 11:41:53 +00002909 if (Value *V = SimplifyDemandedVectorEltsLow(Arg1, VWidth, VWidth / 2)) {
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00002910 II->setArgOperand(1, V);
2911 return II;
2912 }
2913 break;
2914 }
2915
Simon Pilgrimdb9893f2016-06-07 10:27:15 +00002916 case Intrinsic::x86_avx2_psllv_d:
2917 case Intrinsic::x86_avx2_psllv_d_256:
2918 case Intrinsic::x86_avx2_psllv_q:
2919 case Intrinsic::x86_avx2_psllv_q_256:
Craig Topperb4173a52016-11-13 07:26:19 +00002920 case Intrinsic::x86_avx512_psllv_d_512:
2921 case Intrinsic::x86_avx512_psllv_q_512:
Craig Topper1de753f2016-11-18 06:04:33 +00002922 case Intrinsic::x86_avx512_psllv_w_128:
2923 case Intrinsic::x86_avx512_psllv_w_256:
2924 case Intrinsic::x86_avx512_psllv_w_512:
Simon Pilgrimdb9893f2016-06-07 10:27:15 +00002925 case Intrinsic::x86_avx2_psrav_d:
2926 case Intrinsic::x86_avx2_psrav_d_256:
Craig Topperb4173a52016-11-13 07:26:19 +00002927 case Intrinsic::x86_avx512_psrav_q_128:
2928 case Intrinsic::x86_avx512_psrav_q_256:
2929 case Intrinsic::x86_avx512_psrav_d_512:
2930 case Intrinsic::x86_avx512_psrav_q_512:
Craig Topper1de753f2016-11-18 06:04:33 +00002931 case Intrinsic::x86_avx512_psrav_w_128:
2932 case Intrinsic::x86_avx512_psrav_w_256:
2933 case Intrinsic::x86_avx512_psrav_w_512:
Simon Pilgrimdb9893f2016-06-07 10:27:15 +00002934 case Intrinsic::x86_avx2_psrlv_d:
2935 case Intrinsic::x86_avx2_psrlv_d_256:
2936 case Intrinsic::x86_avx2_psrlv_q:
2937 case Intrinsic::x86_avx2_psrlv_q_256:
Craig Topperb4173a52016-11-13 07:26:19 +00002938 case Intrinsic::x86_avx512_psrlv_d_512:
2939 case Intrinsic::x86_avx512_psrlv_q_512:
Craig Topper1de753f2016-11-18 06:04:33 +00002940 case Intrinsic::x86_avx512_psrlv_w_128:
2941 case Intrinsic::x86_avx512_psrlv_w_256:
2942 case Intrinsic::x86_avx512_psrlv_w_512:
Craig Topperbb4069e2017-07-07 23:16:26 +00002943 if (Value *V = simplifyX86varShift(*II, Builder))
Simon Pilgrimdb9893f2016-06-07 10:27:15 +00002944 return replaceInstUsesWith(*II, V);
2945 break;
2946
Simon Pilgrim6f6b2792017-01-25 14:37:24 +00002947 case Intrinsic::x86_sse2_packssdw_128:
2948 case Intrinsic::x86_sse2_packsswb_128:
2949 case Intrinsic::x86_avx2_packssdw:
2950 case Intrinsic::x86_avx2_packsswb:
Craig Topper3731f4d2017-02-16 07:35:23 +00002951 case Intrinsic::x86_avx512_packssdw_512:
2952 case Intrinsic::x86_avx512_packsswb_512:
Craig Topper4853c432017-07-06 23:18:42 +00002953 if (Value *V = simplifyX86pack(*II, true))
Simon Pilgrim6f6b2792017-01-25 14:37:24 +00002954 return replaceInstUsesWith(*II, V);
2955 break;
2956
2957 case Intrinsic::x86_sse2_packuswb_128:
2958 case Intrinsic::x86_sse41_packusdw:
2959 case Intrinsic::x86_avx2_packusdw:
2960 case Intrinsic::x86_avx2_packuswb:
Craig Topper3731f4d2017-02-16 07:35:23 +00002961 case Intrinsic::x86_avx512_packusdw_512:
2962 case Intrinsic::x86_avx512_packuswb_512:
Craig Topper4853c432017-07-06 23:18:42 +00002963 if (Value *V = simplifyX86pack(*II, false))
Simon Pilgrim6f6b2792017-01-25 14:37:24 +00002964 return replaceInstUsesWith(*II, V);
2965 break;
2966
Craig Topper911025b2018-05-13 21:56:32 +00002967 case Intrinsic::x86_pclmulqdq:
2968 case Intrinsic::x86_pclmulqdq_256:
2969 case Intrinsic::x86_pclmulqdq_512: {
Craig Topperb6122122017-01-26 05:17:13 +00002970 if (auto *C = dyn_cast<ConstantInt>(II->getArgOperand(2))) {
2971 unsigned Imm = C->getZExtValue();
2972
2973 bool MadeChange = false;
2974 Value *Arg0 = II->getArgOperand(0);
2975 Value *Arg1 = II->getArgOperand(1);
2976 unsigned VWidth = Arg0->getType()->getVectorNumElements();
Craig Topperb6122122017-01-26 05:17:13 +00002977
2978 APInt UndefElts1(VWidth, 0);
Craig Topper911025b2018-05-13 21:56:32 +00002979 APInt DemandedElts1 = APInt::getSplat(VWidth,
2980 APInt(2, (Imm & 0x01) ? 2 : 1));
2981 if (Value *V = SimplifyDemandedVectorElts(Arg0, DemandedElts1,
Craig Topperb6122122017-01-26 05:17:13 +00002982 UndefElts1)) {
2983 II->setArgOperand(0, V);
2984 MadeChange = true;
2985 }
2986
2987 APInt UndefElts2(VWidth, 0);
Craig Topper911025b2018-05-13 21:56:32 +00002988 APInt DemandedElts2 = APInt::getSplat(VWidth,
2989 APInt(2, (Imm & 0x10) ? 2 : 1));
2990 if (Value *V = SimplifyDemandedVectorElts(Arg1, DemandedElts2,
Craig Topperb6122122017-01-26 05:17:13 +00002991 UndefElts2)) {
2992 II->setArgOperand(1, V);
2993 MadeChange = true;
2994 }
2995
Craig Topper911025b2018-05-13 21:56:32 +00002996 // If either input elements are undef, the result is zero.
2997 if (DemandedElts1.isSubsetOf(UndefElts1) ||
2998 DemandedElts2.isSubsetOf(UndefElts2))
Craig Topperb6122122017-01-26 05:17:13 +00002999 return replaceInstUsesWith(*II,
3000 ConstantAggregateZero::get(II->getType()));
3001
3002 if (MadeChange)
3003 return II;
3004 }
3005 break;
3006 }
3007
Sanjay Patelc86867c2015-04-16 17:52:13 +00003008 case Intrinsic::x86_sse41_insertps:
Craig Topperbb4069e2017-07-07 23:16:26 +00003009 if (Value *V = simplifyX86insertps(*II, Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00003010 return replaceInstUsesWith(*II, V);
Sanjay Patelc86867c2015-04-16 17:52:13 +00003011 break;
Simon Pilgrim54fcd622015-07-25 20:41:00 +00003012
Simon Pilgrim61116dd2015-09-17 20:32:45 +00003013 case Intrinsic::x86_sse4a_extrq: {
Simon Pilgrim61116dd2015-09-17 20:32:45 +00003014 Value *Op0 = II->getArgOperand(0);
3015 Value *Op1 = II->getArgOperand(1);
3016 unsigned VWidth0 = Op0->getType()->getVectorNumElements();
3017 unsigned VWidth1 = Op1->getType()->getVectorNumElements();
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00003018 assert(Op0->getType()->getPrimitiveSizeInBits() == 128 &&
3019 Op1->getType()->getPrimitiveSizeInBits() == 128 && VWidth0 == 2 &&
3020 VWidth1 == 16 && "Unexpected operand sizes");
Simon Pilgrim61116dd2015-09-17 20:32:45 +00003021
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00003022 // See if we're dealing with constant values.
3023 Constant *C1 = dyn_cast<Constant>(Op1);
3024 ConstantInt *CILength =
Andrea Di Biagio8df5b9c2016-09-07 12:03:03 +00003025 C1 ? dyn_cast_or_null<ConstantInt>(C1->getAggregateElement((unsigned)0))
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00003026 : nullptr;
3027 ConstantInt *CIIndex =
Andrea Di Biagio8df5b9c2016-09-07 12:03:03 +00003028 C1 ? dyn_cast_or_null<ConstantInt>(C1->getAggregateElement((unsigned)1))
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00003029 : nullptr;
3030
3031 // Attempt to simplify to a constant, shuffle vector or EXTRQI call.
Craig Topperbb4069e2017-07-07 23:16:26 +00003032 if (Value *V = simplifyX86extrq(*II, Op0, CILength, CIIndex, Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00003033 return replaceInstUsesWith(*II, V);
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00003034
3035 // EXTRQ only uses the lowest 64-bits of the first 128-bit vector
3036 // operands and the lowest 16-bits of the second.
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00003037 bool MadeChange = false;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00003038 if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth0, 1)) {
3039 II->setArgOperand(0, V);
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00003040 MadeChange = true;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00003041 }
3042 if (Value *V = SimplifyDemandedVectorEltsLow(Op1, VWidth1, 2)) {
3043 II->setArgOperand(1, V);
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00003044 MadeChange = true;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00003045 }
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00003046 if (MadeChange)
3047 return II;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00003048 break;
3049 }
3050
3051 case Intrinsic::x86_sse4a_extrqi: {
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00003052 // EXTRQI: Extract Length bits starting from Index. Zero pad the remaining
3053 // bits of the lower 64-bits. The upper 64-bits are undefined.
3054 Value *Op0 = II->getArgOperand(0);
3055 unsigned VWidth = Op0->getType()->getVectorNumElements();
3056 assert(Op0->getType()->getPrimitiveSizeInBits() == 128 && VWidth == 2 &&
3057 "Unexpected operand size");
Simon Pilgrim61116dd2015-09-17 20:32:45 +00003058
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00003059 // See if we're dealing with constant values.
3060 ConstantInt *CILength = dyn_cast<ConstantInt>(II->getArgOperand(1));
3061 ConstantInt *CIIndex = dyn_cast<ConstantInt>(II->getArgOperand(2));
3062
3063 // Attempt to simplify to a constant or shuffle vector.
Craig Topperbb4069e2017-07-07 23:16:26 +00003064 if (Value *V = simplifyX86extrq(*II, Op0, CILength, CIIndex, Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00003065 return replaceInstUsesWith(*II, V);
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00003066
3067 // EXTRQI only uses the lowest 64-bits of the first 128-bit vector
3068 // operand.
3069 if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth, 1)) {
Simon Pilgrim61116dd2015-09-17 20:32:45 +00003070 II->setArgOperand(0, V);
3071 return II;
3072 }
3073 break;
3074 }
3075
3076 case Intrinsic::x86_sse4a_insertq: {
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00003077 Value *Op0 = II->getArgOperand(0);
3078 Value *Op1 = II->getArgOperand(1);
3079 unsigned VWidth = Op0->getType()->getVectorNumElements();
3080 assert(Op0->getType()->getPrimitiveSizeInBits() == 128 &&
3081 Op1->getType()->getPrimitiveSizeInBits() == 128 && VWidth == 2 &&
3082 Op1->getType()->getVectorNumElements() == 2 &&
3083 "Unexpected operand size");
Simon Pilgrim61116dd2015-09-17 20:32:45 +00003084
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00003085 // See if we're dealing with constant values.
3086 Constant *C1 = dyn_cast<Constant>(Op1);
3087 ConstantInt *CI11 =
Andrea Di Biagiof3fd3162016-09-07 12:47:53 +00003088 C1 ? dyn_cast_or_null<ConstantInt>(C1->getAggregateElement((unsigned)1))
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00003089 : nullptr;
3090
3091 // Attempt to simplify to a constant, shuffle vector or INSERTQI call.
3092 if (CI11) {
Benjamin Kramer46e38f32016-06-08 10:01:20 +00003093 const APInt &V11 = CI11->getValue();
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00003094 APInt Len = V11.zextOrTrunc(6);
3095 APInt Idx = V11.lshr(8).zextOrTrunc(6);
Craig Topperbb4069e2017-07-07 23:16:26 +00003096 if (Value *V = simplifyX86insertq(*II, Op0, Op1, Len, Idx, Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00003097 return replaceInstUsesWith(*II, V);
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00003098 }
3099
3100 // INSERTQ only uses the lowest 64-bits of the first 128-bit vector
3101 // operand.
3102 if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth, 1)) {
Simon Pilgrim61116dd2015-09-17 20:32:45 +00003103 II->setArgOperand(0, V);
3104 return II;
3105 }
3106 break;
3107 }
3108
Filipe Cabecinhas1a805952014-04-24 00:38:14 +00003109 case Intrinsic::x86_sse4a_insertqi: {
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00003110 // INSERTQI: Extract lowest Length bits from lower half of second source and
3111 // insert over first source starting at Index bit. The upper 64-bits are
3112 // undefined.
Simon Pilgrim61116dd2015-09-17 20:32:45 +00003113 Value *Op0 = II->getArgOperand(0);
3114 Value *Op1 = II->getArgOperand(1);
3115 unsigned VWidth0 = Op0->getType()->getVectorNumElements();
3116 unsigned VWidth1 = Op1->getType()->getVectorNumElements();
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00003117 assert(Op0->getType()->getPrimitiveSizeInBits() == 128 &&
3118 Op1->getType()->getPrimitiveSizeInBits() == 128 && VWidth0 == 2 &&
3119 VWidth1 == 2 && "Unexpected operand sizes");
Simon Pilgrim61116dd2015-09-17 20:32:45 +00003120
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00003121 // See if we're dealing with constant values.
3122 ConstantInt *CILength = dyn_cast<ConstantInt>(II->getArgOperand(2));
3123 ConstantInt *CIIndex = dyn_cast<ConstantInt>(II->getArgOperand(3));
3124
3125 // Attempt to simplify to a constant or shuffle vector.
3126 if (CILength && CIIndex) {
3127 APInt Len = CILength->getValue().zextOrTrunc(6);
3128 APInt Idx = CIIndex->getValue().zextOrTrunc(6);
Craig Topperbb4069e2017-07-07 23:16:26 +00003129 if (Value *V = simplifyX86insertq(*II, Op0, Op1, Len, Idx, Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00003130 return replaceInstUsesWith(*II, V);
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00003131 }
3132
3133 // INSERTQI only uses the lowest 64-bits of the first two 128-bit vector
3134 // operands.
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00003135 bool MadeChange = false;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00003136 if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth0, 1)) {
3137 II->setArgOperand(0, V);
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00003138 MadeChange = true;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00003139 }
Simon Pilgrim61116dd2015-09-17 20:32:45 +00003140 if (Value *V = SimplifyDemandedVectorEltsLow(Op1, VWidth1, 1)) {
3141 II->setArgOperand(1, V);
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00003142 MadeChange = true;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00003143 }
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00003144 if (MadeChange)
3145 return II;
Filipe Cabecinhas1a805952014-04-24 00:38:14 +00003146 break;
3147 }
3148
Filipe Cabecinhas82ac07c2014-05-27 03:42:20 +00003149 case Intrinsic::x86_sse41_pblendvb:
3150 case Intrinsic::x86_sse41_blendvps:
3151 case Intrinsic::x86_sse41_blendvpd:
3152 case Intrinsic::x86_avx_blendv_ps_256:
3153 case Intrinsic::x86_avx_blendv_pd_256:
3154 case Intrinsic::x86_avx2_pblendvb: {
Sanjay Patel296d35a2018-09-15 14:25:44 +00003155 // fold (blend A, A, Mask) -> A
Simon Pilgrim8c049d52015-08-12 08:08:56 +00003156 Value *Op0 = II->getArgOperand(0);
3157 Value *Op1 = II->getArgOperand(1);
Filipe Cabecinhas82ac07c2014-05-27 03:42:20 +00003158 Value *Mask = II->getArgOperand(2);
Simon Pilgrim8c049d52015-08-12 08:08:56 +00003159 if (Op0 == Op1)
Sanjay Patel4b198802016-02-01 22:23:39 +00003160 return replaceInstUsesWith(CI, Op0);
Simon Pilgrim8c049d52015-08-12 08:08:56 +00003161
3162 // Zero Mask - select 1st argument.
Simon Pilgrim93f59f52015-08-12 08:23:36 +00003163 if (isa<ConstantAggregateZero>(Mask))
Sanjay Patel4b198802016-02-01 22:23:39 +00003164 return replaceInstUsesWith(CI, Op0);
Simon Pilgrim8c049d52015-08-12 08:08:56 +00003165
3166 // Constant Mask - select 1st/2nd argument lane based on top bit of mask.
Sanjay Patel368ac5d2016-02-21 17:29:33 +00003167 if (auto *ConstantMask = dyn_cast<ConstantDataVector>(Mask)) {
3168 Constant *NewSelector = getNegativeIsTrueBoolVec(ConstantMask);
Simon Pilgrim8c049d52015-08-12 08:08:56 +00003169 return SelectInst::Create(NewSelector, Op1, Op0, "blendv");
Filipe Cabecinhas82ac07c2014-05-27 03:42:20 +00003170 }
Sanjay Patel296d35a2018-09-15 14:25:44 +00003171
3172 // Convert to a vector select if we can bypass casts and find a boolean
3173 // vector condition value.
3174 Value *BoolVec;
Sanjay Patel09e02fb2018-09-22 14:43:55 +00003175 Mask = peekThroughBitcast(Mask);
3176 if (match(Mask, m_SExt(m_Value(BoolVec))) &&
3177 BoolVec->getType()->isVectorTy() &&
3178 BoolVec->getType()->getScalarSizeInBits() == 1) {
3179 assert(Mask->getType()->getPrimitiveSizeInBits() ==
3180 II->getType()->getPrimitiveSizeInBits() &&
3181 "Not expecting mask and operands with different sizes");
3182
3183 unsigned NumMaskElts = Mask->getType()->getVectorNumElements();
3184 unsigned NumOperandElts = II->getType()->getVectorNumElements();
3185 if (NumMaskElts == NumOperandElts)
Sanjay Patel296d35a2018-09-15 14:25:44 +00003186 return SelectInst::Create(BoolVec, Op1, Op0);
Sanjay Patel09e02fb2018-09-22 14:43:55 +00003187
3188 // If the mask has less elements than the operands, each mask bit maps to
3189 // multiple elements of the operands. Bitcast back and forth.
3190 if (NumMaskElts < NumOperandElts) {
3191 Value *CastOp0 = Builder.CreateBitCast(Op0, Mask->getType());
3192 Value *CastOp1 = Builder.CreateBitCast(Op1, Mask->getType());
3193 Value *Sel = Builder.CreateSelect(BoolVec, CastOp1, CastOp0);
3194 return new BitCastInst(Sel, II->getType());
3195 }
Sanjay Patel296d35a2018-09-15 14:25:44 +00003196 }
3197
Simon Pilgrim8c049d52015-08-12 08:08:56 +00003198 break;
Filipe Cabecinhas82ac07c2014-05-27 03:42:20 +00003199 }
3200
Andrea Di Biagio0594e2a2015-09-30 16:44:39 +00003201 case Intrinsic::x86_ssse3_pshuf_b_128:
Simon Pilgrimc0c56e72016-04-24 17:00:34 +00003202 case Intrinsic::x86_avx2_pshuf_b:
Simon Pilgrima22c3a12017-01-18 13:44:04 +00003203 case Intrinsic::x86_avx512_pshuf_b_512:
Craig Topperbb4069e2017-07-07 23:16:26 +00003204 if (Value *V = simplifyX86pshufb(*II, Builder))
Simon Pilgrimc0c56e72016-04-24 17:00:34 +00003205 return replaceInstUsesWith(*II, V);
3206 break;
Andrea Di Biagio0594e2a2015-09-30 16:44:39 +00003207
Rafael Espindolabad3f772014-04-21 22:06:04 +00003208 case Intrinsic::x86_avx_vpermilvar_ps:
3209 case Intrinsic::x86_avx_vpermilvar_ps_256:
Craig Topper58917f32016-12-11 01:59:36 +00003210 case Intrinsic::x86_avx512_vpermilvar_ps_512:
Rafael Espindolabad3f772014-04-21 22:06:04 +00003211 case Intrinsic::x86_avx_vpermilvar_pd:
Simon Pilgrim2f6097d2016-04-24 17:23:46 +00003212 case Intrinsic::x86_avx_vpermilvar_pd_256:
Simon Pilgrima22c3a12017-01-18 13:44:04 +00003213 case Intrinsic::x86_avx512_vpermilvar_pd_512:
Craig Topperbb4069e2017-07-07 23:16:26 +00003214 if (Value *V = simplifyX86vpermilvar(*II, Builder))
Simon Pilgrim2f6097d2016-04-24 17:23:46 +00003215 return replaceInstUsesWith(*II, V);
3216 break;
Rafael Espindolabad3f772014-04-21 22:06:04 +00003217
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +00003218 case Intrinsic::x86_avx2_permd:
3219 case Intrinsic::x86_avx2_permps:
Craig Toppere4c045b2018-05-20 23:34:04 +00003220 case Intrinsic::x86_avx512_permvar_df_256:
3221 case Intrinsic::x86_avx512_permvar_df_512:
3222 case Intrinsic::x86_avx512_permvar_di_256:
3223 case Intrinsic::x86_avx512_permvar_di_512:
3224 case Intrinsic::x86_avx512_permvar_hi_128:
3225 case Intrinsic::x86_avx512_permvar_hi_256:
3226 case Intrinsic::x86_avx512_permvar_hi_512:
3227 case Intrinsic::x86_avx512_permvar_qi_128:
3228 case Intrinsic::x86_avx512_permvar_qi_256:
3229 case Intrinsic::x86_avx512_permvar_qi_512:
3230 case Intrinsic::x86_avx512_permvar_sf_512:
3231 case Intrinsic::x86_avx512_permvar_si_512:
Craig Topperbb4069e2017-07-07 23:16:26 +00003232 if (Value *V = simplifyX86vpermv(*II, Builder))
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +00003233 return replaceInstUsesWith(*II, V);
3234 break;
3235
Sanjay Patel98a71502016-02-29 23:16:48 +00003236 case Intrinsic::x86_avx_maskload_ps:
Sanjay Patel6f2c01f2016-02-29 23:59:00 +00003237 case Intrinsic::x86_avx_maskload_pd:
3238 case Intrinsic::x86_avx_maskload_ps_256:
3239 case Intrinsic::x86_avx_maskload_pd_256:
3240 case Intrinsic::x86_avx2_maskload_d:
3241 case Intrinsic::x86_avx2_maskload_q:
3242 case Intrinsic::x86_avx2_maskload_d_256:
3243 case Intrinsic::x86_avx2_maskload_q_256:
Sanjay Patel98a71502016-02-29 23:16:48 +00003244 if (Instruction *I = simplifyX86MaskedLoad(*II, *this))
3245 return I;
3246 break;
3247
Sanjay Patelc4acbae2016-03-12 15:16:59 +00003248 case Intrinsic::x86_sse2_maskmov_dqu:
Sanjay Patel1ace9932016-02-26 21:04:14 +00003249 case Intrinsic::x86_avx_maskstore_ps:
3250 case Intrinsic::x86_avx_maskstore_pd:
3251 case Intrinsic::x86_avx_maskstore_ps_256:
3252 case Intrinsic::x86_avx_maskstore_pd_256:
Sanjay Patelfc7e7eb2016-02-26 21:51:44 +00003253 case Intrinsic::x86_avx2_maskstore_d:
3254 case Intrinsic::x86_avx2_maskstore_q:
3255 case Intrinsic::x86_avx2_maskstore_d_256:
3256 case Intrinsic::x86_avx2_maskstore_q_256:
Sanjay Patel1ace9932016-02-26 21:04:14 +00003257 if (simplifyX86MaskedStore(*II, *this))
3258 return nullptr;
3259 break;
3260
Sanjay Patelbe23a912019-02-01 14:14:47 +00003261 case Intrinsic::x86_addcarry_32:
3262 case Intrinsic::x86_addcarry_64:
3263 if (Value *V = simplifyX86addcarry(*II, Builder))
3264 return replaceInstUsesWith(*II, V);
3265 break;
3266
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003267 case Intrinsic::ppc_altivec_vperm:
3268 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
Bill Schmidta1184632014-06-05 19:46:04 +00003269 // Note that ppc_altivec_vperm has a big-endian bias, so when creating
3270 // a vectorshuffle for little endian, we must undo the transformation
3271 // performed on vec_perm in altivec.h. That is, we must complement
3272 // the permutation mask with respect to 31 and reverse the order of
3273 // V1 and V2.
Chris Lattner0256be92012-01-27 03:08:05 +00003274 if (Constant *Mask = dyn_cast<Constant>(II->getArgOperand(2))) {
3275 assert(Mask->getType()->getVectorNumElements() == 16 &&
3276 "Bad type for intrinsic!");
Jim Grosbach7815f562012-02-03 00:07:04 +00003277
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003278 // Check that all of the elements are integer constants or undefs.
3279 bool AllEltsOk = true;
3280 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0256be92012-01-27 03:08:05 +00003281 Constant *Elt = Mask->getAggregateElement(i);
Craig Topperf40110f2014-04-25 05:29:35 +00003282 if (!Elt || !(isa<ConstantInt>(Elt) || isa<UndefValue>(Elt))) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003283 AllEltsOk = false;
3284 break;
3285 }
3286 }
Jim Grosbach7815f562012-02-03 00:07:04 +00003287
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003288 if (AllEltsOk) {
3289 // Cast the input vectors to byte vectors.
Craig Topperbb4069e2017-07-07 23:16:26 +00003290 Value *Op0 = Builder.CreateBitCast(II->getArgOperand(0),
3291 Mask->getType());
3292 Value *Op1 = Builder.CreateBitCast(II->getArgOperand(1),
3293 Mask->getType());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003294 Value *Result = UndefValue::get(Op0->getType());
Jim Grosbach7815f562012-02-03 00:07:04 +00003295
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003296 // Only extract each element once.
3297 Value *ExtractedElts[32];
3298 memset(ExtractedElts, 0, sizeof(ExtractedElts));
Jim Grosbach7815f562012-02-03 00:07:04 +00003299
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003300 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0256be92012-01-27 03:08:05 +00003301 if (isa<UndefValue>(Mask->getAggregateElement(i)))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003302 continue;
Jim Grosbach7815f562012-02-03 00:07:04 +00003303 unsigned Idx =
Chris Lattner0256be92012-01-27 03:08:05 +00003304 cast<ConstantInt>(Mask->getAggregateElement(i))->getZExtValue();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003305 Idx &= 31; // Match the hardware behavior.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003306 if (DL.isLittleEndian())
Bill Schmidta1184632014-06-05 19:46:04 +00003307 Idx = 31 - Idx;
Jim Grosbach7815f562012-02-03 00:07:04 +00003308
Craig Topperf40110f2014-04-25 05:29:35 +00003309 if (!ExtractedElts[Idx]) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003310 Value *Op0ToUse = (DL.isLittleEndian()) ? Op1 : Op0;
3311 Value *Op1ToUse = (DL.isLittleEndian()) ? Op0 : Op1;
Jim Grosbach7815f562012-02-03 00:07:04 +00003312 ExtractedElts[Idx] =
Craig Topperbb4069e2017-07-07 23:16:26 +00003313 Builder.CreateExtractElement(Idx < 16 ? Op0ToUse : Op1ToUse,
3314 Builder.getInt32(Idx&15));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003315 }
Jim Grosbach7815f562012-02-03 00:07:04 +00003316
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003317 // Insert this value into the result vector.
Craig Topperbb4069e2017-07-07 23:16:26 +00003318 Result = Builder.CreateInsertElement(Result, ExtractedElts[Idx],
3319 Builder.getInt32(i));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003320 }
3321 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
3322 }
3323 }
3324 break;
3325
Alexandros Lamprineas61f0ba12018-05-31 12:19:18 +00003326 case Intrinsic::arm_neon_vld1: {
3327 unsigned MemAlign = getKnownAlignment(II->getArgOperand(0),
3328 DL, II, &AC, &DT);
3329 if (Value *V = simplifyNeonVld1(*II, MemAlign, Builder))
3330 return replaceInstUsesWith(*II, V);
3331 break;
3332 }
3333
Bob Wilsona4e231c2010-10-22 21:41:48 +00003334 case Intrinsic::arm_neon_vld2:
3335 case Intrinsic::arm_neon_vld3:
3336 case Intrinsic::arm_neon_vld4:
3337 case Intrinsic::arm_neon_vld2lane:
3338 case Intrinsic::arm_neon_vld3lane:
3339 case Intrinsic::arm_neon_vld4lane:
3340 case Intrinsic::arm_neon_vst1:
3341 case Intrinsic::arm_neon_vst2:
3342 case Intrinsic::arm_neon_vst3:
3343 case Intrinsic::arm_neon_vst4:
3344 case Intrinsic::arm_neon_vst2lane:
3345 case Intrinsic::arm_neon_vst3lane:
3346 case Intrinsic::arm_neon_vst4lane: {
Justin Bogner99798402016-08-05 01:06:44 +00003347 unsigned MemAlign =
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003348 getKnownAlignment(II->getArgOperand(0), DL, II, &AC, &DT);
Bob Wilsona4e231c2010-10-22 21:41:48 +00003349 unsigned AlignArg = II->getNumArgOperands() - 1;
3350 ConstantInt *IntrAlign = dyn_cast<ConstantInt>(II->getArgOperand(AlignArg));
3351 if (IntrAlign && IntrAlign->getZExtValue() < MemAlign) {
3352 II->setArgOperand(AlignArg,
3353 ConstantInt::get(Type::getInt32Ty(II->getContext()),
3354 MemAlign, false));
3355 return II;
3356 }
3357 break;
3358 }
3359
Alexandros Lamprineas52457d32018-05-30 14:38:50 +00003360 case Intrinsic::arm_neon_vtbl1:
3361 case Intrinsic::aarch64_neon_tbl1:
3362 if (Value *V = simplifyNeonTbl1(*II, Builder))
3363 return replaceInstUsesWith(*II, V);
3364 break;
3365
Lang Hames3a90fab2012-05-01 00:20:38 +00003366 case Intrinsic::arm_neon_vmulls:
Tim Northover00ed9962014-03-29 10:18:08 +00003367 case Intrinsic::arm_neon_vmullu:
Tim Northover3b0846e2014-05-24 12:50:23 +00003368 case Intrinsic::aarch64_neon_smull:
3369 case Intrinsic::aarch64_neon_umull: {
Lang Hames3a90fab2012-05-01 00:20:38 +00003370 Value *Arg0 = II->getArgOperand(0);
3371 Value *Arg1 = II->getArgOperand(1);
3372
3373 // Handle mul by zero first:
3374 if (isa<ConstantAggregateZero>(Arg0) || isa<ConstantAggregateZero>(Arg1)) {
Sanjay Patel4b198802016-02-01 22:23:39 +00003375 return replaceInstUsesWith(CI, ConstantAggregateZero::get(II->getType()));
Lang Hames3a90fab2012-05-01 00:20:38 +00003376 }
3377
3378 // Check for constant LHS & RHS - in this case we just simplify.
Tim Northover00ed9962014-03-29 10:18:08 +00003379 bool Zext = (II->getIntrinsicID() == Intrinsic::arm_neon_vmullu ||
Tim Northover3b0846e2014-05-24 12:50:23 +00003380 II->getIntrinsicID() == Intrinsic::aarch64_neon_umull);
Lang Hames3a90fab2012-05-01 00:20:38 +00003381 VectorType *NewVT = cast<VectorType>(II->getType());
Benjamin Kramer92040952014-02-13 18:23:24 +00003382 if (Constant *CV0 = dyn_cast<Constant>(Arg0)) {
3383 if (Constant *CV1 = dyn_cast<Constant>(Arg1)) {
3384 CV0 = ConstantExpr::getIntegerCast(CV0, NewVT, /*isSigned=*/!Zext);
3385 CV1 = ConstantExpr::getIntegerCast(CV1, NewVT, /*isSigned=*/!Zext);
3386
Sanjay Patel4b198802016-02-01 22:23:39 +00003387 return replaceInstUsesWith(CI, ConstantExpr::getMul(CV0, CV1));
Lang Hames3a90fab2012-05-01 00:20:38 +00003388 }
3389
Alp Tokercb402912014-01-24 17:20:08 +00003390 // Couldn't simplify - canonicalize constant to the RHS.
Lang Hames3a90fab2012-05-01 00:20:38 +00003391 std::swap(Arg0, Arg1);
3392 }
3393
3394 // Handle mul by one:
Benjamin Kramer92040952014-02-13 18:23:24 +00003395 if (Constant *CV1 = dyn_cast<Constant>(Arg1))
Lang Hames3a90fab2012-05-01 00:20:38 +00003396 if (ConstantInt *Splat =
Benjamin Kramer92040952014-02-13 18:23:24 +00003397 dyn_cast_or_null<ConstantInt>(CV1->getSplatValue()))
3398 if (Splat->isOne())
3399 return CastInst::CreateIntegerCast(Arg0, II->getType(),
3400 /*isSigned=*/!Zext);
Lang Hames3a90fab2012-05-01 00:20:38 +00003401
3402 break;
3403 }
Chad Rosier274d72f2018-05-24 15:26:42 +00003404 case Intrinsic::arm_neon_aesd:
3405 case Intrinsic::arm_neon_aese:
3406 case Intrinsic::aarch64_crypto_aesd:
3407 case Intrinsic::aarch64_crypto_aese: {
3408 Value *DataArg = II->getArgOperand(0);
3409 Value *KeyArg = II->getArgOperand(1);
3410
3411 // Try to use the builtin XOR in AESE and AESD to eliminate a prior XOR
3412 Value *Data, *Key;
3413 if (match(KeyArg, m_ZeroInt()) &&
3414 match(DataArg, m_Xor(m_Value(Data), m_Value(Key)))) {
3415 II->setArgOperand(0, Data);
3416 II->setArgOperand(1, Key);
3417 return II;
3418 }
3419 break;
3420 }
Matt Arsenaultbef34e22016-01-22 21:30:34 +00003421 case Intrinsic::amdgcn_rcp: {
Matt Arsenault4c7795d2017-03-24 19:04:57 +00003422 Value *Src = II->getArgOperand(0);
3423
3424 // TODO: Move to ConstantFolding/InstSimplify?
3425 if (isa<UndefValue>(Src))
3426 return replaceInstUsesWith(CI, Src);
3427
3428 if (const ConstantFP *C = dyn_cast<ConstantFP>(Src)) {
Matt Arsenaulta0050b02014-06-19 01:19:19 +00003429 const APFloat &ArgVal = C->getValueAPF();
3430 APFloat Val(ArgVal.getSemantics(), 1.0);
3431 APFloat::opStatus Status = Val.divide(ArgVal,
3432 APFloat::rmNearestTiesToEven);
3433 // Only do this if it was exact and therefore not dependent on the
3434 // rounding mode.
3435 if (Status == APFloat::opOK)
Sanjay Patel4b198802016-02-01 22:23:39 +00003436 return replaceInstUsesWith(CI, ConstantFP::get(II->getContext(), Val));
Matt Arsenaulta0050b02014-06-19 01:19:19 +00003437 }
3438
3439 break;
3440 }
Matt Arsenault4c7795d2017-03-24 19:04:57 +00003441 case Intrinsic::amdgcn_rsq: {
3442 Value *Src = II->getArgOperand(0);
3443
3444 // TODO: Move to ConstantFolding/InstSimplify?
3445 if (isa<UndefValue>(Src))
3446 return replaceInstUsesWith(CI, Src);
3447 break;
3448 }
Matt Arsenault2fe4fbc2016-03-30 22:28:52 +00003449 case Intrinsic::amdgcn_frexp_mant:
3450 case Intrinsic::amdgcn_frexp_exp: {
Matt Arsenault5cd4f8f2016-03-30 22:28:26 +00003451 Value *Src = II->getArgOperand(0);
3452 if (const ConstantFP *C = dyn_cast<ConstantFP>(Src)) {
3453 int Exp;
3454 APFloat Significand = frexp(C->getValueAPF(), Exp,
3455 APFloat::rmNearestTiesToEven);
3456
Matt Arsenault2fe4fbc2016-03-30 22:28:52 +00003457 if (II->getIntrinsicID() == Intrinsic::amdgcn_frexp_mant) {
3458 return replaceInstUsesWith(CI, ConstantFP::get(II->getContext(),
3459 Significand));
3460 }
3461
3462 // Match instruction special case behavior.
3463 if (Exp == APFloat::IEK_NaN || Exp == APFloat::IEK_Inf)
3464 Exp = 0;
3465
3466 return replaceInstUsesWith(CI, ConstantInt::get(II->getType(), Exp));
3467 }
3468
3469 if (isa<UndefValue>(Src))
3470 return replaceInstUsesWith(CI, UndefValue::get(II->getType()));
Matt Arsenault5cd4f8f2016-03-30 22:28:26 +00003471
3472 break;
3473 }
Matt Arsenault46a03822016-09-03 07:06:58 +00003474 case Intrinsic::amdgcn_class: {
3475 enum {
3476 S_NAN = 1 << 0, // Signaling NaN
3477 Q_NAN = 1 << 1, // Quiet NaN
3478 N_INFINITY = 1 << 2, // Negative infinity
3479 N_NORMAL = 1 << 3, // Negative normal
3480 N_SUBNORMAL = 1 << 4, // Negative subnormal
3481 N_ZERO = 1 << 5, // Negative zero
3482 P_ZERO = 1 << 6, // Positive zero
3483 P_SUBNORMAL = 1 << 7, // Positive subnormal
3484 P_NORMAL = 1 << 8, // Positive normal
3485 P_INFINITY = 1 << 9 // Positive infinity
3486 };
3487
3488 const uint32_t FullMask = S_NAN | Q_NAN | N_INFINITY | N_NORMAL |
3489 N_SUBNORMAL | N_ZERO | P_ZERO | P_SUBNORMAL | P_NORMAL | P_INFINITY;
3490
3491 Value *Src0 = II->getArgOperand(0);
3492 Value *Src1 = II->getArgOperand(1);
3493 const ConstantInt *CMask = dyn_cast<ConstantInt>(Src1);
3494 if (!CMask) {
3495 if (isa<UndefValue>(Src0))
3496 return replaceInstUsesWith(*II, UndefValue::get(II->getType()));
3497
3498 if (isa<UndefValue>(Src1))
3499 return replaceInstUsesWith(*II, ConstantInt::get(II->getType(), false));
3500 break;
3501 }
3502
3503 uint32_t Mask = CMask->getZExtValue();
3504
3505 // If all tests are made, it doesn't matter what the value is.
3506 if ((Mask & FullMask) == FullMask)
3507 return replaceInstUsesWith(*II, ConstantInt::get(II->getType(), true));
3508
3509 if ((Mask & FullMask) == 0)
3510 return replaceInstUsesWith(*II, ConstantInt::get(II->getType(), false));
3511
3512 if (Mask == (S_NAN | Q_NAN)) {
3513 // Equivalent of isnan. Replace with standard fcmp.
Craig Topperbb4069e2017-07-07 23:16:26 +00003514 Value *FCmp = Builder.CreateFCmpUNO(Src0, Src0);
Matt Arsenault46a03822016-09-03 07:06:58 +00003515 FCmp->takeName(II);
3516 return replaceInstUsesWith(*II, FCmp);
3517 }
3518
Matt Arsenaultd35f46c2018-08-10 18:58:49 +00003519 if (Mask == (N_ZERO | P_ZERO)) {
3520 // Equivalent of == 0.
3521 Value *FCmp = Builder.CreateFCmpOEQ(
3522 Src0, ConstantFP::get(Src0->getType(), 0.0));
3523
3524 FCmp->takeName(II);
3525 return replaceInstUsesWith(*II, FCmp);
3526 }
3527
Matt Arsenault10de2772018-08-28 18:10:02 +00003528 // fp_class (nnan x), qnan|snan|other -> fp_class (nnan x), other
3529 if (((Mask & S_NAN) || (Mask & Q_NAN)) && isKnownNeverNaN(Src0, &TLI)) {
3530 II->setArgOperand(1, ConstantInt::get(Src1->getType(),
3531 Mask & ~(S_NAN | Q_NAN)));
3532 return II;
3533 }
3534
Matt Arsenault46a03822016-09-03 07:06:58 +00003535 const ConstantFP *CVal = dyn_cast<ConstantFP>(Src0);
3536 if (!CVal) {
3537 if (isa<UndefValue>(Src0))
3538 return replaceInstUsesWith(*II, UndefValue::get(II->getType()));
3539
3540 // Clamp mask to used bits
3541 if ((Mask & FullMask) != Mask) {
Craig Topperbb4069e2017-07-07 23:16:26 +00003542 CallInst *NewCall = Builder.CreateCall(II->getCalledFunction(),
Matt Arsenault46a03822016-09-03 07:06:58 +00003543 { Src0, ConstantInt::get(Src1->getType(), Mask & FullMask) }
3544 );
3545
3546 NewCall->takeName(II);
3547 return replaceInstUsesWith(*II, NewCall);
3548 }
3549
3550 break;
3551 }
3552
3553 const APFloat &Val = CVal->getValueAPF();
3554
3555 bool Result =
3556 ((Mask & S_NAN) && Val.isNaN() && Val.isSignaling()) ||
3557 ((Mask & Q_NAN) && Val.isNaN() && !Val.isSignaling()) ||
3558 ((Mask & N_INFINITY) && Val.isInfinity() && Val.isNegative()) ||
3559 ((Mask & N_NORMAL) && Val.isNormal() && Val.isNegative()) ||
3560 ((Mask & N_SUBNORMAL) && Val.isDenormal() && Val.isNegative()) ||
3561 ((Mask & N_ZERO) && Val.isZero() && Val.isNegative()) ||
3562 ((Mask & P_ZERO) && Val.isZero() && !Val.isNegative()) ||
3563 ((Mask & P_SUBNORMAL) && Val.isDenormal() && !Val.isNegative()) ||
3564 ((Mask & P_NORMAL) && Val.isNormal() && !Val.isNegative()) ||
3565 ((Mask & P_INFINITY) && Val.isInfinity() && !Val.isNegative());
3566
3567 return replaceInstUsesWith(*II, ConstantInt::get(II->getType(), Result));
3568 }
Matt Arsenault1f17c662017-02-22 00:27:34 +00003569 case Intrinsic::amdgcn_cvt_pkrtz: {
3570 Value *Src0 = II->getArgOperand(0);
3571 Value *Src1 = II->getArgOperand(1);
3572 if (const ConstantFP *C0 = dyn_cast<ConstantFP>(Src0)) {
3573 if (const ConstantFP *C1 = dyn_cast<ConstantFP>(Src1)) {
3574 const fltSemantics &HalfSem
3575 = II->getType()->getScalarType()->getFltSemantics();
3576 bool LosesInfo;
3577 APFloat Val0 = C0->getValueAPF();
3578 APFloat Val1 = C1->getValueAPF();
3579 Val0.convert(HalfSem, APFloat::rmTowardZero, &LosesInfo);
3580 Val1.convert(HalfSem, APFloat::rmTowardZero, &LosesInfo);
3581
3582 Constant *Folded = ConstantVector::get({
3583 ConstantFP::get(II->getContext(), Val0),
3584 ConstantFP::get(II->getContext(), Val1) });
3585 return replaceInstUsesWith(*II, Folded);
3586 }
3587 }
3588
3589 if (isa<UndefValue>(Src0) && isa<UndefValue>(Src1))
3590 return replaceInstUsesWith(*II, UndefValue::get(II->getType()));
3591
3592 break;
3593 }
Marek Olsak13e47412018-01-31 20:18:04 +00003594 case Intrinsic::amdgcn_cvt_pknorm_i16:
3595 case Intrinsic::amdgcn_cvt_pknorm_u16:
3596 case Intrinsic::amdgcn_cvt_pk_i16:
3597 case Intrinsic::amdgcn_cvt_pk_u16: {
3598 Value *Src0 = II->getArgOperand(0);
3599 Value *Src1 = II->getArgOperand(1);
3600
3601 if (isa<UndefValue>(Src0) && isa<UndefValue>(Src1))
3602 return replaceInstUsesWith(*II, UndefValue::get(II->getType()));
3603
3604 break;
3605 }
Matt Arsenaultf5262252017-02-22 23:04:58 +00003606 case Intrinsic::amdgcn_ubfe:
3607 case Intrinsic::amdgcn_sbfe: {
3608 // Decompose simple cases into standard shifts.
3609 Value *Src = II->getArgOperand(0);
3610 if (isa<UndefValue>(Src))
3611 return replaceInstUsesWith(*II, Src);
3612
3613 unsigned Width;
3614 Type *Ty = II->getType();
3615 unsigned IntSize = Ty->getIntegerBitWidth();
3616
3617 ConstantInt *CWidth = dyn_cast<ConstantInt>(II->getArgOperand(2));
3618 if (CWidth) {
3619 Width = CWidth->getZExtValue();
3620 if ((Width & (IntSize - 1)) == 0)
3621 return replaceInstUsesWith(*II, ConstantInt::getNullValue(Ty));
3622
3623 if (Width >= IntSize) {
3624 // Hardware ignores high bits, so remove those.
3625 II->setArgOperand(2, ConstantInt::get(CWidth->getType(),
3626 Width & (IntSize - 1)));
3627 return II;
3628 }
3629 }
3630
3631 unsigned Offset;
3632 ConstantInt *COffset = dyn_cast<ConstantInt>(II->getArgOperand(1));
3633 if (COffset) {
3634 Offset = COffset->getZExtValue();
3635 if (Offset >= IntSize) {
3636 II->setArgOperand(1, ConstantInt::get(COffset->getType(),
3637 Offset & (IntSize - 1)));
3638 return II;
3639 }
3640 }
3641
3642 bool Signed = II->getIntrinsicID() == Intrinsic::amdgcn_sbfe;
3643
Matt Arsenaultf5262252017-02-22 23:04:58 +00003644 if (!CWidth || !COffset)
3645 break;
3646
Tom Stellard28d66212018-11-08 17:57:57 +00003647 // The case of Width == 0 is handled above, which makes this tranformation
3648 // safe. If Width == 0, then the ashr and lshr instructions become poison
3649 // value since the shift amount would be equal to the bit size.
3650 assert(Width != 0);
3651
Matt Arsenaultf5262252017-02-22 23:04:58 +00003652 // TODO: This allows folding to undef when the hardware has specific
3653 // behavior?
3654 if (Offset + Width < IntSize) {
Craig Topperbb4069e2017-07-07 23:16:26 +00003655 Value *Shl = Builder.CreateShl(Src, IntSize - Offset - Width);
3656 Value *RightShift = Signed ? Builder.CreateAShr(Shl, IntSize - Width)
3657 : Builder.CreateLShr(Shl, IntSize - Width);
Matt Arsenaultf5262252017-02-22 23:04:58 +00003658 RightShift->takeName(II);
3659 return replaceInstUsesWith(*II, RightShift);
3660 }
3661
Craig Topperbb4069e2017-07-07 23:16:26 +00003662 Value *RightShift = Signed ? Builder.CreateAShr(Src, Offset)
3663 : Builder.CreateLShr(Src, Offset);
Matt Arsenaultf5262252017-02-22 23:04:58 +00003664
3665 RightShift->takeName(II);
3666 return replaceInstUsesWith(*II, RightShift);
3667 }
Matt Arsenaultd4bca1e2017-02-23 00:44:03 +00003668 case Intrinsic::amdgcn_exp:
3669 case Intrinsic::amdgcn_exp_compr: {
Matt Arsenaultcaf13162019-03-12 21:02:54 +00003670 ConstantInt *En = cast<ConstantInt>(II->getArgOperand(1));
Matt Arsenaultd4bca1e2017-02-23 00:44:03 +00003671 unsigned EnBits = En->getZExtValue();
3672 if (EnBits == 0xf)
3673 break; // All inputs enabled.
3674
3675 bool IsCompr = II->getIntrinsicID() == Intrinsic::amdgcn_exp_compr;
3676 bool Changed = false;
3677 for (int I = 0; I < (IsCompr ? 2 : 4); ++I) {
3678 if ((!IsCompr && (EnBits & (1 << I)) == 0) ||
3679 (IsCompr && ((EnBits & (0x3 << (2 * I))) == 0))) {
3680 Value *Src = II->getArgOperand(I + 2);
3681 if (!isa<UndefValue>(Src)) {
3682 II->setArgOperand(I + 2, UndefValue::get(Src->getType()));
3683 Changed = true;
3684 }
3685 }
3686 }
3687
3688 if (Changed)
3689 return II;
3690
3691 break;
Matt Arsenaultcdb468c2017-02-27 23:08:49 +00003692 }
3693 case Intrinsic::amdgcn_fmed3: {
3694 // Note this does not preserve proper sNaN behavior if IEEE-mode is enabled
3695 // for the shader.
3696
3697 Value *Src0 = II->getArgOperand(0);
3698 Value *Src1 = II->getArgOperand(1);
3699 Value *Src2 = II->getArgOperand(2);
3700
Matt Arsenault24ce89b2018-07-05 17:05:36 +00003701 // Checking for NaN before canonicalization provides better fidelity when
3702 // mapping other operations onto fmed3 since the order of operands is
3703 // unchanged.
3704 CallInst *NewCall = nullptr;
3705 if (match(Src0, m_NaN()) || isa<UndefValue>(Src0)) {
3706 NewCall = Builder.CreateMinNum(Src1, Src2);
3707 } else if (match(Src1, m_NaN()) || isa<UndefValue>(Src1)) {
3708 NewCall = Builder.CreateMinNum(Src0, Src2);
3709 } else if (match(Src2, m_NaN()) || isa<UndefValue>(Src2)) {
3710 NewCall = Builder.CreateMaxNum(Src0, Src1);
3711 }
3712
3713 if (NewCall) {
3714 NewCall->copyFastMathFlags(II);
3715 NewCall->takeName(II);
3716 return replaceInstUsesWith(*II, NewCall);
3717 }
3718
Matt Arsenaultcdb468c2017-02-27 23:08:49 +00003719 bool Swap = false;
3720 // Canonicalize constants to RHS operands.
3721 //
3722 // fmed3(c0, x, c1) -> fmed3(x, c0, c1)
3723 if (isa<Constant>(Src0) && !isa<Constant>(Src1)) {
3724 std::swap(Src0, Src1);
3725 Swap = true;
3726 }
3727
3728 if (isa<Constant>(Src1) && !isa<Constant>(Src2)) {
3729 std::swap(Src1, Src2);
3730 Swap = true;
3731 }
3732
3733 if (isa<Constant>(Src0) && !isa<Constant>(Src1)) {
3734 std::swap(Src0, Src1);
3735 Swap = true;
3736 }
3737
3738 if (Swap) {
3739 II->setArgOperand(0, Src0);
3740 II->setArgOperand(1, Src1);
3741 II->setArgOperand(2, Src2);
3742 return II;
3743 }
3744
Matt Arsenaultcdb468c2017-02-27 23:08:49 +00003745 if (const ConstantFP *C0 = dyn_cast<ConstantFP>(Src0)) {
3746 if (const ConstantFP *C1 = dyn_cast<ConstantFP>(Src1)) {
3747 if (const ConstantFP *C2 = dyn_cast<ConstantFP>(Src2)) {
3748 APFloat Result = fmed3AMDGCN(C0->getValueAPF(), C1->getValueAPF(),
3749 C2->getValueAPF());
3750 return replaceInstUsesWith(*II,
Craig Topperbb4069e2017-07-07 23:16:26 +00003751 ConstantFP::get(Builder.getContext(), Result));
Matt Arsenaultcdb468c2017-02-27 23:08:49 +00003752 }
3753 }
3754 }
3755
3756 break;
Matt Arsenaultd4bca1e2017-02-23 00:44:03 +00003757 }
Matt Arsenaultd81f5572017-03-13 18:14:02 +00003758 case Intrinsic::amdgcn_icmp:
3759 case Intrinsic::amdgcn_fcmp: {
Matt Arsenaultcaf13162019-03-12 21:02:54 +00003760 const ConstantInt *CC = cast<ConstantInt>(II->getArgOperand(2));
Matt Arsenaultd81f5572017-03-13 18:14:02 +00003761 // Guard against invalid arguments.
3762 int64_t CCVal = CC->getZExtValue();
3763 bool IsInteger = II->getIntrinsicID() == Intrinsic::amdgcn_icmp;
3764 if ((IsInteger && (CCVal < CmpInst::FIRST_ICMP_PREDICATE ||
3765 CCVal > CmpInst::LAST_ICMP_PREDICATE)) ||
3766 (!IsInteger && (CCVal < CmpInst::FIRST_FCMP_PREDICATE ||
3767 CCVal > CmpInst::LAST_FCMP_PREDICATE)))
3768 break;
3769
3770 Value *Src0 = II->getArgOperand(0);
3771 Value *Src1 = II->getArgOperand(1);
3772
3773 if (auto *CSrc0 = dyn_cast<Constant>(Src0)) {
3774 if (auto *CSrc1 = dyn_cast<Constant>(Src1)) {
3775 Constant *CCmp = ConstantExpr::getCompare(CCVal, CSrc0, CSrc1);
Nicolai Haehnle9c661852017-04-24 17:08:43 +00003776 if (CCmp->isNullValue()) {
3777 return replaceInstUsesWith(
3778 *II, ConstantExpr::getSExt(CCmp, II->getType()));
3779 }
3780
3781 // The result of V_ICMP/V_FCMP assembly instructions (which this
3782 // intrinsic exposes) is one bit per thread, masked with the EXEC
3783 // register (which contains the bitmask of live threads). So a
3784 // comparison that always returns true is the same as a read of the
3785 // EXEC register.
James Y Knight7976eb52019-02-01 20:43:25 +00003786 Function *NewF = Intrinsic::getDeclaration(
Nicolai Haehnle9c661852017-04-24 17:08:43 +00003787 II->getModule(), Intrinsic::read_register, II->getType());
3788 Metadata *MDArgs[] = {MDString::get(II->getContext(), "exec")};
3789 MDNode *MD = MDNode::get(II->getContext(), MDArgs);
3790 Value *Args[] = {MetadataAsValue::get(II->getContext(), MD)};
Craig Topperbb4069e2017-07-07 23:16:26 +00003791 CallInst *NewCall = Builder.CreateCall(NewF, Args);
Nicolai Haehnle9c661852017-04-24 17:08:43 +00003792 NewCall->addAttribute(AttributeList::FunctionIndex,
3793 Attribute::Convergent);
3794 NewCall->takeName(II);
3795 return replaceInstUsesWith(*II, NewCall);
Matt Arsenaultd81f5572017-03-13 18:14:02 +00003796 }
3797
3798 // Canonicalize constants to RHS.
3799 CmpInst::Predicate SwapPred
3800 = CmpInst::getSwappedPredicate(static_cast<CmpInst::Predicate>(CCVal));
3801 II->setArgOperand(0, Src1);
3802 II->setArgOperand(1, Src0);
3803 II->setArgOperand(2, ConstantInt::get(CC->getType(),
3804 static_cast<int>(SwapPred)));
3805 return II;
3806 }
3807
3808 if (CCVal != CmpInst::ICMP_EQ && CCVal != CmpInst::ICMP_NE)
3809 break;
3810
3811 // Canonicalize compare eq with true value to compare != 0
3812 // llvm.amdgcn.icmp(zext (i1 x), 1, eq)
3813 // -> llvm.amdgcn.icmp(zext (i1 x), 0, ne)
3814 // llvm.amdgcn.icmp(sext (i1 x), -1, eq)
3815 // -> llvm.amdgcn.icmp(sext (i1 x), 0, ne)
3816 Value *ExtSrc;
3817 if (CCVal == CmpInst::ICMP_EQ &&
3818 ((match(Src1, m_One()) && match(Src0, m_ZExt(m_Value(ExtSrc)))) ||
3819 (match(Src1, m_AllOnes()) && match(Src0, m_SExt(m_Value(ExtSrc))))) &&
3820 ExtSrc->getType()->isIntegerTy(1)) {
3821 II->setArgOperand(1, ConstantInt::getNullValue(Src1->getType()));
3822 II->setArgOperand(2, ConstantInt::get(CC->getType(), CmpInst::ICMP_NE));
3823 return II;
3824 }
3825
3826 CmpInst::Predicate SrcPred;
3827 Value *SrcLHS;
3828 Value *SrcRHS;
3829
3830 // Fold compare eq/ne with 0 from a compare result as the predicate to the
3831 // intrinsic. The typical use is a wave vote function in the library, which
3832 // will be fed from a user code condition compared with 0. Fold in the
3833 // redundant compare.
3834
3835 // llvm.amdgcn.icmp([sz]ext ([if]cmp pred a, b), 0, ne)
3836 // -> llvm.amdgcn.[if]cmp(a, b, pred)
3837 //
3838 // llvm.amdgcn.icmp([sz]ext ([if]cmp pred a, b), 0, eq)
3839 // -> llvm.amdgcn.[if]cmp(a, b, inv pred)
3840 if (match(Src1, m_Zero()) &&
3841 match(Src0,
3842 m_ZExtOrSExt(m_Cmp(SrcPred, m_Value(SrcLHS), m_Value(SrcRHS))))) {
3843 if (CCVal == CmpInst::ICMP_EQ)
3844 SrcPred = CmpInst::getInversePredicate(SrcPred);
3845
3846 Intrinsic::ID NewIID = CmpInst::isFPPredicate(SrcPred) ?
3847 Intrinsic::amdgcn_fcmp : Intrinsic::amdgcn_icmp;
3848
Matt Arsenault9a389fb2018-08-15 21:14:25 +00003849 Type *Ty = SrcLHS->getType();
3850 if (auto *CmpType = dyn_cast<IntegerType>(Ty)) {
3851 // Promote to next legal integer type.
3852 unsigned Width = CmpType->getBitWidth();
3853 unsigned NewWidth = Width;
Marek Olsak33eb4d92019-01-15 02:13:18 +00003854
3855 // Don't do anything for i1 comparisons.
3856 if (Width == 1)
3857 break;
3858
Matt Arsenault9a389fb2018-08-15 21:14:25 +00003859 if (Width <= 16)
3860 NewWidth = 16;
3861 else if (Width <= 32)
3862 NewWidth = 32;
3863 else if (Width <= 64)
3864 NewWidth = 64;
3865 else if (Width > 64)
3866 break; // Can't handle this.
3867
3868 if (Width != NewWidth) {
3869 IntegerType *CmpTy = Builder.getIntNTy(NewWidth);
3870 if (CmpInst::isSigned(SrcPred)) {
3871 SrcLHS = Builder.CreateSExt(SrcLHS, CmpTy);
3872 SrcRHS = Builder.CreateSExt(SrcRHS, CmpTy);
3873 } else {
3874 SrcLHS = Builder.CreateZExt(SrcLHS, CmpTy);
3875 SrcRHS = Builder.CreateZExt(SrcRHS, CmpTy);
3876 }
3877 }
3878 } else if (!Ty->isFloatTy() && !Ty->isDoubleTy() && !Ty->isHalfTy())
3879 break;
3880
James Y Knight7976eb52019-02-01 20:43:25 +00003881 Function *NewF =
3882 Intrinsic::getDeclaration(II->getModule(), NewIID, SrcLHS->getType());
Matt Arsenaultd81f5572017-03-13 18:14:02 +00003883 Value *Args[] = { SrcLHS, SrcRHS,
3884 ConstantInt::get(CC->getType(), SrcPred) };
Craig Topperbb4069e2017-07-07 23:16:26 +00003885 CallInst *NewCall = Builder.CreateCall(NewF, Args);
Matt Arsenaultd81f5572017-03-13 18:14:02 +00003886 NewCall->takeName(II);
3887 return replaceInstUsesWith(*II, NewCall);
3888 }
3889
3890 break;
3891 }
Marek Olsak2114fc32017-10-24 10:26:59 +00003892 case Intrinsic::amdgcn_wqm_vote: {
3893 // wqm_vote is identity when the argument is constant.
3894 if (!isa<Constant>(II->getArgOperand(0)))
3895 break;
3896
3897 return replaceInstUsesWith(*II, II->getArgOperand(0));
3898 }
Marek Olsakce76ea02017-10-24 10:27:13 +00003899 case Intrinsic::amdgcn_kill: {
3900 const ConstantInt *C = dyn_cast<ConstantInt>(II->getArgOperand(0));
3901 if (!C || !C->getZExtValue())
3902 break;
3903
3904 // amdgcn.kill(i1 1) is a no-op
3905 return eraseInstFromFunction(CI);
3906 }
Stanislav Mekhanoshin0e132dc2018-05-22 08:04:33 +00003907 case Intrinsic::amdgcn_update_dpp: {
3908 Value *Old = II->getArgOperand(0);
3909
Matt Arsenaultcaf13162019-03-12 21:02:54 +00003910 auto BC = cast<ConstantInt>(II->getArgOperand(5));
3911 auto RM = cast<ConstantInt>(II->getArgOperand(3));
3912 auto BM = cast<ConstantInt>(II->getArgOperand(4));
3913 if (BC->isZeroValue() ||
Stanislav Mekhanoshin0e132dc2018-05-22 08:04:33 +00003914 RM->getZExtValue() != 0xF ||
3915 BM->getZExtValue() != 0xF ||
3916 isa<UndefValue>(Old))
3917 break;
3918
3919 // If bound_ctrl = 1, row mask = bank mask = 0xf we can omit old value.
3920 II->setOperand(0, UndefValue::get(Old->getType()));
3921 return II;
3922 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003923 case Intrinsic::stackrestore: {
3924 // If the save is right next to the restore, remove the restore. This can
3925 // happen when variable allocas are DCE'd.
Gabor Greif589a0b92010-06-24 12:58:35 +00003926 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getArgOperand(0))) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003927 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
Vedant Kumarf01827f2018-06-19 23:42:17 +00003928 // Skip over debug info.
3929 if (SS->getNextNonDebugInstruction() == II) {
Sanjay Patel4b198802016-02-01 22:23:39 +00003930 return eraseInstFromFunction(CI);
Davide Italiano189c2cf2018-06-08 20:42:36 +00003931 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003932 }
3933 }
Jim Grosbach7815f562012-02-03 00:07:04 +00003934
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003935 // Scan down this block to see if there is another stack restore in the
3936 // same block without an intervening call/alloca.
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00003937 BasicBlock::iterator BI(II);
Chandler Carruthedb12a82018-10-15 10:04:59 +00003938 Instruction *TI = II->getParent()->getTerminator();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003939 bool CannotRemove = false;
3940 for (++BI; &*BI != TI; ++BI) {
Nuno Lopes55fff832012-06-21 15:45:28 +00003941 if (isa<AllocaInst>(BI)) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003942 CannotRemove = true;
3943 break;
3944 }
3945 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
3946 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
3947 // If there is a stackrestore below this one, remove this one.
3948 if (II->getIntrinsicID() == Intrinsic::stackrestore)
Sanjay Patel4b198802016-02-01 22:23:39 +00003949 return eraseInstFromFunction(CI);
Reid Kleckner892ae2e2016-02-27 00:53:54 +00003950
3951 // Bail if we cross over an intrinsic with side effects, such as
3952 // llvm.stacksave, llvm.read_register, or llvm.setjmp.
3953 if (II->mayHaveSideEffects()) {
3954 CannotRemove = true;
3955 break;
3956 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003957 } else {
3958 // If we found a non-intrinsic call, we can't remove the stack
3959 // restore.
3960 CannotRemove = true;
3961 break;
3962 }
3963 }
3964 }
Jim Grosbach7815f562012-02-03 00:07:04 +00003965
Bill Wendlingf891bf82011-07-31 06:30:59 +00003966 // If the stack restore is in a return, resume, or unwind block and if there
3967 // are no allocas or calls between the restore and the return, nuke the
3968 // restore.
Bill Wendlingd5d95b02012-02-06 21:16:41 +00003969 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<ResumeInst>(TI)))
Sanjay Patel4b198802016-02-01 22:23:39 +00003970 return eraseInstFromFunction(CI);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003971 break;
3972 }
Vitaly Bukaf0500b62016-07-28 22:50:48 +00003973 case Intrinsic::lifetime_start:
Vitaly Buka0ab23cf2016-07-28 22:59:03 +00003974 // Asan needs to poison memory to detect invalid access which is possible
3975 // even for empty lifetime range.
Evgeniy Stepanovc667c1f2017-12-09 00:21:41 +00003976 if (II->getFunction()->hasFnAttribute(Attribute::SanitizeAddress) ||
3977 II->getFunction()->hasFnAttribute(Attribute::SanitizeHWAddress))
Vitaly Buka0ab23cf2016-07-28 22:59:03 +00003978 break;
3979
Arnaud A. de Grandmaison333ef382016-05-10 09:24:49 +00003980 if (removeTriviallyEmptyRange(*II, Intrinsic::lifetime_start,
3981 Intrinsic::lifetime_end, *this))
3982 return nullptr;
Arnaud A. de Grandmaison849f3bf2015-10-01 14:54:31 +00003983 break;
Hal Finkelf5867a72014-07-25 21:45:17 +00003984 case Intrinsic::assume: {
David Majnemerfcc58112016-04-08 16:37:12 +00003985 Value *IIOperand = II->getArgOperand(0);
Sanjay Patel825a4fa2018-06-20 13:22:26 +00003986 // Remove an assume if it is followed by an identical assume.
3987 // TODO: Do we need this? Unless there are conflicting assumptions, the
3988 // computeKnownBits(IIOperand) below here eliminates redundant assumes.
3989 Instruction *Next = II->getNextNonDebugInstruction();
3990 if (match(Next, m_Intrinsic<Intrinsic::assume>(m_Specific(IIOperand))))
David Majnemerfcc58112016-04-08 16:37:12 +00003991 return eraseInstFromFunction(CI);
3992
Hal Finkelf5867a72014-07-25 21:45:17 +00003993 // Canonicalize assume(a && b) -> assume(a); assume(b);
Hal Finkel74c2f352014-09-07 12:44:26 +00003994 // Note: New assumption intrinsics created here are registered by
3995 // the InstCombineIRInserter object.
James Y Knight7976eb52019-02-01 20:43:25 +00003996 FunctionType *AssumeIntrinsicTy = II->getFunctionType();
3997 Value *AssumeIntrinsic = II->getCalledValue();
3998 Value *A, *B;
Hal Finkelf5867a72014-07-25 21:45:17 +00003999 if (match(IIOperand, m_And(m_Value(A), m_Value(B)))) {
James Y Knight7976eb52019-02-01 20:43:25 +00004000 Builder.CreateCall(AssumeIntrinsicTy, AssumeIntrinsic, A, II->getName());
4001 Builder.CreateCall(AssumeIntrinsicTy, AssumeIntrinsic, B, II->getName());
Sanjay Patel4b198802016-02-01 22:23:39 +00004002 return eraseInstFromFunction(*II);
Hal Finkelf5867a72014-07-25 21:45:17 +00004003 }
4004 // assume(!(a || b)) -> assume(!a); assume(!b);
4005 if (match(IIOperand, m_Not(m_Or(m_Value(A), m_Value(B))))) {
James Y Knight7976eb52019-02-01 20:43:25 +00004006 Builder.CreateCall(AssumeIntrinsicTy, AssumeIntrinsic,
4007 Builder.CreateNot(A), II->getName());
4008 Builder.CreateCall(AssumeIntrinsicTy, AssumeIntrinsic,
4009 Builder.CreateNot(B), II->getName());
Sanjay Patel4b198802016-02-01 22:23:39 +00004010 return eraseInstFromFunction(*II);
Hal Finkelf5867a72014-07-25 21:45:17 +00004011 }
Hal Finkel04a15612014-10-04 21:27:06 +00004012
Philip Reames66c6de62014-11-11 23:33:19 +00004013 // assume( (load addr) != null ) -> add 'nonnull' metadata to load
4014 // (if assume is valid at the load)
Sanjay Patelf0d1e7732017-01-03 22:25:31 +00004015 CmpInst::Predicate Pred;
4016 Instruction *LHS;
4017 if (match(IIOperand, m_ICmp(Pred, m_Instruction(LHS), m_Zero())) &&
4018 Pred == ICmpInst::ICMP_NE && LHS->getOpcode() == Instruction::Load &&
4019 LHS->getType()->isPointerTy() &&
4020 isValidAssumeForContext(II, LHS, &DT)) {
4021 MDNode *MD = MDNode::get(II->getContext(), None);
4022 LHS->setMetadata(LLVMContext::MD_nonnull, MD);
4023 return eraseInstFromFunction(*II);
4024
Chandler Carruth24969102015-02-10 08:07:32 +00004025 // TODO: apply nonnull return attributes to calls and invokes
Philip Reames66c6de62014-11-11 23:33:19 +00004026 // TODO: apply range metadata for range check patterns?
4027 }
Sanjay Patelf0d1e7732017-01-03 22:25:31 +00004028
Hal Finkel04a15612014-10-04 21:27:06 +00004029 // If there is a dominating assume with the same condition as this one,
4030 // then this one is redundant, and should be removed.
Craig Topperb45eabc2017-04-26 16:39:58 +00004031 KnownBits Known(1);
4032 computeKnownBits(IIOperand, Known, 0, II);
Craig Topperf0aeee02017-05-05 17:36:09 +00004033 if (Known.isAllOnes())
Sanjay Patel4b198802016-02-01 22:23:39 +00004034 return eraseInstFromFunction(*II);
Hal Finkel04a15612014-10-04 21:27:06 +00004035
Hal Finkel8a9a7832017-01-11 13:24:24 +00004036 // Update the cache of affected values for this assumption (we might be
4037 // here because we just simplified the condition).
4038 AC.updateAffectedValues(II);
Hal Finkelf5867a72014-07-25 21:45:17 +00004039 break;
4040 }
Philip Reames9db26ff2014-12-29 23:27:30 +00004041 case Intrinsic::experimental_gc_relocate: {
4042 // Translate facts known about a pointer before relocating into
4043 // facts about the relocate value, while being careful to
4044 // preserve relocation semantics.
Manuel Jacob83eefa62016-01-05 04:03:00 +00004045 Value *DerivedPtr = cast<GCRelocateInst>(II)->getDerivedPtr();
Philip Reames9db26ff2014-12-29 23:27:30 +00004046
4047 // Remove the relocation if unused, note that this check is required
4048 // to prevent the cases below from looping forever.
4049 if (II->use_empty())
Sanjay Patel4b198802016-02-01 22:23:39 +00004050 return eraseInstFromFunction(*II);
Philip Reames9db26ff2014-12-29 23:27:30 +00004051
4052 // Undef is undef, even after relocation.
4053 // TODO: provide a hook for this in GCStrategy. This is clearly legal for
4054 // most practical collectors, but there was discussion in the review thread
4055 // about whether it was legal for all possible collectors.
Philip Reamesea4d8e82016-02-09 21:09:22 +00004056 if (isa<UndefValue>(DerivedPtr))
4057 // Use undef of gc_relocate's type to replace it.
4058 return replaceInstUsesWith(*II, UndefValue::get(II->getType()));
Philip Reames9db26ff2014-12-29 23:27:30 +00004059
Philip Reamesea4d8e82016-02-09 21:09:22 +00004060 if (auto *PT = dyn_cast<PointerType>(II->getType())) {
4061 // The relocation of null will be null for most any collector.
4062 // TODO: provide a hook for this in GCStrategy. There might be some
4063 // weird collector this property does not hold for.
4064 if (isa<ConstantPointerNull>(DerivedPtr))
4065 // Use null-pointer of gc_relocate's type to replace it.
4066 return replaceInstUsesWith(*II, ConstantPointerNull::get(PT));
Simon Pilgrimc0c56e72016-04-24 17:00:34 +00004067
Philip Reamesea4d8e82016-02-09 21:09:22 +00004068 // isKnownNonNull -> nonnull attribute
Philip Reamesb8d8db32018-11-12 20:00:53 +00004069 if (!II->hasRetAttr(Attribute::NonNull) &&
4070 isKnownNonZero(DerivedPtr, DL, 0, &AC, II, &DT)) {
Reid Klecknerb5180542017-03-21 16:57:19 +00004071 II->addAttribute(AttributeList::ReturnIndex, Attribute::NonNull);
Philip Reamesb8d8db32018-11-12 20:00:53 +00004072 return II;
4073 }
Ramkumar Ramachandra8fcb4982015-02-14 19:37:54 +00004074 }
Philip Reames9db26ff2014-12-29 23:27:30 +00004075
4076 // TODO: bitcast(relocate(p)) -> relocate(bitcast(p))
4077 // Canonicalize on the type from the uses to the defs
Ramkumar Ramachandra8fcb4982015-02-14 19:37:54 +00004078
Philip Reames9db26ff2014-12-29 23:27:30 +00004079 // TODO: relocate((gep p, C, C2, ...)) -> gep(relocate(p), C, C2, ...)
Philip Reamesea4d8e82016-02-09 21:09:22 +00004080 break;
Philip Reames9db26ff2014-12-29 23:27:30 +00004081 }
Artur Pilipenkoe812ca02017-01-25 14:12:12 +00004082
4083 case Intrinsic::experimental_guard: {
Philip Reames79e917d2018-05-09 22:56:32 +00004084 // Is this guard followed by another guard? We scan forward over a small
4085 // fixed window of instructions to handle common cases with conditions
4086 // computed between guards.
Sanjoy Dase0e57952017-02-01 16:34:55 +00004087 Instruction *NextInst = II->getNextNode();
Philip Reames913a7792018-05-10 00:05:29 +00004088 for (unsigned i = 0; i < GuardWideningWindow; i++) {
Philip Reames79e917d2018-05-09 22:56:32 +00004089 // Note: Using context-free form to avoid compile time blow up
4090 if (!isSafeToSpeculativelyExecute(NextInst))
4091 break;
4092 NextInst = NextInst->getNextNode();
4093 }
Sanjoy Dase0e57952017-02-01 16:34:55 +00004094 Value *NextCond = nullptr;
4095 if (match(NextInst,
4096 m_Intrinsic<Intrinsic::experimental_guard>(m_Value(NextCond)))) {
4097 Value *CurrCond = II->getArgOperand(0);
Artur Pilipenkoe812ca02017-01-25 14:12:12 +00004098
Simon Pilgrim68168d12017-03-30 12:59:53 +00004099 // Remove a guard that it is immediately preceded by an identical guard.
Sanjoy Dase0e57952017-02-01 16:34:55 +00004100 if (CurrCond == NextCond)
4101 return eraseInstFromFunction(*NextInst);
4102
4103 // Otherwise canonicalize guard(a); guard(b) -> guard(a & b).
Philip Reames79e917d2018-05-09 22:56:32 +00004104 Instruction* MoveI = II->getNextNode();
4105 while (MoveI != NextInst) {
4106 auto *Temp = MoveI;
4107 MoveI = MoveI->getNextNode();
4108 Temp->moveBefore(II);
4109 }
Craig Topperbb4069e2017-07-07 23:16:26 +00004110 II->setArgOperand(0, Builder.CreateAnd(CurrCond, NextCond));
Sanjoy Dase0e57952017-02-01 16:34:55 +00004111 return eraseInstFromFunction(*NextInst);
4112 }
Artur Pilipenkoe812ca02017-01-25 14:12:12 +00004113 break;
4114 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004115 }
Craig Topperc1892ec2019-01-31 17:23:29 +00004116 return visitCallBase(*II);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004117}
4118
Davide Italianoaec46172017-01-31 18:09:05 +00004119// Fence instruction simplification
4120Instruction *InstCombiner::visitFenceInst(FenceInst &FI) {
4121 // Remove identical consecutive fences.
Vedant Kumarf01827f2018-06-19 23:42:17 +00004122 Instruction *Next = FI.getNextNonDebugInstruction();
Tim Northover9b800602018-06-06 12:46:02 +00004123 if (auto *NFI = dyn_cast<FenceInst>(Next))
Davide Italianoaec46172017-01-31 18:09:05 +00004124 if (FI.isIdenticalTo(NFI))
4125 return eraseInstFromFunction(FI);
4126 return nullptr;
4127}
4128
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004129// InvokeInst simplification
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004130Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Craig Topperc1892ec2019-01-31 17:23:29 +00004131 return visitCallBase(II);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004132}
4133
Craig Topper784929d2019-02-08 20:48:56 +00004134// CallBrInst simplification
4135Instruction *InstCombiner::visitCallBrInst(CallBrInst &CBI) {
4136 return visitCallBase(CBI);
4137}
4138
Sanjay Patelcd4377c2016-01-20 22:24:38 +00004139/// If this cast does not affect the value passed through the varargs area, we
4140/// can eliminate the use of the cast.
Craig Topperc1892ec2019-01-31 17:23:29 +00004141static bool isSafeToEliminateVarargsCast(const CallBase &Call,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004142 const DataLayout &DL,
4143 const CastInst *const CI,
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004144 const int ix) {
4145 if (!CI->isLosslessCast())
4146 return false;
4147
Philip Reames1a1bdb22014-12-02 18:50:36 +00004148 // If this is a GC intrinsic, avoid munging types. We need types for
4149 // statepoint reconstruction in SelectionDAG.
4150 // TODO: This is probably something which should be expanded to all
4151 // intrinsics since the entire point of intrinsics is that
4152 // they are understandable by the optimizer.
Craig Topperc1892ec2019-01-31 17:23:29 +00004153 if (isStatepoint(&Call) || isGCRelocate(&Call) || isGCResult(&Call))
Philip Reames1a1bdb22014-12-02 18:50:36 +00004154 return false;
4155
Reid Kleckner26af2ca2014-01-28 02:38:36 +00004156 // The size of ByVal or InAlloca arguments is derived from the type, so we
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004157 // can't change to a type with a different size. If the size were
4158 // passed explicitly we could avoid this check.
Craig Topperc1892ec2019-01-31 17:23:29 +00004159 if (!Call.isByValOrInAllocaArgument(ix))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004160 return true;
4161
Jim Grosbach7815f562012-02-03 00:07:04 +00004162 Type* SrcTy =
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004163 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
Chris Lattner229907c2011-07-18 04:54:35 +00004164 Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004165 if (!SrcTy->isSized() || !DstTy->isSized())
4166 return false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004167 if (DL.getTypeAllocSize(SrcTy) != DL.getTypeAllocSize(DstTy))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004168 return false;
4169 return true;
4170}
4171
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004172Instruction *InstCombiner::tryOptimizeCall(CallInst *CI) {
Craig Topperf40110f2014-04-25 05:29:35 +00004173 if (!CI->getCalledFunction()) return nullptr;
Eric Christophera7fb58f2010-03-06 10:50:38 +00004174
Chandler Carruthba4c5172015-01-21 11:23:40 +00004175 auto InstCombineRAUW = [this](Instruction *From, Value *With) {
Sanjay Patel4b198802016-02-01 22:23:39 +00004176 replaceInstUsesWith(*From, With);
Chandler Carruthba4c5172015-01-21 11:23:40 +00004177 };
Amara Emerson54f60252018-10-11 14:51:11 +00004178 auto InstCombineErase = [this](Instruction *I) {
4179 eraseInstFromFunction(*I);
4180 };
4181 LibCallSimplifier Simplifier(DL, &TLI, ORE, InstCombineRAUW,
4182 InstCombineErase);
Chandler Carruthba4c5172015-01-21 11:23:40 +00004183 if (Value *With = Simplifier.optimizeCall(CI)) {
Meador Ingee3f2b262012-11-30 04:05:06 +00004184 ++NumSimplified;
Sanjay Patel4b198802016-02-01 22:23:39 +00004185 return CI->use_empty() ? CI : replaceInstUsesWith(*CI, With);
Meador Ingee3f2b262012-11-30 04:05:06 +00004186 }
Meador Ingedf796f82012-10-13 16:45:24 +00004187
Craig Topperf40110f2014-04-25 05:29:35 +00004188 return nullptr;
Eric Christophera7fb58f2010-03-06 10:50:38 +00004189}
4190
Sanjay Patel6038d3e2016-01-29 23:27:03 +00004191static IntrinsicInst *findInitTrampolineFromAlloca(Value *TrampMem) {
Duncan Sandsa0984362011-09-06 13:37:06 +00004192 // Strip off at most one level of pointer casts, looking for an alloca. This
4193 // is good enough in practice and simpler than handling any number of casts.
4194 Value *Underlying = TrampMem->stripPointerCasts();
4195 if (Underlying != TrampMem &&
Chandler Carruthcdf47882014-03-09 03:16:01 +00004196 (!Underlying->hasOneUse() || Underlying->user_back() != TrampMem))
Craig Topperf40110f2014-04-25 05:29:35 +00004197 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00004198 if (!isa<AllocaInst>(Underlying))
Craig Topperf40110f2014-04-25 05:29:35 +00004199 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00004200
Craig Topperf40110f2014-04-25 05:29:35 +00004201 IntrinsicInst *InitTrampoline = nullptr;
Chandler Carruthcdf47882014-03-09 03:16:01 +00004202 for (User *U : TrampMem->users()) {
4203 IntrinsicInst *II = dyn_cast<IntrinsicInst>(U);
Duncan Sandsa0984362011-09-06 13:37:06 +00004204 if (!II)
Craig Topperf40110f2014-04-25 05:29:35 +00004205 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00004206 if (II->getIntrinsicID() == Intrinsic::init_trampoline) {
4207 if (InitTrampoline)
4208 // More than one init_trampoline writes to this value. Give up.
Craig Topperf40110f2014-04-25 05:29:35 +00004209 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00004210 InitTrampoline = II;
4211 continue;
4212 }
4213 if (II->getIntrinsicID() == Intrinsic::adjust_trampoline)
4214 // Allow any number of calls to adjust.trampoline.
4215 continue;
Craig Topperf40110f2014-04-25 05:29:35 +00004216 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00004217 }
4218
4219 // No call to init.trampoline found.
4220 if (!InitTrampoline)
Craig Topperf40110f2014-04-25 05:29:35 +00004221 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00004222
4223 // Check that the alloca is being used in the expected way.
4224 if (InitTrampoline->getOperand(0) != TrampMem)
Craig Topperf40110f2014-04-25 05:29:35 +00004225 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00004226
4227 return InitTrampoline;
4228}
4229
Sanjay Patel6038d3e2016-01-29 23:27:03 +00004230static IntrinsicInst *findInitTrampolineFromBB(IntrinsicInst *AdjustTramp,
Duncan Sandsa0984362011-09-06 13:37:06 +00004231 Value *TrampMem) {
4232 // Visit all the previous instructions in the basic block, and try to find a
4233 // init.trampoline which has a direct path to the adjust.trampoline.
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00004234 for (BasicBlock::iterator I = AdjustTramp->getIterator(),
4235 E = AdjustTramp->getParent()->begin();
4236 I != E;) {
4237 Instruction *Inst = &*--I;
Duncan Sandsa0984362011-09-06 13:37:06 +00004238 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
4239 if (II->getIntrinsicID() == Intrinsic::init_trampoline &&
4240 II->getOperand(0) == TrampMem)
4241 return II;
4242 if (Inst->mayWriteToMemory())
Craig Topperf40110f2014-04-25 05:29:35 +00004243 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00004244 }
Craig Topperf40110f2014-04-25 05:29:35 +00004245 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00004246}
4247
4248// Given a call to llvm.adjust.trampoline, find and return the corresponding
4249// call to llvm.init.trampoline if the call to the trampoline can be optimized
4250// to a direct call to a function. Otherwise return NULL.
Sanjay Patel6038d3e2016-01-29 23:27:03 +00004251static IntrinsicInst *findInitTrampoline(Value *Callee) {
Duncan Sandsa0984362011-09-06 13:37:06 +00004252 Callee = Callee->stripPointerCasts();
4253 IntrinsicInst *AdjustTramp = dyn_cast<IntrinsicInst>(Callee);
4254 if (!AdjustTramp ||
4255 AdjustTramp->getIntrinsicID() != Intrinsic::adjust_trampoline)
Craig Topperf40110f2014-04-25 05:29:35 +00004256 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00004257
4258 Value *TrampMem = AdjustTramp->getOperand(0);
4259
Sanjay Patel6038d3e2016-01-29 23:27:03 +00004260 if (IntrinsicInst *IT = findInitTrampolineFromAlloca(TrampMem))
Duncan Sandsa0984362011-09-06 13:37:06 +00004261 return IT;
Sanjay Patel6038d3e2016-01-29 23:27:03 +00004262 if (IntrinsicInst *IT = findInitTrampolineFromBB(AdjustTramp, TrampMem))
Duncan Sandsa0984362011-09-06 13:37:06 +00004263 return IT;
Craig Topperf40110f2014-04-25 05:29:35 +00004264 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00004265}
4266
Craig Topper784929d2019-02-08 20:48:56 +00004267/// Improvements for call, callbr and invoke instructions.
Craig Topperc1892ec2019-01-31 17:23:29 +00004268Instruction *InstCombiner::visitCallBase(CallBase &Call) {
4269 if (isAllocLikeFn(&Call, &TLI))
4270 return visitAllocSite(Call);
Nuno Lopesdc6085e2012-06-21 21:25:05 +00004271
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004272 bool Changed = false;
4273
Philip Reamesc25df112015-06-16 20:24:25 +00004274 // Mark any parameters that are known to be non-null with the nonnull
4275 // attribute. This is helpful for inlining calls to functions with null
4276 // checks on their arguments.
Reid Kleckner5fbdd172017-05-31 19:23:09 +00004277 SmallVector<unsigned, 4> ArgNos;
Philip Reamesc25df112015-06-16 20:24:25 +00004278 unsigned ArgNo = 0;
Akira Hatanaka237916b2015-12-02 06:58:49 +00004279
Craig Topperc1892ec2019-01-31 17:23:29 +00004280 for (Value *V : Call.args()) {
Sanjay Patelf9f5d3c2016-01-29 23:14:58 +00004281 if (V->getType()->isPointerTy() &&
Craig Topperc1892ec2019-01-31 17:23:29 +00004282 !Call.paramHasAttr(ArgNo, Attribute::NonNull) &&
4283 isKnownNonZero(V, DL, 0, &AC, &Call, &DT))
Reid Kleckner5fbdd172017-05-31 19:23:09 +00004284 ArgNos.push_back(ArgNo);
Philip Reamesc25df112015-06-16 20:24:25 +00004285 ArgNo++;
4286 }
Akira Hatanaka237916b2015-12-02 06:58:49 +00004287
Craig Topperc1892ec2019-01-31 17:23:29 +00004288 assert(ArgNo == Call.arg_size() && "sanity check");
Philip Reamesc25df112015-06-16 20:24:25 +00004289
Reid Kleckner5fbdd172017-05-31 19:23:09 +00004290 if (!ArgNos.empty()) {
Craig Topperc1892ec2019-01-31 17:23:29 +00004291 AttributeList AS = Call.getAttributes();
4292 LLVMContext &Ctx = Call.getContext();
Reid Kleckner5fbdd172017-05-31 19:23:09 +00004293 AS = AS.addParamAttribute(Ctx, ArgNos,
4294 Attribute::get(Ctx, Attribute::NonNull));
Craig Topperc1892ec2019-01-31 17:23:29 +00004295 Call.setAttributes(AS);
Akira Hatanaka237916b2015-12-02 06:58:49 +00004296 Changed = true;
4297 }
4298
Chris Lattner73989652010-12-20 08:25:06 +00004299 // If the callee is a pointer to a function, attempt to move any casts to the
Craig Topper784929d2019-02-08 20:48:56 +00004300 // arguments of the call/callbr/invoke.
Craig Topperc1892ec2019-01-31 17:23:29 +00004301 Value *Callee = Call.getCalledValue();
4302 if (!isa<Function>(Callee) && transformConstExprCastCall(Call))
Craig Topperf40110f2014-04-25 05:29:35 +00004303 return nullptr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004304
Justin Lebar9d943972016-03-14 20:18:54 +00004305 if (Function *CalleeF = dyn_cast<Function>(Callee)) {
4306 // Remove the convergent attr on calls when the callee is not convergent.
Craig Topperc1892ec2019-01-31 17:23:29 +00004307 if (Call.isConvergent() && !CalleeF->isConvergent() &&
Matt Arsenault802ebcb2016-06-20 19:04:44 +00004308 !CalleeF->isIntrinsic()) {
Craig Topperc1892ec2019-01-31 17:23:29 +00004309 LLVM_DEBUG(dbgs() << "Removing convergent attr from instr " << Call
4310 << "\n");
4311 Call.setNotConvergent();
4312 return &Call;
Justin Lebar9d943972016-03-14 20:18:54 +00004313 }
4314
Chris Lattner846a52e2010-02-01 18:11:34 +00004315 // If the call and callee calling conventions don't match, this call must
4316 // be unreachable, as the call is undefined.
Craig Topperc1892ec2019-01-31 17:23:29 +00004317 if (CalleeF->getCallingConv() != Call.getCallingConv() &&
Chris Lattner846a52e2010-02-01 18:11:34 +00004318 // Only do this for calls to a function with a body. A prototype may
4319 // not actually end up matching the implementation's calling conv for a
4320 // variety of reasons (e.g. it may be written in assembly).
4321 !CalleeF->isDeclaration()) {
Craig Topperc1892ec2019-01-31 17:23:29 +00004322 Instruction *OldCall = &Call;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004323 new StoreInst(ConstantInt::getTrue(Callee->getContext()),
Jim Grosbach7815f562012-02-03 00:07:04 +00004324 UndefValue::get(Type::getInt1PtrTy(Callee->getContext())),
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004325 OldCall);
Chad Rosiere28ae302012-12-13 00:18:46 +00004326 // If OldCall does not return void then replaceAllUsesWith undef.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004327 // This allows ValueHandlers and custom metadata to adjust itself.
4328 if (!OldCall->getType()->isVoidTy())
Sanjay Patel4b198802016-02-01 22:23:39 +00004329 replaceInstUsesWith(*OldCall, UndefValue::get(OldCall->getType()));
Chris Lattner2cecedf2010-02-01 18:04:58 +00004330 if (isa<CallInst>(OldCall))
Sanjay Patel4b198802016-02-01 22:23:39 +00004331 return eraseInstFromFunction(*OldCall);
Jim Grosbach7815f562012-02-03 00:07:04 +00004332
Craig Topper784929d2019-02-08 20:48:56 +00004333 // We cannot remove an invoke or a callbr, because it would change thexi
4334 // CFG, just change the callee to a null pointer.
4335 cast<CallBase>(OldCall)->setCalledFunction(
James Y Knight291f7912019-02-01 20:44:54 +00004336 CalleeF->getFunctionType(),
4337 Constant::getNullValue(CalleeF->getType()));
Craig Topperf40110f2014-04-25 05:29:35 +00004338 return nullptr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004339 }
Justin Lebar9d943972016-03-14 20:18:54 +00004340 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004341
Manoj Gupta77eeac32018-07-09 22:27:23 +00004342 if ((isa<ConstantPointerNull>(Callee) &&
Craig Topperc1892ec2019-01-31 17:23:29 +00004343 !NullPointerIsDefined(Call.getFunction())) ||
Manoj Gupta77eeac32018-07-09 22:27:23 +00004344 isa<UndefValue>(Callee)) {
Craig Topperc1892ec2019-01-31 17:23:29 +00004345 // If Call does not return void then replaceAllUsesWith undef.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004346 // This allows ValueHandlers and custom metadata to adjust itself.
Craig Topperc1892ec2019-01-31 17:23:29 +00004347 if (!Call.getType()->isVoidTy())
4348 replaceInstUsesWith(Call, UndefValue::get(Call.getType()));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004349
Craig Topper784929d2019-02-08 20:48:56 +00004350 if (Call.isTerminator()) {
4351 // Can't remove an invoke or callbr because we cannot change the CFG.
Craig Topperf40110f2014-04-25 05:29:35 +00004352 return nullptr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004353 }
Nuno Lopes771e7bd2012-06-21 23:52:14 +00004354
4355 // This instruction is not reachable, just remove it. We insert a store to
4356 // undef so that we know that this code is not reachable, despite the fact
4357 // that we can't modify the CFG here.
4358 new StoreInst(ConstantInt::getTrue(Callee->getContext()),
4359 UndefValue::get(Type::getInt1PtrTy(Callee->getContext())),
Craig Topperc1892ec2019-01-31 17:23:29 +00004360 &Call);
Nuno Lopes771e7bd2012-06-21 23:52:14 +00004361
Craig Topperc1892ec2019-01-31 17:23:29 +00004362 return eraseInstFromFunction(Call);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004363 }
4364
Sanjay Patel6038d3e2016-01-29 23:27:03 +00004365 if (IntrinsicInst *II = findInitTrampoline(Callee))
Craig Topperc1892ec2019-01-31 17:23:29 +00004366 return transformCallThroughTrampoline(Call, *II);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004367
Chris Lattner229907c2011-07-18 04:54:35 +00004368 PointerType *PTy = cast<PointerType>(Callee->getType());
4369 FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004370 if (FTy->isVarArg()) {
Eli Friedman7534b4682011-11-29 01:18:23 +00004371 int ix = FTy->getNumParams();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004372 // See if we can optimize any arguments passed through the varargs area of
4373 // the call.
Craig Topperc1892ec2019-01-31 17:23:29 +00004374 for (auto I = Call.arg_begin() + FTy->getNumParams(), E = Call.arg_end();
4375 I != E; ++I, ++ix) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004376 CastInst *CI = dyn_cast<CastInst>(*I);
Craig Topperc1892ec2019-01-31 17:23:29 +00004377 if (CI && isSafeToEliminateVarargsCast(Call, DL, CI, ix)) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004378 *I = CI->getOperand(0);
4379 Changed = true;
4380 }
4381 }
4382 }
4383
Craig Topperc1892ec2019-01-31 17:23:29 +00004384 if (isa<InlineAsm>(Callee) && !Call.doesNotThrow()) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004385 // Inline asm calls cannot throw - mark them 'nounwind'.
Craig Topperc1892ec2019-01-31 17:23:29 +00004386 Call.setDoesNotThrow();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004387 Changed = true;
4388 }
4389
Micah Villmowcdfe20b2012-10-08 16:38:25 +00004390 // Try to optimize the call if possible, we require DataLayout for most of
Eric Christophera7fb58f2010-03-06 10:50:38 +00004391 // this. None of these calls are seen as possibly dead so go ahead and
4392 // delete the instruction now.
Craig Topperc1892ec2019-01-31 17:23:29 +00004393 if (CallInst *CI = dyn_cast<CallInst>(&Call)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004394 Instruction *I = tryOptimizeCall(CI);
Eric Christopher1810d772010-03-06 10:59:25 +00004395 // If we changed something return the result, etc. Otherwise let
4396 // the fallthrough check.
Sanjay Patel4b198802016-02-01 22:23:39 +00004397 if (I) return eraseInstFromFunction(*I);
Eric Christophera7fb58f2010-03-06 10:50:38 +00004398 }
4399
Craig Topperc1892ec2019-01-31 17:23:29 +00004400 return Changed ? &Call : nullptr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004401}
4402
Sanjay Patelcd4377c2016-01-20 22:24:38 +00004403/// If the callee is a constexpr cast of a function, attempt to move the cast to
Craig Topper784929d2019-02-08 20:48:56 +00004404/// the arguments of the call/callbr/invoke.
Craig Topperc1892ec2019-01-31 17:23:29 +00004405bool InstCombiner::transformConstExprCastCall(CallBase &Call) {
4406 auto *Callee = dyn_cast<Function>(Call.getCalledValue()->stripPointerCasts());
Craig Topperf40110f2014-04-25 05:29:35 +00004407 if (!Callee)
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004408 return false;
Sanjay Patel38ae83d2016-08-11 15:23:56 +00004409
Reid Kleckner298ffc62018-04-02 22:49:44 +00004410 // If this is a call to a thunk function, don't remove the cast. Thunks are
4411 // used to transparently forward all incoming parameters and outgoing return
4412 // values, so it's important to leave the cast in place.
David Majnemer4c0a6e92015-01-21 22:32:04 +00004413 if (Callee->hasFnAttribute("thunk"))
4414 return false;
Sanjay Patel38ae83d2016-08-11 15:23:56 +00004415
Reid Kleckner298ffc62018-04-02 22:49:44 +00004416 // If this is a musttail call, the callee's prototype must match the caller's
4417 // prototype with the exception of pointee types. The code below doesn't
4418 // implement that, so we can't do this transform.
4419 // TODO: Do the transform if it only requires adding pointer casts.
Craig Topperc1892ec2019-01-31 17:23:29 +00004420 if (Call.isMustTailCall())
Reid Kleckner298ffc62018-04-02 22:49:44 +00004421 return false;
4422
Craig Topperc1892ec2019-01-31 17:23:29 +00004423 Instruction *Caller = &Call;
4424 const AttributeList &CallerPAL = Call.getAttributes();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004425
4426 // Okay, this is a cast from a function to a different type. Unless doing so
4427 // would cause a type conversion of one of our arguments, change this call to
4428 // be a direct call with arguments casted to the appropriate types.
Chris Lattner229907c2011-07-18 04:54:35 +00004429 FunctionType *FT = Callee->getFunctionType();
4430 Type *OldRetTy = Caller->getType();
4431 Type *NewRetTy = FT->getReturnType();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004432
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004433 // Check to see if we are changing the return type...
4434 if (OldRetTy != NewRetTy) {
Nick Lewyckya6a17d72014-01-18 22:47:12 +00004435
4436 if (NewRetTy->isStructTy())
4437 return false; // TODO: Handle multiple return values.
4438
David Majnemer9b6b8222015-01-06 08:41:31 +00004439 if (!CastInst::isBitOrNoopPointerCastable(NewRetTy, OldRetTy, DL)) {
Matt Arsenaulte6952f22013-09-17 21:10:14 +00004440 if (Callee->isDeclaration())
4441 return false; // Cannot transform this return value.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004442
Matt Arsenaulte6952f22013-09-17 21:10:14 +00004443 if (!Caller->use_empty() &&
4444 // void -> non-void is handled specially
4445 !NewRetTy->isVoidTy())
Frederic Rissc1892e22014-10-23 04:08:42 +00004446 return false; // Cannot transform this return value.
Matt Arsenaulte6952f22013-09-17 21:10:14 +00004447 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004448
4449 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Reid Klecknerb5180542017-03-21 16:57:19 +00004450 AttrBuilder RAttrs(CallerPAL, AttributeList::ReturnIndex);
Pete Cooper2777d8872015-05-06 23:19:56 +00004451 if (RAttrs.overlaps(AttributeFuncs::typeIncompatible(NewRetTy)))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004452 return false; // Attribute not compatible with transformed value.
4453 }
4454
Craig Topper784929d2019-02-08 20:48:56 +00004455 // If the callbase is an invoke/callbr instruction, and the return value is
4456 // used by a PHI node in a successor, we cannot change the return type of
4457 // the call because there is no place to put the cast instruction (without
4458 // breaking the critical edge). Bail out in this case.
4459 if (!Caller->use_empty()) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004460 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
Chandler Carruthcdf47882014-03-09 03:16:01 +00004461 for (User *U : II->users())
4462 if (PHINode *PN = dyn_cast<PHINode>(U))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004463 if (PN->getParent() == II->getNormalDest() ||
4464 PN->getParent() == II->getUnwindDest())
4465 return false;
Craig Topper784929d2019-02-08 20:48:56 +00004466 // FIXME: Be conservative for callbr to avoid a quadratic search.
Craig Toppera97857b2019-02-10 02:21:29 +00004467 if (isa<CallBrInst>(Caller))
Craig Topper784929d2019-02-08 20:48:56 +00004468 return false;
4469 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004470 }
4471
Craig Topperc1892ec2019-01-31 17:23:29 +00004472 unsigned NumActualArgs = Call.arg_size();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004473 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
4474
David Majnemer9b6b8222015-01-06 08:41:31 +00004475 // Prevent us turning:
4476 // declare void @takes_i32_inalloca(i32* inalloca)
4477 // call void bitcast (void (i32*)* @takes_i32_inalloca to void (i32)*)(i32 0)
4478 //
4479 // into:
4480 // call void @takes_i32_inalloca(i32* null)
David Majnemerd61a6fd2015-03-11 18:03:05 +00004481 //
4482 // Similarly, avoid folding away bitcasts of byval calls.
4483 if (Callee->getAttributes().hasAttrSomewhere(Attribute::InAlloca) ||
4484 Callee->getAttributes().hasAttrSomewhere(Attribute::ByVal))
David Majnemer9b6b8222015-01-06 08:41:31 +00004485 return false;
4486
Craig Topperc1892ec2019-01-31 17:23:29 +00004487 auto AI = Call.arg_begin();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004488 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
Chris Lattner229907c2011-07-18 04:54:35 +00004489 Type *ParamTy = FT->getParamType(i);
4490 Type *ActTy = (*AI)->getType();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004491
David Majnemer9b6b8222015-01-06 08:41:31 +00004492 if (!CastInst::isBitOrNoopPointerCastable(ActTy, ParamTy, DL))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004493 return false; // Cannot transform this parameter value.
4494
Reid Klecknerf021fab2017-04-13 23:12:13 +00004495 if (AttrBuilder(CallerPAL.getParamAttributes(i))
4496 .overlaps(AttributeFuncs::typeIncompatible(ParamTy)))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004497 return false; // Attribute not compatible with transformed value.
Jim Grosbach7815f562012-02-03 00:07:04 +00004498
Craig Topperc1892ec2019-01-31 17:23:29 +00004499 if (Call.isInAllocaArgument(i))
Reid Kleckner26af2ca2014-01-28 02:38:36 +00004500 return false; // Cannot transform to and from inalloca.
4501
Chris Lattner27ca8eb2010-12-20 08:36:38 +00004502 // If the parameter is passed as a byval argument, then we have to have a
4503 // sized type and the sized type has to have the same size as the old type.
Reid Klecknerf021fab2017-04-13 23:12:13 +00004504 if (ParamTy != ActTy && CallerPAL.hasParamAttribute(i, Attribute::ByVal)) {
Chris Lattner229907c2011-07-18 04:54:35 +00004505 PointerType *ParamPTy = dyn_cast<PointerType>(ParamTy);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004506 if (!ParamPTy || !ParamPTy->getElementType()->isSized())
Chris Lattner27ca8eb2010-12-20 08:36:38 +00004507 return false;
Jim Grosbach7815f562012-02-03 00:07:04 +00004508
Matt Arsenaultfa252722013-09-27 22:18:51 +00004509 Type *CurElTy = ActTy->getPointerElementType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004510 if (DL.getTypeAllocSize(CurElTy) !=
4511 DL.getTypeAllocSize(ParamPTy->getElementType()))
Chris Lattner27ca8eb2010-12-20 08:36:38 +00004512 return false;
4513 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004514 }
4515
Chris Lattneradf38b32011-02-24 05:10:56 +00004516 if (Callee->isDeclaration()) {
4517 // Do not delete arguments unless we have a function body.
4518 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg())
4519 return false;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004520
Chris Lattneradf38b32011-02-24 05:10:56 +00004521 // If the callee is just a declaration, don't change the varargsness of the
4522 // call. We don't want to introduce a varargs call where one doesn't
4523 // already exist.
Craig Topperc1892ec2019-01-31 17:23:29 +00004524 PointerType *APTy = cast<PointerType>(Call.getCalledValue()->getType());
Chris Lattneradf38b32011-02-24 05:10:56 +00004525 if (FT->isVarArg()!=cast<FunctionType>(APTy->getElementType())->isVarArg())
4526 return false;
Jim Grosbache84ae7b2012-02-03 00:00:55 +00004527
4528 // If both the callee and the cast type are varargs, we still have to make
4529 // sure the number of fixed parameters are the same or we have the same
4530 // ABI issues as if we introduce a varargs call.
Jim Grosbach1df8cdc2012-02-03 00:26:07 +00004531 if (FT->isVarArg() &&
4532 cast<FunctionType>(APTy->getElementType())->isVarArg() &&
4533 FT->getNumParams() !=
Jim Grosbache84ae7b2012-02-03 00:00:55 +00004534 cast<FunctionType>(APTy->getElementType())->getNumParams())
4535 return false;
Chris Lattneradf38b32011-02-24 05:10:56 +00004536 }
Jim Grosbach7815f562012-02-03 00:07:04 +00004537
Jim Grosbach0ab54182012-02-03 00:00:50 +00004538 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
Reid Kleckneraa0cec72017-04-19 23:17:47 +00004539 !CallerPAL.isEmpty()) {
Jim Grosbach0ab54182012-02-03 00:00:50 +00004540 // In this case we have more arguments than the new function type, but we
4541 // won't be dropping them. Check that these extra arguments have attributes
4542 // that are compatible with being a vararg call argument.
Reid Kleckneraa0cec72017-04-19 23:17:47 +00004543 unsigned SRetIdx;
4544 if (CallerPAL.hasAttrSomewhere(Attribute::StructRet, &SRetIdx) &&
4545 SRetIdx > FT->getNumParams())
4546 return false;
4547 }
Jim Grosbach7815f562012-02-03 00:07:04 +00004548
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004549 // Okay, we decided that this is a safe thing to do: go ahead and start
Chris Lattneradf38b32011-02-24 05:10:56 +00004550 // inserting cast instructions as necessary.
Reid Klecknerc3fae792017-04-13 18:11:03 +00004551 SmallVector<Value *, 8> Args;
4552 SmallVector<AttributeSet, 8> ArgAttrs;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004553 Args.reserve(NumActualArgs);
Reid Klecknerc3fae792017-04-13 18:11:03 +00004554 ArgAttrs.reserve(NumActualArgs);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004555
4556 // Get any return attributes.
Reid Klecknerb5180542017-03-21 16:57:19 +00004557 AttrBuilder RAttrs(CallerPAL, AttributeList::ReturnIndex);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004558
4559 // If the return value is not being used, the type may not be compatible
4560 // with the existing attributes. Wipe out any problematic attributes.
Pete Cooper2777d8872015-05-06 23:19:56 +00004561 RAttrs.remove(AttributeFuncs::typeIncompatible(NewRetTy));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004562
Craig Topperc1892ec2019-01-31 17:23:29 +00004563 AI = Call.arg_begin();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004564 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
Chris Lattner229907c2011-07-18 04:54:35 +00004565 Type *ParamTy = FT->getParamType(i);
Matt Arsenaultcacbb232013-07-30 20:45:05 +00004566
Reid Klecknerc3fae792017-04-13 18:11:03 +00004567 Value *NewArg = *AI;
4568 if ((*AI)->getType() != ParamTy)
Craig Topperbb4069e2017-07-07 23:16:26 +00004569 NewArg = Builder.CreateBitOrPointerCast(*AI, ParamTy);
Reid Klecknerc3fae792017-04-13 18:11:03 +00004570 Args.push_back(NewArg);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004571
4572 // Add any parameter attributes.
Reid Klecknerf021fab2017-04-13 23:12:13 +00004573 ArgAttrs.push_back(CallerPAL.getParamAttributes(i));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004574 }
4575
4576 // If the function takes more arguments than the call was taking, add them
4577 // now.
Reid Klecknerc3fae792017-04-13 18:11:03 +00004578 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004579 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
Reid Klecknerc3fae792017-04-13 18:11:03 +00004580 ArgAttrs.push_back(AttributeSet());
4581 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004582
4583 // If we are removing arguments to the function, emit an obnoxious warning.
4584 if (FT->getNumParams() < NumActualArgs) {
Nick Lewycky90053a12012-12-26 22:00:35 +00004585 // TODO: if (!FT->isVarArg()) this call may be unreachable. PR14722
4586 if (FT->isVarArg()) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004587 // Add all of the arguments in their promoted form to the arg list.
4588 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
Chris Lattner229907c2011-07-18 04:54:35 +00004589 Type *PTy = getPromotedType((*AI)->getType());
Reid Klecknerc3fae792017-04-13 18:11:03 +00004590 Value *NewArg = *AI;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004591 if (PTy != (*AI)->getType()) {
4592 // Must promote to pass through va_arg area!
4593 Instruction::CastOps opcode =
4594 CastInst::getCastOpcode(*AI, false, PTy, false);
Craig Topperbb4069e2017-07-07 23:16:26 +00004595 NewArg = Builder.CreateCast(opcode, *AI, PTy);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004596 }
Reid Klecknerc3fae792017-04-13 18:11:03 +00004597 Args.push_back(NewArg);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004598
4599 // Add any parameter attributes.
Reid Klecknerf021fab2017-04-13 23:12:13 +00004600 ArgAttrs.push_back(CallerPAL.getParamAttributes(i));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004601 }
4602 }
4603 }
4604
Reid Klecknerc2cb5602017-04-12 00:38:00 +00004605 AttributeSet FnAttrs = CallerPAL.getFnAttributes();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004606
4607 if (NewRetTy->isVoidTy())
4608 Caller->setName(""); // Void type should not have a name.
4609
Reid Klecknerc3fae792017-04-13 18:11:03 +00004610 assert((ArgAttrs.size() == FT->getNumParams() || FT->isVarArg()) &&
4611 "missing argument attributes");
4612 LLVMContext &Ctx = Callee->getContext();
4613 AttributeList NewCallerPAL = AttributeList::get(
4614 Ctx, FnAttrs, AttributeSet::get(Ctx, RAttrs), ArgAttrs);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004615
Sanjoy Das76293462015-11-25 00:42:19 +00004616 SmallVector<OperandBundleDef, 1> OpBundles;
Craig Topperc1892ec2019-01-31 17:23:29 +00004617 Call.getOperandBundlesAsDefs(OpBundles);
Sanjoy Das76293462015-11-25 00:42:19 +00004618
Craig Topperc1892ec2019-01-31 17:23:29 +00004619 CallBase *NewCall;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004620 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Craig Topperc1892ec2019-01-31 17:23:29 +00004621 NewCall = Builder.CreateInvoke(Callee, II->getNormalDest(),
4622 II->getUnwindDest(), Args, OpBundles);
Craig Topper784929d2019-02-08 20:48:56 +00004623 } else if (CallBrInst *CBI = dyn_cast<CallBrInst>(Caller)) {
4624 NewCall = Builder.CreateCallBr(Callee, CBI->getDefaultDest(),
4625 CBI->getIndirectDests(), Args, OpBundles);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004626 } else {
Craig Topperc1892ec2019-01-31 17:23:29 +00004627 NewCall = Builder.CreateCall(Callee, Args, OpBundles);
4628 cast<CallInst>(NewCall)->setTailCallKind(
4629 cast<CallInst>(Caller)->getTailCallKind());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004630 }
Craig Topperc1892ec2019-01-31 17:23:29 +00004631 NewCall->takeName(Caller);
4632 NewCall->setCallingConv(Call.getCallingConv());
4633 NewCall->setAttributes(NewCallerPAL);
Reid Kleckner257cb4e2017-04-13 20:26:38 +00004634
4635 // Preserve the weight metadata for the new call instruction. The metadata
4636 // is used by SamplePGO to check callsite's hotness.
4637 uint64_t W;
4638 if (Caller->extractProfTotalWeight(W))
Craig Topperc1892ec2019-01-31 17:23:29 +00004639 NewCall->setProfWeight(W);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004640
4641 // Insert a cast of the return type as necessary.
Craig Topperc1892ec2019-01-31 17:23:29 +00004642 Instruction *NC = NewCall;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004643 Value *NV = NC;
4644 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
4645 if (!NV->getType()->isVoidTy()) {
David Majnemer9b6b8222015-01-06 08:41:31 +00004646 NV = NC = CastInst::CreateBitOrPointerCast(NC, OldRetTy);
Eli Friedman35211c62011-05-27 00:19:40 +00004647 NC->setDebugLoc(Caller->getDebugLoc());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004648
Craig Topper784929d2019-02-08 20:48:56 +00004649 // If this is an invoke/callbr instruction, we should insert it after the
4650 // first non-phi instruction in the normal successor block.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004651 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Bill Wendling07efd6f2011-08-25 01:08:34 +00004652 BasicBlock::iterator I = II->getNormalDest()->getFirstInsertionPt();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004653 InsertNewInstBefore(NC, *I);
Craig Topper784929d2019-02-08 20:48:56 +00004654 } else if (CallBrInst *CBI = dyn_cast<CallBrInst>(Caller)) {
4655 BasicBlock::iterator I = CBI->getDefaultDest()->getFirstInsertionPt();
4656 InsertNewInstBefore(NC, *I);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004657 } else {
Chris Lattner73989652010-12-20 08:25:06 +00004658 // Otherwise, it's a call, just insert cast right after the call.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004659 InsertNewInstBefore(NC, *Caller);
4660 }
4661 Worklist.AddUsersToWorkList(*Caller);
4662 } else {
4663 NV = UndefValue::get(Caller->getType());
4664 }
4665 }
4666
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004667 if (!Caller->use_empty())
Sanjay Patel4b198802016-02-01 22:23:39 +00004668 replaceInstUsesWith(*Caller, NV);
Frederic Rissc1892e22014-10-23 04:08:42 +00004669 else if (Caller->hasValueHandle()) {
4670 if (OldRetTy == NV->getType())
4671 ValueHandleBase::ValueIsRAUWd(Caller, NV);
4672 else
4673 // We cannot call ValueIsRAUWd with a different type, and the
4674 // actual tracked value will disappear.
4675 ValueHandleBase::ValueIsDeleted(Caller);
4676 }
Eli Friedmanb9ed18f2011-05-18 00:32:01 +00004677
Sanjay Patel4b198802016-02-01 22:23:39 +00004678 eraseInstFromFunction(*Caller);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004679 return true;
4680}
4681
Sanjay Patelcd4377c2016-01-20 22:24:38 +00004682/// Turn a call to a function created by init_trampoline / adjust_trampoline
4683/// intrinsic pair into a direct call to the underlying function.
Duncan Sandsa0984362011-09-06 13:37:06 +00004684Instruction *
Craig Topperc1892ec2019-01-31 17:23:29 +00004685InstCombiner::transformCallThroughTrampoline(CallBase &Call,
4686 IntrinsicInst &Tramp) {
4687 Value *Callee = Call.getCalledValue();
James Y Knight291f7912019-02-01 20:44:54 +00004688 Type *CalleeTy = Callee->getType();
4689 FunctionType *FTy = Call.getFunctionType();
Craig Topperc1892ec2019-01-31 17:23:29 +00004690 AttributeList Attrs = Call.getAttributes();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004691
4692 // If the call already has the 'nest' attribute somewhere then give up -
4693 // otherwise 'nest' would occur twice after splicing in the chain.
Bill Wendling6e95ae82012-12-31 00:49:59 +00004694 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Craig Topperf40110f2014-04-25 05:29:35 +00004695 return nullptr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004696
Craig Topperc1892ec2019-01-31 17:23:29 +00004697 Function *NestF = cast<Function>(Tramp.getArgOperand(1)->stripPointerCasts());
James Y Knight291f7912019-02-01 20:44:54 +00004698 FunctionType *NestFTy = NestF->getFunctionType();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004699
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00004700 AttributeList NestAttrs = NestF->getAttributes();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004701 if (!NestAttrs.isEmpty()) {
Reid Klecknerf021fab2017-04-13 23:12:13 +00004702 unsigned NestArgNo = 0;
Craig Topperf40110f2014-04-25 05:29:35 +00004703 Type *NestTy = nullptr;
Reid Klecknerc2cb5602017-04-12 00:38:00 +00004704 AttributeSet NestAttr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004705
4706 // Look for a parameter marked with the 'nest' attribute.
4707 for (FunctionType::param_iterator I = NestFTy->param_begin(),
Reid Klecknerf021fab2017-04-13 23:12:13 +00004708 E = NestFTy->param_end();
4709 I != E; ++NestArgNo, ++I) {
4710 AttributeSet AS = NestAttrs.getParamAttributes(NestArgNo);
4711 if (AS.hasAttribute(Attribute::Nest)) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004712 // Record the parameter type and any other attributes.
4713 NestTy = *I;
Reid Klecknerf021fab2017-04-13 23:12:13 +00004714 NestAttr = AS;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004715 break;
4716 }
Reid Klecknerf021fab2017-04-13 23:12:13 +00004717 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004718
4719 if (NestTy) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004720 std::vector<Value*> NewArgs;
Reid Kleckner7f720332017-04-13 00:58:09 +00004721 std::vector<AttributeSet> NewArgAttrs;
Craig Topperc1892ec2019-01-31 17:23:29 +00004722 NewArgs.reserve(Call.arg_size() + 1);
4723 NewArgAttrs.reserve(Call.arg_size());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004724
4725 // Insert the nest argument into the call argument list, which may
4726 // mean appending it. Likewise for attributes.
4727
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004728 {
Reid Klecknerf021fab2017-04-13 23:12:13 +00004729 unsigned ArgNo = 0;
Craig Topperc1892ec2019-01-31 17:23:29 +00004730 auto I = Call.arg_begin(), E = Call.arg_end();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004731 do {
Reid Klecknerf021fab2017-04-13 23:12:13 +00004732 if (ArgNo == NestArgNo) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004733 // Add the chain argument and attributes.
Craig Topperc1892ec2019-01-31 17:23:29 +00004734 Value *NestVal = Tramp.getArgOperand(2);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004735 if (NestVal->getType() != NestTy)
Craig Topperbb4069e2017-07-07 23:16:26 +00004736 NestVal = Builder.CreateBitCast(NestVal, NestTy, "nest");
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004737 NewArgs.push_back(NestVal);
Reid Kleckner7f720332017-04-13 00:58:09 +00004738 NewArgAttrs.push_back(NestAttr);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004739 }
4740
4741 if (I == E)
4742 break;
4743
4744 // Add the original argument and attributes.
4745 NewArgs.push_back(*I);
Reid Klecknerf021fab2017-04-13 23:12:13 +00004746 NewArgAttrs.push_back(Attrs.getParamAttributes(ArgNo));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004747
Reid Klecknerf021fab2017-04-13 23:12:13 +00004748 ++ArgNo;
Richard Trieu7a083812016-02-18 22:09:30 +00004749 ++I;
Eugene Zelenkocdc71612016-08-11 17:20:18 +00004750 } while (true);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004751 }
4752
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004753 // The trampoline may have been bitcast to a bogus type (FTy).
4754 // Handle this by synthesizing a new function type, equal to FTy
4755 // with the chain parameter inserted.
4756
Jay Foadb804a2b2011-07-12 14:06:48 +00004757 std::vector<Type*> NewTypes;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004758 NewTypes.reserve(FTy->getNumParams()+1);
4759
4760 // Insert the chain's type into the list of parameter types, which may
4761 // mean appending it.
4762 {
Reid Klecknerf021fab2017-04-13 23:12:13 +00004763 unsigned ArgNo = 0;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004764 FunctionType::param_iterator I = FTy->param_begin(),
4765 E = FTy->param_end();
4766
4767 do {
Reid Klecknerf021fab2017-04-13 23:12:13 +00004768 if (ArgNo == NestArgNo)
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004769 // Add the chain's type.
4770 NewTypes.push_back(NestTy);
4771
4772 if (I == E)
4773 break;
4774
4775 // Add the original type.
4776 NewTypes.push_back(*I);
4777
Reid Klecknerf021fab2017-04-13 23:12:13 +00004778 ++ArgNo;
Richard Trieu7a083812016-02-18 22:09:30 +00004779 ++I;
Eugene Zelenkocdc71612016-08-11 17:20:18 +00004780 } while (true);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004781 }
4782
4783 // Replace the trampoline call with a direct call. Let the generic
4784 // code sort out any function type mismatches.
Jim Grosbach7815f562012-02-03 00:07:04 +00004785 FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004786 FTy->isVarArg());
4787 Constant *NewCallee =
4788 NestF->getType() == PointerType::getUnqual(NewFTy) ?
Jim Grosbach7815f562012-02-03 00:07:04 +00004789 NestF : ConstantExpr::getBitCast(NestF,
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004790 PointerType::getUnqual(NewFTy));
Reid Kleckner7f720332017-04-13 00:58:09 +00004791 AttributeList NewPAL =
4792 AttributeList::get(FTy->getContext(), Attrs.getFnAttributes(),
4793 Attrs.getRetAttributes(), NewArgAttrs);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004794
David Majnemer231a68c2016-04-29 08:07:20 +00004795 SmallVector<OperandBundleDef, 1> OpBundles;
Craig Topperc1892ec2019-01-31 17:23:29 +00004796 Call.getOperandBundlesAsDefs(OpBundles);
David Majnemer231a68c2016-04-29 08:07:20 +00004797
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004798 Instruction *NewCaller;
Craig Topperc1892ec2019-01-31 17:23:29 +00004799 if (InvokeInst *II = dyn_cast<InvokeInst>(&Call)) {
James Y Knight7976eb52019-02-01 20:43:25 +00004800 NewCaller = InvokeInst::Create(NewFTy, NewCallee,
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004801 II->getNormalDest(), II->getUnwindDest(),
David Majnemer231a68c2016-04-29 08:07:20 +00004802 NewArgs, OpBundles);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004803 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
4804 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
Craig Topper784929d2019-02-08 20:48:56 +00004805 } else if (CallBrInst *CBI = dyn_cast<CallBrInst>(&Call)) {
4806 NewCaller =
4807 CallBrInst::Create(NewFTy, NewCallee, CBI->getDefaultDest(),
4808 CBI->getIndirectDests(), NewArgs, OpBundles);
4809 cast<CallBrInst>(NewCaller)->setCallingConv(CBI->getCallingConv());
4810 cast<CallBrInst>(NewCaller)->setAttributes(NewPAL);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004811 } else {
James Y Knight7976eb52019-02-01 20:43:25 +00004812 NewCaller = CallInst::Create(NewFTy, NewCallee, NewArgs, OpBundles);
David Majnemerd5648c72016-11-25 22:35:09 +00004813 cast<CallInst>(NewCaller)->setTailCallKind(
Craig Topperc1892ec2019-01-31 17:23:29 +00004814 cast<CallInst>(Call).getTailCallKind());
David Majnemerd5648c72016-11-25 22:35:09 +00004815 cast<CallInst>(NewCaller)->setCallingConv(
Craig Topperc1892ec2019-01-31 17:23:29 +00004816 cast<CallInst>(Call).getCallingConv());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004817 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
4818 }
Craig Topperc1892ec2019-01-31 17:23:29 +00004819 NewCaller->setDebugLoc(Call.getDebugLoc());
Eli Friedman49346012011-05-18 19:57:14 +00004820
4821 return NewCaller;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004822 }
4823 }
4824
4825 // Replace the trampoline call with a direct call. Since there is no 'nest'
4826 // parameter, there is no need to adjust the argument list. Let the generic
4827 // code sort out any function type mismatches.
James Y Knight291f7912019-02-01 20:44:54 +00004828 Constant *NewCallee = ConstantExpr::getBitCast(NestF, CalleeTy);
4829 Call.setCalledFunction(FTy, NewCallee);
Craig Topperc1892ec2019-01-31 17:23:29 +00004830 return &Call;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004831}