blob: 40e52ee755e52fcdff624e8d674ec131c43ce714 [file] [log] [blame]
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001//===- InstCombineCalls.cpp -----------------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the visitCall and visitInvoke functions.
11//
12//===----------------------------------------------------------------------===//
13
Chandler Carrutha9174582015-01-22 05:25:13 +000014#include "InstCombineInternal.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000015#include "llvm/ADT/APFloat.h"
16#include "llvm/ADT/APInt.h"
17#include "llvm/ADT/ArrayRef.h"
18#include "llvm/ADT/None.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000019#include "llvm/ADT/Optional.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000020#include "llvm/ADT/STLExtras.h"
21#include "llvm/ADT/SmallVector.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000022#include "llvm/ADT/Statistic.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000023#include "llvm/ADT/Twine.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000024#include "llvm/Analysis/AssumptionCache.h"
David Majnemer15032582015-05-22 03:56:46 +000025#include "llvm/Analysis/InstructionSimplify.h"
Chris Lattner7a9e47a2010-01-05 07:32:13 +000026#include "llvm/Analysis/MemoryBuiltins.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000027#include "llvm/Analysis/ValueTracking.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000028#include "llvm/IR/Attributes.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000029#include "llvm/IR/BasicBlock.h"
Chandler Carruth219b89b2014-03-04 11:01:28 +000030#include "llvm/IR/CallSite.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000031#include "llvm/IR/Constant.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000032#include "llvm/IR/Constants.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000033#include "llvm/IR/DataLayout.h"
34#include "llvm/IR/DerivedTypes.h"
35#include "llvm/IR/Function.h"
36#include "llvm/IR/GlobalVariable.h"
37#include "llvm/IR/InstrTypes.h"
38#include "llvm/IR/Instruction.h"
39#include "llvm/IR/Instructions.h"
40#include "llvm/IR/IntrinsicInst.h"
41#include "llvm/IR/Intrinsics.h"
42#include "llvm/IR/LLVMContext.h"
43#include "llvm/IR/Metadata.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000044#include "llvm/IR/PatternMatch.h"
Philip Reames1a1bdb22014-12-02 18:50:36 +000045#include "llvm/IR/Statepoint.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000046#include "llvm/IR/Type.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000047#include "llvm/IR/User.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000048#include "llvm/IR/Value.h"
49#include "llvm/IR/ValueHandle.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000050#include "llvm/Support/AtomicOrdering.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000051#include "llvm/Support/Casting.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000052#include "llvm/Support/CommandLine.h"
53#include "llvm/Support/Compiler.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000054#include "llvm/Support/Debug.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000055#include "llvm/Support/ErrorHandling.h"
Craig Topperb45eabc2017-04-26 16:39:58 +000056#include "llvm/Support/KnownBits.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000057#include "llvm/Support/MathExtras.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000058#include "llvm/Support/raw_ostream.h"
59#include "llvm/Transforms/InstCombine/InstCombineWorklist.h"
Chris Lattner6fcd32e2010-12-25 20:37:57 +000060#include "llvm/Transforms/Utils/Local.h"
Chandler Carruthba4c5172015-01-21 11:23:40 +000061#include "llvm/Transforms/Utils/SimplifyLibCalls.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000062#include <algorithm>
63#include <cassert>
64#include <cstdint>
65#include <cstring>
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000066#include <utility>
Eugene Zelenkocdc71612016-08-11 17:20:18 +000067#include <vector>
68
Chris Lattner7a9e47a2010-01-05 07:32:13 +000069using namespace llvm;
Michael Ilseman536cc322012-12-13 03:13:36 +000070using namespace PatternMatch;
Chris Lattner7a9e47a2010-01-05 07:32:13 +000071
Chandler Carruth964daaa2014-04-22 02:55:47 +000072#define DEBUG_TYPE "instcombine"
73
Meador Ingee3f2b262012-11-30 04:05:06 +000074STATISTIC(NumSimplified, "Number of library calls simplified");
75
Igor Laevskya9b68722017-02-08 15:21:48 +000076static cl::opt<unsigned> UnfoldElementAtomicMemcpyMaxElements(
Igor Laevsky900ffa32017-02-08 14:32:04 +000077 "unfold-element-atomic-memcpy-max-elements",
78 cl::init(16),
79 cl::desc("Maximum number of elements in atomic memcpy the optimizer is "
80 "allowed to unfold"));
81
Sanjay Patelcd4377c2016-01-20 22:24:38 +000082/// Return the specified type promoted as it would be to pass though a va_arg
83/// area.
Chris Lattner229907c2011-07-18 04:54:35 +000084static Type *getPromotedType(Type *Ty) {
85 if (IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +000086 if (ITy->getBitWidth() < 32)
87 return Type::getInt32Ty(Ty->getContext());
88 }
89 return Ty;
90}
91
Sanjay Patel368ac5d2016-02-21 17:29:33 +000092/// Return a constant boolean vector that has true elements in all positions
Sanjay Patel24401302016-02-21 17:33:31 +000093/// where the input constant data vector has an element with the sign bit set.
Sanjay Patel368ac5d2016-02-21 17:29:33 +000094static Constant *getNegativeIsTrueBoolVec(ConstantDataVector *V) {
95 SmallVector<Constant *, 32> BoolVec;
96 IntegerType *BoolTy = Type::getInt1Ty(V->getContext());
97 for (unsigned I = 0, E = V->getNumElements(); I != E; ++I) {
98 Constant *Elt = V->getElementAsConstant(I);
99 assert((isa<ConstantInt>(Elt) || isa<ConstantFP>(Elt)) &&
100 "Unexpected constant data vector element type");
101 bool Sign = V->getElementType()->isIntegerTy()
102 ? cast<ConstantInt>(Elt)->isNegative()
103 : cast<ConstantFP>(Elt)->isNegative();
104 BoolVec.push_back(ConstantInt::get(BoolTy, Sign));
105 }
106 return ConstantVector::get(BoolVec);
107}
108
Daniel Neilsonf9c7d292017-10-30 19:51:48 +0000109Instruction *
110InstCombiner::SimplifyElementUnorderedAtomicMemCpy(AtomicMemCpyInst *AMI) {
Igor Laevsky900ffa32017-02-08 14:32:04 +0000111 // Try to unfold this intrinsic into sequence of explicit atomic loads and
112 // stores.
113 // First check that number of elements is compile time constant.
Daniel Neilson3faabbb2017-06-16 14:43:59 +0000114 auto *LengthCI = dyn_cast<ConstantInt>(AMI->getLength());
115 if (!LengthCI)
Igor Laevsky900ffa32017-02-08 14:32:04 +0000116 return nullptr;
117
118 // Check that there are not too many elements.
Daniel Neilson3faabbb2017-06-16 14:43:59 +0000119 uint64_t LengthInBytes = LengthCI->getZExtValue();
120 uint32_t ElementSizeInBytes = AMI->getElementSizeInBytes();
121 uint64_t NumElements = LengthInBytes / ElementSizeInBytes;
Igor Laevsky900ffa32017-02-08 14:32:04 +0000122 if (NumElements >= UnfoldElementAtomicMemcpyMaxElements)
123 return nullptr;
124
Daniel Neilson3faabbb2017-06-16 14:43:59 +0000125 // Only expand if there are elements to copy.
126 if (NumElements > 0) {
127 // Don't unfold into illegal integers
128 uint64_t ElementSizeInBits = ElementSizeInBytes * 8;
129 if (!getDataLayout().isLegalInteger(ElementSizeInBits))
130 return nullptr;
Igor Laevsky900ffa32017-02-08 14:32:04 +0000131
Daniel Neilson3faabbb2017-06-16 14:43:59 +0000132 // Cast source and destination to the correct type. Intrinsic input
133 // arguments are usually represented as i8*. Often operands will be
134 // explicitly casted to i8* and we can just strip those casts instead of
135 // inserting new ones. However it's easier to rely on other InstCombine
136 // rules which will cover trivial cases anyway.
137 Value *Src = AMI->getRawSource();
138 Value *Dst = AMI->getRawDest();
139 Type *ElementPointerType =
140 Type::getIntNPtrTy(AMI->getContext(), ElementSizeInBits,
141 Src->getType()->getPointerAddressSpace());
Igor Laevsky900ffa32017-02-08 14:32:04 +0000142
Craig Topperbb4069e2017-07-07 23:16:26 +0000143 Value *SrcCasted = Builder.CreatePointerCast(Src, ElementPointerType,
144 "memcpy_unfold.src_casted");
145 Value *DstCasted = Builder.CreatePointerCast(Dst, ElementPointerType,
146 "memcpy_unfold.dst_casted");
Igor Laevsky900ffa32017-02-08 14:32:04 +0000147
Daniel Neilson3faabbb2017-06-16 14:43:59 +0000148 for (uint64_t i = 0; i < NumElements; ++i) {
149 // Get current element addresses
150 ConstantInt *ElementIdxCI =
151 ConstantInt::get(AMI->getContext(), APInt(64, i));
152 Value *SrcElementAddr =
Craig Topperbb4069e2017-07-07 23:16:26 +0000153 Builder.CreateGEP(SrcCasted, ElementIdxCI, "memcpy_unfold.src_addr");
Daniel Neilson3faabbb2017-06-16 14:43:59 +0000154 Value *DstElementAddr =
Craig Topperbb4069e2017-07-07 23:16:26 +0000155 Builder.CreateGEP(DstCasted, ElementIdxCI, "memcpy_unfold.dst_addr");
Igor Laevsky900ffa32017-02-08 14:32:04 +0000156
Daniel Neilson3faabbb2017-06-16 14:43:59 +0000157 // Load from the source. Transfer alignment information and mark load as
158 // unordered atomic.
Craig Topperbb4069e2017-07-07 23:16:26 +0000159 LoadInst *Load = Builder.CreateLoad(SrcElementAddr, "memcpy_unfold.val");
Daniel Neilson3faabbb2017-06-16 14:43:59 +0000160 Load->setOrdering(AtomicOrdering::Unordered);
161 // We know alignment of the first element. It is also guaranteed by the
162 // verifier that element size is less or equal than first element
163 // alignment and both of this values are powers of two. This means that
164 // all subsequent accesses are at least element size aligned.
165 // TODO: We can infer better alignment but there is no evidence that this
166 // will matter.
167 Load->setAlignment(i == 0 ? AMI->getParamAlignment(1)
168 : ElementSizeInBytes);
169 Load->setDebugLoc(AMI->getDebugLoc());
Igor Laevsky900ffa32017-02-08 14:32:04 +0000170
Daniel Neilson3faabbb2017-06-16 14:43:59 +0000171 // Store loaded value via unordered atomic store.
Craig Topperbb4069e2017-07-07 23:16:26 +0000172 StoreInst *Store = Builder.CreateStore(Load, DstElementAddr);
Daniel Neilson3faabbb2017-06-16 14:43:59 +0000173 Store->setOrdering(AtomicOrdering::Unordered);
174 Store->setAlignment(i == 0 ? AMI->getParamAlignment(0)
175 : ElementSizeInBytes);
176 Store->setDebugLoc(AMI->getDebugLoc());
177 }
Igor Laevsky900ffa32017-02-08 14:32:04 +0000178 }
179
180 // Set the number of elements of the copy to 0, it will be deleted on the
181 // next iteration.
Daniel Neilson3faabbb2017-06-16 14:43:59 +0000182 AMI->setLength(Constant::getNullValue(LengthCI->getType()));
Igor Laevsky900ffa32017-02-08 14:32:04 +0000183 return AMI;
184}
185
Pete Cooper67cf9a72015-11-19 05:56:52 +0000186Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000187 unsigned DstAlign = getKnownAlignment(MI->getArgOperand(0), DL, MI, &AC, &DT);
188 unsigned SrcAlign = getKnownAlignment(MI->getArgOperand(1), DL, MI, &AC, &DT);
Pete Cooper67cf9a72015-11-19 05:56:52 +0000189 unsigned MinAlign = std::min(DstAlign, SrcAlign);
190 unsigned CopyAlign = MI->getAlignment();
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000191
Pete Cooper67cf9a72015-11-19 05:56:52 +0000192 if (CopyAlign < MinAlign) {
193 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(), MinAlign, false));
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000194 return MI;
195 }
Jim Grosbach7815f562012-02-03 00:07:04 +0000196
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000197 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
198 // load/store.
Gabor Greif0a136c92010-06-24 13:54:33 +0000199 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getArgOperand(2));
Craig Topperf40110f2014-04-25 05:29:35 +0000200 if (!MemOpLength) return nullptr;
Jim Grosbach7815f562012-02-03 00:07:04 +0000201
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000202 // Source and destination pointer types are always "i8*" for intrinsic. See
203 // if the size is something we can handle with a single primitive load/store.
204 // A single load+store correctly handles overlapping memory in the memmove
205 // case.
Michael Liao69e172a2012-08-15 03:49:59 +0000206 uint64_t Size = MemOpLength->getLimitedValue();
Alp Tokercb402912014-01-24 17:20:08 +0000207 assert(Size && "0-sized memory transferring should be removed already.");
Jim Grosbach7815f562012-02-03 00:07:04 +0000208
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000209 if (Size > 8 || (Size&(Size-1)))
Craig Topperf40110f2014-04-25 05:29:35 +0000210 return nullptr; // If not 1/2/4/8 bytes, exit.
Jim Grosbach7815f562012-02-03 00:07:04 +0000211
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000212 // Use an integer load+store unless we can find something better.
Mon P Wangc576ee92010-04-04 03:10:48 +0000213 unsigned SrcAddrSp =
Gabor Greif0a136c92010-06-24 13:54:33 +0000214 cast<PointerType>(MI->getArgOperand(1)->getType())->getAddressSpace();
Gabor Greiff3755202010-04-16 15:33:14 +0000215 unsigned DstAddrSp =
Gabor Greif0a136c92010-06-24 13:54:33 +0000216 cast<PointerType>(MI->getArgOperand(0)->getType())->getAddressSpace();
Mon P Wangc576ee92010-04-04 03:10:48 +0000217
Chris Lattner229907c2011-07-18 04:54:35 +0000218 IntegerType* IntType = IntegerType::get(MI->getContext(), Size<<3);
Mon P Wangc576ee92010-04-04 03:10:48 +0000219 Type *NewSrcPtrTy = PointerType::get(IntType, SrcAddrSp);
220 Type *NewDstPtrTy = PointerType::get(IntType, DstAddrSp);
Jim Grosbach7815f562012-02-03 00:07:04 +0000221
Mikael Holmen760dc9a2017-03-01 06:45:20 +0000222 // If the memcpy has metadata describing the members, see if we can get the
223 // TBAA tag describing our copy.
Craig Topperf40110f2014-04-25 05:29:35 +0000224 MDNode *CopyMD = nullptr;
Mikael Holmen760dc9a2017-03-01 06:45:20 +0000225 if (MDNode *M = MI->getMetadata(LLVMContext::MD_tbaa_struct)) {
226 if (M->getNumOperands() == 3 && M->getOperand(0) &&
227 mdconst::hasa<ConstantInt>(M->getOperand(0)) &&
Craig Topper79ab6432017-07-06 18:39:47 +0000228 mdconst::extract<ConstantInt>(M->getOperand(0))->isZero() &&
Mikael Holmen760dc9a2017-03-01 06:45:20 +0000229 M->getOperand(1) &&
230 mdconst::hasa<ConstantInt>(M->getOperand(1)) &&
231 mdconst::extract<ConstantInt>(M->getOperand(1))->getValue() ==
232 Size &&
233 M->getOperand(2) && isa<MDNode>(M->getOperand(2)))
234 CopyMD = cast<MDNode>(M->getOperand(2));
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000235 }
Jim Grosbach7815f562012-02-03 00:07:04 +0000236
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000237 // If the memcpy/memmove provides better alignment info than we can
238 // infer, use it.
Pete Cooper67cf9a72015-11-19 05:56:52 +0000239 SrcAlign = std::max(SrcAlign, CopyAlign);
240 DstAlign = std::max(DstAlign, CopyAlign);
Jim Grosbach7815f562012-02-03 00:07:04 +0000241
Craig Topperbb4069e2017-07-07 23:16:26 +0000242 Value *Src = Builder.CreateBitCast(MI->getArgOperand(1), NewSrcPtrTy);
243 Value *Dest = Builder.CreateBitCast(MI->getArgOperand(0), NewDstPtrTy);
244 LoadInst *L = Builder.CreateLoad(Src, MI->isVolatile());
Eli Friedman49346012011-05-18 19:57:14 +0000245 L->setAlignment(SrcAlign);
Dan Gohman3f553c22012-09-13 21:51:01 +0000246 if (CopyMD)
247 L->setMetadata(LLVMContext::MD_tbaa, CopyMD);
Dorit Nuzmanabd15f62016-09-04 07:49:39 +0000248 MDNode *LoopMemParallelMD =
249 MI->getMetadata(LLVMContext::MD_mem_parallel_loop_access);
250 if (LoopMemParallelMD)
251 L->setMetadata(LLVMContext::MD_mem_parallel_loop_access, LoopMemParallelMD);
Dorit Nuzman7673ba72016-09-04 07:06:00 +0000252
Craig Topperbb4069e2017-07-07 23:16:26 +0000253 StoreInst *S = Builder.CreateStore(L, Dest, MI->isVolatile());
Eli Friedman49346012011-05-18 19:57:14 +0000254 S->setAlignment(DstAlign);
Dan Gohman3f553c22012-09-13 21:51:01 +0000255 if (CopyMD)
256 S->setMetadata(LLVMContext::MD_tbaa, CopyMD);
Dorit Nuzmanabd15f62016-09-04 07:49:39 +0000257 if (LoopMemParallelMD)
258 S->setMetadata(LLVMContext::MD_mem_parallel_loop_access, LoopMemParallelMD);
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000259
260 // Set the size of the copy to 0, it will be deleted on the next iteration.
Gabor Greif5b1370e2010-06-28 16:50:57 +0000261 MI->setArgOperand(2, Constant::getNullValue(MemOpLength->getType()));
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000262 return MI;
263}
264
265Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000266 unsigned Alignment = getKnownAlignment(MI->getDest(), DL, MI, &AC, &DT);
Pete Cooper67cf9a72015-11-19 05:56:52 +0000267 if (MI->getAlignment() < Alignment) {
268 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
269 Alignment, false));
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000270 return MI;
271 }
Jim Grosbach7815f562012-02-03 00:07:04 +0000272
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000273 // Extract the length and alignment and fill if they are constant.
274 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
275 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
Duncan Sands9dff9be2010-02-15 16:12:20 +0000276 if (!LenC || !FillC || !FillC->getType()->isIntegerTy(8))
Craig Topperf40110f2014-04-25 05:29:35 +0000277 return nullptr;
Michael Liao69e172a2012-08-15 03:49:59 +0000278 uint64_t Len = LenC->getLimitedValue();
Pete Cooper67cf9a72015-11-19 05:56:52 +0000279 Alignment = MI->getAlignment();
Michael Liao69e172a2012-08-15 03:49:59 +0000280 assert(Len && "0-sized memory setting should be removed already.");
Jim Grosbach7815f562012-02-03 00:07:04 +0000281
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000282 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
283 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
Chris Lattner229907c2011-07-18 04:54:35 +0000284 Type *ITy = IntegerType::get(MI->getContext(), Len*8); // n=1 -> i8.
Jim Grosbach7815f562012-02-03 00:07:04 +0000285
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000286 Value *Dest = MI->getDest();
Mon P Wang1991c472010-12-20 01:05:30 +0000287 unsigned DstAddrSp = cast<PointerType>(Dest->getType())->getAddressSpace();
288 Type *NewDstPtrTy = PointerType::get(ITy, DstAddrSp);
Craig Topperbb4069e2017-07-07 23:16:26 +0000289 Dest = Builder.CreateBitCast(Dest, NewDstPtrTy);
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000290
291 // Alignment 0 is identity for alignment 1 for memset, but not store.
292 if (Alignment == 0) Alignment = 1;
Jim Grosbach7815f562012-02-03 00:07:04 +0000293
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000294 // Extract the fill value and store.
295 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
Craig Topperbb4069e2017-07-07 23:16:26 +0000296 StoreInst *S = Builder.CreateStore(ConstantInt::get(ITy, Fill), Dest,
297 MI->isVolatile());
Eli Friedman49346012011-05-18 19:57:14 +0000298 S->setAlignment(Alignment);
Jim Grosbach7815f562012-02-03 00:07:04 +0000299
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000300 // Set the size of the copy to 0, it will be deleted on the next iteration.
301 MI->setLength(Constant::getNullValue(LenC->getType()));
302 return MI;
303 }
304
Simon Pilgrim18617d12015-08-05 08:18:00 +0000305 return nullptr;
306}
307
Sanjay Patel6038d3e2016-01-29 23:27:03 +0000308static Value *simplifyX86immShift(const IntrinsicInst &II,
Simon Pilgrimbecd5e82015-08-13 07:39:03 +0000309 InstCombiner::BuilderTy &Builder) {
310 bool LogicalShift = false;
311 bool ShiftLeft = false;
312
313 switch (II.getIntrinsicID()) {
Craig Topperb4173a52016-11-13 07:26:19 +0000314 default: llvm_unreachable("Unexpected intrinsic!");
Simon Pilgrimbecd5e82015-08-13 07:39:03 +0000315 case Intrinsic::x86_sse2_psra_d:
316 case Intrinsic::x86_sse2_psra_w:
317 case Intrinsic::x86_sse2_psrai_d:
318 case Intrinsic::x86_sse2_psrai_w:
319 case Intrinsic::x86_avx2_psra_d:
320 case Intrinsic::x86_avx2_psra_w:
321 case Intrinsic::x86_avx2_psrai_d:
322 case Intrinsic::x86_avx2_psrai_w:
Craig Topper8b831cb2016-11-13 01:51:55 +0000323 case Intrinsic::x86_avx512_psra_q_128:
324 case Intrinsic::x86_avx512_psrai_q_128:
325 case Intrinsic::x86_avx512_psra_q_256:
326 case Intrinsic::x86_avx512_psrai_q_256:
327 case Intrinsic::x86_avx512_psra_d_512:
328 case Intrinsic::x86_avx512_psra_q_512:
329 case Intrinsic::x86_avx512_psra_w_512:
330 case Intrinsic::x86_avx512_psrai_d_512:
331 case Intrinsic::x86_avx512_psrai_q_512:
332 case Intrinsic::x86_avx512_psrai_w_512:
Simon Pilgrimbecd5e82015-08-13 07:39:03 +0000333 LogicalShift = false; ShiftLeft = false;
334 break;
335 case Intrinsic::x86_sse2_psrl_d:
336 case Intrinsic::x86_sse2_psrl_q:
337 case Intrinsic::x86_sse2_psrl_w:
338 case Intrinsic::x86_sse2_psrli_d:
339 case Intrinsic::x86_sse2_psrli_q:
340 case Intrinsic::x86_sse2_psrli_w:
341 case Intrinsic::x86_avx2_psrl_d:
342 case Intrinsic::x86_avx2_psrl_q:
343 case Intrinsic::x86_avx2_psrl_w:
344 case Intrinsic::x86_avx2_psrli_d:
345 case Intrinsic::x86_avx2_psrli_q:
346 case Intrinsic::x86_avx2_psrli_w:
Craig Topper8b831cb2016-11-13 01:51:55 +0000347 case Intrinsic::x86_avx512_psrl_d_512:
348 case Intrinsic::x86_avx512_psrl_q_512:
349 case Intrinsic::x86_avx512_psrl_w_512:
350 case Intrinsic::x86_avx512_psrli_d_512:
351 case Intrinsic::x86_avx512_psrli_q_512:
352 case Intrinsic::x86_avx512_psrli_w_512:
Simon Pilgrimbecd5e82015-08-13 07:39:03 +0000353 LogicalShift = true; ShiftLeft = false;
354 break;
355 case Intrinsic::x86_sse2_psll_d:
356 case Intrinsic::x86_sse2_psll_q:
357 case Intrinsic::x86_sse2_psll_w:
358 case Intrinsic::x86_sse2_pslli_d:
359 case Intrinsic::x86_sse2_pslli_q:
360 case Intrinsic::x86_sse2_pslli_w:
361 case Intrinsic::x86_avx2_psll_d:
362 case Intrinsic::x86_avx2_psll_q:
363 case Intrinsic::x86_avx2_psll_w:
364 case Intrinsic::x86_avx2_pslli_d:
365 case Intrinsic::x86_avx2_pslli_q:
366 case Intrinsic::x86_avx2_pslli_w:
Craig Topper8b831cb2016-11-13 01:51:55 +0000367 case Intrinsic::x86_avx512_psll_d_512:
368 case Intrinsic::x86_avx512_psll_q_512:
369 case Intrinsic::x86_avx512_psll_w_512:
370 case Intrinsic::x86_avx512_pslli_d_512:
371 case Intrinsic::x86_avx512_pslli_q_512:
372 case Intrinsic::x86_avx512_pslli_w_512:
Simon Pilgrimbecd5e82015-08-13 07:39:03 +0000373 LogicalShift = true; ShiftLeft = true;
374 break;
375 }
Simon Pilgrima3a72b42015-08-10 20:21:15 +0000376 assert((LogicalShift || !ShiftLeft) && "Only logical shifts can shift left");
377
Simon Pilgrim3815c162015-08-07 18:22:50 +0000378 // Simplify if count is constant.
379 auto Arg1 = II.getArgOperand(1);
380 auto CAZ = dyn_cast<ConstantAggregateZero>(Arg1);
381 auto CDV = dyn_cast<ConstantDataVector>(Arg1);
382 auto CInt = dyn_cast<ConstantInt>(Arg1);
383 if (!CAZ && !CDV && !CInt)
Simon Pilgrim18617d12015-08-05 08:18:00 +0000384 return nullptr;
Simon Pilgrim3815c162015-08-07 18:22:50 +0000385
386 APInt Count(64, 0);
387 if (CDV) {
388 // SSE2/AVX2 uses all the first 64-bits of the 128-bit vector
389 // operand to compute the shift amount.
390 auto VT = cast<VectorType>(CDV->getType());
391 unsigned BitWidth = VT->getElementType()->getPrimitiveSizeInBits();
392 assert((64 % BitWidth) == 0 && "Unexpected packed shift size");
393 unsigned NumSubElts = 64 / BitWidth;
394
395 // Concatenate the sub-elements to create the 64-bit value.
396 for (unsigned i = 0; i != NumSubElts; ++i) {
397 unsigned SubEltIdx = (NumSubElts - 1) - i;
398 auto SubElt = cast<ConstantInt>(CDV->getElementAsConstant(SubEltIdx));
Craig Topper24e71012017-04-28 03:36:24 +0000399 Count <<= BitWidth;
Simon Pilgrim3815c162015-08-07 18:22:50 +0000400 Count |= SubElt->getValue().zextOrTrunc(64);
401 }
402 }
403 else if (CInt)
404 Count = CInt->getValue();
Simon Pilgrim18617d12015-08-05 08:18:00 +0000405
406 auto Vec = II.getArgOperand(0);
407 auto VT = cast<VectorType>(Vec->getType());
408 auto SVT = VT->getElementType();
Simon Pilgrim3815c162015-08-07 18:22:50 +0000409 unsigned VWidth = VT->getNumElements();
410 unsigned BitWidth = SVT->getPrimitiveSizeInBits();
411
412 // If shift-by-zero then just return the original value.
Craig Topper73ba1c82017-06-07 07:40:37 +0000413 if (Count.isNullValue())
Simon Pilgrim3815c162015-08-07 18:22:50 +0000414 return Vec;
415
Simon Pilgrima3a72b42015-08-10 20:21:15 +0000416 // Handle cases when Shift >= BitWidth.
417 if (Count.uge(BitWidth)) {
418 // If LogicalShift - just return zero.
419 if (LogicalShift)
420 return ConstantAggregateZero::get(VT);
421
422 // If ArithmeticShift - clamp Shift to (BitWidth - 1).
423 Count = APInt(64, BitWidth - 1);
424 }
Simon Pilgrim18617d12015-08-05 08:18:00 +0000425
Simon Pilgrim18617d12015-08-05 08:18:00 +0000426 // Get a constant vector of the same type as the first operand.
Simon Pilgrim3815c162015-08-07 18:22:50 +0000427 auto ShiftAmt = ConstantInt::get(SVT, Count.zextOrTrunc(BitWidth));
428 auto ShiftVec = Builder.CreateVectorSplat(VWidth, ShiftAmt);
Simon Pilgrim18617d12015-08-05 08:18:00 +0000429
430 if (ShiftLeft)
Simon Pilgrim3815c162015-08-07 18:22:50 +0000431 return Builder.CreateShl(Vec, ShiftVec);
Simon Pilgrim18617d12015-08-05 08:18:00 +0000432
Simon Pilgrima3a72b42015-08-10 20:21:15 +0000433 if (LogicalShift)
434 return Builder.CreateLShr(Vec, ShiftVec);
435
436 return Builder.CreateAShr(Vec, ShiftVec);
Simon Pilgrim18617d12015-08-05 08:18:00 +0000437}
438
Simon Pilgrimdb9893f2016-06-07 10:27:15 +0000439// Attempt to simplify AVX2 per-element shift intrinsics to a generic IR shift.
440// Unlike the generic IR shifts, the intrinsics have defined behaviour for out
441// of range shift amounts (logical - set to zero, arithmetic - splat sign bit).
442static Value *simplifyX86varShift(const IntrinsicInst &II,
443 InstCombiner::BuilderTy &Builder) {
444 bool LogicalShift = false;
445 bool ShiftLeft = false;
446
447 switch (II.getIntrinsicID()) {
Craig Topperb4173a52016-11-13 07:26:19 +0000448 default: llvm_unreachable("Unexpected intrinsic!");
Simon Pilgrimdb9893f2016-06-07 10:27:15 +0000449 case Intrinsic::x86_avx2_psrav_d:
450 case Intrinsic::x86_avx2_psrav_d_256:
Craig Topperb4173a52016-11-13 07:26:19 +0000451 case Intrinsic::x86_avx512_psrav_q_128:
452 case Intrinsic::x86_avx512_psrav_q_256:
453 case Intrinsic::x86_avx512_psrav_d_512:
454 case Intrinsic::x86_avx512_psrav_q_512:
Craig Topper1de753f2016-11-18 06:04:33 +0000455 case Intrinsic::x86_avx512_psrav_w_128:
456 case Intrinsic::x86_avx512_psrav_w_256:
457 case Intrinsic::x86_avx512_psrav_w_512:
Simon Pilgrimdb9893f2016-06-07 10:27:15 +0000458 LogicalShift = false;
459 ShiftLeft = false;
460 break;
461 case Intrinsic::x86_avx2_psrlv_d:
462 case Intrinsic::x86_avx2_psrlv_d_256:
463 case Intrinsic::x86_avx2_psrlv_q:
464 case Intrinsic::x86_avx2_psrlv_q_256:
Craig Topperb4173a52016-11-13 07:26:19 +0000465 case Intrinsic::x86_avx512_psrlv_d_512:
466 case Intrinsic::x86_avx512_psrlv_q_512:
Craig Topper1de753f2016-11-18 06:04:33 +0000467 case Intrinsic::x86_avx512_psrlv_w_128:
468 case Intrinsic::x86_avx512_psrlv_w_256:
469 case Intrinsic::x86_avx512_psrlv_w_512:
Simon Pilgrimdb9893f2016-06-07 10:27:15 +0000470 LogicalShift = true;
471 ShiftLeft = false;
472 break;
473 case Intrinsic::x86_avx2_psllv_d:
474 case Intrinsic::x86_avx2_psllv_d_256:
475 case Intrinsic::x86_avx2_psllv_q:
476 case Intrinsic::x86_avx2_psllv_q_256:
Craig Topperb4173a52016-11-13 07:26:19 +0000477 case Intrinsic::x86_avx512_psllv_d_512:
478 case Intrinsic::x86_avx512_psllv_q_512:
Craig Topper1de753f2016-11-18 06:04:33 +0000479 case Intrinsic::x86_avx512_psllv_w_128:
480 case Intrinsic::x86_avx512_psllv_w_256:
481 case Intrinsic::x86_avx512_psllv_w_512:
Simon Pilgrimdb9893f2016-06-07 10:27:15 +0000482 LogicalShift = true;
483 ShiftLeft = true;
484 break;
485 }
486 assert((LogicalShift || !ShiftLeft) && "Only logical shifts can shift left");
487
488 // Simplify if all shift amounts are constant/undef.
489 auto *CShift = dyn_cast<Constant>(II.getArgOperand(1));
490 if (!CShift)
491 return nullptr;
492
493 auto Vec = II.getArgOperand(0);
494 auto VT = cast<VectorType>(II.getType());
495 auto SVT = VT->getVectorElementType();
496 int NumElts = VT->getNumElements();
497 int BitWidth = SVT->getIntegerBitWidth();
498
499 // Collect each element's shift amount.
500 // We also collect special cases: UNDEF = -1, OUT-OF-RANGE = BitWidth.
501 bool AnyOutOfRange = false;
502 SmallVector<int, 8> ShiftAmts;
503 for (int I = 0; I < NumElts; ++I) {
504 auto *CElt = CShift->getAggregateElement(I);
505 if (CElt && isa<UndefValue>(CElt)) {
506 ShiftAmts.push_back(-1);
507 continue;
508 }
509
510 auto *COp = dyn_cast_or_null<ConstantInt>(CElt);
511 if (!COp)
512 return nullptr;
513
514 // Handle out of range shifts.
515 // If LogicalShift - set to BitWidth (special case).
516 // If ArithmeticShift - set to (BitWidth - 1) (sign splat).
517 APInt ShiftVal = COp->getValue();
518 if (ShiftVal.uge(BitWidth)) {
519 AnyOutOfRange = LogicalShift;
520 ShiftAmts.push_back(LogicalShift ? BitWidth : BitWidth - 1);
521 continue;
522 }
523
524 ShiftAmts.push_back((int)ShiftVal.getZExtValue());
525 }
526
527 // If all elements out of range or UNDEF, return vector of zeros/undefs.
528 // ArithmeticShift should only hit this if they are all UNDEF.
529 auto OutOfRange = [&](int Idx) { return (Idx < 0) || (BitWidth <= Idx); };
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000530 if (llvm::all_of(ShiftAmts, OutOfRange)) {
Simon Pilgrimdb9893f2016-06-07 10:27:15 +0000531 SmallVector<Constant *, 8> ConstantVec;
532 for (int Idx : ShiftAmts) {
533 if (Idx < 0) {
534 ConstantVec.push_back(UndefValue::get(SVT));
535 } else {
536 assert(LogicalShift && "Logical shift expected");
537 ConstantVec.push_back(ConstantInt::getNullValue(SVT));
538 }
539 }
540 return ConstantVector::get(ConstantVec);
541 }
542
543 // We can't handle only some out of range values with generic logical shifts.
544 if (AnyOutOfRange)
545 return nullptr;
546
547 // Build the shift amount constant vector.
548 SmallVector<Constant *, 8> ShiftVecAmts;
549 for (int Idx : ShiftAmts) {
550 if (Idx < 0)
551 ShiftVecAmts.push_back(UndefValue::get(SVT));
552 else
553 ShiftVecAmts.push_back(ConstantInt::get(SVT, Idx));
554 }
555 auto ShiftVec = ConstantVector::get(ShiftVecAmts);
556
557 if (ShiftLeft)
558 return Builder.CreateShl(Vec, ShiftVec);
559
560 if (LogicalShift)
561 return Builder.CreateLShr(Vec, ShiftVec);
562
563 return Builder.CreateAShr(Vec, ShiftVec);
564}
565
Simon Pilgrimf6f3a3612017-01-23 15:22:59 +0000566static Value *simplifyX86muldq(const IntrinsicInst &II,
567 InstCombiner::BuilderTy &Builder) {
Simon Pilgrima50a93f2017-01-20 18:20:30 +0000568 Value *Arg0 = II.getArgOperand(0);
569 Value *Arg1 = II.getArgOperand(1);
570 Type *ResTy = II.getType();
Simon Pilgrimf6f3a3612017-01-23 15:22:59 +0000571 assert(Arg0->getType()->getScalarSizeInBits() == 32 &&
572 Arg1->getType()->getScalarSizeInBits() == 32 &&
573 ResTy->getScalarSizeInBits() == 64 && "Unexpected muldq/muludq types");
Simon Pilgrima50a93f2017-01-20 18:20:30 +0000574
Simon Pilgrimbb13fda2017-01-23 12:07:32 +0000575 // muldq/muludq(undef, undef) -> zero (matches generic mul behavior)
Simon Pilgrim78f86302017-01-24 11:07:41 +0000576 if (isa<UndefValue>(Arg0) || isa<UndefValue>(Arg1))
Simon Pilgrimbb13fda2017-01-23 12:07:32 +0000577 return ConstantAggregateZero::get(ResTy);
Simon Pilgrima50a93f2017-01-20 18:20:30 +0000578
Simon Pilgrimf6f3a3612017-01-23 15:22:59 +0000579 // Constant folding.
580 // PMULDQ = (mul(vXi64 sext(shuffle<0,2,..>(Arg0)),
581 // vXi64 sext(shuffle<0,2,..>(Arg1))))
582 // PMULUDQ = (mul(vXi64 zext(shuffle<0,2,..>(Arg0)),
583 // vXi64 zext(shuffle<0,2,..>(Arg1))))
584 if (!isa<Constant>(Arg0) || !isa<Constant>(Arg1))
585 return nullptr;
586
587 unsigned NumElts = ResTy->getVectorNumElements();
588 assert(Arg0->getType()->getVectorNumElements() == (2 * NumElts) &&
589 Arg1->getType()->getVectorNumElements() == (2 * NumElts) &&
590 "Unexpected muldq/muludq types");
591
592 unsigned IntrinsicID = II.getIntrinsicID();
593 bool IsSigned = (Intrinsic::x86_sse41_pmuldq == IntrinsicID ||
594 Intrinsic::x86_avx2_pmul_dq == IntrinsicID ||
595 Intrinsic::x86_avx512_pmul_dq_512 == IntrinsicID);
596
597 SmallVector<unsigned, 16> ShuffleMask;
598 for (unsigned i = 0; i != NumElts; ++i)
599 ShuffleMask.push_back(i * 2);
600
601 auto *LHS = Builder.CreateShuffleVector(Arg0, Arg0, ShuffleMask);
602 auto *RHS = Builder.CreateShuffleVector(Arg1, Arg1, ShuffleMask);
603
604 if (IsSigned) {
605 LHS = Builder.CreateSExt(LHS, ResTy);
606 RHS = Builder.CreateSExt(RHS, ResTy);
607 } else {
608 LHS = Builder.CreateZExt(LHS, ResTy);
609 RHS = Builder.CreateZExt(RHS, ResTy);
610 }
611
612 return Builder.CreateMul(LHS, RHS);
Simon Pilgrima50a93f2017-01-20 18:20:30 +0000613}
614
Craig Topper4853c432017-07-06 23:18:42 +0000615static Value *simplifyX86pack(IntrinsicInst &II, bool IsSigned) {
Simon Pilgrim6f6b2792017-01-25 14:37:24 +0000616 Value *Arg0 = II.getArgOperand(0);
617 Value *Arg1 = II.getArgOperand(1);
618 Type *ResTy = II.getType();
619
620 // Fast all undef handling.
621 if (isa<UndefValue>(Arg0) && isa<UndefValue>(Arg1))
622 return UndefValue::get(ResTy);
623
624 Type *ArgTy = Arg0->getType();
625 unsigned NumLanes = ResTy->getPrimitiveSizeInBits() / 128;
626 unsigned NumDstElts = ResTy->getVectorNumElements();
627 unsigned NumSrcElts = ArgTy->getVectorNumElements();
628 assert(NumDstElts == (2 * NumSrcElts) && "Unexpected packing types");
629
630 unsigned NumDstEltsPerLane = NumDstElts / NumLanes;
631 unsigned NumSrcEltsPerLane = NumSrcElts / NumLanes;
632 unsigned DstScalarSizeInBits = ResTy->getScalarSizeInBits();
633 assert(ArgTy->getScalarSizeInBits() == (2 * DstScalarSizeInBits) &&
634 "Unexpected packing types");
635
636 // Constant folding.
637 auto *Cst0 = dyn_cast<Constant>(Arg0);
638 auto *Cst1 = dyn_cast<Constant>(Arg1);
639 if (!Cst0 || !Cst1)
640 return nullptr;
641
642 SmallVector<Constant *, 32> Vals;
643 for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
644 for (unsigned Elt = 0; Elt != NumDstEltsPerLane; ++Elt) {
645 unsigned SrcIdx = Lane * NumSrcEltsPerLane + Elt % NumSrcEltsPerLane;
646 auto *Cst = (Elt >= NumSrcEltsPerLane) ? Cst1 : Cst0;
647 auto *COp = Cst->getAggregateElement(SrcIdx);
648 if (COp && isa<UndefValue>(COp)) {
649 Vals.push_back(UndefValue::get(ResTy->getScalarType()));
650 continue;
651 }
652
653 auto *CInt = dyn_cast_or_null<ConstantInt>(COp);
654 if (!CInt)
655 return nullptr;
656
657 APInt Val = CInt->getValue();
658 assert(Val.getBitWidth() == ArgTy->getScalarSizeInBits() &&
659 "Unexpected constant bitwidth");
660
661 if (IsSigned) {
662 // PACKSS: Truncate signed value with signed saturation.
663 // Source values less than dst minint are saturated to minint.
664 // Source values greater than dst maxint are saturated to maxint.
665 if (Val.isSignedIntN(DstScalarSizeInBits))
666 Val = Val.trunc(DstScalarSizeInBits);
667 else if (Val.isNegative())
668 Val = APInt::getSignedMinValue(DstScalarSizeInBits);
669 else
670 Val = APInt::getSignedMaxValue(DstScalarSizeInBits);
671 } else {
672 // PACKUS: Truncate signed value with unsigned saturation.
673 // Source values less than zero are saturated to zero.
674 // Source values greater than dst maxuint are saturated to maxuint.
675 if (Val.isIntN(DstScalarSizeInBits))
676 Val = Val.trunc(DstScalarSizeInBits);
677 else if (Val.isNegative())
678 Val = APInt::getNullValue(DstScalarSizeInBits);
679 else
680 Val = APInt::getAllOnesValue(DstScalarSizeInBits);
681 }
682
683 Vals.push_back(ConstantInt::get(ResTy->getScalarType(), Val));
684 }
685 }
686
687 return ConstantVector::get(Vals);
688}
689
Craig Topper4853c432017-07-06 23:18:42 +0000690static Value *simplifyX86movmsk(const IntrinsicInst &II) {
Simon Pilgrim91e3ac82016-06-07 08:18:35 +0000691 Value *Arg = II.getArgOperand(0);
692 Type *ResTy = II.getType();
693 Type *ArgTy = Arg->getType();
694
695 // movmsk(undef) -> zero as we must ensure the upper bits are zero.
696 if (isa<UndefValue>(Arg))
697 return Constant::getNullValue(ResTy);
698
699 // We can't easily peek through x86_mmx types.
700 if (!ArgTy->isVectorTy())
701 return nullptr;
702
703 auto *C = dyn_cast<Constant>(Arg);
704 if (!C)
705 return nullptr;
706
707 // Extract signbits of the vector input and pack into integer result.
708 APInt Result(ResTy->getPrimitiveSizeInBits(), 0);
709 for (unsigned I = 0, E = ArgTy->getVectorNumElements(); I != E; ++I) {
710 auto *COp = C->getAggregateElement(I);
711 if (!COp)
712 return nullptr;
713 if (isa<UndefValue>(COp))
714 continue;
715
716 auto *CInt = dyn_cast<ConstantInt>(COp);
717 auto *CFp = dyn_cast<ConstantFP>(COp);
718 if (!CInt && !CFp)
719 return nullptr;
720
721 if ((CInt && CInt->isNegative()) || (CFp && CFp->isNegative()))
722 Result.setBit(I);
723 }
724
725 return Constant::getIntegerValue(ResTy, Result);
726}
727
Sanjay Patel6038d3e2016-01-29 23:27:03 +0000728static Value *simplifyX86insertps(const IntrinsicInst &II,
Sanjay Patelc86867c2015-04-16 17:52:13 +0000729 InstCombiner::BuilderTy &Builder) {
Sanjay Patel03c03f52016-01-28 00:03:16 +0000730 auto *CInt = dyn_cast<ConstantInt>(II.getArgOperand(2));
731 if (!CInt)
732 return nullptr;
Simon Pilgrim54fcd622015-07-25 20:41:00 +0000733
Sanjay Patel03c03f52016-01-28 00:03:16 +0000734 VectorType *VecTy = cast<VectorType>(II.getType());
735 assert(VecTy->getNumElements() == 4 && "insertps with wrong vector type");
Sanjay Patelc86867c2015-04-16 17:52:13 +0000736
Sanjay Patel03c03f52016-01-28 00:03:16 +0000737 // The immediate permute control byte looks like this:
738 // [3:0] - zero mask for each 32-bit lane
739 // [5:4] - select one 32-bit destination lane
740 // [7:6] - select one 32-bit source lane
Sanjay Patelc86867c2015-04-16 17:52:13 +0000741
Sanjay Patel03c03f52016-01-28 00:03:16 +0000742 uint8_t Imm = CInt->getZExtValue();
743 uint8_t ZMask = Imm & 0xf;
744 uint8_t DestLane = (Imm >> 4) & 0x3;
745 uint8_t SourceLane = (Imm >> 6) & 0x3;
Sanjay Patelc1d20a32015-04-25 20:55:25 +0000746
Sanjay Patel03c03f52016-01-28 00:03:16 +0000747 ConstantAggregateZero *ZeroVector = ConstantAggregateZero::get(VecTy);
Sanjay Patelc86867c2015-04-16 17:52:13 +0000748
Sanjay Patel03c03f52016-01-28 00:03:16 +0000749 // If all zero mask bits are set, this was just a weird way to
750 // generate a zero vector.
751 if (ZMask == 0xf)
752 return ZeroVector;
Sanjay Patelc1d20a32015-04-25 20:55:25 +0000753
Sanjay Patel03c03f52016-01-28 00:03:16 +0000754 // Initialize by passing all of the first source bits through.
Craig Topper99d1eab2016-06-12 00:41:19 +0000755 uint32_t ShuffleMask[4] = { 0, 1, 2, 3 };
Sanjay Patelc1d20a32015-04-25 20:55:25 +0000756
Sanjay Patel03c03f52016-01-28 00:03:16 +0000757 // We may replace the second operand with the zero vector.
758 Value *V1 = II.getArgOperand(1);
759
760 if (ZMask) {
761 // If the zero mask is being used with a single input or the zero mask
762 // overrides the destination lane, this is a shuffle with the zero vector.
763 if ((II.getArgOperand(0) == II.getArgOperand(1)) ||
764 (ZMask & (1 << DestLane))) {
765 V1 = ZeroVector;
766 // We may still move 32-bits of the first source vector from one lane
767 // to another.
768 ShuffleMask[DestLane] = SourceLane;
769 // The zero mask may override the previous insert operation.
770 for (unsigned i = 0; i < 4; ++i)
771 if ((ZMask >> i) & 0x1)
772 ShuffleMask[i] = i + 4;
Sanjay Patelc1d20a32015-04-25 20:55:25 +0000773 } else {
Sanjay Patel03c03f52016-01-28 00:03:16 +0000774 // TODO: Model this case as 2 shuffles or a 'logical and' plus shuffle?
775 return nullptr;
Sanjay Patelc1d20a32015-04-25 20:55:25 +0000776 }
Sanjay Patel03c03f52016-01-28 00:03:16 +0000777 } else {
778 // Replace the selected destination lane with the selected source lane.
779 ShuffleMask[DestLane] = SourceLane + 4;
Sanjay Patelc86867c2015-04-16 17:52:13 +0000780 }
Sanjay Patel03c03f52016-01-28 00:03:16 +0000781
782 return Builder.CreateShuffleVector(II.getArgOperand(0), V1, ShuffleMask);
Sanjay Patelc86867c2015-04-16 17:52:13 +0000783}
784
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000785/// Attempt to simplify SSE4A EXTRQ/EXTRQI instructions using constant folding
786/// or conversion to a shuffle vector.
Sanjay Patel6038d3e2016-01-29 23:27:03 +0000787static Value *simplifyX86extrq(IntrinsicInst &II, Value *Op0,
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000788 ConstantInt *CILength, ConstantInt *CIIndex,
789 InstCombiner::BuilderTy &Builder) {
790 auto LowConstantHighUndef = [&](uint64_t Val) {
791 Type *IntTy64 = Type::getInt64Ty(II.getContext());
792 Constant *Args[] = {ConstantInt::get(IntTy64, Val),
793 UndefValue::get(IntTy64)};
794 return ConstantVector::get(Args);
795 };
796
797 // See if we're dealing with constant values.
798 Constant *C0 = dyn_cast<Constant>(Op0);
799 ConstantInt *CI0 =
Andrea Di Biagio8df5b9c2016-09-07 12:03:03 +0000800 C0 ? dyn_cast_or_null<ConstantInt>(C0->getAggregateElement((unsigned)0))
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000801 : nullptr;
802
803 // Attempt to constant fold.
804 if (CILength && CIIndex) {
805 // From AMD documentation: "The bit index and field length are each six
806 // bits in length other bits of the field are ignored."
807 APInt APIndex = CIIndex->getValue().zextOrTrunc(6);
808 APInt APLength = CILength->getValue().zextOrTrunc(6);
809
810 unsigned Index = APIndex.getZExtValue();
811
812 // From AMD documentation: "a value of zero in the field length is
813 // defined as length of 64".
814 unsigned Length = APLength == 0 ? 64 : APLength.getZExtValue();
815
816 // From AMD documentation: "If the sum of the bit index + length field
817 // is greater than 64, the results are undefined".
818 unsigned End = Index + Length;
819
820 // Note that both field index and field length are 8-bit quantities.
821 // Since variables 'Index' and 'Length' are unsigned values
822 // obtained from zero-extending field index and field length
823 // respectively, their sum should never wrap around.
824 if (End > 64)
825 return UndefValue::get(II.getType());
826
827 // If we are inserting whole bytes, we can convert this to a shuffle.
828 // Lowering can recognize EXTRQI shuffle masks.
829 if ((Length % 8) == 0 && (Index % 8) == 0) {
830 // Convert bit indices to byte indices.
831 Length /= 8;
832 Index /= 8;
833
834 Type *IntTy8 = Type::getInt8Ty(II.getContext());
835 Type *IntTy32 = Type::getInt32Ty(II.getContext());
836 VectorType *ShufTy = VectorType::get(IntTy8, 16);
837
838 SmallVector<Constant *, 16> ShuffleMask;
839 for (int i = 0; i != (int)Length; ++i)
840 ShuffleMask.push_back(
841 Constant::getIntegerValue(IntTy32, APInt(32, i + Index)));
842 for (int i = Length; i != 8; ++i)
843 ShuffleMask.push_back(
844 Constant::getIntegerValue(IntTy32, APInt(32, i + 16)));
845 for (int i = 8; i != 16; ++i)
846 ShuffleMask.push_back(UndefValue::get(IntTy32));
847
848 Value *SV = Builder.CreateShuffleVector(
849 Builder.CreateBitCast(Op0, ShufTy),
850 ConstantAggregateZero::get(ShufTy), ConstantVector::get(ShuffleMask));
851 return Builder.CreateBitCast(SV, II.getType());
852 }
853
854 // Constant Fold - shift Index'th bit to lowest position and mask off
855 // Length bits.
856 if (CI0) {
857 APInt Elt = CI0->getValue();
Craig Topperfc947bc2017-04-18 17:14:21 +0000858 Elt.lshrInPlace(Index);
859 Elt = Elt.zextOrTrunc(Length);
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000860 return LowConstantHighUndef(Elt.getZExtValue());
861 }
862
863 // If we were an EXTRQ call, we'll save registers if we convert to EXTRQI.
864 if (II.getIntrinsicID() == Intrinsic::x86_sse4a_extrq) {
865 Value *Args[] = {Op0, CILength, CIIndex};
Sanjay Patelaf674fb2015-12-14 17:24:23 +0000866 Module *M = II.getModule();
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000867 Value *F = Intrinsic::getDeclaration(M, Intrinsic::x86_sse4a_extrqi);
868 return Builder.CreateCall(F, Args);
869 }
870 }
871
872 // Constant Fold - extraction from zero is always {zero, undef}.
Craig Topperca2c8762017-07-06 18:39:49 +0000873 if (CI0 && CI0->isZero())
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000874 return LowConstantHighUndef(0);
875
876 return nullptr;
877}
878
879/// Attempt to simplify SSE4A INSERTQ/INSERTQI instructions using constant
880/// folding or conversion to a shuffle vector.
Sanjay Patel6038d3e2016-01-29 23:27:03 +0000881static Value *simplifyX86insertq(IntrinsicInst &II, Value *Op0, Value *Op1,
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000882 APInt APLength, APInt APIndex,
883 InstCombiner::BuilderTy &Builder) {
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000884 // From AMD documentation: "The bit index and field length are each six bits
885 // in length other bits of the field are ignored."
886 APIndex = APIndex.zextOrTrunc(6);
887 APLength = APLength.zextOrTrunc(6);
888
889 // Attempt to constant fold.
890 unsigned Index = APIndex.getZExtValue();
891
892 // From AMD documentation: "a value of zero in the field length is
893 // defined as length of 64".
894 unsigned Length = APLength == 0 ? 64 : APLength.getZExtValue();
895
896 // From AMD documentation: "If the sum of the bit index + length field
897 // is greater than 64, the results are undefined".
898 unsigned End = Index + Length;
899
900 // Note that both field index and field length are 8-bit quantities.
901 // Since variables 'Index' and 'Length' are unsigned values
902 // obtained from zero-extending field index and field length
903 // respectively, their sum should never wrap around.
904 if (End > 64)
905 return UndefValue::get(II.getType());
906
907 // If we are inserting whole bytes, we can convert this to a shuffle.
908 // Lowering can recognize INSERTQI shuffle masks.
909 if ((Length % 8) == 0 && (Index % 8) == 0) {
910 // Convert bit indices to byte indices.
911 Length /= 8;
912 Index /= 8;
913
914 Type *IntTy8 = Type::getInt8Ty(II.getContext());
915 Type *IntTy32 = Type::getInt32Ty(II.getContext());
916 VectorType *ShufTy = VectorType::get(IntTy8, 16);
917
918 SmallVector<Constant *, 16> ShuffleMask;
919 for (int i = 0; i != (int)Index; ++i)
920 ShuffleMask.push_back(Constant::getIntegerValue(IntTy32, APInt(32, i)));
921 for (int i = 0; i != (int)Length; ++i)
922 ShuffleMask.push_back(
923 Constant::getIntegerValue(IntTy32, APInt(32, i + 16)));
924 for (int i = Index + Length; i != 8; ++i)
925 ShuffleMask.push_back(Constant::getIntegerValue(IntTy32, APInt(32, i)));
926 for (int i = 8; i != 16; ++i)
927 ShuffleMask.push_back(UndefValue::get(IntTy32));
928
929 Value *SV = Builder.CreateShuffleVector(Builder.CreateBitCast(Op0, ShufTy),
930 Builder.CreateBitCast(Op1, ShufTy),
931 ConstantVector::get(ShuffleMask));
932 return Builder.CreateBitCast(SV, II.getType());
933 }
934
935 // See if we're dealing with constant values.
936 Constant *C0 = dyn_cast<Constant>(Op0);
937 Constant *C1 = dyn_cast<Constant>(Op1);
938 ConstantInt *CI00 =
Andrea Di Biagiof3fd3162016-09-07 12:47:53 +0000939 C0 ? dyn_cast_or_null<ConstantInt>(C0->getAggregateElement((unsigned)0))
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000940 : nullptr;
941 ConstantInt *CI10 =
Andrea Di Biagiof3fd3162016-09-07 12:47:53 +0000942 C1 ? dyn_cast_or_null<ConstantInt>(C1->getAggregateElement((unsigned)0))
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000943 : nullptr;
944
945 // Constant Fold - insert bottom Length bits starting at the Index'th bit.
946 if (CI00 && CI10) {
947 APInt V00 = CI00->getValue();
948 APInt V10 = CI10->getValue();
949 APInt Mask = APInt::getLowBitsSet(64, Length).shl(Index);
950 V00 = V00 & ~Mask;
951 V10 = V10.zextOrTrunc(Length).zextOrTrunc(64).shl(Index);
952 APInt Val = V00 | V10;
953 Type *IntTy64 = Type::getInt64Ty(II.getContext());
954 Constant *Args[] = {ConstantInt::get(IntTy64, Val.getZExtValue()),
955 UndefValue::get(IntTy64)};
956 return ConstantVector::get(Args);
957 }
958
959 // If we were an INSERTQ call, we'll save demanded elements if we convert to
960 // INSERTQI.
961 if (II.getIntrinsicID() == Intrinsic::x86_sse4a_insertq) {
962 Type *IntTy8 = Type::getInt8Ty(II.getContext());
963 Constant *CILength = ConstantInt::get(IntTy8, Length, false);
964 Constant *CIIndex = ConstantInt::get(IntTy8, Index, false);
965
966 Value *Args[] = {Op0, Op1, CILength, CIIndex};
Sanjay Patelaf674fb2015-12-14 17:24:23 +0000967 Module *M = II.getModule();
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000968 Value *F = Intrinsic::getDeclaration(M, Intrinsic::x86_sse4a_insertqi);
969 return Builder.CreateCall(F, Args);
970 }
971
972 return nullptr;
973}
974
Simon Pilgrimc0c56e72016-04-24 17:00:34 +0000975/// Attempt to convert pshufb* to shufflevector if the mask is constant.
976static Value *simplifyX86pshufb(const IntrinsicInst &II,
977 InstCombiner::BuilderTy &Builder) {
Simon Pilgrimbf60cc42016-04-29 21:34:54 +0000978 Constant *V = dyn_cast<Constant>(II.getArgOperand(1));
979 if (!V)
980 return nullptr;
981
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +0000982 auto *VecTy = cast<VectorType>(II.getType());
983 auto *MaskEltTy = Type::getInt32Ty(II.getContext());
984 unsigned NumElts = VecTy->getNumElements();
Craig Topper9a63d7a2016-12-11 00:23:50 +0000985 assert((NumElts == 16 || NumElts == 32 || NumElts == 64) &&
Simon Pilgrimc0c56e72016-04-24 17:00:34 +0000986 "Unexpected number of elements in shuffle mask!");
Simon Pilgrimbf60cc42016-04-29 21:34:54 +0000987
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +0000988 // Construct a shuffle mask from constant integers or UNDEFs.
Craig Topper9a63d7a2016-12-11 00:23:50 +0000989 Constant *Indexes[64] = {nullptr};
Simon Pilgrimc0c56e72016-04-24 17:00:34 +0000990
Simon Pilgrimbf60cc42016-04-29 21:34:54 +0000991 // Each byte in the shuffle control mask forms an index to permute the
992 // corresponding byte in the destination operand.
993 for (unsigned I = 0; I < NumElts; ++I) {
994 Constant *COp = V->getAggregateElement(I);
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +0000995 if (!COp || (!isa<UndefValue>(COp) && !isa<ConstantInt>(COp)))
Simon Pilgrimbf60cc42016-04-29 21:34:54 +0000996 return nullptr;
Simon Pilgrimc0c56e72016-04-24 17:00:34 +0000997
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +0000998 if (isa<UndefValue>(COp)) {
999 Indexes[I] = UndefValue::get(MaskEltTy);
1000 continue;
1001 }
1002
Simon Pilgrimbf60cc42016-04-29 21:34:54 +00001003 int8_t Index = cast<ConstantInt>(COp)->getValue().getZExtValue();
1004
1005 // If the most significant bit (bit[7]) of each byte of the shuffle
1006 // control mask is set, then zero is written in the result byte.
1007 // The zero vector is in the right-hand side of the resulting
1008 // shufflevector.
1009
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +00001010 // The value of each index for the high 128-bit lane is the least
1011 // significant 4 bits of the respective shuffle control byte.
1012 Index = ((Index < 0) ? NumElts : Index & 0x0F) + (I & 0xF0);
1013 Indexes[I] = ConstantInt::get(MaskEltTy, Index);
Simon Pilgrimbf60cc42016-04-29 21:34:54 +00001014 }
Simon Pilgrimc0c56e72016-04-24 17:00:34 +00001015
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +00001016 auto ShuffleMask = ConstantVector::get(makeArrayRef(Indexes, NumElts));
Simon Pilgrimc0c56e72016-04-24 17:00:34 +00001017 auto V1 = II.getArgOperand(0);
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +00001018 auto V2 = Constant::getNullValue(VecTy);
Simon Pilgrimc0c56e72016-04-24 17:00:34 +00001019 return Builder.CreateShuffleVector(V1, V2, ShuffleMask);
1020}
1021
Simon Pilgrim2f6097d2016-04-24 17:23:46 +00001022/// Attempt to convert vpermilvar* to shufflevector if the mask is constant.
1023static Value *simplifyX86vpermilvar(const IntrinsicInst &II,
1024 InstCombiner::BuilderTy &Builder) {
Simon Pilgrim640f9962016-04-30 07:23:30 +00001025 Constant *V = dyn_cast<Constant>(II.getArgOperand(1));
1026 if (!V)
1027 return nullptr;
Simon Pilgrim2f6097d2016-04-24 17:23:46 +00001028
Craig Topper58917f32016-12-11 01:59:36 +00001029 auto *VecTy = cast<VectorType>(II.getType());
Simon Pilgrimeeacc402016-05-01 20:22:42 +00001030 auto *MaskEltTy = Type::getInt32Ty(II.getContext());
Craig Topper58917f32016-12-11 01:59:36 +00001031 unsigned NumElts = VecTy->getVectorNumElements();
1032 bool IsPD = VecTy->getScalarType()->isDoubleTy();
1033 unsigned NumLaneElts = IsPD ? 2 : 4;
1034 assert(NumElts == 16 || NumElts == 8 || NumElts == 4 || NumElts == 2);
Simon Pilgrim2f6097d2016-04-24 17:23:46 +00001035
Simon Pilgrimeeacc402016-05-01 20:22:42 +00001036 // Construct a shuffle mask from constant integers or UNDEFs.
Craig Topper58917f32016-12-11 01:59:36 +00001037 Constant *Indexes[16] = {nullptr};
Simon Pilgrim640f9962016-04-30 07:23:30 +00001038
1039 // The intrinsics only read one or two bits, clear the rest.
Simon Pilgrimeeacc402016-05-01 20:22:42 +00001040 for (unsigned I = 0; I < NumElts; ++I) {
Simon Pilgrim640f9962016-04-30 07:23:30 +00001041 Constant *COp = V->getAggregateElement(I);
Simon Pilgrimeeacc402016-05-01 20:22:42 +00001042 if (!COp || (!isa<UndefValue>(COp) && !isa<ConstantInt>(COp)))
Simon Pilgrim640f9962016-04-30 07:23:30 +00001043 return nullptr;
1044
Simon Pilgrimeeacc402016-05-01 20:22:42 +00001045 if (isa<UndefValue>(COp)) {
1046 Indexes[I] = UndefValue::get(MaskEltTy);
1047 continue;
1048 }
1049
1050 APInt Index = cast<ConstantInt>(COp)->getValue();
1051 Index = Index.zextOrTrunc(32).getLoBits(2);
Simon Pilgrim640f9962016-04-30 07:23:30 +00001052
1053 // The PD variants uses bit 1 to select per-lane element index, so
1054 // shift down to convert to generic shuffle mask index.
Craig Topper58917f32016-12-11 01:59:36 +00001055 if (IsPD)
Craig Topperfc947bc2017-04-18 17:14:21 +00001056 Index.lshrInPlace(1);
Simon Pilgrimeeacc402016-05-01 20:22:42 +00001057
1058 // The _256 variants are a bit trickier since the mask bits always index
1059 // into the corresponding 128 half. In order to convert to a generic
1060 // shuffle, we have to make that explicit.
Craig Topper58917f32016-12-11 01:59:36 +00001061 Index += APInt(32, (I / NumLaneElts) * NumLaneElts);
Simon Pilgrimeeacc402016-05-01 20:22:42 +00001062
1063 Indexes[I] = ConstantInt::get(MaskEltTy, Index);
Simon Pilgrim2f6097d2016-04-24 17:23:46 +00001064 }
1065
Simon Pilgrimeeacc402016-05-01 20:22:42 +00001066 auto ShuffleMask = ConstantVector::get(makeArrayRef(Indexes, NumElts));
Simon Pilgrim2f6097d2016-04-24 17:23:46 +00001067 auto V1 = II.getArgOperand(0);
1068 auto V2 = UndefValue::get(V1->getType());
1069 return Builder.CreateShuffleVector(V1, V2, ShuffleMask);
1070}
1071
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +00001072/// Attempt to convert vpermd/vpermps to shufflevector if the mask is constant.
1073static Value *simplifyX86vpermv(const IntrinsicInst &II,
1074 InstCombiner::BuilderTy &Builder) {
1075 auto *V = dyn_cast<Constant>(II.getArgOperand(1));
1076 if (!V)
1077 return nullptr;
1078
Simon Pilgrimca140b12016-05-01 20:43:02 +00001079 auto *VecTy = cast<VectorType>(II.getType());
1080 auto *MaskEltTy = Type::getInt32Ty(II.getContext());
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +00001081 unsigned Size = VecTy->getNumElements();
Craig Toppere3280452016-12-25 23:58:57 +00001082 assert((Size == 4 || Size == 8 || Size == 16 || Size == 32 || Size == 64) &&
1083 "Unexpected shuffle mask size");
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +00001084
Simon Pilgrimca140b12016-05-01 20:43:02 +00001085 // Construct a shuffle mask from constant integers or UNDEFs.
Craig Toppere3280452016-12-25 23:58:57 +00001086 Constant *Indexes[64] = {nullptr};
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +00001087
1088 for (unsigned I = 0; I < Size; ++I) {
1089 Constant *COp = V->getAggregateElement(I);
Simon Pilgrimca140b12016-05-01 20:43:02 +00001090 if (!COp || (!isa<UndefValue>(COp) && !isa<ConstantInt>(COp)))
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +00001091 return nullptr;
1092
Simon Pilgrimca140b12016-05-01 20:43:02 +00001093 if (isa<UndefValue>(COp)) {
1094 Indexes[I] = UndefValue::get(MaskEltTy);
1095 continue;
1096 }
1097
Craig Toppere3280452016-12-25 23:58:57 +00001098 uint32_t Index = cast<ConstantInt>(COp)->getZExtValue();
1099 Index &= Size - 1;
Simon Pilgrimca140b12016-05-01 20:43:02 +00001100 Indexes[I] = ConstantInt::get(MaskEltTy, Index);
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +00001101 }
1102
Simon Pilgrimca140b12016-05-01 20:43:02 +00001103 auto ShuffleMask = ConstantVector::get(makeArrayRef(Indexes, Size));
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +00001104 auto V1 = II.getArgOperand(0);
1105 auto V2 = UndefValue::get(VecTy);
1106 return Builder.CreateShuffleVector(V1, V2, ShuffleMask);
1107}
1108
Simon Pilgrim1d1c56e22015-10-11 14:38:34 +00001109/// Decode XOP integer vector comparison intrinsics.
Sanjay Patel6038d3e2016-01-29 23:27:03 +00001110static Value *simplifyX86vpcom(const IntrinsicInst &II,
Sanjay Patelf9f5d3c2016-01-29 23:14:58 +00001111 InstCombiner::BuilderTy &Builder,
1112 bool IsSigned) {
Simon Pilgrim1d1c56e22015-10-11 14:38:34 +00001113 if (auto *CInt = dyn_cast<ConstantInt>(II.getArgOperand(2))) {
1114 uint64_t Imm = CInt->getZExtValue() & 0x7;
1115 VectorType *VecTy = cast<VectorType>(II.getType());
1116 CmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
1117
1118 switch (Imm) {
1119 case 0x0:
1120 Pred = IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1121 break;
1122 case 0x1:
1123 Pred = IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
1124 break;
1125 case 0x2:
1126 Pred = IsSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1127 break;
1128 case 0x3:
1129 Pred = IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
1130 break;
1131 case 0x4:
1132 Pred = ICmpInst::ICMP_EQ; break;
1133 case 0x5:
1134 Pred = ICmpInst::ICMP_NE; break;
1135 case 0x6:
1136 return ConstantInt::getSigned(VecTy, 0); // FALSE
1137 case 0x7:
1138 return ConstantInt::getSigned(VecTy, -1); // TRUE
1139 }
1140
Sanjay Patelf9f5d3c2016-01-29 23:14:58 +00001141 if (Value *Cmp = Builder.CreateICmp(Pred, II.getArgOperand(0),
1142 II.getArgOperand(1)))
Simon Pilgrim1d1c56e22015-10-11 14:38:34 +00001143 return Builder.CreateSExtOrTrunc(Cmp, VecTy);
1144 }
1145 return nullptr;
1146}
1147
Craig Toppere3280452016-12-25 23:58:57 +00001148// Emit a select instruction and appropriate bitcasts to help simplify
1149// masked intrinsics.
1150static Value *emitX86MaskSelect(Value *Mask, Value *Op0, Value *Op1,
1151 InstCombiner::BuilderTy &Builder) {
Craig Topper99163632016-12-30 23:06:28 +00001152 unsigned VWidth = Op0->getType()->getVectorNumElements();
1153
1154 // If the mask is all ones we don't need the select. But we need to check
1155 // only the bit thats will be used in case VWidth is less than 8.
1156 if (auto *C = dyn_cast<ConstantInt>(Mask))
1157 if (C->getValue().zextOrTrunc(VWidth).isAllOnesValue())
1158 return Op0;
1159
Craig Toppere3280452016-12-25 23:58:57 +00001160 auto *MaskTy = VectorType::get(Builder.getInt1Ty(),
1161 cast<IntegerType>(Mask->getType())->getBitWidth());
1162 Mask = Builder.CreateBitCast(Mask, MaskTy);
1163
1164 // If we have less than 8 elements, then the starting mask was an i8 and
1165 // we need to extract down to the right number of elements.
Craig Toppere3280452016-12-25 23:58:57 +00001166 if (VWidth < 8) {
1167 uint32_t Indices[4];
1168 for (unsigned i = 0; i != VWidth; ++i)
1169 Indices[i] = i;
1170 Mask = Builder.CreateShuffleVector(Mask, Mask,
1171 makeArrayRef(Indices, VWidth),
1172 "extract");
1173 }
1174
1175 return Builder.CreateSelect(Mask, Op0, Op1);
1176}
1177
Sanjay Patel0069f562016-01-31 16:35:23 +00001178static Value *simplifyMinnumMaxnum(const IntrinsicInst &II) {
1179 Value *Arg0 = II.getArgOperand(0);
1180 Value *Arg1 = II.getArgOperand(1);
1181
1182 // fmin(x, x) -> x
1183 if (Arg0 == Arg1)
1184 return Arg0;
1185
1186 const auto *C1 = dyn_cast<ConstantFP>(Arg1);
1187
1188 // fmin(x, nan) -> x
1189 if (C1 && C1->isNaN())
1190 return Arg0;
1191
1192 // This is the value because if undef were NaN, we would return the other
1193 // value and cannot return a NaN unless both operands are.
1194 //
1195 // fmin(undef, x) -> x
1196 if (isa<UndefValue>(Arg0))
1197 return Arg1;
1198
1199 // fmin(x, undef) -> x
1200 if (isa<UndefValue>(Arg1))
1201 return Arg0;
1202
1203 Value *X = nullptr;
1204 Value *Y = nullptr;
1205 if (II.getIntrinsicID() == Intrinsic::minnum) {
1206 // fmin(x, fmin(x, y)) -> fmin(x, y)
1207 // fmin(y, fmin(x, y)) -> fmin(x, y)
1208 if (match(Arg1, m_FMin(m_Value(X), m_Value(Y)))) {
1209 if (Arg0 == X || Arg0 == Y)
1210 return Arg1;
1211 }
1212
1213 // fmin(fmin(x, y), x) -> fmin(x, y)
1214 // fmin(fmin(x, y), y) -> fmin(x, y)
1215 if (match(Arg0, m_FMin(m_Value(X), m_Value(Y)))) {
1216 if (Arg1 == X || Arg1 == Y)
1217 return Arg0;
1218 }
1219
1220 // TODO: fmin(nnan x, inf) -> x
1221 // TODO: fmin(nnan ninf x, flt_max) -> x
1222 if (C1 && C1->isInfinity()) {
1223 // fmin(x, -inf) -> -inf
1224 if (C1->isNegative())
1225 return Arg1;
1226 }
1227 } else {
1228 assert(II.getIntrinsicID() == Intrinsic::maxnum);
1229 // fmax(x, fmax(x, y)) -> fmax(x, y)
1230 // fmax(y, fmax(x, y)) -> fmax(x, y)
1231 if (match(Arg1, m_FMax(m_Value(X), m_Value(Y)))) {
1232 if (Arg0 == X || Arg0 == Y)
1233 return Arg1;
1234 }
1235
1236 // fmax(fmax(x, y), x) -> fmax(x, y)
1237 // fmax(fmax(x, y), y) -> fmax(x, y)
1238 if (match(Arg0, m_FMax(m_Value(X), m_Value(Y)))) {
1239 if (Arg1 == X || Arg1 == Y)
1240 return Arg0;
1241 }
1242
1243 // TODO: fmax(nnan x, -inf) -> x
1244 // TODO: fmax(nnan ninf x, -flt_max) -> x
1245 if (C1 && C1->isInfinity()) {
1246 // fmax(x, inf) -> inf
1247 if (!C1->isNegative())
1248 return Arg1;
1249 }
1250 }
1251 return nullptr;
1252}
1253
David Majnemer666aa942016-07-14 06:58:42 +00001254static bool maskIsAllOneOrUndef(Value *Mask) {
1255 auto *ConstMask = dyn_cast<Constant>(Mask);
1256 if (!ConstMask)
1257 return false;
1258 if (ConstMask->isAllOnesValue() || isa<UndefValue>(ConstMask))
1259 return true;
1260 for (unsigned I = 0, E = ConstMask->getType()->getVectorNumElements(); I != E;
1261 ++I) {
1262 if (auto *MaskElt = ConstMask->getAggregateElement(I))
1263 if (MaskElt->isAllOnesValue() || isa<UndefValue>(MaskElt))
1264 continue;
1265 return false;
1266 }
1267 return true;
1268}
1269
Sanjay Patelb695c552016-02-01 17:00:10 +00001270static Value *simplifyMaskedLoad(const IntrinsicInst &II,
1271 InstCombiner::BuilderTy &Builder) {
David Majnemer666aa942016-07-14 06:58:42 +00001272 // If the mask is all ones or undefs, this is a plain vector load of the 1st
1273 // argument.
1274 if (maskIsAllOneOrUndef(II.getArgOperand(2))) {
Sanjay Patelb695c552016-02-01 17:00:10 +00001275 Value *LoadPtr = II.getArgOperand(0);
1276 unsigned Alignment = cast<ConstantInt>(II.getArgOperand(1))->getZExtValue();
1277 return Builder.CreateAlignedLoad(LoadPtr, Alignment, "unmaskedload");
1278 }
1279
1280 return nullptr;
1281}
1282
Sanjay Patel04f792b2016-02-01 19:39:52 +00001283static Instruction *simplifyMaskedStore(IntrinsicInst &II, InstCombiner &IC) {
1284 auto *ConstMask = dyn_cast<Constant>(II.getArgOperand(3));
1285 if (!ConstMask)
1286 return nullptr;
1287
1288 // If the mask is all zeros, this instruction does nothing.
1289 if (ConstMask->isNullValue())
Sanjay Patel4b198802016-02-01 22:23:39 +00001290 return IC.eraseInstFromFunction(II);
Sanjay Patel04f792b2016-02-01 19:39:52 +00001291
1292 // If the mask is all ones, this is a plain vector store of the 1st argument.
1293 if (ConstMask->isAllOnesValue()) {
1294 Value *StorePtr = II.getArgOperand(1);
1295 unsigned Alignment = cast<ConstantInt>(II.getArgOperand(2))->getZExtValue();
1296 return new StoreInst(II.getArgOperand(0), StorePtr, false, Alignment);
1297 }
1298
1299 return nullptr;
1300}
1301
Sanjay Patel103ab7d2016-02-01 22:10:26 +00001302static Instruction *simplifyMaskedGather(IntrinsicInst &II, InstCombiner &IC) {
1303 // If the mask is all zeros, return the "passthru" argument of the gather.
1304 auto *ConstMask = dyn_cast<Constant>(II.getArgOperand(2));
1305 if (ConstMask && ConstMask->isNullValue())
Sanjay Patel4b198802016-02-01 22:23:39 +00001306 return IC.replaceInstUsesWith(II, II.getArgOperand(3));
Sanjay Patel103ab7d2016-02-01 22:10:26 +00001307
1308 return nullptr;
1309}
1310
1311static Instruction *simplifyMaskedScatter(IntrinsicInst &II, InstCombiner &IC) {
1312 // If the mask is all zeros, a scatter does nothing.
1313 auto *ConstMask = dyn_cast<Constant>(II.getArgOperand(3));
1314 if (ConstMask && ConstMask->isNullValue())
Sanjay Patel4b198802016-02-01 22:23:39 +00001315 return IC.eraseInstFromFunction(II);
Sanjay Patel103ab7d2016-02-01 22:10:26 +00001316
1317 return nullptr;
1318}
1319
Amaury Sechet763c59d2016-08-18 20:43:50 +00001320static Instruction *foldCttzCtlz(IntrinsicInst &II, InstCombiner &IC) {
1321 assert((II.getIntrinsicID() == Intrinsic::cttz ||
1322 II.getIntrinsicID() == Intrinsic::ctlz) &&
1323 "Expected cttz or ctlz intrinsic");
Sanjay Patel8e3ab172016-08-05 22:42:46 +00001324 Value *Op0 = II.getArgOperand(0);
Sanjay Patel8e3ab172016-08-05 22:42:46 +00001325
Craig Topper8205a1a2017-05-24 16:53:07 +00001326 KnownBits Known = IC.computeKnownBits(Op0, 0, &II);
Sanjay Patel8e3ab172016-08-05 22:42:46 +00001327
1328 // Create a mask for bits above (ctlz) or below (cttz) the first known one.
1329 bool IsTZ = II.getIntrinsicID() == Intrinsic::cttz;
Craig Topper8df66c62017-05-12 17:20:30 +00001330 unsigned PossibleZeros = IsTZ ? Known.countMaxTrailingZeros()
1331 : Known.countMaxLeadingZeros();
1332 unsigned DefiniteZeros = IsTZ ? Known.countMinTrailingZeros()
1333 : Known.countMinLeadingZeros();
Sanjay Patel8e3ab172016-08-05 22:42:46 +00001334
1335 // If all bits above (ctlz) or below (cttz) the first known one are known
1336 // zero, this value is constant.
1337 // FIXME: This should be in InstSimplify because we're replacing an
1338 // instruction with a constant.
Craig Topper9474e9b2017-04-27 04:51:25 +00001339 if (PossibleZeros == DefiniteZeros) {
Craig Topper0799ff92017-06-03 18:50:32 +00001340 auto *C = ConstantInt::get(Op0->getType(), DefiniteZeros);
Amaury Sechet763c59d2016-08-18 20:43:50 +00001341 return IC.replaceInstUsesWith(II, C);
1342 }
1343
1344 // If the input to cttz/ctlz is known to be non-zero,
1345 // then change the 'ZeroIsUndef' parameter to 'true'
1346 // because we know the zero behavior can't affect the result.
Craig Topper73ba1c82017-06-07 07:40:37 +00001347 if (!Known.One.isNullValue() ||
Craig Topperd45185f2017-05-26 18:23:57 +00001348 isKnownNonZero(Op0, IC.getDataLayout(), 0, &IC.getAssumptionCache(), &II,
1349 &IC.getDominatorTree())) {
Amaury Sechet763c59d2016-08-18 20:43:50 +00001350 if (!match(II.getArgOperand(1), m_One())) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001351 II.setOperand(1, IC.Builder.getTrue());
Amaury Sechet763c59d2016-08-18 20:43:50 +00001352 return &II;
1353 }
1354 }
Sanjay Patel8e3ab172016-08-05 22:42:46 +00001355
Craig Topper5b173f22017-06-21 16:32:35 +00001356 // Add range metadata since known bits can't completely reflect what we know.
1357 // TODO: Handle splat vectors.
1358 auto *IT = dyn_cast<IntegerType>(Op0->getType());
1359 if (IT && IT->getBitWidth() != 1 && !II.getMetadata(LLVMContext::MD_range)) {
1360 Metadata *LowAndHigh[] = {
1361 ConstantAsMetadata::get(ConstantInt::get(IT, DefiniteZeros)),
1362 ConstantAsMetadata::get(ConstantInt::get(IT, PossibleZeros + 1))};
1363 II.setMetadata(LLVMContext::MD_range,
1364 MDNode::get(II.getContext(), LowAndHigh));
1365 return &II;
1366 }
1367
1368 return nullptr;
1369}
1370
1371static Instruction *foldCtpop(IntrinsicInst &II, InstCombiner &IC) {
1372 assert(II.getIntrinsicID() == Intrinsic::ctpop &&
1373 "Expected ctpop intrinsic");
1374 Value *Op0 = II.getArgOperand(0);
1375 // FIXME: Try to simplify vectors of integers.
1376 auto *IT = dyn_cast<IntegerType>(Op0->getType());
1377 if (!IT)
1378 return nullptr;
1379
1380 unsigned BitWidth = IT->getBitWidth();
1381 KnownBits Known(BitWidth);
1382 IC.computeKnownBits(Op0, Known, 0, &II);
1383
1384 unsigned MinCount = Known.countMinPopulation();
1385 unsigned MaxCount = Known.countMaxPopulation();
1386
1387 // Add range metadata since known bits can't completely reflect what we know.
1388 if (IT->getBitWidth() != 1 && !II.getMetadata(LLVMContext::MD_range)) {
1389 Metadata *LowAndHigh[] = {
1390 ConstantAsMetadata::get(ConstantInt::get(IT, MinCount)),
1391 ConstantAsMetadata::get(ConstantInt::get(IT, MaxCount + 1))};
1392 II.setMetadata(LLVMContext::MD_range,
1393 MDNode::get(II.getContext(), LowAndHigh));
1394 return &II;
1395 }
1396
Sanjay Patel8e3ab172016-08-05 22:42:46 +00001397 return nullptr;
1398}
1399
Sanjay Patel1ace9932016-02-26 21:04:14 +00001400// TODO: If the x86 backend knew how to convert a bool vector mask back to an
1401// XMM register mask efficiently, we could transform all x86 masked intrinsics
1402// to LLVM masked intrinsics and remove the x86 masked intrinsic defs.
Sanjay Patel98a71502016-02-29 23:16:48 +00001403static Instruction *simplifyX86MaskedLoad(IntrinsicInst &II, InstCombiner &IC) {
1404 Value *Ptr = II.getOperand(0);
1405 Value *Mask = II.getOperand(1);
Sanjay Patel5e5056d2016-04-12 23:16:23 +00001406 Constant *ZeroVec = Constant::getNullValue(II.getType());
Sanjay Patel98a71502016-02-29 23:16:48 +00001407
1408 // Special case a zero mask since that's not a ConstantDataVector.
Sanjay Patel5e5056d2016-04-12 23:16:23 +00001409 // This masked load instruction creates a zero vector.
Sanjay Patel98a71502016-02-29 23:16:48 +00001410 if (isa<ConstantAggregateZero>(Mask))
Sanjay Patel5e5056d2016-04-12 23:16:23 +00001411 return IC.replaceInstUsesWith(II, ZeroVec);
Sanjay Patel98a71502016-02-29 23:16:48 +00001412
1413 auto *ConstMask = dyn_cast<ConstantDataVector>(Mask);
1414 if (!ConstMask)
1415 return nullptr;
1416
1417 // The mask is constant. Convert this x86 intrinsic to the LLVM instrinsic
1418 // to allow target-independent optimizations.
1419
1420 // First, cast the x86 intrinsic scalar pointer to a vector pointer to match
1421 // the LLVM intrinsic definition for the pointer argument.
1422 unsigned AddrSpace = cast<PointerType>(Ptr->getType())->getAddressSpace();
1423 PointerType *VecPtrTy = PointerType::get(II.getType(), AddrSpace);
Craig Topperbb4069e2017-07-07 23:16:26 +00001424 Value *PtrCast = IC.Builder.CreateBitCast(Ptr, VecPtrTy, "castvec");
Sanjay Patel98a71502016-02-29 23:16:48 +00001425
1426 // Second, convert the x86 XMM integer vector mask to a vector of bools based
1427 // on each element's most significant bit (the sign bit).
1428 Constant *BoolMask = getNegativeIsTrueBoolVec(ConstMask);
1429
Sanjay Patel5e5056d2016-04-12 23:16:23 +00001430 // The pass-through vector for an x86 masked load is a zero vector.
1431 CallInst *NewMaskedLoad =
Craig Topperbb4069e2017-07-07 23:16:26 +00001432 IC.Builder.CreateMaskedLoad(PtrCast, 1, BoolMask, ZeroVec);
Sanjay Patel98a71502016-02-29 23:16:48 +00001433 return IC.replaceInstUsesWith(II, NewMaskedLoad);
1434}
1435
1436// TODO: If the x86 backend knew how to convert a bool vector mask back to an
1437// XMM register mask efficiently, we could transform all x86 masked intrinsics
1438// to LLVM masked intrinsics and remove the x86 masked intrinsic defs.
Sanjay Patel1ace9932016-02-26 21:04:14 +00001439static bool simplifyX86MaskedStore(IntrinsicInst &II, InstCombiner &IC) {
1440 Value *Ptr = II.getOperand(0);
1441 Value *Mask = II.getOperand(1);
1442 Value *Vec = II.getOperand(2);
1443
1444 // Special case a zero mask since that's not a ConstantDataVector:
1445 // this masked store instruction does nothing.
1446 if (isa<ConstantAggregateZero>(Mask)) {
1447 IC.eraseInstFromFunction(II);
1448 return true;
1449 }
1450
Sanjay Patelc4acbae2016-03-12 15:16:59 +00001451 // The SSE2 version is too weird (eg, unaligned but non-temporal) to do
1452 // anything else at this level.
1453 if (II.getIntrinsicID() == Intrinsic::x86_sse2_maskmov_dqu)
1454 return false;
1455
Sanjay Patel1ace9932016-02-26 21:04:14 +00001456 auto *ConstMask = dyn_cast<ConstantDataVector>(Mask);
1457 if (!ConstMask)
1458 return false;
1459
1460 // The mask is constant. Convert this x86 intrinsic to the LLVM instrinsic
1461 // to allow target-independent optimizations.
1462
1463 // First, cast the x86 intrinsic scalar pointer to a vector pointer to match
1464 // the LLVM intrinsic definition for the pointer argument.
1465 unsigned AddrSpace = cast<PointerType>(Ptr->getType())->getAddressSpace();
1466 PointerType *VecPtrTy = PointerType::get(Vec->getType(), AddrSpace);
Craig Topperbb4069e2017-07-07 23:16:26 +00001467 Value *PtrCast = IC.Builder.CreateBitCast(Ptr, VecPtrTy, "castvec");
Sanjay Patel1ace9932016-02-26 21:04:14 +00001468
1469 // Second, convert the x86 XMM integer vector mask to a vector of bools based
1470 // on each element's most significant bit (the sign bit).
1471 Constant *BoolMask = getNegativeIsTrueBoolVec(ConstMask);
1472
Craig Topperbb4069e2017-07-07 23:16:26 +00001473 IC.Builder.CreateMaskedStore(Vec, PtrCast, 1, BoolMask);
Sanjay Patel1ace9932016-02-26 21:04:14 +00001474
1475 // 'Replace uses' doesn't work for stores. Erase the original masked store.
1476 IC.eraseInstFromFunction(II);
1477 return true;
1478}
1479
Matt Arsenaultcdb468c2017-02-27 23:08:49 +00001480// Constant fold llvm.amdgcn.fmed3 intrinsics for standard inputs.
1481//
1482// A single NaN input is folded to minnum, so we rely on that folding for
1483// handling NaNs.
1484static APFloat fmed3AMDGCN(const APFloat &Src0, const APFloat &Src1,
1485 const APFloat &Src2) {
1486 APFloat Max3 = maxnum(maxnum(Src0, Src1), Src2);
1487
1488 APFloat::cmpResult Cmp0 = Max3.compare(Src0);
1489 assert(Cmp0 != APFloat::cmpUnordered && "nans handled separately");
1490 if (Cmp0 == APFloat::cmpEqual)
1491 return maxnum(Src1, Src2);
1492
1493 APFloat::cmpResult Cmp1 = Max3.compare(Src1);
1494 assert(Cmp1 != APFloat::cmpUnordered && "nans handled separately");
1495 if (Cmp1 == APFloat::cmpEqual)
1496 return maxnum(Src0, Src2);
1497
1498 return maxnum(Src0, Src1);
1499}
1500
Arnaud A. de Grandmaison333ef382016-05-10 09:24:49 +00001501// Returns true iff the 2 intrinsics have the same operands, limiting the
1502// comparison to the first NumOperands.
1503static bool haveSameOperands(const IntrinsicInst &I, const IntrinsicInst &E,
1504 unsigned NumOperands) {
1505 assert(I.getNumArgOperands() >= NumOperands && "Not enough operands");
1506 assert(E.getNumArgOperands() >= NumOperands && "Not enough operands");
1507 for (unsigned i = 0; i < NumOperands; i++)
1508 if (I.getArgOperand(i) != E.getArgOperand(i))
1509 return false;
1510 return true;
1511}
1512
1513// Remove trivially empty start/end intrinsic ranges, i.e. a start
1514// immediately followed by an end (ignoring debuginfo or other
1515// start/end intrinsics in between). As this handles only the most trivial
1516// cases, tracking the nesting level is not needed:
1517//
1518// call @llvm.foo.start(i1 0) ; &I
1519// call @llvm.foo.start(i1 0)
1520// call @llvm.foo.end(i1 0) ; This one will not be skipped: it will be removed
1521// call @llvm.foo.end(i1 0)
1522static bool removeTriviallyEmptyRange(IntrinsicInst &I, unsigned StartID,
1523 unsigned EndID, InstCombiner &IC) {
1524 assert(I.getIntrinsicID() == StartID &&
1525 "Start intrinsic does not have expected ID");
1526 BasicBlock::iterator BI(I), BE(I.getParent()->end());
1527 for (++BI; BI != BE; ++BI) {
1528 if (auto *E = dyn_cast<IntrinsicInst>(BI)) {
1529 if (isa<DbgInfoIntrinsic>(E) || E->getIntrinsicID() == StartID)
1530 continue;
1531 if (E->getIntrinsicID() == EndID &&
1532 haveSameOperands(I, *E, E->getNumArgOperands())) {
1533 IC.eraseInstFromFunction(*E);
1534 IC.eraseInstFromFunction(I);
1535 return true;
1536 }
1537 }
1538 break;
1539 }
1540
1541 return false;
1542}
1543
Justin Lebar698c31b2017-01-27 00:58:58 +00001544// Convert NVVM intrinsics to target-generic LLVM code where possible.
1545static Instruction *SimplifyNVVMIntrinsic(IntrinsicInst *II, InstCombiner &IC) {
1546 // Each NVVM intrinsic we can simplify can be replaced with one of:
1547 //
1548 // * an LLVM intrinsic,
1549 // * an LLVM cast operation,
1550 // * an LLVM binary operation, or
1551 // * ad-hoc LLVM IR for the particular operation.
1552
1553 // Some transformations are only valid when the module's
1554 // flush-denormals-to-zero (ftz) setting is true/false, whereas other
1555 // transformations are valid regardless of the module's ftz setting.
1556 enum FtzRequirementTy {
1557 FTZ_Any, // Any ftz setting is ok.
1558 FTZ_MustBeOn, // Transformation is valid only if ftz is on.
1559 FTZ_MustBeOff, // Transformation is valid only if ftz is off.
1560 };
1561 // Classes of NVVM intrinsics that can't be replaced one-to-one with a
1562 // target-generic intrinsic, cast op, or binary op but that we can nonetheless
1563 // simplify.
1564 enum SpecialCase {
1565 SPC_Reciprocal,
1566 };
1567
1568 // SimplifyAction is a poor-man's variant (plus an additional flag) that
1569 // represents how to replace an NVVM intrinsic with target-generic LLVM IR.
1570 struct SimplifyAction {
1571 // Invariant: At most one of these Optionals has a value.
1572 Optional<Intrinsic::ID> IID;
1573 Optional<Instruction::CastOps> CastOp;
1574 Optional<Instruction::BinaryOps> BinaryOp;
1575 Optional<SpecialCase> Special;
1576
1577 FtzRequirementTy FtzRequirement = FTZ_Any;
1578
1579 SimplifyAction() = default;
1580
1581 SimplifyAction(Intrinsic::ID IID, FtzRequirementTy FtzReq)
1582 : IID(IID), FtzRequirement(FtzReq) {}
1583
1584 // Cast operations don't have anything to do with FTZ, so we skip that
1585 // argument.
1586 SimplifyAction(Instruction::CastOps CastOp) : CastOp(CastOp) {}
1587
1588 SimplifyAction(Instruction::BinaryOps BinaryOp, FtzRequirementTy FtzReq)
1589 : BinaryOp(BinaryOp), FtzRequirement(FtzReq) {}
1590
1591 SimplifyAction(SpecialCase Special, FtzRequirementTy FtzReq)
1592 : Special(Special), FtzRequirement(FtzReq) {}
1593 };
1594
1595 // Try to generate a SimplifyAction describing how to replace our
1596 // IntrinsicInstr with target-generic LLVM IR.
1597 const SimplifyAction Action = [II]() -> SimplifyAction {
1598 switch (II->getIntrinsicID()) {
Justin Lebar698c31b2017-01-27 00:58:58 +00001599 // NVVM intrinsics that map directly to LLVM intrinsics.
1600 case Intrinsic::nvvm_ceil_d:
1601 return {Intrinsic::ceil, FTZ_Any};
1602 case Intrinsic::nvvm_ceil_f:
1603 return {Intrinsic::ceil, FTZ_MustBeOff};
1604 case Intrinsic::nvvm_ceil_ftz_f:
1605 return {Intrinsic::ceil, FTZ_MustBeOn};
1606 case Intrinsic::nvvm_fabs_d:
1607 return {Intrinsic::fabs, FTZ_Any};
1608 case Intrinsic::nvvm_fabs_f:
1609 return {Intrinsic::fabs, FTZ_MustBeOff};
1610 case Intrinsic::nvvm_fabs_ftz_f:
1611 return {Intrinsic::fabs, FTZ_MustBeOn};
1612 case Intrinsic::nvvm_floor_d:
1613 return {Intrinsic::floor, FTZ_Any};
1614 case Intrinsic::nvvm_floor_f:
1615 return {Intrinsic::floor, FTZ_MustBeOff};
1616 case Intrinsic::nvvm_floor_ftz_f:
1617 return {Intrinsic::floor, FTZ_MustBeOn};
1618 case Intrinsic::nvvm_fma_rn_d:
1619 return {Intrinsic::fma, FTZ_Any};
1620 case Intrinsic::nvvm_fma_rn_f:
1621 return {Intrinsic::fma, FTZ_MustBeOff};
1622 case Intrinsic::nvvm_fma_rn_ftz_f:
1623 return {Intrinsic::fma, FTZ_MustBeOn};
1624 case Intrinsic::nvvm_fmax_d:
1625 return {Intrinsic::maxnum, FTZ_Any};
1626 case Intrinsic::nvvm_fmax_f:
1627 return {Intrinsic::maxnum, FTZ_MustBeOff};
1628 case Intrinsic::nvvm_fmax_ftz_f:
1629 return {Intrinsic::maxnum, FTZ_MustBeOn};
1630 case Intrinsic::nvvm_fmin_d:
1631 return {Intrinsic::minnum, FTZ_Any};
1632 case Intrinsic::nvvm_fmin_f:
1633 return {Intrinsic::minnum, FTZ_MustBeOff};
1634 case Intrinsic::nvvm_fmin_ftz_f:
1635 return {Intrinsic::minnum, FTZ_MustBeOn};
1636 case Intrinsic::nvvm_round_d:
1637 return {Intrinsic::round, FTZ_Any};
1638 case Intrinsic::nvvm_round_f:
1639 return {Intrinsic::round, FTZ_MustBeOff};
1640 case Intrinsic::nvvm_round_ftz_f:
1641 return {Intrinsic::round, FTZ_MustBeOn};
1642 case Intrinsic::nvvm_sqrt_rn_d:
1643 return {Intrinsic::sqrt, FTZ_Any};
1644 case Intrinsic::nvvm_sqrt_f:
1645 // nvvm_sqrt_f is a special case. For most intrinsics, foo_ftz_f is the
1646 // ftz version, and foo_f is the non-ftz version. But nvvm_sqrt_f adopts
1647 // the ftz-ness of the surrounding code. sqrt_rn_f and sqrt_rn_ftz_f are
1648 // the versions with explicit ftz-ness.
1649 return {Intrinsic::sqrt, FTZ_Any};
1650 case Intrinsic::nvvm_sqrt_rn_f:
1651 return {Intrinsic::sqrt, FTZ_MustBeOff};
1652 case Intrinsic::nvvm_sqrt_rn_ftz_f:
1653 return {Intrinsic::sqrt, FTZ_MustBeOn};
1654 case Intrinsic::nvvm_trunc_d:
1655 return {Intrinsic::trunc, FTZ_Any};
1656 case Intrinsic::nvvm_trunc_f:
1657 return {Intrinsic::trunc, FTZ_MustBeOff};
1658 case Intrinsic::nvvm_trunc_ftz_f:
1659 return {Intrinsic::trunc, FTZ_MustBeOn};
1660
1661 // NVVM intrinsics that map to LLVM cast operations.
1662 //
1663 // Note that llvm's target-generic conversion operators correspond to the rz
1664 // (round to zero) versions of the nvvm conversion intrinsics, even though
1665 // most everything else here uses the rn (round to nearest even) nvvm ops.
1666 case Intrinsic::nvvm_d2i_rz:
1667 case Intrinsic::nvvm_f2i_rz:
1668 case Intrinsic::nvvm_d2ll_rz:
1669 case Intrinsic::nvvm_f2ll_rz:
1670 return {Instruction::FPToSI};
1671 case Intrinsic::nvvm_d2ui_rz:
1672 case Intrinsic::nvvm_f2ui_rz:
1673 case Intrinsic::nvvm_d2ull_rz:
1674 case Intrinsic::nvvm_f2ull_rz:
1675 return {Instruction::FPToUI};
1676 case Intrinsic::nvvm_i2d_rz:
1677 case Intrinsic::nvvm_i2f_rz:
1678 case Intrinsic::nvvm_ll2d_rz:
1679 case Intrinsic::nvvm_ll2f_rz:
1680 return {Instruction::SIToFP};
1681 case Intrinsic::nvvm_ui2d_rz:
1682 case Intrinsic::nvvm_ui2f_rz:
1683 case Intrinsic::nvvm_ull2d_rz:
1684 case Intrinsic::nvvm_ull2f_rz:
1685 return {Instruction::UIToFP};
1686
1687 // NVVM intrinsics that map to LLVM binary ops.
1688 case Intrinsic::nvvm_add_rn_d:
1689 return {Instruction::FAdd, FTZ_Any};
1690 case Intrinsic::nvvm_add_rn_f:
1691 return {Instruction::FAdd, FTZ_MustBeOff};
1692 case Intrinsic::nvvm_add_rn_ftz_f:
1693 return {Instruction::FAdd, FTZ_MustBeOn};
1694 case Intrinsic::nvvm_mul_rn_d:
1695 return {Instruction::FMul, FTZ_Any};
1696 case Intrinsic::nvvm_mul_rn_f:
1697 return {Instruction::FMul, FTZ_MustBeOff};
1698 case Intrinsic::nvvm_mul_rn_ftz_f:
1699 return {Instruction::FMul, FTZ_MustBeOn};
1700 case Intrinsic::nvvm_div_rn_d:
1701 return {Instruction::FDiv, FTZ_Any};
1702 case Intrinsic::nvvm_div_rn_f:
1703 return {Instruction::FDiv, FTZ_MustBeOff};
1704 case Intrinsic::nvvm_div_rn_ftz_f:
1705 return {Instruction::FDiv, FTZ_MustBeOn};
1706
1707 // The remainder of cases are NVVM intrinsics that map to LLVM idioms, but
1708 // need special handling.
1709 //
Hiroshi Inoue0ca79dc2017-07-11 06:04:59 +00001710 // We seem to be missing intrinsics for rcp.approx.{ftz.}f32, which is just
Justin Lebar698c31b2017-01-27 00:58:58 +00001711 // as well.
1712 case Intrinsic::nvvm_rcp_rn_d:
1713 return {SPC_Reciprocal, FTZ_Any};
1714 case Intrinsic::nvvm_rcp_rn_f:
1715 return {SPC_Reciprocal, FTZ_MustBeOff};
1716 case Intrinsic::nvvm_rcp_rn_ftz_f:
1717 return {SPC_Reciprocal, FTZ_MustBeOn};
1718
1719 // We do not currently simplify intrinsics that give an approximate answer.
1720 // These include:
1721 //
1722 // - nvvm_cos_approx_{f,ftz_f}
1723 // - nvvm_ex2_approx_{d,f,ftz_f}
1724 // - nvvm_lg2_approx_{d,f,ftz_f}
1725 // - nvvm_sin_approx_{f,ftz_f}
1726 // - nvvm_sqrt_approx_{f,ftz_f}
1727 // - nvvm_rsqrt_approx_{d,f,ftz_f}
1728 // - nvvm_div_approx_{ftz_d,ftz_f,f}
1729 // - nvvm_rcp_approx_ftz_d
1730 //
1731 // Ideally we'd encode them as e.g. "fast call @llvm.cos", where "fast"
1732 // means that fastmath is enabled in the intrinsic. Unfortunately only
1733 // binary operators (currently) have a fastmath bit in SelectionDAG, so this
1734 // information gets lost and we can't select on it.
1735 //
1736 // TODO: div and rcp are lowered to a binary op, so these we could in theory
1737 // lower them to "fast fdiv".
1738
1739 default:
1740 return {};
1741 }
1742 }();
1743
1744 // If Action.FtzRequirementTy is not satisfied by the module's ftz state, we
1745 // can bail out now. (Notice that in the case that IID is not an NVVM
1746 // intrinsic, we don't have to look up any module metadata, as
1747 // FtzRequirementTy will be FTZ_Any.)
1748 if (Action.FtzRequirement != FTZ_Any) {
1749 bool FtzEnabled =
1750 II->getFunction()->getFnAttribute("nvptx-f32ftz").getValueAsString() ==
1751 "true";
1752
1753 if (FtzEnabled != (Action.FtzRequirement == FTZ_MustBeOn))
1754 return nullptr;
1755 }
1756
1757 // Simplify to target-generic intrinsic.
1758 if (Action.IID) {
1759 SmallVector<Value *, 4> Args(II->arg_operands());
1760 // All the target-generic intrinsics currently of interest to us have one
1761 // type argument, equal to that of the nvvm intrinsic's argument.
Justin Lebare3ac0fb2017-01-27 01:49:39 +00001762 Type *Tys[] = {II->getArgOperand(0)->getType()};
Justin Lebar698c31b2017-01-27 00:58:58 +00001763 return CallInst::Create(
1764 Intrinsic::getDeclaration(II->getModule(), *Action.IID, Tys), Args);
1765 }
1766
1767 // Simplify to target-generic binary op.
1768 if (Action.BinaryOp)
1769 return BinaryOperator::Create(*Action.BinaryOp, II->getArgOperand(0),
1770 II->getArgOperand(1), II->getName());
1771
1772 // Simplify to target-generic cast op.
1773 if (Action.CastOp)
1774 return CastInst::Create(*Action.CastOp, II->getArgOperand(0), II->getType(),
1775 II->getName());
1776
1777 // All that's left are the special cases.
1778 if (!Action.Special)
1779 return nullptr;
1780
1781 switch (*Action.Special) {
1782 case SPC_Reciprocal:
1783 // Simplify reciprocal.
1784 return BinaryOperator::Create(
1785 Instruction::FDiv, ConstantFP::get(II->getArgOperand(0)->getType(), 1),
1786 II->getArgOperand(0), II->getName());
1787 }
Justin Lebar25ebe2d2017-01-27 02:04:07 +00001788 llvm_unreachable("All SpecialCase enumerators should be handled in switch.");
Justin Lebar698c31b2017-01-27 00:58:58 +00001789}
1790
Arnaud A. de Grandmaison333ef382016-05-10 09:24:49 +00001791Instruction *InstCombiner::visitVAStartInst(VAStartInst &I) {
1792 removeTriviallyEmptyRange(I, Intrinsic::vastart, Intrinsic::vaend, *this);
1793 return nullptr;
1794}
1795
1796Instruction *InstCombiner::visitVACopyInst(VACopyInst &I) {
1797 removeTriviallyEmptyRange(I, Intrinsic::vacopy, Intrinsic::vaend, *this);
1798 return nullptr;
1799}
1800
Sanjay Patelcd4377c2016-01-20 22:24:38 +00001801/// CallInst simplification. This mostly only handles folding of intrinsic
1802/// instructions. For normal calls, it allows visitCallSite to do the heavy
1803/// lifting.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001804Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Philip Reames7a6db4f2017-12-27 00:16:12 +00001805 if (Value *V = SimplifyCall(&CI, SQ.getWithInstruction(&CI)))
Sanjay Patel4b198802016-02-01 22:23:39 +00001806 return replaceInstUsesWith(CI, V);
David Majnemer15032582015-05-22 03:56:46 +00001807
Justin Bogner99798402016-08-05 01:06:44 +00001808 if (isFreeCall(&CI, &TLI))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001809 return visitFree(CI);
1810
1811 // If the caller function is nounwind, mark the call as nounwind, even if the
1812 // callee isn't.
Sanjay Patel5a470952016-08-11 15:16:06 +00001813 if (CI.getFunction()->doesNotThrow() && !CI.doesNotThrow()) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001814 CI.setDoesNotThrow();
1815 return &CI;
1816 }
Jim Grosbach7815f562012-02-03 00:07:04 +00001817
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001818 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
1819 if (!II) return visitCallSite(&CI);
Gabor Greif589a0b92010-06-24 12:58:35 +00001820
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001821 // Intrinsics cannot occur in an invoke, so handle them here instead of in
1822 // visitCallSite.
1823 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
1824 bool Changed = false;
1825
1826 // memmove/cpy/set of zero bytes is a noop.
1827 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
Chris Lattnerc663a672010-10-01 05:51:02 +00001828 if (NumBytes->isNullValue())
Sanjay Patel4b198802016-02-01 22:23:39 +00001829 return eraseInstFromFunction(CI);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001830
1831 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
1832 if (CI->getZExtValue() == 1) {
1833 // Replace the instruction with just byte operations. We would
1834 // transform other cases to loads/stores, but we don't know if
1835 // alignment is sufficient.
1836 }
1837 }
Jim Grosbach7815f562012-02-03 00:07:04 +00001838
Chris Lattnerc663a672010-10-01 05:51:02 +00001839 // No other transformations apply to volatile transfers.
1840 if (MI->isVolatile())
Craig Topperf40110f2014-04-25 05:29:35 +00001841 return nullptr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001842
1843 // If we have a memmove and the source operation is a constant global,
1844 // then the source and dest pointers can't alias, so we can change this
1845 // into a call to memcpy.
1846 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
1847 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
1848 if (GVSrc->isConstant()) {
Sanjay Patelaf674fb2015-12-14 17:24:23 +00001849 Module *M = CI.getModule();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001850 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
Jay Foadb804a2b2011-07-12 14:06:48 +00001851 Type *Tys[3] = { CI.getArgOperand(0)->getType(),
1852 CI.getArgOperand(1)->getType(),
1853 CI.getArgOperand(2)->getType() };
Benjamin Kramere6e19332011-07-14 17:45:39 +00001854 CI.setCalledFunction(Intrinsic::getDeclaration(M, MemCpyID, Tys));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001855 Changed = true;
1856 }
1857 }
1858
1859 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) {
1860 // memmove(x,x,size) -> noop.
1861 if (MTI->getSource() == MTI->getDest())
Sanjay Patel4b198802016-02-01 22:23:39 +00001862 return eraseInstFromFunction(CI);
Eric Christopher7258dcd2010-04-16 23:37:20 +00001863 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001864
Eric Christopher7258dcd2010-04-16 23:37:20 +00001865 // If we can determine a pointer alignment that is bigger than currently
1866 // set, update the alignment.
Pete Cooper67cf9a72015-11-19 05:56:52 +00001867 if (isa<MemTransferInst>(MI)) {
1868 if (Instruction *I = SimplifyMemTransfer(MI))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001869 return I;
1870 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
1871 if (Instruction *I = SimplifyMemSet(MSI))
1872 return I;
1873 }
Gabor Greif590d95e2010-06-24 13:42:49 +00001874
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001875 if (Changed) return II;
1876 }
Jim Grosbach7815f562012-02-03 00:07:04 +00001877
Daniel Neilsonf9c7d292017-10-30 19:51:48 +00001878 if (auto *AMI = dyn_cast<AtomicMemCpyInst>(II)) {
Daniel Neilson3faabbb2017-06-16 14:43:59 +00001879 if (Constant *C = dyn_cast<Constant>(AMI->getLength()))
Igor Laevsky4b317fa2017-02-08 14:23:47 +00001880 if (C->isNullValue())
1881 return eraseInstFromFunction(*AMI);
Igor Laevsky900ffa32017-02-08 14:32:04 +00001882
Daniel Neilson3faabbb2017-06-16 14:43:59 +00001883 if (Instruction *I = SimplifyElementUnorderedAtomicMemCpy(AMI))
Igor Laevsky900ffa32017-02-08 14:32:04 +00001884 return I;
Igor Laevsky4b317fa2017-02-08 14:23:47 +00001885 }
1886
Justin Lebar698c31b2017-01-27 00:58:58 +00001887 if (Instruction *I = SimplifyNVVMIntrinsic(II, *this))
1888 return I;
1889
Sanjay Patel1c600c62016-01-20 16:41:43 +00001890 auto SimplifyDemandedVectorEltsLow = [this](Value *Op, unsigned Width,
1891 unsigned DemandedWidth) {
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001892 APInt UndefElts(Width, 0);
1893 APInt DemandedElts = APInt::getLowBitsSet(Width, DemandedWidth);
1894 return SimplifyDemandedVectorElts(Op, DemandedElts, UndefElts);
1895 };
1896
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001897 switch (II->getIntrinsicID()) {
1898 default: break;
George Burgess IV3f089142016-12-20 23:46:36 +00001899 case Intrinsic::objectsize:
1900 if (ConstantInt *N =
1901 lowerObjectSizeCall(II, DL, &TLI, /*MustSucceed=*/false))
1902 return replaceInstUsesWith(CI, N);
Craig Topperf40110f2014-04-25 05:29:35 +00001903 return nullptr;
Michael Ilseman536cc322012-12-13 03:13:36 +00001904 case Intrinsic::bswap: {
1905 Value *IIOperand = II->getArgOperand(0);
Craig Topperf40110f2014-04-25 05:29:35 +00001906 Value *X = nullptr;
Michael Ilseman536cc322012-12-13 03:13:36 +00001907
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001908 // bswap(trunc(bswap(x))) -> trunc(lshr(x, c))
Michael Ilseman536cc322012-12-13 03:13:36 +00001909 if (match(IIOperand, m_Trunc(m_BSwap(m_Value(X))))) {
1910 unsigned C = X->getType()->getPrimitiveSizeInBits() -
1911 IIOperand->getType()->getPrimitiveSizeInBits();
1912 Value *CV = ConstantInt::get(X->getType(), C);
Craig Topperbb4069e2017-07-07 23:16:26 +00001913 Value *V = Builder.CreateLShr(X, CV);
Michael Ilseman536cc322012-12-13 03:13:36 +00001914 return new TruncInst(V, IIOperand->getType());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001915 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001916 break;
Michael Ilseman536cc322012-12-13 03:13:36 +00001917 }
Sanjay Patelb695c552016-02-01 17:00:10 +00001918 case Intrinsic::masked_load:
Craig Topperbb4069e2017-07-07 23:16:26 +00001919 if (Value *SimplifiedMaskedOp = simplifyMaskedLoad(*II, Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00001920 return replaceInstUsesWith(CI, SimplifiedMaskedOp);
Sanjay Patelb695c552016-02-01 17:00:10 +00001921 break;
Sanjay Patel04f792b2016-02-01 19:39:52 +00001922 case Intrinsic::masked_store:
1923 return simplifyMaskedStore(*II, *this);
Sanjay Patel103ab7d2016-02-01 22:10:26 +00001924 case Intrinsic::masked_gather:
1925 return simplifyMaskedGather(*II, *this);
1926 case Intrinsic::masked_scatter:
1927 return simplifyMaskedScatter(*II, *this);
Sanjay Patelb695c552016-02-01 17:00:10 +00001928
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001929 case Intrinsic::powi:
Gabor Greif589a0b92010-06-24 12:58:35 +00001930 if (ConstantInt *Power = dyn_cast<ConstantInt>(II->getArgOperand(1))) {
Philip Reames5000ba62017-12-27 01:14:30 +00001931 // 0 and 1 are handled in instsimplify
1932
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001933 // powi(x, -1) -> 1/x
Craig Topper79ab6432017-07-06 18:39:47 +00001934 if (Power->isMinusOne())
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001935 return BinaryOperator::CreateFDiv(ConstantFP::get(CI.getType(), 1.0),
Gabor Greif589a0b92010-06-24 12:58:35 +00001936 II->getArgOperand(0));
Philip Reamescd13a662017-12-27 01:30:12 +00001937 // powi(x, 2) -> x*x
1938 if (Power->equalsInt(2))
1939 return BinaryOperator::CreateFMul(II->getArgOperand(0),
1940 II->getArgOperand(0));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001941 }
1942 break;
Jim Grosbach7815f562012-02-03 00:07:04 +00001943
Sanjay Patel8e3ab172016-08-05 22:42:46 +00001944 case Intrinsic::cttz:
1945 case Intrinsic::ctlz:
Amaury Sechet763c59d2016-08-18 20:43:50 +00001946 if (auto *I = foldCttzCtlz(*II, *this))
1947 return I;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001948 break;
Sanjoy Dasb0984472015-04-08 04:27:22 +00001949
Craig Topper5b173f22017-06-21 16:32:35 +00001950 case Intrinsic::ctpop:
1951 if (auto *I = foldCtpop(*II, *this))
1952 return I;
1953 break;
1954
Nick Lewyckyabe2cc12015-04-13 19:17:37 +00001955 case Intrinsic::uadd_with_overflow:
1956 case Intrinsic::sadd_with_overflow:
1957 case Intrinsic::umul_with_overflow:
1958 case Intrinsic::smul_with_overflow:
Gabor Greif5b1370e2010-06-28 16:50:57 +00001959 if (isa<Constant>(II->getArgOperand(0)) &&
1960 !isa<Constant>(II->getArgOperand(1))) {
Sanjoy Dasb0984472015-04-08 04:27:22 +00001961 // Canonicalize constants into the RHS.
Gabor Greif5b1370e2010-06-28 16:50:57 +00001962 Value *LHS = II->getArgOperand(0);
1963 II->setArgOperand(0, II->getArgOperand(1));
1964 II->setArgOperand(1, LHS);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001965 return II;
1966 }
Justin Bognercd1d5aa2016-08-17 20:30:52 +00001967 LLVM_FALLTHROUGH;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001968
Nick Lewyckyabe2cc12015-04-13 19:17:37 +00001969 case Intrinsic::usub_with_overflow:
1970 case Intrinsic::ssub_with_overflow: {
Sanjoy Dasb0984472015-04-08 04:27:22 +00001971 OverflowCheckFlavor OCF =
1972 IntrinsicIDToOverflowCheckFlavor(II->getIntrinsicID());
1973 assert(OCF != OCF_INVALID && "unexpected!");
Jim Grosbach7815f562012-02-03 00:07:04 +00001974
Sanjoy Dasb0984472015-04-08 04:27:22 +00001975 Value *OperationResult = nullptr;
1976 Constant *OverflowResult = nullptr;
1977 if (OptimizeOverflowCheck(OCF, II->getArgOperand(0), II->getArgOperand(1),
1978 *II, OperationResult, OverflowResult))
1979 return CreateOverflowTuple(II, OperationResult, OverflowResult);
Benjamin Kramera420df22014-07-04 10:22:21 +00001980
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001981 break;
Erik Eckstein096ff7d2014-12-11 08:02:30 +00001982 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001983
Matt Arsenaultd6511b42014-10-21 23:00:20 +00001984 case Intrinsic::minnum:
1985 case Intrinsic::maxnum: {
1986 Value *Arg0 = II->getArgOperand(0);
1987 Value *Arg1 = II->getArgOperand(1);
Sanjay Patel0069f562016-01-31 16:35:23 +00001988 // Canonicalize constants to the RHS.
1989 if (isa<ConstantFP>(Arg0) && !isa<ConstantFP>(Arg1)) {
Matt Arsenaultd6511b42014-10-21 23:00:20 +00001990 II->setArgOperand(0, Arg1);
1991 II->setArgOperand(1, Arg0);
1992 return II;
1993 }
Sanjay Patel0069f562016-01-31 16:35:23 +00001994 if (Value *V = simplifyMinnumMaxnum(*II))
Sanjay Patel4b198802016-02-01 22:23:39 +00001995 return replaceInstUsesWith(*II, V);
Matt Arsenaultd6511b42014-10-21 23:00:20 +00001996 break;
1997 }
Matt Arsenault1cc294c2017-01-03 04:32:31 +00001998 case Intrinsic::fmuladd: {
Matt Arsenault92057602017-02-16 18:46:24 +00001999 // Canonicalize fast fmuladd to the separate fmul + fadd.
Sanjay Patel629c4112017-11-06 16:27:15 +00002000 if (II->isFast()) {
Craig Topperbb4069e2017-07-07 23:16:26 +00002001 BuilderTy::FastMathFlagGuard Guard(Builder);
2002 Builder.setFastMathFlags(II->getFastMathFlags());
2003 Value *Mul = Builder.CreateFMul(II->getArgOperand(0),
2004 II->getArgOperand(1));
2005 Value *Add = Builder.CreateFAdd(Mul, II->getArgOperand(2));
Matt Arsenault92057602017-02-16 18:46:24 +00002006 Add->takeName(II);
2007 return replaceInstUsesWith(*II, Add);
2008 }
2009
2010 LLVM_FALLTHROUGH;
2011 }
2012 case Intrinsic::fma: {
Matt Arsenault1cc294c2017-01-03 04:32:31 +00002013 Value *Src0 = II->getArgOperand(0);
2014 Value *Src1 = II->getArgOperand(1);
2015
Matt Arsenaultb264c942017-01-03 04:32:35 +00002016 // Canonicalize constants into the RHS.
2017 if (isa<Constant>(Src0) && !isa<Constant>(Src1)) {
2018 II->setArgOperand(0, Src1);
2019 II->setArgOperand(1, Src0);
2020 std::swap(Src0, Src1);
2021 }
2022
2023 Value *LHS = nullptr;
2024 Value *RHS = nullptr;
2025
Matt Arsenault1cc294c2017-01-03 04:32:31 +00002026 // fma fneg(x), fneg(y), z -> fma x, y, z
2027 if (match(Src0, m_FNeg(m_Value(LHS))) &&
2028 match(Src1, m_FNeg(m_Value(RHS)))) {
Matt Arsenault3f509042017-01-10 23:17:52 +00002029 II->setArgOperand(0, LHS);
2030 II->setArgOperand(1, RHS);
2031 return II;
Matt Arsenault1cc294c2017-01-03 04:32:31 +00002032 }
2033
2034 // fma fabs(x), fabs(x), z -> fma x, x, z
2035 if (match(Src0, m_Intrinsic<Intrinsic::fabs>(m_Value(LHS))) &&
2036 match(Src1, m_Intrinsic<Intrinsic::fabs>(m_Value(RHS))) && LHS == RHS) {
Matt Arsenault3f509042017-01-10 23:17:52 +00002037 II->setArgOperand(0, LHS);
2038 II->setArgOperand(1, RHS);
2039 return II;
Matt Arsenault1cc294c2017-01-03 04:32:31 +00002040 }
2041
Matt Arsenaultb264c942017-01-03 04:32:35 +00002042 // fma x, 1, z -> fadd x, z
2043 if (match(Src1, m_FPOne())) {
2044 Instruction *RI = BinaryOperator::CreateFAdd(Src0, II->getArgOperand(2));
2045 RI->copyFastMathFlags(II);
2046 return RI;
2047 }
2048
Matt Arsenault1cc294c2017-01-03 04:32:31 +00002049 break;
2050 }
Matt Arsenault56ff4832017-01-03 22:40:34 +00002051 case Intrinsic::fabs: {
2052 Value *Cond;
2053 Constant *LHS, *RHS;
2054 if (match(II->getArgOperand(0),
2055 m_Select(m_Value(Cond), m_Constant(LHS), m_Constant(RHS)))) {
Craig Topperbb4069e2017-07-07 23:16:26 +00002056 CallInst *Call0 = Builder.CreateCall(II->getCalledFunction(), {LHS});
2057 CallInst *Call1 = Builder.CreateCall(II->getCalledFunction(), {RHS});
Matt Arsenault56ff4832017-01-03 22:40:34 +00002058 return SelectInst::Create(Cond, Call0, Call1);
2059 }
2060
Matt Arsenault954a6242017-01-23 23:55:08 +00002061 LLVM_FALLTHROUGH;
2062 }
2063 case Intrinsic::ceil:
2064 case Intrinsic::floor:
2065 case Intrinsic::round:
2066 case Intrinsic::nearbyint:
Joerg Sonnenberger28bed102017-03-31 19:58:07 +00002067 case Intrinsic::rint:
Matt Arsenault954a6242017-01-23 23:55:08 +00002068 case Intrinsic::trunc: {
Matt Arsenault72333442017-01-17 00:10:40 +00002069 Value *ExtSrc;
2070 if (match(II->getArgOperand(0), m_FPExt(m_Value(ExtSrc))) &&
2071 II->getArgOperand(0)->hasOneUse()) {
2072 // fabs (fpext x) -> fpext (fabs x)
Matt Arsenault954a6242017-01-23 23:55:08 +00002073 Value *F = Intrinsic::getDeclaration(II->getModule(), II->getIntrinsicID(),
Matt Arsenault72333442017-01-17 00:10:40 +00002074 { ExtSrc->getType() });
Craig Topperbb4069e2017-07-07 23:16:26 +00002075 CallInst *NewFabs = Builder.CreateCall(F, ExtSrc);
Matt Arsenault72333442017-01-17 00:10:40 +00002076 NewFabs->copyFastMathFlags(II);
2077 NewFabs->takeName(II);
2078 return new FPExtInst(NewFabs, II->getType());
2079 }
2080
Matt Arsenault56ff4832017-01-03 22:40:34 +00002081 break;
2082 }
Matt Arsenault3bdd75d2017-01-04 22:49:03 +00002083 case Intrinsic::cos:
2084 case Intrinsic::amdgcn_cos: {
2085 Value *SrcSrc;
2086 Value *Src = II->getArgOperand(0);
2087 if (match(Src, m_FNeg(m_Value(SrcSrc))) ||
2088 match(Src, m_Intrinsic<Intrinsic::fabs>(m_Value(SrcSrc)))) {
2089 // cos(-x) -> cos(x)
2090 // cos(fabs(x)) -> cos(x)
2091 II->setArgOperand(0, SrcSrc);
2092 return II;
2093 }
2094
2095 break;
2096 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002097 case Intrinsic::ppc_altivec_lvx:
2098 case Intrinsic::ppc_altivec_lvxl:
Bill Wendlingb902f1d2011-04-13 00:36:11 +00002099 // Turn PPC lvx -> load if the pointer is known aligned.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002100 if (getOrEnforceKnownAlignment(II->getArgOperand(0), 16, DL, II, &AC,
Justin Bogner99798402016-08-05 01:06:44 +00002101 &DT) >= 16) {
Craig Topperbb4069e2017-07-07 23:16:26 +00002102 Value *Ptr = Builder.CreateBitCast(II->getArgOperand(0),
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002103 PointerType::getUnqual(II->getType()));
2104 return new LoadInst(Ptr);
2105 }
2106 break;
Bill Schmidt72954782014-11-12 04:19:40 +00002107 case Intrinsic::ppc_vsx_lxvw4x:
2108 case Intrinsic::ppc_vsx_lxvd2x: {
2109 // Turn PPC VSX loads into normal loads.
Craig Topperbb4069e2017-07-07 23:16:26 +00002110 Value *Ptr = Builder.CreateBitCast(II->getArgOperand(0),
2111 PointerType::getUnqual(II->getType()));
Bill Schmidt72954782014-11-12 04:19:40 +00002112 return new LoadInst(Ptr, Twine(""), false, 1);
2113 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002114 case Intrinsic::ppc_altivec_stvx:
2115 case Intrinsic::ppc_altivec_stvxl:
2116 // Turn stvx -> store if the pointer is known aligned.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002117 if (getOrEnforceKnownAlignment(II->getArgOperand(1), 16, DL, II, &AC,
Justin Bogner99798402016-08-05 01:06:44 +00002118 &DT) >= 16) {
Jim Grosbach7815f562012-02-03 00:07:04 +00002119 Type *OpPtrTy =
Gabor Greifa6d75e22010-06-24 15:51:11 +00002120 PointerType::getUnqual(II->getArgOperand(0)->getType());
Craig Topperbb4069e2017-07-07 23:16:26 +00002121 Value *Ptr = Builder.CreateBitCast(II->getArgOperand(1), OpPtrTy);
Gabor Greifa6d75e22010-06-24 15:51:11 +00002122 return new StoreInst(II->getArgOperand(0), Ptr);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002123 }
2124 break;
Bill Schmidt72954782014-11-12 04:19:40 +00002125 case Intrinsic::ppc_vsx_stxvw4x:
2126 case Intrinsic::ppc_vsx_stxvd2x: {
2127 // Turn PPC VSX stores into normal stores.
2128 Type *OpPtrTy = PointerType::getUnqual(II->getArgOperand(0)->getType());
Craig Topperbb4069e2017-07-07 23:16:26 +00002129 Value *Ptr = Builder.CreateBitCast(II->getArgOperand(1), OpPtrTy);
Bill Schmidt72954782014-11-12 04:19:40 +00002130 return new StoreInst(II->getArgOperand(0), Ptr, false, 1);
2131 }
Hal Finkel221f4672015-02-26 18:56:03 +00002132 case Intrinsic::ppc_qpx_qvlfs:
2133 // Turn PPC QPX qvlfs -> load if the pointer is known aligned.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002134 if (getOrEnforceKnownAlignment(II->getArgOperand(0), 16, DL, II, &AC,
Justin Bogner99798402016-08-05 01:06:44 +00002135 &DT) >= 16) {
Craig Topperbb4069e2017-07-07 23:16:26 +00002136 Type *VTy = VectorType::get(Builder.getFloatTy(),
Hal Finkelf0d68d72015-05-11 06:37:03 +00002137 II->getType()->getVectorNumElements());
Craig Topperbb4069e2017-07-07 23:16:26 +00002138 Value *Ptr = Builder.CreateBitCast(II->getArgOperand(0),
Hal Finkelf0d68d72015-05-11 06:37:03 +00002139 PointerType::getUnqual(VTy));
Craig Topperbb4069e2017-07-07 23:16:26 +00002140 Value *Load = Builder.CreateLoad(Ptr);
Hal Finkelf0d68d72015-05-11 06:37:03 +00002141 return new FPExtInst(Load, II->getType());
Hal Finkel221f4672015-02-26 18:56:03 +00002142 }
2143 break;
2144 case Intrinsic::ppc_qpx_qvlfd:
2145 // Turn PPC QPX qvlfd -> load if the pointer is known aligned.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002146 if (getOrEnforceKnownAlignment(II->getArgOperand(0), 32, DL, II, &AC,
Justin Bogner99798402016-08-05 01:06:44 +00002147 &DT) >= 32) {
Craig Topperbb4069e2017-07-07 23:16:26 +00002148 Value *Ptr = Builder.CreateBitCast(II->getArgOperand(0),
Hal Finkel221f4672015-02-26 18:56:03 +00002149 PointerType::getUnqual(II->getType()));
2150 return new LoadInst(Ptr);
2151 }
2152 break;
2153 case Intrinsic::ppc_qpx_qvstfs:
2154 // Turn PPC QPX qvstfs -> store if the pointer is known aligned.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002155 if (getOrEnforceKnownAlignment(II->getArgOperand(1), 16, DL, II, &AC,
Justin Bogner99798402016-08-05 01:06:44 +00002156 &DT) >= 16) {
Craig Topperbb4069e2017-07-07 23:16:26 +00002157 Type *VTy = VectorType::get(Builder.getFloatTy(),
Hal Finkelf0d68d72015-05-11 06:37:03 +00002158 II->getArgOperand(0)->getType()->getVectorNumElements());
Craig Topperbb4069e2017-07-07 23:16:26 +00002159 Value *TOp = Builder.CreateFPTrunc(II->getArgOperand(0), VTy);
Hal Finkelf0d68d72015-05-11 06:37:03 +00002160 Type *OpPtrTy = PointerType::getUnqual(VTy);
Craig Topperbb4069e2017-07-07 23:16:26 +00002161 Value *Ptr = Builder.CreateBitCast(II->getArgOperand(1), OpPtrTy);
Hal Finkelf0d68d72015-05-11 06:37:03 +00002162 return new StoreInst(TOp, Ptr);
Hal Finkel221f4672015-02-26 18:56:03 +00002163 }
2164 break;
2165 case Intrinsic::ppc_qpx_qvstfd:
2166 // Turn PPC QPX qvstfd -> store if the pointer is known aligned.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002167 if (getOrEnforceKnownAlignment(II->getArgOperand(1), 32, DL, II, &AC,
Justin Bogner99798402016-08-05 01:06:44 +00002168 &DT) >= 32) {
Hal Finkel221f4672015-02-26 18:56:03 +00002169 Type *OpPtrTy =
2170 PointerType::getUnqual(II->getArgOperand(0)->getType());
Craig Topperbb4069e2017-07-07 23:16:26 +00002171 Value *Ptr = Builder.CreateBitCast(II->getArgOperand(1), OpPtrTy);
Hal Finkel221f4672015-02-26 18:56:03 +00002172 return new StoreInst(II->getArgOperand(0), Ptr);
2173 }
2174 break;
Simon Pilgrim20c607b2015-09-12 13:39:53 +00002175
Craig Topper83240032017-07-31 18:52:13 +00002176 case Intrinsic::x86_bmi_bextr_32:
2177 case Intrinsic::x86_bmi_bextr_64:
2178 case Intrinsic::x86_tbm_bextri_u32:
2179 case Intrinsic::x86_tbm_bextri_u64:
2180 // If the RHS is a constant we can try some simplifications.
2181 if (auto *C = dyn_cast<ConstantInt>(II->getArgOperand(1))) {
2182 uint64_t Shift = C->getZExtValue();
2183 uint64_t Length = (Shift >> 8) & 0xff;
2184 Shift &= 0xff;
2185 unsigned BitWidth = II->getType()->getIntegerBitWidth();
2186 // If the length is 0 or the shift is out of range, replace with zero.
2187 if (Length == 0 || Shift >= BitWidth)
2188 return replaceInstUsesWith(CI, ConstantInt::get(II->getType(), 0));
2189 // If the LHS is also a constant, we can completely constant fold this.
2190 if (auto *InC = dyn_cast<ConstantInt>(II->getArgOperand(0))) {
2191 uint64_t Result = InC->getZExtValue() >> Shift;
2192 if (Length > BitWidth)
2193 Length = BitWidth;
2194 Result &= maskTrailingOnes<uint64_t>(Length);
2195 return replaceInstUsesWith(CI, ConstantInt::get(II->getType(), Result));
2196 }
2197 // TODO should we turn this into 'and' if shift is 0? Or 'shl' if we
2198 // are only masking bits that a shift already cleared?
2199 }
2200 break;
2201
Craig Topper317a51e2017-07-31 18:52:15 +00002202 case Intrinsic::x86_bmi_bzhi_32:
2203 case Intrinsic::x86_bmi_bzhi_64:
2204 // If the RHS is a constant we can try some simplifications.
2205 if (auto *C = dyn_cast<ConstantInt>(II->getArgOperand(1))) {
2206 uint64_t Index = C->getZExtValue() & 0xff;
2207 unsigned BitWidth = II->getType()->getIntegerBitWidth();
2208 if (Index >= BitWidth)
2209 return replaceInstUsesWith(CI, II->getArgOperand(0));
2210 if (Index == 0)
2211 return replaceInstUsesWith(CI, ConstantInt::get(II->getType(), 0));
2212 // If the LHS is also a constant, we can completely constant fold this.
2213 if (auto *InC = dyn_cast<ConstantInt>(II->getArgOperand(0))) {
2214 uint64_t Result = InC->getZExtValue();
2215 Result &= maskTrailingOnes<uint64_t>(Index);
2216 return replaceInstUsesWith(CI, ConstantInt::get(II->getType(), Result));
2217 }
2218 // TODO should we convert this to an AND if the RHS is constant?
2219 }
2220 break;
2221
Simon Pilgrim20c607b2015-09-12 13:39:53 +00002222 case Intrinsic::x86_vcvtph2ps_128:
2223 case Intrinsic::x86_vcvtph2ps_256: {
2224 auto Arg = II->getArgOperand(0);
2225 auto ArgType = cast<VectorType>(Arg->getType());
2226 auto RetType = cast<VectorType>(II->getType());
2227 unsigned ArgWidth = ArgType->getNumElements();
2228 unsigned RetWidth = RetType->getNumElements();
2229 assert(RetWidth <= ArgWidth && "Unexpected input/return vector widths");
2230 assert(ArgType->isIntOrIntVectorTy() &&
2231 ArgType->getScalarSizeInBits() == 16 &&
2232 "CVTPH2PS input type should be 16-bit integer vector");
2233 assert(RetType->getScalarType()->isFloatTy() &&
2234 "CVTPH2PS output type should be 32-bit float vector");
2235
2236 // Constant folding: Convert to generic half to single conversion.
Simon Pilgrim48ffca02015-09-12 14:00:17 +00002237 if (isa<ConstantAggregateZero>(Arg))
Sanjay Patel4b198802016-02-01 22:23:39 +00002238 return replaceInstUsesWith(*II, ConstantAggregateZero::get(RetType));
Simon Pilgrim20c607b2015-09-12 13:39:53 +00002239
Simon Pilgrim48ffca02015-09-12 14:00:17 +00002240 if (isa<ConstantDataVector>(Arg)) {
Simon Pilgrim20c607b2015-09-12 13:39:53 +00002241 auto VectorHalfAsShorts = Arg;
2242 if (RetWidth < ArgWidth) {
Craig Topper99d1eab2016-06-12 00:41:19 +00002243 SmallVector<uint32_t, 8> SubVecMask;
Simon Pilgrim20c607b2015-09-12 13:39:53 +00002244 for (unsigned i = 0; i != RetWidth; ++i)
2245 SubVecMask.push_back((int)i);
Craig Topperbb4069e2017-07-07 23:16:26 +00002246 VectorHalfAsShorts = Builder.CreateShuffleVector(
Simon Pilgrim20c607b2015-09-12 13:39:53 +00002247 Arg, UndefValue::get(ArgType), SubVecMask);
2248 }
2249
2250 auto VectorHalfType =
2251 VectorType::get(Type::getHalfTy(II->getContext()), RetWidth);
2252 auto VectorHalfs =
Craig Topperbb4069e2017-07-07 23:16:26 +00002253 Builder.CreateBitCast(VectorHalfAsShorts, VectorHalfType);
2254 auto VectorFloats = Builder.CreateFPExt(VectorHalfs, RetType);
Sanjay Patel4b198802016-02-01 22:23:39 +00002255 return replaceInstUsesWith(*II, VectorFloats);
Simon Pilgrim20c607b2015-09-12 13:39:53 +00002256 }
2257
2258 // We only use the lowest lanes of the argument.
Simon Pilgrim996725e2015-09-19 11:41:53 +00002259 if (Value *V = SimplifyDemandedVectorEltsLow(Arg, ArgWidth, RetWidth)) {
Simon Pilgrim20c607b2015-09-12 13:39:53 +00002260 II->setArgOperand(0, V);
2261 return II;
2262 }
2263 break;
2264 }
2265
Chandler Carruthcf414cf2011-01-10 07:19:37 +00002266 case Intrinsic::x86_sse_cvtss2si:
2267 case Intrinsic::x86_sse_cvtss2si64:
2268 case Intrinsic::x86_sse_cvttss2si:
2269 case Intrinsic::x86_sse_cvttss2si64:
2270 case Intrinsic::x86_sse2_cvtsd2si:
2271 case Intrinsic::x86_sse2_cvtsd2si64:
2272 case Intrinsic::x86_sse2_cvttsd2si:
Craig Topperaeaa52c2016-12-14 07:46:12 +00002273 case Intrinsic::x86_sse2_cvttsd2si64:
2274 case Intrinsic::x86_avx512_vcvtss2si32:
2275 case Intrinsic::x86_avx512_vcvtss2si64:
2276 case Intrinsic::x86_avx512_vcvtss2usi32:
2277 case Intrinsic::x86_avx512_vcvtss2usi64:
2278 case Intrinsic::x86_avx512_vcvtsd2si32:
2279 case Intrinsic::x86_avx512_vcvtsd2si64:
2280 case Intrinsic::x86_avx512_vcvtsd2usi32:
2281 case Intrinsic::x86_avx512_vcvtsd2usi64:
2282 case Intrinsic::x86_avx512_cvttss2si:
2283 case Intrinsic::x86_avx512_cvttss2si64:
2284 case Intrinsic::x86_avx512_cvttss2usi:
2285 case Intrinsic::x86_avx512_cvttss2usi64:
2286 case Intrinsic::x86_avx512_cvttsd2si:
2287 case Intrinsic::x86_avx512_cvttsd2si64:
2288 case Intrinsic::x86_avx512_cvttsd2usi:
2289 case Intrinsic::x86_avx512_cvttsd2usi64: {
Chandler Carruthcf414cf2011-01-10 07:19:37 +00002290 // These intrinsics only demand the 0th element of their input vectors. If
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002291 // we can simplify the input based on that, do so now.
Simon Pilgrim996725e2015-09-19 11:41:53 +00002292 Value *Arg = II->getArgOperand(0);
2293 unsigned VWidth = Arg->getType()->getVectorNumElements();
2294 if (Value *V = SimplifyDemandedVectorEltsLow(Arg, VWidth, 1)) {
Gabor Greif5b1370e2010-06-28 16:50:57 +00002295 II->setArgOperand(0, V);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002296 return II;
2297 }
Simon Pilgrim18617d12015-08-05 08:18:00 +00002298 break;
2299 }
2300
Simon Pilgrim91e3ac82016-06-07 08:18:35 +00002301 case Intrinsic::x86_mmx_pmovmskb:
2302 case Intrinsic::x86_sse_movmsk_ps:
2303 case Intrinsic::x86_sse2_movmsk_pd:
2304 case Intrinsic::x86_sse2_pmovmskb_128:
2305 case Intrinsic::x86_avx_movmsk_pd_256:
2306 case Intrinsic::x86_avx_movmsk_ps_256:
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +00002307 case Intrinsic::x86_avx2_pmovmskb:
Craig Topper4853c432017-07-06 23:18:42 +00002308 if (Value *V = simplifyX86movmsk(*II))
Simon Pilgrim91e3ac82016-06-07 08:18:35 +00002309 return replaceInstUsesWith(*II, V);
2310 break;
Simon Pilgrim91e3ac82016-06-07 08:18:35 +00002311
Simon Pilgrim471efd22016-02-20 23:17:35 +00002312 case Intrinsic::x86_sse_comieq_ss:
2313 case Intrinsic::x86_sse_comige_ss:
2314 case Intrinsic::x86_sse_comigt_ss:
2315 case Intrinsic::x86_sse_comile_ss:
2316 case Intrinsic::x86_sse_comilt_ss:
2317 case Intrinsic::x86_sse_comineq_ss:
2318 case Intrinsic::x86_sse_ucomieq_ss:
2319 case Intrinsic::x86_sse_ucomige_ss:
2320 case Intrinsic::x86_sse_ucomigt_ss:
2321 case Intrinsic::x86_sse_ucomile_ss:
2322 case Intrinsic::x86_sse_ucomilt_ss:
2323 case Intrinsic::x86_sse_ucomineq_ss:
2324 case Intrinsic::x86_sse2_comieq_sd:
2325 case Intrinsic::x86_sse2_comige_sd:
2326 case Intrinsic::x86_sse2_comigt_sd:
2327 case Intrinsic::x86_sse2_comile_sd:
2328 case Intrinsic::x86_sse2_comilt_sd:
2329 case Intrinsic::x86_sse2_comineq_sd:
2330 case Intrinsic::x86_sse2_ucomieq_sd:
2331 case Intrinsic::x86_sse2_ucomige_sd:
2332 case Intrinsic::x86_sse2_ucomigt_sd:
2333 case Intrinsic::x86_sse2_ucomile_sd:
2334 case Intrinsic::x86_sse2_ucomilt_sd:
Craig Topperd9639532016-12-11 07:42:04 +00002335 case Intrinsic::x86_sse2_ucomineq_sd:
Craig Topperd00db692016-12-31 00:45:06 +00002336 case Intrinsic::x86_avx512_vcomi_ss:
2337 case Intrinsic::x86_avx512_vcomi_sd:
Craig Topperd9639532016-12-11 07:42:04 +00002338 case Intrinsic::x86_avx512_mask_cmp_ss:
2339 case Intrinsic::x86_avx512_mask_cmp_sd: {
Simon Pilgrim471efd22016-02-20 23:17:35 +00002340 // These intrinsics only demand the 0th element of their input vectors. If
2341 // we can simplify the input based on that, do so now.
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002342 bool MadeChange = false;
Simon Pilgrim471efd22016-02-20 23:17:35 +00002343 Value *Arg0 = II->getArgOperand(0);
2344 Value *Arg1 = II->getArgOperand(1);
2345 unsigned VWidth = Arg0->getType()->getVectorNumElements();
2346 if (Value *V = SimplifyDemandedVectorEltsLow(Arg0, VWidth, 1)) {
2347 II->setArgOperand(0, V);
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002348 MadeChange = true;
Simon Pilgrim471efd22016-02-20 23:17:35 +00002349 }
2350 if (Value *V = SimplifyDemandedVectorEltsLow(Arg1, VWidth, 1)) {
2351 II->setArgOperand(1, V);
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002352 MadeChange = true;
Simon Pilgrim471efd22016-02-20 23:17:35 +00002353 }
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002354 if (MadeChange)
2355 return II;
Simon Pilgrim471efd22016-02-20 23:17:35 +00002356 break;
2357 }
Michael Zuckerman16b20d22017-04-16 13:26:08 +00002358 case Intrinsic::x86_avx512_mask_cmp_pd_128:
2359 case Intrinsic::x86_avx512_mask_cmp_pd_256:
2360 case Intrinsic::x86_avx512_mask_cmp_pd_512:
2361 case Intrinsic::x86_avx512_mask_cmp_ps_128:
2362 case Intrinsic::x86_avx512_mask_cmp_ps_256:
2363 case Intrinsic::x86_avx512_mask_cmp_ps_512: {
2364 // Folding cmp(sub(a,b),0) -> cmp(a,b) and cmp(0,sub(a,b)) -> cmp(b,a)
2365 Value *Arg0 = II->getArgOperand(0);
2366 Value *Arg1 = II->getArgOperand(1);
2367 bool Arg0IsZero = match(Arg0, m_Zero());
2368 if (Arg0IsZero)
2369 std::swap(Arg0, Arg1);
2370 Value *A, *B;
2371 // This fold requires only the NINF(not +/- inf) since inf minus
2372 // inf is nan.
2373 // NSZ(No Signed Zeros) is not needed because zeros of any sign are
2374 // equal for both compares.
2375 // NNAN is not needed because nans compare the same for both compares.
2376 // The compare intrinsic uses the above assumptions and therefore
2377 // doesn't require additional flags.
2378 if ((match(Arg0, m_OneUse(m_FSub(m_Value(A), m_Value(B)))) &&
Simon Pilgrim472689a2017-12-28 09:35:35 +00002379 match(Arg1, m_Zero()) && isa<Instruction>(Arg0) &&
Michael Zuckerman16b20d22017-04-16 13:26:08 +00002380 cast<Instruction>(Arg0)->getFastMathFlags().noInfs())) {
2381 if (Arg0IsZero)
2382 std::swap(A, B);
2383 II->setArgOperand(0, A);
2384 II->setArgOperand(1, B);
2385 return II;
2386 }
2387 break;
2388 }
Simon Pilgrim471efd22016-02-20 23:17:35 +00002389
Craig Topper020b2282016-12-27 00:23:16 +00002390 case Intrinsic::x86_avx512_mask_add_ps_512:
2391 case Intrinsic::x86_avx512_mask_div_ps_512:
2392 case Intrinsic::x86_avx512_mask_mul_ps_512:
2393 case Intrinsic::x86_avx512_mask_sub_ps_512:
2394 case Intrinsic::x86_avx512_mask_add_pd_512:
2395 case Intrinsic::x86_avx512_mask_div_pd_512:
2396 case Intrinsic::x86_avx512_mask_mul_pd_512:
2397 case Intrinsic::x86_avx512_mask_sub_pd_512:
2398 // If the rounding mode is CUR_DIRECTION(4) we can turn these into regular
2399 // IR operations.
2400 if (auto *R = dyn_cast<ConstantInt>(II->getArgOperand(4))) {
2401 if (R->getValue() == 4) {
2402 Value *Arg0 = II->getArgOperand(0);
2403 Value *Arg1 = II->getArgOperand(1);
2404
2405 Value *V;
2406 switch (II->getIntrinsicID()) {
2407 default: llvm_unreachable("Case stmts out of sync!");
2408 case Intrinsic::x86_avx512_mask_add_ps_512:
2409 case Intrinsic::x86_avx512_mask_add_pd_512:
Craig Topperbb4069e2017-07-07 23:16:26 +00002410 V = Builder.CreateFAdd(Arg0, Arg1);
Craig Topper020b2282016-12-27 00:23:16 +00002411 break;
2412 case Intrinsic::x86_avx512_mask_sub_ps_512:
2413 case Intrinsic::x86_avx512_mask_sub_pd_512:
Craig Topperbb4069e2017-07-07 23:16:26 +00002414 V = Builder.CreateFSub(Arg0, Arg1);
Craig Topper020b2282016-12-27 00:23:16 +00002415 break;
2416 case Intrinsic::x86_avx512_mask_mul_ps_512:
2417 case Intrinsic::x86_avx512_mask_mul_pd_512:
Craig Topperbb4069e2017-07-07 23:16:26 +00002418 V = Builder.CreateFMul(Arg0, Arg1);
Craig Topper020b2282016-12-27 00:23:16 +00002419 break;
2420 case Intrinsic::x86_avx512_mask_div_ps_512:
2421 case Intrinsic::x86_avx512_mask_div_pd_512:
Craig Topperbb4069e2017-07-07 23:16:26 +00002422 V = Builder.CreateFDiv(Arg0, Arg1);
Craig Topper020b2282016-12-27 00:23:16 +00002423 break;
2424 }
2425
2426 // Create a select for the masking.
2427 V = emitX86MaskSelect(II->getArgOperand(3), V, II->getArgOperand(2),
Craig Topperbb4069e2017-07-07 23:16:26 +00002428 Builder);
Craig Topper020b2282016-12-27 00:23:16 +00002429 return replaceInstUsesWith(*II, V);
2430 }
2431 }
2432 break;
2433
Craig Topper790d0fa2016-12-11 07:42:01 +00002434 case Intrinsic::x86_avx512_mask_add_ss_round:
2435 case Intrinsic::x86_avx512_mask_div_ss_round:
2436 case Intrinsic::x86_avx512_mask_mul_ss_round:
2437 case Intrinsic::x86_avx512_mask_sub_ss_round:
Craig Topper790d0fa2016-12-11 07:42:01 +00002438 case Intrinsic::x86_avx512_mask_add_sd_round:
2439 case Intrinsic::x86_avx512_mask_div_sd_round:
2440 case Intrinsic::x86_avx512_mask_mul_sd_round:
2441 case Intrinsic::x86_avx512_mask_sub_sd_round:
Craig Topper7b788ada2016-12-26 06:33:19 +00002442 // If the rounding mode is CUR_DIRECTION(4) we can turn these into regular
2443 // IR operations.
2444 if (auto *R = dyn_cast<ConstantInt>(II->getArgOperand(4))) {
2445 if (R->getValue() == 4) {
Craig Topper7f8540b2016-12-27 01:56:30 +00002446 // Extract the element as scalars.
2447 Value *Arg0 = II->getArgOperand(0);
2448 Value *Arg1 = II->getArgOperand(1);
Craig Topperbb4069e2017-07-07 23:16:26 +00002449 Value *LHS = Builder.CreateExtractElement(Arg0, (uint64_t)0);
2450 Value *RHS = Builder.CreateExtractElement(Arg1, (uint64_t)0);
Craig Topper7b788ada2016-12-26 06:33:19 +00002451
Craig Topper7f8540b2016-12-27 01:56:30 +00002452 Value *V;
2453 switch (II->getIntrinsicID()) {
2454 default: llvm_unreachable("Case stmts out of sync!");
2455 case Intrinsic::x86_avx512_mask_add_ss_round:
2456 case Intrinsic::x86_avx512_mask_add_sd_round:
Craig Topperbb4069e2017-07-07 23:16:26 +00002457 V = Builder.CreateFAdd(LHS, RHS);
Craig Topper7f8540b2016-12-27 01:56:30 +00002458 break;
2459 case Intrinsic::x86_avx512_mask_sub_ss_round:
2460 case Intrinsic::x86_avx512_mask_sub_sd_round:
Craig Topperbb4069e2017-07-07 23:16:26 +00002461 V = Builder.CreateFSub(LHS, RHS);
Craig Topper7f8540b2016-12-27 01:56:30 +00002462 break;
2463 case Intrinsic::x86_avx512_mask_mul_ss_round:
2464 case Intrinsic::x86_avx512_mask_mul_sd_round:
Craig Topperbb4069e2017-07-07 23:16:26 +00002465 V = Builder.CreateFMul(LHS, RHS);
Craig Topper7f8540b2016-12-27 01:56:30 +00002466 break;
2467 case Intrinsic::x86_avx512_mask_div_ss_round:
2468 case Intrinsic::x86_avx512_mask_div_sd_round:
Craig Topperbb4069e2017-07-07 23:16:26 +00002469 V = Builder.CreateFDiv(LHS, RHS);
Craig Topper7f8540b2016-12-27 01:56:30 +00002470 break;
Craig Topper7b788ada2016-12-26 06:33:19 +00002471 }
Craig Topper7f8540b2016-12-27 01:56:30 +00002472
2473 // Handle the masking aspect of the intrinsic.
Craig Topper7f8540b2016-12-27 01:56:30 +00002474 Value *Mask = II->getArgOperand(3);
Craig Topper99163632016-12-30 23:06:28 +00002475 auto *C = dyn_cast<ConstantInt>(Mask);
2476 // We don't need a select if we know the mask bit is a 1.
2477 if (!C || !C->getValue()[0]) {
2478 // Cast the mask to an i1 vector and then extract the lowest element.
Craig Topperbb4069e2017-07-07 23:16:26 +00002479 auto *MaskTy = VectorType::get(Builder.getInt1Ty(),
Craig Topper7f8540b2016-12-27 01:56:30 +00002480 cast<IntegerType>(Mask->getType())->getBitWidth());
Craig Topperbb4069e2017-07-07 23:16:26 +00002481 Mask = Builder.CreateBitCast(Mask, MaskTy);
2482 Mask = Builder.CreateExtractElement(Mask, (uint64_t)0);
Craig Topper99163632016-12-30 23:06:28 +00002483 // Extract the lowest element from the passthru operand.
Craig Topperbb4069e2017-07-07 23:16:26 +00002484 Value *Passthru = Builder.CreateExtractElement(II->getArgOperand(2),
Craig Topper99163632016-12-30 23:06:28 +00002485 (uint64_t)0);
Craig Topperbb4069e2017-07-07 23:16:26 +00002486 V = Builder.CreateSelect(Mask, V, Passthru);
Craig Topper99163632016-12-30 23:06:28 +00002487 }
Craig Topper7f8540b2016-12-27 01:56:30 +00002488
2489 // Insert the result back into the original argument 0.
Craig Topperbb4069e2017-07-07 23:16:26 +00002490 V = Builder.CreateInsertElement(Arg0, V, (uint64_t)0);
Craig Topper7f8540b2016-12-27 01:56:30 +00002491
2492 return replaceInstUsesWith(*II, V);
Craig Topper7b788ada2016-12-26 06:33:19 +00002493 }
2494 }
2495 LLVM_FALLTHROUGH;
2496
2497 // X86 scalar intrinsics simplified with SimplifyDemandedVectorElts.
2498 case Intrinsic::x86_avx512_mask_max_ss_round:
2499 case Intrinsic::x86_avx512_mask_min_ss_round:
Craig Topper790d0fa2016-12-11 07:42:01 +00002500 case Intrinsic::x86_avx512_mask_max_sd_round:
Craig Topper268b3ab2016-12-14 06:06:58 +00002501 case Intrinsic::x86_avx512_mask_min_sd_round:
Craig Topperab5f3552016-12-15 03:49:45 +00002502 case Intrinsic::x86_avx512_mask_vfmadd_ss:
2503 case Intrinsic::x86_avx512_mask_vfmadd_sd:
2504 case Intrinsic::x86_avx512_maskz_vfmadd_ss:
2505 case Intrinsic::x86_avx512_maskz_vfmadd_sd:
2506 case Intrinsic::x86_avx512_mask3_vfmadd_ss:
2507 case Intrinsic::x86_avx512_mask3_vfmadd_sd:
2508 case Intrinsic::x86_avx512_mask3_vfmsub_ss:
2509 case Intrinsic::x86_avx512_mask3_vfmsub_sd:
2510 case Intrinsic::x86_avx512_mask3_vfnmsub_ss:
2511 case Intrinsic::x86_avx512_mask3_vfnmsub_sd:
Craig Topperdfd268d2016-12-14 05:43:05 +00002512 case Intrinsic::x86_fma_vfmadd_ss:
2513 case Intrinsic::x86_fma_vfmsub_ss:
2514 case Intrinsic::x86_fma_vfnmadd_ss:
2515 case Intrinsic::x86_fma_vfnmsub_ss:
2516 case Intrinsic::x86_fma_vfmadd_sd:
2517 case Intrinsic::x86_fma_vfmsub_sd:
2518 case Intrinsic::x86_fma_vfnmadd_sd:
2519 case Intrinsic::x86_fma_vfnmsub_sd:
Craig Toppera0372de2016-12-14 03:17:27 +00002520 case Intrinsic::x86_sse_cmp_ss:
2521 case Intrinsic::x86_sse_min_ss:
2522 case Intrinsic::x86_sse_max_ss:
2523 case Intrinsic::x86_sse2_cmp_sd:
2524 case Intrinsic::x86_sse2_min_sd:
2525 case Intrinsic::x86_sse2_max_sd:
Craig Toppereb6a20e2016-12-14 03:17:30 +00002526 case Intrinsic::x86_sse41_round_ss:
2527 case Intrinsic::x86_sse41_round_sd:
Craig Topperac75bca2016-12-13 07:45:45 +00002528 case Intrinsic::x86_xop_vfrcz_ss:
2529 case Intrinsic::x86_xop_vfrcz_sd: {
2530 unsigned VWidth = II->getType()->getVectorNumElements();
2531 APInt UndefElts(VWidth, 0);
2532 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
2533 if (Value *V = SimplifyDemandedVectorElts(II, AllOnesEltMask, UndefElts)) {
2534 if (V != II)
2535 return replaceInstUsesWith(*II, V);
2536 return II;
2537 }
2538 break;
2539 }
2540
Simon Pilgrima3a72b42015-08-10 20:21:15 +00002541 // Constant fold ashr( <A x Bi>, Ci ).
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00002542 // Constant fold lshr( <A x Bi>, Ci ).
2543 // Constant fold shl( <A x Bi>, Ci ).
Simon Pilgrima3a72b42015-08-10 20:21:15 +00002544 case Intrinsic::x86_sse2_psrai_d:
2545 case Intrinsic::x86_sse2_psrai_w:
Simon Pilgrima3a72b42015-08-10 20:21:15 +00002546 case Intrinsic::x86_avx2_psrai_d:
2547 case Intrinsic::x86_avx2_psrai_w:
Craig Topper8b831cb2016-11-13 01:51:55 +00002548 case Intrinsic::x86_avx512_psrai_q_128:
2549 case Intrinsic::x86_avx512_psrai_q_256:
2550 case Intrinsic::x86_avx512_psrai_d_512:
2551 case Intrinsic::x86_avx512_psrai_q_512:
2552 case Intrinsic::x86_avx512_psrai_w_512:
Simon Pilgrim18617d12015-08-05 08:18:00 +00002553 case Intrinsic::x86_sse2_psrli_d:
2554 case Intrinsic::x86_sse2_psrli_q:
2555 case Intrinsic::x86_sse2_psrli_w:
Simon Pilgrim18617d12015-08-05 08:18:00 +00002556 case Intrinsic::x86_avx2_psrli_d:
2557 case Intrinsic::x86_avx2_psrli_q:
2558 case Intrinsic::x86_avx2_psrli_w:
Craig Topper8b831cb2016-11-13 01:51:55 +00002559 case Intrinsic::x86_avx512_psrli_d_512:
2560 case Intrinsic::x86_avx512_psrli_q_512:
2561 case Intrinsic::x86_avx512_psrli_w_512:
Michael J. Spencerdee4b2c2014-04-24 00:58:18 +00002562 case Intrinsic::x86_sse2_pslli_d:
2563 case Intrinsic::x86_sse2_pslli_q:
2564 case Intrinsic::x86_sse2_pslli_w:
Simon Pilgrim18617d12015-08-05 08:18:00 +00002565 case Intrinsic::x86_avx2_pslli_d:
2566 case Intrinsic::x86_avx2_pslli_q:
2567 case Intrinsic::x86_avx2_pslli_w:
Craig Topper8b831cb2016-11-13 01:51:55 +00002568 case Intrinsic::x86_avx512_pslli_d_512:
2569 case Intrinsic::x86_avx512_pslli_q_512:
2570 case Intrinsic::x86_avx512_pslli_w_512:
Craig Topperbb4069e2017-07-07 23:16:26 +00002571 if (Value *V = simplifyX86immShift(*II, Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00002572 return replaceInstUsesWith(*II, V);
Simon Pilgrim18617d12015-08-05 08:18:00 +00002573 break;
2574
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00002575 case Intrinsic::x86_sse2_psra_d:
2576 case Intrinsic::x86_sse2_psra_w:
2577 case Intrinsic::x86_avx2_psra_d:
2578 case Intrinsic::x86_avx2_psra_w:
Craig Topper8b831cb2016-11-13 01:51:55 +00002579 case Intrinsic::x86_avx512_psra_q_128:
2580 case Intrinsic::x86_avx512_psra_q_256:
2581 case Intrinsic::x86_avx512_psra_d_512:
2582 case Intrinsic::x86_avx512_psra_q_512:
2583 case Intrinsic::x86_avx512_psra_w_512:
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00002584 case Intrinsic::x86_sse2_psrl_d:
2585 case Intrinsic::x86_sse2_psrl_q:
2586 case Intrinsic::x86_sse2_psrl_w:
2587 case Intrinsic::x86_avx2_psrl_d:
2588 case Intrinsic::x86_avx2_psrl_q:
2589 case Intrinsic::x86_avx2_psrl_w:
Craig Topper8b831cb2016-11-13 01:51:55 +00002590 case Intrinsic::x86_avx512_psrl_d_512:
2591 case Intrinsic::x86_avx512_psrl_q_512:
2592 case Intrinsic::x86_avx512_psrl_w_512:
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00002593 case Intrinsic::x86_sse2_psll_d:
2594 case Intrinsic::x86_sse2_psll_q:
2595 case Intrinsic::x86_sse2_psll_w:
2596 case Intrinsic::x86_avx2_psll_d:
2597 case Intrinsic::x86_avx2_psll_q:
Craig Topper8b831cb2016-11-13 01:51:55 +00002598 case Intrinsic::x86_avx2_psll_w:
2599 case Intrinsic::x86_avx512_psll_d_512:
2600 case Intrinsic::x86_avx512_psll_q_512:
2601 case Intrinsic::x86_avx512_psll_w_512: {
Craig Topperbb4069e2017-07-07 23:16:26 +00002602 if (Value *V = simplifyX86immShift(*II, Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00002603 return replaceInstUsesWith(*II, V);
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00002604
2605 // SSE2/AVX2 uses only the first 64-bits of the 128-bit vector
2606 // operand to compute the shift amount.
Simon Pilgrim996725e2015-09-19 11:41:53 +00002607 Value *Arg1 = II->getArgOperand(1);
2608 assert(Arg1->getType()->getPrimitiveSizeInBits() == 128 &&
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00002609 "Unexpected packed shift size");
Simon Pilgrim996725e2015-09-19 11:41:53 +00002610 unsigned VWidth = Arg1->getType()->getVectorNumElements();
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00002611
Simon Pilgrim996725e2015-09-19 11:41:53 +00002612 if (Value *V = SimplifyDemandedVectorEltsLow(Arg1, VWidth, VWidth / 2)) {
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00002613 II->setArgOperand(1, V);
2614 return II;
2615 }
2616 break;
2617 }
2618
Simon Pilgrimdb9893f2016-06-07 10:27:15 +00002619 case Intrinsic::x86_avx2_psllv_d:
2620 case Intrinsic::x86_avx2_psllv_d_256:
2621 case Intrinsic::x86_avx2_psllv_q:
2622 case Intrinsic::x86_avx2_psllv_q_256:
Craig Topperb4173a52016-11-13 07:26:19 +00002623 case Intrinsic::x86_avx512_psllv_d_512:
2624 case Intrinsic::x86_avx512_psllv_q_512:
Craig Topper1de753f2016-11-18 06:04:33 +00002625 case Intrinsic::x86_avx512_psllv_w_128:
2626 case Intrinsic::x86_avx512_psllv_w_256:
2627 case Intrinsic::x86_avx512_psllv_w_512:
Simon Pilgrimdb9893f2016-06-07 10:27:15 +00002628 case Intrinsic::x86_avx2_psrav_d:
2629 case Intrinsic::x86_avx2_psrav_d_256:
Craig Topperb4173a52016-11-13 07:26:19 +00002630 case Intrinsic::x86_avx512_psrav_q_128:
2631 case Intrinsic::x86_avx512_psrav_q_256:
2632 case Intrinsic::x86_avx512_psrav_d_512:
2633 case Intrinsic::x86_avx512_psrav_q_512:
Craig Topper1de753f2016-11-18 06:04:33 +00002634 case Intrinsic::x86_avx512_psrav_w_128:
2635 case Intrinsic::x86_avx512_psrav_w_256:
2636 case Intrinsic::x86_avx512_psrav_w_512:
Simon Pilgrimdb9893f2016-06-07 10:27:15 +00002637 case Intrinsic::x86_avx2_psrlv_d:
2638 case Intrinsic::x86_avx2_psrlv_d_256:
2639 case Intrinsic::x86_avx2_psrlv_q:
2640 case Intrinsic::x86_avx2_psrlv_q_256:
Craig Topperb4173a52016-11-13 07:26:19 +00002641 case Intrinsic::x86_avx512_psrlv_d_512:
2642 case Intrinsic::x86_avx512_psrlv_q_512:
Craig Topper1de753f2016-11-18 06:04:33 +00002643 case Intrinsic::x86_avx512_psrlv_w_128:
2644 case Intrinsic::x86_avx512_psrlv_w_256:
2645 case Intrinsic::x86_avx512_psrlv_w_512:
Craig Topperbb4069e2017-07-07 23:16:26 +00002646 if (Value *V = simplifyX86varShift(*II, Builder))
Simon Pilgrimdb9893f2016-06-07 10:27:15 +00002647 return replaceInstUsesWith(*II, V);
2648 break;
2649
Simon Pilgrimc9cf7fc2016-12-26 23:28:17 +00002650 case Intrinsic::x86_sse2_pmulu_dq:
2651 case Intrinsic::x86_sse41_pmuldq:
2652 case Intrinsic::x86_avx2_pmul_dq:
Craig Topper72f2d4e2016-12-27 05:30:09 +00002653 case Intrinsic::x86_avx2_pmulu_dq:
2654 case Intrinsic::x86_avx512_pmul_dq_512:
2655 case Intrinsic::x86_avx512_pmulu_dq_512: {
Craig Topperbb4069e2017-07-07 23:16:26 +00002656 if (Value *V = simplifyX86muldq(*II, Builder))
Simon Pilgrima50a93f2017-01-20 18:20:30 +00002657 return replaceInstUsesWith(*II, V);
2658
Simon Pilgrimc9cf7fc2016-12-26 23:28:17 +00002659 unsigned VWidth = II->getType()->getVectorNumElements();
2660 APInt UndefElts(VWidth, 0);
2661 APInt DemandedElts = APInt::getAllOnesValue(VWidth);
2662 if (Value *V = SimplifyDemandedVectorElts(II, DemandedElts, UndefElts)) {
2663 if (V != II)
2664 return replaceInstUsesWith(*II, V);
2665 return II;
2666 }
2667 break;
2668 }
2669
Simon Pilgrim6f6b2792017-01-25 14:37:24 +00002670 case Intrinsic::x86_sse2_packssdw_128:
2671 case Intrinsic::x86_sse2_packsswb_128:
2672 case Intrinsic::x86_avx2_packssdw:
2673 case Intrinsic::x86_avx2_packsswb:
Craig Topper3731f4d2017-02-16 07:35:23 +00002674 case Intrinsic::x86_avx512_packssdw_512:
2675 case Intrinsic::x86_avx512_packsswb_512:
Craig Topper4853c432017-07-06 23:18:42 +00002676 if (Value *V = simplifyX86pack(*II, true))
Simon Pilgrim6f6b2792017-01-25 14:37:24 +00002677 return replaceInstUsesWith(*II, V);
2678 break;
2679
2680 case Intrinsic::x86_sse2_packuswb_128:
2681 case Intrinsic::x86_sse41_packusdw:
2682 case Intrinsic::x86_avx2_packusdw:
2683 case Intrinsic::x86_avx2_packuswb:
Craig Topper3731f4d2017-02-16 07:35:23 +00002684 case Intrinsic::x86_avx512_packusdw_512:
2685 case Intrinsic::x86_avx512_packuswb_512:
Craig Topper4853c432017-07-06 23:18:42 +00002686 if (Value *V = simplifyX86pack(*II, false))
Simon Pilgrim6f6b2792017-01-25 14:37:24 +00002687 return replaceInstUsesWith(*II, V);
2688 break;
2689
Craig Topperb6122122017-01-26 05:17:13 +00002690 case Intrinsic::x86_pclmulqdq: {
2691 if (auto *C = dyn_cast<ConstantInt>(II->getArgOperand(2))) {
2692 unsigned Imm = C->getZExtValue();
2693
2694 bool MadeChange = false;
2695 Value *Arg0 = II->getArgOperand(0);
2696 Value *Arg1 = II->getArgOperand(1);
2697 unsigned VWidth = Arg0->getType()->getVectorNumElements();
2698 APInt DemandedElts(VWidth, 0);
2699
2700 APInt UndefElts1(VWidth, 0);
2701 DemandedElts = (Imm & 0x01) ? 2 : 1;
2702 if (Value *V = SimplifyDemandedVectorElts(Arg0, DemandedElts,
2703 UndefElts1)) {
2704 II->setArgOperand(0, V);
2705 MadeChange = true;
2706 }
2707
2708 APInt UndefElts2(VWidth, 0);
2709 DemandedElts = (Imm & 0x10) ? 2 : 1;
2710 if (Value *V = SimplifyDemandedVectorElts(Arg1, DemandedElts,
2711 UndefElts2)) {
2712 II->setArgOperand(1, V);
2713 MadeChange = true;
2714 }
2715
2716 // If both input elements are undef, the result is undef.
2717 if (UndefElts1[(Imm & 0x01) ? 1 : 0] ||
2718 UndefElts2[(Imm & 0x10) ? 1 : 0])
2719 return replaceInstUsesWith(*II,
2720 ConstantAggregateZero::get(II->getType()));
2721
2722 if (MadeChange)
2723 return II;
2724 }
2725 break;
2726 }
2727
Sanjay Patelc86867c2015-04-16 17:52:13 +00002728 case Intrinsic::x86_sse41_insertps:
Craig Topperbb4069e2017-07-07 23:16:26 +00002729 if (Value *V = simplifyX86insertps(*II, Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00002730 return replaceInstUsesWith(*II, V);
Sanjay Patelc86867c2015-04-16 17:52:13 +00002731 break;
Simon Pilgrim54fcd622015-07-25 20:41:00 +00002732
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002733 case Intrinsic::x86_sse4a_extrq: {
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002734 Value *Op0 = II->getArgOperand(0);
2735 Value *Op1 = II->getArgOperand(1);
2736 unsigned VWidth0 = Op0->getType()->getVectorNumElements();
2737 unsigned VWidth1 = Op1->getType()->getVectorNumElements();
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002738 assert(Op0->getType()->getPrimitiveSizeInBits() == 128 &&
2739 Op1->getType()->getPrimitiveSizeInBits() == 128 && VWidth0 == 2 &&
2740 VWidth1 == 16 && "Unexpected operand sizes");
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002741
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002742 // See if we're dealing with constant values.
2743 Constant *C1 = dyn_cast<Constant>(Op1);
2744 ConstantInt *CILength =
Andrea Di Biagio8df5b9c2016-09-07 12:03:03 +00002745 C1 ? dyn_cast_or_null<ConstantInt>(C1->getAggregateElement((unsigned)0))
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002746 : nullptr;
2747 ConstantInt *CIIndex =
Andrea Di Biagio8df5b9c2016-09-07 12:03:03 +00002748 C1 ? dyn_cast_or_null<ConstantInt>(C1->getAggregateElement((unsigned)1))
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002749 : nullptr;
2750
2751 // Attempt to simplify to a constant, shuffle vector or EXTRQI call.
Craig Topperbb4069e2017-07-07 23:16:26 +00002752 if (Value *V = simplifyX86extrq(*II, Op0, CILength, CIIndex, Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00002753 return replaceInstUsesWith(*II, V);
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002754
2755 // EXTRQ only uses the lowest 64-bits of the first 128-bit vector
2756 // operands and the lowest 16-bits of the second.
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002757 bool MadeChange = false;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002758 if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth0, 1)) {
2759 II->setArgOperand(0, V);
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002760 MadeChange = true;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002761 }
2762 if (Value *V = SimplifyDemandedVectorEltsLow(Op1, VWidth1, 2)) {
2763 II->setArgOperand(1, V);
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002764 MadeChange = true;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002765 }
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002766 if (MadeChange)
2767 return II;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002768 break;
2769 }
2770
2771 case Intrinsic::x86_sse4a_extrqi: {
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002772 // EXTRQI: Extract Length bits starting from Index. Zero pad the remaining
2773 // bits of the lower 64-bits. The upper 64-bits are undefined.
2774 Value *Op0 = II->getArgOperand(0);
2775 unsigned VWidth = Op0->getType()->getVectorNumElements();
2776 assert(Op0->getType()->getPrimitiveSizeInBits() == 128 && VWidth == 2 &&
2777 "Unexpected operand size");
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002778
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002779 // See if we're dealing with constant values.
2780 ConstantInt *CILength = dyn_cast<ConstantInt>(II->getArgOperand(1));
2781 ConstantInt *CIIndex = dyn_cast<ConstantInt>(II->getArgOperand(2));
2782
2783 // Attempt to simplify to a constant or shuffle vector.
Craig Topperbb4069e2017-07-07 23:16:26 +00002784 if (Value *V = simplifyX86extrq(*II, Op0, CILength, CIIndex, Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00002785 return replaceInstUsesWith(*II, V);
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002786
2787 // EXTRQI only uses the lowest 64-bits of the first 128-bit vector
2788 // operand.
2789 if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth, 1)) {
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002790 II->setArgOperand(0, V);
2791 return II;
2792 }
2793 break;
2794 }
2795
2796 case Intrinsic::x86_sse4a_insertq: {
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002797 Value *Op0 = II->getArgOperand(0);
2798 Value *Op1 = II->getArgOperand(1);
2799 unsigned VWidth = Op0->getType()->getVectorNumElements();
2800 assert(Op0->getType()->getPrimitiveSizeInBits() == 128 &&
2801 Op1->getType()->getPrimitiveSizeInBits() == 128 && VWidth == 2 &&
2802 Op1->getType()->getVectorNumElements() == 2 &&
2803 "Unexpected operand size");
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002804
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002805 // See if we're dealing with constant values.
2806 Constant *C1 = dyn_cast<Constant>(Op1);
2807 ConstantInt *CI11 =
Andrea Di Biagiof3fd3162016-09-07 12:47:53 +00002808 C1 ? dyn_cast_or_null<ConstantInt>(C1->getAggregateElement((unsigned)1))
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002809 : nullptr;
2810
2811 // Attempt to simplify to a constant, shuffle vector or INSERTQI call.
2812 if (CI11) {
Benjamin Kramer46e38f32016-06-08 10:01:20 +00002813 const APInt &V11 = CI11->getValue();
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002814 APInt Len = V11.zextOrTrunc(6);
2815 APInt Idx = V11.lshr(8).zextOrTrunc(6);
Craig Topperbb4069e2017-07-07 23:16:26 +00002816 if (Value *V = simplifyX86insertq(*II, Op0, Op1, Len, Idx, Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00002817 return replaceInstUsesWith(*II, V);
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002818 }
2819
2820 // INSERTQ only uses the lowest 64-bits of the first 128-bit vector
2821 // operand.
2822 if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth, 1)) {
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002823 II->setArgOperand(0, V);
2824 return II;
2825 }
2826 break;
2827 }
2828
Filipe Cabecinhas1a805952014-04-24 00:38:14 +00002829 case Intrinsic::x86_sse4a_insertqi: {
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002830 // INSERTQI: Extract lowest Length bits from lower half of second source and
2831 // insert over first source starting at Index bit. The upper 64-bits are
2832 // undefined.
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002833 Value *Op0 = II->getArgOperand(0);
2834 Value *Op1 = II->getArgOperand(1);
2835 unsigned VWidth0 = Op0->getType()->getVectorNumElements();
2836 unsigned VWidth1 = Op1->getType()->getVectorNumElements();
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002837 assert(Op0->getType()->getPrimitiveSizeInBits() == 128 &&
2838 Op1->getType()->getPrimitiveSizeInBits() == 128 && VWidth0 == 2 &&
2839 VWidth1 == 2 && "Unexpected operand sizes");
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002840
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002841 // See if we're dealing with constant values.
2842 ConstantInt *CILength = dyn_cast<ConstantInt>(II->getArgOperand(2));
2843 ConstantInt *CIIndex = dyn_cast<ConstantInt>(II->getArgOperand(3));
2844
2845 // Attempt to simplify to a constant or shuffle vector.
2846 if (CILength && CIIndex) {
2847 APInt Len = CILength->getValue().zextOrTrunc(6);
2848 APInt Idx = CIIndex->getValue().zextOrTrunc(6);
Craig Topperbb4069e2017-07-07 23:16:26 +00002849 if (Value *V = simplifyX86insertq(*II, Op0, Op1, Len, Idx, Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00002850 return replaceInstUsesWith(*II, V);
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002851 }
2852
2853 // INSERTQI only uses the lowest 64-bits of the first two 128-bit vector
2854 // operands.
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002855 bool MadeChange = false;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002856 if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth0, 1)) {
2857 II->setArgOperand(0, V);
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002858 MadeChange = true;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002859 }
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002860 if (Value *V = SimplifyDemandedVectorEltsLow(Op1, VWidth1, 1)) {
2861 II->setArgOperand(1, V);
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002862 MadeChange = true;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002863 }
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002864 if (MadeChange)
2865 return II;
Filipe Cabecinhas1a805952014-04-24 00:38:14 +00002866 break;
2867 }
2868
Filipe Cabecinhas82ac07c2014-05-27 03:42:20 +00002869 case Intrinsic::x86_sse41_pblendvb:
2870 case Intrinsic::x86_sse41_blendvps:
2871 case Intrinsic::x86_sse41_blendvpd:
2872 case Intrinsic::x86_avx_blendv_ps_256:
2873 case Intrinsic::x86_avx_blendv_pd_256:
2874 case Intrinsic::x86_avx2_pblendvb: {
2875 // Convert blendv* to vector selects if the mask is constant.
2876 // This optimization is convoluted because the intrinsic is defined as
2877 // getting a vector of floats or doubles for the ps and pd versions.
2878 // FIXME: That should be changed.
Simon Pilgrim8c049d52015-08-12 08:08:56 +00002879
2880 Value *Op0 = II->getArgOperand(0);
2881 Value *Op1 = II->getArgOperand(1);
Filipe Cabecinhas82ac07c2014-05-27 03:42:20 +00002882 Value *Mask = II->getArgOperand(2);
Simon Pilgrim8c049d52015-08-12 08:08:56 +00002883
2884 // fold (blend A, A, Mask) -> A
2885 if (Op0 == Op1)
Sanjay Patel4b198802016-02-01 22:23:39 +00002886 return replaceInstUsesWith(CI, Op0);
Simon Pilgrim8c049d52015-08-12 08:08:56 +00002887
2888 // Zero Mask - select 1st argument.
Simon Pilgrim93f59f52015-08-12 08:23:36 +00002889 if (isa<ConstantAggregateZero>(Mask))
Sanjay Patel4b198802016-02-01 22:23:39 +00002890 return replaceInstUsesWith(CI, Op0);
Simon Pilgrim8c049d52015-08-12 08:08:56 +00002891
2892 // Constant Mask - select 1st/2nd argument lane based on top bit of mask.
Sanjay Patel368ac5d2016-02-21 17:29:33 +00002893 if (auto *ConstantMask = dyn_cast<ConstantDataVector>(Mask)) {
2894 Constant *NewSelector = getNegativeIsTrueBoolVec(ConstantMask);
Simon Pilgrim8c049d52015-08-12 08:08:56 +00002895 return SelectInst::Create(NewSelector, Op1, Op0, "blendv");
Filipe Cabecinhas82ac07c2014-05-27 03:42:20 +00002896 }
Simon Pilgrim8c049d52015-08-12 08:08:56 +00002897 break;
Filipe Cabecinhas82ac07c2014-05-27 03:42:20 +00002898 }
2899
Andrea Di Biagio0594e2a2015-09-30 16:44:39 +00002900 case Intrinsic::x86_ssse3_pshuf_b_128:
Simon Pilgrimc0c56e72016-04-24 17:00:34 +00002901 case Intrinsic::x86_avx2_pshuf_b:
Simon Pilgrima22c3a12017-01-18 13:44:04 +00002902 case Intrinsic::x86_avx512_pshuf_b_512:
Craig Topperbb4069e2017-07-07 23:16:26 +00002903 if (Value *V = simplifyX86pshufb(*II, Builder))
Simon Pilgrimc0c56e72016-04-24 17:00:34 +00002904 return replaceInstUsesWith(*II, V);
2905 break;
Andrea Di Biagio0594e2a2015-09-30 16:44:39 +00002906
Rafael Espindolabad3f772014-04-21 22:06:04 +00002907 case Intrinsic::x86_avx_vpermilvar_ps:
2908 case Intrinsic::x86_avx_vpermilvar_ps_256:
Craig Topper58917f32016-12-11 01:59:36 +00002909 case Intrinsic::x86_avx512_vpermilvar_ps_512:
Rafael Espindolabad3f772014-04-21 22:06:04 +00002910 case Intrinsic::x86_avx_vpermilvar_pd:
Simon Pilgrim2f6097d2016-04-24 17:23:46 +00002911 case Intrinsic::x86_avx_vpermilvar_pd_256:
Simon Pilgrima22c3a12017-01-18 13:44:04 +00002912 case Intrinsic::x86_avx512_vpermilvar_pd_512:
Craig Topperbb4069e2017-07-07 23:16:26 +00002913 if (Value *V = simplifyX86vpermilvar(*II, Builder))
Simon Pilgrim2f6097d2016-04-24 17:23:46 +00002914 return replaceInstUsesWith(*II, V);
2915 break;
Rafael Espindolabad3f772014-04-21 22:06:04 +00002916
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +00002917 case Intrinsic::x86_avx2_permd:
2918 case Intrinsic::x86_avx2_permps:
Craig Topperbb4069e2017-07-07 23:16:26 +00002919 if (Value *V = simplifyX86vpermv(*II, Builder))
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +00002920 return replaceInstUsesWith(*II, V);
2921 break;
2922
Craig Toppere3280452016-12-25 23:58:57 +00002923 case Intrinsic::x86_avx512_mask_permvar_df_256:
2924 case Intrinsic::x86_avx512_mask_permvar_df_512:
2925 case Intrinsic::x86_avx512_mask_permvar_di_256:
2926 case Intrinsic::x86_avx512_mask_permvar_di_512:
2927 case Intrinsic::x86_avx512_mask_permvar_hi_128:
2928 case Intrinsic::x86_avx512_mask_permvar_hi_256:
2929 case Intrinsic::x86_avx512_mask_permvar_hi_512:
2930 case Intrinsic::x86_avx512_mask_permvar_qi_128:
2931 case Intrinsic::x86_avx512_mask_permvar_qi_256:
2932 case Intrinsic::x86_avx512_mask_permvar_qi_512:
2933 case Intrinsic::x86_avx512_mask_permvar_sf_256:
2934 case Intrinsic::x86_avx512_mask_permvar_sf_512:
2935 case Intrinsic::x86_avx512_mask_permvar_si_256:
2936 case Intrinsic::x86_avx512_mask_permvar_si_512:
Craig Topperbb4069e2017-07-07 23:16:26 +00002937 if (Value *V = simplifyX86vpermv(*II, Builder)) {
Craig Toppere3280452016-12-25 23:58:57 +00002938 // We simplified the permuting, now create a select for the masking.
2939 V = emitX86MaskSelect(II->getArgOperand(3), V, II->getArgOperand(2),
Craig Topperbb4069e2017-07-07 23:16:26 +00002940 Builder);
Craig Toppere3280452016-12-25 23:58:57 +00002941 return replaceInstUsesWith(*II, V);
2942 }
2943 break;
2944
Sanjay Patel98a71502016-02-29 23:16:48 +00002945 case Intrinsic::x86_avx_maskload_ps:
Sanjay Patel6f2c01f2016-02-29 23:59:00 +00002946 case Intrinsic::x86_avx_maskload_pd:
2947 case Intrinsic::x86_avx_maskload_ps_256:
2948 case Intrinsic::x86_avx_maskload_pd_256:
2949 case Intrinsic::x86_avx2_maskload_d:
2950 case Intrinsic::x86_avx2_maskload_q:
2951 case Intrinsic::x86_avx2_maskload_d_256:
2952 case Intrinsic::x86_avx2_maskload_q_256:
Sanjay Patel98a71502016-02-29 23:16:48 +00002953 if (Instruction *I = simplifyX86MaskedLoad(*II, *this))
2954 return I;
2955 break;
2956
Sanjay Patelc4acbae2016-03-12 15:16:59 +00002957 case Intrinsic::x86_sse2_maskmov_dqu:
Sanjay Patel1ace9932016-02-26 21:04:14 +00002958 case Intrinsic::x86_avx_maskstore_ps:
2959 case Intrinsic::x86_avx_maskstore_pd:
2960 case Intrinsic::x86_avx_maskstore_ps_256:
2961 case Intrinsic::x86_avx_maskstore_pd_256:
Sanjay Patelfc7e7eb2016-02-26 21:51:44 +00002962 case Intrinsic::x86_avx2_maskstore_d:
2963 case Intrinsic::x86_avx2_maskstore_q:
2964 case Intrinsic::x86_avx2_maskstore_d_256:
2965 case Intrinsic::x86_avx2_maskstore_q_256:
Sanjay Patel1ace9932016-02-26 21:04:14 +00002966 if (simplifyX86MaskedStore(*II, *this))
2967 return nullptr;
2968 break;
2969
Simon Pilgrim1d1c56e22015-10-11 14:38:34 +00002970 case Intrinsic::x86_xop_vpcomb:
2971 case Intrinsic::x86_xop_vpcomd:
2972 case Intrinsic::x86_xop_vpcomq:
2973 case Intrinsic::x86_xop_vpcomw:
Craig Topperbb4069e2017-07-07 23:16:26 +00002974 if (Value *V = simplifyX86vpcom(*II, Builder, true))
Sanjay Patel4b198802016-02-01 22:23:39 +00002975 return replaceInstUsesWith(*II, V);
Simon Pilgrim1d1c56e22015-10-11 14:38:34 +00002976 break;
2977
2978 case Intrinsic::x86_xop_vpcomub:
2979 case Intrinsic::x86_xop_vpcomud:
2980 case Intrinsic::x86_xop_vpcomuq:
2981 case Intrinsic::x86_xop_vpcomuw:
Craig Topperbb4069e2017-07-07 23:16:26 +00002982 if (Value *V = simplifyX86vpcom(*II, Builder, false))
Sanjay Patel4b198802016-02-01 22:23:39 +00002983 return replaceInstUsesWith(*II, V);
Simon Pilgrim1d1c56e22015-10-11 14:38:34 +00002984 break;
2985
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002986 case Intrinsic::ppc_altivec_vperm:
2987 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
Bill Schmidta1184632014-06-05 19:46:04 +00002988 // Note that ppc_altivec_vperm has a big-endian bias, so when creating
2989 // a vectorshuffle for little endian, we must undo the transformation
2990 // performed on vec_perm in altivec.h. That is, we must complement
2991 // the permutation mask with respect to 31 and reverse the order of
2992 // V1 and V2.
Chris Lattner0256be92012-01-27 03:08:05 +00002993 if (Constant *Mask = dyn_cast<Constant>(II->getArgOperand(2))) {
2994 assert(Mask->getType()->getVectorNumElements() == 16 &&
2995 "Bad type for intrinsic!");
Jim Grosbach7815f562012-02-03 00:07:04 +00002996
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002997 // Check that all of the elements are integer constants or undefs.
2998 bool AllEltsOk = true;
2999 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0256be92012-01-27 03:08:05 +00003000 Constant *Elt = Mask->getAggregateElement(i);
Craig Topperf40110f2014-04-25 05:29:35 +00003001 if (!Elt || !(isa<ConstantInt>(Elt) || isa<UndefValue>(Elt))) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003002 AllEltsOk = false;
3003 break;
3004 }
3005 }
Jim Grosbach7815f562012-02-03 00:07:04 +00003006
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003007 if (AllEltsOk) {
3008 // Cast the input vectors to byte vectors.
Craig Topperbb4069e2017-07-07 23:16:26 +00003009 Value *Op0 = Builder.CreateBitCast(II->getArgOperand(0),
3010 Mask->getType());
3011 Value *Op1 = Builder.CreateBitCast(II->getArgOperand(1),
3012 Mask->getType());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003013 Value *Result = UndefValue::get(Op0->getType());
Jim Grosbach7815f562012-02-03 00:07:04 +00003014
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003015 // Only extract each element once.
3016 Value *ExtractedElts[32];
3017 memset(ExtractedElts, 0, sizeof(ExtractedElts));
Jim Grosbach7815f562012-02-03 00:07:04 +00003018
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003019 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0256be92012-01-27 03:08:05 +00003020 if (isa<UndefValue>(Mask->getAggregateElement(i)))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003021 continue;
Jim Grosbach7815f562012-02-03 00:07:04 +00003022 unsigned Idx =
Chris Lattner0256be92012-01-27 03:08:05 +00003023 cast<ConstantInt>(Mask->getAggregateElement(i))->getZExtValue();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003024 Idx &= 31; // Match the hardware behavior.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003025 if (DL.isLittleEndian())
Bill Schmidta1184632014-06-05 19:46:04 +00003026 Idx = 31 - Idx;
Jim Grosbach7815f562012-02-03 00:07:04 +00003027
Craig Topperf40110f2014-04-25 05:29:35 +00003028 if (!ExtractedElts[Idx]) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003029 Value *Op0ToUse = (DL.isLittleEndian()) ? Op1 : Op0;
3030 Value *Op1ToUse = (DL.isLittleEndian()) ? Op0 : Op1;
Jim Grosbach7815f562012-02-03 00:07:04 +00003031 ExtractedElts[Idx] =
Craig Topperbb4069e2017-07-07 23:16:26 +00003032 Builder.CreateExtractElement(Idx < 16 ? Op0ToUse : Op1ToUse,
3033 Builder.getInt32(Idx&15));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003034 }
Jim Grosbach7815f562012-02-03 00:07:04 +00003035
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003036 // Insert this value into the result vector.
Craig Topperbb4069e2017-07-07 23:16:26 +00003037 Result = Builder.CreateInsertElement(Result, ExtractedElts[Idx],
3038 Builder.getInt32(i));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003039 }
3040 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
3041 }
3042 }
3043 break;
3044
Bob Wilsona4e231c2010-10-22 21:41:48 +00003045 case Intrinsic::arm_neon_vld1:
3046 case Intrinsic::arm_neon_vld2:
3047 case Intrinsic::arm_neon_vld3:
3048 case Intrinsic::arm_neon_vld4:
3049 case Intrinsic::arm_neon_vld2lane:
3050 case Intrinsic::arm_neon_vld3lane:
3051 case Intrinsic::arm_neon_vld4lane:
3052 case Intrinsic::arm_neon_vst1:
3053 case Intrinsic::arm_neon_vst2:
3054 case Intrinsic::arm_neon_vst3:
3055 case Intrinsic::arm_neon_vst4:
3056 case Intrinsic::arm_neon_vst2lane:
3057 case Intrinsic::arm_neon_vst3lane:
3058 case Intrinsic::arm_neon_vst4lane: {
Justin Bogner99798402016-08-05 01:06:44 +00003059 unsigned MemAlign =
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003060 getKnownAlignment(II->getArgOperand(0), DL, II, &AC, &DT);
Bob Wilsona4e231c2010-10-22 21:41:48 +00003061 unsigned AlignArg = II->getNumArgOperands() - 1;
3062 ConstantInt *IntrAlign = dyn_cast<ConstantInt>(II->getArgOperand(AlignArg));
3063 if (IntrAlign && IntrAlign->getZExtValue() < MemAlign) {
3064 II->setArgOperand(AlignArg,
3065 ConstantInt::get(Type::getInt32Ty(II->getContext()),
3066 MemAlign, false));
3067 return II;
3068 }
3069 break;
3070 }
3071
Lang Hames3a90fab2012-05-01 00:20:38 +00003072 case Intrinsic::arm_neon_vmulls:
Tim Northover00ed9962014-03-29 10:18:08 +00003073 case Intrinsic::arm_neon_vmullu:
Tim Northover3b0846e2014-05-24 12:50:23 +00003074 case Intrinsic::aarch64_neon_smull:
3075 case Intrinsic::aarch64_neon_umull: {
Lang Hames3a90fab2012-05-01 00:20:38 +00003076 Value *Arg0 = II->getArgOperand(0);
3077 Value *Arg1 = II->getArgOperand(1);
3078
3079 // Handle mul by zero first:
3080 if (isa<ConstantAggregateZero>(Arg0) || isa<ConstantAggregateZero>(Arg1)) {
Sanjay Patel4b198802016-02-01 22:23:39 +00003081 return replaceInstUsesWith(CI, ConstantAggregateZero::get(II->getType()));
Lang Hames3a90fab2012-05-01 00:20:38 +00003082 }
3083
3084 // Check for constant LHS & RHS - in this case we just simplify.
Tim Northover00ed9962014-03-29 10:18:08 +00003085 bool Zext = (II->getIntrinsicID() == Intrinsic::arm_neon_vmullu ||
Tim Northover3b0846e2014-05-24 12:50:23 +00003086 II->getIntrinsicID() == Intrinsic::aarch64_neon_umull);
Lang Hames3a90fab2012-05-01 00:20:38 +00003087 VectorType *NewVT = cast<VectorType>(II->getType());
Benjamin Kramer92040952014-02-13 18:23:24 +00003088 if (Constant *CV0 = dyn_cast<Constant>(Arg0)) {
3089 if (Constant *CV1 = dyn_cast<Constant>(Arg1)) {
3090 CV0 = ConstantExpr::getIntegerCast(CV0, NewVT, /*isSigned=*/!Zext);
3091 CV1 = ConstantExpr::getIntegerCast(CV1, NewVT, /*isSigned=*/!Zext);
3092
Sanjay Patel4b198802016-02-01 22:23:39 +00003093 return replaceInstUsesWith(CI, ConstantExpr::getMul(CV0, CV1));
Lang Hames3a90fab2012-05-01 00:20:38 +00003094 }
3095
Alp Tokercb402912014-01-24 17:20:08 +00003096 // Couldn't simplify - canonicalize constant to the RHS.
Lang Hames3a90fab2012-05-01 00:20:38 +00003097 std::swap(Arg0, Arg1);
3098 }
3099
3100 // Handle mul by one:
Benjamin Kramer92040952014-02-13 18:23:24 +00003101 if (Constant *CV1 = dyn_cast<Constant>(Arg1))
Lang Hames3a90fab2012-05-01 00:20:38 +00003102 if (ConstantInt *Splat =
Benjamin Kramer92040952014-02-13 18:23:24 +00003103 dyn_cast_or_null<ConstantInt>(CV1->getSplatValue()))
3104 if (Splat->isOne())
3105 return CastInst::CreateIntegerCast(Arg0, II->getType(),
3106 /*isSigned=*/!Zext);
Lang Hames3a90fab2012-05-01 00:20:38 +00003107
3108 break;
3109 }
Matt Arsenaultbef34e22016-01-22 21:30:34 +00003110 case Intrinsic::amdgcn_rcp: {
Matt Arsenault4c7795d2017-03-24 19:04:57 +00003111 Value *Src = II->getArgOperand(0);
3112
3113 // TODO: Move to ConstantFolding/InstSimplify?
3114 if (isa<UndefValue>(Src))
3115 return replaceInstUsesWith(CI, Src);
3116
3117 if (const ConstantFP *C = dyn_cast<ConstantFP>(Src)) {
Matt Arsenaulta0050b02014-06-19 01:19:19 +00003118 const APFloat &ArgVal = C->getValueAPF();
3119 APFloat Val(ArgVal.getSemantics(), 1.0);
3120 APFloat::opStatus Status = Val.divide(ArgVal,
3121 APFloat::rmNearestTiesToEven);
3122 // Only do this if it was exact and therefore not dependent on the
3123 // rounding mode.
3124 if (Status == APFloat::opOK)
Sanjay Patel4b198802016-02-01 22:23:39 +00003125 return replaceInstUsesWith(CI, ConstantFP::get(II->getContext(), Val));
Matt Arsenaulta0050b02014-06-19 01:19:19 +00003126 }
3127
3128 break;
3129 }
Matt Arsenault4c7795d2017-03-24 19:04:57 +00003130 case Intrinsic::amdgcn_rsq: {
3131 Value *Src = II->getArgOperand(0);
3132
3133 // TODO: Move to ConstantFolding/InstSimplify?
3134 if (isa<UndefValue>(Src))
3135 return replaceInstUsesWith(CI, Src);
3136 break;
3137 }
Matt Arsenault2fe4fbc2016-03-30 22:28:52 +00003138 case Intrinsic::amdgcn_frexp_mant:
3139 case Intrinsic::amdgcn_frexp_exp: {
Matt Arsenault5cd4f8f2016-03-30 22:28:26 +00003140 Value *Src = II->getArgOperand(0);
3141 if (const ConstantFP *C = dyn_cast<ConstantFP>(Src)) {
3142 int Exp;
3143 APFloat Significand = frexp(C->getValueAPF(), Exp,
3144 APFloat::rmNearestTiesToEven);
3145
Matt Arsenault2fe4fbc2016-03-30 22:28:52 +00003146 if (II->getIntrinsicID() == Intrinsic::amdgcn_frexp_mant) {
3147 return replaceInstUsesWith(CI, ConstantFP::get(II->getContext(),
3148 Significand));
3149 }
3150
3151 // Match instruction special case behavior.
3152 if (Exp == APFloat::IEK_NaN || Exp == APFloat::IEK_Inf)
3153 Exp = 0;
3154
3155 return replaceInstUsesWith(CI, ConstantInt::get(II->getType(), Exp));
3156 }
3157
3158 if (isa<UndefValue>(Src))
3159 return replaceInstUsesWith(CI, UndefValue::get(II->getType()));
Matt Arsenault5cd4f8f2016-03-30 22:28:26 +00003160
3161 break;
3162 }
Matt Arsenault46a03822016-09-03 07:06:58 +00003163 case Intrinsic::amdgcn_class: {
3164 enum {
3165 S_NAN = 1 << 0, // Signaling NaN
3166 Q_NAN = 1 << 1, // Quiet NaN
3167 N_INFINITY = 1 << 2, // Negative infinity
3168 N_NORMAL = 1 << 3, // Negative normal
3169 N_SUBNORMAL = 1 << 4, // Negative subnormal
3170 N_ZERO = 1 << 5, // Negative zero
3171 P_ZERO = 1 << 6, // Positive zero
3172 P_SUBNORMAL = 1 << 7, // Positive subnormal
3173 P_NORMAL = 1 << 8, // Positive normal
3174 P_INFINITY = 1 << 9 // Positive infinity
3175 };
3176
3177 const uint32_t FullMask = S_NAN | Q_NAN | N_INFINITY | N_NORMAL |
3178 N_SUBNORMAL | N_ZERO | P_ZERO | P_SUBNORMAL | P_NORMAL | P_INFINITY;
3179
3180 Value *Src0 = II->getArgOperand(0);
3181 Value *Src1 = II->getArgOperand(1);
3182 const ConstantInt *CMask = dyn_cast<ConstantInt>(Src1);
3183 if (!CMask) {
3184 if (isa<UndefValue>(Src0))
3185 return replaceInstUsesWith(*II, UndefValue::get(II->getType()));
3186
3187 if (isa<UndefValue>(Src1))
3188 return replaceInstUsesWith(*II, ConstantInt::get(II->getType(), false));
3189 break;
3190 }
3191
3192 uint32_t Mask = CMask->getZExtValue();
3193
3194 // If all tests are made, it doesn't matter what the value is.
3195 if ((Mask & FullMask) == FullMask)
3196 return replaceInstUsesWith(*II, ConstantInt::get(II->getType(), true));
3197
3198 if ((Mask & FullMask) == 0)
3199 return replaceInstUsesWith(*II, ConstantInt::get(II->getType(), false));
3200
3201 if (Mask == (S_NAN | Q_NAN)) {
3202 // Equivalent of isnan. Replace with standard fcmp.
Craig Topperbb4069e2017-07-07 23:16:26 +00003203 Value *FCmp = Builder.CreateFCmpUNO(Src0, Src0);
Matt Arsenault46a03822016-09-03 07:06:58 +00003204 FCmp->takeName(II);
3205 return replaceInstUsesWith(*II, FCmp);
3206 }
3207
3208 const ConstantFP *CVal = dyn_cast<ConstantFP>(Src0);
3209 if (!CVal) {
3210 if (isa<UndefValue>(Src0))
3211 return replaceInstUsesWith(*II, UndefValue::get(II->getType()));
3212
3213 // Clamp mask to used bits
3214 if ((Mask & FullMask) != Mask) {
Craig Topperbb4069e2017-07-07 23:16:26 +00003215 CallInst *NewCall = Builder.CreateCall(II->getCalledFunction(),
Matt Arsenault46a03822016-09-03 07:06:58 +00003216 { Src0, ConstantInt::get(Src1->getType(), Mask & FullMask) }
3217 );
3218
3219 NewCall->takeName(II);
3220 return replaceInstUsesWith(*II, NewCall);
3221 }
3222
3223 break;
3224 }
3225
3226 const APFloat &Val = CVal->getValueAPF();
3227
3228 bool Result =
3229 ((Mask & S_NAN) && Val.isNaN() && Val.isSignaling()) ||
3230 ((Mask & Q_NAN) && Val.isNaN() && !Val.isSignaling()) ||
3231 ((Mask & N_INFINITY) && Val.isInfinity() && Val.isNegative()) ||
3232 ((Mask & N_NORMAL) && Val.isNormal() && Val.isNegative()) ||
3233 ((Mask & N_SUBNORMAL) && Val.isDenormal() && Val.isNegative()) ||
3234 ((Mask & N_ZERO) && Val.isZero() && Val.isNegative()) ||
3235 ((Mask & P_ZERO) && Val.isZero() && !Val.isNegative()) ||
3236 ((Mask & P_SUBNORMAL) && Val.isDenormal() && !Val.isNegative()) ||
3237 ((Mask & P_NORMAL) && Val.isNormal() && !Val.isNegative()) ||
3238 ((Mask & P_INFINITY) && Val.isInfinity() && !Val.isNegative());
3239
3240 return replaceInstUsesWith(*II, ConstantInt::get(II->getType(), Result));
3241 }
Matt Arsenault1f17c662017-02-22 00:27:34 +00003242 case Intrinsic::amdgcn_cvt_pkrtz: {
3243 Value *Src0 = II->getArgOperand(0);
3244 Value *Src1 = II->getArgOperand(1);
3245 if (const ConstantFP *C0 = dyn_cast<ConstantFP>(Src0)) {
3246 if (const ConstantFP *C1 = dyn_cast<ConstantFP>(Src1)) {
3247 const fltSemantics &HalfSem
3248 = II->getType()->getScalarType()->getFltSemantics();
3249 bool LosesInfo;
3250 APFloat Val0 = C0->getValueAPF();
3251 APFloat Val1 = C1->getValueAPF();
3252 Val0.convert(HalfSem, APFloat::rmTowardZero, &LosesInfo);
3253 Val1.convert(HalfSem, APFloat::rmTowardZero, &LosesInfo);
3254
3255 Constant *Folded = ConstantVector::get({
3256 ConstantFP::get(II->getContext(), Val0),
3257 ConstantFP::get(II->getContext(), Val1) });
3258 return replaceInstUsesWith(*II, Folded);
3259 }
3260 }
3261
3262 if (isa<UndefValue>(Src0) && isa<UndefValue>(Src1))
3263 return replaceInstUsesWith(*II, UndefValue::get(II->getType()));
3264
3265 break;
3266 }
Matt Arsenaultf5262252017-02-22 23:04:58 +00003267 case Intrinsic::amdgcn_ubfe:
3268 case Intrinsic::amdgcn_sbfe: {
3269 // Decompose simple cases into standard shifts.
3270 Value *Src = II->getArgOperand(0);
3271 if (isa<UndefValue>(Src))
3272 return replaceInstUsesWith(*II, Src);
3273
3274 unsigned Width;
3275 Type *Ty = II->getType();
3276 unsigned IntSize = Ty->getIntegerBitWidth();
3277
3278 ConstantInt *CWidth = dyn_cast<ConstantInt>(II->getArgOperand(2));
3279 if (CWidth) {
3280 Width = CWidth->getZExtValue();
3281 if ((Width & (IntSize - 1)) == 0)
3282 return replaceInstUsesWith(*II, ConstantInt::getNullValue(Ty));
3283
3284 if (Width >= IntSize) {
3285 // Hardware ignores high bits, so remove those.
3286 II->setArgOperand(2, ConstantInt::get(CWidth->getType(),
3287 Width & (IntSize - 1)));
3288 return II;
3289 }
3290 }
3291
3292 unsigned Offset;
3293 ConstantInt *COffset = dyn_cast<ConstantInt>(II->getArgOperand(1));
3294 if (COffset) {
3295 Offset = COffset->getZExtValue();
3296 if (Offset >= IntSize) {
3297 II->setArgOperand(1, ConstantInt::get(COffset->getType(),
3298 Offset & (IntSize - 1)));
3299 return II;
3300 }
3301 }
3302
3303 bool Signed = II->getIntrinsicID() == Intrinsic::amdgcn_sbfe;
3304
3305 // TODO: Also emit sub if only width is constant.
3306 if (!CWidth && COffset && Offset == 0) {
3307 Constant *KSize = ConstantInt::get(COffset->getType(), IntSize);
Craig Topperbb4069e2017-07-07 23:16:26 +00003308 Value *ShiftVal = Builder.CreateSub(KSize, II->getArgOperand(2));
3309 ShiftVal = Builder.CreateZExt(ShiftVal, II->getType());
Matt Arsenaultf5262252017-02-22 23:04:58 +00003310
Craig Topperbb4069e2017-07-07 23:16:26 +00003311 Value *Shl = Builder.CreateShl(Src, ShiftVal);
3312 Value *RightShift = Signed ? Builder.CreateAShr(Shl, ShiftVal)
3313 : Builder.CreateLShr(Shl, ShiftVal);
Matt Arsenaultf5262252017-02-22 23:04:58 +00003314 RightShift->takeName(II);
3315 return replaceInstUsesWith(*II, RightShift);
3316 }
3317
3318 if (!CWidth || !COffset)
3319 break;
3320
3321 // TODO: This allows folding to undef when the hardware has specific
3322 // behavior?
3323 if (Offset + Width < IntSize) {
Craig Topperbb4069e2017-07-07 23:16:26 +00003324 Value *Shl = Builder.CreateShl(Src, IntSize - Offset - Width);
3325 Value *RightShift = Signed ? Builder.CreateAShr(Shl, IntSize - Width)
3326 : Builder.CreateLShr(Shl, IntSize - Width);
Matt Arsenaultf5262252017-02-22 23:04:58 +00003327 RightShift->takeName(II);
3328 return replaceInstUsesWith(*II, RightShift);
3329 }
3330
Craig Topperbb4069e2017-07-07 23:16:26 +00003331 Value *RightShift = Signed ? Builder.CreateAShr(Src, Offset)
3332 : Builder.CreateLShr(Src, Offset);
Matt Arsenaultf5262252017-02-22 23:04:58 +00003333
3334 RightShift->takeName(II);
3335 return replaceInstUsesWith(*II, RightShift);
3336 }
Matt Arsenaultd4bca1e2017-02-23 00:44:03 +00003337 case Intrinsic::amdgcn_exp:
3338 case Intrinsic::amdgcn_exp_compr: {
3339 ConstantInt *En = dyn_cast<ConstantInt>(II->getArgOperand(1));
3340 if (!En) // Illegal.
3341 break;
3342
3343 unsigned EnBits = En->getZExtValue();
3344 if (EnBits == 0xf)
3345 break; // All inputs enabled.
3346
3347 bool IsCompr = II->getIntrinsicID() == Intrinsic::amdgcn_exp_compr;
3348 bool Changed = false;
3349 for (int I = 0; I < (IsCompr ? 2 : 4); ++I) {
3350 if ((!IsCompr && (EnBits & (1 << I)) == 0) ||
3351 (IsCompr && ((EnBits & (0x3 << (2 * I))) == 0))) {
3352 Value *Src = II->getArgOperand(I + 2);
3353 if (!isa<UndefValue>(Src)) {
3354 II->setArgOperand(I + 2, UndefValue::get(Src->getType()));
3355 Changed = true;
3356 }
3357 }
3358 }
3359
3360 if (Changed)
3361 return II;
3362
3363 break;
Matt Arsenaultcdb468c2017-02-27 23:08:49 +00003364 }
3365 case Intrinsic::amdgcn_fmed3: {
3366 // Note this does not preserve proper sNaN behavior if IEEE-mode is enabled
3367 // for the shader.
3368
3369 Value *Src0 = II->getArgOperand(0);
3370 Value *Src1 = II->getArgOperand(1);
3371 Value *Src2 = II->getArgOperand(2);
3372
3373 bool Swap = false;
3374 // Canonicalize constants to RHS operands.
3375 //
3376 // fmed3(c0, x, c1) -> fmed3(x, c0, c1)
3377 if (isa<Constant>(Src0) && !isa<Constant>(Src1)) {
3378 std::swap(Src0, Src1);
3379 Swap = true;
3380 }
3381
3382 if (isa<Constant>(Src1) && !isa<Constant>(Src2)) {
3383 std::swap(Src1, Src2);
3384 Swap = true;
3385 }
3386
3387 if (isa<Constant>(Src0) && !isa<Constant>(Src1)) {
3388 std::swap(Src0, Src1);
3389 Swap = true;
3390 }
3391
3392 if (Swap) {
3393 II->setArgOperand(0, Src0);
3394 II->setArgOperand(1, Src1);
3395 II->setArgOperand(2, Src2);
3396 return II;
3397 }
3398
3399 if (match(Src2, m_NaN()) || isa<UndefValue>(Src2)) {
Craig Topperbb4069e2017-07-07 23:16:26 +00003400 CallInst *NewCall = Builder.CreateMinNum(Src0, Src1);
Matt Arsenaultcdb468c2017-02-27 23:08:49 +00003401 NewCall->copyFastMathFlags(II);
3402 NewCall->takeName(II);
3403 return replaceInstUsesWith(*II, NewCall);
3404 }
3405
3406 if (const ConstantFP *C0 = dyn_cast<ConstantFP>(Src0)) {
3407 if (const ConstantFP *C1 = dyn_cast<ConstantFP>(Src1)) {
3408 if (const ConstantFP *C2 = dyn_cast<ConstantFP>(Src2)) {
3409 APFloat Result = fmed3AMDGCN(C0->getValueAPF(), C1->getValueAPF(),
3410 C2->getValueAPF());
3411 return replaceInstUsesWith(*II,
Craig Topperbb4069e2017-07-07 23:16:26 +00003412 ConstantFP::get(Builder.getContext(), Result));
Matt Arsenaultcdb468c2017-02-27 23:08:49 +00003413 }
3414 }
3415 }
3416
3417 break;
Matt Arsenaultd4bca1e2017-02-23 00:44:03 +00003418 }
Matt Arsenaultd81f5572017-03-13 18:14:02 +00003419 case Intrinsic::amdgcn_icmp:
3420 case Intrinsic::amdgcn_fcmp: {
3421 const ConstantInt *CC = dyn_cast<ConstantInt>(II->getArgOperand(2));
3422 if (!CC)
3423 break;
3424
3425 // Guard against invalid arguments.
3426 int64_t CCVal = CC->getZExtValue();
3427 bool IsInteger = II->getIntrinsicID() == Intrinsic::amdgcn_icmp;
3428 if ((IsInteger && (CCVal < CmpInst::FIRST_ICMP_PREDICATE ||
3429 CCVal > CmpInst::LAST_ICMP_PREDICATE)) ||
3430 (!IsInteger && (CCVal < CmpInst::FIRST_FCMP_PREDICATE ||
3431 CCVal > CmpInst::LAST_FCMP_PREDICATE)))
3432 break;
3433
3434 Value *Src0 = II->getArgOperand(0);
3435 Value *Src1 = II->getArgOperand(1);
3436
3437 if (auto *CSrc0 = dyn_cast<Constant>(Src0)) {
3438 if (auto *CSrc1 = dyn_cast<Constant>(Src1)) {
3439 Constant *CCmp = ConstantExpr::getCompare(CCVal, CSrc0, CSrc1);
Nicolai Haehnle9c661852017-04-24 17:08:43 +00003440 if (CCmp->isNullValue()) {
3441 return replaceInstUsesWith(
3442 *II, ConstantExpr::getSExt(CCmp, II->getType()));
3443 }
3444
3445 // The result of V_ICMP/V_FCMP assembly instructions (which this
3446 // intrinsic exposes) is one bit per thread, masked with the EXEC
3447 // register (which contains the bitmask of live threads). So a
3448 // comparison that always returns true is the same as a read of the
3449 // EXEC register.
3450 Value *NewF = Intrinsic::getDeclaration(
3451 II->getModule(), Intrinsic::read_register, II->getType());
3452 Metadata *MDArgs[] = {MDString::get(II->getContext(), "exec")};
3453 MDNode *MD = MDNode::get(II->getContext(), MDArgs);
3454 Value *Args[] = {MetadataAsValue::get(II->getContext(), MD)};
Craig Topperbb4069e2017-07-07 23:16:26 +00003455 CallInst *NewCall = Builder.CreateCall(NewF, Args);
Nicolai Haehnle9c661852017-04-24 17:08:43 +00003456 NewCall->addAttribute(AttributeList::FunctionIndex,
3457 Attribute::Convergent);
3458 NewCall->takeName(II);
3459 return replaceInstUsesWith(*II, NewCall);
Matt Arsenaultd81f5572017-03-13 18:14:02 +00003460 }
3461
3462 // Canonicalize constants to RHS.
3463 CmpInst::Predicate SwapPred
3464 = CmpInst::getSwappedPredicate(static_cast<CmpInst::Predicate>(CCVal));
3465 II->setArgOperand(0, Src1);
3466 II->setArgOperand(1, Src0);
3467 II->setArgOperand(2, ConstantInt::get(CC->getType(),
3468 static_cast<int>(SwapPred)));
3469 return II;
3470 }
3471
3472 if (CCVal != CmpInst::ICMP_EQ && CCVal != CmpInst::ICMP_NE)
3473 break;
3474
3475 // Canonicalize compare eq with true value to compare != 0
3476 // llvm.amdgcn.icmp(zext (i1 x), 1, eq)
3477 // -> llvm.amdgcn.icmp(zext (i1 x), 0, ne)
3478 // llvm.amdgcn.icmp(sext (i1 x), -1, eq)
3479 // -> llvm.amdgcn.icmp(sext (i1 x), 0, ne)
3480 Value *ExtSrc;
3481 if (CCVal == CmpInst::ICMP_EQ &&
3482 ((match(Src1, m_One()) && match(Src0, m_ZExt(m_Value(ExtSrc)))) ||
3483 (match(Src1, m_AllOnes()) && match(Src0, m_SExt(m_Value(ExtSrc))))) &&
3484 ExtSrc->getType()->isIntegerTy(1)) {
3485 II->setArgOperand(1, ConstantInt::getNullValue(Src1->getType()));
3486 II->setArgOperand(2, ConstantInt::get(CC->getType(), CmpInst::ICMP_NE));
3487 return II;
3488 }
3489
3490 CmpInst::Predicate SrcPred;
3491 Value *SrcLHS;
3492 Value *SrcRHS;
3493
3494 // Fold compare eq/ne with 0 from a compare result as the predicate to the
3495 // intrinsic. The typical use is a wave vote function in the library, which
3496 // will be fed from a user code condition compared with 0. Fold in the
3497 // redundant compare.
3498
3499 // llvm.amdgcn.icmp([sz]ext ([if]cmp pred a, b), 0, ne)
3500 // -> llvm.amdgcn.[if]cmp(a, b, pred)
3501 //
3502 // llvm.amdgcn.icmp([sz]ext ([if]cmp pred a, b), 0, eq)
3503 // -> llvm.amdgcn.[if]cmp(a, b, inv pred)
3504 if (match(Src1, m_Zero()) &&
3505 match(Src0,
3506 m_ZExtOrSExt(m_Cmp(SrcPred, m_Value(SrcLHS), m_Value(SrcRHS))))) {
3507 if (CCVal == CmpInst::ICMP_EQ)
3508 SrcPred = CmpInst::getInversePredicate(SrcPred);
3509
3510 Intrinsic::ID NewIID = CmpInst::isFPPredicate(SrcPred) ?
3511 Intrinsic::amdgcn_fcmp : Intrinsic::amdgcn_icmp;
3512
3513 Value *NewF = Intrinsic::getDeclaration(II->getModule(), NewIID,
3514 SrcLHS->getType());
3515 Value *Args[] = { SrcLHS, SrcRHS,
3516 ConstantInt::get(CC->getType(), SrcPred) };
Craig Topperbb4069e2017-07-07 23:16:26 +00003517 CallInst *NewCall = Builder.CreateCall(NewF, Args);
Matt Arsenaultd81f5572017-03-13 18:14:02 +00003518 NewCall->takeName(II);
3519 return replaceInstUsesWith(*II, NewCall);
3520 }
3521
3522 break;
3523 }
Marek Olsak2114fc32017-10-24 10:26:59 +00003524 case Intrinsic::amdgcn_wqm_vote: {
3525 // wqm_vote is identity when the argument is constant.
3526 if (!isa<Constant>(II->getArgOperand(0)))
3527 break;
3528
3529 return replaceInstUsesWith(*II, II->getArgOperand(0));
3530 }
Marek Olsakce76ea02017-10-24 10:27:13 +00003531 case Intrinsic::amdgcn_kill: {
3532 const ConstantInt *C = dyn_cast<ConstantInt>(II->getArgOperand(0));
3533 if (!C || !C->getZExtValue())
3534 break;
3535
3536 // amdgcn.kill(i1 1) is a no-op
3537 return eraseInstFromFunction(CI);
3538 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003539 case Intrinsic::stackrestore: {
3540 // If the save is right next to the restore, remove the restore. This can
3541 // happen when variable allocas are DCE'd.
Gabor Greif589a0b92010-06-24 12:58:35 +00003542 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getArgOperand(0))) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003543 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00003544 if (&*++SS->getIterator() == II)
Sanjay Patel4b198802016-02-01 22:23:39 +00003545 return eraseInstFromFunction(CI);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003546 }
3547 }
Jim Grosbach7815f562012-02-03 00:07:04 +00003548
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003549 // Scan down this block to see if there is another stack restore in the
3550 // same block without an intervening call/alloca.
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00003551 BasicBlock::iterator BI(II);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003552 TerminatorInst *TI = II->getParent()->getTerminator();
3553 bool CannotRemove = false;
3554 for (++BI; &*BI != TI; ++BI) {
Nuno Lopes55fff832012-06-21 15:45:28 +00003555 if (isa<AllocaInst>(BI)) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003556 CannotRemove = true;
3557 break;
3558 }
3559 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
3560 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
3561 // If there is a stackrestore below this one, remove this one.
3562 if (II->getIntrinsicID() == Intrinsic::stackrestore)
Sanjay Patel4b198802016-02-01 22:23:39 +00003563 return eraseInstFromFunction(CI);
Reid Kleckner892ae2e2016-02-27 00:53:54 +00003564
3565 // Bail if we cross over an intrinsic with side effects, such as
3566 // llvm.stacksave, llvm.read_register, or llvm.setjmp.
3567 if (II->mayHaveSideEffects()) {
3568 CannotRemove = true;
3569 break;
3570 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003571 } else {
3572 // If we found a non-intrinsic call, we can't remove the stack
3573 // restore.
3574 CannotRemove = true;
3575 break;
3576 }
3577 }
3578 }
Jim Grosbach7815f562012-02-03 00:07:04 +00003579
Bill Wendlingf891bf82011-07-31 06:30:59 +00003580 // If the stack restore is in a return, resume, or unwind block and if there
3581 // are no allocas or calls between the restore and the return, nuke the
3582 // restore.
Bill Wendlingd5d95b02012-02-06 21:16:41 +00003583 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<ResumeInst>(TI)))
Sanjay Patel4b198802016-02-01 22:23:39 +00003584 return eraseInstFromFunction(CI);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003585 break;
3586 }
Vitaly Bukaf0500b62016-07-28 22:50:48 +00003587 case Intrinsic::lifetime_start:
Vitaly Buka0ab23cf2016-07-28 22:59:03 +00003588 // Asan needs to poison memory to detect invalid access which is possible
3589 // even for empty lifetime range.
Evgeniy Stepanovc667c1f2017-12-09 00:21:41 +00003590 if (II->getFunction()->hasFnAttribute(Attribute::SanitizeAddress) ||
3591 II->getFunction()->hasFnAttribute(Attribute::SanitizeHWAddress))
Vitaly Buka0ab23cf2016-07-28 22:59:03 +00003592 break;
3593
Arnaud A. de Grandmaison333ef382016-05-10 09:24:49 +00003594 if (removeTriviallyEmptyRange(*II, Intrinsic::lifetime_start,
3595 Intrinsic::lifetime_end, *this))
3596 return nullptr;
Arnaud A. de Grandmaison849f3bf2015-10-01 14:54:31 +00003597 break;
Hal Finkelf5867a72014-07-25 21:45:17 +00003598 case Intrinsic::assume: {
David Majnemerfcc58112016-04-08 16:37:12 +00003599 Value *IIOperand = II->getArgOperand(0);
3600 // Remove an assume if it is immediately followed by an identical assume.
3601 if (match(II->getNextNode(),
3602 m_Intrinsic<Intrinsic::assume>(m_Specific(IIOperand))))
3603 return eraseInstFromFunction(CI);
3604
Hal Finkelf5867a72014-07-25 21:45:17 +00003605 // Canonicalize assume(a && b) -> assume(a); assume(b);
Hal Finkel74c2f352014-09-07 12:44:26 +00003606 // Note: New assumption intrinsics created here are registered by
3607 // the InstCombineIRInserter object.
David Majnemerfcc58112016-04-08 16:37:12 +00003608 Value *AssumeIntrinsic = II->getCalledValue(), *A, *B;
Hal Finkelf5867a72014-07-25 21:45:17 +00003609 if (match(IIOperand, m_And(m_Value(A), m_Value(B)))) {
Craig Topperbb4069e2017-07-07 23:16:26 +00003610 Builder.CreateCall(AssumeIntrinsic, A, II->getName());
3611 Builder.CreateCall(AssumeIntrinsic, B, II->getName());
Sanjay Patel4b198802016-02-01 22:23:39 +00003612 return eraseInstFromFunction(*II);
Hal Finkelf5867a72014-07-25 21:45:17 +00003613 }
3614 // assume(!(a || b)) -> assume(!a); assume(!b);
3615 if (match(IIOperand, m_Not(m_Or(m_Value(A), m_Value(B))))) {
Craig Topperbb4069e2017-07-07 23:16:26 +00003616 Builder.CreateCall(AssumeIntrinsic, Builder.CreateNot(A), II->getName());
3617 Builder.CreateCall(AssumeIntrinsic, Builder.CreateNot(B), II->getName());
Sanjay Patel4b198802016-02-01 22:23:39 +00003618 return eraseInstFromFunction(*II);
Hal Finkelf5867a72014-07-25 21:45:17 +00003619 }
Hal Finkel04a15612014-10-04 21:27:06 +00003620
Philip Reames66c6de62014-11-11 23:33:19 +00003621 // assume( (load addr) != null ) -> add 'nonnull' metadata to load
3622 // (if assume is valid at the load)
Sanjay Patelf0d1e7732017-01-03 22:25:31 +00003623 CmpInst::Predicate Pred;
3624 Instruction *LHS;
3625 if (match(IIOperand, m_ICmp(Pred, m_Instruction(LHS), m_Zero())) &&
3626 Pred == ICmpInst::ICMP_NE && LHS->getOpcode() == Instruction::Load &&
3627 LHS->getType()->isPointerTy() &&
3628 isValidAssumeForContext(II, LHS, &DT)) {
3629 MDNode *MD = MDNode::get(II->getContext(), None);
3630 LHS->setMetadata(LLVMContext::MD_nonnull, MD);
3631 return eraseInstFromFunction(*II);
3632
Chandler Carruth24969102015-02-10 08:07:32 +00003633 // TODO: apply nonnull return attributes to calls and invokes
Philip Reames66c6de62014-11-11 23:33:19 +00003634 // TODO: apply range metadata for range check patterns?
3635 }
Sanjay Patelf0d1e7732017-01-03 22:25:31 +00003636
Hal Finkel04a15612014-10-04 21:27:06 +00003637 // If there is a dominating assume with the same condition as this one,
3638 // then this one is redundant, and should be removed.
Craig Topperb45eabc2017-04-26 16:39:58 +00003639 KnownBits Known(1);
3640 computeKnownBits(IIOperand, Known, 0, II);
Craig Topperf0aeee02017-05-05 17:36:09 +00003641 if (Known.isAllOnes())
Sanjay Patel4b198802016-02-01 22:23:39 +00003642 return eraseInstFromFunction(*II);
Hal Finkel04a15612014-10-04 21:27:06 +00003643
Hal Finkel8a9a7832017-01-11 13:24:24 +00003644 // Update the cache of affected values for this assumption (we might be
3645 // here because we just simplified the condition).
3646 AC.updateAffectedValues(II);
Hal Finkelf5867a72014-07-25 21:45:17 +00003647 break;
3648 }
Philip Reames9db26ff2014-12-29 23:27:30 +00003649 case Intrinsic::experimental_gc_relocate: {
3650 // Translate facts known about a pointer before relocating into
3651 // facts about the relocate value, while being careful to
3652 // preserve relocation semantics.
Manuel Jacob83eefa62016-01-05 04:03:00 +00003653 Value *DerivedPtr = cast<GCRelocateInst>(II)->getDerivedPtr();
Philip Reames9db26ff2014-12-29 23:27:30 +00003654
3655 // Remove the relocation if unused, note that this check is required
3656 // to prevent the cases below from looping forever.
3657 if (II->use_empty())
Sanjay Patel4b198802016-02-01 22:23:39 +00003658 return eraseInstFromFunction(*II);
Philip Reames9db26ff2014-12-29 23:27:30 +00003659
3660 // Undef is undef, even after relocation.
3661 // TODO: provide a hook for this in GCStrategy. This is clearly legal for
3662 // most practical collectors, but there was discussion in the review thread
3663 // about whether it was legal for all possible collectors.
Philip Reamesea4d8e82016-02-09 21:09:22 +00003664 if (isa<UndefValue>(DerivedPtr))
3665 // Use undef of gc_relocate's type to replace it.
3666 return replaceInstUsesWith(*II, UndefValue::get(II->getType()));
Philip Reames9db26ff2014-12-29 23:27:30 +00003667
Philip Reamesea4d8e82016-02-09 21:09:22 +00003668 if (auto *PT = dyn_cast<PointerType>(II->getType())) {
3669 // The relocation of null will be null for most any collector.
3670 // TODO: provide a hook for this in GCStrategy. There might be some
3671 // weird collector this property does not hold for.
3672 if (isa<ConstantPointerNull>(DerivedPtr))
3673 // Use null-pointer of gc_relocate's type to replace it.
3674 return replaceInstUsesWith(*II, ConstantPointerNull::get(PT));
Simon Pilgrimc0c56e72016-04-24 17:00:34 +00003675
Philip Reamesea4d8e82016-02-09 21:09:22 +00003676 // isKnownNonNull -> nonnull attribute
Nuno Lopes404f1062017-09-09 18:23:11 +00003677 if (isKnownNonZero(DerivedPtr, DL, 0, &AC, II, &DT))
Reid Klecknerb5180542017-03-21 16:57:19 +00003678 II->addAttribute(AttributeList::ReturnIndex, Attribute::NonNull);
Ramkumar Ramachandra8fcb4982015-02-14 19:37:54 +00003679 }
Philip Reames9db26ff2014-12-29 23:27:30 +00003680
3681 // TODO: bitcast(relocate(p)) -> relocate(bitcast(p))
3682 // Canonicalize on the type from the uses to the defs
Ramkumar Ramachandra8fcb4982015-02-14 19:37:54 +00003683
Philip Reames9db26ff2014-12-29 23:27:30 +00003684 // TODO: relocate((gep p, C, C2, ...)) -> gep(relocate(p), C, C2, ...)
Philip Reamesea4d8e82016-02-09 21:09:22 +00003685 break;
Philip Reames9db26ff2014-12-29 23:27:30 +00003686 }
Artur Pilipenkoe812ca02017-01-25 14:12:12 +00003687
3688 case Intrinsic::experimental_guard: {
Sanjoy Dase0e57952017-02-01 16:34:55 +00003689 // Is this guard followed by another guard?
3690 Instruction *NextInst = II->getNextNode();
3691 Value *NextCond = nullptr;
3692 if (match(NextInst,
3693 m_Intrinsic<Intrinsic::experimental_guard>(m_Value(NextCond)))) {
3694 Value *CurrCond = II->getArgOperand(0);
Artur Pilipenkoe812ca02017-01-25 14:12:12 +00003695
Simon Pilgrim68168d12017-03-30 12:59:53 +00003696 // Remove a guard that it is immediately preceded by an identical guard.
Sanjoy Dase0e57952017-02-01 16:34:55 +00003697 if (CurrCond == NextCond)
3698 return eraseInstFromFunction(*NextInst);
3699
3700 // Otherwise canonicalize guard(a); guard(b) -> guard(a & b).
Craig Topperbb4069e2017-07-07 23:16:26 +00003701 II->setArgOperand(0, Builder.CreateAnd(CurrCond, NextCond));
Sanjoy Dase0e57952017-02-01 16:34:55 +00003702 return eraseInstFromFunction(*NextInst);
3703 }
Artur Pilipenkoe812ca02017-01-25 14:12:12 +00003704 break;
3705 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003706 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003707 return visitCallSite(II);
3708}
3709
Davide Italianoaec46172017-01-31 18:09:05 +00003710// Fence instruction simplification
3711Instruction *InstCombiner::visitFenceInst(FenceInst &FI) {
3712 // Remove identical consecutive fences.
3713 if (auto *NFI = dyn_cast<FenceInst>(FI.getNextNode()))
3714 if (FI.isIdenticalTo(NFI))
3715 return eraseInstFromFunction(FI);
3716 return nullptr;
3717}
3718
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003719// InvokeInst simplification
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003720Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
3721 return visitCallSite(&II);
3722}
3723
Sanjay Patelcd4377c2016-01-20 22:24:38 +00003724/// If this cast does not affect the value passed through the varargs area, we
3725/// can eliminate the use of the cast.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003726static bool isSafeToEliminateVarargsCast(const CallSite CS,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003727 const DataLayout &DL,
3728 const CastInst *const CI,
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003729 const int ix) {
3730 if (!CI->isLosslessCast())
3731 return false;
3732
Philip Reames1a1bdb22014-12-02 18:50:36 +00003733 // If this is a GC intrinsic, avoid munging types. We need types for
3734 // statepoint reconstruction in SelectionDAG.
3735 // TODO: This is probably something which should be expanded to all
3736 // intrinsics since the entire point of intrinsics is that
3737 // they are understandable by the optimizer.
3738 if (isStatepoint(CS) || isGCRelocate(CS) || isGCResult(CS))
3739 return false;
3740
Reid Kleckner26af2ca2014-01-28 02:38:36 +00003741 // The size of ByVal or InAlloca arguments is derived from the type, so we
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003742 // can't change to a type with a different size. If the size were
3743 // passed explicitly we could avoid this check.
Reid Kleckner26af2ca2014-01-28 02:38:36 +00003744 if (!CS.isByValOrInAllocaArgument(ix))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003745 return true;
3746
Jim Grosbach7815f562012-02-03 00:07:04 +00003747 Type* SrcTy =
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003748 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
Chris Lattner229907c2011-07-18 04:54:35 +00003749 Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003750 if (!SrcTy->isSized() || !DstTy->isSized())
3751 return false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003752 if (DL.getTypeAllocSize(SrcTy) != DL.getTypeAllocSize(DstTy))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003753 return false;
3754 return true;
3755}
3756
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003757Instruction *InstCombiner::tryOptimizeCall(CallInst *CI) {
Craig Topperf40110f2014-04-25 05:29:35 +00003758 if (!CI->getCalledFunction()) return nullptr;
Eric Christophera7fb58f2010-03-06 10:50:38 +00003759
Chandler Carruthba4c5172015-01-21 11:23:40 +00003760 auto InstCombineRAUW = [this](Instruction *From, Value *With) {
Sanjay Patel4b198802016-02-01 22:23:39 +00003761 replaceInstUsesWith(*From, With);
Chandler Carruthba4c5172015-01-21 11:23:40 +00003762 };
Adam Nemetea06e6e2017-07-26 19:03:18 +00003763 LibCallSimplifier Simplifier(DL, &TLI, ORE, InstCombineRAUW);
Chandler Carruthba4c5172015-01-21 11:23:40 +00003764 if (Value *With = Simplifier.optimizeCall(CI)) {
Meador Ingee3f2b262012-11-30 04:05:06 +00003765 ++NumSimplified;
Sanjay Patel4b198802016-02-01 22:23:39 +00003766 return CI->use_empty() ? CI : replaceInstUsesWith(*CI, With);
Meador Ingee3f2b262012-11-30 04:05:06 +00003767 }
Meador Ingedf796f82012-10-13 16:45:24 +00003768
Craig Topperf40110f2014-04-25 05:29:35 +00003769 return nullptr;
Eric Christophera7fb58f2010-03-06 10:50:38 +00003770}
3771
Sanjay Patel6038d3e2016-01-29 23:27:03 +00003772static IntrinsicInst *findInitTrampolineFromAlloca(Value *TrampMem) {
Duncan Sandsa0984362011-09-06 13:37:06 +00003773 // Strip off at most one level of pointer casts, looking for an alloca. This
3774 // is good enough in practice and simpler than handling any number of casts.
3775 Value *Underlying = TrampMem->stripPointerCasts();
3776 if (Underlying != TrampMem &&
Chandler Carruthcdf47882014-03-09 03:16:01 +00003777 (!Underlying->hasOneUse() || Underlying->user_back() != TrampMem))
Craig Topperf40110f2014-04-25 05:29:35 +00003778 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00003779 if (!isa<AllocaInst>(Underlying))
Craig Topperf40110f2014-04-25 05:29:35 +00003780 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00003781
Craig Topperf40110f2014-04-25 05:29:35 +00003782 IntrinsicInst *InitTrampoline = nullptr;
Chandler Carruthcdf47882014-03-09 03:16:01 +00003783 for (User *U : TrampMem->users()) {
3784 IntrinsicInst *II = dyn_cast<IntrinsicInst>(U);
Duncan Sandsa0984362011-09-06 13:37:06 +00003785 if (!II)
Craig Topperf40110f2014-04-25 05:29:35 +00003786 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00003787 if (II->getIntrinsicID() == Intrinsic::init_trampoline) {
3788 if (InitTrampoline)
3789 // More than one init_trampoline writes to this value. Give up.
Craig Topperf40110f2014-04-25 05:29:35 +00003790 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00003791 InitTrampoline = II;
3792 continue;
3793 }
3794 if (II->getIntrinsicID() == Intrinsic::adjust_trampoline)
3795 // Allow any number of calls to adjust.trampoline.
3796 continue;
Craig Topperf40110f2014-04-25 05:29:35 +00003797 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00003798 }
3799
3800 // No call to init.trampoline found.
3801 if (!InitTrampoline)
Craig Topperf40110f2014-04-25 05:29:35 +00003802 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00003803
3804 // Check that the alloca is being used in the expected way.
3805 if (InitTrampoline->getOperand(0) != TrampMem)
Craig Topperf40110f2014-04-25 05:29:35 +00003806 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00003807
3808 return InitTrampoline;
3809}
3810
Sanjay Patel6038d3e2016-01-29 23:27:03 +00003811static IntrinsicInst *findInitTrampolineFromBB(IntrinsicInst *AdjustTramp,
Duncan Sandsa0984362011-09-06 13:37:06 +00003812 Value *TrampMem) {
3813 // Visit all the previous instructions in the basic block, and try to find a
3814 // init.trampoline which has a direct path to the adjust.trampoline.
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00003815 for (BasicBlock::iterator I = AdjustTramp->getIterator(),
3816 E = AdjustTramp->getParent()->begin();
3817 I != E;) {
3818 Instruction *Inst = &*--I;
Duncan Sandsa0984362011-09-06 13:37:06 +00003819 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
3820 if (II->getIntrinsicID() == Intrinsic::init_trampoline &&
3821 II->getOperand(0) == TrampMem)
3822 return II;
3823 if (Inst->mayWriteToMemory())
Craig Topperf40110f2014-04-25 05:29:35 +00003824 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00003825 }
Craig Topperf40110f2014-04-25 05:29:35 +00003826 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00003827}
3828
3829// Given a call to llvm.adjust.trampoline, find and return the corresponding
3830// call to llvm.init.trampoline if the call to the trampoline can be optimized
3831// to a direct call to a function. Otherwise return NULL.
Sanjay Patel6038d3e2016-01-29 23:27:03 +00003832static IntrinsicInst *findInitTrampoline(Value *Callee) {
Duncan Sandsa0984362011-09-06 13:37:06 +00003833 Callee = Callee->stripPointerCasts();
3834 IntrinsicInst *AdjustTramp = dyn_cast<IntrinsicInst>(Callee);
3835 if (!AdjustTramp ||
3836 AdjustTramp->getIntrinsicID() != Intrinsic::adjust_trampoline)
Craig Topperf40110f2014-04-25 05:29:35 +00003837 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00003838
3839 Value *TrampMem = AdjustTramp->getOperand(0);
3840
Sanjay Patel6038d3e2016-01-29 23:27:03 +00003841 if (IntrinsicInst *IT = findInitTrampolineFromAlloca(TrampMem))
Duncan Sandsa0984362011-09-06 13:37:06 +00003842 return IT;
Sanjay Patel6038d3e2016-01-29 23:27:03 +00003843 if (IntrinsicInst *IT = findInitTrampolineFromBB(AdjustTramp, TrampMem))
Duncan Sandsa0984362011-09-06 13:37:06 +00003844 return IT;
Craig Topperf40110f2014-04-25 05:29:35 +00003845 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00003846}
3847
Sanjay Patelcd4377c2016-01-20 22:24:38 +00003848/// Improvements for call and invoke instructions.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003849Instruction *InstCombiner::visitCallSite(CallSite CS) {
Justin Bogner99798402016-08-05 01:06:44 +00003850 if (isAllocLikeFn(CS.getInstruction(), &TLI))
Nuno Lopes95cc4f32012-07-09 18:38:20 +00003851 return visitAllocSite(*CS.getInstruction());
Nuno Lopesdc6085e2012-06-21 21:25:05 +00003852
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003853 bool Changed = false;
3854
Philip Reamesc25df112015-06-16 20:24:25 +00003855 // Mark any parameters that are known to be non-null with the nonnull
3856 // attribute. This is helpful for inlining calls to functions with null
3857 // checks on their arguments.
Reid Kleckner5fbdd172017-05-31 19:23:09 +00003858 SmallVector<unsigned, 4> ArgNos;
Philip Reamesc25df112015-06-16 20:24:25 +00003859 unsigned ArgNo = 0;
Akira Hatanaka237916b2015-12-02 06:58:49 +00003860
Philip Reamesc25df112015-06-16 20:24:25 +00003861 for (Value *V : CS.args()) {
Sanjay Patelf9f5d3c2016-01-29 23:14:58 +00003862 if (V->getType()->isPointerTy() &&
Reid Klecknerfb502d22017-04-14 20:19:02 +00003863 !CS.paramHasAttr(ArgNo, Attribute::NonNull) &&
Nuno Lopes404f1062017-09-09 18:23:11 +00003864 isKnownNonZero(V, DL, 0, &AC, CS.getInstruction(), &DT))
Reid Kleckner5fbdd172017-05-31 19:23:09 +00003865 ArgNos.push_back(ArgNo);
Philip Reamesc25df112015-06-16 20:24:25 +00003866 ArgNo++;
3867 }
Akira Hatanaka237916b2015-12-02 06:58:49 +00003868
Philip Reamesc25df112015-06-16 20:24:25 +00003869 assert(ArgNo == CS.arg_size() && "sanity check");
3870
Reid Kleckner5fbdd172017-05-31 19:23:09 +00003871 if (!ArgNos.empty()) {
Reid Klecknerb5180542017-03-21 16:57:19 +00003872 AttributeList AS = CS.getAttributes();
Akira Hatanaka237916b2015-12-02 06:58:49 +00003873 LLVMContext &Ctx = CS.getInstruction()->getContext();
Reid Kleckner5fbdd172017-05-31 19:23:09 +00003874 AS = AS.addParamAttribute(Ctx, ArgNos,
3875 Attribute::get(Ctx, Attribute::NonNull));
Akira Hatanaka237916b2015-12-02 06:58:49 +00003876 CS.setAttributes(AS);
3877 Changed = true;
3878 }
3879
Chris Lattner73989652010-12-20 08:25:06 +00003880 // If the callee is a pointer to a function, attempt to move any casts to the
3881 // arguments of the call/invoke.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003882 Value *Callee = CS.getCalledValue();
Chris Lattner73989652010-12-20 08:25:06 +00003883 if (!isa<Function>(Callee) && transformConstExprCastCall(CS))
Craig Topperf40110f2014-04-25 05:29:35 +00003884 return nullptr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003885
Justin Lebar9d943972016-03-14 20:18:54 +00003886 if (Function *CalleeF = dyn_cast<Function>(Callee)) {
3887 // Remove the convergent attr on calls when the callee is not convergent.
Matt Arsenault802ebcb2016-06-20 19:04:44 +00003888 if (CS.isConvergent() && !CalleeF->isConvergent() &&
3889 !CalleeF->isIntrinsic()) {
Justin Lebar9d943972016-03-14 20:18:54 +00003890 DEBUG(dbgs() << "Removing convergent attr from instr "
3891 << CS.getInstruction() << "\n");
3892 CS.setNotConvergent();
3893 return CS.getInstruction();
3894 }
3895
Chris Lattner846a52e2010-02-01 18:11:34 +00003896 // If the call and callee calling conventions don't match, this call must
3897 // be unreachable, as the call is undefined.
3898 if (CalleeF->getCallingConv() != CS.getCallingConv() &&
3899 // Only do this for calls to a function with a body. A prototype may
3900 // not actually end up matching the implementation's calling conv for a
3901 // variety of reasons (e.g. it may be written in assembly).
3902 !CalleeF->isDeclaration()) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003903 Instruction *OldCall = CS.getInstruction();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003904 new StoreInst(ConstantInt::getTrue(Callee->getContext()),
Jim Grosbach7815f562012-02-03 00:07:04 +00003905 UndefValue::get(Type::getInt1PtrTy(Callee->getContext())),
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003906 OldCall);
Chad Rosiere28ae302012-12-13 00:18:46 +00003907 // If OldCall does not return void then replaceAllUsesWith undef.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003908 // This allows ValueHandlers and custom metadata to adjust itself.
3909 if (!OldCall->getType()->isVoidTy())
Sanjay Patel4b198802016-02-01 22:23:39 +00003910 replaceInstUsesWith(*OldCall, UndefValue::get(OldCall->getType()));
Chris Lattner2cecedf2010-02-01 18:04:58 +00003911 if (isa<CallInst>(OldCall))
Sanjay Patel4b198802016-02-01 22:23:39 +00003912 return eraseInstFromFunction(*OldCall);
Jim Grosbach7815f562012-02-03 00:07:04 +00003913
Chris Lattner2cecedf2010-02-01 18:04:58 +00003914 // We cannot remove an invoke, because it would change the CFG, just
3915 // change the callee to a null pointer.
Gabor Greiffebf6ab2010-03-20 21:00:25 +00003916 cast<InvokeInst>(OldCall)->setCalledFunction(
Chris Lattner2cecedf2010-02-01 18:04:58 +00003917 Constant::getNullValue(CalleeF->getType()));
Craig Topperf40110f2014-04-25 05:29:35 +00003918 return nullptr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003919 }
Justin Lebar9d943972016-03-14 20:18:54 +00003920 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003921
3922 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
Gabor Greif589a0b92010-06-24 12:58:35 +00003923 // If CS does not return void then replaceAllUsesWith undef.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003924 // This allows ValueHandlers and custom metadata to adjust itself.
3925 if (!CS.getInstruction()->getType()->isVoidTy())
Sanjay Patel4b198802016-02-01 22:23:39 +00003926 replaceInstUsesWith(*CS.getInstruction(),
Eli Friedmanb9ed18f2011-05-18 00:32:01 +00003927 UndefValue::get(CS.getInstruction()->getType()));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003928
Nuno Lopes771e7bd2012-06-21 23:52:14 +00003929 if (isa<InvokeInst>(CS.getInstruction())) {
3930 // Can't remove an invoke because we cannot change the CFG.
Craig Topperf40110f2014-04-25 05:29:35 +00003931 return nullptr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003932 }
Nuno Lopes771e7bd2012-06-21 23:52:14 +00003933
3934 // This instruction is not reachable, just remove it. We insert a store to
3935 // undef so that we know that this code is not reachable, despite the fact
3936 // that we can't modify the CFG here.
3937 new StoreInst(ConstantInt::getTrue(Callee->getContext()),
3938 UndefValue::get(Type::getInt1PtrTy(Callee->getContext())),
3939 CS.getInstruction());
3940
Sanjay Patel4b198802016-02-01 22:23:39 +00003941 return eraseInstFromFunction(*CS.getInstruction());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003942 }
3943
Sanjay Patel6038d3e2016-01-29 23:27:03 +00003944 if (IntrinsicInst *II = findInitTrampoline(Callee))
Duncan Sandsa0984362011-09-06 13:37:06 +00003945 return transformCallThroughTrampoline(CS, II);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003946
Chris Lattner229907c2011-07-18 04:54:35 +00003947 PointerType *PTy = cast<PointerType>(Callee->getType());
3948 FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003949 if (FTy->isVarArg()) {
Eli Friedman7534b4682011-11-29 01:18:23 +00003950 int ix = FTy->getNumParams();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003951 // See if we can optimize any arguments passed through the varargs area of
3952 // the call.
Matt Arsenault5d2e85f2013-06-28 00:25:40 +00003953 for (CallSite::arg_iterator I = CS.arg_begin() + FTy->getNumParams(),
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003954 E = CS.arg_end(); I != E; ++I, ++ix) {
3955 CastInst *CI = dyn_cast<CastInst>(*I);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003956 if (CI && isSafeToEliminateVarargsCast(CS, DL, CI, ix)) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003957 *I = CI->getOperand(0);
3958 Changed = true;
3959 }
3960 }
3961 }
3962
3963 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
3964 // Inline asm calls cannot throw - mark them 'nounwind'.
3965 CS.setDoesNotThrow();
3966 Changed = true;
3967 }
3968
Micah Villmowcdfe20b2012-10-08 16:38:25 +00003969 // Try to optimize the call if possible, we require DataLayout for most of
Eric Christophera7fb58f2010-03-06 10:50:38 +00003970 // this. None of these calls are seen as possibly dead so go ahead and
3971 // delete the instruction now.
3972 if (CallInst *CI = dyn_cast<CallInst>(CS.getInstruction())) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003973 Instruction *I = tryOptimizeCall(CI);
Eric Christopher1810d772010-03-06 10:59:25 +00003974 // If we changed something return the result, etc. Otherwise let
3975 // the fallthrough check.
Sanjay Patel4b198802016-02-01 22:23:39 +00003976 if (I) return eraseInstFromFunction(*I);
Eric Christophera7fb58f2010-03-06 10:50:38 +00003977 }
3978
Craig Topperf40110f2014-04-25 05:29:35 +00003979 return Changed ? CS.getInstruction() : nullptr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003980}
3981
Sanjay Patelcd4377c2016-01-20 22:24:38 +00003982/// If the callee is a constexpr cast of a function, attempt to move the cast to
3983/// the arguments of the call/invoke.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003984bool InstCombiner::transformConstExprCastCall(CallSite CS) {
Sanjay Patele3c335c2016-08-11 15:21:21 +00003985 auto *Callee = dyn_cast<Function>(CS.getCalledValue()->stripPointerCasts());
Craig Topperf40110f2014-04-25 05:29:35 +00003986 if (!Callee)
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003987 return false;
Sanjay Patel38ae83d2016-08-11 15:23:56 +00003988
3989 // The prototype of a thunk is a lie. Don't directly call such a function.
David Majnemer4c0a6e92015-01-21 22:32:04 +00003990 if (Callee->hasFnAttribute("thunk"))
3991 return false;
Sanjay Patel38ae83d2016-08-11 15:23:56 +00003992
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003993 Instruction *Caller = CS.getInstruction();
Reid Klecknerb5180542017-03-21 16:57:19 +00003994 const AttributeList &CallerPAL = CS.getAttributes();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003995
3996 // Okay, this is a cast from a function to a different type. Unless doing so
3997 // would cause a type conversion of one of our arguments, change this call to
3998 // be a direct call with arguments casted to the appropriate types.
Chris Lattner229907c2011-07-18 04:54:35 +00003999 FunctionType *FT = Callee->getFunctionType();
4000 Type *OldRetTy = Caller->getType();
4001 Type *NewRetTy = FT->getReturnType();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004002
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004003 // Check to see if we are changing the return type...
4004 if (OldRetTy != NewRetTy) {
Nick Lewyckya6a17d72014-01-18 22:47:12 +00004005
4006 if (NewRetTy->isStructTy())
4007 return false; // TODO: Handle multiple return values.
4008
David Majnemer9b6b8222015-01-06 08:41:31 +00004009 if (!CastInst::isBitOrNoopPointerCastable(NewRetTy, OldRetTy, DL)) {
Matt Arsenaulte6952f22013-09-17 21:10:14 +00004010 if (Callee->isDeclaration())
4011 return false; // Cannot transform this return value.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004012
Matt Arsenaulte6952f22013-09-17 21:10:14 +00004013 if (!Caller->use_empty() &&
4014 // void -> non-void is handled specially
4015 !NewRetTy->isVoidTy())
Frederic Rissc1892e22014-10-23 04:08:42 +00004016 return false; // Cannot transform this return value.
Matt Arsenaulte6952f22013-09-17 21:10:14 +00004017 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004018
4019 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Reid Klecknerb5180542017-03-21 16:57:19 +00004020 AttrBuilder RAttrs(CallerPAL, AttributeList::ReturnIndex);
Pete Cooper2777d8872015-05-06 23:19:56 +00004021 if (RAttrs.overlaps(AttributeFuncs::typeIncompatible(NewRetTy)))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004022 return false; // Attribute not compatible with transformed value.
4023 }
4024
4025 // If the callsite is an invoke instruction, and the return value is used by
4026 // a PHI node in a successor, we cannot change the return type of the call
4027 // because there is no place to put the cast instruction (without breaking
4028 // the critical edge). Bail out in this case.
4029 if (!Caller->use_empty())
4030 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
Chandler Carruthcdf47882014-03-09 03:16:01 +00004031 for (User *U : II->users())
4032 if (PHINode *PN = dyn_cast<PHINode>(U))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004033 if (PN->getParent() == II->getNormalDest() ||
4034 PN->getParent() == II->getUnwindDest())
4035 return false;
4036 }
4037
Matt Arsenault5d2e85f2013-06-28 00:25:40 +00004038 unsigned NumActualArgs = CS.arg_size();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004039 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
4040
David Majnemer9b6b8222015-01-06 08:41:31 +00004041 // Prevent us turning:
4042 // declare void @takes_i32_inalloca(i32* inalloca)
4043 // call void bitcast (void (i32*)* @takes_i32_inalloca to void (i32)*)(i32 0)
4044 //
4045 // into:
4046 // call void @takes_i32_inalloca(i32* null)
David Majnemerd61a6fd2015-03-11 18:03:05 +00004047 //
4048 // Similarly, avoid folding away bitcasts of byval calls.
4049 if (Callee->getAttributes().hasAttrSomewhere(Attribute::InAlloca) ||
4050 Callee->getAttributes().hasAttrSomewhere(Attribute::ByVal))
David Majnemer9b6b8222015-01-06 08:41:31 +00004051 return false;
4052
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004053 CallSite::arg_iterator AI = CS.arg_begin();
4054 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
Chris Lattner229907c2011-07-18 04:54:35 +00004055 Type *ParamTy = FT->getParamType(i);
4056 Type *ActTy = (*AI)->getType();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004057
David Majnemer9b6b8222015-01-06 08:41:31 +00004058 if (!CastInst::isBitOrNoopPointerCastable(ActTy, ParamTy, DL))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004059 return false; // Cannot transform this parameter value.
4060
Reid Klecknerf021fab2017-04-13 23:12:13 +00004061 if (AttrBuilder(CallerPAL.getParamAttributes(i))
4062 .overlaps(AttributeFuncs::typeIncompatible(ParamTy)))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004063 return false; // Attribute not compatible with transformed value.
Jim Grosbach7815f562012-02-03 00:07:04 +00004064
Reid Kleckner26af2ca2014-01-28 02:38:36 +00004065 if (CS.isInAllocaArgument(i))
4066 return false; // Cannot transform to and from inalloca.
4067
Chris Lattner27ca8eb2010-12-20 08:36:38 +00004068 // If the parameter is passed as a byval argument, then we have to have a
4069 // sized type and the sized type has to have the same size as the old type.
Reid Klecknerf021fab2017-04-13 23:12:13 +00004070 if (ParamTy != ActTy && CallerPAL.hasParamAttribute(i, Attribute::ByVal)) {
Chris Lattner229907c2011-07-18 04:54:35 +00004071 PointerType *ParamPTy = dyn_cast<PointerType>(ParamTy);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004072 if (!ParamPTy || !ParamPTy->getElementType()->isSized())
Chris Lattner27ca8eb2010-12-20 08:36:38 +00004073 return false;
Jim Grosbach7815f562012-02-03 00:07:04 +00004074
Matt Arsenaultfa252722013-09-27 22:18:51 +00004075 Type *CurElTy = ActTy->getPointerElementType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004076 if (DL.getTypeAllocSize(CurElTy) !=
4077 DL.getTypeAllocSize(ParamPTy->getElementType()))
Chris Lattner27ca8eb2010-12-20 08:36:38 +00004078 return false;
4079 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004080 }
4081
Chris Lattneradf38b32011-02-24 05:10:56 +00004082 if (Callee->isDeclaration()) {
4083 // Do not delete arguments unless we have a function body.
4084 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg())
4085 return false;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004086
Chris Lattneradf38b32011-02-24 05:10:56 +00004087 // If the callee is just a declaration, don't change the varargsness of the
4088 // call. We don't want to introduce a varargs call where one doesn't
4089 // already exist.
Chris Lattner229907c2011-07-18 04:54:35 +00004090 PointerType *APTy = cast<PointerType>(CS.getCalledValue()->getType());
Chris Lattneradf38b32011-02-24 05:10:56 +00004091 if (FT->isVarArg()!=cast<FunctionType>(APTy->getElementType())->isVarArg())
4092 return false;
Jim Grosbache84ae7b2012-02-03 00:00:55 +00004093
4094 // If both the callee and the cast type are varargs, we still have to make
4095 // sure the number of fixed parameters are the same or we have the same
4096 // ABI issues as if we introduce a varargs call.
Jim Grosbach1df8cdc2012-02-03 00:26:07 +00004097 if (FT->isVarArg() &&
4098 cast<FunctionType>(APTy->getElementType())->isVarArg() &&
4099 FT->getNumParams() !=
Jim Grosbache84ae7b2012-02-03 00:00:55 +00004100 cast<FunctionType>(APTy->getElementType())->getNumParams())
4101 return false;
Chris Lattneradf38b32011-02-24 05:10:56 +00004102 }
Jim Grosbach7815f562012-02-03 00:07:04 +00004103
Jim Grosbach0ab54182012-02-03 00:00:50 +00004104 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
Reid Kleckneraa0cec72017-04-19 23:17:47 +00004105 !CallerPAL.isEmpty()) {
Jim Grosbach0ab54182012-02-03 00:00:50 +00004106 // In this case we have more arguments than the new function type, but we
4107 // won't be dropping them. Check that these extra arguments have attributes
4108 // that are compatible with being a vararg call argument.
Reid Kleckneraa0cec72017-04-19 23:17:47 +00004109 unsigned SRetIdx;
4110 if (CallerPAL.hasAttrSomewhere(Attribute::StructRet, &SRetIdx) &&
4111 SRetIdx > FT->getNumParams())
4112 return false;
4113 }
Jim Grosbach7815f562012-02-03 00:07:04 +00004114
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004115 // Okay, we decided that this is a safe thing to do: go ahead and start
Chris Lattneradf38b32011-02-24 05:10:56 +00004116 // inserting cast instructions as necessary.
Reid Klecknerc3fae792017-04-13 18:11:03 +00004117 SmallVector<Value *, 8> Args;
4118 SmallVector<AttributeSet, 8> ArgAttrs;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004119 Args.reserve(NumActualArgs);
Reid Klecknerc3fae792017-04-13 18:11:03 +00004120 ArgAttrs.reserve(NumActualArgs);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004121
4122 // Get any return attributes.
Reid Klecknerb5180542017-03-21 16:57:19 +00004123 AttrBuilder RAttrs(CallerPAL, AttributeList::ReturnIndex);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004124
4125 // If the return value is not being used, the type may not be compatible
4126 // with the existing attributes. Wipe out any problematic attributes.
Pete Cooper2777d8872015-05-06 23:19:56 +00004127 RAttrs.remove(AttributeFuncs::typeIncompatible(NewRetTy));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004128
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004129 AI = CS.arg_begin();
4130 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
Chris Lattner229907c2011-07-18 04:54:35 +00004131 Type *ParamTy = FT->getParamType(i);
Matt Arsenaultcacbb232013-07-30 20:45:05 +00004132
Reid Klecknerc3fae792017-04-13 18:11:03 +00004133 Value *NewArg = *AI;
4134 if ((*AI)->getType() != ParamTy)
Craig Topperbb4069e2017-07-07 23:16:26 +00004135 NewArg = Builder.CreateBitOrPointerCast(*AI, ParamTy);
Reid Klecknerc3fae792017-04-13 18:11:03 +00004136 Args.push_back(NewArg);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004137
4138 // Add any parameter attributes.
Reid Klecknerf021fab2017-04-13 23:12:13 +00004139 ArgAttrs.push_back(CallerPAL.getParamAttributes(i));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004140 }
4141
4142 // If the function takes more arguments than the call was taking, add them
4143 // now.
Reid Klecknerc3fae792017-04-13 18:11:03 +00004144 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004145 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
Reid Klecknerc3fae792017-04-13 18:11:03 +00004146 ArgAttrs.push_back(AttributeSet());
4147 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004148
4149 // If we are removing arguments to the function, emit an obnoxious warning.
4150 if (FT->getNumParams() < NumActualArgs) {
Nick Lewycky90053a12012-12-26 22:00:35 +00004151 // TODO: if (!FT->isVarArg()) this call may be unreachable. PR14722
4152 if (FT->isVarArg()) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004153 // Add all of the arguments in their promoted form to the arg list.
4154 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
Chris Lattner229907c2011-07-18 04:54:35 +00004155 Type *PTy = getPromotedType((*AI)->getType());
Reid Klecknerc3fae792017-04-13 18:11:03 +00004156 Value *NewArg = *AI;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004157 if (PTy != (*AI)->getType()) {
4158 // Must promote to pass through va_arg area!
4159 Instruction::CastOps opcode =
4160 CastInst::getCastOpcode(*AI, false, PTy, false);
Craig Topperbb4069e2017-07-07 23:16:26 +00004161 NewArg = Builder.CreateCast(opcode, *AI, PTy);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004162 }
Reid Klecknerc3fae792017-04-13 18:11:03 +00004163 Args.push_back(NewArg);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004164
4165 // Add any parameter attributes.
Reid Klecknerf021fab2017-04-13 23:12:13 +00004166 ArgAttrs.push_back(CallerPAL.getParamAttributes(i));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004167 }
4168 }
4169 }
4170
Reid Klecknerc2cb5602017-04-12 00:38:00 +00004171 AttributeSet FnAttrs = CallerPAL.getFnAttributes();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004172
4173 if (NewRetTy->isVoidTy())
4174 Caller->setName(""); // Void type should not have a name.
4175
Reid Klecknerc3fae792017-04-13 18:11:03 +00004176 assert((ArgAttrs.size() == FT->getNumParams() || FT->isVarArg()) &&
4177 "missing argument attributes");
4178 LLVMContext &Ctx = Callee->getContext();
4179 AttributeList NewCallerPAL = AttributeList::get(
4180 Ctx, FnAttrs, AttributeSet::get(Ctx, RAttrs), ArgAttrs);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004181
Sanjoy Das76293462015-11-25 00:42:19 +00004182 SmallVector<OperandBundleDef, 1> OpBundles;
Sanjoy Dasc521c7b2015-11-25 00:42:24 +00004183 CS.getOperandBundlesAsDefs(OpBundles);
Sanjoy Das76293462015-11-25 00:42:19 +00004184
Reid Kleckner257cb4e2017-04-13 20:26:38 +00004185 CallSite NewCS;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004186 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Craig Topperbb4069e2017-07-07 23:16:26 +00004187 NewCS = Builder.CreateInvoke(Callee, II->getNormalDest(),
4188 II->getUnwindDest(), Args, OpBundles);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004189 } else {
Craig Topperbb4069e2017-07-07 23:16:26 +00004190 NewCS = Builder.CreateCall(Callee, Args, OpBundles);
Reid Kleckner257cb4e2017-04-13 20:26:38 +00004191 cast<CallInst>(NewCS.getInstruction())
4192 ->setTailCallKind(cast<CallInst>(Caller)->getTailCallKind());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004193 }
Reid Kleckner257cb4e2017-04-13 20:26:38 +00004194 NewCS->takeName(Caller);
4195 NewCS.setCallingConv(CS.getCallingConv());
4196 NewCS.setAttributes(NewCallerPAL);
4197
4198 // Preserve the weight metadata for the new call instruction. The metadata
4199 // is used by SamplePGO to check callsite's hotness.
4200 uint64_t W;
4201 if (Caller->extractProfTotalWeight(W))
4202 NewCS->setProfWeight(W);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004203
4204 // Insert a cast of the return type as necessary.
Reid Kleckner257cb4e2017-04-13 20:26:38 +00004205 Instruction *NC = NewCS.getInstruction();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004206 Value *NV = NC;
4207 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
4208 if (!NV->getType()->isVoidTy()) {
David Majnemer9b6b8222015-01-06 08:41:31 +00004209 NV = NC = CastInst::CreateBitOrPointerCast(NC, OldRetTy);
Eli Friedman35211c62011-05-27 00:19:40 +00004210 NC->setDebugLoc(Caller->getDebugLoc());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004211
4212 // If this is an invoke instruction, we should insert it after the first
4213 // non-phi, instruction in the normal successor block.
4214 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Bill Wendling07efd6f2011-08-25 01:08:34 +00004215 BasicBlock::iterator I = II->getNormalDest()->getFirstInsertionPt();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004216 InsertNewInstBefore(NC, *I);
4217 } else {
Chris Lattner73989652010-12-20 08:25:06 +00004218 // Otherwise, it's a call, just insert cast right after the call.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004219 InsertNewInstBefore(NC, *Caller);
4220 }
4221 Worklist.AddUsersToWorkList(*Caller);
4222 } else {
4223 NV = UndefValue::get(Caller->getType());
4224 }
4225 }
4226
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004227 if (!Caller->use_empty())
Sanjay Patel4b198802016-02-01 22:23:39 +00004228 replaceInstUsesWith(*Caller, NV);
Frederic Rissc1892e22014-10-23 04:08:42 +00004229 else if (Caller->hasValueHandle()) {
4230 if (OldRetTy == NV->getType())
4231 ValueHandleBase::ValueIsRAUWd(Caller, NV);
4232 else
4233 // We cannot call ValueIsRAUWd with a different type, and the
4234 // actual tracked value will disappear.
4235 ValueHandleBase::ValueIsDeleted(Caller);
4236 }
Eli Friedmanb9ed18f2011-05-18 00:32:01 +00004237
Sanjay Patel4b198802016-02-01 22:23:39 +00004238 eraseInstFromFunction(*Caller);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004239 return true;
4240}
4241
Sanjay Patelcd4377c2016-01-20 22:24:38 +00004242/// Turn a call to a function created by init_trampoline / adjust_trampoline
4243/// intrinsic pair into a direct call to the underlying function.
Duncan Sandsa0984362011-09-06 13:37:06 +00004244Instruction *
4245InstCombiner::transformCallThroughTrampoline(CallSite CS,
4246 IntrinsicInst *Tramp) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004247 Value *Callee = CS.getCalledValue();
Chris Lattner229907c2011-07-18 04:54:35 +00004248 PointerType *PTy = cast<PointerType>(Callee->getType());
4249 FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00004250 AttributeList Attrs = CS.getAttributes();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004251
4252 // If the call already has the 'nest' attribute somewhere then give up -
4253 // otherwise 'nest' would occur twice after splicing in the chain.
Bill Wendling6e95ae82012-12-31 00:49:59 +00004254 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Craig Topperf40110f2014-04-25 05:29:35 +00004255 return nullptr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004256
Duncan Sandsa0984362011-09-06 13:37:06 +00004257 assert(Tramp &&
4258 "transformCallThroughTrampoline called with incorrect CallSite.");
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004259
Gabor Greif3e44ea12010-07-22 10:37:47 +00004260 Function *NestF =cast<Function>(Tramp->getArgOperand(1)->stripPointerCasts());
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00004261 FunctionType *NestFTy = cast<FunctionType>(NestF->getValueType());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004262
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00004263 AttributeList NestAttrs = NestF->getAttributes();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004264 if (!NestAttrs.isEmpty()) {
Reid Klecknerf021fab2017-04-13 23:12:13 +00004265 unsigned NestArgNo = 0;
Craig Topperf40110f2014-04-25 05:29:35 +00004266 Type *NestTy = nullptr;
Reid Klecknerc2cb5602017-04-12 00:38:00 +00004267 AttributeSet NestAttr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004268
4269 // Look for a parameter marked with the 'nest' attribute.
4270 for (FunctionType::param_iterator I = NestFTy->param_begin(),
Reid Klecknerf021fab2017-04-13 23:12:13 +00004271 E = NestFTy->param_end();
4272 I != E; ++NestArgNo, ++I) {
4273 AttributeSet AS = NestAttrs.getParamAttributes(NestArgNo);
4274 if (AS.hasAttribute(Attribute::Nest)) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004275 // Record the parameter type and any other attributes.
4276 NestTy = *I;
Reid Klecknerf021fab2017-04-13 23:12:13 +00004277 NestAttr = AS;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004278 break;
4279 }
Reid Klecknerf021fab2017-04-13 23:12:13 +00004280 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004281
4282 if (NestTy) {
4283 Instruction *Caller = CS.getInstruction();
4284 std::vector<Value*> NewArgs;
Reid Kleckner7f720332017-04-13 00:58:09 +00004285 std::vector<AttributeSet> NewArgAttrs;
Matt Arsenault5d2e85f2013-06-28 00:25:40 +00004286 NewArgs.reserve(CS.arg_size() + 1);
Reid Kleckner7f720332017-04-13 00:58:09 +00004287 NewArgAttrs.reserve(CS.arg_size());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004288
4289 // Insert the nest argument into the call argument list, which may
4290 // mean appending it. Likewise for attributes.
4291
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004292 {
Reid Klecknerf021fab2017-04-13 23:12:13 +00004293 unsigned ArgNo = 0;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004294 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
4295 do {
Reid Klecknerf021fab2017-04-13 23:12:13 +00004296 if (ArgNo == NestArgNo) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004297 // Add the chain argument and attributes.
Gabor Greif589a0b92010-06-24 12:58:35 +00004298 Value *NestVal = Tramp->getArgOperand(2);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004299 if (NestVal->getType() != NestTy)
Craig Topperbb4069e2017-07-07 23:16:26 +00004300 NestVal = Builder.CreateBitCast(NestVal, NestTy, "nest");
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004301 NewArgs.push_back(NestVal);
Reid Kleckner7f720332017-04-13 00:58:09 +00004302 NewArgAttrs.push_back(NestAttr);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004303 }
4304
4305 if (I == E)
4306 break;
4307
4308 // Add the original argument and attributes.
4309 NewArgs.push_back(*I);
Reid Klecknerf021fab2017-04-13 23:12:13 +00004310 NewArgAttrs.push_back(Attrs.getParamAttributes(ArgNo));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004311
Reid Klecknerf021fab2017-04-13 23:12:13 +00004312 ++ArgNo;
Richard Trieu7a083812016-02-18 22:09:30 +00004313 ++I;
Eugene Zelenkocdc71612016-08-11 17:20:18 +00004314 } while (true);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004315 }
4316
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004317 // The trampoline may have been bitcast to a bogus type (FTy).
4318 // Handle this by synthesizing a new function type, equal to FTy
4319 // with the chain parameter inserted.
4320
Jay Foadb804a2b2011-07-12 14:06:48 +00004321 std::vector<Type*> NewTypes;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004322 NewTypes.reserve(FTy->getNumParams()+1);
4323
4324 // Insert the chain's type into the list of parameter types, which may
4325 // mean appending it.
4326 {
Reid Klecknerf021fab2017-04-13 23:12:13 +00004327 unsigned ArgNo = 0;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004328 FunctionType::param_iterator I = FTy->param_begin(),
4329 E = FTy->param_end();
4330
4331 do {
Reid Klecknerf021fab2017-04-13 23:12:13 +00004332 if (ArgNo == NestArgNo)
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004333 // Add the chain's type.
4334 NewTypes.push_back(NestTy);
4335
4336 if (I == E)
4337 break;
4338
4339 // Add the original type.
4340 NewTypes.push_back(*I);
4341
Reid Klecknerf021fab2017-04-13 23:12:13 +00004342 ++ArgNo;
Richard Trieu7a083812016-02-18 22:09:30 +00004343 ++I;
Eugene Zelenkocdc71612016-08-11 17:20:18 +00004344 } while (true);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004345 }
4346
4347 // Replace the trampoline call with a direct call. Let the generic
4348 // code sort out any function type mismatches.
Jim Grosbach7815f562012-02-03 00:07:04 +00004349 FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004350 FTy->isVarArg());
4351 Constant *NewCallee =
4352 NestF->getType() == PointerType::getUnqual(NewFTy) ?
Jim Grosbach7815f562012-02-03 00:07:04 +00004353 NestF : ConstantExpr::getBitCast(NestF,
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004354 PointerType::getUnqual(NewFTy));
Reid Kleckner7f720332017-04-13 00:58:09 +00004355 AttributeList NewPAL =
4356 AttributeList::get(FTy->getContext(), Attrs.getFnAttributes(),
4357 Attrs.getRetAttributes(), NewArgAttrs);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004358
David Majnemer231a68c2016-04-29 08:07:20 +00004359 SmallVector<OperandBundleDef, 1> OpBundles;
4360 CS.getOperandBundlesAsDefs(OpBundles);
4361
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004362 Instruction *NewCaller;
4363 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
4364 NewCaller = InvokeInst::Create(NewCallee,
4365 II->getNormalDest(), II->getUnwindDest(),
David Majnemer231a68c2016-04-29 08:07:20 +00004366 NewArgs, OpBundles);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004367 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
4368 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
4369 } else {
David Majnemer231a68c2016-04-29 08:07:20 +00004370 NewCaller = CallInst::Create(NewCallee, NewArgs, OpBundles);
David Majnemerd5648c72016-11-25 22:35:09 +00004371 cast<CallInst>(NewCaller)->setTailCallKind(
4372 cast<CallInst>(Caller)->getTailCallKind());
4373 cast<CallInst>(NewCaller)->setCallingConv(
4374 cast<CallInst>(Caller)->getCallingConv());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004375 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
4376 }
Florian Hahn012c8f92017-12-20 17:16:59 +00004377 NewCaller->setDebugLoc(Caller->getDebugLoc());
Eli Friedman49346012011-05-18 19:57:14 +00004378
4379 return NewCaller;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004380 }
4381 }
4382
4383 // Replace the trampoline call with a direct call. Since there is no 'nest'
4384 // parameter, there is no need to adjust the argument list. Let the generic
4385 // code sort out any function type mismatches.
4386 Constant *NewCallee =
Jim Grosbach7815f562012-02-03 00:07:04 +00004387 NestF->getType() == PTy ? NestF :
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004388 ConstantExpr::getBitCast(NestF, PTy);
4389 CS.setCalledFunction(NewCallee);
4390 return CS.getInstruction();
4391}