blob: 019278b05e709c6d23bd776358c285f75b9e13ba [file] [log] [blame]
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001//===- InstCombineCalls.cpp -----------------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the visitCall and visitInvoke functions.
11//
12//===----------------------------------------------------------------------===//
13
Chandler Carrutha9174582015-01-22 05:25:13 +000014#include "InstCombineInternal.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000015#include "llvm/ADT/APFloat.h"
16#include "llvm/ADT/APInt.h"
17#include "llvm/ADT/ArrayRef.h"
18#include "llvm/ADT/None.h"
Meador Ingee3f2b262012-11-30 04:05:06 +000019#include "llvm/ADT/Statistic.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000020#include "llvm/ADT/STLExtras.h"
21#include "llvm/ADT/SmallVector.h"
22#include "llvm/ADT/Twine.h"
David Majnemer15032582015-05-22 03:56:46 +000023#include "llvm/Analysis/InstructionSimplify.h"
Chris Lattner7a9e47a2010-01-05 07:32:13 +000024#include "llvm/Analysis/MemoryBuiltins.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000025#include "llvm/Analysis/ValueTracking.h"
26#include "llvm/IR/BasicBlock.h"
Chandler Carruth219b89b2014-03-04 11:01:28 +000027#include "llvm/IR/CallSite.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000028#include "llvm/IR/Constant.h"
29#include "llvm/IR/DataLayout.h"
30#include "llvm/IR/DerivedTypes.h"
31#include "llvm/IR/Function.h"
32#include "llvm/IR/GlobalVariable.h"
33#include "llvm/IR/InstrTypes.h"
34#include "llvm/IR/Instruction.h"
35#include "llvm/IR/Instructions.h"
36#include "llvm/IR/IntrinsicInst.h"
37#include "llvm/IR/Intrinsics.h"
38#include "llvm/IR/LLVMContext.h"
39#include "llvm/IR/Metadata.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000040#include "llvm/IR/PatternMatch.h"
Philip Reames1a1bdb22014-12-02 18:50:36 +000041#include "llvm/IR/Statepoint.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000042#include "llvm/IR/Type.h"
43#include "llvm/IR/Value.h"
44#include "llvm/IR/ValueHandle.h"
45#include "llvm/Support/Casting.h"
46#include "llvm/Support/Debug.h"
47#include "llvm/Support/MathExtras.h"
Chris Lattner6fcd32e2010-12-25 20:37:57 +000048#include "llvm/Transforms/Utils/Local.h"
Chandler Carruthba4c5172015-01-21 11:23:40 +000049#include "llvm/Transforms/Utils/SimplifyLibCalls.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000050#include <algorithm>
51#include <cassert>
52#include <cstdint>
53#include <cstring>
54#include <vector>
55
Chris Lattner7a9e47a2010-01-05 07:32:13 +000056using namespace llvm;
Michael Ilseman536cc322012-12-13 03:13:36 +000057using namespace PatternMatch;
Chris Lattner7a9e47a2010-01-05 07:32:13 +000058
Chandler Carruth964daaa2014-04-22 02:55:47 +000059#define DEBUG_TYPE "instcombine"
60
Meador Ingee3f2b262012-11-30 04:05:06 +000061STATISTIC(NumSimplified, "Number of library calls simplified");
62
Igor Laevskya9b68722017-02-08 15:21:48 +000063static cl::opt<unsigned> UnfoldElementAtomicMemcpyMaxElements(
Igor Laevsky900ffa32017-02-08 14:32:04 +000064 "unfold-element-atomic-memcpy-max-elements",
65 cl::init(16),
66 cl::desc("Maximum number of elements in atomic memcpy the optimizer is "
67 "allowed to unfold"));
68
Sanjay Patelcd4377c2016-01-20 22:24:38 +000069/// Return the specified type promoted as it would be to pass though a va_arg
70/// area.
Chris Lattner229907c2011-07-18 04:54:35 +000071static Type *getPromotedType(Type *Ty) {
72 if (IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +000073 if (ITy->getBitWidth() < 32)
74 return Type::getInt32Ty(Ty->getContext());
75 }
76 return Ty;
77}
78
Sanjay Patel368ac5d2016-02-21 17:29:33 +000079/// Return a constant boolean vector that has true elements in all positions
Sanjay Patel24401302016-02-21 17:33:31 +000080/// where the input constant data vector has an element with the sign bit set.
Sanjay Patel368ac5d2016-02-21 17:29:33 +000081static Constant *getNegativeIsTrueBoolVec(ConstantDataVector *V) {
82 SmallVector<Constant *, 32> BoolVec;
83 IntegerType *BoolTy = Type::getInt1Ty(V->getContext());
84 for (unsigned I = 0, E = V->getNumElements(); I != E; ++I) {
85 Constant *Elt = V->getElementAsConstant(I);
86 assert((isa<ConstantInt>(Elt) || isa<ConstantFP>(Elt)) &&
87 "Unexpected constant data vector element type");
88 bool Sign = V->getElementType()->isIntegerTy()
89 ? cast<ConstantInt>(Elt)->isNegative()
90 : cast<ConstantFP>(Elt)->isNegative();
91 BoolVec.push_back(ConstantInt::get(BoolTy, Sign));
92 }
93 return ConstantVector::get(BoolVec);
94}
95
Igor Laevsky900ffa32017-02-08 14:32:04 +000096Instruction *
97InstCombiner::SimplifyElementAtomicMemCpy(ElementAtomicMemCpyInst *AMI) {
98 // Try to unfold this intrinsic into sequence of explicit atomic loads and
99 // stores.
100 // First check that number of elements is compile time constant.
101 auto *NumElementsCI = dyn_cast<ConstantInt>(AMI->getNumElements());
102 if (!NumElementsCI)
103 return nullptr;
104
105 // Check that there are not too many elements.
106 uint64_t NumElements = NumElementsCI->getZExtValue();
107 if (NumElements >= UnfoldElementAtomicMemcpyMaxElements)
108 return nullptr;
109
110 // Don't unfold into illegal integers
111 uint64_t ElementSizeInBytes = AMI->getElementSizeInBytes() * 8;
112 if (!getDataLayout().isLegalInteger(ElementSizeInBytes))
113 return nullptr;
114
115 // Cast source and destination to the correct type. Intrinsic input arguments
116 // are usually represented as i8*.
117 // Often operands will be explicitly casted to i8* and we can just strip
118 // those casts instead of inserting new ones. However it's easier to rely on
119 // other InstCombine rules which will cover trivial cases anyway.
120 Value *Src = AMI->getRawSource();
121 Value *Dst = AMI->getRawDest();
122 Type *ElementPointerType = Type::getIntNPtrTy(
123 AMI->getContext(), ElementSizeInBytes, Src->getType()->getPointerAddressSpace());
124
125 Value *SrcCasted = Builder->CreatePointerCast(Src, ElementPointerType,
126 "memcpy_unfold.src_casted");
127 Value *DstCasted = Builder->CreatePointerCast(Dst, ElementPointerType,
128 "memcpy_unfold.dst_casted");
129
130 for (uint64_t i = 0; i < NumElements; ++i) {
131 // Get current element addresses
132 ConstantInt *ElementIdxCI =
133 ConstantInt::get(AMI->getContext(), APInt(64, i));
134 Value *SrcElementAddr =
135 Builder->CreateGEP(SrcCasted, ElementIdxCI, "memcpy_unfold.src_addr");
136 Value *DstElementAddr =
137 Builder->CreateGEP(DstCasted, ElementIdxCI, "memcpy_unfold.dst_addr");
138
139 // Load from the source. Transfer alignment information and mark load as
140 // unordered atomic.
141 LoadInst *Load = Builder->CreateLoad(SrcElementAddr, "memcpy_unfold.val");
142 Load->setOrdering(AtomicOrdering::Unordered);
143 // We know alignment of the first element. It is also guaranteed by the
144 // verifier that element size is less or equal than first element alignment
145 // and both of this values are powers of two.
146 // This means that all subsequent accesses are at least element size
147 // aligned.
148 // TODO: We can infer better alignment but there is no evidence that this
149 // will matter.
150 Load->setAlignment(i == 0 ? AMI->getSrcAlignment()
151 : AMI->getElementSizeInBytes());
152 Load->setDebugLoc(AMI->getDebugLoc());
153
154 // Store loaded value via unordered atomic store.
155 StoreInst *Store = Builder->CreateStore(Load, DstElementAddr);
156 Store->setOrdering(AtomicOrdering::Unordered);
157 Store->setAlignment(i == 0 ? AMI->getDstAlignment()
158 : AMI->getElementSizeInBytes());
159 Store->setDebugLoc(AMI->getDebugLoc());
160 }
161
162 // Set the number of elements of the copy to 0, it will be deleted on the
163 // next iteration.
164 AMI->setNumElements(Constant::getNullValue(NumElementsCI->getType()));
165 return AMI;
166}
167
Pete Cooper67cf9a72015-11-19 05:56:52 +0000168Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000169 unsigned DstAlign = getKnownAlignment(MI->getArgOperand(0), DL, MI, &AC, &DT);
170 unsigned SrcAlign = getKnownAlignment(MI->getArgOperand(1), DL, MI, &AC, &DT);
Pete Cooper67cf9a72015-11-19 05:56:52 +0000171 unsigned MinAlign = std::min(DstAlign, SrcAlign);
172 unsigned CopyAlign = MI->getAlignment();
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000173
Pete Cooper67cf9a72015-11-19 05:56:52 +0000174 if (CopyAlign < MinAlign) {
175 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(), MinAlign, false));
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000176 return MI;
177 }
Jim Grosbach7815f562012-02-03 00:07:04 +0000178
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000179 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
180 // load/store.
Gabor Greif0a136c92010-06-24 13:54:33 +0000181 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getArgOperand(2));
Craig Topperf40110f2014-04-25 05:29:35 +0000182 if (!MemOpLength) return nullptr;
Jim Grosbach7815f562012-02-03 00:07:04 +0000183
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000184 // Source and destination pointer types are always "i8*" for intrinsic. See
185 // if the size is something we can handle with a single primitive load/store.
186 // A single load+store correctly handles overlapping memory in the memmove
187 // case.
Michael Liao69e172a2012-08-15 03:49:59 +0000188 uint64_t Size = MemOpLength->getLimitedValue();
Alp Tokercb402912014-01-24 17:20:08 +0000189 assert(Size && "0-sized memory transferring should be removed already.");
Jim Grosbach7815f562012-02-03 00:07:04 +0000190
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000191 if (Size > 8 || (Size&(Size-1)))
Craig Topperf40110f2014-04-25 05:29:35 +0000192 return nullptr; // If not 1/2/4/8 bytes, exit.
Jim Grosbach7815f562012-02-03 00:07:04 +0000193
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000194 // Use an integer load+store unless we can find something better.
Mon P Wangc576ee92010-04-04 03:10:48 +0000195 unsigned SrcAddrSp =
Gabor Greif0a136c92010-06-24 13:54:33 +0000196 cast<PointerType>(MI->getArgOperand(1)->getType())->getAddressSpace();
Gabor Greiff3755202010-04-16 15:33:14 +0000197 unsigned DstAddrSp =
Gabor Greif0a136c92010-06-24 13:54:33 +0000198 cast<PointerType>(MI->getArgOperand(0)->getType())->getAddressSpace();
Mon P Wangc576ee92010-04-04 03:10:48 +0000199
Chris Lattner229907c2011-07-18 04:54:35 +0000200 IntegerType* IntType = IntegerType::get(MI->getContext(), Size<<3);
Mon P Wangc576ee92010-04-04 03:10:48 +0000201 Type *NewSrcPtrTy = PointerType::get(IntType, SrcAddrSp);
202 Type *NewDstPtrTy = PointerType::get(IntType, DstAddrSp);
Jim Grosbach7815f562012-02-03 00:07:04 +0000203
Mikael Holmen760dc9a2017-03-01 06:45:20 +0000204 // If the memcpy has metadata describing the members, see if we can get the
205 // TBAA tag describing our copy.
Craig Topperf40110f2014-04-25 05:29:35 +0000206 MDNode *CopyMD = nullptr;
Mikael Holmen760dc9a2017-03-01 06:45:20 +0000207 if (MDNode *M = MI->getMetadata(LLVMContext::MD_tbaa_struct)) {
208 if (M->getNumOperands() == 3 && M->getOperand(0) &&
209 mdconst::hasa<ConstantInt>(M->getOperand(0)) &&
210 mdconst::extract<ConstantInt>(M->getOperand(0))->isNullValue() &&
211 M->getOperand(1) &&
212 mdconst::hasa<ConstantInt>(M->getOperand(1)) &&
213 mdconst::extract<ConstantInt>(M->getOperand(1))->getValue() ==
214 Size &&
215 M->getOperand(2) && isa<MDNode>(M->getOperand(2)))
216 CopyMD = cast<MDNode>(M->getOperand(2));
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000217 }
Jim Grosbach7815f562012-02-03 00:07:04 +0000218
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000219 // If the memcpy/memmove provides better alignment info than we can
220 // infer, use it.
Pete Cooper67cf9a72015-11-19 05:56:52 +0000221 SrcAlign = std::max(SrcAlign, CopyAlign);
222 DstAlign = std::max(DstAlign, CopyAlign);
Jim Grosbach7815f562012-02-03 00:07:04 +0000223
Gabor Greif5f3e6562010-06-25 07:57:14 +0000224 Value *Src = Builder->CreateBitCast(MI->getArgOperand(1), NewSrcPtrTy);
225 Value *Dest = Builder->CreateBitCast(MI->getArgOperand(0), NewDstPtrTy);
Eli Friedman49346012011-05-18 19:57:14 +0000226 LoadInst *L = Builder->CreateLoad(Src, MI->isVolatile());
227 L->setAlignment(SrcAlign);
Dan Gohman3f553c22012-09-13 21:51:01 +0000228 if (CopyMD)
229 L->setMetadata(LLVMContext::MD_tbaa, CopyMD);
Dorit Nuzmanabd15f62016-09-04 07:49:39 +0000230 MDNode *LoopMemParallelMD =
231 MI->getMetadata(LLVMContext::MD_mem_parallel_loop_access);
232 if (LoopMemParallelMD)
233 L->setMetadata(LLVMContext::MD_mem_parallel_loop_access, LoopMemParallelMD);
Dorit Nuzman7673ba72016-09-04 07:06:00 +0000234
Eli Friedman49346012011-05-18 19:57:14 +0000235 StoreInst *S = Builder->CreateStore(L, Dest, MI->isVolatile());
236 S->setAlignment(DstAlign);
Dan Gohman3f553c22012-09-13 21:51:01 +0000237 if (CopyMD)
238 S->setMetadata(LLVMContext::MD_tbaa, CopyMD);
Dorit Nuzmanabd15f62016-09-04 07:49:39 +0000239 if (LoopMemParallelMD)
240 S->setMetadata(LLVMContext::MD_mem_parallel_loop_access, LoopMemParallelMD);
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000241
242 // Set the size of the copy to 0, it will be deleted on the next iteration.
Gabor Greif5b1370e2010-06-28 16:50:57 +0000243 MI->setArgOperand(2, Constant::getNullValue(MemOpLength->getType()));
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000244 return MI;
245}
246
247Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000248 unsigned Alignment = getKnownAlignment(MI->getDest(), DL, MI, &AC, &DT);
Pete Cooper67cf9a72015-11-19 05:56:52 +0000249 if (MI->getAlignment() < Alignment) {
250 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
251 Alignment, false));
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000252 return MI;
253 }
Jim Grosbach7815f562012-02-03 00:07:04 +0000254
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000255 // Extract the length and alignment and fill if they are constant.
256 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
257 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
Duncan Sands9dff9be2010-02-15 16:12:20 +0000258 if (!LenC || !FillC || !FillC->getType()->isIntegerTy(8))
Craig Topperf40110f2014-04-25 05:29:35 +0000259 return nullptr;
Michael Liao69e172a2012-08-15 03:49:59 +0000260 uint64_t Len = LenC->getLimitedValue();
Pete Cooper67cf9a72015-11-19 05:56:52 +0000261 Alignment = MI->getAlignment();
Michael Liao69e172a2012-08-15 03:49:59 +0000262 assert(Len && "0-sized memory setting should be removed already.");
Jim Grosbach7815f562012-02-03 00:07:04 +0000263
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000264 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
265 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
Chris Lattner229907c2011-07-18 04:54:35 +0000266 Type *ITy = IntegerType::get(MI->getContext(), Len*8); // n=1 -> i8.
Jim Grosbach7815f562012-02-03 00:07:04 +0000267
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000268 Value *Dest = MI->getDest();
Mon P Wang1991c472010-12-20 01:05:30 +0000269 unsigned DstAddrSp = cast<PointerType>(Dest->getType())->getAddressSpace();
270 Type *NewDstPtrTy = PointerType::get(ITy, DstAddrSp);
271 Dest = Builder->CreateBitCast(Dest, NewDstPtrTy);
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000272
273 // Alignment 0 is identity for alignment 1 for memset, but not store.
274 if (Alignment == 0) Alignment = 1;
Jim Grosbach7815f562012-02-03 00:07:04 +0000275
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000276 // Extract the fill value and store.
277 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
Eli Friedman49346012011-05-18 19:57:14 +0000278 StoreInst *S = Builder->CreateStore(ConstantInt::get(ITy, Fill), Dest,
279 MI->isVolatile());
280 S->setAlignment(Alignment);
Jim Grosbach7815f562012-02-03 00:07:04 +0000281
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000282 // Set the size of the copy to 0, it will be deleted on the next iteration.
283 MI->setLength(Constant::getNullValue(LenC->getType()));
284 return MI;
285 }
286
Simon Pilgrim18617d12015-08-05 08:18:00 +0000287 return nullptr;
288}
289
Sanjay Patel6038d3e2016-01-29 23:27:03 +0000290static Value *simplifyX86immShift(const IntrinsicInst &II,
Simon Pilgrimbecd5e82015-08-13 07:39:03 +0000291 InstCombiner::BuilderTy &Builder) {
292 bool LogicalShift = false;
293 bool ShiftLeft = false;
294
295 switch (II.getIntrinsicID()) {
Craig Topperb4173a52016-11-13 07:26:19 +0000296 default: llvm_unreachable("Unexpected intrinsic!");
Simon Pilgrimbecd5e82015-08-13 07:39:03 +0000297 case Intrinsic::x86_sse2_psra_d:
298 case Intrinsic::x86_sse2_psra_w:
299 case Intrinsic::x86_sse2_psrai_d:
300 case Intrinsic::x86_sse2_psrai_w:
301 case Intrinsic::x86_avx2_psra_d:
302 case Intrinsic::x86_avx2_psra_w:
303 case Intrinsic::x86_avx2_psrai_d:
304 case Intrinsic::x86_avx2_psrai_w:
Craig Topper8b831cb2016-11-13 01:51:55 +0000305 case Intrinsic::x86_avx512_psra_q_128:
306 case Intrinsic::x86_avx512_psrai_q_128:
307 case Intrinsic::x86_avx512_psra_q_256:
308 case Intrinsic::x86_avx512_psrai_q_256:
309 case Intrinsic::x86_avx512_psra_d_512:
310 case Intrinsic::x86_avx512_psra_q_512:
311 case Intrinsic::x86_avx512_psra_w_512:
312 case Intrinsic::x86_avx512_psrai_d_512:
313 case Intrinsic::x86_avx512_psrai_q_512:
314 case Intrinsic::x86_avx512_psrai_w_512:
Simon Pilgrimbecd5e82015-08-13 07:39:03 +0000315 LogicalShift = false; ShiftLeft = false;
316 break;
317 case Intrinsic::x86_sse2_psrl_d:
318 case Intrinsic::x86_sse2_psrl_q:
319 case Intrinsic::x86_sse2_psrl_w:
320 case Intrinsic::x86_sse2_psrli_d:
321 case Intrinsic::x86_sse2_psrli_q:
322 case Intrinsic::x86_sse2_psrli_w:
323 case Intrinsic::x86_avx2_psrl_d:
324 case Intrinsic::x86_avx2_psrl_q:
325 case Intrinsic::x86_avx2_psrl_w:
326 case Intrinsic::x86_avx2_psrli_d:
327 case Intrinsic::x86_avx2_psrli_q:
328 case Intrinsic::x86_avx2_psrli_w:
Craig Topper8b831cb2016-11-13 01:51:55 +0000329 case Intrinsic::x86_avx512_psrl_d_512:
330 case Intrinsic::x86_avx512_psrl_q_512:
331 case Intrinsic::x86_avx512_psrl_w_512:
332 case Intrinsic::x86_avx512_psrli_d_512:
333 case Intrinsic::x86_avx512_psrli_q_512:
334 case Intrinsic::x86_avx512_psrli_w_512:
Simon Pilgrimbecd5e82015-08-13 07:39:03 +0000335 LogicalShift = true; ShiftLeft = false;
336 break;
337 case Intrinsic::x86_sse2_psll_d:
338 case Intrinsic::x86_sse2_psll_q:
339 case Intrinsic::x86_sse2_psll_w:
340 case Intrinsic::x86_sse2_pslli_d:
341 case Intrinsic::x86_sse2_pslli_q:
342 case Intrinsic::x86_sse2_pslli_w:
343 case Intrinsic::x86_avx2_psll_d:
344 case Intrinsic::x86_avx2_psll_q:
345 case Intrinsic::x86_avx2_psll_w:
346 case Intrinsic::x86_avx2_pslli_d:
347 case Intrinsic::x86_avx2_pslli_q:
348 case Intrinsic::x86_avx2_pslli_w:
Craig Topper8b831cb2016-11-13 01:51:55 +0000349 case Intrinsic::x86_avx512_psll_d_512:
350 case Intrinsic::x86_avx512_psll_q_512:
351 case Intrinsic::x86_avx512_psll_w_512:
352 case Intrinsic::x86_avx512_pslli_d_512:
353 case Intrinsic::x86_avx512_pslli_q_512:
354 case Intrinsic::x86_avx512_pslli_w_512:
Simon Pilgrimbecd5e82015-08-13 07:39:03 +0000355 LogicalShift = true; ShiftLeft = true;
356 break;
357 }
Simon Pilgrima3a72b42015-08-10 20:21:15 +0000358 assert((LogicalShift || !ShiftLeft) && "Only logical shifts can shift left");
359
Simon Pilgrim3815c162015-08-07 18:22:50 +0000360 // Simplify if count is constant.
361 auto Arg1 = II.getArgOperand(1);
362 auto CAZ = dyn_cast<ConstantAggregateZero>(Arg1);
363 auto CDV = dyn_cast<ConstantDataVector>(Arg1);
364 auto CInt = dyn_cast<ConstantInt>(Arg1);
365 if (!CAZ && !CDV && !CInt)
Simon Pilgrim18617d12015-08-05 08:18:00 +0000366 return nullptr;
Simon Pilgrim3815c162015-08-07 18:22:50 +0000367
368 APInt Count(64, 0);
369 if (CDV) {
370 // SSE2/AVX2 uses all the first 64-bits of the 128-bit vector
371 // operand to compute the shift amount.
372 auto VT = cast<VectorType>(CDV->getType());
373 unsigned BitWidth = VT->getElementType()->getPrimitiveSizeInBits();
374 assert((64 % BitWidth) == 0 && "Unexpected packed shift size");
375 unsigned NumSubElts = 64 / BitWidth;
376
377 // Concatenate the sub-elements to create the 64-bit value.
378 for (unsigned i = 0; i != NumSubElts; ++i) {
379 unsigned SubEltIdx = (NumSubElts - 1) - i;
380 auto SubElt = cast<ConstantInt>(CDV->getElementAsConstant(SubEltIdx));
381 Count = Count.shl(BitWidth);
382 Count |= SubElt->getValue().zextOrTrunc(64);
383 }
384 }
385 else if (CInt)
386 Count = CInt->getValue();
Simon Pilgrim18617d12015-08-05 08:18:00 +0000387
388 auto Vec = II.getArgOperand(0);
389 auto VT = cast<VectorType>(Vec->getType());
390 auto SVT = VT->getElementType();
Simon Pilgrim3815c162015-08-07 18:22:50 +0000391 unsigned VWidth = VT->getNumElements();
392 unsigned BitWidth = SVT->getPrimitiveSizeInBits();
393
394 // If shift-by-zero then just return the original value.
395 if (Count == 0)
396 return Vec;
397
Simon Pilgrima3a72b42015-08-10 20:21:15 +0000398 // Handle cases when Shift >= BitWidth.
399 if (Count.uge(BitWidth)) {
400 // If LogicalShift - just return zero.
401 if (LogicalShift)
402 return ConstantAggregateZero::get(VT);
403
404 // If ArithmeticShift - clamp Shift to (BitWidth - 1).
405 Count = APInt(64, BitWidth - 1);
406 }
Simon Pilgrim18617d12015-08-05 08:18:00 +0000407
Simon Pilgrim18617d12015-08-05 08:18:00 +0000408 // Get a constant vector of the same type as the first operand.
Simon Pilgrim3815c162015-08-07 18:22:50 +0000409 auto ShiftAmt = ConstantInt::get(SVT, Count.zextOrTrunc(BitWidth));
410 auto ShiftVec = Builder.CreateVectorSplat(VWidth, ShiftAmt);
Simon Pilgrim18617d12015-08-05 08:18:00 +0000411
412 if (ShiftLeft)
Simon Pilgrim3815c162015-08-07 18:22:50 +0000413 return Builder.CreateShl(Vec, ShiftVec);
Simon Pilgrim18617d12015-08-05 08:18:00 +0000414
Simon Pilgrima3a72b42015-08-10 20:21:15 +0000415 if (LogicalShift)
416 return Builder.CreateLShr(Vec, ShiftVec);
417
418 return Builder.CreateAShr(Vec, ShiftVec);
Simon Pilgrim18617d12015-08-05 08:18:00 +0000419}
420
Simon Pilgrimdb9893f2016-06-07 10:27:15 +0000421// Attempt to simplify AVX2 per-element shift intrinsics to a generic IR shift.
422// Unlike the generic IR shifts, the intrinsics have defined behaviour for out
423// of range shift amounts (logical - set to zero, arithmetic - splat sign bit).
424static Value *simplifyX86varShift(const IntrinsicInst &II,
425 InstCombiner::BuilderTy &Builder) {
426 bool LogicalShift = false;
427 bool ShiftLeft = false;
428
429 switch (II.getIntrinsicID()) {
Craig Topperb4173a52016-11-13 07:26:19 +0000430 default: llvm_unreachable("Unexpected intrinsic!");
Simon Pilgrimdb9893f2016-06-07 10:27:15 +0000431 case Intrinsic::x86_avx2_psrav_d:
432 case Intrinsic::x86_avx2_psrav_d_256:
Craig Topperb4173a52016-11-13 07:26:19 +0000433 case Intrinsic::x86_avx512_psrav_q_128:
434 case Intrinsic::x86_avx512_psrav_q_256:
435 case Intrinsic::x86_avx512_psrav_d_512:
436 case Intrinsic::x86_avx512_psrav_q_512:
Craig Topper1de753f2016-11-18 06:04:33 +0000437 case Intrinsic::x86_avx512_psrav_w_128:
438 case Intrinsic::x86_avx512_psrav_w_256:
439 case Intrinsic::x86_avx512_psrav_w_512:
Simon Pilgrimdb9893f2016-06-07 10:27:15 +0000440 LogicalShift = false;
441 ShiftLeft = false;
442 break;
443 case Intrinsic::x86_avx2_psrlv_d:
444 case Intrinsic::x86_avx2_psrlv_d_256:
445 case Intrinsic::x86_avx2_psrlv_q:
446 case Intrinsic::x86_avx2_psrlv_q_256:
Craig Topperb4173a52016-11-13 07:26:19 +0000447 case Intrinsic::x86_avx512_psrlv_d_512:
448 case Intrinsic::x86_avx512_psrlv_q_512:
Craig Topper1de753f2016-11-18 06:04:33 +0000449 case Intrinsic::x86_avx512_psrlv_w_128:
450 case Intrinsic::x86_avx512_psrlv_w_256:
451 case Intrinsic::x86_avx512_psrlv_w_512:
Simon Pilgrimdb9893f2016-06-07 10:27:15 +0000452 LogicalShift = true;
453 ShiftLeft = false;
454 break;
455 case Intrinsic::x86_avx2_psllv_d:
456 case Intrinsic::x86_avx2_psllv_d_256:
457 case Intrinsic::x86_avx2_psllv_q:
458 case Intrinsic::x86_avx2_psllv_q_256:
Craig Topperb4173a52016-11-13 07:26:19 +0000459 case Intrinsic::x86_avx512_psllv_d_512:
460 case Intrinsic::x86_avx512_psllv_q_512:
Craig Topper1de753f2016-11-18 06:04:33 +0000461 case Intrinsic::x86_avx512_psllv_w_128:
462 case Intrinsic::x86_avx512_psllv_w_256:
463 case Intrinsic::x86_avx512_psllv_w_512:
Simon Pilgrimdb9893f2016-06-07 10:27:15 +0000464 LogicalShift = true;
465 ShiftLeft = true;
466 break;
467 }
468 assert((LogicalShift || !ShiftLeft) && "Only logical shifts can shift left");
469
470 // Simplify if all shift amounts are constant/undef.
471 auto *CShift = dyn_cast<Constant>(II.getArgOperand(1));
472 if (!CShift)
473 return nullptr;
474
475 auto Vec = II.getArgOperand(0);
476 auto VT = cast<VectorType>(II.getType());
477 auto SVT = VT->getVectorElementType();
478 int NumElts = VT->getNumElements();
479 int BitWidth = SVT->getIntegerBitWidth();
480
481 // Collect each element's shift amount.
482 // We also collect special cases: UNDEF = -1, OUT-OF-RANGE = BitWidth.
483 bool AnyOutOfRange = false;
484 SmallVector<int, 8> ShiftAmts;
485 for (int I = 0; I < NumElts; ++I) {
486 auto *CElt = CShift->getAggregateElement(I);
487 if (CElt && isa<UndefValue>(CElt)) {
488 ShiftAmts.push_back(-1);
489 continue;
490 }
491
492 auto *COp = dyn_cast_or_null<ConstantInt>(CElt);
493 if (!COp)
494 return nullptr;
495
496 // Handle out of range shifts.
497 // If LogicalShift - set to BitWidth (special case).
498 // If ArithmeticShift - set to (BitWidth - 1) (sign splat).
499 APInt ShiftVal = COp->getValue();
500 if (ShiftVal.uge(BitWidth)) {
501 AnyOutOfRange = LogicalShift;
502 ShiftAmts.push_back(LogicalShift ? BitWidth : BitWidth - 1);
503 continue;
504 }
505
506 ShiftAmts.push_back((int)ShiftVal.getZExtValue());
507 }
508
509 // If all elements out of range or UNDEF, return vector of zeros/undefs.
510 // ArithmeticShift should only hit this if they are all UNDEF.
511 auto OutOfRange = [&](int Idx) { return (Idx < 0) || (BitWidth <= Idx); };
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000512 if (all_of(ShiftAmts, OutOfRange)) {
Simon Pilgrimdb9893f2016-06-07 10:27:15 +0000513 SmallVector<Constant *, 8> ConstantVec;
514 for (int Idx : ShiftAmts) {
515 if (Idx < 0) {
516 ConstantVec.push_back(UndefValue::get(SVT));
517 } else {
518 assert(LogicalShift && "Logical shift expected");
519 ConstantVec.push_back(ConstantInt::getNullValue(SVT));
520 }
521 }
522 return ConstantVector::get(ConstantVec);
523 }
524
525 // We can't handle only some out of range values with generic logical shifts.
526 if (AnyOutOfRange)
527 return nullptr;
528
529 // Build the shift amount constant vector.
530 SmallVector<Constant *, 8> ShiftVecAmts;
531 for (int Idx : ShiftAmts) {
532 if (Idx < 0)
533 ShiftVecAmts.push_back(UndefValue::get(SVT));
534 else
535 ShiftVecAmts.push_back(ConstantInt::get(SVT, Idx));
536 }
537 auto ShiftVec = ConstantVector::get(ShiftVecAmts);
538
539 if (ShiftLeft)
540 return Builder.CreateShl(Vec, ShiftVec);
541
542 if (LogicalShift)
543 return Builder.CreateLShr(Vec, ShiftVec);
544
545 return Builder.CreateAShr(Vec, ShiftVec);
546}
547
Simon Pilgrimf6f3a3612017-01-23 15:22:59 +0000548static Value *simplifyX86muldq(const IntrinsicInst &II,
549 InstCombiner::BuilderTy &Builder) {
Simon Pilgrima50a93f2017-01-20 18:20:30 +0000550 Value *Arg0 = II.getArgOperand(0);
551 Value *Arg1 = II.getArgOperand(1);
552 Type *ResTy = II.getType();
Simon Pilgrimf6f3a3612017-01-23 15:22:59 +0000553 assert(Arg0->getType()->getScalarSizeInBits() == 32 &&
554 Arg1->getType()->getScalarSizeInBits() == 32 &&
555 ResTy->getScalarSizeInBits() == 64 && "Unexpected muldq/muludq types");
Simon Pilgrima50a93f2017-01-20 18:20:30 +0000556
Simon Pilgrimbb13fda2017-01-23 12:07:32 +0000557 // muldq/muludq(undef, undef) -> zero (matches generic mul behavior)
Simon Pilgrim78f86302017-01-24 11:07:41 +0000558 if (isa<UndefValue>(Arg0) || isa<UndefValue>(Arg1))
Simon Pilgrimbb13fda2017-01-23 12:07:32 +0000559 return ConstantAggregateZero::get(ResTy);
Simon Pilgrima50a93f2017-01-20 18:20:30 +0000560
Simon Pilgrimf6f3a3612017-01-23 15:22:59 +0000561 // Constant folding.
562 // PMULDQ = (mul(vXi64 sext(shuffle<0,2,..>(Arg0)),
563 // vXi64 sext(shuffle<0,2,..>(Arg1))))
564 // PMULUDQ = (mul(vXi64 zext(shuffle<0,2,..>(Arg0)),
565 // vXi64 zext(shuffle<0,2,..>(Arg1))))
566 if (!isa<Constant>(Arg0) || !isa<Constant>(Arg1))
567 return nullptr;
568
569 unsigned NumElts = ResTy->getVectorNumElements();
570 assert(Arg0->getType()->getVectorNumElements() == (2 * NumElts) &&
571 Arg1->getType()->getVectorNumElements() == (2 * NumElts) &&
572 "Unexpected muldq/muludq types");
573
574 unsigned IntrinsicID = II.getIntrinsicID();
575 bool IsSigned = (Intrinsic::x86_sse41_pmuldq == IntrinsicID ||
576 Intrinsic::x86_avx2_pmul_dq == IntrinsicID ||
577 Intrinsic::x86_avx512_pmul_dq_512 == IntrinsicID);
578
579 SmallVector<unsigned, 16> ShuffleMask;
580 for (unsigned i = 0; i != NumElts; ++i)
581 ShuffleMask.push_back(i * 2);
582
583 auto *LHS = Builder.CreateShuffleVector(Arg0, Arg0, ShuffleMask);
584 auto *RHS = Builder.CreateShuffleVector(Arg1, Arg1, ShuffleMask);
585
586 if (IsSigned) {
587 LHS = Builder.CreateSExt(LHS, ResTy);
588 RHS = Builder.CreateSExt(RHS, ResTy);
589 } else {
590 LHS = Builder.CreateZExt(LHS, ResTy);
591 RHS = Builder.CreateZExt(RHS, ResTy);
592 }
593
594 return Builder.CreateMul(LHS, RHS);
Simon Pilgrima50a93f2017-01-20 18:20:30 +0000595}
596
Simon Pilgrim6f6b2792017-01-25 14:37:24 +0000597static Value *simplifyX86pack(IntrinsicInst &II, InstCombiner &IC,
598 InstCombiner::BuilderTy &Builder, bool IsSigned) {
599 Value *Arg0 = II.getArgOperand(0);
600 Value *Arg1 = II.getArgOperand(1);
601 Type *ResTy = II.getType();
602
603 // Fast all undef handling.
604 if (isa<UndefValue>(Arg0) && isa<UndefValue>(Arg1))
605 return UndefValue::get(ResTy);
606
607 Type *ArgTy = Arg0->getType();
608 unsigned NumLanes = ResTy->getPrimitiveSizeInBits() / 128;
609 unsigned NumDstElts = ResTy->getVectorNumElements();
610 unsigned NumSrcElts = ArgTy->getVectorNumElements();
611 assert(NumDstElts == (2 * NumSrcElts) && "Unexpected packing types");
612
613 unsigned NumDstEltsPerLane = NumDstElts / NumLanes;
614 unsigned NumSrcEltsPerLane = NumSrcElts / NumLanes;
615 unsigned DstScalarSizeInBits = ResTy->getScalarSizeInBits();
616 assert(ArgTy->getScalarSizeInBits() == (2 * DstScalarSizeInBits) &&
617 "Unexpected packing types");
618
619 // Constant folding.
620 auto *Cst0 = dyn_cast<Constant>(Arg0);
621 auto *Cst1 = dyn_cast<Constant>(Arg1);
622 if (!Cst0 || !Cst1)
623 return nullptr;
624
625 SmallVector<Constant *, 32> Vals;
626 for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
627 for (unsigned Elt = 0; Elt != NumDstEltsPerLane; ++Elt) {
628 unsigned SrcIdx = Lane * NumSrcEltsPerLane + Elt % NumSrcEltsPerLane;
629 auto *Cst = (Elt >= NumSrcEltsPerLane) ? Cst1 : Cst0;
630 auto *COp = Cst->getAggregateElement(SrcIdx);
631 if (COp && isa<UndefValue>(COp)) {
632 Vals.push_back(UndefValue::get(ResTy->getScalarType()));
633 continue;
634 }
635
636 auto *CInt = dyn_cast_or_null<ConstantInt>(COp);
637 if (!CInt)
638 return nullptr;
639
640 APInt Val = CInt->getValue();
641 assert(Val.getBitWidth() == ArgTy->getScalarSizeInBits() &&
642 "Unexpected constant bitwidth");
643
644 if (IsSigned) {
645 // PACKSS: Truncate signed value with signed saturation.
646 // Source values less than dst minint are saturated to minint.
647 // Source values greater than dst maxint are saturated to maxint.
648 if (Val.isSignedIntN(DstScalarSizeInBits))
649 Val = Val.trunc(DstScalarSizeInBits);
650 else if (Val.isNegative())
651 Val = APInt::getSignedMinValue(DstScalarSizeInBits);
652 else
653 Val = APInt::getSignedMaxValue(DstScalarSizeInBits);
654 } else {
655 // PACKUS: Truncate signed value with unsigned saturation.
656 // Source values less than zero are saturated to zero.
657 // Source values greater than dst maxuint are saturated to maxuint.
658 if (Val.isIntN(DstScalarSizeInBits))
659 Val = Val.trunc(DstScalarSizeInBits);
660 else if (Val.isNegative())
661 Val = APInt::getNullValue(DstScalarSizeInBits);
662 else
663 Val = APInt::getAllOnesValue(DstScalarSizeInBits);
664 }
665
666 Vals.push_back(ConstantInt::get(ResTy->getScalarType(), Val));
667 }
668 }
669
670 return ConstantVector::get(Vals);
671}
672
Simon Pilgrim91e3ac82016-06-07 08:18:35 +0000673static Value *simplifyX86movmsk(const IntrinsicInst &II,
674 InstCombiner::BuilderTy &Builder) {
675 Value *Arg = II.getArgOperand(0);
676 Type *ResTy = II.getType();
677 Type *ArgTy = Arg->getType();
678
679 // movmsk(undef) -> zero as we must ensure the upper bits are zero.
680 if (isa<UndefValue>(Arg))
681 return Constant::getNullValue(ResTy);
682
683 // We can't easily peek through x86_mmx types.
684 if (!ArgTy->isVectorTy())
685 return nullptr;
686
687 auto *C = dyn_cast<Constant>(Arg);
688 if (!C)
689 return nullptr;
690
691 // Extract signbits of the vector input and pack into integer result.
692 APInt Result(ResTy->getPrimitiveSizeInBits(), 0);
693 for (unsigned I = 0, E = ArgTy->getVectorNumElements(); I != E; ++I) {
694 auto *COp = C->getAggregateElement(I);
695 if (!COp)
696 return nullptr;
697 if (isa<UndefValue>(COp))
698 continue;
699
700 auto *CInt = dyn_cast<ConstantInt>(COp);
701 auto *CFp = dyn_cast<ConstantFP>(COp);
702 if (!CInt && !CFp)
703 return nullptr;
704
705 if ((CInt && CInt->isNegative()) || (CFp && CFp->isNegative()))
706 Result.setBit(I);
707 }
708
709 return Constant::getIntegerValue(ResTy, Result);
710}
711
Sanjay Patel6038d3e2016-01-29 23:27:03 +0000712static Value *simplifyX86insertps(const IntrinsicInst &II,
Sanjay Patelc86867c2015-04-16 17:52:13 +0000713 InstCombiner::BuilderTy &Builder) {
Sanjay Patel03c03f52016-01-28 00:03:16 +0000714 auto *CInt = dyn_cast<ConstantInt>(II.getArgOperand(2));
715 if (!CInt)
716 return nullptr;
Simon Pilgrim54fcd622015-07-25 20:41:00 +0000717
Sanjay Patel03c03f52016-01-28 00:03:16 +0000718 VectorType *VecTy = cast<VectorType>(II.getType());
719 assert(VecTy->getNumElements() == 4 && "insertps with wrong vector type");
Sanjay Patelc86867c2015-04-16 17:52:13 +0000720
Sanjay Patel03c03f52016-01-28 00:03:16 +0000721 // The immediate permute control byte looks like this:
722 // [3:0] - zero mask for each 32-bit lane
723 // [5:4] - select one 32-bit destination lane
724 // [7:6] - select one 32-bit source lane
Sanjay Patelc86867c2015-04-16 17:52:13 +0000725
Sanjay Patel03c03f52016-01-28 00:03:16 +0000726 uint8_t Imm = CInt->getZExtValue();
727 uint8_t ZMask = Imm & 0xf;
728 uint8_t DestLane = (Imm >> 4) & 0x3;
729 uint8_t SourceLane = (Imm >> 6) & 0x3;
Sanjay Patelc1d20a32015-04-25 20:55:25 +0000730
Sanjay Patel03c03f52016-01-28 00:03:16 +0000731 ConstantAggregateZero *ZeroVector = ConstantAggregateZero::get(VecTy);
Sanjay Patelc86867c2015-04-16 17:52:13 +0000732
Sanjay Patel03c03f52016-01-28 00:03:16 +0000733 // If all zero mask bits are set, this was just a weird way to
734 // generate a zero vector.
735 if (ZMask == 0xf)
736 return ZeroVector;
Sanjay Patelc1d20a32015-04-25 20:55:25 +0000737
Sanjay Patel03c03f52016-01-28 00:03:16 +0000738 // Initialize by passing all of the first source bits through.
Craig Topper99d1eab2016-06-12 00:41:19 +0000739 uint32_t ShuffleMask[4] = { 0, 1, 2, 3 };
Sanjay Patelc1d20a32015-04-25 20:55:25 +0000740
Sanjay Patel03c03f52016-01-28 00:03:16 +0000741 // We may replace the second operand with the zero vector.
742 Value *V1 = II.getArgOperand(1);
743
744 if (ZMask) {
745 // If the zero mask is being used with a single input or the zero mask
746 // overrides the destination lane, this is a shuffle with the zero vector.
747 if ((II.getArgOperand(0) == II.getArgOperand(1)) ||
748 (ZMask & (1 << DestLane))) {
749 V1 = ZeroVector;
750 // We may still move 32-bits of the first source vector from one lane
751 // to another.
752 ShuffleMask[DestLane] = SourceLane;
753 // The zero mask may override the previous insert operation.
754 for (unsigned i = 0; i < 4; ++i)
755 if ((ZMask >> i) & 0x1)
756 ShuffleMask[i] = i + 4;
Sanjay Patelc1d20a32015-04-25 20:55:25 +0000757 } else {
Sanjay Patel03c03f52016-01-28 00:03:16 +0000758 // TODO: Model this case as 2 shuffles or a 'logical and' plus shuffle?
759 return nullptr;
Sanjay Patelc1d20a32015-04-25 20:55:25 +0000760 }
Sanjay Patel03c03f52016-01-28 00:03:16 +0000761 } else {
762 // Replace the selected destination lane with the selected source lane.
763 ShuffleMask[DestLane] = SourceLane + 4;
Sanjay Patelc86867c2015-04-16 17:52:13 +0000764 }
Sanjay Patel03c03f52016-01-28 00:03:16 +0000765
766 return Builder.CreateShuffleVector(II.getArgOperand(0), V1, ShuffleMask);
Sanjay Patelc86867c2015-04-16 17:52:13 +0000767}
768
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000769/// Attempt to simplify SSE4A EXTRQ/EXTRQI instructions using constant folding
770/// or conversion to a shuffle vector.
Sanjay Patel6038d3e2016-01-29 23:27:03 +0000771static Value *simplifyX86extrq(IntrinsicInst &II, Value *Op0,
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000772 ConstantInt *CILength, ConstantInt *CIIndex,
773 InstCombiner::BuilderTy &Builder) {
774 auto LowConstantHighUndef = [&](uint64_t Val) {
775 Type *IntTy64 = Type::getInt64Ty(II.getContext());
776 Constant *Args[] = {ConstantInt::get(IntTy64, Val),
777 UndefValue::get(IntTy64)};
778 return ConstantVector::get(Args);
779 };
780
781 // See if we're dealing with constant values.
782 Constant *C0 = dyn_cast<Constant>(Op0);
783 ConstantInt *CI0 =
Andrea Di Biagio8df5b9c2016-09-07 12:03:03 +0000784 C0 ? dyn_cast_or_null<ConstantInt>(C0->getAggregateElement((unsigned)0))
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000785 : nullptr;
786
787 // Attempt to constant fold.
788 if (CILength && CIIndex) {
789 // From AMD documentation: "The bit index and field length are each six
790 // bits in length other bits of the field are ignored."
791 APInt APIndex = CIIndex->getValue().zextOrTrunc(6);
792 APInt APLength = CILength->getValue().zextOrTrunc(6);
793
794 unsigned Index = APIndex.getZExtValue();
795
796 // From AMD documentation: "a value of zero in the field length is
797 // defined as length of 64".
798 unsigned Length = APLength == 0 ? 64 : APLength.getZExtValue();
799
800 // From AMD documentation: "If the sum of the bit index + length field
801 // is greater than 64, the results are undefined".
802 unsigned End = Index + Length;
803
804 // Note that both field index and field length are 8-bit quantities.
805 // Since variables 'Index' and 'Length' are unsigned values
806 // obtained from zero-extending field index and field length
807 // respectively, their sum should never wrap around.
808 if (End > 64)
809 return UndefValue::get(II.getType());
810
811 // If we are inserting whole bytes, we can convert this to a shuffle.
812 // Lowering can recognize EXTRQI shuffle masks.
813 if ((Length % 8) == 0 && (Index % 8) == 0) {
814 // Convert bit indices to byte indices.
815 Length /= 8;
816 Index /= 8;
817
818 Type *IntTy8 = Type::getInt8Ty(II.getContext());
819 Type *IntTy32 = Type::getInt32Ty(II.getContext());
820 VectorType *ShufTy = VectorType::get(IntTy8, 16);
821
822 SmallVector<Constant *, 16> ShuffleMask;
823 for (int i = 0; i != (int)Length; ++i)
824 ShuffleMask.push_back(
825 Constant::getIntegerValue(IntTy32, APInt(32, i + Index)));
826 for (int i = Length; i != 8; ++i)
827 ShuffleMask.push_back(
828 Constant::getIntegerValue(IntTy32, APInt(32, i + 16)));
829 for (int i = 8; i != 16; ++i)
830 ShuffleMask.push_back(UndefValue::get(IntTy32));
831
832 Value *SV = Builder.CreateShuffleVector(
833 Builder.CreateBitCast(Op0, ShufTy),
834 ConstantAggregateZero::get(ShufTy), ConstantVector::get(ShuffleMask));
835 return Builder.CreateBitCast(SV, II.getType());
836 }
837
838 // Constant Fold - shift Index'th bit to lowest position and mask off
839 // Length bits.
840 if (CI0) {
841 APInt Elt = CI0->getValue();
842 Elt = Elt.lshr(Index).zextOrTrunc(Length);
843 return LowConstantHighUndef(Elt.getZExtValue());
844 }
845
846 // If we were an EXTRQ call, we'll save registers if we convert to EXTRQI.
847 if (II.getIntrinsicID() == Intrinsic::x86_sse4a_extrq) {
848 Value *Args[] = {Op0, CILength, CIIndex};
Sanjay Patelaf674fb2015-12-14 17:24:23 +0000849 Module *M = II.getModule();
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000850 Value *F = Intrinsic::getDeclaration(M, Intrinsic::x86_sse4a_extrqi);
851 return Builder.CreateCall(F, Args);
852 }
853 }
854
855 // Constant Fold - extraction from zero is always {zero, undef}.
856 if (CI0 && CI0->equalsInt(0))
857 return LowConstantHighUndef(0);
858
859 return nullptr;
860}
861
862/// Attempt to simplify SSE4A INSERTQ/INSERTQI instructions using constant
863/// folding or conversion to a shuffle vector.
Sanjay Patel6038d3e2016-01-29 23:27:03 +0000864static Value *simplifyX86insertq(IntrinsicInst &II, Value *Op0, Value *Op1,
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000865 APInt APLength, APInt APIndex,
866 InstCombiner::BuilderTy &Builder) {
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000867 // From AMD documentation: "The bit index and field length are each six bits
868 // in length other bits of the field are ignored."
869 APIndex = APIndex.zextOrTrunc(6);
870 APLength = APLength.zextOrTrunc(6);
871
872 // Attempt to constant fold.
873 unsigned Index = APIndex.getZExtValue();
874
875 // From AMD documentation: "a value of zero in the field length is
876 // defined as length of 64".
877 unsigned Length = APLength == 0 ? 64 : APLength.getZExtValue();
878
879 // From AMD documentation: "If the sum of the bit index + length field
880 // is greater than 64, the results are undefined".
881 unsigned End = Index + Length;
882
883 // Note that both field index and field length are 8-bit quantities.
884 // Since variables 'Index' and 'Length' are unsigned values
885 // obtained from zero-extending field index and field length
886 // respectively, their sum should never wrap around.
887 if (End > 64)
888 return UndefValue::get(II.getType());
889
890 // If we are inserting whole bytes, we can convert this to a shuffle.
891 // Lowering can recognize INSERTQI shuffle masks.
892 if ((Length % 8) == 0 && (Index % 8) == 0) {
893 // Convert bit indices to byte indices.
894 Length /= 8;
895 Index /= 8;
896
897 Type *IntTy8 = Type::getInt8Ty(II.getContext());
898 Type *IntTy32 = Type::getInt32Ty(II.getContext());
899 VectorType *ShufTy = VectorType::get(IntTy8, 16);
900
901 SmallVector<Constant *, 16> ShuffleMask;
902 for (int i = 0; i != (int)Index; ++i)
903 ShuffleMask.push_back(Constant::getIntegerValue(IntTy32, APInt(32, i)));
904 for (int i = 0; i != (int)Length; ++i)
905 ShuffleMask.push_back(
906 Constant::getIntegerValue(IntTy32, APInt(32, i + 16)));
907 for (int i = Index + Length; i != 8; ++i)
908 ShuffleMask.push_back(Constant::getIntegerValue(IntTy32, APInt(32, i)));
909 for (int i = 8; i != 16; ++i)
910 ShuffleMask.push_back(UndefValue::get(IntTy32));
911
912 Value *SV = Builder.CreateShuffleVector(Builder.CreateBitCast(Op0, ShufTy),
913 Builder.CreateBitCast(Op1, ShufTy),
914 ConstantVector::get(ShuffleMask));
915 return Builder.CreateBitCast(SV, II.getType());
916 }
917
918 // See if we're dealing with constant values.
919 Constant *C0 = dyn_cast<Constant>(Op0);
920 Constant *C1 = dyn_cast<Constant>(Op1);
921 ConstantInt *CI00 =
Andrea Di Biagiof3fd3162016-09-07 12:47:53 +0000922 C0 ? dyn_cast_or_null<ConstantInt>(C0->getAggregateElement((unsigned)0))
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000923 : nullptr;
924 ConstantInt *CI10 =
Andrea Di Biagiof3fd3162016-09-07 12:47:53 +0000925 C1 ? dyn_cast_or_null<ConstantInt>(C1->getAggregateElement((unsigned)0))
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000926 : nullptr;
927
928 // Constant Fold - insert bottom Length bits starting at the Index'th bit.
929 if (CI00 && CI10) {
930 APInt V00 = CI00->getValue();
931 APInt V10 = CI10->getValue();
932 APInt Mask = APInt::getLowBitsSet(64, Length).shl(Index);
933 V00 = V00 & ~Mask;
934 V10 = V10.zextOrTrunc(Length).zextOrTrunc(64).shl(Index);
935 APInt Val = V00 | V10;
936 Type *IntTy64 = Type::getInt64Ty(II.getContext());
937 Constant *Args[] = {ConstantInt::get(IntTy64, Val.getZExtValue()),
938 UndefValue::get(IntTy64)};
939 return ConstantVector::get(Args);
940 }
941
942 // If we were an INSERTQ call, we'll save demanded elements if we convert to
943 // INSERTQI.
944 if (II.getIntrinsicID() == Intrinsic::x86_sse4a_insertq) {
945 Type *IntTy8 = Type::getInt8Ty(II.getContext());
946 Constant *CILength = ConstantInt::get(IntTy8, Length, false);
947 Constant *CIIndex = ConstantInt::get(IntTy8, Index, false);
948
949 Value *Args[] = {Op0, Op1, CILength, CIIndex};
Sanjay Patelaf674fb2015-12-14 17:24:23 +0000950 Module *M = II.getModule();
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000951 Value *F = Intrinsic::getDeclaration(M, Intrinsic::x86_sse4a_insertqi);
952 return Builder.CreateCall(F, Args);
953 }
954
955 return nullptr;
956}
957
Simon Pilgrimc0c56e72016-04-24 17:00:34 +0000958/// Attempt to convert pshufb* to shufflevector if the mask is constant.
959static Value *simplifyX86pshufb(const IntrinsicInst &II,
960 InstCombiner::BuilderTy &Builder) {
Simon Pilgrimbf60cc42016-04-29 21:34:54 +0000961 Constant *V = dyn_cast<Constant>(II.getArgOperand(1));
962 if (!V)
963 return nullptr;
964
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +0000965 auto *VecTy = cast<VectorType>(II.getType());
966 auto *MaskEltTy = Type::getInt32Ty(II.getContext());
967 unsigned NumElts = VecTy->getNumElements();
Craig Topper9a63d7a2016-12-11 00:23:50 +0000968 assert((NumElts == 16 || NumElts == 32 || NumElts == 64) &&
Simon Pilgrimc0c56e72016-04-24 17:00:34 +0000969 "Unexpected number of elements in shuffle mask!");
Simon Pilgrimbf60cc42016-04-29 21:34:54 +0000970
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +0000971 // Construct a shuffle mask from constant integers or UNDEFs.
Craig Topper9a63d7a2016-12-11 00:23:50 +0000972 Constant *Indexes[64] = {nullptr};
Simon Pilgrimc0c56e72016-04-24 17:00:34 +0000973
Simon Pilgrimbf60cc42016-04-29 21:34:54 +0000974 // Each byte in the shuffle control mask forms an index to permute the
975 // corresponding byte in the destination operand.
976 for (unsigned I = 0; I < NumElts; ++I) {
977 Constant *COp = V->getAggregateElement(I);
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +0000978 if (!COp || (!isa<UndefValue>(COp) && !isa<ConstantInt>(COp)))
Simon Pilgrimbf60cc42016-04-29 21:34:54 +0000979 return nullptr;
Simon Pilgrimc0c56e72016-04-24 17:00:34 +0000980
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +0000981 if (isa<UndefValue>(COp)) {
982 Indexes[I] = UndefValue::get(MaskEltTy);
983 continue;
984 }
985
Simon Pilgrimbf60cc42016-04-29 21:34:54 +0000986 int8_t Index = cast<ConstantInt>(COp)->getValue().getZExtValue();
987
988 // If the most significant bit (bit[7]) of each byte of the shuffle
989 // control mask is set, then zero is written in the result byte.
990 // The zero vector is in the right-hand side of the resulting
991 // shufflevector.
992
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +0000993 // The value of each index for the high 128-bit lane is the least
994 // significant 4 bits of the respective shuffle control byte.
995 Index = ((Index < 0) ? NumElts : Index & 0x0F) + (I & 0xF0);
996 Indexes[I] = ConstantInt::get(MaskEltTy, Index);
Simon Pilgrimbf60cc42016-04-29 21:34:54 +0000997 }
Simon Pilgrimc0c56e72016-04-24 17:00:34 +0000998
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +0000999 auto ShuffleMask = ConstantVector::get(makeArrayRef(Indexes, NumElts));
Simon Pilgrimc0c56e72016-04-24 17:00:34 +00001000 auto V1 = II.getArgOperand(0);
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +00001001 auto V2 = Constant::getNullValue(VecTy);
Simon Pilgrimc0c56e72016-04-24 17:00:34 +00001002 return Builder.CreateShuffleVector(V1, V2, ShuffleMask);
1003}
1004
Simon Pilgrim2f6097d2016-04-24 17:23:46 +00001005/// Attempt to convert vpermilvar* to shufflevector if the mask is constant.
1006static Value *simplifyX86vpermilvar(const IntrinsicInst &II,
1007 InstCombiner::BuilderTy &Builder) {
Simon Pilgrim640f9962016-04-30 07:23:30 +00001008 Constant *V = dyn_cast<Constant>(II.getArgOperand(1));
1009 if (!V)
1010 return nullptr;
Simon Pilgrim2f6097d2016-04-24 17:23:46 +00001011
Craig Topper58917f32016-12-11 01:59:36 +00001012 auto *VecTy = cast<VectorType>(II.getType());
Simon Pilgrimeeacc402016-05-01 20:22:42 +00001013 auto *MaskEltTy = Type::getInt32Ty(II.getContext());
Craig Topper58917f32016-12-11 01:59:36 +00001014 unsigned NumElts = VecTy->getVectorNumElements();
1015 bool IsPD = VecTy->getScalarType()->isDoubleTy();
1016 unsigned NumLaneElts = IsPD ? 2 : 4;
1017 assert(NumElts == 16 || NumElts == 8 || NumElts == 4 || NumElts == 2);
Simon Pilgrim2f6097d2016-04-24 17:23:46 +00001018
Simon Pilgrimeeacc402016-05-01 20:22:42 +00001019 // Construct a shuffle mask from constant integers or UNDEFs.
Craig Topper58917f32016-12-11 01:59:36 +00001020 Constant *Indexes[16] = {nullptr};
Simon Pilgrim640f9962016-04-30 07:23:30 +00001021
1022 // The intrinsics only read one or two bits, clear the rest.
Simon Pilgrimeeacc402016-05-01 20:22:42 +00001023 for (unsigned I = 0; I < NumElts; ++I) {
Simon Pilgrim640f9962016-04-30 07:23:30 +00001024 Constant *COp = V->getAggregateElement(I);
Simon Pilgrimeeacc402016-05-01 20:22:42 +00001025 if (!COp || (!isa<UndefValue>(COp) && !isa<ConstantInt>(COp)))
Simon Pilgrim640f9962016-04-30 07:23:30 +00001026 return nullptr;
1027
Simon Pilgrimeeacc402016-05-01 20:22:42 +00001028 if (isa<UndefValue>(COp)) {
1029 Indexes[I] = UndefValue::get(MaskEltTy);
1030 continue;
1031 }
1032
1033 APInt Index = cast<ConstantInt>(COp)->getValue();
1034 Index = Index.zextOrTrunc(32).getLoBits(2);
Simon Pilgrim640f9962016-04-30 07:23:30 +00001035
1036 // The PD variants uses bit 1 to select per-lane element index, so
1037 // shift down to convert to generic shuffle mask index.
Craig Topper58917f32016-12-11 01:59:36 +00001038 if (IsPD)
Simon Pilgrimeeacc402016-05-01 20:22:42 +00001039 Index = Index.lshr(1);
1040
1041 // The _256 variants are a bit trickier since the mask bits always index
1042 // into the corresponding 128 half. In order to convert to a generic
1043 // shuffle, we have to make that explicit.
Craig Topper58917f32016-12-11 01:59:36 +00001044 Index += APInt(32, (I / NumLaneElts) * NumLaneElts);
Simon Pilgrimeeacc402016-05-01 20:22:42 +00001045
1046 Indexes[I] = ConstantInt::get(MaskEltTy, Index);
Simon Pilgrim2f6097d2016-04-24 17:23:46 +00001047 }
1048
Simon Pilgrimeeacc402016-05-01 20:22:42 +00001049 auto ShuffleMask = ConstantVector::get(makeArrayRef(Indexes, NumElts));
Simon Pilgrim2f6097d2016-04-24 17:23:46 +00001050 auto V1 = II.getArgOperand(0);
1051 auto V2 = UndefValue::get(V1->getType());
1052 return Builder.CreateShuffleVector(V1, V2, ShuffleMask);
1053}
1054
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +00001055/// Attempt to convert vpermd/vpermps to shufflevector if the mask is constant.
1056static Value *simplifyX86vpermv(const IntrinsicInst &II,
1057 InstCombiner::BuilderTy &Builder) {
1058 auto *V = dyn_cast<Constant>(II.getArgOperand(1));
1059 if (!V)
1060 return nullptr;
1061
Simon Pilgrimca140b12016-05-01 20:43:02 +00001062 auto *VecTy = cast<VectorType>(II.getType());
1063 auto *MaskEltTy = Type::getInt32Ty(II.getContext());
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +00001064 unsigned Size = VecTy->getNumElements();
Craig Toppere3280452016-12-25 23:58:57 +00001065 assert((Size == 4 || Size == 8 || Size == 16 || Size == 32 || Size == 64) &&
1066 "Unexpected shuffle mask size");
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +00001067
Simon Pilgrimca140b12016-05-01 20:43:02 +00001068 // Construct a shuffle mask from constant integers or UNDEFs.
Craig Toppere3280452016-12-25 23:58:57 +00001069 Constant *Indexes[64] = {nullptr};
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +00001070
1071 for (unsigned I = 0; I < Size; ++I) {
1072 Constant *COp = V->getAggregateElement(I);
Simon Pilgrimca140b12016-05-01 20:43:02 +00001073 if (!COp || (!isa<UndefValue>(COp) && !isa<ConstantInt>(COp)))
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +00001074 return nullptr;
1075
Simon Pilgrimca140b12016-05-01 20:43:02 +00001076 if (isa<UndefValue>(COp)) {
1077 Indexes[I] = UndefValue::get(MaskEltTy);
1078 continue;
1079 }
1080
Craig Toppere3280452016-12-25 23:58:57 +00001081 uint32_t Index = cast<ConstantInt>(COp)->getZExtValue();
1082 Index &= Size - 1;
Simon Pilgrimca140b12016-05-01 20:43:02 +00001083 Indexes[I] = ConstantInt::get(MaskEltTy, Index);
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +00001084 }
1085
Simon Pilgrimca140b12016-05-01 20:43:02 +00001086 auto ShuffleMask = ConstantVector::get(makeArrayRef(Indexes, Size));
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +00001087 auto V1 = II.getArgOperand(0);
1088 auto V2 = UndefValue::get(VecTy);
1089 return Builder.CreateShuffleVector(V1, V2, ShuffleMask);
1090}
1091
Sanjay Patelccf5f242015-03-20 21:47:56 +00001092/// The shuffle mask for a perm2*128 selects any two halves of two 256-bit
1093/// source vectors, unless a zero bit is set. If a zero bit is set,
1094/// then ignore that half of the mask and clear that half of the vector.
Sanjay Patel6038d3e2016-01-29 23:27:03 +00001095static Value *simplifyX86vperm2(const IntrinsicInst &II,
Sanjay Patelccf5f242015-03-20 21:47:56 +00001096 InstCombiner::BuilderTy &Builder) {
Sanjay Patel03c03f52016-01-28 00:03:16 +00001097 auto *CInt = dyn_cast<ConstantInt>(II.getArgOperand(2));
1098 if (!CInt)
1099 return nullptr;
Sanjay Patelccf5f242015-03-20 21:47:56 +00001100
Sanjay Patel03c03f52016-01-28 00:03:16 +00001101 VectorType *VecTy = cast<VectorType>(II.getType());
1102 ConstantAggregateZero *ZeroVector = ConstantAggregateZero::get(VecTy);
Sanjay Patel43a87fd2015-03-24 20:36:42 +00001103
Sanjay Patel03c03f52016-01-28 00:03:16 +00001104 // The immediate permute control byte looks like this:
1105 // [1:0] - select 128 bits from sources for low half of destination
1106 // [2] - ignore
1107 // [3] - zero low half of destination
1108 // [5:4] - select 128 bits from sources for high half of destination
1109 // [6] - ignore
1110 // [7] - zero high half of destination
Sanjay Patel43a87fd2015-03-24 20:36:42 +00001111
Sanjay Patel03c03f52016-01-28 00:03:16 +00001112 uint8_t Imm = CInt->getZExtValue();
Sanjay Patel43a87fd2015-03-24 20:36:42 +00001113
Sanjay Patel03c03f52016-01-28 00:03:16 +00001114 bool LowHalfZero = Imm & 0x08;
1115 bool HighHalfZero = Imm & 0x80;
Sanjay Patel43a87fd2015-03-24 20:36:42 +00001116
Sanjay Patel03c03f52016-01-28 00:03:16 +00001117 // If both zero mask bits are set, this was just a weird way to
1118 // generate a zero vector.
1119 if (LowHalfZero && HighHalfZero)
1120 return ZeroVector;
Sanjay Patel43a87fd2015-03-24 20:36:42 +00001121
Sanjay Patel03c03f52016-01-28 00:03:16 +00001122 // If 0 or 1 zero mask bits are set, this is a simple shuffle.
1123 unsigned NumElts = VecTy->getNumElements();
1124 unsigned HalfSize = NumElts / 2;
Craig Topper99d1eab2016-06-12 00:41:19 +00001125 SmallVector<uint32_t, 8> ShuffleMask(NumElts);
Simon Pilgrim54fcd622015-07-25 20:41:00 +00001126
Sanjay Patel03c03f52016-01-28 00:03:16 +00001127 // The high bit of the selection field chooses the 1st or 2nd operand.
1128 bool LowInputSelect = Imm & 0x02;
1129 bool HighInputSelect = Imm & 0x20;
Sanjay Patelccf5f242015-03-20 21:47:56 +00001130
Sanjay Patel03c03f52016-01-28 00:03:16 +00001131 // The low bit of the selection field chooses the low or high half
1132 // of the selected operand.
1133 bool LowHalfSelect = Imm & 0x01;
1134 bool HighHalfSelect = Imm & 0x10;
Simon Pilgrim54fcd622015-07-25 20:41:00 +00001135
Sanjay Patel03c03f52016-01-28 00:03:16 +00001136 // Determine which operand(s) are actually in use for this instruction.
1137 Value *V0 = LowInputSelect ? II.getArgOperand(1) : II.getArgOperand(0);
1138 Value *V1 = HighInputSelect ? II.getArgOperand(1) : II.getArgOperand(0);
Simon Pilgrim54fcd622015-07-25 20:41:00 +00001139
Sanjay Patel03c03f52016-01-28 00:03:16 +00001140 // If needed, replace operands based on zero mask.
1141 V0 = LowHalfZero ? ZeroVector : V0;
1142 V1 = HighHalfZero ? ZeroVector : V1;
Sanjay Patelccf5f242015-03-20 21:47:56 +00001143
Sanjay Patel03c03f52016-01-28 00:03:16 +00001144 // Permute low half of result.
1145 unsigned StartIndex = LowHalfSelect ? HalfSize : 0;
1146 for (unsigned i = 0; i < HalfSize; ++i)
1147 ShuffleMask[i] = StartIndex + i;
Sanjay Patel43a87fd2015-03-24 20:36:42 +00001148
Sanjay Patel03c03f52016-01-28 00:03:16 +00001149 // Permute high half of result.
1150 StartIndex = HighHalfSelect ? HalfSize : 0;
1151 StartIndex += NumElts;
1152 for (unsigned i = 0; i < HalfSize; ++i)
1153 ShuffleMask[i + HalfSize] = StartIndex + i;
1154
1155 return Builder.CreateShuffleVector(V0, V1, ShuffleMask);
Sanjay Patelccf5f242015-03-20 21:47:56 +00001156}
1157
Simon Pilgrim1d1c56e22015-10-11 14:38:34 +00001158/// Decode XOP integer vector comparison intrinsics.
Sanjay Patel6038d3e2016-01-29 23:27:03 +00001159static Value *simplifyX86vpcom(const IntrinsicInst &II,
Sanjay Patelf9f5d3c2016-01-29 23:14:58 +00001160 InstCombiner::BuilderTy &Builder,
1161 bool IsSigned) {
Simon Pilgrim1d1c56e22015-10-11 14:38:34 +00001162 if (auto *CInt = dyn_cast<ConstantInt>(II.getArgOperand(2))) {
1163 uint64_t Imm = CInt->getZExtValue() & 0x7;
1164 VectorType *VecTy = cast<VectorType>(II.getType());
1165 CmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
1166
1167 switch (Imm) {
1168 case 0x0:
1169 Pred = IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1170 break;
1171 case 0x1:
1172 Pred = IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
1173 break;
1174 case 0x2:
1175 Pred = IsSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1176 break;
1177 case 0x3:
1178 Pred = IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
1179 break;
1180 case 0x4:
1181 Pred = ICmpInst::ICMP_EQ; break;
1182 case 0x5:
1183 Pred = ICmpInst::ICMP_NE; break;
1184 case 0x6:
1185 return ConstantInt::getSigned(VecTy, 0); // FALSE
1186 case 0x7:
1187 return ConstantInt::getSigned(VecTy, -1); // TRUE
1188 }
1189
Sanjay Patelf9f5d3c2016-01-29 23:14:58 +00001190 if (Value *Cmp = Builder.CreateICmp(Pred, II.getArgOperand(0),
1191 II.getArgOperand(1)))
Simon Pilgrim1d1c56e22015-10-11 14:38:34 +00001192 return Builder.CreateSExtOrTrunc(Cmp, VecTy);
1193 }
1194 return nullptr;
1195}
1196
Craig Toppere3280452016-12-25 23:58:57 +00001197// Emit a select instruction and appropriate bitcasts to help simplify
1198// masked intrinsics.
1199static Value *emitX86MaskSelect(Value *Mask, Value *Op0, Value *Op1,
1200 InstCombiner::BuilderTy &Builder) {
Craig Topper99163632016-12-30 23:06:28 +00001201 unsigned VWidth = Op0->getType()->getVectorNumElements();
1202
1203 // If the mask is all ones we don't need the select. But we need to check
1204 // only the bit thats will be used in case VWidth is less than 8.
1205 if (auto *C = dyn_cast<ConstantInt>(Mask))
1206 if (C->getValue().zextOrTrunc(VWidth).isAllOnesValue())
1207 return Op0;
1208
Craig Toppere3280452016-12-25 23:58:57 +00001209 auto *MaskTy = VectorType::get(Builder.getInt1Ty(),
1210 cast<IntegerType>(Mask->getType())->getBitWidth());
1211 Mask = Builder.CreateBitCast(Mask, MaskTy);
1212
1213 // If we have less than 8 elements, then the starting mask was an i8 and
1214 // we need to extract down to the right number of elements.
Craig Toppere3280452016-12-25 23:58:57 +00001215 if (VWidth < 8) {
1216 uint32_t Indices[4];
1217 for (unsigned i = 0; i != VWidth; ++i)
1218 Indices[i] = i;
1219 Mask = Builder.CreateShuffleVector(Mask, Mask,
1220 makeArrayRef(Indices, VWidth),
1221 "extract");
1222 }
1223
1224 return Builder.CreateSelect(Mask, Op0, Op1);
1225}
1226
Sanjay Patel0069f562016-01-31 16:35:23 +00001227static Value *simplifyMinnumMaxnum(const IntrinsicInst &II) {
1228 Value *Arg0 = II.getArgOperand(0);
1229 Value *Arg1 = II.getArgOperand(1);
1230
1231 // fmin(x, x) -> x
1232 if (Arg0 == Arg1)
1233 return Arg0;
1234
1235 const auto *C1 = dyn_cast<ConstantFP>(Arg1);
1236
1237 // fmin(x, nan) -> x
1238 if (C1 && C1->isNaN())
1239 return Arg0;
1240
1241 // This is the value because if undef were NaN, we would return the other
1242 // value and cannot return a NaN unless both operands are.
1243 //
1244 // fmin(undef, x) -> x
1245 if (isa<UndefValue>(Arg0))
1246 return Arg1;
1247
1248 // fmin(x, undef) -> x
1249 if (isa<UndefValue>(Arg1))
1250 return Arg0;
1251
1252 Value *X = nullptr;
1253 Value *Y = nullptr;
1254 if (II.getIntrinsicID() == Intrinsic::minnum) {
1255 // fmin(x, fmin(x, y)) -> fmin(x, y)
1256 // fmin(y, fmin(x, y)) -> fmin(x, y)
1257 if (match(Arg1, m_FMin(m_Value(X), m_Value(Y)))) {
1258 if (Arg0 == X || Arg0 == Y)
1259 return Arg1;
1260 }
1261
1262 // fmin(fmin(x, y), x) -> fmin(x, y)
1263 // fmin(fmin(x, y), y) -> fmin(x, y)
1264 if (match(Arg0, m_FMin(m_Value(X), m_Value(Y)))) {
1265 if (Arg1 == X || Arg1 == Y)
1266 return Arg0;
1267 }
1268
1269 // TODO: fmin(nnan x, inf) -> x
1270 // TODO: fmin(nnan ninf x, flt_max) -> x
1271 if (C1 && C1->isInfinity()) {
1272 // fmin(x, -inf) -> -inf
1273 if (C1->isNegative())
1274 return Arg1;
1275 }
1276 } else {
1277 assert(II.getIntrinsicID() == Intrinsic::maxnum);
1278 // fmax(x, fmax(x, y)) -> fmax(x, y)
1279 // fmax(y, fmax(x, y)) -> fmax(x, y)
1280 if (match(Arg1, m_FMax(m_Value(X), m_Value(Y)))) {
1281 if (Arg0 == X || Arg0 == Y)
1282 return Arg1;
1283 }
1284
1285 // fmax(fmax(x, y), x) -> fmax(x, y)
1286 // fmax(fmax(x, y), y) -> fmax(x, y)
1287 if (match(Arg0, m_FMax(m_Value(X), m_Value(Y)))) {
1288 if (Arg1 == X || Arg1 == Y)
1289 return Arg0;
1290 }
1291
1292 // TODO: fmax(nnan x, -inf) -> x
1293 // TODO: fmax(nnan ninf x, -flt_max) -> x
1294 if (C1 && C1->isInfinity()) {
1295 // fmax(x, inf) -> inf
1296 if (!C1->isNegative())
1297 return Arg1;
1298 }
1299 }
1300 return nullptr;
1301}
1302
David Majnemer666aa942016-07-14 06:58:42 +00001303static bool maskIsAllOneOrUndef(Value *Mask) {
1304 auto *ConstMask = dyn_cast<Constant>(Mask);
1305 if (!ConstMask)
1306 return false;
1307 if (ConstMask->isAllOnesValue() || isa<UndefValue>(ConstMask))
1308 return true;
1309 for (unsigned I = 0, E = ConstMask->getType()->getVectorNumElements(); I != E;
1310 ++I) {
1311 if (auto *MaskElt = ConstMask->getAggregateElement(I))
1312 if (MaskElt->isAllOnesValue() || isa<UndefValue>(MaskElt))
1313 continue;
1314 return false;
1315 }
1316 return true;
1317}
1318
Sanjay Patelb695c552016-02-01 17:00:10 +00001319static Value *simplifyMaskedLoad(const IntrinsicInst &II,
1320 InstCombiner::BuilderTy &Builder) {
David Majnemer666aa942016-07-14 06:58:42 +00001321 // If the mask is all ones or undefs, this is a plain vector load of the 1st
1322 // argument.
1323 if (maskIsAllOneOrUndef(II.getArgOperand(2))) {
Sanjay Patelb695c552016-02-01 17:00:10 +00001324 Value *LoadPtr = II.getArgOperand(0);
1325 unsigned Alignment = cast<ConstantInt>(II.getArgOperand(1))->getZExtValue();
1326 return Builder.CreateAlignedLoad(LoadPtr, Alignment, "unmaskedload");
1327 }
1328
1329 return nullptr;
1330}
1331
Sanjay Patel04f792b2016-02-01 19:39:52 +00001332static Instruction *simplifyMaskedStore(IntrinsicInst &II, InstCombiner &IC) {
1333 auto *ConstMask = dyn_cast<Constant>(II.getArgOperand(3));
1334 if (!ConstMask)
1335 return nullptr;
1336
1337 // If the mask is all zeros, this instruction does nothing.
1338 if (ConstMask->isNullValue())
Sanjay Patel4b198802016-02-01 22:23:39 +00001339 return IC.eraseInstFromFunction(II);
Sanjay Patel04f792b2016-02-01 19:39:52 +00001340
1341 // If the mask is all ones, this is a plain vector store of the 1st argument.
1342 if (ConstMask->isAllOnesValue()) {
1343 Value *StorePtr = II.getArgOperand(1);
1344 unsigned Alignment = cast<ConstantInt>(II.getArgOperand(2))->getZExtValue();
1345 return new StoreInst(II.getArgOperand(0), StorePtr, false, Alignment);
1346 }
1347
1348 return nullptr;
1349}
1350
Sanjay Patel103ab7d2016-02-01 22:10:26 +00001351static Instruction *simplifyMaskedGather(IntrinsicInst &II, InstCombiner &IC) {
1352 // If the mask is all zeros, return the "passthru" argument of the gather.
1353 auto *ConstMask = dyn_cast<Constant>(II.getArgOperand(2));
1354 if (ConstMask && ConstMask->isNullValue())
Sanjay Patel4b198802016-02-01 22:23:39 +00001355 return IC.replaceInstUsesWith(II, II.getArgOperand(3));
Sanjay Patel103ab7d2016-02-01 22:10:26 +00001356
1357 return nullptr;
1358}
1359
1360static Instruction *simplifyMaskedScatter(IntrinsicInst &II, InstCombiner &IC) {
1361 // If the mask is all zeros, a scatter does nothing.
1362 auto *ConstMask = dyn_cast<Constant>(II.getArgOperand(3));
1363 if (ConstMask && ConstMask->isNullValue())
Sanjay Patel4b198802016-02-01 22:23:39 +00001364 return IC.eraseInstFromFunction(II);
Sanjay Patel103ab7d2016-02-01 22:10:26 +00001365
1366 return nullptr;
1367}
1368
Amaury Sechet763c59d2016-08-18 20:43:50 +00001369static Instruction *foldCttzCtlz(IntrinsicInst &II, InstCombiner &IC) {
1370 assert((II.getIntrinsicID() == Intrinsic::cttz ||
1371 II.getIntrinsicID() == Intrinsic::ctlz) &&
1372 "Expected cttz or ctlz intrinsic");
Sanjay Patel8e3ab172016-08-05 22:42:46 +00001373 Value *Op0 = II.getArgOperand(0);
1374 // FIXME: Try to simplify vectors of integers.
1375 auto *IT = dyn_cast<IntegerType>(Op0->getType());
1376 if (!IT)
1377 return nullptr;
1378
1379 unsigned BitWidth = IT->getBitWidth();
1380 APInt KnownZero(BitWidth, 0);
1381 APInt KnownOne(BitWidth, 0);
1382 IC.computeKnownBits(Op0, KnownZero, KnownOne, 0, &II);
1383
1384 // Create a mask for bits above (ctlz) or below (cttz) the first known one.
1385 bool IsTZ = II.getIntrinsicID() == Intrinsic::cttz;
1386 unsigned NumMaskBits = IsTZ ? KnownOne.countTrailingZeros()
1387 : KnownOne.countLeadingZeros();
1388 APInt Mask = IsTZ ? APInt::getLowBitsSet(BitWidth, NumMaskBits)
1389 : APInt::getHighBitsSet(BitWidth, NumMaskBits);
1390
1391 // If all bits above (ctlz) or below (cttz) the first known one are known
1392 // zero, this value is constant.
1393 // FIXME: This should be in InstSimplify because we're replacing an
1394 // instruction with a constant.
Amaury Sechet763c59d2016-08-18 20:43:50 +00001395 if ((Mask & KnownZero) == Mask) {
1396 auto *C = ConstantInt::get(IT, APInt(BitWidth, NumMaskBits));
1397 return IC.replaceInstUsesWith(II, C);
1398 }
1399
1400 // If the input to cttz/ctlz is known to be non-zero,
1401 // then change the 'ZeroIsUndef' parameter to 'true'
1402 // because we know the zero behavior can't affect the result.
1403 if (KnownOne != 0 || isKnownNonZero(Op0, IC.getDataLayout())) {
1404 if (!match(II.getArgOperand(1), m_One())) {
1405 II.setOperand(1, IC.Builder->getTrue());
1406 return &II;
1407 }
1408 }
Sanjay Patel8e3ab172016-08-05 22:42:46 +00001409
1410 return nullptr;
1411}
1412
Sanjay Patel1ace9932016-02-26 21:04:14 +00001413// TODO: If the x86 backend knew how to convert a bool vector mask back to an
1414// XMM register mask efficiently, we could transform all x86 masked intrinsics
1415// to LLVM masked intrinsics and remove the x86 masked intrinsic defs.
Sanjay Patel98a71502016-02-29 23:16:48 +00001416static Instruction *simplifyX86MaskedLoad(IntrinsicInst &II, InstCombiner &IC) {
1417 Value *Ptr = II.getOperand(0);
1418 Value *Mask = II.getOperand(1);
Sanjay Patel5e5056d2016-04-12 23:16:23 +00001419 Constant *ZeroVec = Constant::getNullValue(II.getType());
Sanjay Patel98a71502016-02-29 23:16:48 +00001420
1421 // Special case a zero mask since that's not a ConstantDataVector.
Sanjay Patel5e5056d2016-04-12 23:16:23 +00001422 // This masked load instruction creates a zero vector.
Sanjay Patel98a71502016-02-29 23:16:48 +00001423 if (isa<ConstantAggregateZero>(Mask))
Sanjay Patel5e5056d2016-04-12 23:16:23 +00001424 return IC.replaceInstUsesWith(II, ZeroVec);
Sanjay Patel98a71502016-02-29 23:16:48 +00001425
1426 auto *ConstMask = dyn_cast<ConstantDataVector>(Mask);
1427 if (!ConstMask)
1428 return nullptr;
1429
1430 // The mask is constant. Convert this x86 intrinsic to the LLVM instrinsic
1431 // to allow target-independent optimizations.
1432
1433 // First, cast the x86 intrinsic scalar pointer to a vector pointer to match
1434 // the LLVM intrinsic definition for the pointer argument.
1435 unsigned AddrSpace = cast<PointerType>(Ptr->getType())->getAddressSpace();
1436 PointerType *VecPtrTy = PointerType::get(II.getType(), AddrSpace);
1437 Value *PtrCast = IC.Builder->CreateBitCast(Ptr, VecPtrTy, "castvec");
1438
1439 // Second, convert the x86 XMM integer vector mask to a vector of bools based
1440 // on each element's most significant bit (the sign bit).
1441 Constant *BoolMask = getNegativeIsTrueBoolVec(ConstMask);
1442
Sanjay Patel5e5056d2016-04-12 23:16:23 +00001443 // The pass-through vector for an x86 masked load is a zero vector.
1444 CallInst *NewMaskedLoad =
1445 IC.Builder->CreateMaskedLoad(PtrCast, 1, BoolMask, ZeroVec);
Sanjay Patel98a71502016-02-29 23:16:48 +00001446 return IC.replaceInstUsesWith(II, NewMaskedLoad);
1447}
1448
1449// TODO: If the x86 backend knew how to convert a bool vector mask back to an
1450// XMM register mask efficiently, we could transform all x86 masked intrinsics
1451// to LLVM masked intrinsics and remove the x86 masked intrinsic defs.
Sanjay Patel1ace9932016-02-26 21:04:14 +00001452static bool simplifyX86MaskedStore(IntrinsicInst &II, InstCombiner &IC) {
1453 Value *Ptr = II.getOperand(0);
1454 Value *Mask = II.getOperand(1);
1455 Value *Vec = II.getOperand(2);
1456
1457 // Special case a zero mask since that's not a ConstantDataVector:
1458 // this masked store instruction does nothing.
1459 if (isa<ConstantAggregateZero>(Mask)) {
1460 IC.eraseInstFromFunction(II);
1461 return true;
1462 }
1463
Sanjay Patelc4acbae2016-03-12 15:16:59 +00001464 // The SSE2 version is too weird (eg, unaligned but non-temporal) to do
1465 // anything else at this level.
1466 if (II.getIntrinsicID() == Intrinsic::x86_sse2_maskmov_dqu)
1467 return false;
1468
Sanjay Patel1ace9932016-02-26 21:04:14 +00001469 auto *ConstMask = dyn_cast<ConstantDataVector>(Mask);
1470 if (!ConstMask)
1471 return false;
1472
1473 // The mask is constant. Convert this x86 intrinsic to the LLVM instrinsic
1474 // to allow target-independent optimizations.
1475
1476 // First, cast the x86 intrinsic scalar pointer to a vector pointer to match
1477 // the LLVM intrinsic definition for the pointer argument.
1478 unsigned AddrSpace = cast<PointerType>(Ptr->getType())->getAddressSpace();
1479 PointerType *VecPtrTy = PointerType::get(Vec->getType(), AddrSpace);
Sanjay Patel1ace9932016-02-26 21:04:14 +00001480 Value *PtrCast = IC.Builder->CreateBitCast(Ptr, VecPtrTy, "castvec");
1481
1482 // Second, convert the x86 XMM integer vector mask to a vector of bools based
1483 // on each element's most significant bit (the sign bit).
1484 Constant *BoolMask = getNegativeIsTrueBoolVec(ConstMask);
1485
1486 IC.Builder->CreateMaskedStore(Vec, PtrCast, 1, BoolMask);
1487
1488 // 'Replace uses' doesn't work for stores. Erase the original masked store.
1489 IC.eraseInstFromFunction(II);
1490 return true;
1491}
1492
Matt Arsenaultcdb468c2017-02-27 23:08:49 +00001493// Constant fold llvm.amdgcn.fmed3 intrinsics for standard inputs.
1494//
1495// A single NaN input is folded to minnum, so we rely on that folding for
1496// handling NaNs.
1497static APFloat fmed3AMDGCN(const APFloat &Src0, const APFloat &Src1,
1498 const APFloat &Src2) {
1499 APFloat Max3 = maxnum(maxnum(Src0, Src1), Src2);
1500
1501 APFloat::cmpResult Cmp0 = Max3.compare(Src0);
1502 assert(Cmp0 != APFloat::cmpUnordered && "nans handled separately");
1503 if (Cmp0 == APFloat::cmpEqual)
1504 return maxnum(Src1, Src2);
1505
1506 APFloat::cmpResult Cmp1 = Max3.compare(Src1);
1507 assert(Cmp1 != APFloat::cmpUnordered && "nans handled separately");
1508 if (Cmp1 == APFloat::cmpEqual)
1509 return maxnum(Src0, Src2);
1510
1511 return maxnum(Src0, Src1);
1512}
1513
Arnaud A. de Grandmaison333ef382016-05-10 09:24:49 +00001514// Returns true iff the 2 intrinsics have the same operands, limiting the
1515// comparison to the first NumOperands.
1516static bool haveSameOperands(const IntrinsicInst &I, const IntrinsicInst &E,
1517 unsigned NumOperands) {
1518 assert(I.getNumArgOperands() >= NumOperands && "Not enough operands");
1519 assert(E.getNumArgOperands() >= NumOperands && "Not enough operands");
1520 for (unsigned i = 0; i < NumOperands; i++)
1521 if (I.getArgOperand(i) != E.getArgOperand(i))
1522 return false;
1523 return true;
1524}
1525
1526// Remove trivially empty start/end intrinsic ranges, i.e. a start
1527// immediately followed by an end (ignoring debuginfo or other
1528// start/end intrinsics in between). As this handles only the most trivial
1529// cases, tracking the nesting level is not needed:
1530//
1531// call @llvm.foo.start(i1 0) ; &I
1532// call @llvm.foo.start(i1 0)
1533// call @llvm.foo.end(i1 0) ; This one will not be skipped: it will be removed
1534// call @llvm.foo.end(i1 0)
1535static bool removeTriviallyEmptyRange(IntrinsicInst &I, unsigned StartID,
1536 unsigned EndID, InstCombiner &IC) {
1537 assert(I.getIntrinsicID() == StartID &&
1538 "Start intrinsic does not have expected ID");
1539 BasicBlock::iterator BI(I), BE(I.getParent()->end());
1540 for (++BI; BI != BE; ++BI) {
1541 if (auto *E = dyn_cast<IntrinsicInst>(BI)) {
1542 if (isa<DbgInfoIntrinsic>(E) || E->getIntrinsicID() == StartID)
1543 continue;
1544 if (E->getIntrinsicID() == EndID &&
1545 haveSameOperands(I, *E, E->getNumArgOperands())) {
1546 IC.eraseInstFromFunction(*E);
1547 IC.eraseInstFromFunction(I);
1548 return true;
1549 }
1550 }
1551 break;
1552 }
1553
1554 return false;
1555}
1556
Justin Lebar698c31b2017-01-27 00:58:58 +00001557// Convert NVVM intrinsics to target-generic LLVM code where possible.
1558static Instruction *SimplifyNVVMIntrinsic(IntrinsicInst *II, InstCombiner &IC) {
1559 // Each NVVM intrinsic we can simplify can be replaced with one of:
1560 //
1561 // * an LLVM intrinsic,
1562 // * an LLVM cast operation,
1563 // * an LLVM binary operation, or
1564 // * ad-hoc LLVM IR for the particular operation.
1565
1566 // Some transformations are only valid when the module's
1567 // flush-denormals-to-zero (ftz) setting is true/false, whereas other
1568 // transformations are valid regardless of the module's ftz setting.
1569 enum FtzRequirementTy {
1570 FTZ_Any, // Any ftz setting is ok.
1571 FTZ_MustBeOn, // Transformation is valid only if ftz is on.
1572 FTZ_MustBeOff, // Transformation is valid only if ftz is off.
1573 };
1574 // Classes of NVVM intrinsics that can't be replaced one-to-one with a
1575 // target-generic intrinsic, cast op, or binary op but that we can nonetheless
1576 // simplify.
1577 enum SpecialCase {
1578 SPC_Reciprocal,
1579 };
1580
1581 // SimplifyAction is a poor-man's variant (plus an additional flag) that
1582 // represents how to replace an NVVM intrinsic with target-generic LLVM IR.
1583 struct SimplifyAction {
1584 // Invariant: At most one of these Optionals has a value.
1585 Optional<Intrinsic::ID> IID;
1586 Optional<Instruction::CastOps> CastOp;
1587 Optional<Instruction::BinaryOps> BinaryOp;
1588 Optional<SpecialCase> Special;
1589
1590 FtzRequirementTy FtzRequirement = FTZ_Any;
1591
1592 SimplifyAction() = default;
1593
1594 SimplifyAction(Intrinsic::ID IID, FtzRequirementTy FtzReq)
1595 : IID(IID), FtzRequirement(FtzReq) {}
1596
1597 // Cast operations don't have anything to do with FTZ, so we skip that
1598 // argument.
1599 SimplifyAction(Instruction::CastOps CastOp) : CastOp(CastOp) {}
1600
1601 SimplifyAction(Instruction::BinaryOps BinaryOp, FtzRequirementTy FtzReq)
1602 : BinaryOp(BinaryOp), FtzRequirement(FtzReq) {}
1603
1604 SimplifyAction(SpecialCase Special, FtzRequirementTy FtzReq)
1605 : Special(Special), FtzRequirement(FtzReq) {}
1606 };
1607
1608 // Try to generate a SimplifyAction describing how to replace our
1609 // IntrinsicInstr with target-generic LLVM IR.
1610 const SimplifyAction Action = [II]() -> SimplifyAction {
1611 switch (II->getIntrinsicID()) {
1612
1613 // NVVM intrinsics that map directly to LLVM intrinsics.
1614 case Intrinsic::nvvm_ceil_d:
1615 return {Intrinsic::ceil, FTZ_Any};
1616 case Intrinsic::nvvm_ceil_f:
1617 return {Intrinsic::ceil, FTZ_MustBeOff};
1618 case Intrinsic::nvvm_ceil_ftz_f:
1619 return {Intrinsic::ceil, FTZ_MustBeOn};
1620 case Intrinsic::nvvm_fabs_d:
1621 return {Intrinsic::fabs, FTZ_Any};
1622 case Intrinsic::nvvm_fabs_f:
1623 return {Intrinsic::fabs, FTZ_MustBeOff};
1624 case Intrinsic::nvvm_fabs_ftz_f:
1625 return {Intrinsic::fabs, FTZ_MustBeOn};
1626 case Intrinsic::nvvm_floor_d:
1627 return {Intrinsic::floor, FTZ_Any};
1628 case Intrinsic::nvvm_floor_f:
1629 return {Intrinsic::floor, FTZ_MustBeOff};
1630 case Intrinsic::nvvm_floor_ftz_f:
1631 return {Intrinsic::floor, FTZ_MustBeOn};
1632 case Intrinsic::nvvm_fma_rn_d:
1633 return {Intrinsic::fma, FTZ_Any};
1634 case Intrinsic::nvvm_fma_rn_f:
1635 return {Intrinsic::fma, FTZ_MustBeOff};
1636 case Intrinsic::nvvm_fma_rn_ftz_f:
1637 return {Intrinsic::fma, FTZ_MustBeOn};
1638 case Intrinsic::nvvm_fmax_d:
1639 return {Intrinsic::maxnum, FTZ_Any};
1640 case Intrinsic::nvvm_fmax_f:
1641 return {Intrinsic::maxnum, FTZ_MustBeOff};
1642 case Intrinsic::nvvm_fmax_ftz_f:
1643 return {Intrinsic::maxnum, FTZ_MustBeOn};
1644 case Intrinsic::nvvm_fmin_d:
1645 return {Intrinsic::minnum, FTZ_Any};
1646 case Intrinsic::nvvm_fmin_f:
1647 return {Intrinsic::minnum, FTZ_MustBeOff};
1648 case Intrinsic::nvvm_fmin_ftz_f:
1649 return {Intrinsic::minnum, FTZ_MustBeOn};
1650 case Intrinsic::nvvm_round_d:
1651 return {Intrinsic::round, FTZ_Any};
1652 case Intrinsic::nvvm_round_f:
1653 return {Intrinsic::round, FTZ_MustBeOff};
1654 case Intrinsic::nvvm_round_ftz_f:
1655 return {Intrinsic::round, FTZ_MustBeOn};
1656 case Intrinsic::nvvm_sqrt_rn_d:
1657 return {Intrinsic::sqrt, FTZ_Any};
1658 case Intrinsic::nvvm_sqrt_f:
1659 // nvvm_sqrt_f is a special case. For most intrinsics, foo_ftz_f is the
1660 // ftz version, and foo_f is the non-ftz version. But nvvm_sqrt_f adopts
1661 // the ftz-ness of the surrounding code. sqrt_rn_f and sqrt_rn_ftz_f are
1662 // the versions with explicit ftz-ness.
1663 return {Intrinsic::sqrt, FTZ_Any};
1664 case Intrinsic::nvvm_sqrt_rn_f:
1665 return {Intrinsic::sqrt, FTZ_MustBeOff};
1666 case Intrinsic::nvvm_sqrt_rn_ftz_f:
1667 return {Intrinsic::sqrt, FTZ_MustBeOn};
1668 case Intrinsic::nvvm_trunc_d:
1669 return {Intrinsic::trunc, FTZ_Any};
1670 case Intrinsic::nvvm_trunc_f:
1671 return {Intrinsic::trunc, FTZ_MustBeOff};
1672 case Intrinsic::nvvm_trunc_ftz_f:
1673 return {Intrinsic::trunc, FTZ_MustBeOn};
1674
1675 // NVVM intrinsics that map to LLVM cast operations.
1676 //
1677 // Note that llvm's target-generic conversion operators correspond to the rz
1678 // (round to zero) versions of the nvvm conversion intrinsics, even though
1679 // most everything else here uses the rn (round to nearest even) nvvm ops.
1680 case Intrinsic::nvvm_d2i_rz:
1681 case Intrinsic::nvvm_f2i_rz:
1682 case Intrinsic::nvvm_d2ll_rz:
1683 case Intrinsic::nvvm_f2ll_rz:
1684 return {Instruction::FPToSI};
1685 case Intrinsic::nvvm_d2ui_rz:
1686 case Intrinsic::nvvm_f2ui_rz:
1687 case Intrinsic::nvvm_d2ull_rz:
1688 case Intrinsic::nvvm_f2ull_rz:
1689 return {Instruction::FPToUI};
1690 case Intrinsic::nvvm_i2d_rz:
1691 case Intrinsic::nvvm_i2f_rz:
1692 case Intrinsic::nvvm_ll2d_rz:
1693 case Intrinsic::nvvm_ll2f_rz:
1694 return {Instruction::SIToFP};
1695 case Intrinsic::nvvm_ui2d_rz:
1696 case Intrinsic::nvvm_ui2f_rz:
1697 case Intrinsic::nvvm_ull2d_rz:
1698 case Intrinsic::nvvm_ull2f_rz:
1699 return {Instruction::UIToFP};
1700
1701 // NVVM intrinsics that map to LLVM binary ops.
1702 case Intrinsic::nvvm_add_rn_d:
1703 return {Instruction::FAdd, FTZ_Any};
1704 case Intrinsic::nvvm_add_rn_f:
1705 return {Instruction::FAdd, FTZ_MustBeOff};
1706 case Intrinsic::nvvm_add_rn_ftz_f:
1707 return {Instruction::FAdd, FTZ_MustBeOn};
1708 case Intrinsic::nvvm_mul_rn_d:
1709 return {Instruction::FMul, FTZ_Any};
1710 case Intrinsic::nvvm_mul_rn_f:
1711 return {Instruction::FMul, FTZ_MustBeOff};
1712 case Intrinsic::nvvm_mul_rn_ftz_f:
1713 return {Instruction::FMul, FTZ_MustBeOn};
1714 case Intrinsic::nvvm_div_rn_d:
1715 return {Instruction::FDiv, FTZ_Any};
1716 case Intrinsic::nvvm_div_rn_f:
1717 return {Instruction::FDiv, FTZ_MustBeOff};
1718 case Intrinsic::nvvm_div_rn_ftz_f:
1719 return {Instruction::FDiv, FTZ_MustBeOn};
1720
1721 // The remainder of cases are NVVM intrinsics that map to LLVM idioms, but
1722 // need special handling.
1723 //
1724 // We seem to be mising intrinsics for rcp.approx.{ftz.}f32, which is just
1725 // as well.
1726 case Intrinsic::nvvm_rcp_rn_d:
1727 return {SPC_Reciprocal, FTZ_Any};
1728 case Intrinsic::nvvm_rcp_rn_f:
1729 return {SPC_Reciprocal, FTZ_MustBeOff};
1730 case Intrinsic::nvvm_rcp_rn_ftz_f:
1731 return {SPC_Reciprocal, FTZ_MustBeOn};
1732
1733 // We do not currently simplify intrinsics that give an approximate answer.
1734 // These include:
1735 //
1736 // - nvvm_cos_approx_{f,ftz_f}
1737 // - nvvm_ex2_approx_{d,f,ftz_f}
1738 // - nvvm_lg2_approx_{d,f,ftz_f}
1739 // - nvvm_sin_approx_{f,ftz_f}
1740 // - nvvm_sqrt_approx_{f,ftz_f}
1741 // - nvvm_rsqrt_approx_{d,f,ftz_f}
1742 // - nvvm_div_approx_{ftz_d,ftz_f,f}
1743 // - nvvm_rcp_approx_ftz_d
1744 //
1745 // Ideally we'd encode them as e.g. "fast call @llvm.cos", where "fast"
1746 // means that fastmath is enabled in the intrinsic. Unfortunately only
1747 // binary operators (currently) have a fastmath bit in SelectionDAG, so this
1748 // information gets lost and we can't select on it.
1749 //
1750 // TODO: div and rcp are lowered to a binary op, so these we could in theory
1751 // lower them to "fast fdiv".
1752
1753 default:
1754 return {};
1755 }
1756 }();
1757
1758 // If Action.FtzRequirementTy is not satisfied by the module's ftz state, we
1759 // can bail out now. (Notice that in the case that IID is not an NVVM
1760 // intrinsic, we don't have to look up any module metadata, as
1761 // FtzRequirementTy will be FTZ_Any.)
1762 if (Action.FtzRequirement != FTZ_Any) {
1763 bool FtzEnabled =
1764 II->getFunction()->getFnAttribute("nvptx-f32ftz").getValueAsString() ==
1765 "true";
1766
1767 if (FtzEnabled != (Action.FtzRequirement == FTZ_MustBeOn))
1768 return nullptr;
1769 }
1770
1771 // Simplify to target-generic intrinsic.
1772 if (Action.IID) {
1773 SmallVector<Value *, 4> Args(II->arg_operands());
1774 // All the target-generic intrinsics currently of interest to us have one
1775 // type argument, equal to that of the nvvm intrinsic's argument.
Justin Lebare3ac0fb2017-01-27 01:49:39 +00001776 Type *Tys[] = {II->getArgOperand(0)->getType()};
Justin Lebar698c31b2017-01-27 00:58:58 +00001777 return CallInst::Create(
1778 Intrinsic::getDeclaration(II->getModule(), *Action.IID, Tys), Args);
1779 }
1780
1781 // Simplify to target-generic binary op.
1782 if (Action.BinaryOp)
1783 return BinaryOperator::Create(*Action.BinaryOp, II->getArgOperand(0),
1784 II->getArgOperand(1), II->getName());
1785
1786 // Simplify to target-generic cast op.
1787 if (Action.CastOp)
1788 return CastInst::Create(*Action.CastOp, II->getArgOperand(0), II->getType(),
1789 II->getName());
1790
1791 // All that's left are the special cases.
1792 if (!Action.Special)
1793 return nullptr;
1794
1795 switch (*Action.Special) {
1796 case SPC_Reciprocal:
1797 // Simplify reciprocal.
1798 return BinaryOperator::Create(
1799 Instruction::FDiv, ConstantFP::get(II->getArgOperand(0)->getType(), 1),
1800 II->getArgOperand(0), II->getName());
1801 }
Justin Lebar25ebe2d2017-01-27 02:04:07 +00001802 llvm_unreachable("All SpecialCase enumerators should be handled in switch.");
Justin Lebar698c31b2017-01-27 00:58:58 +00001803}
1804
Arnaud A. de Grandmaison333ef382016-05-10 09:24:49 +00001805Instruction *InstCombiner::visitVAStartInst(VAStartInst &I) {
1806 removeTriviallyEmptyRange(I, Intrinsic::vastart, Intrinsic::vaend, *this);
1807 return nullptr;
1808}
1809
1810Instruction *InstCombiner::visitVACopyInst(VACopyInst &I) {
1811 removeTriviallyEmptyRange(I, Intrinsic::vacopy, Intrinsic::vaend, *this);
1812 return nullptr;
1813}
1814
Sanjay Patelcd4377c2016-01-20 22:24:38 +00001815/// CallInst simplification. This mostly only handles folding of intrinsic
1816/// instructions. For normal calls, it allows visitCallSite to do the heavy
1817/// lifting.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001818Instruction *InstCombiner::visitCallInst(CallInst &CI) {
David Majnemer15032582015-05-22 03:56:46 +00001819 auto Args = CI.arg_operands();
1820 if (Value *V = SimplifyCall(CI.getCalledValue(), Args.begin(), Args.end(), DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001821 &TLI, &DT, &AC))
Sanjay Patel4b198802016-02-01 22:23:39 +00001822 return replaceInstUsesWith(CI, V);
David Majnemer15032582015-05-22 03:56:46 +00001823
Justin Bogner99798402016-08-05 01:06:44 +00001824 if (isFreeCall(&CI, &TLI))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001825 return visitFree(CI);
1826
1827 // If the caller function is nounwind, mark the call as nounwind, even if the
1828 // callee isn't.
Sanjay Patel5a470952016-08-11 15:16:06 +00001829 if (CI.getFunction()->doesNotThrow() && !CI.doesNotThrow()) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001830 CI.setDoesNotThrow();
1831 return &CI;
1832 }
Jim Grosbach7815f562012-02-03 00:07:04 +00001833
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001834 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
1835 if (!II) return visitCallSite(&CI);
Gabor Greif589a0b92010-06-24 12:58:35 +00001836
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001837 // Intrinsics cannot occur in an invoke, so handle them here instead of in
1838 // visitCallSite.
1839 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
1840 bool Changed = false;
1841
1842 // memmove/cpy/set of zero bytes is a noop.
1843 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
Chris Lattnerc663a672010-10-01 05:51:02 +00001844 if (NumBytes->isNullValue())
Sanjay Patel4b198802016-02-01 22:23:39 +00001845 return eraseInstFromFunction(CI);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001846
1847 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
1848 if (CI->getZExtValue() == 1) {
1849 // Replace the instruction with just byte operations. We would
1850 // transform other cases to loads/stores, but we don't know if
1851 // alignment is sufficient.
1852 }
1853 }
Jim Grosbach7815f562012-02-03 00:07:04 +00001854
Chris Lattnerc663a672010-10-01 05:51:02 +00001855 // No other transformations apply to volatile transfers.
1856 if (MI->isVolatile())
Craig Topperf40110f2014-04-25 05:29:35 +00001857 return nullptr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001858
1859 // If we have a memmove and the source operation is a constant global,
1860 // then the source and dest pointers can't alias, so we can change this
1861 // into a call to memcpy.
1862 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
1863 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
1864 if (GVSrc->isConstant()) {
Sanjay Patelaf674fb2015-12-14 17:24:23 +00001865 Module *M = CI.getModule();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001866 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
Jay Foadb804a2b2011-07-12 14:06:48 +00001867 Type *Tys[3] = { CI.getArgOperand(0)->getType(),
1868 CI.getArgOperand(1)->getType(),
1869 CI.getArgOperand(2)->getType() };
Benjamin Kramere6e19332011-07-14 17:45:39 +00001870 CI.setCalledFunction(Intrinsic::getDeclaration(M, MemCpyID, Tys));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001871 Changed = true;
1872 }
1873 }
1874
1875 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) {
1876 // memmove(x,x,size) -> noop.
1877 if (MTI->getSource() == MTI->getDest())
Sanjay Patel4b198802016-02-01 22:23:39 +00001878 return eraseInstFromFunction(CI);
Eric Christopher7258dcd2010-04-16 23:37:20 +00001879 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001880
Eric Christopher7258dcd2010-04-16 23:37:20 +00001881 // If we can determine a pointer alignment that is bigger than currently
1882 // set, update the alignment.
Pete Cooper67cf9a72015-11-19 05:56:52 +00001883 if (isa<MemTransferInst>(MI)) {
1884 if (Instruction *I = SimplifyMemTransfer(MI))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001885 return I;
1886 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
1887 if (Instruction *I = SimplifyMemSet(MSI))
1888 return I;
1889 }
Gabor Greif590d95e2010-06-24 13:42:49 +00001890
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001891 if (Changed) return II;
1892 }
Jim Grosbach7815f562012-02-03 00:07:04 +00001893
Igor Laevsky4b317fa2017-02-08 14:23:47 +00001894 if (auto *AMI = dyn_cast<ElementAtomicMemCpyInst>(II)) {
1895 if (Constant *C = dyn_cast<Constant>(AMI->getNumElements()))
1896 if (C->isNullValue())
1897 return eraseInstFromFunction(*AMI);
Igor Laevsky900ffa32017-02-08 14:32:04 +00001898
1899 if (Instruction *I = SimplifyElementAtomicMemCpy(AMI))
1900 return I;
Igor Laevsky4b317fa2017-02-08 14:23:47 +00001901 }
1902
Justin Lebar698c31b2017-01-27 00:58:58 +00001903 if (Instruction *I = SimplifyNVVMIntrinsic(II, *this))
1904 return I;
1905
Sanjay Patel1c600c62016-01-20 16:41:43 +00001906 auto SimplifyDemandedVectorEltsLow = [this](Value *Op, unsigned Width,
1907 unsigned DemandedWidth) {
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001908 APInt UndefElts(Width, 0);
1909 APInt DemandedElts = APInt::getLowBitsSet(Width, DemandedWidth);
1910 return SimplifyDemandedVectorElts(Op, DemandedElts, UndefElts);
1911 };
1912
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001913 switch (II->getIntrinsicID()) {
1914 default: break;
George Burgess IV3f089142016-12-20 23:46:36 +00001915 case Intrinsic::objectsize:
1916 if (ConstantInt *N =
1917 lowerObjectSizeCall(II, DL, &TLI, /*MustSucceed=*/false))
1918 return replaceInstUsesWith(CI, N);
Craig Topperf40110f2014-04-25 05:29:35 +00001919 return nullptr;
George Burgess IV3f089142016-12-20 23:46:36 +00001920
Michael Ilseman536cc322012-12-13 03:13:36 +00001921 case Intrinsic::bswap: {
1922 Value *IIOperand = II->getArgOperand(0);
Craig Topperf40110f2014-04-25 05:29:35 +00001923 Value *X = nullptr;
Michael Ilseman536cc322012-12-13 03:13:36 +00001924
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001925 // bswap(bswap(x)) -> x
Michael Ilseman536cc322012-12-13 03:13:36 +00001926 if (match(IIOperand, m_BSwap(m_Value(X))))
Sanjay Patel4b198802016-02-01 22:23:39 +00001927 return replaceInstUsesWith(CI, X);
Jim Grosbach7815f562012-02-03 00:07:04 +00001928
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001929 // bswap(trunc(bswap(x))) -> trunc(lshr(x, c))
Michael Ilseman536cc322012-12-13 03:13:36 +00001930 if (match(IIOperand, m_Trunc(m_BSwap(m_Value(X))))) {
1931 unsigned C = X->getType()->getPrimitiveSizeInBits() -
1932 IIOperand->getType()->getPrimitiveSizeInBits();
1933 Value *CV = ConstantInt::get(X->getType(), C);
1934 Value *V = Builder->CreateLShr(X, CV);
1935 return new TruncInst(V, IIOperand->getType());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001936 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001937 break;
Michael Ilseman536cc322012-12-13 03:13:36 +00001938 }
1939
James Molloy2d09c002015-11-12 12:39:41 +00001940 case Intrinsic::bitreverse: {
1941 Value *IIOperand = II->getArgOperand(0);
1942 Value *X = nullptr;
1943
1944 // bitreverse(bitreverse(x)) -> x
1945 if (match(IIOperand, m_Intrinsic<Intrinsic::bitreverse>(m_Value(X))))
Sanjay Patel4b198802016-02-01 22:23:39 +00001946 return replaceInstUsesWith(CI, X);
James Molloy2d09c002015-11-12 12:39:41 +00001947 break;
1948 }
1949
Sanjay Patelb695c552016-02-01 17:00:10 +00001950 case Intrinsic::masked_load:
1951 if (Value *SimplifiedMaskedOp = simplifyMaskedLoad(*II, *Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00001952 return replaceInstUsesWith(CI, SimplifiedMaskedOp);
Sanjay Patelb695c552016-02-01 17:00:10 +00001953 break;
Sanjay Patel04f792b2016-02-01 19:39:52 +00001954 case Intrinsic::masked_store:
1955 return simplifyMaskedStore(*II, *this);
Sanjay Patel103ab7d2016-02-01 22:10:26 +00001956 case Intrinsic::masked_gather:
1957 return simplifyMaskedGather(*II, *this);
1958 case Intrinsic::masked_scatter:
1959 return simplifyMaskedScatter(*II, *this);
Sanjay Patelb695c552016-02-01 17:00:10 +00001960
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001961 case Intrinsic::powi:
Gabor Greif589a0b92010-06-24 12:58:35 +00001962 if (ConstantInt *Power = dyn_cast<ConstantInt>(II->getArgOperand(1))) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001963 // powi(x, 0) -> 1.0
1964 if (Power->isZero())
Sanjay Patel4b198802016-02-01 22:23:39 +00001965 return replaceInstUsesWith(CI, ConstantFP::get(CI.getType(), 1.0));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001966 // powi(x, 1) -> x
1967 if (Power->isOne())
Sanjay Patel4b198802016-02-01 22:23:39 +00001968 return replaceInstUsesWith(CI, II->getArgOperand(0));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001969 // powi(x, -1) -> 1/x
1970 if (Power->isAllOnesValue())
1971 return BinaryOperator::CreateFDiv(ConstantFP::get(CI.getType(), 1.0),
Gabor Greif589a0b92010-06-24 12:58:35 +00001972 II->getArgOperand(0));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001973 }
1974 break;
Jim Grosbach7815f562012-02-03 00:07:04 +00001975
Sanjay Patel8e3ab172016-08-05 22:42:46 +00001976 case Intrinsic::cttz:
1977 case Intrinsic::ctlz:
Amaury Sechet763c59d2016-08-18 20:43:50 +00001978 if (auto *I = foldCttzCtlz(*II, *this))
1979 return I;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001980 break;
Sanjoy Dasb0984472015-04-08 04:27:22 +00001981
Nick Lewyckyabe2cc12015-04-13 19:17:37 +00001982 case Intrinsic::uadd_with_overflow:
1983 case Intrinsic::sadd_with_overflow:
1984 case Intrinsic::umul_with_overflow:
1985 case Intrinsic::smul_with_overflow:
Gabor Greif5b1370e2010-06-28 16:50:57 +00001986 if (isa<Constant>(II->getArgOperand(0)) &&
1987 !isa<Constant>(II->getArgOperand(1))) {
Sanjoy Dasb0984472015-04-08 04:27:22 +00001988 // Canonicalize constants into the RHS.
Gabor Greif5b1370e2010-06-28 16:50:57 +00001989 Value *LHS = II->getArgOperand(0);
1990 II->setArgOperand(0, II->getArgOperand(1));
1991 II->setArgOperand(1, LHS);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001992 return II;
1993 }
Justin Bognercd1d5aa2016-08-17 20:30:52 +00001994 LLVM_FALLTHROUGH;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001995
Nick Lewyckyabe2cc12015-04-13 19:17:37 +00001996 case Intrinsic::usub_with_overflow:
1997 case Intrinsic::ssub_with_overflow: {
Sanjoy Dasb0984472015-04-08 04:27:22 +00001998 OverflowCheckFlavor OCF =
1999 IntrinsicIDToOverflowCheckFlavor(II->getIntrinsicID());
2000 assert(OCF != OCF_INVALID && "unexpected!");
Jim Grosbach7815f562012-02-03 00:07:04 +00002001
Sanjoy Dasb0984472015-04-08 04:27:22 +00002002 Value *OperationResult = nullptr;
2003 Constant *OverflowResult = nullptr;
2004 if (OptimizeOverflowCheck(OCF, II->getArgOperand(0), II->getArgOperand(1),
2005 *II, OperationResult, OverflowResult))
2006 return CreateOverflowTuple(II, OperationResult, OverflowResult);
Benjamin Kramera420df22014-07-04 10:22:21 +00002007
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002008 break;
Erik Eckstein096ff7d2014-12-11 08:02:30 +00002009 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002010
Matt Arsenaultd6511b42014-10-21 23:00:20 +00002011 case Intrinsic::minnum:
2012 case Intrinsic::maxnum: {
2013 Value *Arg0 = II->getArgOperand(0);
2014 Value *Arg1 = II->getArgOperand(1);
Sanjay Patel0069f562016-01-31 16:35:23 +00002015 // Canonicalize constants to the RHS.
2016 if (isa<ConstantFP>(Arg0) && !isa<ConstantFP>(Arg1)) {
Matt Arsenaultd6511b42014-10-21 23:00:20 +00002017 II->setArgOperand(0, Arg1);
2018 II->setArgOperand(1, Arg0);
2019 return II;
2020 }
Sanjay Patel0069f562016-01-31 16:35:23 +00002021 if (Value *V = simplifyMinnumMaxnum(*II))
Sanjay Patel4b198802016-02-01 22:23:39 +00002022 return replaceInstUsesWith(*II, V);
Matt Arsenaultd6511b42014-10-21 23:00:20 +00002023 break;
2024 }
Matt Arsenault1cc294c2017-01-03 04:32:31 +00002025 case Intrinsic::fmuladd: {
Matt Arsenault92057602017-02-16 18:46:24 +00002026 // Canonicalize fast fmuladd to the separate fmul + fadd.
2027 if (II->hasUnsafeAlgebra()) {
2028 BuilderTy::FastMathFlagGuard Guard(*Builder);
2029 Builder->setFastMathFlags(II->getFastMathFlags());
2030 Value *Mul = Builder->CreateFMul(II->getArgOperand(0),
2031 II->getArgOperand(1));
2032 Value *Add = Builder->CreateFAdd(Mul, II->getArgOperand(2));
2033 Add->takeName(II);
2034 return replaceInstUsesWith(*II, Add);
2035 }
2036
2037 LLVM_FALLTHROUGH;
2038 }
2039 case Intrinsic::fma: {
Matt Arsenault1cc294c2017-01-03 04:32:31 +00002040 Value *Src0 = II->getArgOperand(0);
2041 Value *Src1 = II->getArgOperand(1);
2042
Matt Arsenaultb264c942017-01-03 04:32:35 +00002043 // Canonicalize constants into the RHS.
2044 if (isa<Constant>(Src0) && !isa<Constant>(Src1)) {
2045 II->setArgOperand(0, Src1);
2046 II->setArgOperand(1, Src0);
2047 std::swap(Src0, Src1);
2048 }
2049
2050 Value *LHS = nullptr;
2051 Value *RHS = nullptr;
2052
Matt Arsenault1cc294c2017-01-03 04:32:31 +00002053 // fma fneg(x), fneg(y), z -> fma x, y, z
2054 if (match(Src0, m_FNeg(m_Value(LHS))) &&
2055 match(Src1, m_FNeg(m_Value(RHS)))) {
Matt Arsenault3f509042017-01-10 23:17:52 +00002056 II->setArgOperand(0, LHS);
2057 II->setArgOperand(1, RHS);
2058 return II;
Matt Arsenault1cc294c2017-01-03 04:32:31 +00002059 }
2060
2061 // fma fabs(x), fabs(x), z -> fma x, x, z
2062 if (match(Src0, m_Intrinsic<Intrinsic::fabs>(m_Value(LHS))) &&
2063 match(Src1, m_Intrinsic<Intrinsic::fabs>(m_Value(RHS))) && LHS == RHS) {
Matt Arsenault3f509042017-01-10 23:17:52 +00002064 II->setArgOperand(0, LHS);
2065 II->setArgOperand(1, RHS);
2066 return II;
Matt Arsenault1cc294c2017-01-03 04:32:31 +00002067 }
2068
Matt Arsenaultb264c942017-01-03 04:32:35 +00002069 // fma x, 1, z -> fadd x, z
2070 if (match(Src1, m_FPOne())) {
2071 Instruction *RI = BinaryOperator::CreateFAdd(Src0, II->getArgOperand(2));
2072 RI->copyFastMathFlags(II);
2073 return RI;
2074 }
2075
Matt Arsenault1cc294c2017-01-03 04:32:31 +00002076 break;
2077 }
Matt Arsenault56ff4832017-01-03 22:40:34 +00002078 case Intrinsic::fabs: {
2079 Value *Cond;
2080 Constant *LHS, *RHS;
2081 if (match(II->getArgOperand(0),
2082 m_Select(m_Value(Cond), m_Constant(LHS), m_Constant(RHS)))) {
2083 CallInst *Call0 = Builder->CreateCall(II->getCalledFunction(), {LHS});
2084 CallInst *Call1 = Builder->CreateCall(II->getCalledFunction(), {RHS});
2085 return SelectInst::Create(Cond, Call0, Call1);
2086 }
2087
Matt Arsenault954a6242017-01-23 23:55:08 +00002088 LLVM_FALLTHROUGH;
2089 }
2090 case Intrinsic::ceil:
2091 case Intrinsic::floor:
2092 case Intrinsic::round:
2093 case Intrinsic::nearbyint:
2094 case Intrinsic::trunc: {
Matt Arsenault72333442017-01-17 00:10:40 +00002095 Value *ExtSrc;
2096 if (match(II->getArgOperand(0), m_FPExt(m_Value(ExtSrc))) &&
2097 II->getArgOperand(0)->hasOneUse()) {
2098 // fabs (fpext x) -> fpext (fabs x)
Matt Arsenault954a6242017-01-23 23:55:08 +00002099 Value *F = Intrinsic::getDeclaration(II->getModule(), II->getIntrinsicID(),
Matt Arsenault72333442017-01-17 00:10:40 +00002100 { ExtSrc->getType() });
2101 CallInst *NewFabs = Builder->CreateCall(F, ExtSrc);
2102 NewFabs->copyFastMathFlags(II);
2103 NewFabs->takeName(II);
2104 return new FPExtInst(NewFabs, II->getType());
2105 }
2106
Matt Arsenault56ff4832017-01-03 22:40:34 +00002107 break;
2108 }
Matt Arsenault3bdd75d2017-01-04 22:49:03 +00002109 case Intrinsic::cos:
2110 case Intrinsic::amdgcn_cos: {
2111 Value *SrcSrc;
2112 Value *Src = II->getArgOperand(0);
2113 if (match(Src, m_FNeg(m_Value(SrcSrc))) ||
2114 match(Src, m_Intrinsic<Intrinsic::fabs>(m_Value(SrcSrc)))) {
2115 // cos(-x) -> cos(x)
2116 // cos(fabs(x)) -> cos(x)
2117 II->setArgOperand(0, SrcSrc);
2118 return II;
2119 }
2120
2121 break;
2122 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002123 case Intrinsic::ppc_altivec_lvx:
2124 case Intrinsic::ppc_altivec_lvxl:
Bill Wendlingb902f1d2011-04-13 00:36:11 +00002125 // Turn PPC lvx -> load if the pointer is known aligned.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002126 if (getOrEnforceKnownAlignment(II->getArgOperand(0), 16, DL, II, &AC,
Justin Bogner99798402016-08-05 01:06:44 +00002127 &DT) >= 16) {
Gabor Greif589a0b92010-06-24 12:58:35 +00002128 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(0),
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002129 PointerType::getUnqual(II->getType()));
2130 return new LoadInst(Ptr);
2131 }
2132 break;
Bill Schmidt72954782014-11-12 04:19:40 +00002133 case Intrinsic::ppc_vsx_lxvw4x:
2134 case Intrinsic::ppc_vsx_lxvd2x: {
2135 // Turn PPC VSX loads into normal loads.
2136 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(0),
2137 PointerType::getUnqual(II->getType()));
2138 return new LoadInst(Ptr, Twine(""), false, 1);
2139 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002140 case Intrinsic::ppc_altivec_stvx:
2141 case Intrinsic::ppc_altivec_stvxl:
2142 // Turn stvx -> store if the pointer is known aligned.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002143 if (getOrEnforceKnownAlignment(II->getArgOperand(1), 16, DL, II, &AC,
Justin Bogner99798402016-08-05 01:06:44 +00002144 &DT) >= 16) {
Jim Grosbach7815f562012-02-03 00:07:04 +00002145 Type *OpPtrTy =
Gabor Greifa6d75e22010-06-24 15:51:11 +00002146 PointerType::getUnqual(II->getArgOperand(0)->getType());
2147 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(1), OpPtrTy);
2148 return new StoreInst(II->getArgOperand(0), Ptr);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002149 }
2150 break;
Bill Schmidt72954782014-11-12 04:19:40 +00002151 case Intrinsic::ppc_vsx_stxvw4x:
2152 case Intrinsic::ppc_vsx_stxvd2x: {
2153 // Turn PPC VSX stores into normal stores.
2154 Type *OpPtrTy = PointerType::getUnqual(II->getArgOperand(0)->getType());
2155 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(1), OpPtrTy);
2156 return new StoreInst(II->getArgOperand(0), Ptr, false, 1);
2157 }
Hal Finkel221f4672015-02-26 18:56:03 +00002158 case Intrinsic::ppc_qpx_qvlfs:
2159 // Turn PPC QPX qvlfs -> load if the pointer is known aligned.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002160 if (getOrEnforceKnownAlignment(II->getArgOperand(0), 16, DL, II, &AC,
Justin Bogner99798402016-08-05 01:06:44 +00002161 &DT) >= 16) {
Hal Finkelf0d68d72015-05-11 06:37:03 +00002162 Type *VTy = VectorType::get(Builder->getFloatTy(),
2163 II->getType()->getVectorNumElements());
Hal Finkel221f4672015-02-26 18:56:03 +00002164 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(0),
Hal Finkelf0d68d72015-05-11 06:37:03 +00002165 PointerType::getUnqual(VTy));
2166 Value *Load = Builder->CreateLoad(Ptr);
2167 return new FPExtInst(Load, II->getType());
Hal Finkel221f4672015-02-26 18:56:03 +00002168 }
2169 break;
2170 case Intrinsic::ppc_qpx_qvlfd:
2171 // Turn PPC QPX qvlfd -> load if the pointer is known aligned.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002172 if (getOrEnforceKnownAlignment(II->getArgOperand(0), 32, DL, II, &AC,
Justin Bogner99798402016-08-05 01:06:44 +00002173 &DT) >= 32) {
Hal Finkel221f4672015-02-26 18:56:03 +00002174 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(0),
2175 PointerType::getUnqual(II->getType()));
2176 return new LoadInst(Ptr);
2177 }
2178 break;
2179 case Intrinsic::ppc_qpx_qvstfs:
2180 // Turn PPC QPX qvstfs -> store if the pointer is known aligned.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002181 if (getOrEnforceKnownAlignment(II->getArgOperand(1), 16, DL, II, &AC,
Justin Bogner99798402016-08-05 01:06:44 +00002182 &DT) >= 16) {
Hal Finkelf0d68d72015-05-11 06:37:03 +00002183 Type *VTy = VectorType::get(Builder->getFloatTy(),
2184 II->getArgOperand(0)->getType()->getVectorNumElements());
2185 Value *TOp = Builder->CreateFPTrunc(II->getArgOperand(0), VTy);
2186 Type *OpPtrTy = PointerType::getUnqual(VTy);
Hal Finkel221f4672015-02-26 18:56:03 +00002187 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(1), OpPtrTy);
Hal Finkelf0d68d72015-05-11 06:37:03 +00002188 return new StoreInst(TOp, Ptr);
Hal Finkel221f4672015-02-26 18:56:03 +00002189 }
2190 break;
2191 case Intrinsic::ppc_qpx_qvstfd:
2192 // Turn PPC QPX qvstfd -> store if the pointer is known aligned.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002193 if (getOrEnforceKnownAlignment(II->getArgOperand(1), 32, DL, II, &AC,
Justin Bogner99798402016-08-05 01:06:44 +00002194 &DT) >= 32) {
Hal Finkel221f4672015-02-26 18:56:03 +00002195 Type *OpPtrTy =
2196 PointerType::getUnqual(II->getArgOperand(0)->getType());
2197 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(1), OpPtrTy);
2198 return new StoreInst(II->getArgOperand(0), Ptr);
2199 }
2200 break;
Simon Pilgrim20c607b2015-09-12 13:39:53 +00002201
Simon Pilgrim20c607b2015-09-12 13:39:53 +00002202 case Intrinsic::x86_vcvtph2ps_128:
2203 case Intrinsic::x86_vcvtph2ps_256: {
2204 auto Arg = II->getArgOperand(0);
2205 auto ArgType = cast<VectorType>(Arg->getType());
2206 auto RetType = cast<VectorType>(II->getType());
2207 unsigned ArgWidth = ArgType->getNumElements();
2208 unsigned RetWidth = RetType->getNumElements();
2209 assert(RetWidth <= ArgWidth && "Unexpected input/return vector widths");
2210 assert(ArgType->isIntOrIntVectorTy() &&
2211 ArgType->getScalarSizeInBits() == 16 &&
2212 "CVTPH2PS input type should be 16-bit integer vector");
2213 assert(RetType->getScalarType()->isFloatTy() &&
2214 "CVTPH2PS output type should be 32-bit float vector");
2215
2216 // Constant folding: Convert to generic half to single conversion.
Simon Pilgrim48ffca02015-09-12 14:00:17 +00002217 if (isa<ConstantAggregateZero>(Arg))
Sanjay Patel4b198802016-02-01 22:23:39 +00002218 return replaceInstUsesWith(*II, ConstantAggregateZero::get(RetType));
Simon Pilgrim20c607b2015-09-12 13:39:53 +00002219
Simon Pilgrim48ffca02015-09-12 14:00:17 +00002220 if (isa<ConstantDataVector>(Arg)) {
Simon Pilgrim20c607b2015-09-12 13:39:53 +00002221 auto VectorHalfAsShorts = Arg;
2222 if (RetWidth < ArgWidth) {
Craig Topper99d1eab2016-06-12 00:41:19 +00002223 SmallVector<uint32_t, 8> SubVecMask;
Simon Pilgrim20c607b2015-09-12 13:39:53 +00002224 for (unsigned i = 0; i != RetWidth; ++i)
2225 SubVecMask.push_back((int)i);
2226 VectorHalfAsShorts = Builder->CreateShuffleVector(
2227 Arg, UndefValue::get(ArgType), SubVecMask);
2228 }
2229
2230 auto VectorHalfType =
2231 VectorType::get(Type::getHalfTy(II->getContext()), RetWidth);
2232 auto VectorHalfs =
2233 Builder->CreateBitCast(VectorHalfAsShorts, VectorHalfType);
2234 auto VectorFloats = Builder->CreateFPExt(VectorHalfs, RetType);
Sanjay Patel4b198802016-02-01 22:23:39 +00002235 return replaceInstUsesWith(*II, VectorFloats);
Simon Pilgrim20c607b2015-09-12 13:39:53 +00002236 }
2237
2238 // We only use the lowest lanes of the argument.
Simon Pilgrim996725e2015-09-19 11:41:53 +00002239 if (Value *V = SimplifyDemandedVectorEltsLow(Arg, ArgWidth, RetWidth)) {
Simon Pilgrim20c607b2015-09-12 13:39:53 +00002240 II->setArgOperand(0, V);
2241 return II;
2242 }
2243 break;
2244 }
2245
Chandler Carruthcf414cf2011-01-10 07:19:37 +00002246 case Intrinsic::x86_sse_cvtss2si:
2247 case Intrinsic::x86_sse_cvtss2si64:
2248 case Intrinsic::x86_sse_cvttss2si:
2249 case Intrinsic::x86_sse_cvttss2si64:
2250 case Intrinsic::x86_sse2_cvtsd2si:
2251 case Intrinsic::x86_sse2_cvtsd2si64:
2252 case Intrinsic::x86_sse2_cvttsd2si:
Craig Topperaeaa52c2016-12-14 07:46:12 +00002253 case Intrinsic::x86_sse2_cvttsd2si64:
2254 case Intrinsic::x86_avx512_vcvtss2si32:
2255 case Intrinsic::x86_avx512_vcvtss2si64:
2256 case Intrinsic::x86_avx512_vcvtss2usi32:
2257 case Intrinsic::x86_avx512_vcvtss2usi64:
2258 case Intrinsic::x86_avx512_vcvtsd2si32:
2259 case Intrinsic::x86_avx512_vcvtsd2si64:
2260 case Intrinsic::x86_avx512_vcvtsd2usi32:
2261 case Intrinsic::x86_avx512_vcvtsd2usi64:
2262 case Intrinsic::x86_avx512_cvttss2si:
2263 case Intrinsic::x86_avx512_cvttss2si64:
2264 case Intrinsic::x86_avx512_cvttss2usi:
2265 case Intrinsic::x86_avx512_cvttss2usi64:
2266 case Intrinsic::x86_avx512_cvttsd2si:
2267 case Intrinsic::x86_avx512_cvttsd2si64:
2268 case Intrinsic::x86_avx512_cvttsd2usi:
2269 case Intrinsic::x86_avx512_cvttsd2usi64: {
Chandler Carruthcf414cf2011-01-10 07:19:37 +00002270 // These intrinsics only demand the 0th element of their input vectors. If
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002271 // we can simplify the input based on that, do so now.
Simon Pilgrim996725e2015-09-19 11:41:53 +00002272 Value *Arg = II->getArgOperand(0);
2273 unsigned VWidth = Arg->getType()->getVectorNumElements();
2274 if (Value *V = SimplifyDemandedVectorEltsLow(Arg, VWidth, 1)) {
Gabor Greif5b1370e2010-06-28 16:50:57 +00002275 II->setArgOperand(0, V);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002276 return II;
2277 }
Simon Pilgrim18617d12015-08-05 08:18:00 +00002278 break;
2279 }
2280
Simon Pilgrim91e3ac82016-06-07 08:18:35 +00002281 case Intrinsic::x86_mmx_pmovmskb:
2282 case Intrinsic::x86_sse_movmsk_ps:
2283 case Intrinsic::x86_sse2_movmsk_pd:
2284 case Intrinsic::x86_sse2_pmovmskb_128:
2285 case Intrinsic::x86_avx_movmsk_pd_256:
2286 case Intrinsic::x86_avx_movmsk_ps_256:
2287 case Intrinsic::x86_avx2_pmovmskb: {
2288 if (Value *V = simplifyX86movmsk(*II, *Builder))
2289 return replaceInstUsesWith(*II, V);
2290 break;
2291 }
2292
Simon Pilgrim471efd22016-02-20 23:17:35 +00002293 case Intrinsic::x86_sse_comieq_ss:
2294 case Intrinsic::x86_sse_comige_ss:
2295 case Intrinsic::x86_sse_comigt_ss:
2296 case Intrinsic::x86_sse_comile_ss:
2297 case Intrinsic::x86_sse_comilt_ss:
2298 case Intrinsic::x86_sse_comineq_ss:
2299 case Intrinsic::x86_sse_ucomieq_ss:
2300 case Intrinsic::x86_sse_ucomige_ss:
2301 case Intrinsic::x86_sse_ucomigt_ss:
2302 case Intrinsic::x86_sse_ucomile_ss:
2303 case Intrinsic::x86_sse_ucomilt_ss:
2304 case Intrinsic::x86_sse_ucomineq_ss:
2305 case Intrinsic::x86_sse2_comieq_sd:
2306 case Intrinsic::x86_sse2_comige_sd:
2307 case Intrinsic::x86_sse2_comigt_sd:
2308 case Intrinsic::x86_sse2_comile_sd:
2309 case Intrinsic::x86_sse2_comilt_sd:
2310 case Intrinsic::x86_sse2_comineq_sd:
2311 case Intrinsic::x86_sse2_ucomieq_sd:
2312 case Intrinsic::x86_sse2_ucomige_sd:
2313 case Intrinsic::x86_sse2_ucomigt_sd:
2314 case Intrinsic::x86_sse2_ucomile_sd:
2315 case Intrinsic::x86_sse2_ucomilt_sd:
Craig Topperd9639532016-12-11 07:42:04 +00002316 case Intrinsic::x86_sse2_ucomineq_sd:
Craig Topperd00db692016-12-31 00:45:06 +00002317 case Intrinsic::x86_avx512_vcomi_ss:
2318 case Intrinsic::x86_avx512_vcomi_sd:
Craig Topperd9639532016-12-11 07:42:04 +00002319 case Intrinsic::x86_avx512_mask_cmp_ss:
2320 case Intrinsic::x86_avx512_mask_cmp_sd: {
Simon Pilgrim471efd22016-02-20 23:17:35 +00002321 // These intrinsics only demand the 0th element of their input vectors. If
2322 // we can simplify the input based on that, do so now.
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002323 bool MadeChange = false;
Simon Pilgrim471efd22016-02-20 23:17:35 +00002324 Value *Arg0 = II->getArgOperand(0);
2325 Value *Arg1 = II->getArgOperand(1);
2326 unsigned VWidth = Arg0->getType()->getVectorNumElements();
2327 if (Value *V = SimplifyDemandedVectorEltsLow(Arg0, VWidth, 1)) {
2328 II->setArgOperand(0, V);
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002329 MadeChange = true;
Simon Pilgrim471efd22016-02-20 23:17:35 +00002330 }
2331 if (Value *V = SimplifyDemandedVectorEltsLow(Arg1, VWidth, 1)) {
2332 II->setArgOperand(1, V);
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002333 MadeChange = true;
Simon Pilgrim471efd22016-02-20 23:17:35 +00002334 }
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002335 if (MadeChange)
2336 return II;
Simon Pilgrim471efd22016-02-20 23:17:35 +00002337 break;
2338 }
2339
Craig Topper020b2282016-12-27 00:23:16 +00002340 case Intrinsic::x86_avx512_mask_add_ps_512:
2341 case Intrinsic::x86_avx512_mask_div_ps_512:
2342 case Intrinsic::x86_avx512_mask_mul_ps_512:
2343 case Intrinsic::x86_avx512_mask_sub_ps_512:
2344 case Intrinsic::x86_avx512_mask_add_pd_512:
2345 case Intrinsic::x86_avx512_mask_div_pd_512:
2346 case Intrinsic::x86_avx512_mask_mul_pd_512:
2347 case Intrinsic::x86_avx512_mask_sub_pd_512:
2348 // If the rounding mode is CUR_DIRECTION(4) we can turn these into regular
2349 // IR operations.
2350 if (auto *R = dyn_cast<ConstantInt>(II->getArgOperand(4))) {
2351 if (R->getValue() == 4) {
2352 Value *Arg0 = II->getArgOperand(0);
2353 Value *Arg1 = II->getArgOperand(1);
2354
2355 Value *V;
2356 switch (II->getIntrinsicID()) {
2357 default: llvm_unreachable("Case stmts out of sync!");
2358 case Intrinsic::x86_avx512_mask_add_ps_512:
2359 case Intrinsic::x86_avx512_mask_add_pd_512:
2360 V = Builder->CreateFAdd(Arg0, Arg1);
2361 break;
2362 case Intrinsic::x86_avx512_mask_sub_ps_512:
2363 case Intrinsic::x86_avx512_mask_sub_pd_512:
2364 V = Builder->CreateFSub(Arg0, Arg1);
2365 break;
2366 case Intrinsic::x86_avx512_mask_mul_ps_512:
2367 case Intrinsic::x86_avx512_mask_mul_pd_512:
2368 V = Builder->CreateFMul(Arg0, Arg1);
2369 break;
2370 case Intrinsic::x86_avx512_mask_div_ps_512:
2371 case Intrinsic::x86_avx512_mask_div_pd_512:
2372 V = Builder->CreateFDiv(Arg0, Arg1);
2373 break;
2374 }
2375
2376 // Create a select for the masking.
2377 V = emitX86MaskSelect(II->getArgOperand(3), V, II->getArgOperand(2),
2378 *Builder);
2379 return replaceInstUsesWith(*II, V);
2380 }
2381 }
2382 break;
2383
Craig Topper790d0fa2016-12-11 07:42:01 +00002384 case Intrinsic::x86_avx512_mask_add_ss_round:
2385 case Intrinsic::x86_avx512_mask_div_ss_round:
2386 case Intrinsic::x86_avx512_mask_mul_ss_round:
2387 case Intrinsic::x86_avx512_mask_sub_ss_round:
Craig Topper790d0fa2016-12-11 07:42:01 +00002388 case Intrinsic::x86_avx512_mask_add_sd_round:
2389 case Intrinsic::x86_avx512_mask_div_sd_round:
2390 case Intrinsic::x86_avx512_mask_mul_sd_round:
2391 case Intrinsic::x86_avx512_mask_sub_sd_round:
Craig Topper7b788ada2016-12-26 06:33:19 +00002392 // If the rounding mode is CUR_DIRECTION(4) we can turn these into regular
2393 // IR operations.
2394 if (auto *R = dyn_cast<ConstantInt>(II->getArgOperand(4))) {
2395 if (R->getValue() == 4) {
Craig Topper7f8540b2016-12-27 01:56:30 +00002396 // Extract the element as scalars.
2397 Value *Arg0 = II->getArgOperand(0);
2398 Value *Arg1 = II->getArgOperand(1);
2399 Value *LHS = Builder->CreateExtractElement(Arg0, (uint64_t)0);
2400 Value *RHS = Builder->CreateExtractElement(Arg1, (uint64_t)0);
Craig Topper7b788ada2016-12-26 06:33:19 +00002401
Craig Topper7f8540b2016-12-27 01:56:30 +00002402 Value *V;
2403 switch (II->getIntrinsicID()) {
2404 default: llvm_unreachable("Case stmts out of sync!");
2405 case Intrinsic::x86_avx512_mask_add_ss_round:
2406 case Intrinsic::x86_avx512_mask_add_sd_round:
2407 V = Builder->CreateFAdd(LHS, RHS);
2408 break;
2409 case Intrinsic::x86_avx512_mask_sub_ss_round:
2410 case Intrinsic::x86_avx512_mask_sub_sd_round:
2411 V = Builder->CreateFSub(LHS, RHS);
2412 break;
2413 case Intrinsic::x86_avx512_mask_mul_ss_round:
2414 case Intrinsic::x86_avx512_mask_mul_sd_round:
2415 V = Builder->CreateFMul(LHS, RHS);
2416 break;
2417 case Intrinsic::x86_avx512_mask_div_ss_round:
2418 case Intrinsic::x86_avx512_mask_div_sd_round:
2419 V = Builder->CreateFDiv(LHS, RHS);
2420 break;
Craig Topper7b788ada2016-12-26 06:33:19 +00002421 }
Craig Topper7f8540b2016-12-27 01:56:30 +00002422
2423 // Handle the masking aspect of the intrinsic.
Craig Topper7f8540b2016-12-27 01:56:30 +00002424 Value *Mask = II->getArgOperand(3);
Craig Topper99163632016-12-30 23:06:28 +00002425 auto *C = dyn_cast<ConstantInt>(Mask);
2426 // We don't need a select if we know the mask bit is a 1.
2427 if (!C || !C->getValue()[0]) {
2428 // Cast the mask to an i1 vector and then extract the lowest element.
2429 auto *MaskTy = VectorType::get(Builder->getInt1Ty(),
Craig Topper7f8540b2016-12-27 01:56:30 +00002430 cast<IntegerType>(Mask->getType())->getBitWidth());
Craig Topper99163632016-12-30 23:06:28 +00002431 Mask = Builder->CreateBitCast(Mask, MaskTy);
2432 Mask = Builder->CreateExtractElement(Mask, (uint64_t)0);
2433 // Extract the lowest element from the passthru operand.
2434 Value *Passthru = Builder->CreateExtractElement(II->getArgOperand(2),
2435 (uint64_t)0);
2436 V = Builder->CreateSelect(Mask, V, Passthru);
2437 }
Craig Topper7f8540b2016-12-27 01:56:30 +00002438
2439 // Insert the result back into the original argument 0.
2440 V = Builder->CreateInsertElement(Arg0, V, (uint64_t)0);
2441
2442 return replaceInstUsesWith(*II, V);
Craig Topper7b788ada2016-12-26 06:33:19 +00002443 }
2444 }
2445 LLVM_FALLTHROUGH;
2446
2447 // X86 scalar intrinsics simplified with SimplifyDemandedVectorElts.
2448 case Intrinsic::x86_avx512_mask_max_ss_round:
2449 case Intrinsic::x86_avx512_mask_min_ss_round:
Craig Topper790d0fa2016-12-11 07:42:01 +00002450 case Intrinsic::x86_avx512_mask_max_sd_round:
Craig Topper268b3ab2016-12-14 06:06:58 +00002451 case Intrinsic::x86_avx512_mask_min_sd_round:
Craig Topperab5f3552016-12-15 03:49:45 +00002452 case Intrinsic::x86_avx512_mask_vfmadd_ss:
2453 case Intrinsic::x86_avx512_mask_vfmadd_sd:
2454 case Intrinsic::x86_avx512_maskz_vfmadd_ss:
2455 case Intrinsic::x86_avx512_maskz_vfmadd_sd:
2456 case Intrinsic::x86_avx512_mask3_vfmadd_ss:
2457 case Intrinsic::x86_avx512_mask3_vfmadd_sd:
2458 case Intrinsic::x86_avx512_mask3_vfmsub_ss:
2459 case Intrinsic::x86_avx512_mask3_vfmsub_sd:
2460 case Intrinsic::x86_avx512_mask3_vfnmsub_ss:
2461 case Intrinsic::x86_avx512_mask3_vfnmsub_sd:
Craig Topperdfd268d2016-12-14 05:43:05 +00002462 case Intrinsic::x86_fma_vfmadd_ss:
2463 case Intrinsic::x86_fma_vfmsub_ss:
2464 case Intrinsic::x86_fma_vfnmadd_ss:
2465 case Intrinsic::x86_fma_vfnmsub_ss:
2466 case Intrinsic::x86_fma_vfmadd_sd:
2467 case Intrinsic::x86_fma_vfmsub_sd:
2468 case Intrinsic::x86_fma_vfnmadd_sd:
2469 case Intrinsic::x86_fma_vfnmsub_sd:
Craig Toppera0372de2016-12-14 03:17:27 +00002470 case Intrinsic::x86_sse_cmp_ss:
2471 case Intrinsic::x86_sse_min_ss:
2472 case Intrinsic::x86_sse_max_ss:
2473 case Intrinsic::x86_sse2_cmp_sd:
2474 case Intrinsic::x86_sse2_min_sd:
2475 case Intrinsic::x86_sse2_max_sd:
Craig Toppereb6a20e2016-12-14 03:17:30 +00002476 case Intrinsic::x86_sse41_round_ss:
2477 case Intrinsic::x86_sse41_round_sd:
Craig Topperac75bca2016-12-13 07:45:45 +00002478 case Intrinsic::x86_xop_vfrcz_ss:
2479 case Intrinsic::x86_xop_vfrcz_sd: {
2480 unsigned VWidth = II->getType()->getVectorNumElements();
2481 APInt UndefElts(VWidth, 0);
2482 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
2483 if (Value *V = SimplifyDemandedVectorElts(II, AllOnesEltMask, UndefElts)) {
2484 if (V != II)
2485 return replaceInstUsesWith(*II, V);
2486 return II;
2487 }
2488 break;
2489 }
2490
Simon Pilgrima3a72b42015-08-10 20:21:15 +00002491 // Constant fold ashr( <A x Bi>, Ci ).
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00002492 // Constant fold lshr( <A x Bi>, Ci ).
2493 // Constant fold shl( <A x Bi>, Ci ).
Simon Pilgrima3a72b42015-08-10 20:21:15 +00002494 case Intrinsic::x86_sse2_psrai_d:
2495 case Intrinsic::x86_sse2_psrai_w:
Simon Pilgrima3a72b42015-08-10 20:21:15 +00002496 case Intrinsic::x86_avx2_psrai_d:
2497 case Intrinsic::x86_avx2_psrai_w:
Craig Topper8b831cb2016-11-13 01:51:55 +00002498 case Intrinsic::x86_avx512_psrai_q_128:
2499 case Intrinsic::x86_avx512_psrai_q_256:
2500 case Intrinsic::x86_avx512_psrai_d_512:
2501 case Intrinsic::x86_avx512_psrai_q_512:
2502 case Intrinsic::x86_avx512_psrai_w_512:
Simon Pilgrim18617d12015-08-05 08:18:00 +00002503 case Intrinsic::x86_sse2_psrli_d:
2504 case Intrinsic::x86_sse2_psrli_q:
2505 case Intrinsic::x86_sse2_psrli_w:
Simon Pilgrim18617d12015-08-05 08:18:00 +00002506 case Intrinsic::x86_avx2_psrli_d:
2507 case Intrinsic::x86_avx2_psrli_q:
2508 case Intrinsic::x86_avx2_psrli_w:
Craig Topper8b831cb2016-11-13 01:51:55 +00002509 case Intrinsic::x86_avx512_psrli_d_512:
2510 case Intrinsic::x86_avx512_psrli_q_512:
2511 case Intrinsic::x86_avx512_psrli_w_512:
Michael J. Spencerdee4b2c2014-04-24 00:58:18 +00002512 case Intrinsic::x86_sse2_pslli_d:
2513 case Intrinsic::x86_sse2_pslli_q:
2514 case Intrinsic::x86_sse2_pslli_w:
Simon Pilgrim18617d12015-08-05 08:18:00 +00002515 case Intrinsic::x86_avx2_pslli_d:
2516 case Intrinsic::x86_avx2_pslli_q:
2517 case Intrinsic::x86_avx2_pslli_w:
Craig Topper8b831cb2016-11-13 01:51:55 +00002518 case Intrinsic::x86_avx512_pslli_d_512:
2519 case Intrinsic::x86_avx512_pslli_q_512:
2520 case Intrinsic::x86_avx512_pslli_w_512:
Sanjay Patel6038d3e2016-01-29 23:27:03 +00002521 if (Value *V = simplifyX86immShift(*II, *Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00002522 return replaceInstUsesWith(*II, V);
Simon Pilgrim18617d12015-08-05 08:18:00 +00002523 break;
2524
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00002525 case Intrinsic::x86_sse2_psra_d:
2526 case Intrinsic::x86_sse2_psra_w:
2527 case Intrinsic::x86_avx2_psra_d:
2528 case Intrinsic::x86_avx2_psra_w:
Craig Topper8b831cb2016-11-13 01:51:55 +00002529 case Intrinsic::x86_avx512_psra_q_128:
2530 case Intrinsic::x86_avx512_psra_q_256:
2531 case Intrinsic::x86_avx512_psra_d_512:
2532 case Intrinsic::x86_avx512_psra_q_512:
2533 case Intrinsic::x86_avx512_psra_w_512:
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00002534 case Intrinsic::x86_sse2_psrl_d:
2535 case Intrinsic::x86_sse2_psrl_q:
2536 case Intrinsic::x86_sse2_psrl_w:
2537 case Intrinsic::x86_avx2_psrl_d:
2538 case Intrinsic::x86_avx2_psrl_q:
2539 case Intrinsic::x86_avx2_psrl_w:
Craig Topper8b831cb2016-11-13 01:51:55 +00002540 case Intrinsic::x86_avx512_psrl_d_512:
2541 case Intrinsic::x86_avx512_psrl_q_512:
2542 case Intrinsic::x86_avx512_psrl_w_512:
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00002543 case Intrinsic::x86_sse2_psll_d:
2544 case Intrinsic::x86_sse2_psll_q:
2545 case Intrinsic::x86_sse2_psll_w:
2546 case Intrinsic::x86_avx2_psll_d:
2547 case Intrinsic::x86_avx2_psll_q:
Craig Topper8b831cb2016-11-13 01:51:55 +00002548 case Intrinsic::x86_avx2_psll_w:
2549 case Intrinsic::x86_avx512_psll_d_512:
2550 case Intrinsic::x86_avx512_psll_q_512:
2551 case Intrinsic::x86_avx512_psll_w_512: {
Sanjay Patel6038d3e2016-01-29 23:27:03 +00002552 if (Value *V = simplifyX86immShift(*II, *Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00002553 return replaceInstUsesWith(*II, V);
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00002554
2555 // SSE2/AVX2 uses only the first 64-bits of the 128-bit vector
2556 // operand to compute the shift amount.
Simon Pilgrim996725e2015-09-19 11:41:53 +00002557 Value *Arg1 = II->getArgOperand(1);
2558 assert(Arg1->getType()->getPrimitiveSizeInBits() == 128 &&
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00002559 "Unexpected packed shift size");
Simon Pilgrim996725e2015-09-19 11:41:53 +00002560 unsigned VWidth = Arg1->getType()->getVectorNumElements();
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00002561
Simon Pilgrim996725e2015-09-19 11:41:53 +00002562 if (Value *V = SimplifyDemandedVectorEltsLow(Arg1, VWidth, VWidth / 2)) {
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00002563 II->setArgOperand(1, V);
2564 return II;
2565 }
2566 break;
2567 }
2568
Simon Pilgrimdb9893f2016-06-07 10:27:15 +00002569 case Intrinsic::x86_avx2_psllv_d:
2570 case Intrinsic::x86_avx2_psllv_d_256:
2571 case Intrinsic::x86_avx2_psllv_q:
2572 case Intrinsic::x86_avx2_psllv_q_256:
Craig Topperb4173a52016-11-13 07:26:19 +00002573 case Intrinsic::x86_avx512_psllv_d_512:
2574 case Intrinsic::x86_avx512_psllv_q_512:
Craig Topper1de753f2016-11-18 06:04:33 +00002575 case Intrinsic::x86_avx512_psllv_w_128:
2576 case Intrinsic::x86_avx512_psllv_w_256:
2577 case Intrinsic::x86_avx512_psllv_w_512:
Simon Pilgrimdb9893f2016-06-07 10:27:15 +00002578 case Intrinsic::x86_avx2_psrav_d:
2579 case Intrinsic::x86_avx2_psrav_d_256:
Craig Topperb4173a52016-11-13 07:26:19 +00002580 case Intrinsic::x86_avx512_psrav_q_128:
2581 case Intrinsic::x86_avx512_psrav_q_256:
2582 case Intrinsic::x86_avx512_psrav_d_512:
2583 case Intrinsic::x86_avx512_psrav_q_512:
Craig Topper1de753f2016-11-18 06:04:33 +00002584 case Intrinsic::x86_avx512_psrav_w_128:
2585 case Intrinsic::x86_avx512_psrav_w_256:
2586 case Intrinsic::x86_avx512_psrav_w_512:
Simon Pilgrimdb9893f2016-06-07 10:27:15 +00002587 case Intrinsic::x86_avx2_psrlv_d:
2588 case Intrinsic::x86_avx2_psrlv_d_256:
2589 case Intrinsic::x86_avx2_psrlv_q:
2590 case Intrinsic::x86_avx2_psrlv_q_256:
Craig Topperb4173a52016-11-13 07:26:19 +00002591 case Intrinsic::x86_avx512_psrlv_d_512:
2592 case Intrinsic::x86_avx512_psrlv_q_512:
Craig Topper1de753f2016-11-18 06:04:33 +00002593 case Intrinsic::x86_avx512_psrlv_w_128:
2594 case Intrinsic::x86_avx512_psrlv_w_256:
2595 case Intrinsic::x86_avx512_psrlv_w_512:
Simon Pilgrimdb9893f2016-06-07 10:27:15 +00002596 if (Value *V = simplifyX86varShift(*II, *Builder))
2597 return replaceInstUsesWith(*II, V);
2598 break;
2599
Simon Pilgrimc9cf7fc2016-12-26 23:28:17 +00002600 case Intrinsic::x86_sse2_pmulu_dq:
2601 case Intrinsic::x86_sse41_pmuldq:
2602 case Intrinsic::x86_avx2_pmul_dq:
Craig Topper72f2d4e2016-12-27 05:30:09 +00002603 case Intrinsic::x86_avx2_pmulu_dq:
2604 case Intrinsic::x86_avx512_pmul_dq_512:
2605 case Intrinsic::x86_avx512_pmulu_dq_512: {
Simon Pilgrimf6f3a3612017-01-23 15:22:59 +00002606 if (Value *V = simplifyX86muldq(*II, *Builder))
Simon Pilgrima50a93f2017-01-20 18:20:30 +00002607 return replaceInstUsesWith(*II, V);
2608
Simon Pilgrimc9cf7fc2016-12-26 23:28:17 +00002609 unsigned VWidth = II->getType()->getVectorNumElements();
2610 APInt UndefElts(VWidth, 0);
2611 APInt DemandedElts = APInt::getAllOnesValue(VWidth);
2612 if (Value *V = SimplifyDemandedVectorElts(II, DemandedElts, UndefElts)) {
2613 if (V != II)
2614 return replaceInstUsesWith(*II, V);
2615 return II;
2616 }
2617 break;
2618 }
2619
Simon Pilgrim6f6b2792017-01-25 14:37:24 +00002620 case Intrinsic::x86_sse2_packssdw_128:
2621 case Intrinsic::x86_sse2_packsswb_128:
2622 case Intrinsic::x86_avx2_packssdw:
2623 case Intrinsic::x86_avx2_packsswb:
Craig Topper3731f4d2017-02-16 07:35:23 +00002624 case Intrinsic::x86_avx512_packssdw_512:
2625 case Intrinsic::x86_avx512_packsswb_512:
Simon Pilgrim6f6b2792017-01-25 14:37:24 +00002626 if (Value *V = simplifyX86pack(*II, *this, *Builder, true))
2627 return replaceInstUsesWith(*II, V);
2628 break;
2629
2630 case Intrinsic::x86_sse2_packuswb_128:
2631 case Intrinsic::x86_sse41_packusdw:
2632 case Intrinsic::x86_avx2_packusdw:
2633 case Intrinsic::x86_avx2_packuswb:
Craig Topper3731f4d2017-02-16 07:35:23 +00002634 case Intrinsic::x86_avx512_packusdw_512:
2635 case Intrinsic::x86_avx512_packuswb_512:
Simon Pilgrim6f6b2792017-01-25 14:37:24 +00002636 if (Value *V = simplifyX86pack(*II, *this, *Builder, false))
2637 return replaceInstUsesWith(*II, V);
2638 break;
2639
Craig Topperb6122122017-01-26 05:17:13 +00002640 case Intrinsic::x86_pclmulqdq: {
2641 if (auto *C = dyn_cast<ConstantInt>(II->getArgOperand(2))) {
2642 unsigned Imm = C->getZExtValue();
2643
2644 bool MadeChange = false;
2645 Value *Arg0 = II->getArgOperand(0);
2646 Value *Arg1 = II->getArgOperand(1);
2647 unsigned VWidth = Arg0->getType()->getVectorNumElements();
2648 APInt DemandedElts(VWidth, 0);
2649
2650 APInt UndefElts1(VWidth, 0);
2651 DemandedElts = (Imm & 0x01) ? 2 : 1;
2652 if (Value *V = SimplifyDemandedVectorElts(Arg0, DemandedElts,
2653 UndefElts1)) {
2654 II->setArgOperand(0, V);
2655 MadeChange = true;
2656 }
2657
2658 APInt UndefElts2(VWidth, 0);
2659 DemandedElts = (Imm & 0x10) ? 2 : 1;
2660 if (Value *V = SimplifyDemandedVectorElts(Arg1, DemandedElts,
2661 UndefElts2)) {
2662 II->setArgOperand(1, V);
2663 MadeChange = true;
2664 }
2665
2666 // If both input elements are undef, the result is undef.
2667 if (UndefElts1[(Imm & 0x01) ? 1 : 0] ||
2668 UndefElts2[(Imm & 0x10) ? 1 : 0])
2669 return replaceInstUsesWith(*II,
2670 ConstantAggregateZero::get(II->getType()));
2671
2672 if (MadeChange)
2673 return II;
2674 }
2675 break;
2676 }
2677
Sanjay Patelc86867c2015-04-16 17:52:13 +00002678 case Intrinsic::x86_sse41_insertps:
Sanjay Patel6038d3e2016-01-29 23:27:03 +00002679 if (Value *V = simplifyX86insertps(*II, *Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00002680 return replaceInstUsesWith(*II, V);
Sanjay Patelc86867c2015-04-16 17:52:13 +00002681 break;
Simon Pilgrim54fcd622015-07-25 20:41:00 +00002682
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002683 case Intrinsic::x86_sse4a_extrq: {
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002684 Value *Op0 = II->getArgOperand(0);
2685 Value *Op1 = II->getArgOperand(1);
2686 unsigned VWidth0 = Op0->getType()->getVectorNumElements();
2687 unsigned VWidth1 = Op1->getType()->getVectorNumElements();
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002688 assert(Op0->getType()->getPrimitiveSizeInBits() == 128 &&
2689 Op1->getType()->getPrimitiveSizeInBits() == 128 && VWidth0 == 2 &&
2690 VWidth1 == 16 && "Unexpected operand sizes");
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002691
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002692 // See if we're dealing with constant values.
2693 Constant *C1 = dyn_cast<Constant>(Op1);
2694 ConstantInt *CILength =
Andrea Di Biagio8df5b9c2016-09-07 12:03:03 +00002695 C1 ? dyn_cast_or_null<ConstantInt>(C1->getAggregateElement((unsigned)0))
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002696 : nullptr;
2697 ConstantInt *CIIndex =
Andrea Di Biagio8df5b9c2016-09-07 12:03:03 +00002698 C1 ? dyn_cast_or_null<ConstantInt>(C1->getAggregateElement((unsigned)1))
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002699 : nullptr;
2700
2701 // Attempt to simplify to a constant, shuffle vector or EXTRQI call.
Sanjay Patel6038d3e2016-01-29 23:27:03 +00002702 if (Value *V = simplifyX86extrq(*II, Op0, CILength, CIIndex, *Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00002703 return replaceInstUsesWith(*II, V);
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002704
2705 // EXTRQ only uses the lowest 64-bits of the first 128-bit vector
2706 // operands and the lowest 16-bits of the second.
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002707 bool MadeChange = false;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002708 if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth0, 1)) {
2709 II->setArgOperand(0, V);
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002710 MadeChange = true;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002711 }
2712 if (Value *V = SimplifyDemandedVectorEltsLow(Op1, VWidth1, 2)) {
2713 II->setArgOperand(1, V);
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002714 MadeChange = true;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002715 }
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002716 if (MadeChange)
2717 return II;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002718 break;
2719 }
2720
2721 case Intrinsic::x86_sse4a_extrqi: {
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002722 // EXTRQI: Extract Length bits starting from Index. Zero pad the remaining
2723 // bits of the lower 64-bits. The upper 64-bits are undefined.
2724 Value *Op0 = II->getArgOperand(0);
2725 unsigned VWidth = Op0->getType()->getVectorNumElements();
2726 assert(Op0->getType()->getPrimitiveSizeInBits() == 128 && VWidth == 2 &&
2727 "Unexpected operand size");
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002728
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002729 // See if we're dealing with constant values.
2730 ConstantInt *CILength = dyn_cast<ConstantInt>(II->getArgOperand(1));
2731 ConstantInt *CIIndex = dyn_cast<ConstantInt>(II->getArgOperand(2));
2732
2733 // Attempt to simplify to a constant or shuffle vector.
Sanjay Patel6038d3e2016-01-29 23:27:03 +00002734 if (Value *V = simplifyX86extrq(*II, Op0, CILength, CIIndex, *Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00002735 return replaceInstUsesWith(*II, V);
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002736
2737 // EXTRQI only uses the lowest 64-bits of the first 128-bit vector
2738 // operand.
2739 if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth, 1)) {
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002740 II->setArgOperand(0, V);
2741 return II;
2742 }
2743 break;
2744 }
2745
2746 case Intrinsic::x86_sse4a_insertq: {
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002747 Value *Op0 = II->getArgOperand(0);
2748 Value *Op1 = II->getArgOperand(1);
2749 unsigned VWidth = Op0->getType()->getVectorNumElements();
2750 assert(Op0->getType()->getPrimitiveSizeInBits() == 128 &&
2751 Op1->getType()->getPrimitiveSizeInBits() == 128 && VWidth == 2 &&
2752 Op1->getType()->getVectorNumElements() == 2 &&
2753 "Unexpected operand size");
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002754
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002755 // See if we're dealing with constant values.
2756 Constant *C1 = dyn_cast<Constant>(Op1);
2757 ConstantInt *CI11 =
Andrea Di Biagiof3fd3162016-09-07 12:47:53 +00002758 C1 ? dyn_cast_or_null<ConstantInt>(C1->getAggregateElement((unsigned)1))
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002759 : nullptr;
2760
2761 // Attempt to simplify to a constant, shuffle vector or INSERTQI call.
2762 if (CI11) {
Benjamin Kramer46e38f32016-06-08 10:01:20 +00002763 const APInt &V11 = CI11->getValue();
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002764 APInt Len = V11.zextOrTrunc(6);
2765 APInt Idx = V11.lshr(8).zextOrTrunc(6);
Sanjay Patel6038d3e2016-01-29 23:27:03 +00002766 if (Value *V = simplifyX86insertq(*II, Op0, Op1, Len, Idx, *Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00002767 return replaceInstUsesWith(*II, V);
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002768 }
2769
2770 // INSERTQ only uses the lowest 64-bits of the first 128-bit vector
2771 // operand.
2772 if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth, 1)) {
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002773 II->setArgOperand(0, V);
2774 return II;
2775 }
2776 break;
2777 }
2778
Filipe Cabecinhas1a805952014-04-24 00:38:14 +00002779 case Intrinsic::x86_sse4a_insertqi: {
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002780 // INSERTQI: Extract lowest Length bits from lower half of second source and
2781 // insert over first source starting at Index bit. The upper 64-bits are
2782 // undefined.
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002783 Value *Op0 = II->getArgOperand(0);
2784 Value *Op1 = II->getArgOperand(1);
2785 unsigned VWidth0 = Op0->getType()->getVectorNumElements();
2786 unsigned VWidth1 = Op1->getType()->getVectorNumElements();
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002787 assert(Op0->getType()->getPrimitiveSizeInBits() == 128 &&
2788 Op1->getType()->getPrimitiveSizeInBits() == 128 && VWidth0 == 2 &&
2789 VWidth1 == 2 && "Unexpected operand sizes");
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002790
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002791 // See if we're dealing with constant values.
2792 ConstantInt *CILength = dyn_cast<ConstantInt>(II->getArgOperand(2));
2793 ConstantInt *CIIndex = dyn_cast<ConstantInt>(II->getArgOperand(3));
2794
2795 // Attempt to simplify to a constant or shuffle vector.
2796 if (CILength && CIIndex) {
2797 APInt Len = CILength->getValue().zextOrTrunc(6);
2798 APInt Idx = CIIndex->getValue().zextOrTrunc(6);
Sanjay Patel6038d3e2016-01-29 23:27:03 +00002799 if (Value *V = simplifyX86insertq(*II, Op0, Op1, Len, Idx, *Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00002800 return replaceInstUsesWith(*II, V);
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002801 }
2802
2803 // INSERTQI only uses the lowest 64-bits of the first two 128-bit vector
2804 // operands.
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002805 bool MadeChange = false;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002806 if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth0, 1)) {
2807 II->setArgOperand(0, V);
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002808 MadeChange = true;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002809 }
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002810 if (Value *V = SimplifyDemandedVectorEltsLow(Op1, VWidth1, 1)) {
2811 II->setArgOperand(1, V);
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002812 MadeChange = true;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002813 }
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002814 if (MadeChange)
2815 return II;
Filipe Cabecinhas1a805952014-04-24 00:38:14 +00002816 break;
2817 }
2818
Filipe Cabecinhas82ac07c2014-05-27 03:42:20 +00002819 case Intrinsic::x86_sse41_pblendvb:
2820 case Intrinsic::x86_sse41_blendvps:
2821 case Intrinsic::x86_sse41_blendvpd:
2822 case Intrinsic::x86_avx_blendv_ps_256:
2823 case Intrinsic::x86_avx_blendv_pd_256:
2824 case Intrinsic::x86_avx2_pblendvb: {
2825 // Convert blendv* to vector selects if the mask is constant.
2826 // This optimization is convoluted because the intrinsic is defined as
2827 // getting a vector of floats or doubles for the ps and pd versions.
2828 // FIXME: That should be changed.
Simon Pilgrim8c049d52015-08-12 08:08:56 +00002829
2830 Value *Op0 = II->getArgOperand(0);
2831 Value *Op1 = II->getArgOperand(1);
Filipe Cabecinhas82ac07c2014-05-27 03:42:20 +00002832 Value *Mask = II->getArgOperand(2);
Simon Pilgrim8c049d52015-08-12 08:08:56 +00002833
2834 // fold (blend A, A, Mask) -> A
2835 if (Op0 == Op1)
Sanjay Patel4b198802016-02-01 22:23:39 +00002836 return replaceInstUsesWith(CI, Op0);
Simon Pilgrim8c049d52015-08-12 08:08:56 +00002837
2838 // Zero Mask - select 1st argument.
Simon Pilgrim93f59f52015-08-12 08:23:36 +00002839 if (isa<ConstantAggregateZero>(Mask))
Sanjay Patel4b198802016-02-01 22:23:39 +00002840 return replaceInstUsesWith(CI, Op0);
Simon Pilgrim8c049d52015-08-12 08:08:56 +00002841
2842 // Constant Mask - select 1st/2nd argument lane based on top bit of mask.
Sanjay Patel368ac5d2016-02-21 17:29:33 +00002843 if (auto *ConstantMask = dyn_cast<ConstantDataVector>(Mask)) {
2844 Constant *NewSelector = getNegativeIsTrueBoolVec(ConstantMask);
Simon Pilgrim8c049d52015-08-12 08:08:56 +00002845 return SelectInst::Create(NewSelector, Op1, Op0, "blendv");
Filipe Cabecinhas82ac07c2014-05-27 03:42:20 +00002846 }
Simon Pilgrim8c049d52015-08-12 08:08:56 +00002847 break;
Filipe Cabecinhas82ac07c2014-05-27 03:42:20 +00002848 }
2849
Andrea Di Biagio0594e2a2015-09-30 16:44:39 +00002850 case Intrinsic::x86_ssse3_pshuf_b_128:
Simon Pilgrimc0c56e72016-04-24 17:00:34 +00002851 case Intrinsic::x86_avx2_pshuf_b:
Simon Pilgrima22c3a12017-01-18 13:44:04 +00002852 case Intrinsic::x86_avx512_pshuf_b_512:
Simon Pilgrimc0c56e72016-04-24 17:00:34 +00002853 if (Value *V = simplifyX86pshufb(*II, *Builder))
2854 return replaceInstUsesWith(*II, V);
2855 break;
Andrea Di Biagio0594e2a2015-09-30 16:44:39 +00002856
Rafael Espindolabad3f772014-04-21 22:06:04 +00002857 case Intrinsic::x86_avx_vpermilvar_ps:
2858 case Intrinsic::x86_avx_vpermilvar_ps_256:
Craig Topper58917f32016-12-11 01:59:36 +00002859 case Intrinsic::x86_avx512_vpermilvar_ps_512:
Rafael Espindolabad3f772014-04-21 22:06:04 +00002860 case Intrinsic::x86_avx_vpermilvar_pd:
Simon Pilgrim2f6097d2016-04-24 17:23:46 +00002861 case Intrinsic::x86_avx_vpermilvar_pd_256:
Simon Pilgrima22c3a12017-01-18 13:44:04 +00002862 case Intrinsic::x86_avx512_vpermilvar_pd_512:
Simon Pilgrim2f6097d2016-04-24 17:23:46 +00002863 if (Value *V = simplifyX86vpermilvar(*II, *Builder))
2864 return replaceInstUsesWith(*II, V);
2865 break;
Rafael Espindolabad3f772014-04-21 22:06:04 +00002866
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +00002867 case Intrinsic::x86_avx2_permd:
2868 case Intrinsic::x86_avx2_permps:
2869 if (Value *V = simplifyX86vpermv(*II, *Builder))
2870 return replaceInstUsesWith(*II, V);
2871 break;
2872
Craig Toppere3280452016-12-25 23:58:57 +00002873 case Intrinsic::x86_avx512_mask_permvar_df_256:
2874 case Intrinsic::x86_avx512_mask_permvar_df_512:
2875 case Intrinsic::x86_avx512_mask_permvar_di_256:
2876 case Intrinsic::x86_avx512_mask_permvar_di_512:
2877 case Intrinsic::x86_avx512_mask_permvar_hi_128:
2878 case Intrinsic::x86_avx512_mask_permvar_hi_256:
2879 case Intrinsic::x86_avx512_mask_permvar_hi_512:
2880 case Intrinsic::x86_avx512_mask_permvar_qi_128:
2881 case Intrinsic::x86_avx512_mask_permvar_qi_256:
2882 case Intrinsic::x86_avx512_mask_permvar_qi_512:
2883 case Intrinsic::x86_avx512_mask_permvar_sf_256:
2884 case Intrinsic::x86_avx512_mask_permvar_sf_512:
2885 case Intrinsic::x86_avx512_mask_permvar_si_256:
2886 case Intrinsic::x86_avx512_mask_permvar_si_512:
2887 if (Value *V = simplifyX86vpermv(*II, *Builder)) {
2888 // We simplified the permuting, now create a select for the masking.
2889 V = emitX86MaskSelect(II->getArgOperand(3), V, II->getArgOperand(2),
2890 *Builder);
2891 return replaceInstUsesWith(*II, V);
2892 }
2893 break;
2894
Sanjay Patelccf5f242015-03-20 21:47:56 +00002895 case Intrinsic::x86_avx_vperm2f128_pd_256:
2896 case Intrinsic::x86_avx_vperm2f128_ps_256:
2897 case Intrinsic::x86_avx_vperm2f128_si_256:
Sanjay Patele304bea2015-03-24 22:39:29 +00002898 case Intrinsic::x86_avx2_vperm2i128:
Sanjay Patel6038d3e2016-01-29 23:27:03 +00002899 if (Value *V = simplifyX86vperm2(*II, *Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00002900 return replaceInstUsesWith(*II, V);
Sanjay Patelccf5f242015-03-20 21:47:56 +00002901 break;
2902
Sanjay Patel98a71502016-02-29 23:16:48 +00002903 case Intrinsic::x86_avx_maskload_ps:
Sanjay Patel6f2c01f2016-02-29 23:59:00 +00002904 case Intrinsic::x86_avx_maskload_pd:
2905 case Intrinsic::x86_avx_maskload_ps_256:
2906 case Intrinsic::x86_avx_maskload_pd_256:
2907 case Intrinsic::x86_avx2_maskload_d:
2908 case Intrinsic::x86_avx2_maskload_q:
2909 case Intrinsic::x86_avx2_maskload_d_256:
2910 case Intrinsic::x86_avx2_maskload_q_256:
Sanjay Patel98a71502016-02-29 23:16:48 +00002911 if (Instruction *I = simplifyX86MaskedLoad(*II, *this))
2912 return I;
2913 break;
2914
Sanjay Patelc4acbae2016-03-12 15:16:59 +00002915 case Intrinsic::x86_sse2_maskmov_dqu:
Sanjay Patel1ace9932016-02-26 21:04:14 +00002916 case Intrinsic::x86_avx_maskstore_ps:
2917 case Intrinsic::x86_avx_maskstore_pd:
2918 case Intrinsic::x86_avx_maskstore_ps_256:
2919 case Intrinsic::x86_avx_maskstore_pd_256:
Sanjay Patelfc7e7eb2016-02-26 21:51:44 +00002920 case Intrinsic::x86_avx2_maskstore_d:
2921 case Intrinsic::x86_avx2_maskstore_q:
2922 case Intrinsic::x86_avx2_maskstore_d_256:
2923 case Intrinsic::x86_avx2_maskstore_q_256:
Sanjay Patel1ace9932016-02-26 21:04:14 +00002924 if (simplifyX86MaskedStore(*II, *this))
2925 return nullptr;
2926 break;
2927
Simon Pilgrim1d1c56e22015-10-11 14:38:34 +00002928 case Intrinsic::x86_xop_vpcomb:
2929 case Intrinsic::x86_xop_vpcomd:
2930 case Intrinsic::x86_xop_vpcomq:
2931 case Intrinsic::x86_xop_vpcomw:
Sanjay Patel6038d3e2016-01-29 23:27:03 +00002932 if (Value *V = simplifyX86vpcom(*II, *Builder, true))
Sanjay Patel4b198802016-02-01 22:23:39 +00002933 return replaceInstUsesWith(*II, V);
Simon Pilgrim1d1c56e22015-10-11 14:38:34 +00002934 break;
2935
2936 case Intrinsic::x86_xop_vpcomub:
2937 case Intrinsic::x86_xop_vpcomud:
2938 case Intrinsic::x86_xop_vpcomuq:
2939 case Intrinsic::x86_xop_vpcomuw:
Sanjay Patel6038d3e2016-01-29 23:27:03 +00002940 if (Value *V = simplifyX86vpcom(*II, *Builder, false))
Sanjay Patel4b198802016-02-01 22:23:39 +00002941 return replaceInstUsesWith(*II, V);
Simon Pilgrim1d1c56e22015-10-11 14:38:34 +00002942 break;
2943
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002944 case Intrinsic::ppc_altivec_vperm:
2945 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
Bill Schmidta1184632014-06-05 19:46:04 +00002946 // Note that ppc_altivec_vperm has a big-endian bias, so when creating
2947 // a vectorshuffle for little endian, we must undo the transformation
2948 // performed on vec_perm in altivec.h. That is, we must complement
2949 // the permutation mask with respect to 31 and reverse the order of
2950 // V1 and V2.
Chris Lattner0256be92012-01-27 03:08:05 +00002951 if (Constant *Mask = dyn_cast<Constant>(II->getArgOperand(2))) {
2952 assert(Mask->getType()->getVectorNumElements() == 16 &&
2953 "Bad type for intrinsic!");
Jim Grosbach7815f562012-02-03 00:07:04 +00002954
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002955 // Check that all of the elements are integer constants or undefs.
2956 bool AllEltsOk = true;
2957 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0256be92012-01-27 03:08:05 +00002958 Constant *Elt = Mask->getAggregateElement(i);
Craig Topperf40110f2014-04-25 05:29:35 +00002959 if (!Elt || !(isa<ConstantInt>(Elt) || isa<UndefValue>(Elt))) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002960 AllEltsOk = false;
2961 break;
2962 }
2963 }
Jim Grosbach7815f562012-02-03 00:07:04 +00002964
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002965 if (AllEltsOk) {
2966 // Cast the input vectors to byte vectors.
Gabor Greif3e44ea12010-07-22 10:37:47 +00002967 Value *Op0 = Builder->CreateBitCast(II->getArgOperand(0),
2968 Mask->getType());
2969 Value *Op1 = Builder->CreateBitCast(II->getArgOperand(1),
2970 Mask->getType());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002971 Value *Result = UndefValue::get(Op0->getType());
Jim Grosbach7815f562012-02-03 00:07:04 +00002972
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002973 // Only extract each element once.
2974 Value *ExtractedElts[32];
2975 memset(ExtractedElts, 0, sizeof(ExtractedElts));
Jim Grosbach7815f562012-02-03 00:07:04 +00002976
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002977 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0256be92012-01-27 03:08:05 +00002978 if (isa<UndefValue>(Mask->getAggregateElement(i)))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002979 continue;
Jim Grosbach7815f562012-02-03 00:07:04 +00002980 unsigned Idx =
Chris Lattner0256be92012-01-27 03:08:05 +00002981 cast<ConstantInt>(Mask->getAggregateElement(i))->getZExtValue();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002982 Idx &= 31; // Match the hardware behavior.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002983 if (DL.isLittleEndian())
Bill Schmidta1184632014-06-05 19:46:04 +00002984 Idx = 31 - Idx;
Jim Grosbach7815f562012-02-03 00:07:04 +00002985
Craig Topperf40110f2014-04-25 05:29:35 +00002986 if (!ExtractedElts[Idx]) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002987 Value *Op0ToUse = (DL.isLittleEndian()) ? Op1 : Op0;
2988 Value *Op1ToUse = (DL.isLittleEndian()) ? Op0 : Op1;
Jim Grosbach7815f562012-02-03 00:07:04 +00002989 ExtractedElts[Idx] =
Bill Schmidta1184632014-06-05 19:46:04 +00002990 Builder->CreateExtractElement(Idx < 16 ? Op0ToUse : Op1ToUse,
Benjamin Kramer547b6c52011-09-27 20:39:19 +00002991 Builder->getInt32(Idx&15));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002992 }
Jim Grosbach7815f562012-02-03 00:07:04 +00002993
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002994 // Insert this value into the result vector.
2995 Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
Benjamin Kramer547b6c52011-09-27 20:39:19 +00002996 Builder->getInt32(i));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002997 }
2998 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
2999 }
3000 }
3001 break;
3002
Bob Wilsona4e231c2010-10-22 21:41:48 +00003003 case Intrinsic::arm_neon_vld1:
3004 case Intrinsic::arm_neon_vld2:
3005 case Intrinsic::arm_neon_vld3:
3006 case Intrinsic::arm_neon_vld4:
3007 case Intrinsic::arm_neon_vld2lane:
3008 case Intrinsic::arm_neon_vld3lane:
3009 case Intrinsic::arm_neon_vld4lane:
3010 case Intrinsic::arm_neon_vst1:
3011 case Intrinsic::arm_neon_vst2:
3012 case Intrinsic::arm_neon_vst3:
3013 case Intrinsic::arm_neon_vst4:
3014 case Intrinsic::arm_neon_vst2lane:
3015 case Intrinsic::arm_neon_vst3lane:
3016 case Intrinsic::arm_neon_vst4lane: {
Justin Bogner99798402016-08-05 01:06:44 +00003017 unsigned MemAlign =
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003018 getKnownAlignment(II->getArgOperand(0), DL, II, &AC, &DT);
Bob Wilsona4e231c2010-10-22 21:41:48 +00003019 unsigned AlignArg = II->getNumArgOperands() - 1;
3020 ConstantInt *IntrAlign = dyn_cast<ConstantInt>(II->getArgOperand(AlignArg));
3021 if (IntrAlign && IntrAlign->getZExtValue() < MemAlign) {
3022 II->setArgOperand(AlignArg,
3023 ConstantInt::get(Type::getInt32Ty(II->getContext()),
3024 MemAlign, false));
3025 return II;
3026 }
3027 break;
3028 }
3029
Lang Hames3a90fab2012-05-01 00:20:38 +00003030 case Intrinsic::arm_neon_vmulls:
Tim Northover00ed9962014-03-29 10:18:08 +00003031 case Intrinsic::arm_neon_vmullu:
Tim Northover3b0846e2014-05-24 12:50:23 +00003032 case Intrinsic::aarch64_neon_smull:
3033 case Intrinsic::aarch64_neon_umull: {
Lang Hames3a90fab2012-05-01 00:20:38 +00003034 Value *Arg0 = II->getArgOperand(0);
3035 Value *Arg1 = II->getArgOperand(1);
3036
3037 // Handle mul by zero first:
3038 if (isa<ConstantAggregateZero>(Arg0) || isa<ConstantAggregateZero>(Arg1)) {
Sanjay Patel4b198802016-02-01 22:23:39 +00003039 return replaceInstUsesWith(CI, ConstantAggregateZero::get(II->getType()));
Lang Hames3a90fab2012-05-01 00:20:38 +00003040 }
3041
3042 // Check for constant LHS & RHS - in this case we just simplify.
Tim Northover00ed9962014-03-29 10:18:08 +00003043 bool Zext = (II->getIntrinsicID() == Intrinsic::arm_neon_vmullu ||
Tim Northover3b0846e2014-05-24 12:50:23 +00003044 II->getIntrinsicID() == Intrinsic::aarch64_neon_umull);
Lang Hames3a90fab2012-05-01 00:20:38 +00003045 VectorType *NewVT = cast<VectorType>(II->getType());
Benjamin Kramer92040952014-02-13 18:23:24 +00003046 if (Constant *CV0 = dyn_cast<Constant>(Arg0)) {
3047 if (Constant *CV1 = dyn_cast<Constant>(Arg1)) {
3048 CV0 = ConstantExpr::getIntegerCast(CV0, NewVT, /*isSigned=*/!Zext);
3049 CV1 = ConstantExpr::getIntegerCast(CV1, NewVT, /*isSigned=*/!Zext);
3050
Sanjay Patel4b198802016-02-01 22:23:39 +00003051 return replaceInstUsesWith(CI, ConstantExpr::getMul(CV0, CV1));
Lang Hames3a90fab2012-05-01 00:20:38 +00003052 }
3053
Alp Tokercb402912014-01-24 17:20:08 +00003054 // Couldn't simplify - canonicalize constant to the RHS.
Lang Hames3a90fab2012-05-01 00:20:38 +00003055 std::swap(Arg0, Arg1);
3056 }
3057
3058 // Handle mul by one:
Benjamin Kramer92040952014-02-13 18:23:24 +00003059 if (Constant *CV1 = dyn_cast<Constant>(Arg1))
Lang Hames3a90fab2012-05-01 00:20:38 +00003060 if (ConstantInt *Splat =
Benjamin Kramer92040952014-02-13 18:23:24 +00003061 dyn_cast_or_null<ConstantInt>(CV1->getSplatValue()))
3062 if (Splat->isOne())
3063 return CastInst::CreateIntegerCast(Arg0, II->getType(),
3064 /*isSigned=*/!Zext);
Lang Hames3a90fab2012-05-01 00:20:38 +00003065
3066 break;
3067 }
3068
Matt Arsenaultbef34e22016-01-22 21:30:34 +00003069 case Intrinsic::amdgcn_rcp: {
Matt Arsenaulta0050b02014-06-19 01:19:19 +00003070 if (const ConstantFP *C = dyn_cast<ConstantFP>(II->getArgOperand(0))) {
3071 const APFloat &ArgVal = C->getValueAPF();
3072 APFloat Val(ArgVal.getSemantics(), 1.0);
3073 APFloat::opStatus Status = Val.divide(ArgVal,
3074 APFloat::rmNearestTiesToEven);
3075 // Only do this if it was exact and therefore not dependent on the
3076 // rounding mode.
3077 if (Status == APFloat::opOK)
Sanjay Patel4b198802016-02-01 22:23:39 +00003078 return replaceInstUsesWith(CI, ConstantFP::get(II->getContext(), Val));
Matt Arsenaulta0050b02014-06-19 01:19:19 +00003079 }
3080
3081 break;
3082 }
Matt Arsenault2fe4fbc2016-03-30 22:28:52 +00003083 case Intrinsic::amdgcn_frexp_mant:
3084 case Intrinsic::amdgcn_frexp_exp: {
Matt Arsenault5cd4f8f2016-03-30 22:28:26 +00003085 Value *Src = II->getArgOperand(0);
3086 if (const ConstantFP *C = dyn_cast<ConstantFP>(Src)) {
3087 int Exp;
3088 APFloat Significand = frexp(C->getValueAPF(), Exp,
3089 APFloat::rmNearestTiesToEven);
3090
Matt Arsenault2fe4fbc2016-03-30 22:28:52 +00003091 if (II->getIntrinsicID() == Intrinsic::amdgcn_frexp_mant) {
3092 return replaceInstUsesWith(CI, ConstantFP::get(II->getContext(),
3093 Significand));
3094 }
3095
3096 // Match instruction special case behavior.
3097 if (Exp == APFloat::IEK_NaN || Exp == APFloat::IEK_Inf)
3098 Exp = 0;
3099
3100 return replaceInstUsesWith(CI, ConstantInt::get(II->getType(), Exp));
3101 }
3102
3103 if (isa<UndefValue>(Src))
3104 return replaceInstUsesWith(CI, UndefValue::get(II->getType()));
Matt Arsenault5cd4f8f2016-03-30 22:28:26 +00003105
3106 break;
3107 }
Matt Arsenault46a03822016-09-03 07:06:58 +00003108 case Intrinsic::amdgcn_class: {
3109 enum {
3110 S_NAN = 1 << 0, // Signaling NaN
3111 Q_NAN = 1 << 1, // Quiet NaN
3112 N_INFINITY = 1 << 2, // Negative infinity
3113 N_NORMAL = 1 << 3, // Negative normal
3114 N_SUBNORMAL = 1 << 4, // Negative subnormal
3115 N_ZERO = 1 << 5, // Negative zero
3116 P_ZERO = 1 << 6, // Positive zero
3117 P_SUBNORMAL = 1 << 7, // Positive subnormal
3118 P_NORMAL = 1 << 8, // Positive normal
3119 P_INFINITY = 1 << 9 // Positive infinity
3120 };
3121
3122 const uint32_t FullMask = S_NAN | Q_NAN | N_INFINITY | N_NORMAL |
3123 N_SUBNORMAL | N_ZERO | P_ZERO | P_SUBNORMAL | P_NORMAL | P_INFINITY;
3124
3125 Value *Src0 = II->getArgOperand(0);
3126 Value *Src1 = II->getArgOperand(1);
3127 const ConstantInt *CMask = dyn_cast<ConstantInt>(Src1);
3128 if (!CMask) {
3129 if (isa<UndefValue>(Src0))
3130 return replaceInstUsesWith(*II, UndefValue::get(II->getType()));
3131
3132 if (isa<UndefValue>(Src1))
3133 return replaceInstUsesWith(*II, ConstantInt::get(II->getType(), false));
3134 break;
3135 }
3136
3137 uint32_t Mask = CMask->getZExtValue();
3138
3139 // If all tests are made, it doesn't matter what the value is.
3140 if ((Mask & FullMask) == FullMask)
3141 return replaceInstUsesWith(*II, ConstantInt::get(II->getType(), true));
3142
3143 if ((Mask & FullMask) == 0)
3144 return replaceInstUsesWith(*II, ConstantInt::get(II->getType(), false));
3145
3146 if (Mask == (S_NAN | Q_NAN)) {
3147 // Equivalent of isnan. Replace with standard fcmp.
3148 Value *FCmp = Builder->CreateFCmpUNO(Src0, Src0);
3149 FCmp->takeName(II);
3150 return replaceInstUsesWith(*II, FCmp);
3151 }
3152
3153 const ConstantFP *CVal = dyn_cast<ConstantFP>(Src0);
3154 if (!CVal) {
3155 if (isa<UndefValue>(Src0))
3156 return replaceInstUsesWith(*II, UndefValue::get(II->getType()));
3157
3158 // Clamp mask to used bits
3159 if ((Mask & FullMask) != Mask) {
3160 CallInst *NewCall = Builder->CreateCall(II->getCalledFunction(),
3161 { Src0, ConstantInt::get(Src1->getType(), Mask & FullMask) }
3162 );
3163
3164 NewCall->takeName(II);
3165 return replaceInstUsesWith(*II, NewCall);
3166 }
3167
3168 break;
3169 }
3170
3171 const APFloat &Val = CVal->getValueAPF();
3172
3173 bool Result =
3174 ((Mask & S_NAN) && Val.isNaN() && Val.isSignaling()) ||
3175 ((Mask & Q_NAN) && Val.isNaN() && !Val.isSignaling()) ||
3176 ((Mask & N_INFINITY) && Val.isInfinity() && Val.isNegative()) ||
3177 ((Mask & N_NORMAL) && Val.isNormal() && Val.isNegative()) ||
3178 ((Mask & N_SUBNORMAL) && Val.isDenormal() && Val.isNegative()) ||
3179 ((Mask & N_ZERO) && Val.isZero() && Val.isNegative()) ||
3180 ((Mask & P_ZERO) && Val.isZero() && !Val.isNegative()) ||
3181 ((Mask & P_SUBNORMAL) && Val.isDenormal() && !Val.isNegative()) ||
3182 ((Mask & P_NORMAL) && Val.isNormal() && !Val.isNegative()) ||
3183 ((Mask & P_INFINITY) && Val.isInfinity() && !Val.isNegative());
3184
3185 return replaceInstUsesWith(*II, ConstantInt::get(II->getType(), Result));
3186 }
Matt Arsenault1f17c662017-02-22 00:27:34 +00003187 case Intrinsic::amdgcn_cvt_pkrtz: {
3188 Value *Src0 = II->getArgOperand(0);
3189 Value *Src1 = II->getArgOperand(1);
3190 if (const ConstantFP *C0 = dyn_cast<ConstantFP>(Src0)) {
3191 if (const ConstantFP *C1 = dyn_cast<ConstantFP>(Src1)) {
3192 const fltSemantics &HalfSem
3193 = II->getType()->getScalarType()->getFltSemantics();
3194 bool LosesInfo;
3195 APFloat Val0 = C0->getValueAPF();
3196 APFloat Val1 = C1->getValueAPF();
3197 Val0.convert(HalfSem, APFloat::rmTowardZero, &LosesInfo);
3198 Val1.convert(HalfSem, APFloat::rmTowardZero, &LosesInfo);
3199
3200 Constant *Folded = ConstantVector::get({
3201 ConstantFP::get(II->getContext(), Val0),
3202 ConstantFP::get(II->getContext(), Val1) });
3203 return replaceInstUsesWith(*II, Folded);
3204 }
3205 }
3206
3207 if (isa<UndefValue>(Src0) && isa<UndefValue>(Src1))
3208 return replaceInstUsesWith(*II, UndefValue::get(II->getType()));
3209
3210 break;
3211 }
Matt Arsenaultf5262252017-02-22 23:04:58 +00003212 case Intrinsic::amdgcn_ubfe:
3213 case Intrinsic::amdgcn_sbfe: {
3214 // Decompose simple cases into standard shifts.
3215 Value *Src = II->getArgOperand(0);
3216 if (isa<UndefValue>(Src))
3217 return replaceInstUsesWith(*II, Src);
3218
3219 unsigned Width;
3220 Type *Ty = II->getType();
3221 unsigned IntSize = Ty->getIntegerBitWidth();
3222
3223 ConstantInt *CWidth = dyn_cast<ConstantInt>(II->getArgOperand(2));
3224 if (CWidth) {
3225 Width = CWidth->getZExtValue();
3226 if ((Width & (IntSize - 1)) == 0)
3227 return replaceInstUsesWith(*II, ConstantInt::getNullValue(Ty));
3228
3229 if (Width >= IntSize) {
3230 // Hardware ignores high bits, so remove those.
3231 II->setArgOperand(2, ConstantInt::get(CWidth->getType(),
3232 Width & (IntSize - 1)));
3233 return II;
3234 }
3235 }
3236
3237 unsigned Offset;
3238 ConstantInt *COffset = dyn_cast<ConstantInt>(II->getArgOperand(1));
3239 if (COffset) {
3240 Offset = COffset->getZExtValue();
3241 if (Offset >= IntSize) {
3242 II->setArgOperand(1, ConstantInt::get(COffset->getType(),
3243 Offset & (IntSize - 1)));
3244 return II;
3245 }
3246 }
3247
3248 bool Signed = II->getIntrinsicID() == Intrinsic::amdgcn_sbfe;
3249
3250 // TODO: Also emit sub if only width is constant.
3251 if (!CWidth && COffset && Offset == 0) {
3252 Constant *KSize = ConstantInt::get(COffset->getType(), IntSize);
3253 Value *ShiftVal = Builder->CreateSub(KSize, II->getArgOperand(2));
3254 ShiftVal = Builder->CreateZExt(ShiftVal, II->getType());
3255
3256 Value *Shl = Builder->CreateShl(Src, ShiftVal);
3257 Value *RightShift = Signed ?
3258 Builder->CreateAShr(Shl, ShiftVal) :
3259 Builder->CreateLShr(Shl, ShiftVal);
3260 RightShift->takeName(II);
3261 return replaceInstUsesWith(*II, RightShift);
3262 }
3263
3264 if (!CWidth || !COffset)
3265 break;
3266
3267 // TODO: This allows folding to undef when the hardware has specific
3268 // behavior?
3269 if (Offset + Width < IntSize) {
3270 Value *Shl = Builder->CreateShl(Src, IntSize - Offset - Width);
3271 Value *RightShift = Signed ?
3272 Builder->CreateAShr(Shl, IntSize - Width) :
3273 Builder->CreateLShr(Shl, IntSize - Width);
3274 RightShift->takeName(II);
3275 return replaceInstUsesWith(*II, RightShift);
3276 }
3277
3278 Value *RightShift = Signed ?
3279 Builder->CreateAShr(Src, Offset) :
3280 Builder->CreateLShr(Src, Offset);
3281
3282 RightShift->takeName(II);
3283 return replaceInstUsesWith(*II, RightShift);
3284 }
Matt Arsenaultd4bca1e2017-02-23 00:44:03 +00003285 case Intrinsic::amdgcn_exp:
3286 case Intrinsic::amdgcn_exp_compr: {
3287 ConstantInt *En = dyn_cast<ConstantInt>(II->getArgOperand(1));
3288 if (!En) // Illegal.
3289 break;
3290
3291 unsigned EnBits = En->getZExtValue();
3292 if (EnBits == 0xf)
3293 break; // All inputs enabled.
3294
3295 bool IsCompr = II->getIntrinsicID() == Intrinsic::amdgcn_exp_compr;
3296 bool Changed = false;
3297 for (int I = 0; I < (IsCompr ? 2 : 4); ++I) {
3298 if ((!IsCompr && (EnBits & (1 << I)) == 0) ||
3299 (IsCompr && ((EnBits & (0x3 << (2 * I))) == 0))) {
3300 Value *Src = II->getArgOperand(I + 2);
3301 if (!isa<UndefValue>(Src)) {
3302 II->setArgOperand(I + 2, UndefValue::get(Src->getType()));
3303 Changed = true;
3304 }
3305 }
3306 }
3307
3308 if (Changed)
3309 return II;
3310
3311 break;
Matt Arsenaultcdb468c2017-02-27 23:08:49 +00003312
3313 }
3314 case Intrinsic::amdgcn_fmed3: {
3315 // Note this does not preserve proper sNaN behavior if IEEE-mode is enabled
3316 // for the shader.
3317
3318 Value *Src0 = II->getArgOperand(0);
3319 Value *Src1 = II->getArgOperand(1);
3320 Value *Src2 = II->getArgOperand(2);
3321
3322 bool Swap = false;
3323 // Canonicalize constants to RHS operands.
3324 //
3325 // fmed3(c0, x, c1) -> fmed3(x, c0, c1)
3326 if (isa<Constant>(Src0) && !isa<Constant>(Src1)) {
3327 std::swap(Src0, Src1);
3328 Swap = true;
3329 }
3330
3331 if (isa<Constant>(Src1) && !isa<Constant>(Src2)) {
3332 std::swap(Src1, Src2);
3333 Swap = true;
3334 }
3335
3336 if (isa<Constant>(Src0) && !isa<Constant>(Src1)) {
3337 std::swap(Src0, Src1);
3338 Swap = true;
3339 }
3340
3341 if (Swap) {
3342 II->setArgOperand(0, Src0);
3343 II->setArgOperand(1, Src1);
3344 II->setArgOperand(2, Src2);
3345 return II;
3346 }
3347
3348 if (match(Src2, m_NaN()) || isa<UndefValue>(Src2)) {
3349 CallInst *NewCall = Builder->CreateMinNum(Src0, Src1);
3350 NewCall->copyFastMathFlags(II);
3351 NewCall->takeName(II);
3352 return replaceInstUsesWith(*II, NewCall);
3353 }
3354
3355 if (const ConstantFP *C0 = dyn_cast<ConstantFP>(Src0)) {
3356 if (const ConstantFP *C1 = dyn_cast<ConstantFP>(Src1)) {
3357 if (const ConstantFP *C2 = dyn_cast<ConstantFP>(Src2)) {
3358 APFloat Result = fmed3AMDGCN(C0->getValueAPF(), C1->getValueAPF(),
3359 C2->getValueAPF());
3360 return replaceInstUsesWith(*II,
3361 ConstantFP::get(Builder->getContext(), Result));
3362 }
3363 }
3364 }
3365
3366 break;
Matt Arsenaultd4bca1e2017-02-23 00:44:03 +00003367 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003368 case Intrinsic::stackrestore: {
3369 // If the save is right next to the restore, remove the restore. This can
3370 // happen when variable allocas are DCE'd.
Gabor Greif589a0b92010-06-24 12:58:35 +00003371 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getArgOperand(0))) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003372 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00003373 if (&*++SS->getIterator() == II)
Sanjay Patel4b198802016-02-01 22:23:39 +00003374 return eraseInstFromFunction(CI);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003375 }
3376 }
Jim Grosbach7815f562012-02-03 00:07:04 +00003377
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003378 // Scan down this block to see if there is another stack restore in the
3379 // same block without an intervening call/alloca.
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00003380 BasicBlock::iterator BI(II);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003381 TerminatorInst *TI = II->getParent()->getTerminator();
3382 bool CannotRemove = false;
3383 for (++BI; &*BI != TI; ++BI) {
Nuno Lopes55fff832012-06-21 15:45:28 +00003384 if (isa<AllocaInst>(BI)) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003385 CannotRemove = true;
3386 break;
3387 }
3388 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
3389 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
3390 // If there is a stackrestore below this one, remove this one.
3391 if (II->getIntrinsicID() == Intrinsic::stackrestore)
Sanjay Patel4b198802016-02-01 22:23:39 +00003392 return eraseInstFromFunction(CI);
Reid Kleckner892ae2e2016-02-27 00:53:54 +00003393
3394 // Bail if we cross over an intrinsic with side effects, such as
3395 // llvm.stacksave, llvm.read_register, or llvm.setjmp.
3396 if (II->mayHaveSideEffects()) {
3397 CannotRemove = true;
3398 break;
3399 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003400 } else {
3401 // If we found a non-intrinsic call, we can't remove the stack
3402 // restore.
3403 CannotRemove = true;
3404 break;
3405 }
3406 }
3407 }
Jim Grosbach7815f562012-02-03 00:07:04 +00003408
Bill Wendlingf891bf82011-07-31 06:30:59 +00003409 // If the stack restore is in a return, resume, or unwind block and if there
3410 // are no allocas or calls between the restore and the return, nuke the
3411 // restore.
Bill Wendlingd5d95b02012-02-06 21:16:41 +00003412 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<ResumeInst>(TI)))
Sanjay Patel4b198802016-02-01 22:23:39 +00003413 return eraseInstFromFunction(CI);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003414 break;
3415 }
Vitaly Bukaf0500b62016-07-28 22:50:48 +00003416 case Intrinsic::lifetime_start:
Vitaly Buka0ab23cf2016-07-28 22:59:03 +00003417 // Asan needs to poison memory to detect invalid access which is possible
3418 // even for empty lifetime range.
3419 if (II->getFunction()->hasFnAttribute(Attribute::SanitizeAddress))
3420 break;
3421
Arnaud A. de Grandmaison333ef382016-05-10 09:24:49 +00003422 if (removeTriviallyEmptyRange(*II, Intrinsic::lifetime_start,
3423 Intrinsic::lifetime_end, *this))
3424 return nullptr;
Arnaud A. de Grandmaison849f3bf2015-10-01 14:54:31 +00003425 break;
Hal Finkelf5867a72014-07-25 21:45:17 +00003426 case Intrinsic::assume: {
David Majnemerfcc58112016-04-08 16:37:12 +00003427 Value *IIOperand = II->getArgOperand(0);
3428 // Remove an assume if it is immediately followed by an identical assume.
3429 if (match(II->getNextNode(),
3430 m_Intrinsic<Intrinsic::assume>(m_Specific(IIOperand))))
3431 return eraseInstFromFunction(CI);
3432
Hal Finkelf5867a72014-07-25 21:45:17 +00003433 // Canonicalize assume(a && b) -> assume(a); assume(b);
Hal Finkel74c2f352014-09-07 12:44:26 +00003434 // Note: New assumption intrinsics created here are registered by
3435 // the InstCombineIRInserter object.
David Majnemerfcc58112016-04-08 16:37:12 +00003436 Value *AssumeIntrinsic = II->getCalledValue(), *A, *B;
Hal Finkelf5867a72014-07-25 21:45:17 +00003437 if (match(IIOperand, m_And(m_Value(A), m_Value(B)))) {
3438 Builder->CreateCall(AssumeIntrinsic, A, II->getName());
3439 Builder->CreateCall(AssumeIntrinsic, B, II->getName());
Sanjay Patel4b198802016-02-01 22:23:39 +00003440 return eraseInstFromFunction(*II);
Hal Finkelf5867a72014-07-25 21:45:17 +00003441 }
3442 // assume(!(a || b)) -> assume(!a); assume(!b);
3443 if (match(IIOperand, m_Not(m_Or(m_Value(A), m_Value(B))))) {
Hal Finkel74c2f352014-09-07 12:44:26 +00003444 Builder->CreateCall(AssumeIntrinsic, Builder->CreateNot(A),
3445 II->getName());
3446 Builder->CreateCall(AssumeIntrinsic, Builder->CreateNot(B),
3447 II->getName());
Sanjay Patel4b198802016-02-01 22:23:39 +00003448 return eraseInstFromFunction(*II);
Hal Finkelf5867a72014-07-25 21:45:17 +00003449 }
Hal Finkel04a15612014-10-04 21:27:06 +00003450
Philip Reames66c6de62014-11-11 23:33:19 +00003451 // assume( (load addr) != null ) -> add 'nonnull' metadata to load
3452 // (if assume is valid at the load)
Sanjay Patelf0d1e7732017-01-03 22:25:31 +00003453 CmpInst::Predicate Pred;
3454 Instruction *LHS;
3455 if (match(IIOperand, m_ICmp(Pred, m_Instruction(LHS), m_Zero())) &&
3456 Pred == ICmpInst::ICMP_NE && LHS->getOpcode() == Instruction::Load &&
3457 LHS->getType()->isPointerTy() &&
3458 isValidAssumeForContext(II, LHS, &DT)) {
3459 MDNode *MD = MDNode::get(II->getContext(), None);
3460 LHS->setMetadata(LLVMContext::MD_nonnull, MD);
3461 return eraseInstFromFunction(*II);
3462
Chandler Carruth24969102015-02-10 08:07:32 +00003463 // TODO: apply nonnull return attributes to calls and invokes
Philip Reames66c6de62014-11-11 23:33:19 +00003464 // TODO: apply range metadata for range check patterns?
3465 }
Sanjay Patelf0d1e7732017-01-03 22:25:31 +00003466
Hal Finkel04a15612014-10-04 21:27:06 +00003467 // If there is a dominating assume with the same condition as this one,
3468 // then this one is redundant, and should be removed.
Hal Finkel45646882014-10-05 00:53:02 +00003469 APInt KnownZero(1, 0), KnownOne(1, 0);
3470 computeKnownBits(IIOperand, KnownZero, KnownOne, 0, II);
3471 if (KnownOne.isAllOnesValue())
Sanjay Patel4b198802016-02-01 22:23:39 +00003472 return eraseInstFromFunction(*II);
Hal Finkel04a15612014-10-04 21:27:06 +00003473
Hal Finkel8a9a7832017-01-11 13:24:24 +00003474 // Update the cache of affected values for this assumption (we might be
3475 // here because we just simplified the condition).
3476 AC.updateAffectedValues(II);
Hal Finkelf5867a72014-07-25 21:45:17 +00003477 break;
3478 }
Philip Reames9db26ff2014-12-29 23:27:30 +00003479 case Intrinsic::experimental_gc_relocate: {
3480 // Translate facts known about a pointer before relocating into
3481 // facts about the relocate value, while being careful to
3482 // preserve relocation semantics.
Manuel Jacob83eefa62016-01-05 04:03:00 +00003483 Value *DerivedPtr = cast<GCRelocateInst>(II)->getDerivedPtr();
Philip Reames9db26ff2014-12-29 23:27:30 +00003484
3485 // Remove the relocation if unused, note that this check is required
3486 // to prevent the cases below from looping forever.
3487 if (II->use_empty())
Sanjay Patel4b198802016-02-01 22:23:39 +00003488 return eraseInstFromFunction(*II);
Philip Reames9db26ff2014-12-29 23:27:30 +00003489
3490 // Undef is undef, even after relocation.
3491 // TODO: provide a hook for this in GCStrategy. This is clearly legal for
3492 // most practical collectors, but there was discussion in the review thread
3493 // about whether it was legal for all possible collectors.
Philip Reamesea4d8e82016-02-09 21:09:22 +00003494 if (isa<UndefValue>(DerivedPtr))
3495 // Use undef of gc_relocate's type to replace it.
3496 return replaceInstUsesWith(*II, UndefValue::get(II->getType()));
Philip Reames9db26ff2014-12-29 23:27:30 +00003497
Philip Reamesea4d8e82016-02-09 21:09:22 +00003498 if (auto *PT = dyn_cast<PointerType>(II->getType())) {
3499 // The relocation of null will be null for most any collector.
3500 // TODO: provide a hook for this in GCStrategy. There might be some
3501 // weird collector this property does not hold for.
3502 if (isa<ConstantPointerNull>(DerivedPtr))
3503 // Use null-pointer of gc_relocate's type to replace it.
3504 return replaceInstUsesWith(*II, ConstantPointerNull::get(PT));
Simon Pilgrimc0c56e72016-04-24 17:00:34 +00003505
Philip Reamesea4d8e82016-02-09 21:09:22 +00003506 // isKnownNonNull -> nonnull attribute
Justin Bogner99798402016-08-05 01:06:44 +00003507 if (isKnownNonNullAt(DerivedPtr, II, &DT))
Philip Reamesea4d8e82016-02-09 21:09:22 +00003508 II->addAttribute(AttributeSet::ReturnIndex, Attribute::NonNull);
Ramkumar Ramachandra8fcb4982015-02-14 19:37:54 +00003509 }
Philip Reames9db26ff2014-12-29 23:27:30 +00003510
3511 // TODO: bitcast(relocate(p)) -> relocate(bitcast(p))
3512 // Canonicalize on the type from the uses to the defs
Ramkumar Ramachandra8fcb4982015-02-14 19:37:54 +00003513
Philip Reames9db26ff2014-12-29 23:27:30 +00003514 // TODO: relocate((gep p, C, C2, ...)) -> gep(relocate(p), C, C2, ...)
Philip Reamesea4d8e82016-02-09 21:09:22 +00003515 break;
Philip Reames9db26ff2014-12-29 23:27:30 +00003516 }
Artur Pilipenkoe812ca02017-01-25 14:12:12 +00003517
3518 case Intrinsic::experimental_guard: {
Sanjoy Dase0e57952017-02-01 16:34:55 +00003519 // Is this guard followed by another guard?
3520 Instruction *NextInst = II->getNextNode();
3521 Value *NextCond = nullptr;
3522 if (match(NextInst,
3523 m_Intrinsic<Intrinsic::experimental_guard>(m_Value(NextCond)))) {
3524 Value *CurrCond = II->getArgOperand(0);
Artur Pilipenkoe812ca02017-01-25 14:12:12 +00003525
Sanjoy Dase0e57952017-02-01 16:34:55 +00003526 // Remove a guard that it is immediately preceeded by an identical guard.
3527 if (CurrCond == NextCond)
3528 return eraseInstFromFunction(*NextInst);
3529
3530 // Otherwise canonicalize guard(a); guard(b) -> guard(a & b).
3531 II->setArgOperand(0, Builder->CreateAnd(CurrCond, NextCond));
3532 return eraseInstFromFunction(*NextInst);
3533 }
Artur Pilipenkoe812ca02017-01-25 14:12:12 +00003534 break;
3535 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003536 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003537 return visitCallSite(II);
3538}
3539
Davide Italianoaec46172017-01-31 18:09:05 +00003540// Fence instruction simplification
3541Instruction *InstCombiner::visitFenceInst(FenceInst &FI) {
3542 // Remove identical consecutive fences.
3543 if (auto *NFI = dyn_cast<FenceInst>(FI.getNextNode()))
3544 if (FI.isIdenticalTo(NFI))
3545 return eraseInstFromFunction(FI);
3546 return nullptr;
3547}
3548
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003549// InvokeInst simplification
3550//
3551Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
3552 return visitCallSite(&II);
3553}
3554
Sanjay Patelcd4377c2016-01-20 22:24:38 +00003555/// If this cast does not affect the value passed through the varargs area, we
3556/// can eliminate the use of the cast.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003557static bool isSafeToEliminateVarargsCast(const CallSite CS,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003558 const DataLayout &DL,
3559 const CastInst *const CI,
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003560 const int ix) {
3561 if (!CI->isLosslessCast())
3562 return false;
3563
Philip Reames1a1bdb22014-12-02 18:50:36 +00003564 // If this is a GC intrinsic, avoid munging types. We need types for
3565 // statepoint reconstruction in SelectionDAG.
3566 // TODO: This is probably something which should be expanded to all
3567 // intrinsics since the entire point of intrinsics is that
3568 // they are understandable by the optimizer.
3569 if (isStatepoint(CS) || isGCRelocate(CS) || isGCResult(CS))
3570 return false;
3571
Reid Kleckner26af2ca2014-01-28 02:38:36 +00003572 // The size of ByVal or InAlloca arguments is derived from the type, so we
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003573 // can't change to a type with a different size. If the size were
3574 // passed explicitly we could avoid this check.
Reid Kleckner26af2ca2014-01-28 02:38:36 +00003575 if (!CS.isByValOrInAllocaArgument(ix))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003576 return true;
3577
Jim Grosbach7815f562012-02-03 00:07:04 +00003578 Type* SrcTy =
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003579 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
Chris Lattner229907c2011-07-18 04:54:35 +00003580 Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003581 if (!SrcTy->isSized() || !DstTy->isSized())
3582 return false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003583 if (DL.getTypeAllocSize(SrcTy) != DL.getTypeAllocSize(DstTy))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003584 return false;
3585 return true;
3586}
3587
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003588Instruction *InstCombiner::tryOptimizeCall(CallInst *CI) {
Craig Topperf40110f2014-04-25 05:29:35 +00003589 if (!CI->getCalledFunction()) return nullptr;
Eric Christophera7fb58f2010-03-06 10:50:38 +00003590
Chandler Carruthba4c5172015-01-21 11:23:40 +00003591 auto InstCombineRAUW = [this](Instruction *From, Value *With) {
Sanjay Patel4b198802016-02-01 22:23:39 +00003592 replaceInstUsesWith(*From, With);
Chandler Carruthba4c5172015-01-21 11:23:40 +00003593 };
Justin Bogner99798402016-08-05 01:06:44 +00003594 LibCallSimplifier Simplifier(DL, &TLI, InstCombineRAUW);
Chandler Carruthba4c5172015-01-21 11:23:40 +00003595 if (Value *With = Simplifier.optimizeCall(CI)) {
Meador Ingee3f2b262012-11-30 04:05:06 +00003596 ++NumSimplified;
Sanjay Patel4b198802016-02-01 22:23:39 +00003597 return CI->use_empty() ? CI : replaceInstUsesWith(*CI, With);
Meador Ingee3f2b262012-11-30 04:05:06 +00003598 }
Meador Ingedf796f82012-10-13 16:45:24 +00003599
Craig Topperf40110f2014-04-25 05:29:35 +00003600 return nullptr;
Eric Christophera7fb58f2010-03-06 10:50:38 +00003601}
3602
Sanjay Patel6038d3e2016-01-29 23:27:03 +00003603static IntrinsicInst *findInitTrampolineFromAlloca(Value *TrampMem) {
Duncan Sandsa0984362011-09-06 13:37:06 +00003604 // Strip off at most one level of pointer casts, looking for an alloca. This
3605 // is good enough in practice and simpler than handling any number of casts.
3606 Value *Underlying = TrampMem->stripPointerCasts();
3607 if (Underlying != TrampMem &&
Chandler Carruthcdf47882014-03-09 03:16:01 +00003608 (!Underlying->hasOneUse() || Underlying->user_back() != TrampMem))
Craig Topperf40110f2014-04-25 05:29:35 +00003609 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00003610 if (!isa<AllocaInst>(Underlying))
Craig Topperf40110f2014-04-25 05:29:35 +00003611 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00003612
Craig Topperf40110f2014-04-25 05:29:35 +00003613 IntrinsicInst *InitTrampoline = nullptr;
Chandler Carruthcdf47882014-03-09 03:16:01 +00003614 for (User *U : TrampMem->users()) {
3615 IntrinsicInst *II = dyn_cast<IntrinsicInst>(U);
Duncan Sandsa0984362011-09-06 13:37:06 +00003616 if (!II)
Craig Topperf40110f2014-04-25 05:29:35 +00003617 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00003618 if (II->getIntrinsicID() == Intrinsic::init_trampoline) {
3619 if (InitTrampoline)
3620 // More than one init_trampoline writes to this value. Give up.
Craig Topperf40110f2014-04-25 05:29:35 +00003621 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00003622 InitTrampoline = II;
3623 continue;
3624 }
3625 if (II->getIntrinsicID() == Intrinsic::adjust_trampoline)
3626 // Allow any number of calls to adjust.trampoline.
3627 continue;
Craig Topperf40110f2014-04-25 05:29:35 +00003628 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00003629 }
3630
3631 // No call to init.trampoline found.
3632 if (!InitTrampoline)
Craig Topperf40110f2014-04-25 05:29:35 +00003633 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00003634
3635 // Check that the alloca is being used in the expected way.
3636 if (InitTrampoline->getOperand(0) != TrampMem)
Craig Topperf40110f2014-04-25 05:29:35 +00003637 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00003638
3639 return InitTrampoline;
3640}
3641
Sanjay Patel6038d3e2016-01-29 23:27:03 +00003642static IntrinsicInst *findInitTrampolineFromBB(IntrinsicInst *AdjustTramp,
Duncan Sandsa0984362011-09-06 13:37:06 +00003643 Value *TrampMem) {
3644 // Visit all the previous instructions in the basic block, and try to find a
3645 // init.trampoline which has a direct path to the adjust.trampoline.
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00003646 for (BasicBlock::iterator I = AdjustTramp->getIterator(),
3647 E = AdjustTramp->getParent()->begin();
3648 I != E;) {
3649 Instruction *Inst = &*--I;
Duncan Sandsa0984362011-09-06 13:37:06 +00003650 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
3651 if (II->getIntrinsicID() == Intrinsic::init_trampoline &&
3652 II->getOperand(0) == TrampMem)
3653 return II;
3654 if (Inst->mayWriteToMemory())
Craig Topperf40110f2014-04-25 05:29:35 +00003655 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00003656 }
Craig Topperf40110f2014-04-25 05:29:35 +00003657 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00003658}
3659
3660// Given a call to llvm.adjust.trampoline, find and return the corresponding
3661// call to llvm.init.trampoline if the call to the trampoline can be optimized
3662// to a direct call to a function. Otherwise return NULL.
3663//
Sanjay Patel6038d3e2016-01-29 23:27:03 +00003664static IntrinsicInst *findInitTrampoline(Value *Callee) {
Duncan Sandsa0984362011-09-06 13:37:06 +00003665 Callee = Callee->stripPointerCasts();
3666 IntrinsicInst *AdjustTramp = dyn_cast<IntrinsicInst>(Callee);
3667 if (!AdjustTramp ||
3668 AdjustTramp->getIntrinsicID() != Intrinsic::adjust_trampoline)
Craig Topperf40110f2014-04-25 05:29:35 +00003669 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00003670
3671 Value *TrampMem = AdjustTramp->getOperand(0);
3672
Sanjay Patel6038d3e2016-01-29 23:27:03 +00003673 if (IntrinsicInst *IT = findInitTrampolineFromAlloca(TrampMem))
Duncan Sandsa0984362011-09-06 13:37:06 +00003674 return IT;
Sanjay Patel6038d3e2016-01-29 23:27:03 +00003675 if (IntrinsicInst *IT = findInitTrampolineFromBB(AdjustTramp, TrampMem))
Duncan Sandsa0984362011-09-06 13:37:06 +00003676 return IT;
Craig Topperf40110f2014-04-25 05:29:35 +00003677 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00003678}
3679
Sanjay Patelcd4377c2016-01-20 22:24:38 +00003680/// Improvements for call and invoke instructions.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003681Instruction *InstCombiner::visitCallSite(CallSite CS) {
Justin Bogner99798402016-08-05 01:06:44 +00003682 if (isAllocLikeFn(CS.getInstruction(), &TLI))
Nuno Lopes95cc4f32012-07-09 18:38:20 +00003683 return visitAllocSite(*CS.getInstruction());
Nuno Lopesdc6085e2012-06-21 21:25:05 +00003684
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003685 bool Changed = false;
3686
Philip Reamesc25df112015-06-16 20:24:25 +00003687 // Mark any parameters that are known to be non-null with the nonnull
3688 // attribute. This is helpful for inlining calls to functions with null
3689 // checks on their arguments.
Akira Hatanaka237916b2015-12-02 06:58:49 +00003690 SmallVector<unsigned, 4> Indices;
Philip Reamesc25df112015-06-16 20:24:25 +00003691 unsigned ArgNo = 0;
Akira Hatanaka237916b2015-12-02 06:58:49 +00003692
Philip Reamesc25df112015-06-16 20:24:25 +00003693 for (Value *V : CS.args()) {
Sanjay Patelf9f5d3c2016-01-29 23:14:58 +00003694 if (V->getType()->isPointerTy() &&
3695 !CS.paramHasAttr(ArgNo + 1, Attribute::NonNull) &&
Justin Bogner99798402016-08-05 01:06:44 +00003696 isKnownNonNullAt(V, CS.getInstruction(), &DT))
Akira Hatanaka237916b2015-12-02 06:58:49 +00003697 Indices.push_back(ArgNo + 1);
Philip Reamesc25df112015-06-16 20:24:25 +00003698 ArgNo++;
3699 }
Akira Hatanaka237916b2015-12-02 06:58:49 +00003700
Philip Reamesc25df112015-06-16 20:24:25 +00003701 assert(ArgNo == CS.arg_size() && "sanity check");
3702
Akira Hatanaka237916b2015-12-02 06:58:49 +00003703 if (!Indices.empty()) {
3704 AttributeSet AS = CS.getAttributes();
3705 LLVMContext &Ctx = CS.getInstruction()->getContext();
3706 AS = AS.addAttribute(Ctx, Indices,
3707 Attribute::get(Ctx, Attribute::NonNull));
3708 CS.setAttributes(AS);
3709 Changed = true;
3710 }
3711
Chris Lattner73989652010-12-20 08:25:06 +00003712 // If the callee is a pointer to a function, attempt to move any casts to the
3713 // arguments of the call/invoke.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003714 Value *Callee = CS.getCalledValue();
Chris Lattner73989652010-12-20 08:25:06 +00003715 if (!isa<Function>(Callee) && transformConstExprCastCall(CS))
Craig Topperf40110f2014-04-25 05:29:35 +00003716 return nullptr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003717
Justin Lebar9d943972016-03-14 20:18:54 +00003718 if (Function *CalleeF = dyn_cast<Function>(Callee)) {
3719 // Remove the convergent attr on calls when the callee is not convergent.
Matt Arsenault802ebcb2016-06-20 19:04:44 +00003720 if (CS.isConvergent() && !CalleeF->isConvergent() &&
3721 !CalleeF->isIntrinsic()) {
Justin Lebar9d943972016-03-14 20:18:54 +00003722 DEBUG(dbgs() << "Removing convergent attr from instr "
3723 << CS.getInstruction() << "\n");
3724 CS.setNotConvergent();
3725 return CS.getInstruction();
3726 }
3727
Chris Lattner846a52e2010-02-01 18:11:34 +00003728 // If the call and callee calling conventions don't match, this call must
3729 // be unreachable, as the call is undefined.
3730 if (CalleeF->getCallingConv() != CS.getCallingConv() &&
3731 // Only do this for calls to a function with a body. A prototype may
3732 // not actually end up matching the implementation's calling conv for a
3733 // variety of reasons (e.g. it may be written in assembly).
3734 !CalleeF->isDeclaration()) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003735 Instruction *OldCall = CS.getInstruction();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003736 new StoreInst(ConstantInt::getTrue(Callee->getContext()),
Jim Grosbach7815f562012-02-03 00:07:04 +00003737 UndefValue::get(Type::getInt1PtrTy(Callee->getContext())),
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003738 OldCall);
Chad Rosiere28ae302012-12-13 00:18:46 +00003739 // If OldCall does not return void then replaceAllUsesWith undef.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003740 // This allows ValueHandlers and custom metadata to adjust itself.
3741 if (!OldCall->getType()->isVoidTy())
Sanjay Patel4b198802016-02-01 22:23:39 +00003742 replaceInstUsesWith(*OldCall, UndefValue::get(OldCall->getType()));
Chris Lattner2cecedf2010-02-01 18:04:58 +00003743 if (isa<CallInst>(OldCall))
Sanjay Patel4b198802016-02-01 22:23:39 +00003744 return eraseInstFromFunction(*OldCall);
Jim Grosbach7815f562012-02-03 00:07:04 +00003745
Chris Lattner2cecedf2010-02-01 18:04:58 +00003746 // We cannot remove an invoke, because it would change the CFG, just
3747 // change the callee to a null pointer.
Gabor Greiffebf6ab2010-03-20 21:00:25 +00003748 cast<InvokeInst>(OldCall)->setCalledFunction(
Chris Lattner2cecedf2010-02-01 18:04:58 +00003749 Constant::getNullValue(CalleeF->getType()));
Craig Topperf40110f2014-04-25 05:29:35 +00003750 return nullptr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003751 }
Justin Lebar9d943972016-03-14 20:18:54 +00003752 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003753
3754 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
Gabor Greif589a0b92010-06-24 12:58:35 +00003755 // If CS does not return void then replaceAllUsesWith undef.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003756 // This allows ValueHandlers and custom metadata to adjust itself.
3757 if (!CS.getInstruction()->getType()->isVoidTy())
Sanjay Patel4b198802016-02-01 22:23:39 +00003758 replaceInstUsesWith(*CS.getInstruction(),
Eli Friedmanb9ed18f2011-05-18 00:32:01 +00003759 UndefValue::get(CS.getInstruction()->getType()));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003760
Nuno Lopes771e7bd2012-06-21 23:52:14 +00003761 if (isa<InvokeInst>(CS.getInstruction())) {
3762 // Can't remove an invoke because we cannot change the CFG.
Craig Topperf40110f2014-04-25 05:29:35 +00003763 return nullptr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003764 }
Nuno Lopes771e7bd2012-06-21 23:52:14 +00003765
3766 // This instruction is not reachable, just remove it. We insert a store to
3767 // undef so that we know that this code is not reachable, despite the fact
3768 // that we can't modify the CFG here.
3769 new StoreInst(ConstantInt::getTrue(Callee->getContext()),
3770 UndefValue::get(Type::getInt1PtrTy(Callee->getContext())),
3771 CS.getInstruction());
3772
Sanjay Patel4b198802016-02-01 22:23:39 +00003773 return eraseInstFromFunction(*CS.getInstruction());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003774 }
3775
Sanjay Patel6038d3e2016-01-29 23:27:03 +00003776 if (IntrinsicInst *II = findInitTrampoline(Callee))
Duncan Sandsa0984362011-09-06 13:37:06 +00003777 return transformCallThroughTrampoline(CS, II);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003778
Chris Lattner229907c2011-07-18 04:54:35 +00003779 PointerType *PTy = cast<PointerType>(Callee->getType());
3780 FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003781 if (FTy->isVarArg()) {
Eli Friedman7534b4682011-11-29 01:18:23 +00003782 int ix = FTy->getNumParams();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003783 // See if we can optimize any arguments passed through the varargs area of
3784 // the call.
Matt Arsenault5d2e85f2013-06-28 00:25:40 +00003785 for (CallSite::arg_iterator I = CS.arg_begin() + FTy->getNumParams(),
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003786 E = CS.arg_end(); I != E; ++I, ++ix) {
3787 CastInst *CI = dyn_cast<CastInst>(*I);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003788 if (CI && isSafeToEliminateVarargsCast(CS, DL, CI, ix)) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003789 *I = CI->getOperand(0);
3790 Changed = true;
3791 }
3792 }
3793 }
3794
3795 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
3796 // Inline asm calls cannot throw - mark them 'nounwind'.
3797 CS.setDoesNotThrow();
3798 Changed = true;
3799 }
3800
Micah Villmowcdfe20b2012-10-08 16:38:25 +00003801 // Try to optimize the call if possible, we require DataLayout for most of
Eric Christophera7fb58f2010-03-06 10:50:38 +00003802 // this. None of these calls are seen as possibly dead so go ahead and
3803 // delete the instruction now.
3804 if (CallInst *CI = dyn_cast<CallInst>(CS.getInstruction())) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003805 Instruction *I = tryOptimizeCall(CI);
Eric Christopher1810d772010-03-06 10:59:25 +00003806 // If we changed something return the result, etc. Otherwise let
3807 // the fallthrough check.
Sanjay Patel4b198802016-02-01 22:23:39 +00003808 if (I) return eraseInstFromFunction(*I);
Eric Christophera7fb58f2010-03-06 10:50:38 +00003809 }
3810
Craig Topperf40110f2014-04-25 05:29:35 +00003811 return Changed ? CS.getInstruction() : nullptr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003812}
3813
Sanjay Patelcd4377c2016-01-20 22:24:38 +00003814/// If the callee is a constexpr cast of a function, attempt to move the cast to
3815/// the arguments of the call/invoke.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003816bool InstCombiner::transformConstExprCastCall(CallSite CS) {
Sanjay Patele3c335c2016-08-11 15:21:21 +00003817 auto *Callee = dyn_cast<Function>(CS.getCalledValue()->stripPointerCasts());
Craig Topperf40110f2014-04-25 05:29:35 +00003818 if (!Callee)
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003819 return false;
Sanjay Patel38ae83d2016-08-11 15:23:56 +00003820
3821 // The prototype of a thunk is a lie. Don't directly call such a function.
David Majnemer4c0a6e92015-01-21 22:32:04 +00003822 if (Callee->hasFnAttribute("thunk"))
3823 return false;
Sanjay Patel38ae83d2016-08-11 15:23:56 +00003824
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003825 Instruction *Caller = CS.getInstruction();
Bill Wendlinge94d8432012-12-07 23:16:57 +00003826 const AttributeSet &CallerPAL = CS.getAttributes();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003827
3828 // Okay, this is a cast from a function to a different type. Unless doing so
3829 // would cause a type conversion of one of our arguments, change this call to
3830 // be a direct call with arguments casted to the appropriate types.
3831 //
Chris Lattner229907c2011-07-18 04:54:35 +00003832 FunctionType *FT = Callee->getFunctionType();
3833 Type *OldRetTy = Caller->getType();
3834 Type *NewRetTy = FT->getReturnType();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003835
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003836 // Check to see if we are changing the return type...
3837 if (OldRetTy != NewRetTy) {
Nick Lewyckya6a17d72014-01-18 22:47:12 +00003838
3839 if (NewRetTy->isStructTy())
3840 return false; // TODO: Handle multiple return values.
3841
David Majnemer9b6b8222015-01-06 08:41:31 +00003842 if (!CastInst::isBitOrNoopPointerCastable(NewRetTy, OldRetTy, DL)) {
Matt Arsenaulte6952f22013-09-17 21:10:14 +00003843 if (Callee->isDeclaration())
3844 return false; // Cannot transform this return value.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003845
Matt Arsenaulte6952f22013-09-17 21:10:14 +00003846 if (!Caller->use_empty() &&
3847 // void -> non-void is handled specially
3848 !NewRetTy->isVoidTy())
Frederic Rissc1892e22014-10-23 04:08:42 +00003849 return false; // Cannot transform this return value.
Matt Arsenaulte6952f22013-09-17 21:10:14 +00003850 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003851
3852 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Bill Wendling658d24d2013-01-18 21:53:16 +00003853 AttrBuilder RAttrs(CallerPAL, AttributeSet::ReturnIndex);
Pete Cooper2777d8872015-05-06 23:19:56 +00003854 if (RAttrs.overlaps(AttributeFuncs::typeIncompatible(NewRetTy)))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003855 return false; // Attribute not compatible with transformed value.
3856 }
3857
3858 // If the callsite is an invoke instruction, and the return value is used by
3859 // a PHI node in a successor, we cannot change the return type of the call
3860 // because there is no place to put the cast instruction (without breaking
3861 // the critical edge). Bail out in this case.
3862 if (!Caller->use_empty())
3863 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
Chandler Carruthcdf47882014-03-09 03:16:01 +00003864 for (User *U : II->users())
3865 if (PHINode *PN = dyn_cast<PHINode>(U))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003866 if (PN->getParent() == II->getNormalDest() ||
3867 PN->getParent() == II->getUnwindDest())
3868 return false;
3869 }
3870
Matt Arsenault5d2e85f2013-06-28 00:25:40 +00003871 unsigned NumActualArgs = CS.arg_size();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003872 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
3873
David Majnemer9b6b8222015-01-06 08:41:31 +00003874 // Prevent us turning:
3875 // declare void @takes_i32_inalloca(i32* inalloca)
3876 // call void bitcast (void (i32*)* @takes_i32_inalloca to void (i32)*)(i32 0)
3877 //
3878 // into:
3879 // call void @takes_i32_inalloca(i32* null)
David Majnemerd61a6fd2015-03-11 18:03:05 +00003880 //
3881 // Similarly, avoid folding away bitcasts of byval calls.
3882 if (Callee->getAttributes().hasAttrSomewhere(Attribute::InAlloca) ||
3883 Callee->getAttributes().hasAttrSomewhere(Attribute::ByVal))
David Majnemer9b6b8222015-01-06 08:41:31 +00003884 return false;
3885
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003886 CallSite::arg_iterator AI = CS.arg_begin();
3887 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
Chris Lattner229907c2011-07-18 04:54:35 +00003888 Type *ParamTy = FT->getParamType(i);
3889 Type *ActTy = (*AI)->getType();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003890
David Majnemer9b6b8222015-01-06 08:41:31 +00003891 if (!CastInst::isBitOrNoopPointerCastable(ActTy, ParamTy, DL))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003892 return false; // Cannot transform this parameter value.
3893
Bill Wendling49bc76c2013-01-23 06:14:59 +00003894 if (AttrBuilder(CallerPAL.getParamAttributes(i + 1), i + 1).
Pete Cooper2777d8872015-05-06 23:19:56 +00003895 overlaps(AttributeFuncs::typeIncompatible(ParamTy)))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003896 return false; // Attribute not compatible with transformed value.
Jim Grosbach7815f562012-02-03 00:07:04 +00003897
Reid Kleckner26af2ca2014-01-28 02:38:36 +00003898 if (CS.isInAllocaArgument(i))
3899 return false; // Cannot transform to and from inalloca.
3900
Chris Lattner27ca8eb2010-12-20 08:36:38 +00003901 // If the parameter is passed as a byval argument, then we have to have a
3902 // sized type and the sized type has to have the same size as the old type.
Bill Wendling49bc76c2013-01-23 06:14:59 +00003903 if (ParamTy != ActTy &&
3904 CallerPAL.getParamAttributes(i + 1).hasAttribute(i + 1,
3905 Attribute::ByVal)) {
Chris Lattner229907c2011-07-18 04:54:35 +00003906 PointerType *ParamPTy = dyn_cast<PointerType>(ParamTy);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003907 if (!ParamPTy || !ParamPTy->getElementType()->isSized())
Chris Lattner27ca8eb2010-12-20 08:36:38 +00003908 return false;
Jim Grosbach7815f562012-02-03 00:07:04 +00003909
Matt Arsenaultfa252722013-09-27 22:18:51 +00003910 Type *CurElTy = ActTy->getPointerElementType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003911 if (DL.getTypeAllocSize(CurElTy) !=
3912 DL.getTypeAllocSize(ParamPTy->getElementType()))
Chris Lattner27ca8eb2010-12-20 08:36:38 +00003913 return false;
3914 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003915 }
3916
Chris Lattneradf38b32011-02-24 05:10:56 +00003917 if (Callee->isDeclaration()) {
3918 // Do not delete arguments unless we have a function body.
3919 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg())
3920 return false;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003921
Chris Lattneradf38b32011-02-24 05:10:56 +00003922 // If the callee is just a declaration, don't change the varargsness of the
3923 // call. We don't want to introduce a varargs call where one doesn't
3924 // already exist.
Chris Lattner229907c2011-07-18 04:54:35 +00003925 PointerType *APTy = cast<PointerType>(CS.getCalledValue()->getType());
Chris Lattneradf38b32011-02-24 05:10:56 +00003926 if (FT->isVarArg()!=cast<FunctionType>(APTy->getElementType())->isVarArg())
3927 return false;
Jim Grosbache84ae7b2012-02-03 00:00:55 +00003928
3929 // If both the callee and the cast type are varargs, we still have to make
3930 // sure the number of fixed parameters are the same or we have the same
3931 // ABI issues as if we introduce a varargs call.
Jim Grosbach1df8cdc2012-02-03 00:26:07 +00003932 if (FT->isVarArg() &&
3933 cast<FunctionType>(APTy->getElementType())->isVarArg() &&
3934 FT->getNumParams() !=
Jim Grosbache84ae7b2012-02-03 00:00:55 +00003935 cast<FunctionType>(APTy->getElementType())->getNumParams())
3936 return false;
Chris Lattneradf38b32011-02-24 05:10:56 +00003937 }
Jim Grosbach7815f562012-02-03 00:07:04 +00003938
Jim Grosbach0ab54182012-02-03 00:00:50 +00003939 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
3940 !CallerPAL.isEmpty())
3941 // In this case we have more arguments than the new function type, but we
3942 // won't be dropping them. Check that these extra arguments have attributes
3943 // that are compatible with being a vararg call argument.
3944 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
Bill Wendling57625a42013-01-25 23:09:36 +00003945 unsigned Index = CallerPAL.getSlotIndex(i - 1);
3946 if (Index <= FT->getNumParams())
Jim Grosbach0ab54182012-02-03 00:00:50 +00003947 break;
Bill Wendling57625a42013-01-25 23:09:36 +00003948
Bill Wendlingd97b75d2012-12-19 08:57:40 +00003949 // Check if it has an attribute that's incompatible with varargs.
Bill Wendling57625a42013-01-25 23:09:36 +00003950 AttributeSet PAttrs = CallerPAL.getSlotAttributes(i - 1);
3951 if (PAttrs.hasAttribute(Index, Attribute::StructRet))
Jim Grosbach0ab54182012-02-03 00:00:50 +00003952 return false;
3953 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003954
Jim Grosbach7815f562012-02-03 00:07:04 +00003955
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003956 // Okay, we decided that this is a safe thing to do: go ahead and start
Chris Lattneradf38b32011-02-24 05:10:56 +00003957 // inserting cast instructions as necessary.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003958 std::vector<Value*> Args;
3959 Args.reserve(NumActualArgs);
Bill Wendling3575c8c2013-01-27 02:08:22 +00003960 SmallVector<AttributeSet, 8> attrVec;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003961 attrVec.reserve(NumCommonArgs);
3962
3963 // Get any return attributes.
Bill Wendling658d24d2013-01-18 21:53:16 +00003964 AttrBuilder RAttrs(CallerPAL, AttributeSet::ReturnIndex);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003965
3966 // If the return value is not being used, the type may not be compatible
3967 // with the existing attributes. Wipe out any problematic attributes.
Pete Cooper2777d8872015-05-06 23:19:56 +00003968 RAttrs.remove(AttributeFuncs::typeIncompatible(NewRetTy));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003969
3970 // Add the new return attributes.
Bill Wendling70f39172012-10-09 00:01:21 +00003971 if (RAttrs.hasAttributes())
Bill Wendling3575c8c2013-01-27 02:08:22 +00003972 attrVec.push_back(AttributeSet::get(Caller->getContext(),
3973 AttributeSet::ReturnIndex, RAttrs));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003974
3975 AI = CS.arg_begin();
3976 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
Chris Lattner229907c2011-07-18 04:54:35 +00003977 Type *ParamTy = FT->getParamType(i);
Matt Arsenaultcacbb232013-07-30 20:45:05 +00003978
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003979 if ((*AI)->getType() == ParamTy) {
3980 Args.push_back(*AI);
3981 } else {
David Majnemer9b6b8222015-01-06 08:41:31 +00003982 Args.push_back(Builder->CreateBitOrPointerCast(*AI, ParamTy));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003983 }
3984
3985 // Add any parameter attributes.
Bill Wendling49bc76c2013-01-23 06:14:59 +00003986 AttrBuilder PAttrs(CallerPAL.getParamAttributes(i + 1), i + 1);
Bill Wendling76d2cd22012-10-14 08:54:26 +00003987 if (PAttrs.hasAttributes())
Bill Wendling3575c8c2013-01-27 02:08:22 +00003988 attrVec.push_back(AttributeSet::get(Caller->getContext(), i + 1,
3989 PAttrs));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003990 }
3991
3992 // If the function takes more arguments than the call was taking, add them
3993 // now.
3994 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
3995 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
3996
3997 // If we are removing arguments to the function, emit an obnoxious warning.
3998 if (FT->getNumParams() < NumActualArgs) {
Nick Lewycky90053a12012-12-26 22:00:35 +00003999 // TODO: if (!FT->isVarArg()) this call may be unreachable. PR14722
4000 if (FT->isVarArg()) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004001 // Add all of the arguments in their promoted form to the arg list.
4002 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
Chris Lattner229907c2011-07-18 04:54:35 +00004003 Type *PTy = getPromotedType((*AI)->getType());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004004 if (PTy != (*AI)->getType()) {
4005 // Must promote to pass through va_arg area!
4006 Instruction::CastOps opcode =
4007 CastInst::getCastOpcode(*AI, false, PTy, false);
Benjamin Kramer547b6c52011-09-27 20:39:19 +00004008 Args.push_back(Builder->CreateCast(opcode, *AI, PTy));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004009 } else {
4010 Args.push_back(*AI);
4011 }
4012
4013 // Add any parameter attributes.
Bill Wendling49bc76c2013-01-23 06:14:59 +00004014 AttrBuilder PAttrs(CallerPAL.getParamAttributes(i + 1), i + 1);
Bill Wendling76d2cd22012-10-14 08:54:26 +00004015 if (PAttrs.hasAttributes())
Bill Wendling3575c8c2013-01-27 02:08:22 +00004016 attrVec.push_back(AttributeSet::get(FT->getContext(), i + 1,
4017 PAttrs));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004018 }
4019 }
4020 }
4021
Bill Wendlingbd4ea162013-01-21 21:57:28 +00004022 AttributeSet FnAttrs = CallerPAL.getFnAttributes();
Bill Wendling77543892013-01-18 21:11:39 +00004023 if (CallerPAL.hasAttributes(AttributeSet::FunctionIndex))
Bill Wendling3575c8c2013-01-27 02:08:22 +00004024 attrVec.push_back(AttributeSet::get(Callee->getContext(), FnAttrs));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004025
4026 if (NewRetTy->isVoidTy())
4027 Caller->setName(""); // Void type should not have a name.
4028
Bill Wendlinge94d8432012-12-07 23:16:57 +00004029 const AttributeSet &NewCallerPAL = AttributeSet::get(Callee->getContext(),
Bill Wendlingbd4ea162013-01-21 21:57:28 +00004030 attrVec);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004031
Sanjoy Das76293462015-11-25 00:42:19 +00004032 SmallVector<OperandBundleDef, 1> OpBundles;
Sanjoy Dasc521c7b2015-11-25 00:42:24 +00004033 CS.getOperandBundlesAsDefs(OpBundles);
Sanjoy Das76293462015-11-25 00:42:19 +00004034
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004035 Instruction *NC;
4036 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Sanjoy Das76293462015-11-25 00:42:19 +00004037 NC = Builder->CreateInvoke(Callee, II->getNormalDest(), II->getUnwindDest(),
4038 Args, OpBundles);
Eli Friedman96254a02011-05-18 01:28:27 +00004039 NC->takeName(II);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004040 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
4041 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
4042 } else {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004043 CallInst *CI = cast<CallInst>(Caller);
Sanjoy Das76293462015-11-25 00:42:19 +00004044 NC = Builder->CreateCall(Callee, Args, OpBundles);
Eli Friedman96254a02011-05-18 01:28:27 +00004045 NC->takeName(CI);
David Majnemerd5648c72016-11-25 22:35:09 +00004046 cast<CallInst>(NC)->setTailCallKind(CI->getTailCallKind());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004047 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
4048 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
4049 }
4050
4051 // Insert a cast of the return type as necessary.
4052 Value *NV = NC;
4053 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
4054 if (!NV->getType()->isVoidTy()) {
David Majnemer9b6b8222015-01-06 08:41:31 +00004055 NV = NC = CastInst::CreateBitOrPointerCast(NC, OldRetTy);
Eli Friedman35211c62011-05-27 00:19:40 +00004056 NC->setDebugLoc(Caller->getDebugLoc());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004057
4058 // If this is an invoke instruction, we should insert it after the first
4059 // non-phi, instruction in the normal successor block.
4060 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Bill Wendling07efd6f2011-08-25 01:08:34 +00004061 BasicBlock::iterator I = II->getNormalDest()->getFirstInsertionPt();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004062 InsertNewInstBefore(NC, *I);
4063 } else {
Chris Lattner73989652010-12-20 08:25:06 +00004064 // Otherwise, it's a call, just insert cast right after the call.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004065 InsertNewInstBefore(NC, *Caller);
4066 }
4067 Worklist.AddUsersToWorkList(*Caller);
4068 } else {
4069 NV = UndefValue::get(Caller->getType());
4070 }
4071 }
4072
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004073 if (!Caller->use_empty())
Sanjay Patel4b198802016-02-01 22:23:39 +00004074 replaceInstUsesWith(*Caller, NV);
Frederic Rissc1892e22014-10-23 04:08:42 +00004075 else if (Caller->hasValueHandle()) {
4076 if (OldRetTy == NV->getType())
4077 ValueHandleBase::ValueIsRAUWd(Caller, NV);
4078 else
4079 // We cannot call ValueIsRAUWd with a different type, and the
4080 // actual tracked value will disappear.
4081 ValueHandleBase::ValueIsDeleted(Caller);
4082 }
Eli Friedmanb9ed18f2011-05-18 00:32:01 +00004083
Sanjay Patel4b198802016-02-01 22:23:39 +00004084 eraseInstFromFunction(*Caller);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004085 return true;
4086}
4087
Sanjay Patelcd4377c2016-01-20 22:24:38 +00004088/// Turn a call to a function created by init_trampoline / adjust_trampoline
4089/// intrinsic pair into a direct call to the underlying function.
Duncan Sandsa0984362011-09-06 13:37:06 +00004090Instruction *
4091InstCombiner::transformCallThroughTrampoline(CallSite CS,
4092 IntrinsicInst *Tramp) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004093 Value *Callee = CS.getCalledValue();
Chris Lattner229907c2011-07-18 04:54:35 +00004094 PointerType *PTy = cast<PointerType>(Callee->getType());
4095 FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Bill Wendlinge94d8432012-12-07 23:16:57 +00004096 const AttributeSet &Attrs = CS.getAttributes();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004097
4098 // If the call already has the 'nest' attribute somewhere then give up -
4099 // otherwise 'nest' would occur twice after splicing in the chain.
Bill Wendling6e95ae82012-12-31 00:49:59 +00004100 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Craig Topperf40110f2014-04-25 05:29:35 +00004101 return nullptr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004102
Duncan Sandsa0984362011-09-06 13:37:06 +00004103 assert(Tramp &&
4104 "transformCallThroughTrampoline called with incorrect CallSite.");
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004105
Gabor Greif3e44ea12010-07-22 10:37:47 +00004106 Function *NestF =cast<Function>(Tramp->getArgOperand(1)->stripPointerCasts());
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00004107 FunctionType *NestFTy = cast<FunctionType>(NestF->getValueType());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004108
Bill Wendlinge94d8432012-12-07 23:16:57 +00004109 const AttributeSet &NestAttrs = NestF->getAttributes();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004110 if (!NestAttrs.isEmpty()) {
4111 unsigned NestIdx = 1;
Craig Topperf40110f2014-04-25 05:29:35 +00004112 Type *NestTy = nullptr;
Bill Wendling49bc76c2013-01-23 06:14:59 +00004113 AttributeSet NestAttr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004114
4115 // Look for a parameter marked with the 'nest' attribute.
4116 for (FunctionType::param_iterator I = NestFTy->param_begin(),
4117 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Bill Wendling49bc76c2013-01-23 06:14:59 +00004118 if (NestAttrs.hasAttribute(NestIdx, Attribute::Nest)) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004119 // Record the parameter type and any other attributes.
4120 NestTy = *I;
4121 NestAttr = NestAttrs.getParamAttributes(NestIdx);
4122 break;
4123 }
4124
4125 if (NestTy) {
4126 Instruction *Caller = CS.getInstruction();
4127 std::vector<Value*> NewArgs;
Matt Arsenault5d2e85f2013-06-28 00:25:40 +00004128 NewArgs.reserve(CS.arg_size() + 1);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004129
Bill Wendling3575c8c2013-01-27 02:08:22 +00004130 SmallVector<AttributeSet, 8> NewAttrs;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004131 NewAttrs.reserve(Attrs.getNumSlots() + 1);
4132
4133 // Insert the nest argument into the call argument list, which may
4134 // mean appending it. Likewise for attributes.
4135
4136 // Add any result attributes.
Bill Wendling658d24d2013-01-18 21:53:16 +00004137 if (Attrs.hasAttributes(AttributeSet::ReturnIndex))
Bill Wendling3575c8c2013-01-27 02:08:22 +00004138 NewAttrs.push_back(AttributeSet::get(Caller->getContext(),
4139 Attrs.getRetAttributes()));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004140
4141 {
4142 unsigned Idx = 1;
4143 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
4144 do {
4145 if (Idx == NestIdx) {
4146 // Add the chain argument and attributes.
Gabor Greif589a0b92010-06-24 12:58:35 +00004147 Value *NestVal = Tramp->getArgOperand(2);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004148 if (NestVal->getType() != NestTy)
Eli Friedman41e509a2011-05-18 23:58:37 +00004149 NestVal = Builder->CreateBitCast(NestVal, NestTy, "nest");
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004150 NewArgs.push_back(NestVal);
Bill Wendling3575c8c2013-01-27 02:08:22 +00004151 NewAttrs.push_back(AttributeSet::get(Caller->getContext(),
4152 NestAttr));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004153 }
4154
4155 if (I == E)
4156 break;
4157
4158 // Add the original argument and attributes.
4159 NewArgs.push_back(*I);
Bill Wendling49bc76c2013-01-23 06:14:59 +00004160 AttributeSet Attr = Attrs.getParamAttributes(Idx);
4161 if (Attr.hasAttributes(Idx)) {
Bill Wendling3575c8c2013-01-27 02:08:22 +00004162 AttrBuilder B(Attr, Idx);
4163 NewAttrs.push_back(AttributeSet::get(Caller->getContext(),
4164 Idx + (Idx >= NestIdx), B));
Bill Wendling49bc76c2013-01-23 06:14:59 +00004165 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004166
Richard Trieu7a083812016-02-18 22:09:30 +00004167 ++Idx;
4168 ++I;
Eugene Zelenkocdc71612016-08-11 17:20:18 +00004169 } while (true);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004170 }
4171
4172 // Add any function attributes.
Bill Wendling77543892013-01-18 21:11:39 +00004173 if (Attrs.hasAttributes(AttributeSet::FunctionIndex))
Bill Wendling3575c8c2013-01-27 02:08:22 +00004174 NewAttrs.push_back(AttributeSet::get(FTy->getContext(),
4175 Attrs.getFnAttributes()));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004176
4177 // The trampoline may have been bitcast to a bogus type (FTy).
4178 // Handle this by synthesizing a new function type, equal to FTy
4179 // with the chain parameter inserted.
4180
Jay Foadb804a2b2011-07-12 14:06:48 +00004181 std::vector<Type*> NewTypes;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004182 NewTypes.reserve(FTy->getNumParams()+1);
4183
4184 // Insert the chain's type into the list of parameter types, which may
4185 // mean appending it.
4186 {
4187 unsigned Idx = 1;
4188 FunctionType::param_iterator I = FTy->param_begin(),
4189 E = FTy->param_end();
4190
4191 do {
4192 if (Idx == NestIdx)
4193 // Add the chain's type.
4194 NewTypes.push_back(NestTy);
4195
4196 if (I == E)
4197 break;
4198
4199 // Add the original type.
4200 NewTypes.push_back(*I);
4201
Richard Trieu7a083812016-02-18 22:09:30 +00004202 ++Idx;
4203 ++I;
Eugene Zelenkocdc71612016-08-11 17:20:18 +00004204 } while (true);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004205 }
4206
4207 // Replace the trampoline call with a direct call. Let the generic
4208 // code sort out any function type mismatches.
Jim Grosbach7815f562012-02-03 00:07:04 +00004209 FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004210 FTy->isVarArg());
4211 Constant *NewCallee =
4212 NestF->getType() == PointerType::getUnqual(NewFTy) ?
Jim Grosbach7815f562012-02-03 00:07:04 +00004213 NestF : ConstantExpr::getBitCast(NestF,
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004214 PointerType::getUnqual(NewFTy));
Jim Grosbachbdbd7342013-04-05 21:20:12 +00004215 const AttributeSet &NewPAL =
4216 AttributeSet::get(FTy->getContext(), NewAttrs);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004217
David Majnemer231a68c2016-04-29 08:07:20 +00004218 SmallVector<OperandBundleDef, 1> OpBundles;
4219 CS.getOperandBundlesAsDefs(OpBundles);
4220
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004221 Instruction *NewCaller;
4222 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
4223 NewCaller = InvokeInst::Create(NewCallee,
4224 II->getNormalDest(), II->getUnwindDest(),
David Majnemer231a68c2016-04-29 08:07:20 +00004225 NewArgs, OpBundles);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004226 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
4227 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
4228 } else {
David Majnemer231a68c2016-04-29 08:07:20 +00004229 NewCaller = CallInst::Create(NewCallee, NewArgs, OpBundles);
David Majnemerd5648c72016-11-25 22:35:09 +00004230 cast<CallInst>(NewCaller)->setTailCallKind(
4231 cast<CallInst>(Caller)->getTailCallKind());
4232 cast<CallInst>(NewCaller)->setCallingConv(
4233 cast<CallInst>(Caller)->getCallingConv());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004234 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
4235 }
Eli Friedman49346012011-05-18 19:57:14 +00004236
4237 return NewCaller;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004238 }
4239 }
4240
4241 // Replace the trampoline call with a direct call. Since there is no 'nest'
4242 // parameter, there is no need to adjust the argument list. Let the generic
4243 // code sort out any function type mismatches.
4244 Constant *NewCallee =
Jim Grosbach7815f562012-02-03 00:07:04 +00004245 NestF->getType() == PTy ? NestF :
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004246 ConstantExpr::getBitCast(NestF, PTy);
4247 CS.setCalledFunction(NewCallee);
4248 return CS.getInstruction();
4249}