blob: 80b1957a7e21a766ac518dd26742f1083972343e [file] [log] [blame]
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001//===- InstCombineCalls.cpp -----------------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the visitCall and visitInvoke functions.
11//
12//===----------------------------------------------------------------------===//
13
Chandler Carrutha9174582015-01-22 05:25:13 +000014#include "InstCombineInternal.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000015#include "llvm/ADT/APFloat.h"
16#include "llvm/ADT/APInt.h"
17#include "llvm/ADT/ArrayRef.h"
18#include "llvm/ADT/None.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000019#include "llvm/ADT/Optional.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000020#include "llvm/ADT/STLExtras.h"
21#include "llvm/ADT/SmallVector.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000022#include "llvm/ADT/Statistic.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000023#include "llvm/ADT/Twine.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000024#include "llvm/Analysis/AssumptionCache.h"
David Majnemer15032582015-05-22 03:56:46 +000025#include "llvm/Analysis/InstructionSimplify.h"
Chris Lattner7a9e47a2010-01-05 07:32:13 +000026#include "llvm/Analysis/MemoryBuiltins.h"
David Blaikie2be39222018-03-21 22:34:23 +000027#include "llvm/Analysis/Utils/Local.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000028#include "llvm/Analysis/ValueTracking.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000029#include "llvm/IR/Attributes.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000030#include "llvm/IR/BasicBlock.h"
Chandler Carruth219b89b2014-03-04 11:01:28 +000031#include "llvm/IR/CallSite.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000032#include "llvm/IR/Constant.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000033#include "llvm/IR/Constants.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000034#include "llvm/IR/DataLayout.h"
35#include "llvm/IR/DerivedTypes.h"
36#include "llvm/IR/Function.h"
37#include "llvm/IR/GlobalVariable.h"
38#include "llvm/IR/InstrTypes.h"
39#include "llvm/IR/Instruction.h"
40#include "llvm/IR/Instructions.h"
41#include "llvm/IR/IntrinsicInst.h"
42#include "llvm/IR/Intrinsics.h"
43#include "llvm/IR/LLVMContext.h"
44#include "llvm/IR/Metadata.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000045#include "llvm/IR/PatternMatch.h"
Philip Reames1a1bdb22014-12-02 18:50:36 +000046#include "llvm/IR/Statepoint.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000047#include "llvm/IR/Type.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000048#include "llvm/IR/User.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000049#include "llvm/IR/Value.h"
50#include "llvm/IR/ValueHandle.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000051#include "llvm/Support/AtomicOrdering.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000052#include "llvm/Support/Casting.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000053#include "llvm/Support/CommandLine.h"
54#include "llvm/Support/Compiler.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000055#include "llvm/Support/Debug.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000056#include "llvm/Support/ErrorHandling.h"
Craig Topperb45eabc2017-04-26 16:39:58 +000057#include "llvm/Support/KnownBits.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000058#include "llvm/Support/MathExtras.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000059#include "llvm/Support/raw_ostream.h"
60#include "llvm/Transforms/InstCombine/InstCombineWorklist.h"
Chandler Carruthba4c5172015-01-21 11:23:40 +000061#include "llvm/Transforms/Utils/SimplifyLibCalls.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000062#include <algorithm>
63#include <cassert>
64#include <cstdint>
65#include <cstring>
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000066#include <utility>
Eugene Zelenkocdc71612016-08-11 17:20:18 +000067#include <vector>
68
Chris Lattner7a9e47a2010-01-05 07:32:13 +000069using namespace llvm;
Michael Ilseman536cc322012-12-13 03:13:36 +000070using namespace PatternMatch;
Chris Lattner7a9e47a2010-01-05 07:32:13 +000071
Chandler Carruth964daaa2014-04-22 02:55:47 +000072#define DEBUG_TYPE "instcombine"
73
Meador Ingee3f2b262012-11-30 04:05:06 +000074STATISTIC(NumSimplified, "Number of library calls simplified");
75
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
Philip Reames79e917d2018-05-09 22:56:32 +000082static cl::opt<unsigned> GuardWideningWindow(
83 "instcombine-guard-widening-window",
84 cl::init(3),
85 cl::desc("How wide an instruction window to bypass looking for "
86 "another guard"));
87
88
Sanjay Patelcd4377c2016-01-20 22:24:38 +000089/// Return the specified type promoted as it would be to pass though a va_arg
90/// area.
Chris Lattner229907c2011-07-18 04:54:35 +000091static Type *getPromotedType(Type *Ty) {
92 if (IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +000093 if (ITy->getBitWidth() < 32)
94 return Type::getInt32Ty(Ty->getContext());
95 }
96 return Ty;
97}
98
Sanjay Patel368ac5d2016-02-21 17:29:33 +000099/// Return a constant boolean vector that has true elements in all positions
Sanjay Patel24401302016-02-21 17:33:31 +0000100/// where the input constant data vector has an element with the sign bit set.
Sanjay Patel368ac5d2016-02-21 17:29:33 +0000101static Constant *getNegativeIsTrueBoolVec(ConstantDataVector *V) {
102 SmallVector<Constant *, 32> BoolVec;
103 IntegerType *BoolTy = Type::getInt1Ty(V->getContext());
104 for (unsigned I = 0, E = V->getNumElements(); I != E; ++I) {
105 Constant *Elt = V->getElementAsConstant(I);
106 assert((isa<ConstantInt>(Elt) || isa<ConstantFP>(Elt)) &&
107 "Unexpected constant data vector element type");
108 bool Sign = V->getElementType()->isIntegerTy()
109 ? cast<ConstantInt>(Elt)->isNegative()
110 : cast<ConstantFP>(Elt)->isNegative();
111 BoolVec.push_back(ConstantInt::get(BoolTy, Sign));
112 }
113 return ConstantVector::get(BoolVec);
114}
115
Daniel Neilsonf9c7d292017-10-30 19:51:48 +0000116Instruction *
117InstCombiner::SimplifyElementUnorderedAtomicMemCpy(AtomicMemCpyInst *AMI) {
Igor Laevsky900ffa32017-02-08 14:32:04 +0000118 // Try to unfold this intrinsic into sequence of explicit atomic loads and
119 // stores.
120 // First check that number of elements is compile time constant.
Daniel Neilson3faabbb2017-06-16 14:43:59 +0000121 auto *LengthCI = dyn_cast<ConstantInt>(AMI->getLength());
122 if (!LengthCI)
Igor Laevsky900ffa32017-02-08 14:32:04 +0000123 return nullptr;
124
125 // Check that there are not too many elements.
Daniel Neilson3faabbb2017-06-16 14:43:59 +0000126 uint64_t LengthInBytes = LengthCI->getZExtValue();
127 uint32_t ElementSizeInBytes = AMI->getElementSizeInBytes();
128 uint64_t NumElements = LengthInBytes / ElementSizeInBytes;
Igor Laevsky900ffa32017-02-08 14:32:04 +0000129 if (NumElements >= UnfoldElementAtomicMemcpyMaxElements)
130 return nullptr;
131
Daniel Neilson3faabbb2017-06-16 14:43:59 +0000132 // Only expand if there are elements to copy.
133 if (NumElements > 0) {
134 // Don't unfold into illegal integers
135 uint64_t ElementSizeInBits = ElementSizeInBytes * 8;
136 if (!getDataLayout().isLegalInteger(ElementSizeInBits))
137 return nullptr;
Igor Laevsky900ffa32017-02-08 14:32:04 +0000138
Daniel Neilson3faabbb2017-06-16 14:43:59 +0000139 // Cast source and destination to the correct type. Intrinsic input
140 // arguments are usually represented as i8*. Often operands will be
141 // explicitly casted to i8* and we can just strip those casts instead of
142 // inserting new ones. However it's easier to rely on other InstCombine
143 // rules which will cover trivial cases anyway.
144 Value *Src = AMI->getRawSource();
145 Value *Dst = AMI->getRawDest();
146 Type *ElementPointerType =
147 Type::getIntNPtrTy(AMI->getContext(), ElementSizeInBits,
148 Src->getType()->getPointerAddressSpace());
Igor Laevsky900ffa32017-02-08 14:32:04 +0000149
Craig Topperbb4069e2017-07-07 23:16:26 +0000150 Value *SrcCasted = Builder.CreatePointerCast(Src, ElementPointerType,
151 "memcpy_unfold.src_casted");
152 Value *DstCasted = Builder.CreatePointerCast(Dst, ElementPointerType,
153 "memcpy_unfold.dst_casted");
Igor Laevsky900ffa32017-02-08 14:32:04 +0000154
Daniel Neilson3faabbb2017-06-16 14:43:59 +0000155 for (uint64_t i = 0; i < NumElements; ++i) {
156 // Get current element addresses
157 ConstantInt *ElementIdxCI =
158 ConstantInt::get(AMI->getContext(), APInt(64, i));
159 Value *SrcElementAddr =
Craig Topperbb4069e2017-07-07 23:16:26 +0000160 Builder.CreateGEP(SrcCasted, ElementIdxCI, "memcpy_unfold.src_addr");
Daniel Neilson3faabbb2017-06-16 14:43:59 +0000161 Value *DstElementAddr =
Craig Topperbb4069e2017-07-07 23:16:26 +0000162 Builder.CreateGEP(DstCasted, ElementIdxCI, "memcpy_unfold.dst_addr");
Igor Laevsky900ffa32017-02-08 14:32:04 +0000163
Daniel Neilson3faabbb2017-06-16 14:43:59 +0000164 // Load from the source. Transfer alignment information and mark load as
165 // unordered atomic.
Craig Topperbb4069e2017-07-07 23:16:26 +0000166 LoadInst *Load = Builder.CreateLoad(SrcElementAddr, "memcpy_unfold.val");
Daniel Neilson3faabbb2017-06-16 14:43:59 +0000167 Load->setOrdering(AtomicOrdering::Unordered);
168 // We know alignment of the first element. It is also guaranteed by the
169 // verifier that element size is less or equal than first element
170 // alignment and both of this values are powers of two. This means that
171 // all subsequent accesses are at least element size aligned.
172 // TODO: We can infer better alignment but there is no evidence that this
173 // will matter.
174 Load->setAlignment(i == 0 ? AMI->getParamAlignment(1)
175 : ElementSizeInBytes);
176 Load->setDebugLoc(AMI->getDebugLoc());
Igor Laevsky900ffa32017-02-08 14:32:04 +0000177
Daniel Neilson3faabbb2017-06-16 14:43:59 +0000178 // Store loaded value via unordered atomic store.
Craig Topperbb4069e2017-07-07 23:16:26 +0000179 StoreInst *Store = Builder.CreateStore(Load, DstElementAddr);
Daniel Neilson3faabbb2017-06-16 14:43:59 +0000180 Store->setOrdering(AtomicOrdering::Unordered);
181 Store->setAlignment(i == 0 ? AMI->getParamAlignment(0)
182 : ElementSizeInBytes);
183 Store->setDebugLoc(AMI->getDebugLoc());
184 }
Igor Laevsky900ffa32017-02-08 14:32:04 +0000185 }
186
187 // Set the number of elements of the copy to 0, it will be deleted on the
188 // next iteration.
Daniel Neilson3faabbb2017-06-16 14:43:59 +0000189 AMI->setLength(Constant::getNullValue(LengthCI->getType()));
Igor Laevsky900ffa32017-02-08 14:32:04 +0000190 return AMI;
191}
192
Pete Cooper67cf9a72015-11-19 05:56:52 +0000193Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Daniel Neilson2363da92018-02-12 23:06:55 +0000194 unsigned DstAlign = getKnownAlignment(MI->getRawDest(), DL, MI, &AC, &DT);
195 unsigned CopyDstAlign = MI->getDestAlignment();
196 if (CopyDstAlign < DstAlign){
197 MI->setDestAlignment(DstAlign);
198 return MI;
199 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000200
Daniel Neilson2363da92018-02-12 23:06:55 +0000201 auto* MTI = cast<MemTransferInst>(MI);
202 unsigned SrcAlign = getKnownAlignment(MTI->getRawSource(), DL, MI, &AC, &DT);
203 unsigned CopySrcAlign = MTI->getSourceAlignment();
204 if (CopySrcAlign < SrcAlign) {
205 MTI->setSourceAlignment(SrcAlign);
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000206 return MI;
207 }
Jim Grosbach7815f562012-02-03 00:07:04 +0000208
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000209 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
210 // load/store.
Gabor Greif0a136c92010-06-24 13:54:33 +0000211 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getArgOperand(2));
Craig Topperf40110f2014-04-25 05:29:35 +0000212 if (!MemOpLength) return nullptr;
Jim Grosbach7815f562012-02-03 00:07:04 +0000213
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000214 // Source and destination pointer types are always "i8*" for intrinsic. See
215 // if the size is something we can handle with a single primitive load/store.
216 // A single load+store correctly handles overlapping memory in the memmove
217 // case.
Michael Liao69e172a2012-08-15 03:49:59 +0000218 uint64_t Size = MemOpLength->getLimitedValue();
Alp Tokercb402912014-01-24 17:20:08 +0000219 assert(Size && "0-sized memory transferring should be removed already.");
Jim Grosbach7815f562012-02-03 00:07:04 +0000220
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000221 if (Size > 8 || (Size&(Size-1)))
Craig Topperf40110f2014-04-25 05:29:35 +0000222 return nullptr; // If not 1/2/4/8 bytes, exit.
Jim Grosbach7815f562012-02-03 00:07:04 +0000223
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000224 // Use an integer load+store unless we can find something better.
Mon P Wangc576ee92010-04-04 03:10:48 +0000225 unsigned SrcAddrSp =
Gabor Greif0a136c92010-06-24 13:54:33 +0000226 cast<PointerType>(MI->getArgOperand(1)->getType())->getAddressSpace();
Gabor Greiff3755202010-04-16 15:33:14 +0000227 unsigned DstAddrSp =
Gabor Greif0a136c92010-06-24 13:54:33 +0000228 cast<PointerType>(MI->getArgOperand(0)->getType())->getAddressSpace();
Mon P Wangc576ee92010-04-04 03:10:48 +0000229
Chris Lattner229907c2011-07-18 04:54:35 +0000230 IntegerType* IntType = IntegerType::get(MI->getContext(), Size<<3);
Mon P Wangc576ee92010-04-04 03:10:48 +0000231 Type *NewSrcPtrTy = PointerType::get(IntType, SrcAddrSp);
232 Type *NewDstPtrTy = PointerType::get(IntType, DstAddrSp);
Jim Grosbach7815f562012-02-03 00:07:04 +0000233
Mikael Holmen760dc9a2017-03-01 06:45:20 +0000234 // If the memcpy has metadata describing the members, see if we can get the
235 // TBAA tag describing our copy.
Craig Topperf40110f2014-04-25 05:29:35 +0000236 MDNode *CopyMD = nullptr;
Ivan A. Kosarevf03f5792018-02-19 12:10:20 +0000237 if (MDNode *M = MI->getMetadata(LLVMContext::MD_tbaa)) {
238 CopyMD = M;
239 } else if (MDNode *M = MI->getMetadata(LLVMContext::MD_tbaa_struct)) {
Mikael Holmen760dc9a2017-03-01 06:45:20 +0000240 if (M->getNumOperands() == 3 && M->getOperand(0) &&
241 mdconst::hasa<ConstantInt>(M->getOperand(0)) &&
Craig Topper79ab6432017-07-06 18:39:47 +0000242 mdconst::extract<ConstantInt>(M->getOperand(0))->isZero() &&
Mikael Holmen760dc9a2017-03-01 06:45:20 +0000243 M->getOperand(1) &&
244 mdconst::hasa<ConstantInt>(M->getOperand(1)) &&
245 mdconst::extract<ConstantInt>(M->getOperand(1))->getValue() ==
246 Size &&
247 M->getOperand(2) && isa<MDNode>(M->getOperand(2)))
248 CopyMD = cast<MDNode>(M->getOperand(2));
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000249 }
Jim Grosbach7815f562012-02-03 00:07:04 +0000250
Craig Topperbb4069e2017-07-07 23:16:26 +0000251 Value *Src = Builder.CreateBitCast(MI->getArgOperand(1), NewSrcPtrTy);
252 Value *Dest = Builder.CreateBitCast(MI->getArgOperand(0), NewDstPtrTy);
253 LoadInst *L = Builder.CreateLoad(Src, MI->isVolatile());
Daniel Neilson2363da92018-02-12 23:06:55 +0000254 // Alignment from the mem intrinsic will be better, so use it.
255 L->setAlignment(CopySrcAlign);
Dan Gohman3f553c22012-09-13 21:51:01 +0000256 if (CopyMD)
257 L->setMetadata(LLVMContext::MD_tbaa, CopyMD);
Dorit Nuzmanabd15f62016-09-04 07:49:39 +0000258 MDNode *LoopMemParallelMD =
259 MI->getMetadata(LLVMContext::MD_mem_parallel_loop_access);
260 if (LoopMemParallelMD)
261 L->setMetadata(LLVMContext::MD_mem_parallel_loop_access, LoopMemParallelMD);
Dorit Nuzman7673ba72016-09-04 07:06:00 +0000262
Craig Topperbb4069e2017-07-07 23:16:26 +0000263 StoreInst *S = Builder.CreateStore(L, Dest, MI->isVolatile());
Daniel Neilson2363da92018-02-12 23:06:55 +0000264 // Alignment from the mem intrinsic will be better, so use it.
265 S->setAlignment(CopyDstAlign);
Dan Gohman3f553c22012-09-13 21:51:01 +0000266 if (CopyMD)
267 S->setMetadata(LLVMContext::MD_tbaa, CopyMD);
Dorit Nuzmanabd15f62016-09-04 07:49:39 +0000268 if (LoopMemParallelMD)
269 S->setMetadata(LLVMContext::MD_mem_parallel_loop_access, LoopMemParallelMD);
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000270
271 // Set the size of the copy to 0, it will be deleted on the next iteration.
Gabor Greif5b1370e2010-06-28 16:50:57 +0000272 MI->setArgOperand(2, Constant::getNullValue(MemOpLength->getType()));
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000273 return MI;
274}
275
276Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000277 unsigned Alignment = getKnownAlignment(MI->getDest(), DL, MI, &AC, &DT);
Daniel Neilson38af2ee2018-02-02 22:03:03 +0000278 if (MI->getDestAlignment() < Alignment) {
279 MI->setDestAlignment(Alignment);
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000280 return MI;
281 }
Jim Grosbach7815f562012-02-03 00:07:04 +0000282
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000283 // Extract the length and alignment and fill if they are constant.
284 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
285 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
Duncan Sands9dff9be2010-02-15 16:12:20 +0000286 if (!LenC || !FillC || !FillC->getType()->isIntegerTy(8))
Craig Topperf40110f2014-04-25 05:29:35 +0000287 return nullptr;
Michael Liao69e172a2012-08-15 03:49:59 +0000288 uint64_t Len = LenC->getLimitedValue();
Daniel Neilson710d7b92018-03-22 18:36:15 +0000289 Alignment = MI->getDestAlignment();
Michael Liao69e172a2012-08-15 03:49:59 +0000290 assert(Len && "0-sized memory setting should be removed already.");
Jim Grosbach7815f562012-02-03 00:07:04 +0000291
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000292 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
293 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
Chris Lattner229907c2011-07-18 04:54:35 +0000294 Type *ITy = IntegerType::get(MI->getContext(), Len*8); // n=1 -> i8.
Jim Grosbach7815f562012-02-03 00:07:04 +0000295
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000296 Value *Dest = MI->getDest();
Mon P Wang1991c472010-12-20 01:05:30 +0000297 unsigned DstAddrSp = cast<PointerType>(Dest->getType())->getAddressSpace();
298 Type *NewDstPtrTy = PointerType::get(ITy, DstAddrSp);
Craig Topperbb4069e2017-07-07 23:16:26 +0000299 Dest = Builder.CreateBitCast(Dest, NewDstPtrTy);
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000300
301 // Alignment 0 is identity for alignment 1 for memset, but not store.
302 if (Alignment == 0) Alignment = 1;
Jim Grosbach7815f562012-02-03 00:07:04 +0000303
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000304 // Extract the fill value and store.
305 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
Craig Topperbb4069e2017-07-07 23:16:26 +0000306 StoreInst *S = Builder.CreateStore(ConstantInt::get(ITy, Fill), Dest,
307 MI->isVolatile());
Eli Friedman49346012011-05-18 19:57:14 +0000308 S->setAlignment(Alignment);
Jim Grosbach7815f562012-02-03 00:07:04 +0000309
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000310 // Set the size of the copy to 0, it will be deleted on the next iteration.
311 MI->setLength(Constant::getNullValue(LenC->getType()));
312 return MI;
313 }
314
Simon Pilgrim18617d12015-08-05 08:18:00 +0000315 return nullptr;
316}
317
Sanjay Patel6038d3e2016-01-29 23:27:03 +0000318static Value *simplifyX86immShift(const IntrinsicInst &II,
Simon Pilgrimbecd5e82015-08-13 07:39:03 +0000319 InstCombiner::BuilderTy &Builder) {
320 bool LogicalShift = false;
321 bool ShiftLeft = false;
322
323 switch (II.getIntrinsicID()) {
Craig Topperb4173a52016-11-13 07:26:19 +0000324 default: llvm_unreachable("Unexpected intrinsic!");
Simon Pilgrimbecd5e82015-08-13 07:39:03 +0000325 case Intrinsic::x86_sse2_psra_d:
326 case Intrinsic::x86_sse2_psra_w:
327 case Intrinsic::x86_sse2_psrai_d:
328 case Intrinsic::x86_sse2_psrai_w:
329 case Intrinsic::x86_avx2_psra_d:
330 case Intrinsic::x86_avx2_psra_w:
331 case Intrinsic::x86_avx2_psrai_d:
332 case Intrinsic::x86_avx2_psrai_w:
Craig Topper8b831cb2016-11-13 01:51:55 +0000333 case Intrinsic::x86_avx512_psra_q_128:
334 case Intrinsic::x86_avx512_psrai_q_128:
335 case Intrinsic::x86_avx512_psra_q_256:
336 case Intrinsic::x86_avx512_psrai_q_256:
337 case Intrinsic::x86_avx512_psra_d_512:
338 case Intrinsic::x86_avx512_psra_q_512:
339 case Intrinsic::x86_avx512_psra_w_512:
340 case Intrinsic::x86_avx512_psrai_d_512:
341 case Intrinsic::x86_avx512_psrai_q_512:
342 case Intrinsic::x86_avx512_psrai_w_512:
Simon Pilgrimbecd5e82015-08-13 07:39:03 +0000343 LogicalShift = false; ShiftLeft = false;
344 break;
345 case Intrinsic::x86_sse2_psrl_d:
346 case Intrinsic::x86_sse2_psrl_q:
347 case Intrinsic::x86_sse2_psrl_w:
348 case Intrinsic::x86_sse2_psrli_d:
349 case Intrinsic::x86_sse2_psrli_q:
350 case Intrinsic::x86_sse2_psrli_w:
351 case Intrinsic::x86_avx2_psrl_d:
352 case Intrinsic::x86_avx2_psrl_q:
353 case Intrinsic::x86_avx2_psrl_w:
354 case Intrinsic::x86_avx2_psrli_d:
355 case Intrinsic::x86_avx2_psrli_q:
356 case Intrinsic::x86_avx2_psrli_w:
Craig Topper8b831cb2016-11-13 01:51:55 +0000357 case Intrinsic::x86_avx512_psrl_d_512:
358 case Intrinsic::x86_avx512_psrl_q_512:
359 case Intrinsic::x86_avx512_psrl_w_512:
360 case Intrinsic::x86_avx512_psrli_d_512:
361 case Intrinsic::x86_avx512_psrli_q_512:
362 case Intrinsic::x86_avx512_psrli_w_512:
Simon Pilgrimbecd5e82015-08-13 07:39:03 +0000363 LogicalShift = true; ShiftLeft = false;
364 break;
365 case Intrinsic::x86_sse2_psll_d:
366 case Intrinsic::x86_sse2_psll_q:
367 case Intrinsic::x86_sse2_psll_w:
368 case Intrinsic::x86_sse2_pslli_d:
369 case Intrinsic::x86_sse2_pslli_q:
370 case Intrinsic::x86_sse2_pslli_w:
371 case Intrinsic::x86_avx2_psll_d:
372 case Intrinsic::x86_avx2_psll_q:
373 case Intrinsic::x86_avx2_psll_w:
374 case Intrinsic::x86_avx2_pslli_d:
375 case Intrinsic::x86_avx2_pslli_q:
376 case Intrinsic::x86_avx2_pslli_w:
Craig Topper8b831cb2016-11-13 01:51:55 +0000377 case Intrinsic::x86_avx512_psll_d_512:
378 case Intrinsic::x86_avx512_psll_q_512:
379 case Intrinsic::x86_avx512_psll_w_512:
380 case Intrinsic::x86_avx512_pslli_d_512:
381 case Intrinsic::x86_avx512_pslli_q_512:
382 case Intrinsic::x86_avx512_pslli_w_512:
Simon Pilgrimbecd5e82015-08-13 07:39:03 +0000383 LogicalShift = true; ShiftLeft = true;
384 break;
385 }
Simon Pilgrima3a72b42015-08-10 20:21:15 +0000386 assert((LogicalShift || !ShiftLeft) && "Only logical shifts can shift left");
387
Simon Pilgrim3815c162015-08-07 18:22:50 +0000388 // Simplify if count is constant.
389 auto Arg1 = II.getArgOperand(1);
390 auto CAZ = dyn_cast<ConstantAggregateZero>(Arg1);
391 auto CDV = dyn_cast<ConstantDataVector>(Arg1);
392 auto CInt = dyn_cast<ConstantInt>(Arg1);
393 if (!CAZ && !CDV && !CInt)
Simon Pilgrim18617d12015-08-05 08:18:00 +0000394 return nullptr;
Simon Pilgrim3815c162015-08-07 18:22:50 +0000395
396 APInt Count(64, 0);
397 if (CDV) {
398 // SSE2/AVX2 uses all the first 64-bits of the 128-bit vector
399 // operand to compute the shift amount.
400 auto VT = cast<VectorType>(CDV->getType());
401 unsigned BitWidth = VT->getElementType()->getPrimitiveSizeInBits();
402 assert((64 % BitWidth) == 0 && "Unexpected packed shift size");
403 unsigned NumSubElts = 64 / BitWidth;
404
405 // Concatenate the sub-elements to create the 64-bit value.
406 for (unsigned i = 0; i != NumSubElts; ++i) {
407 unsigned SubEltIdx = (NumSubElts - 1) - i;
408 auto SubElt = cast<ConstantInt>(CDV->getElementAsConstant(SubEltIdx));
Craig Topper24e71012017-04-28 03:36:24 +0000409 Count <<= BitWidth;
Simon Pilgrim3815c162015-08-07 18:22:50 +0000410 Count |= SubElt->getValue().zextOrTrunc(64);
411 }
412 }
413 else if (CInt)
414 Count = CInt->getValue();
Simon Pilgrim18617d12015-08-05 08:18:00 +0000415
416 auto Vec = II.getArgOperand(0);
417 auto VT = cast<VectorType>(Vec->getType());
418 auto SVT = VT->getElementType();
Simon Pilgrim3815c162015-08-07 18:22:50 +0000419 unsigned VWidth = VT->getNumElements();
420 unsigned BitWidth = SVT->getPrimitiveSizeInBits();
421
422 // If shift-by-zero then just return the original value.
Craig Topper73ba1c82017-06-07 07:40:37 +0000423 if (Count.isNullValue())
Simon Pilgrim3815c162015-08-07 18:22:50 +0000424 return Vec;
425
Simon Pilgrima3a72b42015-08-10 20:21:15 +0000426 // Handle cases when Shift >= BitWidth.
427 if (Count.uge(BitWidth)) {
428 // If LogicalShift - just return zero.
429 if (LogicalShift)
430 return ConstantAggregateZero::get(VT);
431
432 // If ArithmeticShift - clamp Shift to (BitWidth - 1).
433 Count = APInt(64, BitWidth - 1);
434 }
Simon Pilgrim18617d12015-08-05 08:18:00 +0000435
Simon Pilgrim18617d12015-08-05 08:18:00 +0000436 // Get a constant vector of the same type as the first operand.
Simon Pilgrim3815c162015-08-07 18:22:50 +0000437 auto ShiftAmt = ConstantInt::get(SVT, Count.zextOrTrunc(BitWidth));
438 auto ShiftVec = Builder.CreateVectorSplat(VWidth, ShiftAmt);
Simon Pilgrim18617d12015-08-05 08:18:00 +0000439
440 if (ShiftLeft)
Simon Pilgrim3815c162015-08-07 18:22:50 +0000441 return Builder.CreateShl(Vec, ShiftVec);
Simon Pilgrim18617d12015-08-05 08:18:00 +0000442
Simon Pilgrima3a72b42015-08-10 20:21:15 +0000443 if (LogicalShift)
444 return Builder.CreateLShr(Vec, ShiftVec);
445
446 return Builder.CreateAShr(Vec, ShiftVec);
Simon Pilgrim18617d12015-08-05 08:18:00 +0000447}
448
Simon Pilgrimdb9893f2016-06-07 10:27:15 +0000449// Attempt to simplify AVX2 per-element shift intrinsics to a generic IR shift.
450// Unlike the generic IR shifts, the intrinsics have defined behaviour for out
451// of range shift amounts (logical - set to zero, arithmetic - splat sign bit).
452static Value *simplifyX86varShift(const IntrinsicInst &II,
453 InstCombiner::BuilderTy &Builder) {
454 bool LogicalShift = false;
455 bool ShiftLeft = false;
456
457 switch (II.getIntrinsicID()) {
Craig Topperb4173a52016-11-13 07:26:19 +0000458 default: llvm_unreachable("Unexpected intrinsic!");
Simon Pilgrimdb9893f2016-06-07 10:27:15 +0000459 case Intrinsic::x86_avx2_psrav_d:
460 case Intrinsic::x86_avx2_psrav_d_256:
Craig Topperb4173a52016-11-13 07:26:19 +0000461 case Intrinsic::x86_avx512_psrav_q_128:
462 case Intrinsic::x86_avx512_psrav_q_256:
463 case Intrinsic::x86_avx512_psrav_d_512:
464 case Intrinsic::x86_avx512_psrav_q_512:
Craig Topper1de753f2016-11-18 06:04:33 +0000465 case Intrinsic::x86_avx512_psrav_w_128:
466 case Intrinsic::x86_avx512_psrav_w_256:
467 case Intrinsic::x86_avx512_psrav_w_512:
Simon Pilgrimdb9893f2016-06-07 10:27:15 +0000468 LogicalShift = false;
469 ShiftLeft = false;
470 break;
471 case Intrinsic::x86_avx2_psrlv_d:
472 case Intrinsic::x86_avx2_psrlv_d_256:
473 case Intrinsic::x86_avx2_psrlv_q:
474 case Intrinsic::x86_avx2_psrlv_q_256:
Craig Topperb4173a52016-11-13 07:26:19 +0000475 case Intrinsic::x86_avx512_psrlv_d_512:
476 case Intrinsic::x86_avx512_psrlv_q_512:
Craig Topper1de753f2016-11-18 06:04:33 +0000477 case Intrinsic::x86_avx512_psrlv_w_128:
478 case Intrinsic::x86_avx512_psrlv_w_256:
479 case Intrinsic::x86_avx512_psrlv_w_512:
Simon Pilgrimdb9893f2016-06-07 10:27:15 +0000480 LogicalShift = true;
481 ShiftLeft = false;
482 break;
483 case Intrinsic::x86_avx2_psllv_d:
484 case Intrinsic::x86_avx2_psllv_d_256:
485 case Intrinsic::x86_avx2_psllv_q:
486 case Intrinsic::x86_avx2_psllv_q_256:
Craig Topperb4173a52016-11-13 07:26:19 +0000487 case Intrinsic::x86_avx512_psllv_d_512:
488 case Intrinsic::x86_avx512_psllv_q_512:
Craig Topper1de753f2016-11-18 06:04:33 +0000489 case Intrinsic::x86_avx512_psllv_w_128:
490 case Intrinsic::x86_avx512_psllv_w_256:
491 case Intrinsic::x86_avx512_psllv_w_512:
Simon Pilgrimdb9893f2016-06-07 10:27:15 +0000492 LogicalShift = true;
493 ShiftLeft = true;
494 break;
495 }
496 assert((LogicalShift || !ShiftLeft) && "Only logical shifts can shift left");
497
498 // Simplify if all shift amounts are constant/undef.
499 auto *CShift = dyn_cast<Constant>(II.getArgOperand(1));
500 if (!CShift)
501 return nullptr;
502
503 auto Vec = II.getArgOperand(0);
504 auto VT = cast<VectorType>(II.getType());
505 auto SVT = VT->getVectorElementType();
506 int NumElts = VT->getNumElements();
507 int BitWidth = SVT->getIntegerBitWidth();
508
509 // Collect each element's shift amount.
510 // We also collect special cases: UNDEF = -1, OUT-OF-RANGE = BitWidth.
511 bool AnyOutOfRange = false;
512 SmallVector<int, 8> ShiftAmts;
513 for (int I = 0; I < NumElts; ++I) {
514 auto *CElt = CShift->getAggregateElement(I);
515 if (CElt && isa<UndefValue>(CElt)) {
516 ShiftAmts.push_back(-1);
517 continue;
518 }
519
520 auto *COp = dyn_cast_or_null<ConstantInt>(CElt);
521 if (!COp)
522 return nullptr;
523
524 // Handle out of range shifts.
525 // If LogicalShift - set to BitWidth (special case).
526 // If ArithmeticShift - set to (BitWidth - 1) (sign splat).
527 APInt ShiftVal = COp->getValue();
528 if (ShiftVal.uge(BitWidth)) {
529 AnyOutOfRange = LogicalShift;
530 ShiftAmts.push_back(LogicalShift ? BitWidth : BitWidth - 1);
531 continue;
532 }
533
534 ShiftAmts.push_back((int)ShiftVal.getZExtValue());
535 }
536
537 // If all elements out of range or UNDEF, return vector of zeros/undefs.
538 // ArithmeticShift should only hit this if they are all UNDEF.
539 auto OutOfRange = [&](int Idx) { return (Idx < 0) || (BitWidth <= Idx); };
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000540 if (llvm::all_of(ShiftAmts, OutOfRange)) {
Simon Pilgrimdb9893f2016-06-07 10:27:15 +0000541 SmallVector<Constant *, 8> ConstantVec;
542 for (int Idx : ShiftAmts) {
543 if (Idx < 0) {
544 ConstantVec.push_back(UndefValue::get(SVT));
545 } else {
546 assert(LogicalShift && "Logical shift expected");
547 ConstantVec.push_back(ConstantInt::getNullValue(SVT));
548 }
549 }
550 return ConstantVector::get(ConstantVec);
551 }
552
553 // We can't handle only some out of range values with generic logical shifts.
554 if (AnyOutOfRange)
555 return nullptr;
556
557 // Build the shift amount constant vector.
558 SmallVector<Constant *, 8> ShiftVecAmts;
559 for (int Idx : ShiftAmts) {
560 if (Idx < 0)
561 ShiftVecAmts.push_back(UndefValue::get(SVT));
562 else
563 ShiftVecAmts.push_back(ConstantInt::get(SVT, Idx));
564 }
565 auto ShiftVec = ConstantVector::get(ShiftVecAmts);
566
567 if (ShiftLeft)
568 return Builder.CreateShl(Vec, ShiftVec);
569
570 if (LogicalShift)
571 return Builder.CreateLShr(Vec, ShiftVec);
572
573 return Builder.CreateAShr(Vec, ShiftVec);
574}
575
Craig Topper4853c432017-07-06 23:18:42 +0000576static Value *simplifyX86pack(IntrinsicInst &II, bool IsSigned) {
Simon Pilgrim6f6b2792017-01-25 14:37:24 +0000577 Value *Arg0 = II.getArgOperand(0);
578 Value *Arg1 = II.getArgOperand(1);
579 Type *ResTy = II.getType();
580
581 // Fast all undef handling.
582 if (isa<UndefValue>(Arg0) && isa<UndefValue>(Arg1))
583 return UndefValue::get(ResTy);
584
585 Type *ArgTy = Arg0->getType();
586 unsigned NumLanes = ResTy->getPrimitiveSizeInBits() / 128;
587 unsigned NumDstElts = ResTy->getVectorNumElements();
588 unsigned NumSrcElts = ArgTy->getVectorNumElements();
589 assert(NumDstElts == (2 * NumSrcElts) && "Unexpected packing types");
590
591 unsigned NumDstEltsPerLane = NumDstElts / NumLanes;
592 unsigned NumSrcEltsPerLane = NumSrcElts / NumLanes;
593 unsigned DstScalarSizeInBits = ResTy->getScalarSizeInBits();
594 assert(ArgTy->getScalarSizeInBits() == (2 * DstScalarSizeInBits) &&
595 "Unexpected packing types");
596
597 // Constant folding.
598 auto *Cst0 = dyn_cast<Constant>(Arg0);
599 auto *Cst1 = dyn_cast<Constant>(Arg1);
600 if (!Cst0 || !Cst1)
601 return nullptr;
602
603 SmallVector<Constant *, 32> Vals;
604 for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
605 for (unsigned Elt = 0; Elt != NumDstEltsPerLane; ++Elt) {
606 unsigned SrcIdx = Lane * NumSrcEltsPerLane + Elt % NumSrcEltsPerLane;
607 auto *Cst = (Elt >= NumSrcEltsPerLane) ? Cst1 : Cst0;
608 auto *COp = Cst->getAggregateElement(SrcIdx);
609 if (COp && isa<UndefValue>(COp)) {
610 Vals.push_back(UndefValue::get(ResTy->getScalarType()));
611 continue;
612 }
613
614 auto *CInt = dyn_cast_or_null<ConstantInt>(COp);
615 if (!CInt)
616 return nullptr;
617
618 APInt Val = CInt->getValue();
619 assert(Val.getBitWidth() == ArgTy->getScalarSizeInBits() &&
620 "Unexpected constant bitwidth");
621
622 if (IsSigned) {
623 // PACKSS: Truncate signed value with signed saturation.
624 // Source values less than dst minint are saturated to minint.
625 // Source values greater than dst maxint are saturated to maxint.
626 if (Val.isSignedIntN(DstScalarSizeInBits))
627 Val = Val.trunc(DstScalarSizeInBits);
628 else if (Val.isNegative())
629 Val = APInt::getSignedMinValue(DstScalarSizeInBits);
630 else
631 Val = APInt::getSignedMaxValue(DstScalarSizeInBits);
632 } else {
633 // PACKUS: Truncate signed value with unsigned saturation.
634 // Source values less than zero are saturated to zero.
635 // Source values greater than dst maxuint are saturated to maxuint.
636 if (Val.isIntN(DstScalarSizeInBits))
637 Val = Val.trunc(DstScalarSizeInBits);
638 else if (Val.isNegative())
639 Val = APInt::getNullValue(DstScalarSizeInBits);
640 else
641 Val = APInt::getAllOnesValue(DstScalarSizeInBits);
642 }
643
644 Vals.push_back(ConstantInt::get(ResTy->getScalarType(), Val));
645 }
646 }
647
648 return ConstantVector::get(Vals);
649}
650
Craig Topper4853c432017-07-06 23:18:42 +0000651static Value *simplifyX86movmsk(const IntrinsicInst &II) {
Simon Pilgrim91e3ac82016-06-07 08:18:35 +0000652 Value *Arg = II.getArgOperand(0);
653 Type *ResTy = II.getType();
654 Type *ArgTy = Arg->getType();
655
656 // movmsk(undef) -> zero as we must ensure the upper bits are zero.
657 if (isa<UndefValue>(Arg))
658 return Constant::getNullValue(ResTy);
659
660 // We can't easily peek through x86_mmx types.
661 if (!ArgTy->isVectorTy())
662 return nullptr;
663
664 auto *C = dyn_cast<Constant>(Arg);
665 if (!C)
666 return nullptr;
667
668 // Extract signbits of the vector input and pack into integer result.
669 APInt Result(ResTy->getPrimitiveSizeInBits(), 0);
670 for (unsigned I = 0, E = ArgTy->getVectorNumElements(); I != E; ++I) {
671 auto *COp = C->getAggregateElement(I);
672 if (!COp)
673 return nullptr;
674 if (isa<UndefValue>(COp))
675 continue;
676
677 auto *CInt = dyn_cast<ConstantInt>(COp);
678 auto *CFp = dyn_cast<ConstantFP>(COp);
679 if (!CInt && !CFp)
680 return nullptr;
681
682 if ((CInt && CInt->isNegative()) || (CFp && CFp->isNegative()))
683 Result.setBit(I);
684 }
685
686 return Constant::getIntegerValue(ResTy, Result);
687}
688
Sanjay Patel6038d3e2016-01-29 23:27:03 +0000689static Value *simplifyX86insertps(const IntrinsicInst &II,
Sanjay Patelc86867c2015-04-16 17:52:13 +0000690 InstCombiner::BuilderTy &Builder) {
Sanjay Patel03c03f52016-01-28 00:03:16 +0000691 auto *CInt = dyn_cast<ConstantInt>(II.getArgOperand(2));
692 if (!CInt)
693 return nullptr;
Simon Pilgrim54fcd622015-07-25 20:41:00 +0000694
Sanjay Patel03c03f52016-01-28 00:03:16 +0000695 VectorType *VecTy = cast<VectorType>(II.getType());
696 assert(VecTy->getNumElements() == 4 && "insertps with wrong vector type");
Sanjay Patelc86867c2015-04-16 17:52:13 +0000697
Sanjay Patel03c03f52016-01-28 00:03:16 +0000698 // The immediate permute control byte looks like this:
699 // [3:0] - zero mask for each 32-bit lane
700 // [5:4] - select one 32-bit destination lane
701 // [7:6] - select one 32-bit source lane
Sanjay Patelc86867c2015-04-16 17:52:13 +0000702
Sanjay Patel03c03f52016-01-28 00:03:16 +0000703 uint8_t Imm = CInt->getZExtValue();
704 uint8_t ZMask = Imm & 0xf;
705 uint8_t DestLane = (Imm >> 4) & 0x3;
706 uint8_t SourceLane = (Imm >> 6) & 0x3;
Sanjay Patelc1d20a32015-04-25 20:55:25 +0000707
Sanjay Patel03c03f52016-01-28 00:03:16 +0000708 ConstantAggregateZero *ZeroVector = ConstantAggregateZero::get(VecTy);
Sanjay Patelc86867c2015-04-16 17:52:13 +0000709
Sanjay Patel03c03f52016-01-28 00:03:16 +0000710 // If all zero mask bits are set, this was just a weird way to
711 // generate a zero vector.
712 if (ZMask == 0xf)
713 return ZeroVector;
Sanjay Patelc1d20a32015-04-25 20:55:25 +0000714
Sanjay Patel03c03f52016-01-28 00:03:16 +0000715 // Initialize by passing all of the first source bits through.
Craig Topper99d1eab2016-06-12 00:41:19 +0000716 uint32_t ShuffleMask[4] = { 0, 1, 2, 3 };
Sanjay Patelc1d20a32015-04-25 20:55:25 +0000717
Sanjay Patel03c03f52016-01-28 00:03:16 +0000718 // We may replace the second operand with the zero vector.
719 Value *V1 = II.getArgOperand(1);
720
721 if (ZMask) {
722 // If the zero mask is being used with a single input or the zero mask
723 // overrides the destination lane, this is a shuffle with the zero vector.
724 if ((II.getArgOperand(0) == II.getArgOperand(1)) ||
725 (ZMask & (1 << DestLane))) {
726 V1 = ZeroVector;
727 // We may still move 32-bits of the first source vector from one lane
728 // to another.
729 ShuffleMask[DestLane] = SourceLane;
730 // The zero mask may override the previous insert operation.
731 for (unsigned i = 0; i < 4; ++i)
732 if ((ZMask >> i) & 0x1)
733 ShuffleMask[i] = i + 4;
Sanjay Patelc1d20a32015-04-25 20:55:25 +0000734 } else {
Sanjay Patel03c03f52016-01-28 00:03:16 +0000735 // TODO: Model this case as 2 shuffles or a 'logical and' plus shuffle?
736 return nullptr;
Sanjay Patelc1d20a32015-04-25 20:55:25 +0000737 }
Sanjay Patel03c03f52016-01-28 00:03:16 +0000738 } else {
739 // Replace the selected destination lane with the selected source lane.
740 ShuffleMask[DestLane] = SourceLane + 4;
Sanjay Patelc86867c2015-04-16 17:52:13 +0000741 }
Sanjay Patel03c03f52016-01-28 00:03:16 +0000742
743 return Builder.CreateShuffleVector(II.getArgOperand(0), V1, ShuffleMask);
Sanjay Patelc86867c2015-04-16 17:52:13 +0000744}
745
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000746/// Attempt to simplify SSE4A EXTRQ/EXTRQI instructions using constant folding
747/// or conversion to a shuffle vector.
Sanjay Patel6038d3e2016-01-29 23:27:03 +0000748static Value *simplifyX86extrq(IntrinsicInst &II, Value *Op0,
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000749 ConstantInt *CILength, ConstantInt *CIIndex,
750 InstCombiner::BuilderTy &Builder) {
751 auto LowConstantHighUndef = [&](uint64_t Val) {
752 Type *IntTy64 = Type::getInt64Ty(II.getContext());
753 Constant *Args[] = {ConstantInt::get(IntTy64, Val),
754 UndefValue::get(IntTy64)};
755 return ConstantVector::get(Args);
756 };
757
758 // See if we're dealing with constant values.
759 Constant *C0 = dyn_cast<Constant>(Op0);
760 ConstantInt *CI0 =
Andrea Di Biagio8df5b9c2016-09-07 12:03:03 +0000761 C0 ? dyn_cast_or_null<ConstantInt>(C0->getAggregateElement((unsigned)0))
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000762 : nullptr;
763
764 // Attempt to constant fold.
765 if (CILength && CIIndex) {
766 // From AMD documentation: "The bit index and field length are each six
767 // bits in length other bits of the field are ignored."
768 APInt APIndex = CIIndex->getValue().zextOrTrunc(6);
769 APInt APLength = CILength->getValue().zextOrTrunc(6);
770
771 unsigned Index = APIndex.getZExtValue();
772
773 // From AMD documentation: "a value of zero in the field length is
774 // defined as length of 64".
775 unsigned Length = APLength == 0 ? 64 : APLength.getZExtValue();
776
777 // From AMD documentation: "If the sum of the bit index + length field
778 // is greater than 64, the results are undefined".
779 unsigned End = Index + Length;
780
781 // Note that both field index and field length are 8-bit quantities.
782 // Since variables 'Index' and 'Length' are unsigned values
783 // obtained from zero-extending field index and field length
784 // respectively, their sum should never wrap around.
785 if (End > 64)
786 return UndefValue::get(II.getType());
787
788 // If we are inserting whole bytes, we can convert this to a shuffle.
789 // Lowering can recognize EXTRQI shuffle masks.
790 if ((Length % 8) == 0 && (Index % 8) == 0) {
791 // Convert bit indices to byte indices.
792 Length /= 8;
793 Index /= 8;
794
795 Type *IntTy8 = Type::getInt8Ty(II.getContext());
796 Type *IntTy32 = Type::getInt32Ty(II.getContext());
797 VectorType *ShufTy = VectorType::get(IntTy8, 16);
798
799 SmallVector<Constant *, 16> ShuffleMask;
800 for (int i = 0; i != (int)Length; ++i)
801 ShuffleMask.push_back(
802 Constant::getIntegerValue(IntTy32, APInt(32, i + Index)));
803 for (int i = Length; i != 8; ++i)
804 ShuffleMask.push_back(
805 Constant::getIntegerValue(IntTy32, APInt(32, i + 16)));
806 for (int i = 8; i != 16; ++i)
807 ShuffleMask.push_back(UndefValue::get(IntTy32));
808
809 Value *SV = Builder.CreateShuffleVector(
810 Builder.CreateBitCast(Op0, ShufTy),
811 ConstantAggregateZero::get(ShufTy), ConstantVector::get(ShuffleMask));
812 return Builder.CreateBitCast(SV, II.getType());
813 }
814
815 // Constant Fold - shift Index'th bit to lowest position and mask off
816 // Length bits.
817 if (CI0) {
818 APInt Elt = CI0->getValue();
Craig Topperfc947bc2017-04-18 17:14:21 +0000819 Elt.lshrInPlace(Index);
820 Elt = Elt.zextOrTrunc(Length);
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000821 return LowConstantHighUndef(Elt.getZExtValue());
822 }
823
824 // If we were an EXTRQ call, we'll save registers if we convert to EXTRQI.
825 if (II.getIntrinsicID() == Intrinsic::x86_sse4a_extrq) {
826 Value *Args[] = {Op0, CILength, CIIndex};
Sanjay Patelaf674fb2015-12-14 17:24:23 +0000827 Module *M = II.getModule();
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000828 Value *F = Intrinsic::getDeclaration(M, Intrinsic::x86_sse4a_extrqi);
829 return Builder.CreateCall(F, Args);
830 }
831 }
832
833 // Constant Fold - extraction from zero is always {zero, undef}.
Craig Topperca2c8762017-07-06 18:39:49 +0000834 if (CI0 && CI0->isZero())
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000835 return LowConstantHighUndef(0);
836
837 return nullptr;
838}
839
840/// Attempt to simplify SSE4A INSERTQ/INSERTQI instructions using constant
841/// folding or conversion to a shuffle vector.
Sanjay Patel6038d3e2016-01-29 23:27:03 +0000842static Value *simplifyX86insertq(IntrinsicInst &II, Value *Op0, Value *Op1,
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000843 APInt APLength, APInt APIndex,
844 InstCombiner::BuilderTy &Builder) {
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000845 // From AMD documentation: "The bit index and field length are each six bits
846 // in length other bits of the field are ignored."
847 APIndex = APIndex.zextOrTrunc(6);
848 APLength = APLength.zextOrTrunc(6);
849
850 // Attempt to constant fold.
851 unsigned Index = APIndex.getZExtValue();
852
853 // From AMD documentation: "a value of zero in the field length is
854 // defined as length of 64".
855 unsigned Length = APLength == 0 ? 64 : APLength.getZExtValue();
856
857 // From AMD documentation: "If the sum of the bit index + length field
858 // is greater than 64, the results are undefined".
859 unsigned End = Index + Length;
860
861 // Note that both field index and field length are 8-bit quantities.
862 // Since variables 'Index' and 'Length' are unsigned values
863 // obtained from zero-extending field index and field length
864 // respectively, their sum should never wrap around.
865 if (End > 64)
866 return UndefValue::get(II.getType());
867
868 // If we are inserting whole bytes, we can convert this to a shuffle.
869 // Lowering can recognize INSERTQI shuffle masks.
870 if ((Length % 8) == 0 && (Index % 8) == 0) {
871 // Convert bit indices to byte indices.
872 Length /= 8;
873 Index /= 8;
874
875 Type *IntTy8 = Type::getInt8Ty(II.getContext());
876 Type *IntTy32 = Type::getInt32Ty(II.getContext());
877 VectorType *ShufTy = VectorType::get(IntTy8, 16);
878
879 SmallVector<Constant *, 16> ShuffleMask;
880 for (int i = 0; i != (int)Index; ++i)
881 ShuffleMask.push_back(Constant::getIntegerValue(IntTy32, APInt(32, i)));
882 for (int i = 0; i != (int)Length; ++i)
883 ShuffleMask.push_back(
884 Constant::getIntegerValue(IntTy32, APInt(32, i + 16)));
885 for (int i = Index + Length; i != 8; ++i)
886 ShuffleMask.push_back(Constant::getIntegerValue(IntTy32, APInt(32, i)));
887 for (int i = 8; i != 16; ++i)
888 ShuffleMask.push_back(UndefValue::get(IntTy32));
889
890 Value *SV = Builder.CreateShuffleVector(Builder.CreateBitCast(Op0, ShufTy),
891 Builder.CreateBitCast(Op1, ShufTy),
892 ConstantVector::get(ShuffleMask));
893 return Builder.CreateBitCast(SV, II.getType());
894 }
895
896 // See if we're dealing with constant values.
897 Constant *C0 = dyn_cast<Constant>(Op0);
898 Constant *C1 = dyn_cast<Constant>(Op1);
899 ConstantInt *CI00 =
Andrea Di Biagiof3fd3162016-09-07 12:47:53 +0000900 C0 ? dyn_cast_or_null<ConstantInt>(C0->getAggregateElement((unsigned)0))
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000901 : nullptr;
902 ConstantInt *CI10 =
Andrea Di Biagiof3fd3162016-09-07 12:47:53 +0000903 C1 ? dyn_cast_or_null<ConstantInt>(C1->getAggregateElement((unsigned)0))
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000904 : nullptr;
905
906 // Constant Fold - insert bottom Length bits starting at the Index'th bit.
907 if (CI00 && CI10) {
908 APInt V00 = CI00->getValue();
909 APInt V10 = CI10->getValue();
910 APInt Mask = APInt::getLowBitsSet(64, Length).shl(Index);
911 V00 = V00 & ~Mask;
912 V10 = V10.zextOrTrunc(Length).zextOrTrunc(64).shl(Index);
913 APInt Val = V00 | V10;
914 Type *IntTy64 = Type::getInt64Ty(II.getContext());
915 Constant *Args[] = {ConstantInt::get(IntTy64, Val.getZExtValue()),
916 UndefValue::get(IntTy64)};
917 return ConstantVector::get(Args);
918 }
919
920 // If we were an INSERTQ call, we'll save demanded elements if we convert to
921 // INSERTQI.
922 if (II.getIntrinsicID() == Intrinsic::x86_sse4a_insertq) {
923 Type *IntTy8 = Type::getInt8Ty(II.getContext());
924 Constant *CILength = ConstantInt::get(IntTy8, Length, false);
925 Constant *CIIndex = ConstantInt::get(IntTy8, Index, false);
926
927 Value *Args[] = {Op0, Op1, CILength, CIIndex};
Sanjay Patelaf674fb2015-12-14 17:24:23 +0000928 Module *M = II.getModule();
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000929 Value *F = Intrinsic::getDeclaration(M, Intrinsic::x86_sse4a_insertqi);
930 return Builder.CreateCall(F, Args);
931 }
932
933 return nullptr;
934}
935
Simon Pilgrimc0c56e72016-04-24 17:00:34 +0000936/// Attempt to convert pshufb* to shufflevector if the mask is constant.
937static Value *simplifyX86pshufb(const IntrinsicInst &II,
938 InstCombiner::BuilderTy &Builder) {
Simon Pilgrimbf60cc42016-04-29 21:34:54 +0000939 Constant *V = dyn_cast<Constant>(II.getArgOperand(1));
940 if (!V)
941 return nullptr;
942
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +0000943 auto *VecTy = cast<VectorType>(II.getType());
944 auto *MaskEltTy = Type::getInt32Ty(II.getContext());
945 unsigned NumElts = VecTy->getNumElements();
Craig Topper9a63d7a2016-12-11 00:23:50 +0000946 assert((NumElts == 16 || NumElts == 32 || NumElts == 64) &&
Simon Pilgrimc0c56e72016-04-24 17:00:34 +0000947 "Unexpected number of elements in shuffle mask!");
Simon Pilgrimbf60cc42016-04-29 21:34:54 +0000948
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +0000949 // Construct a shuffle mask from constant integers or UNDEFs.
Craig Topper9a63d7a2016-12-11 00:23:50 +0000950 Constant *Indexes[64] = {nullptr};
Simon Pilgrimc0c56e72016-04-24 17:00:34 +0000951
Simon Pilgrimbf60cc42016-04-29 21:34:54 +0000952 // Each byte in the shuffle control mask forms an index to permute the
953 // corresponding byte in the destination operand.
954 for (unsigned I = 0; I < NumElts; ++I) {
955 Constant *COp = V->getAggregateElement(I);
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +0000956 if (!COp || (!isa<UndefValue>(COp) && !isa<ConstantInt>(COp)))
Simon Pilgrimbf60cc42016-04-29 21:34:54 +0000957 return nullptr;
Simon Pilgrimc0c56e72016-04-24 17:00:34 +0000958
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +0000959 if (isa<UndefValue>(COp)) {
960 Indexes[I] = UndefValue::get(MaskEltTy);
961 continue;
962 }
963
Simon Pilgrimbf60cc42016-04-29 21:34:54 +0000964 int8_t Index = cast<ConstantInt>(COp)->getValue().getZExtValue();
965
966 // If the most significant bit (bit[7]) of each byte of the shuffle
967 // control mask is set, then zero is written in the result byte.
968 // The zero vector is in the right-hand side of the resulting
969 // shufflevector.
970
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +0000971 // The value of each index for the high 128-bit lane is the least
972 // significant 4 bits of the respective shuffle control byte.
973 Index = ((Index < 0) ? NumElts : Index & 0x0F) + (I & 0xF0);
974 Indexes[I] = ConstantInt::get(MaskEltTy, Index);
Simon Pilgrimbf60cc42016-04-29 21:34:54 +0000975 }
Simon Pilgrimc0c56e72016-04-24 17:00:34 +0000976
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +0000977 auto ShuffleMask = ConstantVector::get(makeArrayRef(Indexes, NumElts));
Simon Pilgrimc0c56e72016-04-24 17:00:34 +0000978 auto V1 = II.getArgOperand(0);
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +0000979 auto V2 = Constant::getNullValue(VecTy);
Simon Pilgrimc0c56e72016-04-24 17:00:34 +0000980 return Builder.CreateShuffleVector(V1, V2, ShuffleMask);
981}
982
Simon Pilgrim2f6097d2016-04-24 17:23:46 +0000983/// Attempt to convert vpermilvar* to shufflevector if the mask is constant.
984static Value *simplifyX86vpermilvar(const IntrinsicInst &II,
985 InstCombiner::BuilderTy &Builder) {
Simon Pilgrim640f9962016-04-30 07:23:30 +0000986 Constant *V = dyn_cast<Constant>(II.getArgOperand(1));
987 if (!V)
988 return nullptr;
Simon Pilgrim2f6097d2016-04-24 17:23:46 +0000989
Craig Topper58917f32016-12-11 01:59:36 +0000990 auto *VecTy = cast<VectorType>(II.getType());
Simon Pilgrimeeacc402016-05-01 20:22:42 +0000991 auto *MaskEltTy = Type::getInt32Ty(II.getContext());
Craig Topper58917f32016-12-11 01:59:36 +0000992 unsigned NumElts = VecTy->getVectorNumElements();
993 bool IsPD = VecTy->getScalarType()->isDoubleTy();
994 unsigned NumLaneElts = IsPD ? 2 : 4;
995 assert(NumElts == 16 || NumElts == 8 || NumElts == 4 || NumElts == 2);
Simon Pilgrim2f6097d2016-04-24 17:23:46 +0000996
Simon Pilgrimeeacc402016-05-01 20:22:42 +0000997 // Construct a shuffle mask from constant integers or UNDEFs.
Craig Topper58917f32016-12-11 01:59:36 +0000998 Constant *Indexes[16] = {nullptr};
Simon Pilgrim640f9962016-04-30 07:23:30 +0000999
1000 // The intrinsics only read one or two bits, clear the rest.
Simon Pilgrimeeacc402016-05-01 20:22:42 +00001001 for (unsigned I = 0; I < NumElts; ++I) {
Simon Pilgrim640f9962016-04-30 07:23:30 +00001002 Constant *COp = V->getAggregateElement(I);
Simon Pilgrimeeacc402016-05-01 20:22:42 +00001003 if (!COp || (!isa<UndefValue>(COp) && !isa<ConstantInt>(COp)))
Simon Pilgrim640f9962016-04-30 07:23:30 +00001004 return nullptr;
1005
Simon Pilgrimeeacc402016-05-01 20:22:42 +00001006 if (isa<UndefValue>(COp)) {
1007 Indexes[I] = UndefValue::get(MaskEltTy);
1008 continue;
1009 }
1010
1011 APInt Index = cast<ConstantInt>(COp)->getValue();
1012 Index = Index.zextOrTrunc(32).getLoBits(2);
Simon Pilgrim640f9962016-04-30 07:23:30 +00001013
1014 // The PD variants uses bit 1 to select per-lane element index, so
1015 // shift down to convert to generic shuffle mask index.
Craig Topper58917f32016-12-11 01:59:36 +00001016 if (IsPD)
Craig Topperfc947bc2017-04-18 17:14:21 +00001017 Index.lshrInPlace(1);
Simon Pilgrimeeacc402016-05-01 20:22:42 +00001018
1019 // The _256 variants are a bit trickier since the mask bits always index
1020 // into the corresponding 128 half. In order to convert to a generic
1021 // shuffle, we have to make that explicit.
Craig Topper58917f32016-12-11 01:59:36 +00001022 Index += APInt(32, (I / NumLaneElts) * NumLaneElts);
Simon Pilgrimeeacc402016-05-01 20:22:42 +00001023
1024 Indexes[I] = ConstantInt::get(MaskEltTy, Index);
Simon Pilgrim2f6097d2016-04-24 17:23:46 +00001025 }
1026
Simon Pilgrimeeacc402016-05-01 20:22:42 +00001027 auto ShuffleMask = ConstantVector::get(makeArrayRef(Indexes, NumElts));
Simon Pilgrim2f6097d2016-04-24 17:23:46 +00001028 auto V1 = II.getArgOperand(0);
1029 auto V2 = UndefValue::get(V1->getType());
1030 return Builder.CreateShuffleVector(V1, V2, ShuffleMask);
1031}
1032
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +00001033/// Attempt to convert vpermd/vpermps to shufflevector if the mask is constant.
1034static Value *simplifyX86vpermv(const IntrinsicInst &II,
1035 InstCombiner::BuilderTy &Builder) {
1036 auto *V = dyn_cast<Constant>(II.getArgOperand(1));
1037 if (!V)
1038 return nullptr;
1039
Simon Pilgrimca140b12016-05-01 20:43:02 +00001040 auto *VecTy = cast<VectorType>(II.getType());
1041 auto *MaskEltTy = Type::getInt32Ty(II.getContext());
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +00001042 unsigned Size = VecTy->getNumElements();
Craig Toppere3280452016-12-25 23:58:57 +00001043 assert((Size == 4 || Size == 8 || Size == 16 || Size == 32 || Size == 64) &&
1044 "Unexpected shuffle mask size");
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +00001045
Simon Pilgrimca140b12016-05-01 20:43:02 +00001046 // Construct a shuffle mask from constant integers or UNDEFs.
Craig Toppere3280452016-12-25 23:58:57 +00001047 Constant *Indexes[64] = {nullptr};
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +00001048
1049 for (unsigned I = 0; I < Size; ++I) {
1050 Constant *COp = V->getAggregateElement(I);
Simon Pilgrimca140b12016-05-01 20:43:02 +00001051 if (!COp || (!isa<UndefValue>(COp) && !isa<ConstantInt>(COp)))
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +00001052 return nullptr;
1053
Simon Pilgrimca140b12016-05-01 20:43:02 +00001054 if (isa<UndefValue>(COp)) {
1055 Indexes[I] = UndefValue::get(MaskEltTy);
1056 continue;
1057 }
1058
Craig Toppere3280452016-12-25 23:58:57 +00001059 uint32_t Index = cast<ConstantInt>(COp)->getZExtValue();
1060 Index &= Size - 1;
Simon Pilgrimca140b12016-05-01 20:43:02 +00001061 Indexes[I] = ConstantInt::get(MaskEltTy, Index);
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +00001062 }
1063
Simon Pilgrimca140b12016-05-01 20:43:02 +00001064 auto ShuffleMask = ConstantVector::get(makeArrayRef(Indexes, Size));
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +00001065 auto V1 = II.getArgOperand(0);
1066 auto V2 = UndefValue::get(VecTy);
1067 return Builder.CreateShuffleVector(V1, V2, ShuffleMask);
1068}
1069
Simon Pilgrim1d1c56e22015-10-11 14:38:34 +00001070/// Decode XOP integer vector comparison intrinsics.
Sanjay Patel6038d3e2016-01-29 23:27:03 +00001071static Value *simplifyX86vpcom(const IntrinsicInst &II,
Sanjay Patelf9f5d3c2016-01-29 23:14:58 +00001072 InstCombiner::BuilderTy &Builder,
1073 bool IsSigned) {
Simon Pilgrim1d1c56e22015-10-11 14:38:34 +00001074 if (auto *CInt = dyn_cast<ConstantInt>(II.getArgOperand(2))) {
1075 uint64_t Imm = CInt->getZExtValue() & 0x7;
1076 VectorType *VecTy = cast<VectorType>(II.getType());
1077 CmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
1078
1079 switch (Imm) {
1080 case 0x0:
1081 Pred = IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1082 break;
1083 case 0x1:
1084 Pred = IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
1085 break;
1086 case 0x2:
1087 Pred = IsSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1088 break;
1089 case 0x3:
1090 Pred = IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
1091 break;
1092 case 0x4:
1093 Pred = ICmpInst::ICMP_EQ; break;
1094 case 0x5:
1095 Pred = ICmpInst::ICMP_NE; break;
1096 case 0x6:
1097 return ConstantInt::getSigned(VecTy, 0); // FALSE
1098 case 0x7:
1099 return ConstantInt::getSigned(VecTy, -1); // TRUE
1100 }
1101
Sanjay Patelf9f5d3c2016-01-29 23:14:58 +00001102 if (Value *Cmp = Builder.CreateICmp(Pred, II.getArgOperand(0),
1103 II.getArgOperand(1)))
Simon Pilgrim1d1c56e22015-10-11 14:38:34 +00001104 return Builder.CreateSExtOrTrunc(Cmp, VecTy);
1105 }
1106 return nullptr;
1107}
1108
Craig Toppere3280452016-12-25 23:58:57 +00001109// Emit a select instruction and appropriate bitcasts to help simplify
1110// masked intrinsics.
1111static Value *emitX86MaskSelect(Value *Mask, Value *Op0, Value *Op1,
1112 InstCombiner::BuilderTy &Builder) {
Craig Topper99163632016-12-30 23:06:28 +00001113 unsigned VWidth = Op0->getType()->getVectorNumElements();
1114
1115 // If the mask is all ones we don't need the select. But we need to check
1116 // only the bit thats will be used in case VWidth is less than 8.
1117 if (auto *C = dyn_cast<ConstantInt>(Mask))
1118 if (C->getValue().zextOrTrunc(VWidth).isAllOnesValue())
1119 return Op0;
1120
Craig Toppere3280452016-12-25 23:58:57 +00001121 auto *MaskTy = VectorType::get(Builder.getInt1Ty(),
1122 cast<IntegerType>(Mask->getType())->getBitWidth());
1123 Mask = Builder.CreateBitCast(Mask, MaskTy);
1124
1125 // If we have less than 8 elements, then the starting mask was an i8 and
1126 // we need to extract down to the right number of elements.
Craig Toppere3280452016-12-25 23:58:57 +00001127 if (VWidth < 8) {
1128 uint32_t Indices[4];
1129 for (unsigned i = 0; i != VWidth; ++i)
1130 Indices[i] = i;
1131 Mask = Builder.CreateShuffleVector(Mask, Mask,
1132 makeArrayRef(Indices, VWidth),
1133 "extract");
1134 }
1135
1136 return Builder.CreateSelect(Mask, Op0, Op1);
1137}
1138
Sanjay Patel0069f562016-01-31 16:35:23 +00001139static Value *simplifyMinnumMaxnum(const IntrinsicInst &II) {
1140 Value *Arg0 = II.getArgOperand(0);
1141 Value *Arg1 = II.getArgOperand(1);
1142
1143 // fmin(x, x) -> x
1144 if (Arg0 == Arg1)
1145 return Arg0;
1146
1147 const auto *C1 = dyn_cast<ConstantFP>(Arg1);
1148
1149 // fmin(x, nan) -> x
1150 if (C1 && C1->isNaN())
1151 return Arg0;
1152
1153 // This is the value because if undef were NaN, we would return the other
1154 // value and cannot return a NaN unless both operands are.
1155 //
1156 // fmin(undef, x) -> x
1157 if (isa<UndefValue>(Arg0))
1158 return Arg1;
1159
1160 // fmin(x, undef) -> x
1161 if (isa<UndefValue>(Arg1))
1162 return Arg0;
1163
1164 Value *X = nullptr;
1165 Value *Y = nullptr;
1166 if (II.getIntrinsicID() == Intrinsic::minnum) {
1167 // fmin(x, fmin(x, y)) -> fmin(x, y)
1168 // fmin(y, fmin(x, y)) -> fmin(x, y)
1169 if (match(Arg1, m_FMin(m_Value(X), m_Value(Y)))) {
1170 if (Arg0 == X || Arg0 == Y)
1171 return Arg1;
1172 }
1173
1174 // fmin(fmin(x, y), x) -> fmin(x, y)
1175 // fmin(fmin(x, y), y) -> fmin(x, y)
1176 if (match(Arg0, m_FMin(m_Value(X), m_Value(Y)))) {
1177 if (Arg1 == X || Arg1 == Y)
1178 return Arg0;
1179 }
1180
1181 // TODO: fmin(nnan x, inf) -> x
1182 // TODO: fmin(nnan ninf x, flt_max) -> x
1183 if (C1 && C1->isInfinity()) {
1184 // fmin(x, -inf) -> -inf
1185 if (C1->isNegative())
1186 return Arg1;
1187 }
1188 } else {
1189 assert(II.getIntrinsicID() == Intrinsic::maxnum);
1190 // fmax(x, fmax(x, y)) -> fmax(x, y)
1191 // fmax(y, fmax(x, y)) -> fmax(x, y)
1192 if (match(Arg1, m_FMax(m_Value(X), m_Value(Y)))) {
1193 if (Arg0 == X || Arg0 == Y)
1194 return Arg1;
1195 }
1196
1197 // fmax(fmax(x, y), x) -> fmax(x, y)
1198 // fmax(fmax(x, y), y) -> fmax(x, y)
1199 if (match(Arg0, m_FMax(m_Value(X), m_Value(Y)))) {
1200 if (Arg1 == X || Arg1 == Y)
1201 return Arg0;
1202 }
1203
1204 // TODO: fmax(nnan x, -inf) -> x
1205 // TODO: fmax(nnan ninf x, -flt_max) -> x
1206 if (C1 && C1->isInfinity()) {
1207 // fmax(x, inf) -> inf
1208 if (!C1->isNegative())
1209 return Arg1;
1210 }
1211 }
1212 return nullptr;
1213}
1214
David Majnemer666aa942016-07-14 06:58:42 +00001215static bool maskIsAllOneOrUndef(Value *Mask) {
1216 auto *ConstMask = dyn_cast<Constant>(Mask);
1217 if (!ConstMask)
1218 return false;
1219 if (ConstMask->isAllOnesValue() || isa<UndefValue>(ConstMask))
1220 return true;
1221 for (unsigned I = 0, E = ConstMask->getType()->getVectorNumElements(); I != E;
1222 ++I) {
1223 if (auto *MaskElt = ConstMask->getAggregateElement(I))
1224 if (MaskElt->isAllOnesValue() || isa<UndefValue>(MaskElt))
1225 continue;
1226 return false;
1227 }
1228 return true;
1229}
1230
Sanjay Patelb695c552016-02-01 17:00:10 +00001231static Value *simplifyMaskedLoad(const IntrinsicInst &II,
1232 InstCombiner::BuilderTy &Builder) {
David Majnemer666aa942016-07-14 06:58:42 +00001233 // If the mask is all ones or undefs, this is a plain vector load of the 1st
1234 // argument.
1235 if (maskIsAllOneOrUndef(II.getArgOperand(2))) {
Sanjay Patelb695c552016-02-01 17:00:10 +00001236 Value *LoadPtr = II.getArgOperand(0);
1237 unsigned Alignment = cast<ConstantInt>(II.getArgOperand(1))->getZExtValue();
1238 return Builder.CreateAlignedLoad(LoadPtr, Alignment, "unmaskedload");
1239 }
1240
1241 return nullptr;
1242}
1243
Sanjay Patel04f792b2016-02-01 19:39:52 +00001244static Instruction *simplifyMaskedStore(IntrinsicInst &II, InstCombiner &IC) {
1245 auto *ConstMask = dyn_cast<Constant>(II.getArgOperand(3));
1246 if (!ConstMask)
1247 return nullptr;
1248
1249 // If the mask is all zeros, this instruction does nothing.
1250 if (ConstMask->isNullValue())
Sanjay Patel4b198802016-02-01 22:23:39 +00001251 return IC.eraseInstFromFunction(II);
Sanjay Patel04f792b2016-02-01 19:39:52 +00001252
1253 // If the mask is all ones, this is a plain vector store of the 1st argument.
1254 if (ConstMask->isAllOnesValue()) {
1255 Value *StorePtr = II.getArgOperand(1);
1256 unsigned Alignment = cast<ConstantInt>(II.getArgOperand(2))->getZExtValue();
1257 return new StoreInst(II.getArgOperand(0), StorePtr, false, Alignment);
1258 }
1259
1260 return nullptr;
1261}
1262
Sanjay Patel103ab7d2016-02-01 22:10:26 +00001263static Instruction *simplifyMaskedGather(IntrinsicInst &II, InstCombiner &IC) {
1264 // If the mask is all zeros, return the "passthru" argument of the gather.
1265 auto *ConstMask = dyn_cast<Constant>(II.getArgOperand(2));
1266 if (ConstMask && ConstMask->isNullValue())
Sanjay Patel4b198802016-02-01 22:23:39 +00001267 return IC.replaceInstUsesWith(II, II.getArgOperand(3));
Sanjay Patel103ab7d2016-02-01 22:10:26 +00001268
1269 return nullptr;
1270}
1271
1272static Instruction *simplifyMaskedScatter(IntrinsicInst &II, InstCombiner &IC) {
1273 // If the mask is all zeros, a scatter does nothing.
1274 auto *ConstMask = dyn_cast<Constant>(II.getArgOperand(3));
1275 if (ConstMask && ConstMask->isNullValue())
Sanjay Patel4b198802016-02-01 22:23:39 +00001276 return IC.eraseInstFromFunction(II);
Sanjay Patel103ab7d2016-02-01 22:10:26 +00001277
1278 return nullptr;
1279}
1280
Amaury Sechet763c59d2016-08-18 20:43:50 +00001281static Instruction *foldCttzCtlz(IntrinsicInst &II, InstCombiner &IC) {
1282 assert((II.getIntrinsicID() == Intrinsic::cttz ||
1283 II.getIntrinsicID() == Intrinsic::ctlz) &&
1284 "Expected cttz or ctlz intrinsic");
Sanjay Patel8e3ab172016-08-05 22:42:46 +00001285 Value *Op0 = II.getArgOperand(0);
Sanjay Patel8e3ab172016-08-05 22:42:46 +00001286
Craig Topper8205a1a2017-05-24 16:53:07 +00001287 KnownBits Known = IC.computeKnownBits(Op0, 0, &II);
Sanjay Patel8e3ab172016-08-05 22:42:46 +00001288
1289 // Create a mask for bits above (ctlz) or below (cttz) the first known one.
1290 bool IsTZ = II.getIntrinsicID() == Intrinsic::cttz;
Craig Topper8df66c62017-05-12 17:20:30 +00001291 unsigned PossibleZeros = IsTZ ? Known.countMaxTrailingZeros()
1292 : Known.countMaxLeadingZeros();
1293 unsigned DefiniteZeros = IsTZ ? Known.countMinTrailingZeros()
1294 : Known.countMinLeadingZeros();
Sanjay Patel8e3ab172016-08-05 22:42:46 +00001295
1296 // If all bits above (ctlz) or below (cttz) the first known one are known
1297 // zero, this value is constant.
1298 // FIXME: This should be in InstSimplify because we're replacing an
1299 // instruction with a constant.
Craig Topper9474e9b2017-04-27 04:51:25 +00001300 if (PossibleZeros == DefiniteZeros) {
Craig Topper0799ff92017-06-03 18:50:32 +00001301 auto *C = ConstantInt::get(Op0->getType(), DefiniteZeros);
Amaury Sechet763c59d2016-08-18 20:43:50 +00001302 return IC.replaceInstUsesWith(II, C);
1303 }
1304
1305 // If the input to cttz/ctlz is known to be non-zero,
1306 // then change the 'ZeroIsUndef' parameter to 'true'
1307 // because we know the zero behavior can't affect the result.
Craig Topper73ba1c82017-06-07 07:40:37 +00001308 if (!Known.One.isNullValue() ||
Craig Topperd45185f2017-05-26 18:23:57 +00001309 isKnownNonZero(Op0, IC.getDataLayout(), 0, &IC.getAssumptionCache(), &II,
1310 &IC.getDominatorTree())) {
Amaury Sechet763c59d2016-08-18 20:43:50 +00001311 if (!match(II.getArgOperand(1), m_One())) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001312 II.setOperand(1, IC.Builder.getTrue());
Amaury Sechet763c59d2016-08-18 20:43:50 +00001313 return &II;
1314 }
1315 }
Sanjay Patel8e3ab172016-08-05 22:42:46 +00001316
Craig Topper5b173f22017-06-21 16:32:35 +00001317 // Add range metadata since known bits can't completely reflect what we know.
1318 // TODO: Handle splat vectors.
1319 auto *IT = dyn_cast<IntegerType>(Op0->getType());
1320 if (IT && IT->getBitWidth() != 1 && !II.getMetadata(LLVMContext::MD_range)) {
1321 Metadata *LowAndHigh[] = {
1322 ConstantAsMetadata::get(ConstantInt::get(IT, DefiniteZeros)),
1323 ConstantAsMetadata::get(ConstantInt::get(IT, PossibleZeros + 1))};
1324 II.setMetadata(LLVMContext::MD_range,
1325 MDNode::get(II.getContext(), LowAndHigh));
1326 return &II;
1327 }
1328
1329 return nullptr;
1330}
1331
1332static Instruction *foldCtpop(IntrinsicInst &II, InstCombiner &IC) {
1333 assert(II.getIntrinsicID() == Intrinsic::ctpop &&
1334 "Expected ctpop intrinsic");
1335 Value *Op0 = II.getArgOperand(0);
1336 // FIXME: Try to simplify vectors of integers.
1337 auto *IT = dyn_cast<IntegerType>(Op0->getType());
1338 if (!IT)
1339 return nullptr;
1340
1341 unsigned BitWidth = IT->getBitWidth();
1342 KnownBits Known(BitWidth);
1343 IC.computeKnownBits(Op0, Known, 0, &II);
1344
1345 unsigned MinCount = Known.countMinPopulation();
1346 unsigned MaxCount = Known.countMaxPopulation();
1347
1348 // Add range metadata since known bits can't completely reflect what we know.
1349 if (IT->getBitWidth() != 1 && !II.getMetadata(LLVMContext::MD_range)) {
1350 Metadata *LowAndHigh[] = {
1351 ConstantAsMetadata::get(ConstantInt::get(IT, MinCount)),
1352 ConstantAsMetadata::get(ConstantInt::get(IT, MaxCount + 1))};
1353 II.setMetadata(LLVMContext::MD_range,
1354 MDNode::get(II.getContext(), LowAndHigh));
1355 return &II;
1356 }
1357
Sanjay Patel8e3ab172016-08-05 22:42:46 +00001358 return nullptr;
1359}
1360
Sanjay Patel1ace9932016-02-26 21:04:14 +00001361// TODO: If the x86 backend knew how to convert a bool vector mask back to an
1362// XMM register mask efficiently, we could transform all x86 masked intrinsics
1363// to LLVM masked intrinsics and remove the x86 masked intrinsic defs.
Sanjay Patel98a71502016-02-29 23:16:48 +00001364static Instruction *simplifyX86MaskedLoad(IntrinsicInst &II, InstCombiner &IC) {
1365 Value *Ptr = II.getOperand(0);
1366 Value *Mask = II.getOperand(1);
Sanjay Patel5e5056d2016-04-12 23:16:23 +00001367 Constant *ZeroVec = Constant::getNullValue(II.getType());
Sanjay Patel98a71502016-02-29 23:16:48 +00001368
1369 // Special case a zero mask since that's not a ConstantDataVector.
Sanjay Patel5e5056d2016-04-12 23:16:23 +00001370 // This masked load instruction creates a zero vector.
Sanjay Patel98a71502016-02-29 23:16:48 +00001371 if (isa<ConstantAggregateZero>(Mask))
Sanjay Patel5e5056d2016-04-12 23:16:23 +00001372 return IC.replaceInstUsesWith(II, ZeroVec);
Sanjay Patel98a71502016-02-29 23:16:48 +00001373
1374 auto *ConstMask = dyn_cast<ConstantDataVector>(Mask);
1375 if (!ConstMask)
1376 return nullptr;
1377
1378 // The mask is constant. Convert this x86 intrinsic to the LLVM instrinsic
1379 // to allow target-independent optimizations.
1380
1381 // First, cast the x86 intrinsic scalar pointer to a vector pointer to match
1382 // the LLVM intrinsic definition for the pointer argument.
1383 unsigned AddrSpace = cast<PointerType>(Ptr->getType())->getAddressSpace();
1384 PointerType *VecPtrTy = PointerType::get(II.getType(), AddrSpace);
Craig Topperbb4069e2017-07-07 23:16:26 +00001385 Value *PtrCast = IC.Builder.CreateBitCast(Ptr, VecPtrTy, "castvec");
Sanjay Patel98a71502016-02-29 23:16:48 +00001386
1387 // Second, convert the x86 XMM integer vector mask to a vector of bools based
1388 // on each element's most significant bit (the sign bit).
1389 Constant *BoolMask = getNegativeIsTrueBoolVec(ConstMask);
1390
Sanjay Patel5e5056d2016-04-12 23:16:23 +00001391 // The pass-through vector for an x86 masked load is a zero vector.
1392 CallInst *NewMaskedLoad =
Craig Topperbb4069e2017-07-07 23:16:26 +00001393 IC.Builder.CreateMaskedLoad(PtrCast, 1, BoolMask, ZeroVec);
Sanjay Patel98a71502016-02-29 23:16:48 +00001394 return IC.replaceInstUsesWith(II, NewMaskedLoad);
1395}
1396
1397// TODO: If the x86 backend knew how to convert a bool vector mask back to an
1398// XMM register mask efficiently, we could transform all x86 masked intrinsics
1399// to LLVM masked intrinsics and remove the x86 masked intrinsic defs.
Sanjay Patel1ace9932016-02-26 21:04:14 +00001400static bool simplifyX86MaskedStore(IntrinsicInst &II, InstCombiner &IC) {
1401 Value *Ptr = II.getOperand(0);
1402 Value *Mask = II.getOperand(1);
1403 Value *Vec = II.getOperand(2);
1404
1405 // Special case a zero mask since that's not a ConstantDataVector:
1406 // this masked store instruction does nothing.
1407 if (isa<ConstantAggregateZero>(Mask)) {
1408 IC.eraseInstFromFunction(II);
1409 return true;
1410 }
1411
Sanjay Patelc4acbae2016-03-12 15:16:59 +00001412 // The SSE2 version is too weird (eg, unaligned but non-temporal) to do
1413 // anything else at this level.
1414 if (II.getIntrinsicID() == Intrinsic::x86_sse2_maskmov_dqu)
1415 return false;
1416
Sanjay Patel1ace9932016-02-26 21:04:14 +00001417 auto *ConstMask = dyn_cast<ConstantDataVector>(Mask);
1418 if (!ConstMask)
1419 return false;
1420
1421 // The mask is constant. Convert this x86 intrinsic to the LLVM instrinsic
1422 // to allow target-independent optimizations.
1423
1424 // First, cast the x86 intrinsic scalar pointer to a vector pointer to match
1425 // the LLVM intrinsic definition for the pointer argument.
1426 unsigned AddrSpace = cast<PointerType>(Ptr->getType())->getAddressSpace();
1427 PointerType *VecPtrTy = PointerType::get(Vec->getType(), AddrSpace);
Craig Topperbb4069e2017-07-07 23:16:26 +00001428 Value *PtrCast = IC.Builder.CreateBitCast(Ptr, VecPtrTy, "castvec");
Sanjay Patel1ace9932016-02-26 21:04:14 +00001429
1430 // Second, convert the x86 XMM integer vector mask to a vector of bools based
1431 // on each element's most significant bit (the sign bit).
1432 Constant *BoolMask = getNegativeIsTrueBoolVec(ConstMask);
1433
Craig Topperbb4069e2017-07-07 23:16:26 +00001434 IC.Builder.CreateMaskedStore(Vec, PtrCast, 1, BoolMask);
Sanjay Patel1ace9932016-02-26 21:04:14 +00001435
1436 // 'Replace uses' doesn't work for stores. Erase the original masked store.
1437 IC.eraseInstFromFunction(II);
1438 return true;
1439}
1440
Matt Arsenaultcdb468c2017-02-27 23:08:49 +00001441// Constant fold llvm.amdgcn.fmed3 intrinsics for standard inputs.
1442//
1443// A single NaN input is folded to minnum, so we rely on that folding for
1444// handling NaNs.
1445static APFloat fmed3AMDGCN(const APFloat &Src0, const APFloat &Src1,
1446 const APFloat &Src2) {
1447 APFloat Max3 = maxnum(maxnum(Src0, Src1), Src2);
1448
1449 APFloat::cmpResult Cmp0 = Max3.compare(Src0);
1450 assert(Cmp0 != APFloat::cmpUnordered && "nans handled separately");
1451 if (Cmp0 == APFloat::cmpEqual)
1452 return maxnum(Src1, Src2);
1453
1454 APFloat::cmpResult Cmp1 = Max3.compare(Src1);
1455 assert(Cmp1 != APFloat::cmpUnordered && "nans handled separately");
1456 if (Cmp1 == APFloat::cmpEqual)
1457 return maxnum(Src0, Src2);
1458
1459 return maxnum(Src0, Src1);
1460}
1461
Arnaud A. de Grandmaison333ef382016-05-10 09:24:49 +00001462// Returns true iff the 2 intrinsics have the same operands, limiting the
1463// comparison to the first NumOperands.
1464static bool haveSameOperands(const IntrinsicInst &I, const IntrinsicInst &E,
1465 unsigned NumOperands) {
1466 assert(I.getNumArgOperands() >= NumOperands && "Not enough operands");
1467 assert(E.getNumArgOperands() >= NumOperands && "Not enough operands");
1468 for (unsigned i = 0; i < NumOperands; i++)
1469 if (I.getArgOperand(i) != E.getArgOperand(i))
1470 return false;
1471 return true;
1472}
1473
1474// Remove trivially empty start/end intrinsic ranges, i.e. a start
1475// immediately followed by an end (ignoring debuginfo or other
1476// start/end intrinsics in between). As this handles only the most trivial
1477// cases, tracking the nesting level is not needed:
1478//
1479// call @llvm.foo.start(i1 0) ; &I
1480// call @llvm.foo.start(i1 0)
1481// call @llvm.foo.end(i1 0) ; This one will not be skipped: it will be removed
1482// call @llvm.foo.end(i1 0)
1483static bool removeTriviallyEmptyRange(IntrinsicInst &I, unsigned StartID,
1484 unsigned EndID, InstCombiner &IC) {
1485 assert(I.getIntrinsicID() == StartID &&
1486 "Start intrinsic does not have expected ID");
1487 BasicBlock::iterator BI(I), BE(I.getParent()->end());
1488 for (++BI; BI != BE; ++BI) {
1489 if (auto *E = dyn_cast<IntrinsicInst>(BI)) {
1490 if (isa<DbgInfoIntrinsic>(E) || E->getIntrinsicID() == StartID)
1491 continue;
1492 if (E->getIntrinsicID() == EndID &&
1493 haveSameOperands(I, *E, E->getNumArgOperands())) {
1494 IC.eraseInstFromFunction(*E);
1495 IC.eraseInstFromFunction(I);
1496 return true;
1497 }
1498 }
1499 break;
1500 }
1501
1502 return false;
1503}
1504
Justin Lebar698c31b2017-01-27 00:58:58 +00001505// Convert NVVM intrinsics to target-generic LLVM code where possible.
1506static Instruction *SimplifyNVVMIntrinsic(IntrinsicInst *II, InstCombiner &IC) {
1507 // Each NVVM intrinsic we can simplify can be replaced with one of:
1508 //
1509 // * an LLVM intrinsic,
1510 // * an LLVM cast operation,
1511 // * an LLVM binary operation, or
1512 // * ad-hoc LLVM IR for the particular operation.
1513
1514 // Some transformations are only valid when the module's
1515 // flush-denormals-to-zero (ftz) setting is true/false, whereas other
1516 // transformations are valid regardless of the module's ftz setting.
1517 enum FtzRequirementTy {
1518 FTZ_Any, // Any ftz setting is ok.
1519 FTZ_MustBeOn, // Transformation is valid only if ftz is on.
1520 FTZ_MustBeOff, // Transformation is valid only if ftz is off.
1521 };
1522 // Classes of NVVM intrinsics that can't be replaced one-to-one with a
1523 // target-generic intrinsic, cast op, or binary op but that we can nonetheless
1524 // simplify.
1525 enum SpecialCase {
1526 SPC_Reciprocal,
1527 };
1528
1529 // SimplifyAction is a poor-man's variant (plus an additional flag) that
1530 // represents how to replace an NVVM intrinsic with target-generic LLVM IR.
1531 struct SimplifyAction {
1532 // Invariant: At most one of these Optionals has a value.
1533 Optional<Intrinsic::ID> IID;
1534 Optional<Instruction::CastOps> CastOp;
1535 Optional<Instruction::BinaryOps> BinaryOp;
1536 Optional<SpecialCase> Special;
1537
1538 FtzRequirementTy FtzRequirement = FTZ_Any;
1539
1540 SimplifyAction() = default;
1541
1542 SimplifyAction(Intrinsic::ID IID, FtzRequirementTy FtzReq)
1543 : IID(IID), FtzRequirement(FtzReq) {}
1544
1545 // Cast operations don't have anything to do with FTZ, so we skip that
1546 // argument.
1547 SimplifyAction(Instruction::CastOps CastOp) : CastOp(CastOp) {}
1548
1549 SimplifyAction(Instruction::BinaryOps BinaryOp, FtzRequirementTy FtzReq)
1550 : BinaryOp(BinaryOp), FtzRequirement(FtzReq) {}
1551
1552 SimplifyAction(SpecialCase Special, FtzRequirementTy FtzReq)
1553 : Special(Special), FtzRequirement(FtzReq) {}
1554 };
1555
1556 // Try to generate a SimplifyAction describing how to replace our
1557 // IntrinsicInstr with target-generic LLVM IR.
1558 const SimplifyAction Action = [II]() -> SimplifyAction {
1559 switch (II->getIntrinsicID()) {
Justin Lebar698c31b2017-01-27 00:58:58 +00001560 // NVVM intrinsics that map directly to LLVM intrinsics.
1561 case Intrinsic::nvvm_ceil_d:
1562 return {Intrinsic::ceil, FTZ_Any};
1563 case Intrinsic::nvvm_ceil_f:
1564 return {Intrinsic::ceil, FTZ_MustBeOff};
1565 case Intrinsic::nvvm_ceil_ftz_f:
1566 return {Intrinsic::ceil, FTZ_MustBeOn};
1567 case Intrinsic::nvvm_fabs_d:
1568 return {Intrinsic::fabs, FTZ_Any};
1569 case Intrinsic::nvvm_fabs_f:
1570 return {Intrinsic::fabs, FTZ_MustBeOff};
1571 case Intrinsic::nvvm_fabs_ftz_f:
1572 return {Intrinsic::fabs, FTZ_MustBeOn};
1573 case Intrinsic::nvvm_floor_d:
1574 return {Intrinsic::floor, FTZ_Any};
1575 case Intrinsic::nvvm_floor_f:
1576 return {Intrinsic::floor, FTZ_MustBeOff};
1577 case Intrinsic::nvvm_floor_ftz_f:
1578 return {Intrinsic::floor, FTZ_MustBeOn};
1579 case Intrinsic::nvvm_fma_rn_d:
1580 return {Intrinsic::fma, FTZ_Any};
1581 case Intrinsic::nvvm_fma_rn_f:
1582 return {Intrinsic::fma, FTZ_MustBeOff};
1583 case Intrinsic::nvvm_fma_rn_ftz_f:
1584 return {Intrinsic::fma, FTZ_MustBeOn};
1585 case Intrinsic::nvvm_fmax_d:
1586 return {Intrinsic::maxnum, FTZ_Any};
1587 case Intrinsic::nvvm_fmax_f:
1588 return {Intrinsic::maxnum, FTZ_MustBeOff};
1589 case Intrinsic::nvvm_fmax_ftz_f:
1590 return {Intrinsic::maxnum, FTZ_MustBeOn};
1591 case Intrinsic::nvvm_fmin_d:
1592 return {Intrinsic::minnum, FTZ_Any};
1593 case Intrinsic::nvvm_fmin_f:
1594 return {Intrinsic::minnum, FTZ_MustBeOff};
1595 case Intrinsic::nvvm_fmin_ftz_f:
1596 return {Intrinsic::minnum, FTZ_MustBeOn};
1597 case Intrinsic::nvvm_round_d:
1598 return {Intrinsic::round, FTZ_Any};
1599 case Intrinsic::nvvm_round_f:
1600 return {Intrinsic::round, FTZ_MustBeOff};
1601 case Intrinsic::nvvm_round_ftz_f:
1602 return {Intrinsic::round, FTZ_MustBeOn};
1603 case Intrinsic::nvvm_sqrt_rn_d:
1604 return {Intrinsic::sqrt, FTZ_Any};
1605 case Intrinsic::nvvm_sqrt_f:
1606 // nvvm_sqrt_f is a special case. For most intrinsics, foo_ftz_f is the
1607 // ftz version, and foo_f is the non-ftz version. But nvvm_sqrt_f adopts
1608 // the ftz-ness of the surrounding code. sqrt_rn_f and sqrt_rn_ftz_f are
1609 // the versions with explicit ftz-ness.
1610 return {Intrinsic::sqrt, FTZ_Any};
1611 case Intrinsic::nvvm_sqrt_rn_f:
1612 return {Intrinsic::sqrt, FTZ_MustBeOff};
1613 case Intrinsic::nvvm_sqrt_rn_ftz_f:
1614 return {Intrinsic::sqrt, FTZ_MustBeOn};
1615 case Intrinsic::nvvm_trunc_d:
1616 return {Intrinsic::trunc, FTZ_Any};
1617 case Intrinsic::nvvm_trunc_f:
1618 return {Intrinsic::trunc, FTZ_MustBeOff};
1619 case Intrinsic::nvvm_trunc_ftz_f:
1620 return {Intrinsic::trunc, FTZ_MustBeOn};
1621
1622 // NVVM intrinsics that map to LLVM cast operations.
1623 //
1624 // Note that llvm's target-generic conversion operators correspond to the rz
1625 // (round to zero) versions of the nvvm conversion intrinsics, even though
1626 // most everything else here uses the rn (round to nearest even) nvvm ops.
1627 case Intrinsic::nvvm_d2i_rz:
1628 case Intrinsic::nvvm_f2i_rz:
1629 case Intrinsic::nvvm_d2ll_rz:
1630 case Intrinsic::nvvm_f2ll_rz:
1631 return {Instruction::FPToSI};
1632 case Intrinsic::nvvm_d2ui_rz:
1633 case Intrinsic::nvvm_f2ui_rz:
1634 case Intrinsic::nvvm_d2ull_rz:
1635 case Intrinsic::nvvm_f2ull_rz:
1636 return {Instruction::FPToUI};
1637 case Intrinsic::nvvm_i2d_rz:
1638 case Intrinsic::nvvm_i2f_rz:
1639 case Intrinsic::nvvm_ll2d_rz:
1640 case Intrinsic::nvvm_ll2f_rz:
1641 return {Instruction::SIToFP};
1642 case Intrinsic::nvvm_ui2d_rz:
1643 case Intrinsic::nvvm_ui2f_rz:
1644 case Intrinsic::nvvm_ull2d_rz:
1645 case Intrinsic::nvvm_ull2f_rz:
1646 return {Instruction::UIToFP};
1647
1648 // NVVM intrinsics that map to LLVM binary ops.
1649 case Intrinsic::nvvm_add_rn_d:
1650 return {Instruction::FAdd, FTZ_Any};
1651 case Intrinsic::nvvm_add_rn_f:
1652 return {Instruction::FAdd, FTZ_MustBeOff};
1653 case Intrinsic::nvvm_add_rn_ftz_f:
1654 return {Instruction::FAdd, FTZ_MustBeOn};
1655 case Intrinsic::nvvm_mul_rn_d:
1656 return {Instruction::FMul, FTZ_Any};
1657 case Intrinsic::nvvm_mul_rn_f:
1658 return {Instruction::FMul, FTZ_MustBeOff};
1659 case Intrinsic::nvvm_mul_rn_ftz_f:
1660 return {Instruction::FMul, FTZ_MustBeOn};
1661 case Intrinsic::nvvm_div_rn_d:
1662 return {Instruction::FDiv, FTZ_Any};
1663 case Intrinsic::nvvm_div_rn_f:
1664 return {Instruction::FDiv, FTZ_MustBeOff};
1665 case Intrinsic::nvvm_div_rn_ftz_f:
1666 return {Instruction::FDiv, FTZ_MustBeOn};
1667
1668 // The remainder of cases are NVVM intrinsics that map to LLVM idioms, but
1669 // need special handling.
1670 //
Hiroshi Inoue0ca79dc2017-07-11 06:04:59 +00001671 // We seem to be missing intrinsics for rcp.approx.{ftz.}f32, which is just
Justin Lebar698c31b2017-01-27 00:58:58 +00001672 // as well.
1673 case Intrinsic::nvvm_rcp_rn_d:
1674 return {SPC_Reciprocal, FTZ_Any};
1675 case Intrinsic::nvvm_rcp_rn_f:
1676 return {SPC_Reciprocal, FTZ_MustBeOff};
1677 case Intrinsic::nvvm_rcp_rn_ftz_f:
1678 return {SPC_Reciprocal, FTZ_MustBeOn};
1679
1680 // We do not currently simplify intrinsics that give an approximate answer.
1681 // These include:
1682 //
1683 // - nvvm_cos_approx_{f,ftz_f}
1684 // - nvvm_ex2_approx_{d,f,ftz_f}
1685 // - nvvm_lg2_approx_{d,f,ftz_f}
1686 // - nvvm_sin_approx_{f,ftz_f}
1687 // - nvvm_sqrt_approx_{f,ftz_f}
1688 // - nvvm_rsqrt_approx_{d,f,ftz_f}
1689 // - nvvm_div_approx_{ftz_d,ftz_f,f}
1690 // - nvvm_rcp_approx_ftz_d
1691 //
1692 // Ideally we'd encode them as e.g. "fast call @llvm.cos", where "fast"
1693 // means that fastmath is enabled in the intrinsic. Unfortunately only
1694 // binary operators (currently) have a fastmath bit in SelectionDAG, so this
1695 // information gets lost and we can't select on it.
1696 //
1697 // TODO: div and rcp are lowered to a binary op, so these we could in theory
1698 // lower them to "fast fdiv".
1699
1700 default:
1701 return {};
1702 }
1703 }();
1704
1705 // If Action.FtzRequirementTy is not satisfied by the module's ftz state, we
1706 // can bail out now. (Notice that in the case that IID is not an NVVM
1707 // intrinsic, we don't have to look up any module metadata, as
1708 // FtzRequirementTy will be FTZ_Any.)
1709 if (Action.FtzRequirement != FTZ_Any) {
1710 bool FtzEnabled =
1711 II->getFunction()->getFnAttribute("nvptx-f32ftz").getValueAsString() ==
1712 "true";
1713
1714 if (FtzEnabled != (Action.FtzRequirement == FTZ_MustBeOn))
1715 return nullptr;
1716 }
1717
1718 // Simplify to target-generic intrinsic.
1719 if (Action.IID) {
1720 SmallVector<Value *, 4> Args(II->arg_operands());
1721 // All the target-generic intrinsics currently of interest to us have one
1722 // type argument, equal to that of the nvvm intrinsic's argument.
Justin Lebare3ac0fb2017-01-27 01:49:39 +00001723 Type *Tys[] = {II->getArgOperand(0)->getType()};
Justin Lebar698c31b2017-01-27 00:58:58 +00001724 return CallInst::Create(
1725 Intrinsic::getDeclaration(II->getModule(), *Action.IID, Tys), Args);
1726 }
1727
1728 // Simplify to target-generic binary op.
1729 if (Action.BinaryOp)
1730 return BinaryOperator::Create(*Action.BinaryOp, II->getArgOperand(0),
1731 II->getArgOperand(1), II->getName());
1732
1733 // Simplify to target-generic cast op.
1734 if (Action.CastOp)
1735 return CastInst::Create(*Action.CastOp, II->getArgOperand(0), II->getType(),
1736 II->getName());
1737
1738 // All that's left are the special cases.
1739 if (!Action.Special)
1740 return nullptr;
1741
1742 switch (*Action.Special) {
1743 case SPC_Reciprocal:
1744 // Simplify reciprocal.
1745 return BinaryOperator::Create(
1746 Instruction::FDiv, ConstantFP::get(II->getArgOperand(0)->getType(), 1),
1747 II->getArgOperand(0), II->getName());
1748 }
Justin Lebar25ebe2d2017-01-27 02:04:07 +00001749 llvm_unreachable("All SpecialCase enumerators should be handled in switch.");
Justin Lebar698c31b2017-01-27 00:58:58 +00001750}
1751
Arnaud A. de Grandmaison333ef382016-05-10 09:24:49 +00001752Instruction *InstCombiner::visitVAStartInst(VAStartInst &I) {
1753 removeTriviallyEmptyRange(I, Intrinsic::vastart, Intrinsic::vaend, *this);
1754 return nullptr;
1755}
1756
1757Instruction *InstCombiner::visitVACopyInst(VACopyInst &I) {
1758 removeTriviallyEmptyRange(I, Intrinsic::vacopy, Intrinsic::vaend, *this);
1759 return nullptr;
1760}
1761
Sanjay Patelcd4377c2016-01-20 22:24:38 +00001762/// CallInst simplification. This mostly only handles folding of intrinsic
1763/// instructions. For normal calls, it allows visitCallSite to do the heavy
1764/// lifting.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001765Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Philip Reames7a6db4f2017-12-27 00:16:12 +00001766 if (Value *V = SimplifyCall(&CI, SQ.getWithInstruction(&CI)))
Sanjay Patel4b198802016-02-01 22:23:39 +00001767 return replaceInstUsesWith(CI, V);
David Majnemer15032582015-05-22 03:56:46 +00001768
Justin Bogner99798402016-08-05 01:06:44 +00001769 if (isFreeCall(&CI, &TLI))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001770 return visitFree(CI);
1771
1772 // If the caller function is nounwind, mark the call as nounwind, even if the
1773 // callee isn't.
Sanjay Patel5a470952016-08-11 15:16:06 +00001774 if (CI.getFunction()->doesNotThrow() && !CI.doesNotThrow()) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001775 CI.setDoesNotThrow();
1776 return &CI;
1777 }
Jim Grosbach7815f562012-02-03 00:07:04 +00001778
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001779 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
1780 if (!II) return visitCallSite(&CI);
Gabor Greif589a0b92010-06-24 12:58:35 +00001781
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001782 // Intrinsics cannot occur in an invoke, so handle them here instead of in
1783 // visitCallSite.
1784 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
1785 bool Changed = false;
1786
1787 // memmove/cpy/set of zero bytes is a noop.
1788 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
Chris Lattnerc663a672010-10-01 05:51:02 +00001789 if (NumBytes->isNullValue())
Sanjay Patel4b198802016-02-01 22:23:39 +00001790 return eraseInstFromFunction(CI);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001791
1792 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
1793 if (CI->getZExtValue() == 1) {
1794 // Replace the instruction with just byte operations. We would
1795 // transform other cases to loads/stores, but we don't know if
1796 // alignment is sufficient.
1797 }
1798 }
Jim Grosbach7815f562012-02-03 00:07:04 +00001799
Chris Lattnerc663a672010-10-01 05:51:02 +00001800 // No other transformations apply to volatile transfers.
1801 if (MI->isVolatile())
Craig Topperf40110f2014-04-25 05:29:35 +00001802 return nullptr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001803
1804 // If we have a memmove and the source operation is a constant global,
1805 // then the source and dest pointers can't alias, so we can change this
1806 // into a call to memcpy.
1807 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
1808 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
1809 if (GVSrc->isConstant()) {
Sanjay Patelaf674fb2015-12-14 17:24:23 +00001810 Module *M = CI.getModule();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001811 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
Jay Foadb804a2b2011-07-12 14:06:48 +00001812 Type *Tys[3] = { CI.getArgOperand(0)->getType(),
1813 CI.getArgOperand(1)->getType(),
1814 CI.getArgOperand(2)->getType() };
Benjamin Kramere6e19332011-07-14 17:45:39 +00001815 CI.setCalledFunction(Intrinsic::getDeclaration(M, MemCpyID, Tys));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001816 Changed = true;
1817 }
1818 }
1819
1820 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) {
1821 // memmove(x,x,size) -> noop.
1822 if (MTI->getSource() == MTI->getDest())
Sanjay Patel4b198802016-02-01 22:23:39 +00001823 return eraseInstFromFunction(CI);
Eric Christopher7258dcd2010-04-16 23:37:20 +00001824 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001825
Eric Christopher7258dcd2010-04-16 23:37:20 +00001826 // If we can determine a pointer alignment that is bigger than currently
1827 // set, update the alignment.
Pete Cooper67cf9a72015-11-19 05:56:52 +00001828 if (isa<MemTransferInst>(MI)) {
1829 if (Instruction *I = SimplifyMemTransfer(MI))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001830 return I;
1831 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
1832 if (Instruction *I = SimplifyMemSet(MSI))
1833 return I;
1834 }
Gabor Greif590d95e2010-06-24 13:42:49 +00001835
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001836 if (Changed) return II;
1837 }
Jim Grosbach7815f562012-02-03 00:07:04 +00001838
Daniel Neilsonf9c7d292017-10-30 19:51:48 +00001839 if (auto *AMI = dyn_cast<AtomicMemCpyInst>(II)) {
Daniel Neilson3faabbb2017-06-16 14:43:59 +00001840 if (Constant *C = dyn_cast<Constant>(AMI->getLength()))
Igor Laevsky4b317fa2017-02-08 14:23:47 +00001841 if (C->isNullValue())
1842 return eraseInstFromFunction(*AMI);
Igor Laevsky900ffa32017-02-08 14:32:04 +00001843
Daniel Neilson3faabbb2017-06-16 14:43:59 +00001844 if (Instruction *I = SimplifyElementUnorderedAtomicMemCpy(AMI))
Igor Laevsky900ffa32017-02-08 14:32:04 +00001845 return I;
Igor Laevsky4b317fa2017-02-08 14:23:47 +00001846 }
1847
Justin Lebar698c31b2017-01-27 00:58:58 +00001848 if (Instruction *I = SimplifyNVVMIntrinsic(II, *this))
1849 return I;
1850
Sanjay Patel1c600c62016-01-20 16:41:43 +00001851 auto SimplifyDemandedVectorEltsLow = [this](Value *Op, unsigned Width,
1852 unsigned DemandedWidth) {
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001853 APInt UndefElts(Width, 0);
1854 APInt DemandedElts = APInt::getLowBitsSet(Width, DemandedWidth);
1855 return SimplifyDemandedVectorElts(Op, DemandedElts, UndefElts);
1856 };
1857
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001858 switch (II->getIntrinsicID()) {
1859 default: break;
George Burgess IV3f089142016-12-20 23:46:36 +00001860 case Intrinsic::objectsize:
1861 if (ConstantInt *N =
1862 lowerObjectSizeCall(II, DL, &TLI, /*MustSucceed=*/false))
1863 return replaceInstUsesWith(CI, N);
Craig Topperf40110f2014-04-25 05:29:35 +00001864 return nullptr;
Michael Ilseman536cc322012-12-13 03:13:36 +00001865 case Intrinsic::bswap: {
1866 Value *IIOperand = II->getArgOperand(0);
Craig Topperf40110f2014-04-25 05:29:35 +00001867 Value *X = nullptr;
Michael Ilseman536cc322012-12-13 03:13:36 +00001868
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001869 // bswap(trunc(bswap(x))) -> trunc(lshr(x, c))
Michael Ilseman536cc322012-12-13 03:13:36 +00001870 if (match(IIOperand, m_Trunc(m_BSwap(m_Value(X))))) {
1871 unsigned C = X->getType()->getPrimitiveSizeInBits() -
1872 IIOperand->getType()->getPrimitiveSizeInBits();
1873 Value *CV = ConstantInt::get(X->getType(), C);
Craig Topperbb4069e2017-07-07 23:16:26 +00001874 Value *V = Builder.CreateLShr(X, CV);
Michael Ilseman536cc322012-12-13 03:13:36 +00001875 return new TruncInst(V, IIOperand->getType());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001876 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001877 break;
Michael Ilseman536cc322012-12-13 03:13:36 +00001878 }
Sanjay Patelb695c552016-02-01 17:00:10 +00001879 case Intrinsic::masked_load:
Craig Topperbb4069e2017-07-07 23:16:26 +00001880 if (Value *SimplifiedMaskedOp = simplifyMaskedLoad(*II, Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00001881 return replaceInstUsesWith(CI, SimplifiedMaskedOp);
Sanjay Patelb695c552016-02-01 17:00:10 +00001882 break;
Sanjay Patel04f792b2016-02-01 19:39:52 +00001883 case Intrinsic::masked_store:
1884 return simplifyMaskedStore(*II, *this);
Sanjay Patel103ab7d2016-02-01 22:10:26 +00001885 case Intrinsic::masked_gather:
1886 return simplifyMaskedGather(*II, *this);
1887 case Intrinsic::masked_scatter:
1888 return simplifyMaskedScatter(*II, *this);
Sanjay Patelb695c552016-02-01 17:00:10 +00001889
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001890 case Intrinsic::powi:
Gabor Greif589a0b92010-06-24 12:58:35 +00001891 if (ConstantInt *Power = dyn_cast<ConstantInt>(II->getArgOperand(1))) {
Philip Reames5000ba62017-12-27 01:14:30 +00001892 // 0 and 1 are handled in instsimplify
1893
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001894 // powi(x, -1) -> 1/x
Craig Topper79ab6432017-07-06 18:39:47 +00001895 if (Power->isMinusOne())
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001896 return BinaryOperator::CreateFDiv(ConstantFP::get(CI.getType(), 1.0),
Gabor Greif589a0b92010-06-24 12:58:35 +00001897 II->getArgOperand(0));
Philip Reamescd13a662017-12-27 01:30:12 +00001898 // powi(x, 2) -> x*x
1899 if (Power->equalsInt(2))
1900 return BinaryOperator::CreateFMul(II->getArgOperand(0),
1901 II->getArgOperand(0));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001902 }
1903 break;
Jim Grosbach7815f562012-02-03 00:07:04 +00001904
Sanjay Patel8e3ab172016-08-05 22:42:46 +00001905 case Intrinsic::cttz:
1906 case Intrinsic::ctlz:
Amaury Sechet763c59d2016-08-18 20:43:50 +00001907 if (auto *I = foldCttzCtlz(*II, *this))
1908 return I;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001909 break;
Sanjoy Dasb0984472015-04-08 04:27:22 +00001910
Craig Topper5b173f22017-06-21 16:32:35 +00001911 case Intrinsic::ctpop:
1912 if (auto *I = foldCtpop(*II, *this))
1913 return I;
1914 break;
1915
Nick Lewyckyabe2cc12015-04-13 19:17:37 +00001916 case Intrinsic::uadd_with_overflow:
1917 case Intrinsic::sadd_with_overflow:
1918 case Intrinsic::umul_with_overflow:
1919 case Intrinsic::smul_with_overflow:
Gabor Greif5b1370e2010-06-28 16:50:57 +00001920 if (isa<Constant>(II->getArgOperand(0)) &&
1921 !isa<Constant>(II->getArgOperand(1))) {
Sanjoy Dasb0984472015-04-08 04:27:22 +00001922 // Canonicalize constants into the RHS.
Gabor Greif5b1370e2010-06-28 16:50:57 +00001923 Value *LHS = II->getArgOperand(0);
1924 II->setArgOperand(0, II->getArgOperand(1));
1925 II->setArgOperand(1, LHS);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001926 return II;
1927 }
Justin Bognercd1d5aa2016-08-17 20:30:52 +00001928 LLVM_FALLTHROUGH;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001929
Nick Lewyckyabe2cc12015-04-13 19:17:37 +00001930 case Intrinsic::usub_with_overflow:
1931 case Intrinsic::ssub_with_overflow: {
Sanjoy Dasb0984472015-04-08 04:27:22 +00001932 OverflowCheckFlavor OCF =
1933 IntrinsicIDToOverflowCheckFlavor(II->getIntrinsicID());
1934 assert(OCF != OCF_INVALID && "unexpected!");
Jim Grosbach7815f562012-02-03 00:07:04 +00001935
Sanjoy Dasb0984472015-04-08 04:27:22 +00001936 Value *OperationResult = nullptr;
1937 Constant *OverflowResult = nullptr;
1938 if (OptimizeOverflowCheck(OCF, II->getArgOperand(0), II->getArgOperand(1),
1939 *II, OperationResult, OverflowResult))
1940 return CreateOverflowTuple(II, OperationResult, OverflowResult);
Benjamin Kramera420df22014-07-04 10:22:21 +00001941
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001942 break;
Erik Eckstein096ff7d2014-12-11 08:02:30 +00001943 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001944
Matt Arsenaultd6511b42014-10-21 23:00:20 +00001945 case Intrinsic::minnum:
1946 case Intrinsic::maxnum: {
1947 Value *Arg0 = II->getArgOperand(0);
1948 Value *Arg1 = II->getArgOperand(1);
Sanjay Patel0069f562016-01-31 16:35:23 +00001949 // Canonicalize constants to the RHS.
1950 if (isa<ConstantFP>(Arg0) && !isa<ConstantFP>(Arg1)) {
Matt Arsenaultd6511b42014-10-21 23:00:20 +00001951 II->setArgOperand(0, Arg1);
1952 II->setArgOperand(1, Arg0);
1953 return II;
1954 }
Sanjay Patel0069f562016-01-31 16:35:23 +00001955 if (Value *V = simplifyMinnumMaxnum(*II))
Sanjay Patel4b198802016-02-01 22:23:39 +00001956 return replaceInstUsesWith(*II, V);
Matt Arsenaultd6511b42014-10-21 23:00:20 +00001957 break;
1958 }
Matt Arsenault1cc294c2017-01-03 04:32:31 +00001959 case Intrinsic::fmuladd: {
Matt Arsenault92057602017-02-16 18:46:24 +00001960 // Canonicalize fast fmuladd to the separate fmul + fadd.
Sanjay Patel629c4112017-11-06 16:27:15 +00001961 if (II->isFast()) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001962 BuilderTy::FastMathFlagGuard Guard(Builder);
1963 Builder.setFastMathFlags(II->getFastMathFlags());
1964 Value *Mul = Builder.CreateFMul(II->getArgOperand(0),
1965 II->getArgOperand(1));
1966 Value *Add = Builder.CreateFAdd(Mul, II->getArgOperand(2));
Matt Arsenault92057602017-02-16 18:46:24 +00001967 Add->takeName(II);
1968 return replaceInstUsesWith(*II, Add);
1969 }
1970
1971 LLVM_FALLTHROUGH;
1972 }
1973 case Intrinsic::fma: {
Matt Arsenault1cc294c2017-01-03 04:32:31 +00001974 Value *Src0 = II->getArgOperand(0);
1975 Value *Src1 = II->getArgOperand(1);
1976
Sanjay Patel236442e2018-04-05 13:24:26 +00001977 // Canonicalize constant multiply operand to Src1.
Matt Arsenaultb264c942017-01-03 04:32:35 +00001978 if (isa<Constant>(Src0) && !isa<Constant>(Src1)) {
1979 II->setArgOperand(0, Src1);
1980 II->setArgOperand(1, Src0);
1981 std::swap(Src0, Src1);
1982 }
1983
Matt Arsenault1cc294c2017-01-03 04:32:31 +00001984 // fma fneg(x), fneg(y), z -> fma x, y, z
Sanjay Patel236442e2018-04-05 13:24:26 +00001985 Value *X, *Y;
1986 if (match(Src0, m_FNeg(m_Value(X))) && match(Src1, m_FNeg(m_Value(Y)))) {
1987 II->setArgOperand(0, X);
1988 II->setArgOperand(1, Y);
Matt Arsenault3f509042017-01-10 23:17:52 +00001989 return II;
Matt Arsenault1cc294c2017-01-03 04:32:31 +00001990 }
1991
1992 // fma fabs(x), fabs(x), z -> fma x, x, z
Sanjay Patel236442e2018-04-05 13:24:26 +00001993 if (match(Src0, m_Intrinsic<Intrinsic::fabs>(m_Value(X))) &&
1994 match(Src1, m_Intrinsic<Intrinsic::fabs>(m_Specific(X)))) {
1995 II->setArgOperand(0, X);
1996 II->setArgOperand(1, X);
Matt Arsenault3f509042017-01-10 23:17:52 +00001997 return II;
Matt Arsenault1cc294c2017-01-03 04:32:31 +00001998 }
1999
Matt Arsenaultb264c942017-01-03 04:32:35 +00002000 // fma x, 1, z -> fadd x, z
2001 if (match(Src1, m_FPOne())) {
Sanjay Patel236442e2018-04-05 13:24:26 +00002002 auto *FAdd = BinaryOperator::CreateFAdd(Src0, II->getArgOperand(2));
2003 FAdd->copyFastMathFlags(II);
2004 return FAdd;
Matt Arsenaultb264c942017-01-03 04:32:35 +00002005 }
2006
Matt Arsenault1cc294c2017-01-03 04:32:31 +00002007 break;
2008 }
Matt Arsenault56ff4832017-01-03 22:40:34 +00002009 case Intrinsic::fabs: {
2010 Value *Cond;
2011 Constant *LHS, *RHS;
2012 if (match(II->getArgOperand(0),
2013 m_Select(m_Value(Cond), m_Constant(LHS), m_Constant(RHS)))) {
Craig Topperbb4069e2017-07-07 23:16:26 +00002014 CallInst *Call0 = Builder.CreateCall(II->getCalledFunction(), {LHS});
2015 CallInst *Call1 = Builder.CreateCall(II->getCalledFunction(), {RHS});
Matt Arsenault56ff4832017-01-03 22:40:34 +00002016 return SelectInst::Create(Cond, Call0, Call1);
2017 }
2018
Matt Arsenault954a6242017-01-23 23:55:08 +00002019 LLVM_FALLTHROUGH;
2020 }
2021 case Intrinsic::ceil:
2022 case Intrinsic::floor:
2023 case Intrinsic::round:
2024 case Intrinsic::nearbyint:
Joerg Sonnenberger28bed102017-03-31 19:58:07 +00002025 case Intrinsic::rint:
Matt Arsenault954a6242017-01-23 23:55:08 +00002026 case Intrinsic::trunc: {
Matt Arsenault72333442017-01-17 00:10:40 +00002027 Value *ExtSrc;
Sanjay Patel32381d72018-03-23 21:18:12 +00002028 if (match(II->getArgOperand(0), m_OneUse(m_FPExt(m_Value(ExtSrc))))) {
2029 // Narrow the call: intrinsic (fpext x) -> fpext (intrinsic x)
2030 Value *NarrowII = Builder.CreateIntrinsic(II->getIntrinsicID(),
2031 { ExtSrc }, II);
2032 return new FPExtInst(NarrowII, II->getType());
Matt Arsenault72333442017-01-17 00:10:40 +00002033 }
Matt Arsenault56ff4832017-01-03 22:40:34 +00002034 break;
2035 }
Matt Arsenault3bdd75d2017-01-04 22:49:03 +00002036 case Intrinsic::cos:
2037 case Intrinsic::amdgcn_cos: {
2038 Value *SrcSrc;
2039 Value *Src = II->getArgOperand(0);
2040 if (match(Src, m_FNeg(m_Value(SrcSrc))) ||
2041 match(Src, m_Intrinsic<Intrinsic::fabs>(m_Value(SrcSrc)))) {
2042 // cos(-x) -> cos(x)
2043 // cos(fabs(x)) -> cos(x)
2044 II->setArgOperand(0, SrcSrc);
2045 return II;
2046 }
2047
2048 break;
2049 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002050 case Intrinsic::ppc_altivec_lvx:
2051 case Intrinsic::ppc_altivec_lvxl:
Bill Wendlingb902f1d2011-04-13 00:36:11 +00002052 // Turn PPC lvx -> load if the pointer is known aligned.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002053 if (getOrEnforceKnownAlignment(II->getArgOperand(0), 16, DL, II, &AC,
Justin Bogner99798402016-08-05 01:06:44 +00002054 &DT) >= 16) {
Craig Topperbb4069e2017-07-07 23:16:26 +00002055 Value *Ptr = Builder.CreateBitCast(II->getArgOperand(0),
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002056 PointerType::getUnqual(II->getType()));
2057 return new LoadInst(Ptr);
2058 }
2059 break;
Bill Schmidt72954782014-11-12 04:19:40 +00002060 case Intrinsic::ppc_vsx_lxvw4x:
2061 case Intrinsic::ppc_vsx_lxvd2x: {
2062 // Turn PPC VSX loads into normal loads.
Craig Topperbb4069e2017-07-07 23:16:26 +00002063 Value *Ptr = Builder.CreateBitCast(II->getArgOperand(0),
2064 PointerType::getUnqual(II->getType()));
Bill Schmidt72954782014-11-12 04:19:40 +00002065 return new LoadInst(Ptr, Twine(""), false, 1);
2066 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002067 case Intrinsic::ppc_altivec_stvx:
2068 case Intrinsic::ppc_altivec_stvxl:
2069 // Turn stvx -> store if the pointer is known aligned.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002070 if (getOrEnforceKnownAlignment(II->getArgOperand(1), 16, DL, II, &AC,
Justin Bogner99798402016-08-05 01:06:44 +00002071 &DT) >= 16) {
Jim Grosbach7815f562012-02-03 00:07:04 +00002072 Type *OpPtrTy =
Gabor Greifa6d75e22010-06-24 15:51:11 +00002073 PointerType::getUnqual(II->getArgOperand(0)->getType());
Craig Topperbb4069e2017-07-07 23:16:26 +00002074 Value *Ptr = Builder.CreateBitCast(II->getArgOperand(1), OpPtrTy);
Gabor Greifa6d75e22010-06-24 15:51:11 +00002075 return new StoreInst(II->getArgOperand(0), Ptr);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002076 }
2077 break;
Bill Schmidt72954782014-11-12 04:19:40 +00002078 case Intrinsic::ppc_vsx_stxvw4x:
2079 case Intrinsic::ppc_vsx_stxvd2x: {
2080 // Turn PPC VSX stores into normal stores.
2081 Type *OpPtrTy = PointerType::getUnqual(II->getArgOperand(0)->getType());
Craig Topperbb4069e2017-07-07 23:16:26 +00002082 Value *Ptr = Builder.CreateBitCast(II->getArgOperand(1), OpPtrTy);
Bill Schmidt72954782014-11-12 04:19:40 +00002083 return new StoreInst(II->getArgOperand(0), Ptr, false, 1);
2084 }
Hal Finkel221f4672015-02-26 18:56:03 +00002085 case Intrinsic::ppc_qpx_qvlfs:
2086 // Turn PPC QPX qvlfs -> load if the pointer is known aligned.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002087 if (getOrEnforceKnownAlignment(II->getArgOperand(0), 16, DL, II, &AC,
Justin Bogner99798402016-08-05 01:06:44 +00002088 &DT) >= 16) {
Craig Topperbb4069e2017-07-07 23:16:26 +00002089 Type *VTy = VectorType::get(Builder.getFloatTy(),
Hal Finkelf0d68d72015-05-11 06:37:03 +00002090 II->getType()->getVectorNumElements());
Craig Topperbb4069e2017-07-07 23:16:26 +00002091 Value *Ptr = Builder.CreateBitCast(II->getArgOperand(0),
Hal Finkelf0d68d72015-05-11 06:37:03 +00002092 PointerType::getUnqual(VTy));
Craig Topperbb4069e2017-07-07 23:16:26 +00002093 Value *Load = Builder.CreateLoad(Ptr);
Hal Finkelf0d68d72015-05-11 06:37:03 +00002094 return new FPExtInst(Load, II->getType());
Hal Finkel221f4672015-02-26 18:56:03 +00002095 }
2096 break;
2097 case Intrinsic::ppc_qpx_qvlfd:
2098 // Turn PPC QPX qvlfd -> load if the pointer is known aligned.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002099 if (getOrEnforceKnownAlignment(II->getArgOperand(0), 32, DL, II, &AC,
Justin Bogner99798402016-08-05 01:06:44 +00002100 &DT) >= 32) {
Craig Topperbb4069e2017-07-07 23:16:26 +00002101 Value *Ptr = Builder.CreateBitCast(II->getArgOperand(0),
Hal Finkel221f4672015-02-26 18:56:03 +00002102 PointerType::getUnqual(II->getType()));
2103 return new LoadInst(Ptr);
2104 }
2105 break;
2106 case Intrinsic::ppc_qpx_qvstfs:
2107 // Turn PPC QPX qvstfs -> store if the pointer is known aligned.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002108 if (getOrEnforceKnownAlignment(II->getArgOperand(1), 16, DL, II, &AC,
Justin Bogner99798402016-08-05 01:06:44 +00002109 &DT) >= 16) {
Craig Topperbb4069e2017-07-07 23:16:26 +00002110 Type *VTy = VectorType::get(Builder.getFloatTy(),
Hal Finkelf0d68d72015-05-11 06:37:03 +00002111 II->getArgOperand(0)->getType()->getVectorNumElements());
Craig Topperbb4069e2017-07-07 23:16:26 +00002112 Value *TOp = Builder.CreateFPTrunc(II->getArgOperand(0), VTy);
Hal Finkelf0d68d72015-05-11 06:37:03 +00002113 Type *OpPtrTy = PointerType::getUnqual(VTy);
Craig Topperbb4069e2017-07-07 23:16:26 +00002114 Value *Ptr = Builder.CreateBitCast(II->getArgOperand(1), OpPtrTy);
Hal Finkelf0d68d72015-05-11 06:37:03 +00002115 return new StoreInst(TOp, Ptr);
Hal Finkel221f4672015-02-26 18:56:03 +00002116 }
2117 break;
2118 case Intrinsic::ppc_qpx_qvstfd:
2119 // Turn PPC QPX qvstfd -> store if the pointer is known aligned.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002120 if (getOrEnforceKnownAlignment(II->getArgOperand(1), 32, DL, II, &AC,
Justin Bogner99798402016-08-05 01:06:44 +00002121 &DT) >= 32) {
Hal Finkel221f4672015-02-26 18:56:03 +00002122 Type *OpPtrTy =
2123 PointerType::getUnqual(II->getArgOperand(0)->getType());
Craig Topperbb4069e2017-07-07 23:16:26 +00002124 Value *Ptr = Builder.CreateBitCast(II->getArgOperand(1), OpPtrTy);
Hal Finkel221f4672015-02-26 18:56:03 +00002125 return new StoreInst(II->getArgOperand(0), Ptr);
2126 }
2127 break;
Simon Pilgrim20c607b2015-09-12 13:39:53 +00002128
Craig Topper83240032017-07-31 18:52:13 +00002129 case Intrinsic::x86_bmi_bextr_32:
2130 case Intrinsic::x86_bmi_bextr_64:
2131 case Intrinsic::x86_tbm_bextri_u32:
2132 case Intrinsic::x86_tbm_bextri_u64:
2133 // If the RHS is a constant we can try some simplifications.
2134 if (auto *C = dyn_cast<ConstantInt>(II->getArgOperand(1))) {
2135 uint64_t Shift = C->getZExtValue();
2136 uint64_t Length = (Shift >> 8) & 0xff;
2137 Shift &= 0xff;
2138 unsigned BitWidth = II->getType()->getIntegerBitWidth();
2139 // If the length is 0 or the shift is out of range, replace with zero.
2140 if (Length == 0 || Shift >= BitWidth)
2141 return replaceInstUsesWith(CI, ConstantInt::get(II->getType(), 0));
2142 // If the LHS is also a constant, we can completely constant fold this.
2143 if (auto *InC = dyn_cast<ConstantInt>(II->getArgOperand(0))) {
2144 uint64_t Result = InC->getZExtValue() >> Shift;
2145 if (Length > BitWidth)
2146 Length = BitWidth;
2147 Result &= maskTrailingOnes<uint64_t>(Length);
2148 return replaceInstUsesWith(CI, ConstantInt::get(II->getType(), Result));
2149 }
2150 // TODO should we turn this into 'and' if shift is 0? Or 'shl' if we
2151 // are only masking bits that a shift already cleared?
2152 }
2153 break;
2154
Craig Topper317a51e2017-07-31 18:52:15 +00002155 case Intrinsic::x86_bmi_bzhi_32:
2156 case Intrinsic::x86_bmi_bzhi_64:
2157 // If the RHS is a constant we can try some simplifications.
2158 if (auto *C = dyn_cast<ConstantInt>(II->getArgOperand(1))) {
2159 uint64_t Index = C->getZExtValue() & 0xff;
2160 unsigned BitWidth = II->getType()->getIntegerBitWidth();
2161 if (Index >= BitWidth)
2162 return replaceInstUsesWith(CI, II->getArgOperand(0));
2163 if (Index == 0)
2164 return replaceInstUsesWith(CI, ConstantInt::get(II->getType(), 0));
2165 // If the LHS is also a constant, we can completely constant fold this.
2166 if (auto *InC = dyn_cast<ConstantInt>(II->getArgOperand(0))) {
2167 uint64_t Result = InC->getZExtValue();
2168 Result &= maskTrailingOnes<uint64_t>(Index);
2169 return replaceInstUsesWith(CI, ConstantInt::get(II->getType(), Result));
2170 }
2171 // TODO should we convert this to an AND if the RHS is constant?
2172 }
2173 break;
2174
Simon Pilgrim20c607b2015-09-12 13:39:53 +00002175 case Intrinsic::x86_vcvtph2ps_128:
2176 case Intrinsic::x86_vcvtph2ps_256: {
2177 auto Arg = II->getArgOperand(0);
2178 auto ArgType = cast<VectorType>(Arg->getType());
2179 auto RetType = cast<VectorType>(II->getType());
2180 unsigned ArgWidth = ArgType->getNumElements();
2181 unsigned RetWidth = RetType->getNumElements();
2182 assert(RetWidth <= ArgWidth && "Unexpected input/return vector widths");
2183 assert(ArgType->isIntOrIntVectorTy() &&
2184 ArgType->getScalarSizeInBits() == 16 &&
2185 "CVTPH2PS input type should be 16-bit integer vector");
2186 assert(RetType->getScalarType()->isFloatTy() &&
2187 "CVTPH2PS output type should be 32-bit float vector");
2188
2189 // Constant folding: Convert to generic half to single conversion.
Simon Pilgrim48ffca02015-09-12 14:00:17 +00002190 if (isa<ConstantAggregateZero>(Arg))
Sanjay Patel4b198802016-02-01 22:23:39 +00002191 return replaceInstUsesWith(*II, ConstantAggregateZero::get(RetType));
Simon Pilgrim20c607b2015-09-12 13:39:53 +00002192
Simon Pilgrim48ffca02015-09-12 14:00:17 +00002193 if (isa<ConstantDataVector>(Arg)) {
Simon Pilgrim20c607b2015-09-12 13:39:53 +00002194 auto VectorHalfAsShorts = Arg;
2195 if (RetWidth < ArgWidth) {
Craig Topper99d1eab2016-06-12 00:41:19 +00002196 SmallVector<uint32_t, 8> SubVecMask;
Simon Pilgrim20c607b2015-09-12 13:39:53 +00002197 for (unsigned i = 0; i != RetWidth; ++i)
2198 SubVecMask.push_back((int)i);
Craig Topperbb4069e2017-07-07 23:16:26 +00002199 VectorHalfAsShorts = Builder.CreateShuffleVector(
Simon Pilgrim20c607b2015-09-12 13:39:53 +00002200 Arg, UndefValue::get(ArgType), SubVecMask);
2201 }
2202
2203 auto VectorHalfType =
2204 VectorType::get(Type::getHalfTy(II->getContext()), RetWidth);
2205 auto VectorHalfs =
Craig Topperbb4069e2017-07-07 23:16:26 +00002206 Builder.CreateBitCast(VectorHalfAsShorts, VectorHalfType);
2207 auto VectorFloats = Builder.CreateFPExt(VectorHalfs, RetType);
Sanjay Patel4b198802016-02-01 22:23:39 +00002208 return replaceInstUsesWith(*II, VectorFloats);
Simon Pilgrim20c607b2015-09-12 13:39:53 +00002209 }
2210
2211 // We only use the lowest lanes of the argument.
Simon Pilgrim996725e2015-09-19 11:41:53 +00002212 if (Value *V = SimplifyDemandedVectorEltsLow(Arg, ArgWidth, RetWidth)) {
Simon Pilgrim20c607b2015-09-12 13:39:53 +00002213 II->setArgOperand(0, V);
2214 return II;
2215 }
2216 break;
2217 }
2218
Chandler Carruthcf414cf2011-01-10 07:19:37 +00002219 case Intrinsic::x86_sse_cvtss2si:
2220 case Intrinsic::x86_sse_cvtss2si64:
2221 case Intrinsic::x86_sse_cvttss2si:
2222 case Intrinsic::x86_sse_cvttss2si64:
2223 case Intrinsic::x86_sse2_cvtsd2si:
2224 case Intrinsic::x86_sse2_cvtsd2si64:
2225 case Intrinsic::x86_sse2_cvttsd2si:
Craig Topperaeaa52c2016-12-14 07:46:12 +00002226 case Intrinsic::x86_sse2_cvttsd2si64:
2227 case Intrinsic::x86_avx512_vcvtss2si32:
2228 case Intrinsic::x86_avx512_vcvtss2si64:
2229 case Intrinsic::x86_avx512_vcvtss2usi32:
2230 case Intrinsic::x86_avx512_vcvtss2usi64:
2231 case Intrinsic::x86_avx512_vcvtsd2si32:
2232 case Intrinsic::x86_avx512_vcvtsd2si64:
2233 case Intrinsic::x86_avx512_vcvtsd2usi32:
2234 case Intrinsic::x86_avx512_vcvtsd2usi64:
2235 case Intrinsic::x86_avx512_cvttss2si:
2236 case Intrinsic::x86_avx512_cvttss2si64:
2237 case Intrinsic::x86_avx512_cvttss2usi:
2238 case Intrinsic::x86_avx512_cvttss2usi64:
2239 case Intrinsic::x86_avx512_cvttsd2si:
2240 case Intrinsic::x86_avx512_cvttsd2si64:
2241 case Intrinsic::x86_avx512_cvttsd2usi:
2242 case Intrinsic::x86_avx512_cvttsd2usi64: {
Chandler Carruthcf414cf2011-01-10 07:19:37 +00002243 // These intrinsics only demand the 0th element of their input vectors. If
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002244 // we can simplify the input based on that, do so now.
Simon Pilgrim996725e2015-09-19 11:41:53 +00002245 Value *Arg = II->getArgOperand(0);
2246 unsigned VWidth = Arg->getType()->getVectorNumElements();
2247 if (Value *V = SimplifyDemandedVectorEltsLow(Arg, VWidth, 1)) {
Gabor Greif5b1370e2010-06-28 16:50:57 +00002248 II->setArgOperand(0, V);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002249 return II;
2250 }
Simon Pilgrim18617d12015-08-05 08:18:00 +00002251 break;
2252 }
2253
Simon Pilgrim91e3ac82016-06-07 08:18:35 +00002254 case Intrinsic::x86_mmx_pmovmskb:
2255 case Intrinsic::x86_sse_movmsk_ps:
2256 case Intrinsic::x86_sse2_movmsk_pd:
2257 case Intrinsic::x86_sse2_pmovmskb_128:
2258 case Intrinsic::x86_avx_movmsk_pd_256:
2259 case Intrinsic::x86_avx_movmsk_ps_256:
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +00002260 case Intrinsic::x86_avx2_pmovmskb:
Craig Topper4853c432017-07-06 23:18:42 +00002261 if (Value *V = simplifyX86movmsk(*II))
Simon Pilgrim91e3ac82016-06-07 08:18:35 +00002262 return replaceInstUsesWith(*II, V);
2263 break;
Simon Pilgrim91e3ac82016-06-07 08:18:35 +00002264
Simon Pilgrim471efd22016-02-20 23:17:35 +00002265 case Intrinsic::x86_sse_comieq_ss:
2266 case Intrinsic::x86_sse_comige_ss:
2267 case Intrinsic::x86_sse_comigt_ss:
2268 case Intrinsic::x86_sse_comile_ss:
2269 case Intrinsic::x86_sse_comilt_ss:
2270 case Intrinsic::x86_sse_comineq_ss:
2271 case Intrinsic::x86_sse_ucomieq_ss:
2272 case Intrinsic::x86_sse_ucomige_ss:
2273 case Intrinsic::x86_sse_ucomigt_ss:
2274 case Intrinsic::x86_sse_ucomile_ss:
2275 case Intrinsic::x86_sse_ucomilt_ss:
2276 case Intrinsic::x86_sse_ucomineq_ss:
2277 case Intrinsic::x86_sse2_comieq_sd:
2278 case Intrinsic::x86_sse2_comige_sd:
2279 case Intrinsic::x86_sse2_comigt_sd:
2280 case Intrinsic::x86_sse2_comile_sd:
2281 case Intrinsic::x86_sse2_comilt_sd:
2282 case Intrinsic::x86_sse2_comineq_sd:
2283 case Intrinsic::x86_sse2_ucomieq_sd:
2284 case Intrinsic::x86_sse2_ucomige_sd:
2285 case Intrinsic::x86_sse2_ucomigt_sd:
2286 case Intrinsic::x86_sse2_ucomile_sd:
2287 case Intrinsic::x86_sse2_ucomilt_sd:
Craig Topperd9639532016-12-11 07:42:04 +00002288 case Intrinsic::x86_sse2_ucomineq_sd:
Craig Topperd00db692016-12-31 00:45:06 +00002289 case Intrinsic::x86_avx512_vcomi_ss:
2290 case Intrinsic::x86_avx512_vcomi_sd:
Craig Topperd9639532016-12-11 07:42:04 +00002291 case Intrinsic::x86_avx512_mask_cmp_ss:
2292 case Intrinsic::x86_avx512_mask_cmp_sd: {
Simon Pilgrim471efd22016-02-20 23:17:35 +00002293 // These intrinsics only demand the 0th element of their input vectors. If
2294 // we can simplify the input based on that, do so now.
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002295 bool MadeChange = false;
Simon Pilgrim471efd22016-02-20 23:17:35 +00002296 Value *Arg0 = II->getArgOperand(0);
2297 Value *Arg1 = II->getArgOperand(1);
2298 unsigned VWidth = Arg0->getType()->getVectorNumElements();
2299 if (Value *V = SimplifyDemandedVectorEltsLow(Arg0, VWidth, 1)) {
2300 II->setArgOperand(0, V);
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002301 MadeChange = true;
Simon Pilgrim471efd22016-02-20 23:17:35 +00002302 }
2303 if (Value *V = SimplifyDemandedVectorEltsLow(Arg1, VWidth, 1)) {
2304 II->setArgOperand(1, V);
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002305 MadeChange = true;
Simon Pilgrim471efd22016-02-20 23:17:35 +00002306 }
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002307 if (MadeChange)
2308 return II;
Simon Pilgrim471efd22016-02-20 23:17:35 +00002309 break;
2310 }
Michael Zuckerman16b20d22017-04-16 13:26:08 +00002311 case Intrinsic::x86_avx512_mask_cmp_pd_128:
2312 case Intrinsic::x86_avx512_mask_cmp_pd_256:
2313 case Intrinsic::x86_avx512_mask_cmp_pd_512:
2314 case Intrinsic::x86_avx512_mask_cmp_ps_128:
2315 case Intrinsic::x86_avx512_mask_cmp_ps_256:
2316 case Intrinsic::x86_avx512_mask_cmp_ps_512: {
2317 // Folding cmp(sub(a,b),0) -> cmp(a,b) and cmp(0,sub(a,b)) -> cmp(b,a)
2318 Value *Arg0 = II->getArgOperand(0);
2319 Value *Arg1 = II->getArgOperand(1);
Sanjay Patel93e64dd2018-03-25 21:16:33 +00002320 bool Arg0IsZero = match(Arg0, m_PosZeroFP());
Michael Zuckerman16b20d22017-04-16 13:26:08 +00002321 if (Arg0IsZero)
2322 std::swap(Arg0, Arg1);
2323 Value *A, *B;
2324 // This fold requires only the NINF(not +/- inf) since inf minus
2325 // inf is nan.
2326 // NSZ(No Signed Zeros) is not needed because zeros of any sign are
2327 // equal for both compares.
2328 // NNAN is not needed because nans compare the same for both compares.
2329 // The compare intrinsic uses the above assumptions and therefore
2330 // doesn't require additional flags.
2331 if ((match(Arg0, m_OneUse(m_FSub(m_Value(A), m_Value(B)))) &&
Sanjay Patel93e64dd2018-03-25 21:16:33 +00002332 match(Arg1, m_PosZeroFP()) && isa<Instruction>(Arg0) &&
Michael Zuckerman16b20d22017-04-16 13:26:08 +00002333 cast<Instruction>(Arg0)->getFastMathFlags().noInfs())) {
2334 if (Arg0IsZero)
2335 std::swap(A, B);
2336 II->setArgOperand(0, A);
2337 II->setArgOperand(1, B);
2338 return II;
2339 }
2340 break;
2341 }
Simon Pilgrim471efd22016-02-20 23:17:35 +00002342
Craig Topper020b2282016-12-27 00:23:16 +00002343 case Intrinsic::x86_avx512_mask_add_ps_512:
2344 case Intrinsic::x86_avx512_mask_div_ps_512:
2345 case Intrinsic::x86_avx512_mask_mul_ps_512:
2346 case Intrinsic::x86_avx512_mask_sub_ps_512:
2347 case Intrinsic::x86_avx512_mask_add_pd_512:
2348 case Intrinsic::x86_avx512_mask_div_pd_512:
2349 case Intrinsic::x86_avx512_mask_mul_pd_512:
2350 case Intrinsic::x86_avx512_mask_sub_pd_512:
2351 // If the rounding mode is CUR_DIRECTION(4) we can turn these into regular
2352 // IR operations.
2353 if (auto *R = dyn_cast<ConstantInt>(II->getArgOperand(4))) {
2354 if (R->getValue() == 4) {
2355 Value *Arg0 = II->getArgOperand(0);
2356 Value *Arg1 = II->getArgOperand(1);
2357
2358 Value *V;
2359 switch (II->getIntrinsicID()) {
2360 default: llvm_unreachable("Case stmts out of sync!");
2361 case Intrinsic::x86_avx512_mask_add_ps_512:
2362 case Intrinsic::x86_avx512_mask_add_pd_512:
Craig Topperbb4069e2017-07-07 23:16:26 +00002363 V = Builder.CreateFAdd(Arg0, Arg1);
Craig Topper020b2282016-12-27 00:23:16 +00002364 break;
2365 case Intrinsic::x86_avx512_mask_sub_ps_512:
2366 case Intrinsic::x86_avx512_mask_sub_pd_512:
Craig Topperbb4069e2017-07-07 23:16:26 +00002367 V = Builder.CreateFSub(Arg0, Arg1);
Craig Topper020b2282016-12-27 00:23:16 +00002368 break;
2369 case Intrinsic::x86_avx512_mask_mul_ps_512:
2370 case Intrinsic::x86_avx512_mask_mul_pd_512:
Craig Topperbb4069e2017-07-07 23:16:26 +00002371 V = Builder.CreateFMul(Arg0, Arg1);
Craig Topper020b2282016-12-27 00:23:16 +00002372 break;
2373 case Intrinsic::x86_avx512_mask_div_ps_512:
2374 case Intrinsic::x86_avx512_mask_div_pd_512:
Craig Topperbb4069e2017-07-07 23:16:26 +00002375 V = Builder.CreateFDiv(Arg0, Arg1);
Craig Topper020b2282016-12-27 00:23:16 +00002376 break;
2377 }
2378
2379 // Create a select for the masking.
2380 V = emitX86MaskSelect(II->getArgOperand(3), V, II->getArgOperand(2),
Craig Topperbb4069e2017-07-07 23:16:26 +00002381 Builder);
Craig Topper020b2282016-12-27 00:23:16 +00002382 return replaceInstUsesWith(*II, V);
2383 }
2384 }
2385 break;
2386
Craig Topper790d0fa2016-12-11 07:42:01 +00002387 case Intrinsic::x86_avx512_mask_add_ss_round:
2388 case Intrinsic::x86_avx512_mask_div_ss_round:
2389 case Intrinsic::x86_avx512_mask_mul_ss_round:
2390 case Intrinsic::x86_avx512_mask_sub_ss_round:
Craig Topper790d0fa2016-12-11 07:42:01 +00002391 case Intrinsic::x86_avx512_mask_add_sd_round:
2392 case Intrinsic::x86_avx512_mask_div_sd_round:
2393 case Intrinsic::x86_avx512_mask_mul_sd_round:
2394 case Intrinsic::x86_avx512_mask_sub_sd_round:
Craig Topper7b788ada2016-12-26 06:33:19 +00002395 // If the rounding mode is CUR_DIRECTION(4) we can turn these into regular
2396 // IR operations.
2397 if (auto *R = dyn_cast<ConstantInt>(II->getArgOperand(4))) {
2398 if (R->getValue() == 4) {
Craig Topper7f8540b2016-12-27 01:56:30 +00002399 // Extract the element as scalars.
2400 Value *Arg0 = II->getArgOperand(0);
2401 Value *Arg1 = II->getArgOperand(1);
Craig Topperbb4069e2017-07-07 23:16:26 +00002402 Value *LHS = Builder.CreateExtractElement(Arg0, (uint64_t)0);
2403 Value *RHS = Builder.CreateExtractElement(Arg1, (uint64_t)0);
Craig Topper7b788ada2016-12-26 06:33:19 +00002404
Craig Topper7f8540b2016-12-27 01:56:30 +00002405 Value *V;
2406 switch (II->getIntrinsicID()) {
2407 default: llvm_unreachable("Case stmts out of sync!");
2408 case Intrinsic::x86_avx512_mask_add_ss_round:
2409 case Intrinsic::x86_avx512_mask_add_sd_round:
Craig Topperbb4069e2017-07-07 23:16:26 +00002410 V = Builder.CreateFAdd(LHS, RHS);
Craig Topper7f8540b2016-12-27 01:56:30 +00002411 break;
2412 case Intrinsic::x86_avx512_mask_sub_ss_round:
2413 case Intrinsic::x86_avx512_mask_sub_sd_round:
Craig Topperbb4069e2017-07-07 23:16:26 +00002414 V = Builder.CreateFSub(LHS, RHS);
Craig Topper7f8540b2016-12-27 01:56:30 +00002415 break;
2416 case Intrinsic::x86_avx512_mask_mul_ss_round:
2417 case Intrinsic::x86_avx512_mask_mul_sd_round:
Craig Topperbb4069e2017-07-07 23:16:26 +00002418 V = Builder.CreateFMul(LHS, RHS);
Craig Topper7f8540b2016-12-27 01:56:30 +00002419 break;
2420 case Intrinsic::x86_avx512_mask_div_ss_round:
2421 case Intrinsic::x86_avx512_mask_div_sd_round:
Craig Topperbb4069e2017-07-07 23:16:26 +00002422 V = Builder.CreateFDiv(LHS, RHS);
Craig Topper7f8540b2016-12-27 01:56:30 +00002423 break;
Craig Topper7b788ada2016-12-26 06:33:19 +00002424 }
Craig Topper7f8540b2016-12-27 01:56:30 +00002425
2426 // Handle the masking aspect of the intrinsic.
Craig Topper7f8540b2016-12-27 01:56:30 +00002427 Value *Mask = II->getArgOperand(3);
Craig Topper99163632016-12-30 23:06:28 +00002428 auto *C = dyn_cast<ConstantInt>(Mask);
2429 // We don't need a select if we know the mask bit is a 1.
2430 if (!C || !C->getValue()[0]) {
2431 // Cast the mask to an i1 vector and then extract the lowest element.
Craig Topperbb4069e2017-07-07 23:16:26 +00002432 auto *MaskTy = VectorType::get(Builder.getInt1Ty(),
Craig Topper7f8540b2016-12-27 01:56:30 +00002433 cast<IntegerType>(Mask->getType())->getBitWidth());
Craig Topperbb4069e2017-07-07 23:16:26 +00002434 Mask = Builder.CreateBitCast(Mask, MaskTy);
2435 Mask = Builder.CreateExtractElement(Mask, (uint64_t)0);
Craig Topper99163632016-12-30 23:06:28 +00002436 // Extract the lowest element from the passthru operand.
Craig Topperbb4069e2017-07-07 23:16:26 +00002437 Value *Passthru = Builder.CreateExtractElement(II->getArgOperand(2),
Craig Topper99163632016-12-30 23:06:28 +00002438 (uint64_t)0);
Craig Topperbb4069e2017-07-07 23:16:26 +00002439 V = Builder.CreateSelect(Mask, V, Passthru);
Craig Topper99163632016-12-30 23:06:28 +00002440 }
Craig Topper7f8540b2016-12-27 01:56:30 +00002441
2442 // Insert the result back into the original argument 0.
Craig Topperbb4069e2017-07-07 23:16:26 +00002443 V = Builder.CreateInsertElement(Arg0, V, (uint64_t)0);
Craig Topper7f8540b2016-12-27 01:56:30 +00002444
2445 return replaceInstUsesWith(*II, V);
Craig Topper7b788ada2016-12-26 06:33:19 +00002446 }
2447 }
2448 LLVM_FALLTHROUGH;
2449
2450 // X86 scalar intrinsics simplified with SimplifyDemandedVectorElts.
2451 case Intrinsic::x86_avx512_mask_max_ss_round:
2452 case Intrinsic::x86_avx512_mask_min_ss_round:
Craig Topper790d0fa2016-12-11 07:42:01 +00002453 case Intrinsic::x86_avx512_mask_max_sd_round:
Craig Topper268b3ab2016-12-14 06:06:58 +00002454 case Intrinsic::x86_avx512_mask_min_sd_round:
Craig Topperab5f3552016-12-15 03:49:45 +00002455 case Intrinsic::x86_avx512_mask_vfmadd_ss:
2456 case Intrinsic::x86_avx512_mask_vfmadd_sd:
2457 case Intrinsic::x86_avx512_maskz_vfmadd_ss:
2458 case Intrinsic::x86_avx512_maskz_vfmadd_sd:
2459 case Intrinsic::x86_avx512_mask3_vfmadd_ss:
2460 case Intrinsic::x86_avx512_mask3_vfmadd_sd:
2461 case Intrinsic::x86_avx512_mask3_vfmsub_ss:
2462 case Intrinsic::x86_avx512_mask3_vfmsub_sd:
2463 case Intrinsic::x86_avx512_mask3_vfnmsub_ss:
2464 case Intrinsic::x86_avx512_mask3_vfnmsub_sd:
Craig Topperdfd268d2016-12-14 05:43:05 +00002465 case Intrinsic::x86_fma_vfmadd_ss:
2466 case Intrinsic::x86_fma_vfmsub_ss:
2467 case Intrinsic::x86_fma_vfnmadd_ss:
2468 case Intrinsic::x86_fma_vfnmsub_ss:
2469 case Intrinsic::x86_fma_vfmadd_sd:
2470 case Intrinsic::x86_fma_vfmsub_sd:
2471 case Intrinsic::x86_fma_vfnmadd_sd:
2472 case Intrinsic::x86_fma_vfnmsub_sd:
Craig Toppera0372de2016-12-14 03:17:27 +00002473 case Intrinsic::x86_sse_cmp_ss:
2474 case Intrinsic::x86_sse_min_ss:
2475 case Intrinsic::x86_sse_max_ss:
2476 case Intrinsic::x86_sse2_cmp_sd:
2477 case Intrinsic::x86_sse2_min_sd:
2478 case Intrinsic::x86_sse2_max_sd:
Craig Toppereb6a20e2016-12-14 03:17:30 +00002479 case Intrinsic::x86_sse41_round_ss:
2480 case Intrinsic::x86_sse41_round_sd:
Craig Topperac75bca2016-12-13 07:45:45 +00002481 case Intrinsic::x86_xop_vfrcz_ss:
2482 case Intrinsic::x86_xop_vfrcz_sd: {
2483 unsigned VWidth = II->getType()->getVectorNumElements();
2484 APInt UndefElts(VWidth, 0);
2485 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
2486 if (Value *V = SimplifyDemandedVectorElts(II, AllOnesEltMask, UndefElts)) {
2487 if (V != II)
2488 return replaceInstUsesWith(*II, V);
2489 return II;
2490 }
2491 break;
2492 }
2493
Simon Pilgrima3a72b42015-08-10 20:21:15 +00002494 // Constant fold ashr( <A x Bi>, Ci ).
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00002495 // Constant fold lshr( <A x Bi>, Ci ).
2496 // Constant fold shl( <A x Bi>, Ci ).
Simon Pilgrima3a72b42015-08-10 20:21:15 +00002497 case Intrinsic::x86_sse2_psrai_d:
2498 case Intrinsic::x86_sse2_psrai_w:
Simon Pilgrima3a72b42015-08-10 20:21:15 +00002499 case Intrinsic::x86_avx2_psrai_d:
2500 case Intrinsic::x86_avx2_psrai_w:
Craig Topper8b831cb2016-11-13 01:51:55 +00002501 case Intrinsic::x86_avx512_psrai_q_128:
2502 case Intrinsic::x86_avx512_psrai_q_256:
2503 case Intrinsic::x86_avx512_psrai_d_512:
2504 case Intrinsic::x86_avx512_psrai_q_512:
2505 case Intrinsic::x86_avx512_psrai_w_512:
Simon Pilgrim18617d12015-08-05 08:18:00 +00002506 case Intrinsic::x86_sse2_psrli_d:
2507 case Intrinsic::x86_sse2_psrli_q:
2508 case Intrinsic::x86_sse2_psrli_w:
Simon Pilgrim18617d12015-08-05 08:18:00 +00002509 case Intrinsic::x86_avx2_psrli_d:
2510 case Intrinsic::x86_avx2_psrli_q:
2511 case Intrinsic::x86_avx2_psrli_w:
Craig Topper8b831cb2016-11-13 01:51:55 +00002512 case Intrinsic::x86_avx512_psrli_d_512:
2513 case Intrinsic::x86_avx512_psrli_q_512:
2514 case Intrinsic::x86_avx512_psrli_w_512:
Michael J. Spencerdee4b2c2014-04-24 00:58:18 +00002515 case Intrinsic::x86_sse2_pslli_d:
2516 case Intrinsic::x86_sse2_pslli_q:
2517 case Intrinsic::x86_sse2_pslli_w:
Simon Pilgrim18617d12015-08-05 08:18:00 +00002518 case Intrinsic::x86_avx2_pslli_d:
2519 case Intrinsic::x86_avx2_pslli_q:
2520 case Intrinsic::x86_avx2_pslli_w:
Craig Topper8b831cb2016-11-13 01:51:55 +00002521 case Intrinsic::x86_avx512_pslli_d_512:
2522 case Intrinsic::x86_avx512_pslli_q_512:
2523 case Intrinsic::x86_avx512_pslli_w_512:
Craig Topperbb4069e2017-07-07 23:16:26 +00002524 if (Value *V = simplifyX86immShift(*II, Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00002525 return replaceInstUsesWith(*II, V);
Simon Pilgrim18617d12015-08-05 08:18:00 +00002526 break;
2527
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00002528 case Intrinsic::x86_sse2_psra_d:
2529 case Intrinsic::x86_sse2_psra_w:
2530 case Intrinsic::x86_avx2_psra_d:
2531 case Intrinsic::x86_avx2_psra_w:
Craig Topper8b831cb2016-11-13 01:51:55 +00002532 case Intrinsic::x86_avx512_psra_q_128:
2533 case Intrinsic::x86_avx512_psra_q_256:
2534 case Intrinsic::x86_avx512_psra_d_512:
2535 case Intrinsic::x86_avx512_psra_q_512:
2536 case Intrinsic::x86_avx512_psra_w_512:
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00002537 case Intrinsic::x86_sse2_psrl_d:
2538 case Intrinsic::x86_sse2_psrl_q:
2539 case Intrinsic::x86_sse2_psrl_w:
2540 case Intrinsic::x86_avx2_psrl_d:
2541 case Intrinsic::x86_avx2_psrl_q:
2542 case Intrinsic::x86_avx2_psrl_w:
Craig Topper8b831cb2016-11-13 01:51:55 +00002543 case Intrinsic::x86_avx512_psrl_d_512:
2544 case Intrinsic::x86_avx512_psrl_q_512:
2545 case Intrinsic::x86_avx512_psrl_w_512:
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00002546 case Intrinsic::x86_sse2_psll_d:
2547 case Intrinsic::x86_sse2_psll_q:
2548 case Intrinsic::x86_sse2_psll_w:
2549 case Intrinsic::x86_avx2_psll_d:
2550 case Intrinsic::x86_avx2_psll_q:
Craig Topper8b831cb2016-11-13 01:51:55 +00002551 case Intrinsic::x86_avx2_psll_w:
2552 case Intrinsic::x86_avx512_psll_d_512:
2553 case Intrinsic::x86_avx512_psll_q_512:
2554 case Intrinsic::x86_avx512_psll_w_512: {
Craig Topperbb4069e2017-07-07 23:16:26 +00002555 if (Value *V = simplifyX86immShift(*II, Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00002556 return replaceInstUsesWith(*II, V);
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00002557
2558 // SSE2/AVX2 uses only the first 64-bits of the 128-bit vector
2559 // operand to compute the shift amount.
Simon Pilgrim996725e2015-09-19 11:41:53 +00002560 Value *Arg1 = II->getArgOperand(1);
2561 assert(Arg1->getType()->getPrimitiveSizeInBits() == 128 &&
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00002562 "Unexpected packed shift size");
Simon Pilgrim996725e2015-09-19 11:41:53 +00002563 unsigned VWidth = Arg1->getType()->getVectorNumElements();
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00002564
Simon Pilgrim996725e2015-09-19 11:41:53 +00002565 if (Value *V = SimplifyDemandedVectorEltsLow(Arg1, VWidth, VWidth / 2)) {
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00002566 II->setArgOperand(1, V);
2567 return II;
2568 }
2569 break;
2570 }
2571
Simon Pilgrimdb9893f2016-06-07 10:27:15 +00002572 case Intrinsic::x86_avx2_psllv_d:
2573 case Intrinsic::x86_avx2_psllv_d_256:
2574 case Intrinsic::x86_avx2_psllv_q:
2575 case Intrinsic::x86_avx2_psllv_q_256:
Craig Topperb4173a52016-11-13 07:26:19 +00002576 case Intrinsic::x86_avx512_psllv_d_512:
2577 case Intrinsic::x86_avx512_psllv_q_512:
Craig Topper1de753f2016-11-18 06:04:33 +00002578 case Intrinsic::x86_avx512_psllv_w_128:
2579 case Intrinsic::x86_avx512_psllv_w_256:
2580 case Intrinsic::x86_avx512_psllv_w_512:
Simon Pilgrimdb9893f2016-06-07 10:27:15 +00002581 case Intrinsic::x86_avx2_psrav_d:
2582 case Intrinsic::x86_avx2_psrav_d_256:
Craig Topperb4173a52016-11-13 07:26:19 +00002583 case Intrinsic::x86_avx512_psrav_q_128:
2584 case Intrinsic::x86_avx512_psrav_q_256:
2585 case Intrinsic::x86_avx512_psrav_d_512:
2586 case Intrinsic::x86_avx512_psrav_q_512:
Craig Topper1de753f2016-11-18 06:04:33 +00002587 case Intrinsic::x86_avx512_psrav_w_128:
2588 case Intrinsic::x86_avx512_psrav_w_256:
2589 case Intrinsic::x86_avx512_psrav_w_512:
Simon Pilgrimdb9893f2016-06-07 10:27:15 +00002590 case Intrinsic::x86_avx2_psrlv_d:
2591 case Intrinsic::x86_avx2_psrlv_d_256:
2592 case Intrinsic::x86_avx2_psrlv_q:
2593 case Intrinsic::x86_avx2_psrlv_q_256:
Craig Topperb4173a52016-11-13 07:26:19 +00002594 case Intrinsic::x86_avx512_psrlv_d_512:
2595 case Intrinsic::x86_avx512_psrlv_q_512:
Craig Topper1de753f2016-11-18 06:04:33 +00002596 case Intrinsic::x86_avx512_psrlv_w_128:
2597 case Intrinsic::x86_avx512_psrlv_w_256:
2598 case Intrinsic::x86_avx512_psrlv_w_512:
Craig Topperbb4069e2017-07-07 23:16:26 +00002599 if (Value *V = simplifyX86varShift(*II, Builder))
Simon Pilgrimdb9893f2016-06-07 10:27:15 +00002600 return replaceInstUsesWith(*II, V);
2601 break;
2602
Simon Pilgrim6f6b2792017-01-25 14:37:24 +00002603 case Intrinsic::x86_sse2_packssdw_128:
2604 case Intrinsic::x86_sse2_packsswb_128:
2605 case Intrinsic::x86_avx2_packssdw:
2606 case Intrinsic::x86_avx2_packsswb:
Craig Topper3731f4d2017-02-16 07:35:23 +00002607 case Intrinsic::x86_avx512_packssdw_512:
2608 case Intrinsic::x86_avx512_packsswb_512:
Craig Topper4853c432017-07-06 23:18:42 +00002609 if (Value *V = simplifyX86pack(*II, true))
Simon Pilgrim6f6b2792017-01-25 14:37:24 +00002610 return replaceInstUsesWith(*II, V);
2611 break;
2612
2613 case Intrinsic::x86_sse2_packuswb_128:
2614 case Intrinsic::x86_sse41_packusdw:
2615 case Intrinsic::x86_avx2_packusdw:
2616 case Intrinsic::x86_avx2_packuswb:
Craig Topper3731f4d2017-02-16 07:35:23 +00002617 case Intrinsic::x86_avx512_packusdw_512:
2618 case Intrinsic::x86_avx512_packuswb_512:
Craig Topper4853c432017-07-06 23:18:42 +00002619 if (Value *V = simplifyX86pack(*II, false))
Simon Pilgrim6f6b2792017-01-25 14:37:24 +00002620 return replaceInstUsesWith(*II, V);
2621 break;
2622
Craig Topperb6122122017-01-26 05:17:13 +00002623 case Intrinsic::x86_pclmulqdq: {
2624 if (auto *C = dyn_cast<ConstantInt>(II->getArgOperand(2))) {
2625 unsigned Imm = C->getZExtValue();
2626
2627 bool MadeChange = false;
2628 Value *Arg0 = II->getArgOperand(0);
2629 Value *Arg1 = II->getArgOperand(1);
2630 unsigned VWidth = Arg0->getType()->getVectorNumElements();
2631 APInt DemandedElts(VWidth, 0);
2632
2633 APInt UndefElts1(VWidth, 0);
2634 DemandedElts = (Imm & 0x01) ? 2 : 1;
2635 if (Value *V = SimplifyDemandedVectorElts(Arg0, DemandedElts,
2636 UndefElts1)) {
2637 II->setArgOperand(0, V);
2638 MadeChange = true;
2639 }
2640
2641 APInt UndefElts2(VWidth, 0);
2642 DemandedElts = (Imm & 0x10) ? 2 : 1;
2643 if (Value *V = SimplifyDemandedVectorElts(Arg1, DemandedElts,
2644 UndefElts2)) {
2645 II->setArgOperand(1, V);
2646 MadeChange = true;
2647 }
2648
2649 // If both input elements are undef, the result is undef.
2650 if (UndefElts1[(Imm & 0x01) ? 1 : 0] ||
2651 UndefElts2[(Imm & 0x10) ? 1 : 0])
2652 return replaceInstUsesWith(*II,
2653 ConstantAggregateZero::get(II->getType()));
2654
2655 if (MadeChange)
2656 return II;
2657 }
2658 break;
2659 }
2660
Sanjay Patelc86867c2015-04-16 17:52:13 +00002661 case Intrinsic::x86_sse41_insertps:
Craig Topperbb4069e2017-07-07 23:16:26 +00002662 if (Value *V = simplifyX86insertps(*II, Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00002663 return replaceInstUsesWith(*II, V);
Sanjay Patelc86867c2015-04-16 17:52:13 +00002664 break;
Simon Pilgrim54fcd622015-07-25 20:41:00 +00002665
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002666 case Intrinsic::x86_sse4a_extrq: {
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002667 Value *Op0 = II->getArgOperand(0);
2668 Value *Op1 = II->getArgOperand(1);
2669 unsigned VWidth0 = Op0->getType()->getVectorNumElements();
2670 unsigned VWidth1 = Op1->getType()->getVectorNumElements();
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002671 assert(Op0->getType()->getPrimitiveSizeInBits() == 128 &&
2672 Op1->getType()->getPrimitiveSizeInBits() == 128 && VWidth0 == 2 &&
2673 VWidth1 == 16 && "Unexpected operand sizes");
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002674
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002675 // See if we're dealing with constant values.
2676 Constant *C1 = dyn_cast<Constant>(Op1);
2677 ConstantInt *CILength =
Andrea Di Biagio8df5b9c2016-09-07 12:03:03 +00002678 C1 ? dyn_cast_or_null<ConstantInt>(C1->getAggregateElement((unsigned)0))
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002679 : nullptr;
2680 ConstantInt *CIIndex =
Andrea Di Biagio8df5b9c2016-09-07 12:03:03 +00002681 C1 ? dyn_cast_or_null<ConstantInt>(C1->getAggregateElement((unsigned)1))
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002682 : nullptr;
2683
2684 // Attempt to simplify to a constant, shuffle vector or EXTRQI call.
Craig Topperbb4069e2017-07-07 23:16:26 +00002685 if (Value *V = simplifyX86extrq(*II, Op0, CILength, CIIndex, Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00002686 return replaceInstUsesWith(*II, V);
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002687
2688 // EXTRQ only uses the lowest 64-bits of the first 128-bit vector
2689 // operands and the lowest 16-bits of the second.
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002690 bool MadeChange = false;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002691 if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth0, 1)) {
2692 II->setArgOperand(0, V);
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002693 MadeChange = true;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002694 }
2695 if (Value *V = SimplifyDemandedVectorEltsLow(Op1, VWidth1, 2)) {
2696 II->setArgOperand(1, V);
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002697 MadeChange = true;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002698 }
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002699 if (MadeChange)
2700 return II;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002701 break;
2702 }
2703
2704 case Intrinsic::x86_sse4a_extrqi: {
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002705 // EXTRQI: Extract Length bits starting from Index. Zero pad the remaining
2706 // bits of the lower 64-bits. The upper 64-bits are undefined.
2707 Value *Op0 = II->getArgOperand(0);
2708 unsigned VWidth = Op0->getType()->getVectorNumElements();
2709 assert(Op0->getType()->getPrimitiveSizeInBits() == 128 && VWidth == 2 &&
2710 "Unexpected operand size");
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002711
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002712 // See if we're dealing with constant values.
2713 ConstantInt *CILength = dyn_cast<ConstantInt>(II->getArgOperand(1));
2714 ConstantInt *CIIndex = dyn_cast<ConstantInt>(II->getArgOperand(2));
2715
2716 // Attempt to simplify to a constant or shuffle vector.
Craig Topperbb4069e2017-07-07 23:16:26 +00002717 if (Value *V = simplifyX86extrq(*II, Op0, CILength, CIIndex, Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00002718 return replaceInstUsesWith(*II, V);
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002719
2720 // EXTRQI only uses the lowest 64-bits of the first 128-bit vector
2721 // operand.
2722 if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth, 1)) {
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002723 II->setArgOperand(0, V);
2724 return II;
2725 }
2726 break;
2727 }
2728
2729 case Intrinsic::x86_sse4a_insertq: {
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002730 Value *Op0 = II->getArgOperand(0);
2731 Value *Op1 = II->getArgOperand(1);
2732 unsigned VWidth = Op0->getType()->getVectorNumElements();
2733 assert(Op0->getType()->getPrimitiveSizeInBits() == 128 &&
2734 Op1->getType()->getPrimitiveSizeInBits() == 128 && VWidth == 2 &&
2735 Op1->getType()->getVectorNumElements() == 2 &&
2736 "Unexpected operand size");
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002737
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002738 // See if we're dealing with constant values.
2739 Constant *C1 = dyn_cast<Constant>(Op1);
2740 ConstantInt *CI11 =
Andrea Di Biagiof3fd3162016-09-07 12:47:53 +00002741 C1 ? dyn_cast_or_null<ConstantInt>(C1->getAggregateElement((unsigned)1))
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002742 : nullptr;
2743
2744 // Attempt to simplify to a constant, shuffle vector or INSERTQI call.
2745 if (CI11) {
Benjamin Kramer46e38f32016-06-08 10:01:20 +00002746 const APInt &V11 = CI11->getValue();
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002747 APInt Len = V11.zextOrTrunc(6);
2748 APInt Idx = V11.lshr(8).zextOrTrunc(6);
Craig Topperbb4069e2017-07-07 23:16:26 +00002749 if (Value *V = simplifyX86insertq(*II, Op0, Op1, Len, Idx, Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00002750 return replaceInstUsesWith(*II, V);
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002751 }
2752
2753 // INSERTQ only uses the lowest 64-bits of the first 128-bit vector
2754 // operand.
2755 if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth, 1)) {
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002756 II->setArgOperand(0, V);
2757 return II;
2758 }
2759 break;
2760 }
2761
Filipe Cabecinhas1a805952014-04-24 00:38:14 +00002762 case Intrinsic::x86_sse4a_insertqi: {
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002763 // INSERTQI: Extract lowest Length bits from lower half of second source and
2764 // insert over first source starting at Index bit. The upper 64-bits are
2765 // undefined.
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002766 Value *Op0 = II->getArgOperand(0);
2767 Value *Op1 = II->getArgOperand(1);
2768 unsigned VWidth0 = Op0->getType()->getVectorNumElements();
2769 unsigned VWidth1 = Op1->getType()->getVectorNumElements();
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002770 assert(Op0->getType()->getPrimitiveSizeInBits() == 128 &&
2771 Op1->getType()->getPrimitiveSizeInBits() == 128 && VWidth0 == 2 &&
2772 VWidth1 == 2 && "Unexpected operand sizes");
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002773
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002774 // See if we're dealing with constant values.
2775 ConstantInt *CILength = dyn_cast<ConstantInt>(II->getArgOperand(2));
2776 ConstantInt *CIIndex = dyn_cast<ConstantInt>(II->getArgOperand(3));
2777
2778 // Attempt to simplify to a constant or shuffle vector.
2779 if (CILength && CIIndex) {
2780 APInt Len = CILength->getValue().zextOrTrunc(6);
2781 APInt Idx = CIIndex->getValue().zextOrTrunc(6);
Craig Topperbb4069e2017-07-07 23:16:26 +00002782 if (Value *V = simplifyX86insertq(*II, Op0, Op1, Len, Idx, Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00002783 return replaceInstUsesWith(*II, V);
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002784 }
2785
2786 // INSERTQI only uses the lowest 64-bits of the first two 128-bit vector
2787 // operands.
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002788 bool MadeChange = false;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002789 if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth0, 1)) {
2790 II->setArgOperand(0, V);
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002791 MadeChange = true;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002792 }
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002793 if (Value *V = SimplifyDemandedVectorEltsLow(Op1, VWidth1, 1)) {
2794 II->setArgOperand(1, V);
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002795 MadeChange = true;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002796 }
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002797 if (MadeChange)
2798 return II;
Filipe Cabecinhas1a805952014-04-24 00:38:14 +00002799 break;
2800 }
2801
Filipe Cabecinhas82ac07c2014-05-27 03:42:20 +00002802 case Intrinsic::x86_sse41_pblendvb:
2803 case Intrinsic::x86_sse41_blendvps:
2804 case Intrinsic::x86_sse41_blendvpd:
2805 case Intrinsic::x86_avx_blendv_ps_256:
2806 case Intrinsic::x86_avx_blendv_pd_256:
2807 case Intrinsic::x86_avx2_pblendvb: {
2808 // Convert blendv* to vector selects if the mask is constant.
2809 // This optimization is convoluted because the intrinsic is defined as
2810 // getting a vector of floats or doubles for the ps and pd versions.
2811 // FIXME: That should be changed.
Simon Pilgrim8c049d52015-08-12 08:08:56 +00002812
2813 Value *Op0 = II->getArgOperand(0);
2814 Value *Op1 = II->getArgOperand(1);
Filipe Cabecinhas82ac07c2014-05-27 03:42:20 +00002815 Value *Mask = II->getArgOperand(2);
Simon Pilgrim8c049d52015-08-12 08:08:56 +00002816
2817 // fold (blend A, A, Mask) -> A
2818 if (Op0 == Op1)
Sanjay Patel4b198802016-02-01 22:23:39 +00002819 return replaceInstUsesWith(CI, Op0);
Simon Pilgrim8c049d52015-08-12 08:08:56 +00002820
2821 // Zero Mask - select 1st argument.
Simon Pilgrim93f59f52015-08-12 08:23:36 +00002822 if (isa<ConstantAggregateZero>(Mask))
Sanjay Patel4b198802016-02-01 22:23:39 +00002823 return replaceInstUsesWith(CI, Op0);
Simon Pilgrim8c049d52015-08-12 08:08:56 +00002824
2825 // Constant Mask - select 1st/2nd argument lane based on top bit of mask.
Sanjay Patel368ac5d2016-02-21 17:29:33 +00002826 if (auto *ConstantMask = dyn_cast<ConstantDataVector>(Mask)) {
2827 Constant *NewSelector = getNegativeIsTrueBoolVec(ConstantMask);
Simon Pilgrim8c049d52015-08-12 08:08:56 +00002828 return SelectInst::Create(NewSelector, Op1, Op0, "blendv");
Filipe Cabecinhas82ac07c2014-05-27 03:42:20 +00002829 }
Simon Pilgrim8c049d52015-08-12 08:08:56 +00002830 break;
Filipe Cabecinhas82ac07c2014-05-27 03:42:20 +00002831 }
2832
Andrea Di Biagio0594e2a2015-09-30 16:44:39 +00002833 case Intrinsic::x86_ssse3_pshuf_b_128:
Simon Pilgrimc0c56e72016-04-24 17:00:34 +00002834 case Intrinsic::x86_avx2_pshuf_b:
Simon Pilgrima22c3a12017-01-18 13:44:04 +00002835 case Intrinsic::x86_avx512_pshuf_b_512:
Craig Topperbb4069e2017-07-07 23:16:26 +00002836 if (Value *V = simplifyX86pshufb(*II, Builder))
Simon Pilgrimc0c56e72016-04-24 17:00:34 +00002837 return replaceInstUsesWith(*II, V);
2838 break;
Andrea Di Biagio0594e2a2015-09-30 16:44:39 +00002839
Rafael Espindolabad3f772014-04-21 22:06:04 +00002840 case Intrinsic::x86_avx_vpermilvar_ps:
2841 case Intrinsic::x86_avx_vpermilvar_ps_256:
Craig Topper58917f32016-12-11 01:59:36 +00002842 case Intrinsic::x86_avx512_vpermilvar_ps_512:
Rafael Espindolabad3f772014-04-21 22:06:04 +00002843 case Intrinsic::x86_avx_vpermilvar_pd:
Simon Pilgrim2f6097d2016-04-24 17:23:46 +00002844 case Intrinsic::x86_avx_vpermilvar_pd_256:
Simon Pilgrima22c3a12017-01-18 13:44:04 +00002845 case Intrinsic::x86_avx512_vpermilvar_pd_512:
Craig Topperbb4069e2017-07-07 23:16:26 +00002846 if (Value *V = simplifyX86vpermilvar(*II, Builder))
Simon Pilgrim2f6097d2016-04-24 17:23:46 +00002847 return replaceInstUsesWith(*II, V);
2848 break;
Rafael Espindolabad3f772014-04-21 22:06:04 +00002849
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +00002850 case Intrinsic::x86_avx2_permd:
2851 case Intrinsic::x86_avx2_permps:
Craig Topperbb4069e2017-07-07 23:16:26 +00002852 if (Value *V = simplifyX86vpermv(*II, Builder))
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +00002853 return replaceInstUsesWith(*II, V);
2854 break;
2855
Craig Toppere3280452016-12-25 23:58:57 +00002856 case Intrinsic::x86_avx512_mask_permvar_df_256:
2857 case Intrinsic::x86_avx512_mask_permvar_df_512:
2858 case Intrinsic::x86_avx512_mask_permvar_di_256:
2859 case Intrinsic::x86_avx512_mask_permvar_di_512:
2860 case Intrinsic::x86_avx512_mask_permvar_hi_128:
2861 case Intrinsic::x86_avx512_mask_permvar_hi_256:
2862 case Intrinsic::x86_avx512_mask_permvar_hi_512:
2863 case Intrinsic::x86_avx512_mask_permvar_qi_128:
2864 case Intrinsic::x86_avx512_mask_permvar_qi_256:
2865 case Intrinsic::x86_avx512_mask_permvar_qi_512:
2866 case Intrinsic::x86_avx512_mask_permvar_sf_256:
2867 case Intrinsic::x86_avx512_mask_permvar_sf_512:
2868 case Intrinsic::x86_avx512_mask_permvar_si_256:
2869 case Intrinsic::x86_avx512_mask_permvar_si_512:
Craig Topperbb4069e2017-07-07 23:16:26 +00002870 if (Value *V = simplifyX86vpermv(*II, Builder)) {
Craig Toppere3280452016-12-25 23:58:57 +00002871 // We simplified the permuting, now create a select for the masking.
2872 V = emitX86MaskSelect(II->getArgOperand(3), V, II->getArgOperand(2),
Craig Topperbb4069e2017-07-07 23:16:26 +00002873 Builder);
Craig Toppere3280452016-12-25 23:58:57 +00002874 return replaceInstUsesWith(*II, V);
2875 }
2876 break;
2877
Sanjay Patel98a71502016-02-29 23:16:48 +00002878 case Intrinsic::x86_avx_maskload_ps:
Sanjay Patel6f2c01f2016-02-29 23:59:00 +00002879 case Intrinsic::x86_avx_maskload_pd:
2880 case Intrinsic::x86_avx_maskload_ps_256:
2881 case Intrinsic::x86_avx_maskload_pd_256:
2882 case Intrinsic::x86_avx2_maskload_d:
2883 case Intrinsic::x86_avx2_maskload_q:
2884 case Intrinsic::x86_avx2_maskload_d_256:
2885 case Intrinsic::x86_avx2_maskload_q_256:
Sanjay Patel98a71502016-02-29 23:16:48 +00002886 if (Instruction *I = simplifyX86MaskedLoad(*II, *this))
2887 return I;
2888 break;
2889
Sanjay Patelc4acbae2016-03-12 15:16:59 +00002890 case Intrinsic::x86_sse2_maskmov_dqu:
Sanjay Patel1ace9932016-02-26 21:04:14 +00002891 case Intrinsic::x86_avx_maskstore_ps:
2892 case Intrinsic::x86_avx_maskstore_pd:
2893 case Intrinsic::x86_avx_maskstore_ps_256:
2894 case Intrinsic::x86_avx_maskstore_pd_256:
Sanjay Patelfc7e7eb2016-02-26 21:51:44 +00002895 case Intrinsic::x86_avx2_maskstore_d:
2896 case Intrinsic::x86_avx2_maskstore_q:
2897 case Intrinsic::x86_avx2_maskstore_d_256:
2898 case Intrinsic::x86_avx2_maskstore_q_256:
Sanjay Patel1ace9932016-02-26 21:04:14 +00002899 if (simplifyX86MaskedStore(*II, *this))
2900 return nullptr;
2901 break;
2902
Simon Pilgrim1d1c56e22015-10-11 14:38:34 +00002903 case Intrinsic::x86_xop_vpcomb:
2904 case Intrinsic::x86_xop_vpcomd:
2905 case Intrinsic::x86_xop_vpcomq:
2906 case Intrinsic::x86_xop_vpcomw:
Craig Topperbb4069e2017-07-07 23:16:26 +00002907 if (Value *V = simplifyX86vpcom(*II, Builder, true))
Sanjay Patel4b198802016-02-01 22:23:39 +00002908 return replaceInstUsesWith(*II, V);
Simon Pilgrim1d1c56e22015-10-11 14:38:34 +00002909 break;
2910
2911 case Intrinsic::x86_xop_vpcomub:
2912 case Intrinsic::x86_xop_vpcomud:
2913 case Intrinsic::x86_xop_vpcomuq:
2914 case Intrinsic::x86_xop_vpcomuw:
Craig Topperbb4069e2017-07-07 23:16:26 +00002915 if (Value *V = simplifyX86vpcom(*II, Builder, false))
Sanjay Patel4b198802016-02-01 22:23:39 +00002916 return replaceInstUsesWith(*II, V);
Simon Pilgrim1d1c56e22015-10-11 14:38:34 +00002917 break;
2918
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002919 case Intrinsic::ppc_altivec_vperm:
2920 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
Bill Schmidta1184632014-06-05 19:46:04 +00002921 // Note that ppc_altivec_vperm has a big-endian bias, so when creating
2922 // a vectorshuffle for little endian, we must undo the transformation
2923 // performed on vec_perm in altivec.h. That is, we must complement
2924 // the permutation mask with respect to 31 and reverse the order of
2925 // V1 and V2.
Chris Lattner0256be92012-01-27 03:08:05 +00002926 if (Constant *Mask = dyn_cast<Constant>(II->getArgOperand(2))) {
2927 assert(Mask->getType()->getVectorNumElements() == 16 &&
2928 "Bad type for intrinsic!");
Jim Grosbach7815f562012-02-03 00:07:04 +00002929
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002930 // Check that all of the elements are integer constants or undefs.
2931 bool AllEltsOk = true;
2932 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0256be92012-01-27 03:08:05 +00002933 Constant *Elt = Mask->getAggregateElement(i);
Craig Topperf40110f2014-04-25 05:29:35 +00002934 if (!Elt || !(isa<ConstantInt>(Elt) || isa<UndefValue>(Elt))) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002935 AllEltsOk = false;
2936 break;
2937 }
2938 }
Jim Grosbach7815f562012-02-03 00:07:04 +00002939
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002940 if (AllEltsOk) {
2941 // Cast the input vectors to byte vectors.
Craig Topperbb4069e2017-07-07 23:16:26 +00002942 Value *Op0 = Builder.CreateBitCast(II->getArgOperand(0),
2943 Mask->getType());
2944 Value *Op1 = Builder.CreateBitCast(II->getArgOperand(1),
2945 Mask->getType());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002946 Value *Result = UndefValue::get(Op0->getType());
Jim Grosbach7815f562012-02-03 00:07:04 +00002947
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002948 // Only extract each element once.
2949 Value *ExtractedElts[32];
2950 memset(ExtractedElts, 0, sizeof(ExtractedElts));
Jim Grosbach7815f562012-02-03 00:07:04 +00002951
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002952 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0256be92012-01-27 03:08:05 +00002953 if (isa<UndefValue>(Mask->getAggregateElement(i)))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002954 continue;
Jim Grosbach7815f562012-02-03 00:07:04 +00002955 unsigned Idx =
Chris Lattner0256be92012-01-27 03:08:05 +00002956 cast<ConstantInt>(Mask->getAggregateElement(i))->getZExtValue();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002957 Idx &= 31; // Match the hardware behavior.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002958 if (DL.isLittleEndian())
Bill Schmidta1184632014-06-05 19:46:04 +00002959 Idx = 31 - Idx;
Jim Grosbach7815f562012-02-03 00:07:04 +00002960
Craig Topperf40110f2014-04-25 05:29:35 +00002961 if (!ExtractedElts[Idx]) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002962 Value *Op0ToUse = (DL.isLittleEndian()) ? Op1 : Op0;
2963 Value *Op1ToUse = (DL.isLittleEndian()) ? Op0 : Op1;
Jim Grosbach7815f562012-02-03 00:07:04 +00002964 ExtractedElts[Idx] =
Craig Topperbb4069e2017-07-07 23:16:26 +00002965 Builder.CreateExtractElement(Idx < 16 ? Op0ToUse : Op1ToUse,
2966 Builder.getInt32(Idx&15));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002967 }
Jim Grosbach7815f562012-02-03 00:07:04 +00002968
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002969 // Insert this value into the result vector.
Craig Topperbb4069e2017-07-07 23:16:26 +00002970 Result = Builder.CreateInsertElement(Result, ExtractedElts[Idx],
2971 Builder.getInt32(i));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002972 }
2973 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
2974 }
2975 }
2976 break;
2977
Bob Wilsona4e231c2010-10-22 21:41:48 +00002978 case Intrinsic::arm_neon_vld1:
2979 case Intrinsic::arm_neon_vld2:
2980 case Intrinsic::arm_neon_vld3:
2981 case Intrinsic::arm_neon_vld4:
2982 case Intrinsic::arm_neon_vld2lane:
2983 case Intrinsic::arm_neon_vld3lane:
2984 case Intrinsic::arm_neon_vld4lane:
2985 case Intrinsic::arm_neon_vst1:
2986 case Intrinsic::arm_neon_vst2:
2987 case Intrinsic::arm_neon_vst3:
2988 case Intrinsic::arm_neon_vst4:
2989 case Intrinsic::arm_neon_vst2lane:
2990 case Intrinsic::arm_neon_vst3lane:
2991 case Intrinsic::arm_neon_vst4lane: {
Justin Bogner99798402016-08-05 01:06:44 +00002992 unsigned MemAlign =
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002993 getKnownAlignment(II->getArgOperand(0), DL, II, &AC, &DT);
Bob Wilsona4e231c2010-10-22 21:41:48 +00002994 unsigned AlignArg = II->getNumArgOperands() - 1;
2995 ConstantInt *IntrAlign = dyn_cast<ConstantInt>(II->getArgOperand(AlignArg));
2996 if (IntrAlign && IntrAlign->getZExtValue() < MemAlign) {
2997 II->setArgOperand(AlignArg,
2998 ConstantInt::get(Type::getInt32Ty(II->getContext()),
2999 MemAlign, false));
3000 return II;
3001 }
3002 break;
3003 }
3004
Lang Hames3a90fab2012-05-01 00:20:38 +00003005 case Intrinsic::arm_neon_vmulls:
Tim Northover00ed9962014-03-29 10:18:08 +00003006 case Intrinsic::arm_neon_vmullu:
Tim Northover3b0846e2014-05-24 12:50:23 +00003007 case Intrinsic::aarch64_neon_smull:
3008 case Intrinsic::aarch64_neon_umull: {
Lang Hames3a90fab2012-05-01 00:20:38 +00003009 Value *Arg0 = II->getArgOperand(0);
3010 Value *Arg1 = II->getArgOperand(1);
3011
3012 // Handle mul by zero first:
3013 if (isa<ConstantAggregateZero>(Arg0) || isa<ConstantAggregateZero>(Arg1)) {
Sanjay Patel4b198802016-02-01 22:23:39 +00003014 return replaceInstUsesWith(CI, ConstantAggregateZero::get(II->getType()));
Lang Hames3a90fab2012-05-01 00:20:38 +00003015 }
3016
3017 // Check for constant LHS & RHS - in this case we just simplify.
Tim Northover00ed9962014-03-29 10:18:08 +00003018 bool Zext = (II->getIntrinsicID() == Intrinsic::arm_neon_vmullu ||
Tim Northover3b0846e2014-05-24 12:50:23 +00003019 II->getIntrinsicID() == Intrinsic::aarch64_neon_umull);
Lang Hames3a90fab2012-05-01 00:20:38 +00003020 VectorType *NewVT = cast<VectorType>(II->getType());
Benjamin Kramer92040952014-02-13 18:23:24 +00003021 if (Constant *CV0 = dyn_cast<Constant>(Arg0)) {
3022 if (Constant *CV1 = dyn_cast<Constant>(Arg1)) {
3023 CV0 = ConstantExpr::getIntegerCast(CV0, NewVT, /*isSigned=*/!Zext);
3024 CV1 = ConstantExpr::getIntegerCast(CV1, NewVT, /*isSigned=*/!Zext);
3025
Sanjay Patel4b198802016-02-01 22:23:39 +00003026 return replaceInstUsesWith(CI, ConstantExpr::getMul(CV0, CV1));
Lang Hames3a90fab2012-05-01 00:20:38 +00003027 }
3028
Alp Tokercb402912014-01-24 17:20:08 +00003029 // Couldn't simplify - canonicalize constant to the RHS.
Lang Hames3a90fab2012-05-01 00:20:38 +00003030 std::swap(Arg0, Arg1);
3031 }
3032
3033 // Handle mul by one:
Benjamin Kramer92040952014-02-13 18:23:24 +00003034 if (Constant *CV1 = dyn_cast<Constant>(Arg1))
Lang Hames3a90fab2012-05-01 00:20:38 +00003035 if (ConstantInt *Splat =
Benjamin Kramer92040952014-02-13 18:23:24 +00003036 dyn_cast_or_null<ConstantInt>(CV1->getSplatValue()))
3037 if (Splat->isOne())
3038 return CastInst::CreateIntegerCast(Arg0, II->getType(),
3039 /*isSigned=*/!Zext);
Lang Hames3a90fab2012-05-01 00:20:38 +00003040
3041 break;
3042 }
Matt Arsenaultbef34e22016-01-22 21:30:34 +00003043 case Intrinsic::amdgcn_rcp: {
Matt Arsenault4c7795d2017-03-24 19:04:57 +00003044 Value *Src = II->getArgOperand(0);
3045
3046 // TODO: Move to ConstantFolding/InstSimplify?
3047 if (isa<UndefValue>(Src))
3048 return replaceInstUsesWith(CI, Src);
3049
3050 if (const ConstantFP *C = dyn_cast<ConstantFP>(Src)) {
Matt Arsenaulta0050b02014-06-19 01:19:19 +00003051 const APFloat &ArgVal = C->getValueAPF();
3052 APFloat Val(ArgVal.getSemantics(), 1.0);
3053 APFloat::opStatus Status = Val.divide(ArgVal,
3054 APFloat::rmNearestTiesToEven);
3055 // Only do this if it was exact and therefore not dependent on the
3056 // rounding mode.
3057 if (Status == APFloat::opOK)
Sanjay Patel4b198802016-02-01 22:23:39 +00003058 return replaceInstUsesWith(CI, ConstantFP::get(II->getContext(), Val));
Matt Arsenaulta0050b02014-06-19 01:19:19 +00003059 }
3060
3061 break;
3062 }
Matt Arsenault4c7795d2017-03-24 19:04:57 +00003063 case Intrinsic::amdgcn_rsq: {
3064 Value *Src = II->getArgOperand(0);
3065
3066 // TODO: Move to ConstantFolding/InstSimplify?
3067 if (isa<UndefValue>(Src))
3068 return replaceInstUsesWith(CI, Src);
3069 break;
3070 }
Matt Arsenault2fe4fbc2016-03-30 22:28:52 +00003071 case Intrinsic::amdgcn_frexp_mant:
3072 case Intrinsic::amdgcn_frexp_exp: {
Matt Arsenault5cd4f8f2016-03-30 22:28:26 +00003073 Value *Src = II->getArgOperand(0);
3074 if (const ConstantFP *C = dyn_cast<ConstantFP>(Src)) {
3075 int Exp;
3076 APFloat Significand = frexp(C->getValueAPF(), Exp,
3077 APFloat::rmNearestTiesToEven);
3078
Matt Arsenault2fe4fbc2016-03-30 22:28:52 +00003079 if (II->getIntrinsicID() == Intrinsic::amdgcn_frexp_mant) {
3080 return replaceInstUsesWith(CI, ConstantFP::get(II->getContext(),
3081 Significand));
3082 }
3083
3084 // Match instruction special case behavior.
3085 if (Exp == APFloat::IEK_NaN || Exp == APFloat::IEK_Inf)
3086 Exp = 0;
3087
3088 return replaceInstUsesWith(CI, ConstantInt::get(II->getType(), Exp));
3089 }
3090
3091 if (isa<UndefValue>(Src))
3092 return replaceInstUsesWith(CI, UndefValue::get(II->getType()));
Matt Arsenault5cd4f8f2016-03-30 22:28:26 +00003093
3094 break;
3095 }
Matt Arsenault46a03822016-09-03 07:06:58 +00003096 case Intrinsic::amdgcn_class: {
3097 enum {
3098 S_NAN = 1 << 0, // Signaling NaN
3099 Q_NAN = 1 << 1, // Quiet NaN
3100 N_INFINITY = 1 << 2, // Negative infinity
3101 N_NORMAL = 1 << 3, // Negative normal
3102 N_SUBNORMAL = 1 << 4, // Negative subnormal
3103 N_ZERO = 1 << 5, // Negative zero
3104 P_ZERO = 1 << 6, // Positive zero
3105 P_SUBNORMAL = 1 << 7, // Positive subnormal
3106 P_NORMAL = 1 << 8, // Positive normal
3107 P_INFINITY = 1 << 9 // Positive infinity
3108 };
3109
3110 const uint32_t FullMask = S_NAN | Q_NAN | N_INFINITY | N_NORMAL |
3111 N_SUBNORMAL | N_ZERO | P_ZERO | P_SUBNORMAL | P_NORMAL | P_INFINITY;
3112
3113 Value *Src0 = II->getArgOperand(0);
3114 Value *Src1 = II->getArgOperand(1);
3115 const ConstantInt *CMask = dyn_cast<ConstantInt>(Src1);
3116 if (!CMask) {
3117 if (isa<UndefValue>(Src0))
3118 return replaceInstUsesWith(*II, UndefValue::get(II->getType()));
3119
3120 if (isa<UndefValue>(Src1))
3121 return replaceInstUsesWith(*II, ConstantInt::get(II->getType(), false));
3122 break;
3123 }
3124
3125 uint32_t Mask = CMask->getZExtValue();
3126
3127 // If all tests are made, it doesn't matter what the value is.
3128 if ((Mask & FullMask) == FullMask)
3129 return replaceInstUsesWith(*II, ConstantInt::get(II->getType(), true));
3130
3131 if ((Mask & FullMask) == 0)
3132 return replaceInstUsesWith(*II, ConstantInt::get(II->getType(), false));
3133
3134 if (Mask == (S_NAN | Q_NAN)) {
3135 // Equivalent of isnan. Replace with standard fcmp.
Craig Topperbb4069e2017-07-07 23:16:26 +00003136 Value *FCmp = Builder.CreateFCmpUNO(Src0, Src0);
Matt Arsenault46a03822016-09-03 07:06:58 +00003137 FCmp->takeName(II);
3138 return replaceInstUsesWith(*II, FCmp);
3139 }
3140
3141 const ConstantFP *CVal = dyn_cast<ConstantFP>(Src0);
3142 if (!CVal) {
3143 if (isa<UndefValue>(Src0))
3144 return replaceInstUsesWith(*II, UndefValue::get(II->getType()));
3145
3146 // Clamp mask to used bits
3147 if ((Mask & FullMask) != Mask) {
Craig Topperbb4069e2017-07-07 23:16:26 +00003148 CallInst *NewCall = Builder.CreateCall(II->getCalledFunction(),
Matt Arsenault46a03822016-09-03 07:06:58 +00003149 { Src0, ConstantInt::get(Src1->getType(), Mask & FullMask) }
3150 );
3151
3152 NewCall->takeName(II);
3153 return replaceInstUsesWith(*II, NewCall);
3154 }
3155
3156 break;
3157 }
3158
3159 const APFloat &Val = CVal->getValueAPF();
3160
3161 bool Result =
3162 ((Mask & S_NAN) && Val.isNaN() && Val.isSignaling()) ||
3163 ((Mask & Q_NAN) && Val.isNaN() && !Val.isSignaling()) ||
3164 ((Mask & N_INFINITY) && Val.isInfinity() && Val.isNegative()) ||
3165 ((Mask & N_NORMAL) && Val.isNormal() && Val.isNegative()) ||
3166 ((Mask & N_SUBNORMAL) && Val.isDenormal() && Val.isNegative()) ||
3167 ((Mask & N_ZERO) && Val.isZero() && Val.isNegative()) ||
3168 ((Mask & P_ZERO) && Val.isZero() && !Val.isNegative()) ||
3169 ((Mask & P_SUBNORMAL) && Val.isDenormal() && !Val.isNegative()) ||
3170 ((Mask & P_NORMAL) && Val.isNormal() && !Val.isNegative()) ||
3171 ((Mask & P_INFINITY) && Val.isInfinity() && !Val.isNegative());
3172
3173 return replaceInstUsesWith(*II, ConstantInt::get(II->getType(), Result));
3174 }
Matt Arsenault1f17c662017-02-22 00:27:34 +00003175 case Intrinsic::amdgcn_cvt_pkrtz: {
3176 Value *Src0 = II->getArgOperand(0);
3177 Value *Src1 = II->getArgOperand(1);
3178 if (const ConstantFP *C0 = dyn_cast<ConstantFP>(Src0)) {
3179 if (const ConstantFP *C1 = dyn_cast<ConstantFP>(Src1)) {
3180 const fltSemantics &HalfSem
3181 = II->getType()->getScalarType()->getFltSemantics();
3182 bool LosesInfo;
3183 APFloat Val0 = C0->getValueAPF();
3184 APFloat Val1 = C1->getValueAPF();
3185 Val0.convert(HalfSem, APFloat::rmTowardZero, &LosesInfo);
3186 Val1.convert(HalfSem, APFloat::rmTowardZero, &LosesInfo);
3187
3188 Constant *Folded = ConstantVector::get({
3189 ConstantFP::get(II->getContext(), Val0),
3190 ConstantFP::get(II->getContext(), Val1) });
3191 return replaceInstUsesWith(*II, Folded);
3192 }
3193 }
3194
3195 if (isa<UndefValue>(Src0) && isa<UndefValue>(Src1))
3196 return replaceInstUsesWith(*II, UndefValue::get(II->getType()));
3197
3198 break;
3199 }
Marek Olsak13e47412018-01-31 20:18:04 +00003200 case Intrinsic::amdgcn_cvt_pknorm_i16:
3201 case Intrinsic::amdgcn_cvt_pknorm_u16:
3202 case Intrinsic::amdgcn_cvt_pk_i16:
3203 case Intrinsic::amdgcn_cvt_pk_u16: {
3204 Value *Src0 = II->getArgOperand(0);
3205 Value *Src1 = II->getArgOperand(1);
3206
3207 if (isa<UndefValue>(Src0) && isa<UndefValue>(Src1))
3208 return replaceInstUsesWith(*II, UndefValue::get(II->getType()));
3209
3210 break;
3211 }
Matt Arsenaultf5262252017-02-22 23:04:58 +00003212 case Intrinsic::amdgcn_ubfe:
3213 case Intrinsic::amdgcn_sbfe: {
3214 // Decompose simple cases into standard shifts.
3215 Value *Src = II->getArgOperand(0);
3216 if (isa<UndefValue>(Src))
3217 return replaceInstUsesWith(*II, Src);
3218
3219 unsigned Width;
3220 Type *Ty = II->getType();
3221 unsigned IntSize = Ty->getIntegerBitWidth();
3222
3223 ConstantInt *CWidth = dyn_cast<ConstantInt>(II->getArgOperand(2));
3224 if (CWidth) {
3225 Width = CWidth->getZExtValue();
3226 if ((Width & (IntSize - 1)) == 0)
3227 return replaceInstUsesWith(*II, ConstantInt::getNullValue(Ty));
3228
3229 if (Width >= IntSize) {
3230 // Hardware ignores high bits, so remove those.
3231 II->setArgOperand(2, ConstantInt::get(CWidth->getType(),
3232 Width & (IntSize - 1)));
3233 return II;
3234 }
3235 }
3236
3237 unsigned Offset;
3238 ConstantInt *COffset = dyn_cast<ConstantInt>(II->getArgOperand(1));
3239 if (COffset) {
3240 Offset = COffset->getZExtValue();
3241 if (Offset >= IntSize) {
3242 II->setArgOperand(1, ConstantInt::get(COffset->getType(),
3243 Offset & (IntSize - 1)));
3244 return II;
3245 }
3246 }
3247
3248 bool Signed = II->getIntrinsicID() == Intrinsic::amdgcn_sbfe;
3249
3250 // TODO: Also emit sub if only width is constant.
3251 if (!CWidth && COffset && Offset == 0) {
3252 Constant *KSize = ConstantInt::get(COffset->getType(), IntSize);
Craig Topperbb4069e2017-07-07 23:16:26 +00003253 Value *ShiftVal = Builder.CreateSub(KSize, II->getArgOperand(2));
3254 ShiftVal = Builder.CreateZExt(ShiftVal, II->getType());
Matt Arsenaultf5262252017-02-22 23:04:58 +00003255
Craig Topperbb4069e2017-07-07 23:16:26 +00003256 Value *Shl = Builder.CreateShl(Src, ShiftVal);
3257 Value *RightShift = Signed ? Builder.CreateAShr(Shl, ShiftVal)
3258 : Builder.CreateLShr(Shl, ShiftVal);
Matt Arsenaultf5262252017-02-22 23:04:58 +00003259 RightShift->takeName(II);
3260 return replaceInstUsesWith(*II, RightShift);
3261 }
3262
3263 if (!CWidth || !COffset)
3264 break;
3265
3266 // TODO: This allows folding to undef when the hardware has specific
3267 // behavior?
3268 if (Offset + Width < IntSize) {
Craig Topperbb4069e2017-07-07 23:16:26 +00003269 Value *Shl = Builder.CreateShl(Src, IntSize - Offset - Width);
3270 Value *RightShift = Signed ? Builder.CreateAShr(Shl, IntSize - Width)
3271 : Builder.CreateLShr(Shl, IntSize - Width);
Matt Arsenaultf5262252017-02-22 23:04:58 +00003272 RightShift->takeName(II);
3273 return replaceInstUsesWith(*II, RightShift);
3274 }
3275
Craig Topperbb4069e2017-07-07 23:16:26 +00003276 Value *RightShift = Signed ? Builder.CreateAShr(Src, Offset)
3277 : Builder.CreateLShr(Src, Offset);
Matt Arsenaultf5262252017-02-22 23:04:58 +00003278
3279 RightShift->takeName(II);
3280 return replaceInstUsesWith(*II, RightShift);
3281 }
Matt Arsenaultd4bca1e2017-02-23 00:44:03 +00003282 case Intrinsic::amdgcn_exp:
3283 case Intrinsic::amdgcn_exp_compr: {
3284 ConstantInt *En = dyn_cast<ConstantInt>(II->getArgOperand(1));
3285 if (!En) // Illegal.
3286 break;
3287
3288 unsigned EnBits = En->getZExtValue();
3289 if (EnBits == 0xf)
3290 break; // All inputs enabled.
3291
3292 bool IsCompr = II->getIntrinsicID() == Intrinsic::amdgcn_exp_compr;
3293 bool Changed = false;
3294 for (int I = 0; I < (IsCompr ? 2 : 4); ++I) {
3295 if ((!IsCompr && (EnBits & (1 << I)) == 0) ||
3296 (IsCompr && ((EnBits & (0x3 << (2 * I))) == 0))) {
3297 Value *Src = II->getArgOperand(I + 2);
3298 if (!isa<UndefValue>(Src)) {
3299 II->setArgOperand(I + 2, UndefValue::get(Src->getType()));
3300 Changed = true;
3301 }
3302 }
3303 }
3304
3305 if (Changed)
3306 return II;
3307
3308 break;
Matt Arsenaultcdb468c2017-02-27 23:08:49 +00003309 }
3310 case Intrinsic::amdgcn_fmed3: {
3311 // Note this does not preserve proper sNaN behavior if IEEE-mode is enabled
3312 // for the shader.
3313
3314 Value *Src0 = II->getArgOperand(0);
3315 Value *Src1 = II->getArgOperand(1);
3316 Value *Src2 = II->getArgOperand(2);
3317
3318 bool Swap = false;
3319 // Canonicalize constants to RHS operands.
3320 //
3321 // fmed3(c0, x, c1) -> fmed3(x, c0, c1)
3322 if (isa<Constant>(Src0) && !isa<Constant>(Src1)) {
3323 std::swap(Src0, Src1);
3324 Swap = true;
3325 }
3326
3327 if (isa<Constant>(Src1) && !isa<Constant>(Src2)) {
3328 std::swap(Src1, Src2);
3329 Swap = true;
3330 }
3331
3332 if (isa<Constant>(Src0) && !isa<Constant>(Src1)) {
3333 std::swap(Src0, Src1);
3334 Swap = true;
3335 }
3336
3337 if (Swap) {
3338 II->setArgOperand(0, Src0);
3339 II->setArgOperand(1, Src1);
3340 II->setArgOperand(2, Src2);
3341 return II;
3342 }
3343
3344 if (match(Src2, m_NaN()) || isa<UndefValue>(Src2)) {
Craig Topperbb4069e2017-07-07 23:16:26 +00003345 CallInst *NewCall = Builder.CreateMinNum(Src0, Src1);
Matt Arsenaultcdb468c2017-02-27 23:08:49 +00003346 NewCall->copyFastMathFlags(II);
3347 NewCall->takeName(II);
3348 return replaceInstUsesWith(*II, NewCall);
3349 }
3350
3351 if (const ConstantFP *C0 = dyn_cast<ConstantFP>(Src0)) {
3352 if (const ConstantFP *C1 = dyn_cast<ConstantFP>(Src1)) {
3353 if (const ConstantFP *C2 = dyn_cast<ConstantFP>(Src2)) {
3354 APFloat Result = fmed3AMDGCN(C0->getValueAPF(), C1->getValueAPF(),
3355 C2->getValueAPF());
3356 return replaceInstUsesWith(*II,
Craig Topperbb4069e2017-07-07 23:16:26 +00003357 ConstantFP::get(Builder.getContext(), Result));
Matt Arsenaultcdb468c2017-02-27 23:08:49 +00003358 }
3359 }
3360 }
3361
3362 break;
Matt Arsenaultd4bca1e2017-02-23 00:44:03 +00003363 }
Matt Arsenaultd81f5572017-03-13 18:14:02 +00003364 case Intrinsic::amdgcn_icmp:
3365 case Intrinsic::amdgcn_fcmp: {
3366 const ConstantInt *CC = dyn_cast<ConstantInt>(II->getArgOperand(2));
3367 if (!CC)
3368 break;
3369
3370 // Guard against invalid arguments.
3371 int64_t CCVal = CC->getZExtValue();
3372 bool IsInteger = II->getIntrinsicID() == Intrinsic::amdgcn_icmp;
3373 if ((IsInteger && (CCVal < CmpInst::FIRST_ICMP_PREDICATE ||
3374 CCVal > CmpInst::LAST_ICMP_PREDICATE)) ||
3375 (!IsInteger && (CCVal < CmpInst::FIRST_FCMP_PREDICATE ||
3376 CCVal > CmpInst::LAST_FCMP_PREDICATE)))
3377 break;
3378
3379 Value *Src0 = II->getArgOperand(0);
3380 Value *Src1 = II->getArgOperand(1);
3381
3382 if (auto *CSrc0 = dyn_cast<Constant>(Src0)) {
3383 if (auto *CSrc1 = dyn_cast<Constant>(Src1)) {
3384 Constant *CCmp = ConstantExpr::getCompare(CCVal, CSrc0, CSrc1);
Nicolai Haehnle9c661852017-04-24 17:08:43 +00003385 if (CCmp->isNullValue()) {
3386 return replaceInstUsesWith(
3387 *II, ConstantExpr::getSExt(CCmp, II->getType()));
3388 }
3389
3390 // The result of V_ICMP/V_FCMP assembly instructions (which this
3391 // intrinsic exposes) is one bit per thread, masked with the EXEC
3392 // register (which contains the bitmask of live threads). So a
3393 // comparison that always returns true is the same as a read of the
3394 // EXEC register.
3395 Value *NewF = Intrinsic::getDeclaration(
3396 II->getModule(), Intrinsic::read_register, II->getType());
3397 Metadata *MDArgs[] = {MDString::get(II->getContext(), "exec")};
3398 MDNode *MD = MDNode::get(II->getContext(), MDArgs);
3399 Value *Args[] = {MetadataAsValue::get(II->getContext(), MD)};
Craig Topperbb4069e2017-07-07 23:16:26 +00003400 CallInst *NewCall = Builder.CreateCall(NewF, Args);
Nicolai Haehnle9c661852017-04-24 17:08:43 +00003401 NewCall->addAttribute(AttributeList::FunctionIndex,
3402 Attribute::Convergent);
3403 NewCall->takeName(II);
3404 return replaceInstUsesWith(*II, NewCall);
Matt Arsenaultd81f5572017-03-13 18:14:02 +00003405 }
3406
3407 // Canonicalize constants to RHS.
3408 CmpInst::Predicate SwapPred
3409 = CmpInst::getSwappedPredicate(static_cast<CmpInst::Predicate>(CCVal));
3410 II->setArgOperand(0, Src1);
3411 II->setArgOperand(1, Src0);
3412 II->setArgOperand(2, ConstantInt::get(CC->getType(),
3413 static_cast<int>(SwapPred)));
3414 return II;
3415 }
3416
3417 if (CCVal != CmpInst::ICMP_EQ && CCVal != CmpInst::ICMP_NE)
3418 break;
3419
3420 // Canonicalize compare eq with true value to compare != 0
3421 // llvm.amdgcn.icmp(zext (i1 x), 1, eq)
3422 // -> llvm.amdgcn.icmp(zext (i1 x), 0, ne)
3423 // llvm.amdgcn.icmp(sext (i1 x), -1, eq)
3424 // -> llvm.amdgcn.icmp(sext (i1 x), 0, ne)
3425 Value *ExtSrc;
3426 if (CCVal == CmpInst::ICMP_EQ &&
3427 ((match(Src1, m_One()) && match(Src0, m_ZExt(m_Value(ExtSrc)))) ||
3428 (match(Src1, m_AllOnes()) && match(Src0, m_SExt(m_Value(ExtSrc))))) &&
3429 ExtSrc->getType()->isIntegerTy(1)) {
3430 II->setArgOperand(1, ConstantInt::getNullValue(Src1->getType()));
3431 II->setArgOperand(2, ConstantInt::get(CC->getType(), CmpInst::ICMP_NE));
3432 return II;
3433 }
3434
3435 CmpInst::Predicate SrcPred;
3436 Value *SrcLHS;
3437 Value *SrcRHS;
3438
3439 // Fold compare eq/ne with 0 from a compare result as the predicate to the
3440 // intrinsic. The typical use is a wave vote function in the library, which
3441 // will be fed from a user code condition compared with 0. Fold in the
3442 // redundant compare.
3443
3444 // llvm.amdgcn.icmp([sz]ext ([if]cmp pred a, b), 0, ne)
3445 // -> llvm.amdgcn.[if]cmp(a, b, pred)
3446 //
3447 // llvm.amdgcn.icmp([sz]ext ([if]cmp pred a, b), 0, eq)
3448 // -> llvm.amdgcn.[if]cmp(a, b, inv pred)
3449 if (match(Src1, m_Zero()) &&
3450 match(Src0,
3451 m_ZExtOrSExt(m_Cmp(SrcPred, m_Value(SrcLHS), m_Value(SrcRHS))))) {
3452 if (CCVal == CmpInst::ICMP_EQ)
3453 SrcPred = CmpInst::getInversePredicate(SrcPred);
3454
3455 Intrinsic::ID NewIID = CmpInst::isFPPredicate(SrcPred) ?
3456 Intrinsic::amdgcn_fcmp : Intrinsic::amdgcn_icmp;
3457
3458 Value *NewF = Intrinsic::getDeclaration(II->getModule(), NewIID,
3459 SrcLHS->getType());
3460 Value *Args[] = { SrcLHS, SrcRHS,
3461 ConstantInt::get(CC->getType(), SrcPred) };
Craig Topperbb4069e2017-07-07 23:16:26 +00003462 CallInst *NewCall = Builder.CreateCall(NewF, Args);
Matt Arsenaultd81f5572017-03-13 18:14:02 +00003463 NewCall->takeName(II);
3464 return replaceInstUsesWith(*II, NewCall);
3465 }
3466
3467 break;
3468 }
Marek Olsak2114fc32017-10-24 10:26:59 +00003469 case Intrinsic::amdgcn_wqm_vote: {
3470 // wqm_vote is identity when the argument is constant.
3471 if (!isa<Constant>(II->getArgOperand(0)))
3472 break;
3473
3474 return replaceInstUsesWith(*II, II->getArgOperand(0));
3475 }
Marek Olsakce76ea02017-10-24 10:27:13 +00003476 case Intrinsic::amdgcn_kill: {
3477 const ConstantInt *C = dyn_cast<ConstantInt>(II->getArgOperand(0));
3478 if (!C || !C->getZExtValue())
3479 break;
3480
3481 // amdgcn.kill(i1 1) is a no-op
3482 return eraseInstFromFunction(CI);
3483 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003484 case Intrinsic::stackrestore: {
3485 // If the save is right next to the restore, remove the restore. This can
3486 // happen when variable allocas are DCE'd.
Gabor Greif589a0b92010-06-24 12:58:35 +00003487 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getArgOperand(0))) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003488 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00003489 if (&*++SS->getIterator() == II)
Sanjay Patel4b198802016-02-01 22:23:39 +00003490 return eraseInstFromFunction(CI);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003491 }
3492 }
Jim Grosbach7815f562012-02-03 00:07:04 +00003493
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003494 // Scan down this block to see if there is another stack restore in the
3495 // same block without an intervening call/alloca.
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00003496 BasicBlock::iterator BI(II);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003497 TerminatorInst *TI = II->getParent()->getTerminator();
3498 bool CannotRemove = false;
3499 for (++BI; &*BI != TI; ++BI) {
Nuno Lopes55fff832012-06-21 15:45:28 +00003500 if (isa<AllocaInst>(BI)) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003501 CannotRemove = true;
3502 break;
3503 }
3504 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
3505 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
3506 // If there is a stackrestore below this one, remove this one.
3507 if (II->getIntrinsicID() == Intrinsic::stackrestore)
Sanjay Patel4b198802016-02-01 22:23:39 +00003508 return eraseInstFromFunction(CI);
Reid Kleckner892ae2e2016-02-27 00:53:54 +00003509
3510 // Bail if we cross over an intrinsic with side effects, such as
3511 // llvm.stacksave, llvm.read_register, or llvm.setjmp.
3512 if (II->mayHaveSideEffects()) {
3513 CannotRemove = true;
3514 break;
3515 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003516 } else {
3517 // If we found a non-intrinsic call, we can't remove the stack
3518 // restore.
3519 CannotRemove = true;
3520 break;
3521 }
3522 }
3523 }
Jim Grosbach7815f562012-02-03 00:07:04 +00003524
Bill Wendlingf891bf82011-07-31 06:30:59 +00003525 // If the stack restore is in a return, resume, or unwind block and if there
3526 // are no allocas or calls between the restore and the return, nuke the
3527 // restore.
Bill Wendlingd5d95b02012-02-06 21:16:41 +00003528 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<ResumeInst>(TI)))
Sanjay Patel4b198802016-02-01 22:23:39 +00003529 return eraseInstFromFunction(CI);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003530 break;
3531 }
Vitaly Bukaf0500b62016-07-28 22:50:48 +00003532 case Intrinsic::lifetime_start:
Vitaly Buka0ab23cf2016-07-28 22:59:03 +00003533 // Asan needs to poison memory to detect invalid access which is possible
3534 // even for empty lifetime range.
Evgeniy Stepanovc667c1f2017-12-09 00:21:41 +00003535 if (II->getFunction()->hasFnAttribute(Attribute::SanitizeAddress) ||
3536 II->getFunction()->hasFnAttribute(Attribute::SanitizeHWAddress))
Vitaly Buka0ab23cf2016-07-28 22:59:03 +00003537 break;
3538
Arnaud A. de Grandmaison333ef382016-05-10 09:24:49 +00003539 if (removeTriviallyEmptyRange(*II, Intrinsic::lifetime_start,
3540 Intrinsic::lifetime_end, *this))
3541 return nullptr;
Arnaud A. de Grandmaison849f3bf2015-10-01 14:54:31 +00003542 break;
Hal Finkelf5867a72014-07-25 21:45:17 +00003543 case Intrinsic::assume: {
David Majnemerfcc58112016-04-08 16:37:12 +00003544 Value *IIOperand = II->getArgOperand(0);
3545 // Remove an assume if it is immediately followed by an identical assume.
3546 if (match(II->getNextNode(),
3547 m_Intrinsic<Intrinsic::assume>(m_Specific(IIOperand))))
3548 return eraseInstFromFunction(CI);
3549
Hal Finkelf5867a72014-07-25 21:45:17 +00003550 // Canonicalize assume(a && b) -> assume(a); assume(b);
Hal Finkel74c2f352014-09-07 12:44:26 +00003551 // Note: New assumption intrinsics created here are registered by
3552 // the InstCombineIRInserter object.
David Majnemerfcc58112016-04-08 16:37:12 +00003553 Value *AssumeIntrinsic = II->getCalledValue(), *A, *B;
Hal Finkelf5867a72014-07-25 21:45:17 +00003554 if (match(IIOperand, m_And(m_Value(A), m_Value(B)))) {
Craig Topperbb4069e2017-07-07 23:16:26 +00003555 Builder.CreateCall(AssumeIntrinsic, A, II->getName());
3556 Builder.CreateCall(AssumeIntrinsic, B, II->getName());
Sanjay Patel4b198802016-02-01 22:23:39 +00003557 return eraseInstFromFunction(*II);
Hal Finkelf5867a72014-07-25 21:45:17 +00003558 }
3559 // assume(!(a || b)) -> assume(!a); assume(!b);
3560 if (match(IIOperand, m_Not(m_Or(m_Value(A), m_Value(B))))) {
Craig Topperbb4069e2017-07-07 23:16:26 +00003561 Builder.CreateCall(AssumeIntrinsic, Builder.CreateNot(A), II->getName());
3562 Builder.CreateCall(AssumeIntrinsic, Builder.CreateNot(B), II->getName());
Sanjay Patel4b198802016-02-01 22:23:39 +00003563 return eraseInstFromFunction(*II);
Hal Finkelf5867a72014-07-25 21:45:17 +00003564 }
Hal Finkel04a15612014-10-04 21:27:06 +00003565
Philip Reames66c6de62014-11-11 23:33:19 +00003566 // assume( (load addr) != null ) -> add 'nonnull' metadata to load
3567 // (if assume is valid at the load)
Sanjay Patelf0d1e7732017-01-03 22:25:31 +00003568 CmpInst::Predicate Pred;
3569 Instruction *LHS;
3570 if (match(IIOperand, m_ICmp(Pred, m_Instruction(LHS), m_Zero())) &&
3571 Pred == ICmpInst::ICMP_NE && LHS->getOpcode() == Instruction::Load &&
3572 LHS->getType()->isPointerTy() &&
3573 isValidAssumeForContext(II, LHS, &DT)) {
3574 MDNode *MD = MDNode::get(II->getContext(), None);
3575 LHS->setMetadata(LLVMContext::MD_nonnull, MD);
3576 return eraseInstFromFunction(*II);
3577
Chandler Carruth24969102015-02-10 08:07:32 +00003578 // TODO: apply nonnull return attributes to calls and invokes
Philip Reames66c6de62014-11-11 23:33:19 +00003579 // TODO: apply range metadata for range check patterns?
3580 }
Sanjay Patelf0d1e7732017-01-03 22:25:31 +00003581
Hal Finkel04a15612014-10-04 21:27:06 +00003582 // If there is a dominating assume with the same condition as this one,
3583 // then this one is redundant, and should be removed.
Craig Topperb45eabc2017-04-26 16:39:58 +00003584 KnownBits Known(1);
3585 computeKnownBits(IIOperand, Known, 0, II);
Craig Topperf0aeee02017-05-05 17:36:09 +00003586 if (Known.isAllOnes())
Sanjay Patel4b198802016-02-01 22:23:39 +00003587 return eraseInstFromFunction(*II);
Hal Finkel04a15612014-10-04 21:27:06 +00003588
Hal Finkel8a9a7832017-01-11 13:24:24 +00003589 // Update the cache of affected values for this assumption (we might be
3590 // here because we just simplified the condition).
3591 AC.updateAffectedValues(II);
Hal Finkelf5867a72014-07-25 21:45:17 +00003592 break;
3593 }
Philip Reames9db26ff2014-12-29 23:27:30 +00003594 case Intrinsic::experimental_gc_relocate: {
3595 // Translate facts known about a pointer before relocating into
3596 // facts about the relocate value, while being careful to
3597 // preserve relocation semantics.
Manuel Jacob83eefa62016-01-05 04:03:00 +00003598 Value *DerivedPtr = cast<GCRelocateInst>(II)->getDerivedPtr();
Philip Reames9db26ff2014-12-29 23:27:30 +00003599
3600 // Remove the relocation if unused, note that this check is required
3601 // to prevent the cases below from looping forever.
3602 if (II->use_empty())
Sanjay Patel4b198802016-02-01 22:23:39 +00003603 return eraseInstFromFunction(*II);
Philip Reames9db26ff2014-12-29 23:27:30 +00003604
3605 // Undef is undef, even after relocation.
3606 // TODO: provide a hook for this in GCStrategy. This is clearly legal for
3607 // most practical collectors, but there was discussion in the review thread
3608 // about whether it was legal for all possible collectors.
Philip Reamesea4d8e82016-02-09 21:09:22 +00003609 if (isa<UndefValue>(DerivedPtr))
3610 // Use undef of gc_relocate's type to replace it.
3611 return replaceInstUsesWith(*II, UndefValue::get(II->getType()));
Philip Reames9db26ff2014-12-29 23:27:30 +00003612
Philip Reamesea4d8e82016-02-09 21:09:22 +00003613 if (auto *PT = dyn_cast<PointerType>(II->getType())) {
3614 // The relocation of null will be null for most any collector.
3615 // TODO: provide a hook for this in GCStrategy. There might be some
3616 // weird collector this property does not hold for.
3617 if (isa<ConstantPointerNull>(DerivedPtr))
3618 // Use null-pointer of gc_relocate's type to replace it.
3619 return replaceInstUsesWith(*II, ConstantPointerNull::get(PT));
Simon Pilgrimc0c56e72016-04-24 17:00:34 +00003620
Philip Reamesea4d8e82016-02-09 21:09:22 +00003621 // isKnownNonNull -> nonnull attribute
Nuno Lopes404f1062017-09-09 18:23:11 +00003622 if (isKnownNonZero(DerivedPtr, DL, 0, &AC, II, &DT))
Reid Klecknerb5180542017-03-21 16:57:19 +00003623 II->addAttribute(AttributeList::ReturnIndex, Attribute::NonNull);
Ramkumar Ramachandra8fcb4982015-02-14 19:37:54 +00003624 }
Philip Reames9db26ff2014-12-29 23:27:30 +00003625
3626 // TODO: bitcast(relocate(p)) -> relocate(bitcast(p))
3627 // Canonicalize on the type from the uses to the defs
Ramkumar Ramachandra8fcb4982015-02-14 19:37:54 +00003628
Philip Reames9db26ff2014-12-29 23:27:30 +00003629 // TODO: relocate((gep p, C, C2, ...)) -> gep(relocate(p), C, C2, ...)
Philip Reamesea4d8e82016-02-09 21:09:22 +00003630 break;
Philip Reames9db26ff2014-12-29 23:27:30 +00003631 }
Artur Pilipenkoe812ca02017-01-25 14:12:12 +00003632
3633 case Intrinsic::experimental_guard: {
Philip Reames79e917d2018-05-09 22:56:32 +00003634 // Is this guard followed by another guard? We scan forward over a small
3635 // fixed window of instructions to handle common cases with conditions
3636 // computed between guards.
Sanjoy Dase0e57952017-02-01 16:34:55 +00003637 Instruction *NextInst = II->getNextNode();
Philip Reames79e917d2018-05-09 22:56:32 +00003638 for (int i = 0; i < GuardWideningWindow; i++) {
3639 // Note: Using context-free form to avoid compile time blow up
3640 if (!isSafeToSpeculativelyExecute(NextInst))
3641 break;
3642 NextInst = NextInst->getNextNode();
3643 }
Sanjoy Dase0e57952017-02-01 16:34:55 +00003644 Value *NextCond = nullptr;
3645 if (match(NextInst,
3646 m_Intrinsic<Intrinsic::experimental_guard>(m_Value(NextCond)))) {
3647 Value *CurrCond = II->getArgOperand(0);
Artur Pilipenkoe812ca02017-01-25 14:12:12 +00003648
Simon Pilgrim68168d12017-03-30 12:59:53 +00003649 // Remove a guard that it is immediately preceded by an identical guard.
Sanjoy Dase0e57952017-02-01 16:34:55 +00003650 if (CurrCond == NextCond)
3651 return eraseInstFromFunction(*NextInst);
3652
3653 // Otherwise canonicalize guard(a); guard(b) -> guard(a & b).
Philip Reames79e917d2018-05-09 22:56:32 +00003654 Instruction* MoveI = II->getNextNode();
3655 while (MoveI != NextInst) {
3656 auto *Temp = MoveI;
3657 MoveI = MoveI->getNextNode();
3658 Temp->moveBefore(II);
3659 }
Craig Topperbb4069e2017-07-07 23:16:26 +00003660 II->setArgOperand(0, Builder.CreateAnd(CurrCond, NextCond));
Sanjoy Dase0e57952017-02-01 16:34:55 +00003661 return eraseInstFromFunction(*NextInst);
3662 }
Artur Pilipenkoe812ca02017-01-25 14:12:12 +00003663 break;
3664 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003665 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003666 return visitCallSite(II);
3667}
3668
Davide Italianoaec46172017-01-31 18:09:05 +00003669// Fence instruction simplification
3670Instruction *InstCombiner::visitFenceInst(FenceInst &FI) {
3671 // Remove identical consecutive fences.
3672 if (auto *NFI = dyn_cast<FenceInst>(FI.getNextNode()))
3673 if (FI.isIdenticalTo(NFI))
3674 return eraseInstFromFunction(FI);
3675 return nullptr;
3676}
3677
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003678// InvokeInst simplification
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003679Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
3680 return visitCallSite(&II);
3681}
3682
Sanjay Patelcd4377c2016-01-20 22:24:38 +00003683/// If this cast does not affect the value passed through the varargs area, we
3684/// can eliminate the use of the cast.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003685static bool isSafeToEliminateVarargsCast(const CallSite CS,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003686 const DataLayout &DL,
3687 const CastInst *const CI,
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003688 const int ix) {
3689 if (!CI->isLosslessCast())
3690 return false;
3691
Philip Reames1a1bdb22014-12-02 18:50:36 +00003692 // If this is a GC intrinsic, avoid munging types. We need types for
3693 // statepoint reconstruction in SelectionDAG.
3694 // TODO: This is probably something which should be expanded to all
3695 // intrinsics since the entire point of intrinsics is that
3696 // they are understandable by the optimizer.
3697 if (isStatepoint(CS) || isGCRelocate(CS) || isGCResult(CS))
3698 return false;
3699
Reid Kleckner26af2ca2014-01-28 02:38:36 +00003700 // The size of ByVal or InAlloca arguments is derived from the type, so we
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003701 // can't change to a type with a different size. If the size were
3702 // passed explicitly we could avoid this check.
Reid Kleckner26af2ca2014-01-28 02:38:36 +00003703 if (!CS.isByValOrInAllocaArgument(ix))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003704 return true;
3705
Jim Grosbach7815f562012-02-03 00:07:04 +00003706 Type* SrcTy =
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003707 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
Chris Lattner229907c2011-07-18 04:54:35 +00003708 Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003709 if (!SrcTy->isSized() || !DstTy->isSized())
3710 return false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003711 if (DL.getTypeAllocSize(SrcTy) != DL.getTypeAllocSize(DstTy))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003712 return false;
3713 return true;
3714}
3715
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003716Instruction *InstCombiner::tryOptimizeCall(CallInst *CI) {
Craig Topperf40110f2014-04-25 05:29:35 +00003717 if (!CI->getCalledFunction()) return nullptr;
Eric Christophera7fb58f2010-03-06 10:50:38 +00003718
Chandler Carruthba4c5172015-01-21 11:23:40 +00003719 auto InstCombineRAUW = [this](Instruction *From, Value *With) {
Sanjay Patel4b198802016-02-01 22:23:39 +00003720 replaceInstUsesWith(*From, With);
Chandler Carruthba4c5172015-01-21 11:23:40 +00003721 };
Adam Nemetea06e6e2017-07-26 19:03:18 +00003722 LibCallSimplifier Simplifier(DL, &TLI, ORE, InstCombineRAUW);
Chandler Carruthba4c5172015-01-21 11:23:40 +00003723 if (Value *With = Simplifier.optimizeCall(CI)) {
Meador Ingee3f2b262012-11-30 04:05:06 +00003724 ++NumSimplified;
Sanjay Patel4b198802016-02-01 22:23:39 +00003725 return CI->use_empty() ? CI : replaceInstUsesWith(*CI, With);
Meador Ingee3f2b262012-11-30 04:05:06 +00003726 }
Meador Ingedf796f82012-10-13 16:45:24 +00003727
Craig Topperf40110f2014-04-25 05:29:35 +00003728 return nullptr;
Eric Christophera7fb58f2010-03-06 10:50:38 +00003729}
3730
Sanjay Patel6038d3e2016-01-29 23:27:03 +00003731static IntrinsicInst *findInitTrampolineFromAlloca(Value *TrampMem) {
Duncan Sandsa0984362011-09-06 13:37:06 +00003732 // Strip off at most one level of pointer casts, looking for an alloca. This
3733 // is good enough in practice and simpler than handling any number of casts.
3734 Value *Underlying = TrampMem->stripPointerCasts();
3735 if (Underlying != TrampMem &&
Chandler Carruthcdf47882014-03-09 03:16:01 +00003736 (!Underlying->hasOneUse() || Underlying->user_back() != TrampMem))
Craig Topperf40110f2014-04-25 05:29:35 +00003737 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00003738 if (!isa<AllocaInst>(Underlying))
Craig Topperf40110f2014-04-25 05:29:35 +00003739 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00003740
Craig Topperf40110f2014-04-25 05:29:35 +00003741 IntrinsicInst *InitTrampoline = nullptr;
Chandler Carruthcdf47882014-03-09 03:16:01 +00003742 for (User *U : TrampMem->users()) {
3743 IntrinsicInst *II = dyn_cast<IntrinsicInst>(U);
Duncan Sandsa0984362011-09-06 13:37:06 +00003744 if (!II)
Craig Topperf40110f2014-04-25 05:29:35 +00003745 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00003746 if (II->getIntrinsicID() == Intrinsic::init_trampoline) {
3747 if (InitTrampoline)
3748 // More than one init_trampoline writes to this value. Give up.
Craig Topperf40110f2014-04-25 05:29:35 +00003749 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00003750 InitTrampoline = II;
3751 continue;
3752 }
3753 if (II->getIntrinsicID() == Intrinsic::adjust_trampoline)
3754 // Allow any number of calls to adjust.trampoline.
3755 continue;
Craig Topperf40110f2014-04-25 05:29:35 +00003756 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00003757 }
3758
3759 // No call to init.trampoline found.
3760 if (!InitTrampoline)
Craig Topperf40110f2014-04-25 05:29:35 +00003761 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00003762
3763 // Check that the alloca is being used in the expected way.
3764 if (InitTrampoline->getOperand(0) != TrampMem)
Craig Topperf40110f2014-04-25 05:29:35 +00003765 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00003766
3767 return InitTrampoline;
3768}
3769
Sanjay Patel6038d3e2016-01-29 23:27:03 +00003770static IntrinsicInst *findInitTrampolineFromBB(IntrinsicInst *AdjustTramp,
Duncan Sandsa0984362011-09-06 13:37:06 +00003771 Value *TrampMem) {
3772 // Visit all the previous instructions in the basic block, and try to find a
3773 // init.trampoline which has a direct path to the adjust.trampoline.
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00003774 for (BasicBlock::iterator I = AdjustTramp->getIterator(),
3775 E = AdjustTramp->getParent()->begin();
3776 I != E;) {
3777 Instruction *Inst = &*--I;
Duncan Sandsa0984362011-09-06 13:37:06 +00003778 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
3779 if (II->getIntrinsicID() == Intrinsic::init_trampoline &&
3780 II->getOperand(0) == TrampMem)
3781 return II;
3782 if (Inst->mayWriteToMemory())
Craig Topperf40110f2014-04-25 05:29:35 +00003783 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00003784 }
Craig Topperf40110f2014-04-25 05:29:35 +00003785 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00003786}
3787
3788// Given a call to llvm.adjust.trampoline, find and return the corresponding
3789// call to llvm.init.trampoline if the call to the trampoline can be optimized
3790// to a direct call to a function. Otherwise return NULL.
Sanjay Patel6038d3e2016-01-29 23:27:03 +00003791static IntrinsicInst *findInitTrampoline(Value *Callee) {
Duncan Sandsa0984362011-09-06 13:37:06 +00003792 Callee = Callee->stripPointerCasts();
3793 IntrinsicInst *AdjustTramp = dyn_cast<IntrinsicInst>(Callee);
3794 if (!AdjustTramp ||
3795 AdjustTramp->getIntrinsicID() != Intrinsic::adjust_trampoline)
Craig Topperf40110f2014-04-25 05:29:35 +00003796 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00003797
3798 Value *TrampMem = AdjustTramp->getOperand(0);
3799
Sanjay Patel6038d3e2016-01-29 23:27:03 +00003800 if (IntrinsicInst *IT = findInitTrampolineFromAlloca(TrampMem))
Duncan Sandsa0984362011-09-06 13:37:06 +00003801 return IT;
Sanjay Patel6038d3e2016-01-29 23:27:03 +00003802 if (IntrinsicInst *IT = findInitTrampolineFromBB(AdjustTramp, TrampMem))
Duncan Sandsa0984362011-09-06 13:37:06 +00003803 return IT;
Craig Topperf40110f2014-04-25 05:29:35 +00003804 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00003805}
3806
Sanjay Patelcd4377c2016-01-20 22:24:38 +00003807/// Improvements for call and invoke instructions.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003808Instruction *InstCombiner::visitCallSite(CallSite CS) {
Justin Bogner99798402016-08-05 01:06:44 +00003809 if (isAllocLikeFn(CS.getInstruction(), &TLI))
Nuno Lopes95cc4f32012-07-09 18:38:20 +00003810 return visitAllocSite(*CS.getInstruction());
Nuno Lopesdc6085e2012-06-21 21:25:05 +00003811
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003812 bool Changed = false;
3813
Philip Reamesc25df112015-06-16 20:24:25 +00003814 // Mark any parameters that are known to be non-null with the nonnull
3815 // attribute. This is helpful for inlining calls to functions with null
3816 // checks on their arguments.
Reid Kleckner5fbdd172017-05-31 19:23:09 +00003817 SmallVector<unsigned, 4> ArgNos;
Philip Reamesc25df112015-06-16 20:24:25 +00003818 unsigned ArgNo = 0;
Akira Hatanaka237916b2015-12-02 06:58:49 +00003819
Philip Reamesc25df112015-06-16 20:24:25 +00003820 for (Value *V : CS.args()) {
Sanjay Patelf9f5d3c2016-01-29 23:14:58 +00003821 if (V->getType()->isPointerTy() &&
Reid Klecknerfb502d22017-04-14 20:19:02 +00003822 !CS.paramHasAttr(ArgNo, Attribute::NonNull) &&
Nuno Lopes404f1062017-09-09 18:23:11 +00003823 isKnownNonZero(V, DL, 0, &AC, CS.getInstruction(), &DT))
Reid Kleckner5fbdd172017-05-31 19:23:09 +00003824 ArgNos.push_back(ArgNo);
Philip Reamesc25df112015-06-16 20:24:25 +00003825 ArgNo++;
3826 }
Akira Hatanaka237916b2015-12-02 06:58:49 +00003827
Philip Reamesc25df112015-06-16 20:24:25 +00003828 assert(ArgNo == CS.arg_size() && "sanity check");
3829
Reid Kleckner5fbdd172017-05-31 19:23:09 +00003830 if (!ArgNos.empty()) {
Reid Klecknerb5180542017-03-21 16:57:19 +00003831 AttributeList AS = CS.getAttributes();
Akira Hatanaka237916b2015-12-02 06:58:49 +00003832 LLVMContext &Ctx = CS.getInstruction()->getContext();
Reid Kleckner5fbdd172017-05-31 19:23:09 +00003833 AS = AS.addParamAttribute(Ctx, ArgNos,
3834 Attribute::get(Ctx, Attribute::NonNull));
Akira Hatanaka237916b2015-12-02 06:58:49 +00003835 CS.setAttributes(AS);
3836 Changed = true;
3837 }
3838
Chris Lattner73989652010-12-20 08:25:06 +00003839 // If the callee is a pointer to a function, attempt to move any casts to the
3840 // arguments of the call/invoke.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003841 Value *Callee = CS.getCalledValue();
Chris Lattner73989652010-12-20 08:25:06 +00003842 if (!isa<Function>(Callee) && transformConstExprCastCall(CS))
Craig Topperf40110f2014-04-25 05:29:35 +00003843 return nullptr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003844
Justin Lebar9d943972016-03-14 20:18:54 +00003845 if (Function *CalleeF = dyn_cast<Function>(Callee)) {
3846 // Remove the convergent attr on calls when the callee is not convergent.
Matt Arsenault802ebcb2016-06-20 19:04:44 +00003847 if (CS.isConvergent() && !CalleeF->isConvergent() &&
3848 !CalleeF->isIntrinsic()) {
Justin Lebar9d943972016-03-14 20:18:54 +00003849 DEBUG(dbgs() << "Removing convergent attr from instr "
3850 << CS.getInstruction() << "\n");
3851 CS.setNotConvergent();
3852 return CS.getInstruction();
3853 }
3854
Chris Lattner846a52e2010-02-01 18:11:34 +00003855 // If the call and callee calling conventions don't match, this call must
3856 // be unreachable, as the call is undefined.
3857 if (CalleeF->getCallingConv() != CS.getCallingConv() &&
3858 // Only do this for calls to a function with a body. A prototype may
3859 // not actually end up matching the implementation's calling conv for a
3860 // variety of reasons (e.g. it may be written in assembly).
3861 !CalleeF->isDeclaration()) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003862 Instruction *OldCall = CS.getInstruction();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003863 new StoreInst(ConstantInt::getTrue(Callee->getContext()),
Jim Grosbach7815f562012-02-03 00:07:04 +00003864 UndefValue::get(Type::getInt1PtrTy(Callee->getContext())),
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003865 OldCall);
Chad Rosiere28ae302012-12-13 00:18:46 +00003866 // If OldCall does not return void then replaceAllUsesWith undef.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003867 // This allows ValueHandlers and custom metadata to adjust itself.
3868 if (!OldCall->getType()->isVoidTy())
Sanjay Patel4b198802016-02-01 22:23:39 +00003869 replaceInstUsesWith(*OldCall, UndefValue::get(OldCall->getType()));
Chris Lattner2cecedf2010-02-01 18:04:58 +00003870 if (isa<CallInst>(OldCall))
Sanjay Patel4b198802016-02-01 22:23:39 +00003871 return eraseInstFromFunction(*OldCall);
Jim Grosbach7815f562012-02-03 00:07:04 +00003872
Chris Lattner2cecedf2010-02-01 18:04:58 +00003873 // We cannot remove an invoke, because it would change the CFG, just
3874 // change the callee to a null pointer.
Gabor Greiffebf6ab2010-03-20 21:00:25 +00003875 cast<InvokeInst>(OldCall)->setCalledFunction(
Chris Lattner2cecedf2010-02-01 18:04:58 +00003876 Constant::getNullValue(CalleeF->getType()));
Craig Topperf40110f2014-04-25 05:29:35 +00003877 return nullptr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003878 }
Justin Lebar9d943972016-03-14 20:18:54 +00003879 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003880
3881 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
Gabor Greif589a0b92010-06-24 12:58:35 +00003882 // If CS does not return void then replaceAllUsesWith undef.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003883 // This allows ValueHandlers and custom metadata to adjust itself.
3884 if (!CS.getInstruction()->getType()->isVoidTy())
Sanjay Patel4b198802016-02-01 22:23:39 +00003885 replaceInstUsesWith(*CS.getInstruction(),
Eli Friedmanb9ed18f2011-05-18 00:32:01 +00003886 UndefValue::get(CS.getInstruction()->getType()));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003887
Nuno Lopes771e7bd2012-06-21 23:52:14 +00003888 if (isa<InvokeInst>(CS.getInstruction())) {
3889 // Can't remove an invoke because we cannot change the CFG.
Craig Topperf40110f2014-04-25 05:29:35 +00003890 return nullptr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003891 }
Nuno Lopes771e7bd2012-06-21 23:52:14 +00003892
3893 // This instruction is not reachable, just remove it. We insert a store to
3894 // undef so that we know that this code is not reachable, despite the fact
3895 // that we can't modify the CFG here.
3896 new StoreInst(ConstantInt::getTrue(Callee->getContext()),
3897 UndefValue::get(Type::getInt1PtrTy(Callee->getContext())),
3898 CS.getInstruction());
3899
Sanjay Patel4b198802016-02-01 22:23:39 +00003900 return eraseInstFromFunction(*CS.getInstruction());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003901 }
3902
Sanjay Patel6038d3e2016-01-29 23:27:03 +00003903 if (IntrinsicInst *II = findInitTrampoline(Callee))
Duncan Sandsa0984362011-09-06 13:37:06 +00003904 return transformCallThroughTrampoline(CS, II);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003905
Chris Lattner229907c2011-07-18 04:54:35 +00003906 PointerType *PTy = cast<PointerType>(Callee->getType());
3907 FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003908 if (FTy->isVarArg()) {
Eli Friedman7534b4682011-11-29 01:18:23 +00003909 int ix = FTy->getNumParams();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003910 // See if we can optimize any arguments passed through the varargs area of
3911 // the call.
Matt Arsenault5d2e85f2013-06-28 00:25:40 +00003912 for (CallSite::arg_iterator I = CS.arg_begin() + FTy->getNumParams(),
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003913 E = CS.arg_end(); I != E; ++I, ++ix) {
3914 CastInst *CI = dyn_cast<CastInst>(*I);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003915 if (CI && isSafeToEliminateVarargsCast(CS, DL, CI, ix)) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003916 *I = CI->getOperand(0);
3917 Changed = true;
3918 }
3919 }
3920 }
3921
3922 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
3923 // Inline asm calls cannot throw - mark them 'nounwind'.
3924 CS.setDoesNotThrow();
3925 Changed = true;
3926 }
3927
Micah Villmowcdfe20b2012-10-08 16:38:25 +00003928 // Try to optimize the call if possible, we require DataLayout for most of
Eric Christophera7fb58f2010-03-06 10:50:38 +00003929 // this. None of these calls are seen as possibly dead so go ahead and
3930 // delete the instruction now.
3931 if (CallInst *CI = dyn_cast<CallInst>(CS.getInstruction())) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003932 Instruction *I = tryOptimizeCall(CI);
Eric Christopher1810d772010-03-06 10:59:25 +00003933 // If we changed something return the result, etc. Otherwise let
3934 // the fallthrough check.
Sanjay Patel4b198802016-02-01 22:23:39 +00003935 if (I) return eraseInstFromFunction(*I);
Eric Christophera7fb58f2010-03-06 10:50:38 +00003936 }
3937
Craig Topperf40110f2014-04-25 05:29:35 +00003938 return Changed ? CS.getInstruction() : nullptr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003939}
3940
Sanjay Patelcd4377c2016-01-20 22:24:38 +00003941/// If the callee is a constexpr cast of a function, attempt to move the cast to
3942/// the arguments of the call/invoke.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003943bool InstCombiner::transformConstExprCastCall(CallSite CS) {
Sanjay Patele3c335c2016-08-11 15:21:21 +00003944 auto *Callee = dyn_cast<Function>(CS.getCalledValue()->stripPointerCasts());
Craig Topperf40110f2014-04-25 05:29:35 +00003945 if (!Callee)
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003946 return false;
Sanjay Patel38ae83d2016-08-11 15:23:56 +00003947
Reid Kleckner298ffc62018-04-02 22:49:44 +00003948 // If this is a call to a thunk function, don't remove the cast. Thunks are
3949 // used to transparently forward all incoming parameters and outgoing return
3950 // values, so it's important to leave the cast in place.
David Majnemer4c0a6e92015-01-21 22:32:04 +00003951 if (Callee->hasFnAttribute("thunk"))
3952 return false;
Sanjay Patel38ae83d2016-08-11 15:23:56 +00003953
Reid Kleckner298ffc62018-04-02 22:49:44 +00003954 // If this is a musttail call, the callee's prototype must match the caller's
3955 // prototype with the exception of pointee types. The code below doesn't
3956 // implement that, so we can't do this transform.
3957 // TODO: Do the transform if it only requires adding pointer casts.
3958 if (CS.isMustTailCall())
3959 return false;
3960
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003961 Instruction *Caller = CS.getInstruction();
Reid Klecknerb5180542017-03-21 16:57:19 +00003962 const AttributeList &CallerPAL = CS.getAttributes();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003963
3964 // Okay, this is a cast from a function to a different type. Unless doing so
3965 // would cause a type conversion of one of our arguments, change this call to
3966 // be a direct call with arguments casted to the appropriate types.
Chris Lattner229907c2011-07-18 04:54:35 +00003967 FunctionType *FT = Callee->getFunctionType();
3968 Type *OldRetTy = Caller->getType();
3969 Type *NewRetTy = FT->getReturnType();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003970
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003971 // Check to see if we are changing the return type...
3972 if (OldRetTy != NewRetTy) {
Nick Lewyckya6a17d72014-01-18 22:47:12 +00003973
3974 if (NewRetTy->isStructTy())
3975 return false; // TODO: Handle multiple return values.
3976
David Majnemer9b6b8222015-01-06 08:41:31 +00003977 if (!CastInst::isBitOrNoopPointerCastable(NewRetTy, OldRetTy, DL)) {
Matt Arsenaulte6952f22013-09-17 21:10:14 +00003978 if (Callee->isDeclaration())
3979 return false; // Cannot transform this return value.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003980
Matt Arsenaulte6952f22013-09-17 21:10:14 +00003981 if (!Caller->use_empty() &&
3982 // void -> non-void is handled specially
3983 !NewRetTy->isVoidTy())
Frederic Rissc1892e22014-10-23 04:08:42 +00003984 return false; // Cannot transform this return value.
Matt Arsenaulte6952f22013-09-17 21:10:14 +00003985 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003986
3987 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Reid Klecknerb5180542017-03-21 16:57:19 +00003988 AttrBuilder RAttrs(CallerPAL, AttributeList::ReturnIndex);
Pete Cooper2777d8872015-05-06 23:19:56 +00003989 if (RAttrs.overlaps(AttributeFuncs::typeIncompatible(NewRetTy)))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003990 return false; // Attribute not compatible with transformed value.
3991 }
3992
3993 // If the callsite is an invoke instruction, and the return value is used by
3994 // a PHI node in a successor, we cannot change the return type of the call
3995 // because there is no place to put the cast instruction (without breaking
3996 // the critical edge). Bail out in this case.
3997 if (!Caller->use_empty())
3998 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
Chandler Carruthcdf47882014-03-09 03:16:01 +00003999 for (User *U : II->users())
4000 if (PHINode *PN = dyn_cast<PHINode>(U))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004001 if (PN->getParent() == II->getNormalDest() ||
4002 PN->getParent() == II->getUnwindDest())
4003 return false;
4004 }
4005
Matt Arsenault5d2e85f2013-06-28 00:25:40 +00004006 unsigned NumActualArgs = CS.arg_size();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004007 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
4008
David Majnemer9b6b8222015-01-06 08:41:31 +00004009 // Prevent us turning:
4010 // declare void @takes_i32_inalloca(i32* inalloca)
4011 // call void bitcast (void (i32*)* @takes_i32_inalloca to void (i32)*)(i32 0)
4012 //
4013 // into:
4014 // call void @takes_i32_inalloca(i32* null)
David Majnemerd61a6fd2015-03-11 18:03:05 +00004015 //
4016 // Similarly, avoid folding away bitcasts of byval calls.
4017 if (Callee->getAttributes().hasAttrSomewhere(Attribute::InAlloca) ||
4018 Callee->getAttributes().hasAttrSomewhere(Attribute::ByVal))
David Majnemer9b6b8222015-01-06 08:41:31 +00004019 return false;
4020
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004021 CallSite::arg_iterator AI = CS.arg_begin();
4022 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
Chris Lattner229907c2011-07-18 04:54:35 +00004023 Type *ParamTy = FT->getParamType(i);
4024 Type *ActTy = (*AI)->getType();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004025
David Majnemer9b6b8222015-01-06 08:41:31 +00004026 if (!CastInst::isBitOrNoopPointerCastable(ActTy, ParamTy, DL))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004027 return false; // Cannot transform this parameter value.
4028
Reid Klecknerf021fab2017-04-13 23:12:13 +00004029 if (AttrBuilder(CallerPAL.getParamAttributes(i))
4030 .overlaps(AttributeFuncs::typeIncompatible(ParamTy)))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004031 return false; // Attribute not compatible with transformed value.
Jim Grosbach7815f562012-02-03 00:07:04 +00004032
Reid Kleckner26af2ca2014-01-28 02:38:36 +00004033 if (CS.isInAllocaArgument(i))
4034 return false; // Cannot transform to and from inalloca.
4035
Chris Lattner27ca8eb2010-12-20 08:36:38 +00004036 // If the parameter is passed as a byval argument, then we have to have a
4037 // sized type and the sized type has to have the same size as the old type.
Reid Klecknerf021fab2017-04-13 23:12:13 +00004038 if (ParamTy != ActTy && CallerPAL.hasParamAttribute(i, Attribute::ByVal)) {
Chris Lattner229907c2011-07-18 04:54:35 +00004039 PointerType *ParamPTy = dyn_cast<PointerType>(ParamTy);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004040 if (!ParamPTy || !ParamPTy->getElementType()->isSized())
Chris Lattner27ca8eb2010-12-20 08:36:38 +00004041 return false;
Jim Grosbach7815f562012-02-03 00:07:04 +00004042
Matt Arsenaultfa252722013-09-27 22:18:51 +00004043 Type *CurElTy = ActTy->getPointerElementType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004044 if (DL.getTypeAllocSize(CurElTy) !=
4045 DL.getTypeAllocSize(ParamPTy->getElementType()))
Chris Lattner27ca8eb2010-12-20 08:36:38 +00004046 return false;
4047 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004048 }
4049
Chris Lattneradf38b32011-02-24 05:10:56 +00004050 if (Callee->isDeclaration()) {
4051 // Do not delete arguments unless we have a function body.
4052 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg())
4053 return false;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004054
Chris Lattneradf38b32011-02-24 05:10:56 +00004055 // If the callee is just a declaration, don't change the varargsness of the
4056 // call. We don't want to introduce a varargs call where one doesn't
4057 // already exist.
Chris Lattner229907c2011-07-18 04:54:35 +00004058 PointerType *APTy = cast<PointerType>(CS.getCalledValue()->getType());
Chris Lattneradf38b32011-02-24 05:10:56 +00004059 if (FT->isVarArg()!=cast<FunctionType>(APTy->getElementType())->isVarArg())
4060 return false;
Jim Grosbache84ae7b2012-02-03 00:00:55 +00004061
4062 // If both the callee and the cast type are varargs, we still have to make
4063 // sure the number of fixed parameters are the same or we have the same
4064 // ABI issues as if we introduce a varargs call.
Jim Grosbach1df8cdc2012-02-03 00:26:07 +00004065 if (FT->isVarArg() &&
4066 cast<FunctionType>(APTy->getElementType())->isVarArg() &&
4067 FT->getNumParams() !=
Jim Grosbache84ae7b2012-02-03 00:00:55 +00004068 cast<FunctionType>(APTy->getElementType())->getNumParams())
4069 return false;
Chris Lattneradf38b32011-02-24 05:10:56 +00004070 }
Jim Grosbach7815f562012-02-03 00:07:04 +00004071
Jim Grosbach0ab54182012-02-03 00:00:50 +00004072 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
Reid Kleckneraa0cec72017-04-19 23:17:47 +00004073 !CallerPAL.isEmpty()) {
Jim Grosbach0ab54182012-02-03 00:00:50 +00004074 // In this case we have more arguments than the new function type, but we
4075 // won't be dropping them. Check that these extra arguments have attributes
4076 // that are compatible with being a vararg call argument.
Reid Kleckneraa0cec72017-04-19 23:17:47 +00004077 unsigned SRetIdx;
4078 if (CallerPAL.hasAttrSomewhere(Attribute::StructRet, &SRetIdx) &&
4079 SRetIdx > FT->getNumParams())
4080 return false;
4081 }
Jim Grosbach7815f562012-02-03 00:07:04 +00004082
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004083 // Okay, we decided that this is a safe thing to do: go ahead and start
Chris Lattneradf38b32011-02-24 05:10:56 +00004084 // inserting cast instructions as necessary.
Reid Klecknerc3fae792017-04-13 18:11:03 +00004085 SmallVector<Value *, 8> Args;
4086 SmallVector<AttributeSet, 8> ArgAttrs;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004087 Args.reserve(NumActualArgs);
Reid Klecknerc3fae792017-04-13 18:11:03 +00004088 ArgAttrs.reserve(NumActualArgs);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004089
4090 // Get any return attributes.
Reid Klecknerb5180542017-03-21 16:57:19 +00004091 AttrBuilder RAttrs(CallerPAL, AttributeList::ReturnIndex);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004092
4093 // If the return value is not being used, the type may not be compatible
4094 // with the existing attributes. Wipe out any problematic attributes.
Pete Cooper2777d8872015-05-06 23:19:56 +00004095 RAttrs.remove(AttributeFuncs::typeIncompatible(NewRetTy));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004096
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004097 AI = CS.arg_begin();
4098 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
Chris Lattner229907c2011-07-18 04:54:35 +00004099 Type *ParamTy = FT->getParamType(i);
Matt Arsenaultcacbb232013-07-30 20:45:05 +00004100
Reid Klecknerc3fae792017-04-13 18:11:03 +00004101 Value *NewArg = *AI;
4102 if ((*AI)->getType() != ParamTy)
Craig Topperbb4069e2017-07-07 23:16:26 +00004103 NewArg = Builder.CreateBitOrPointerCast(*AI, ParamTy);
Reid Klecknerc3fae792017-04-13 18:11:03 +00004104 Args.push_back(NewArg);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004105
4106 // Add any parameter attributes.
Reid Klecknerf021fab2017-04-13 23:12:13 +00004107 ArgAttrs.push_back(CallerPAL.getParamAttributes(i));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004108 }
4109
4110 // If the function takes more arguments than the call was taking, add them
4111 // now.
Reid Klecknerc3fae792017-04-13 18:11:03 +00004112 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004113 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
Reid Klecknerc3fae792017-04-13 18:11:03 +00004114 ArgAttrs.push_back(AttributeSet());
4115 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004116
4117 // If we are removing arguments to the function, emit an obnoxious warning.
4118 if (FT->getNumParams() < NumActualArgs) {
Nick Lewycky90053a12012-12-26 22:00:35 +00004119 // TODO: if (!FT->isVarArg()) this call may be unreachable. PR14722
4120 if (FT->isVarArg()) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004121 // Add all of the arguments in their promoted form to the arg list.
4122 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
Chris Lattner229907c2011-07-18 04:54:35 +00004123 Type *PTy = getPromotedType((*AI)->getType());
Reid Klecknerc3fae792017-04-13 18:11:03 +00004124 Value *NewArg = *AI;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004125 if (PTy != (*AI)->getType()) {
4126 // Must promote to pass through va_arg area!
4127 Instruction::CastOps opcode =
4128 CastInst::getCastOpcode(*AI, false, PTy, false);
Craig Topperbb4069e2017-07-07 23:16:26 +00004129 NewArg = Builder.CreateCast(opcode, *AI, PTy);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004130 }
Reid Klecknerc3fae792017-04-13 18:11:03 +00004131 Args.push_back(NewArg);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004132
4133 // Add any parameter attributes.
Reid Klecknerf021fab2017-04-13 23:12:13 +00004134 ArgAttrs.push_back(CallerPAL.getParamAttributes(i));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004135 }
4136 }
4137 }
4138
Reid Klecknerc2cb5602017-04-12 00:38:00 +00004139 AttributeSet FnAttrs = CallerPAL.getFnAttributes();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004140
4141 if (NewRetTy->isVoidTy())
4142 Caller->setName(""); // Void type should not have a name.
4143
Reid Klecknerc3fae792017-04-13 18:11:03 +00004144 assert((ArgAttrs.size() == FT->getNumParams() || FT->isVarArg()) &&
4145 "missing argument attributes");
4146 LLVMContext &Ctx = Callee->getContext();
4147 AttributeList NewCallerPAL = AttributeList::get(
4148 Ctx, FnAttrs, AttributeSet::get(Ctx, RAttrs), ArgAttrs);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004149
Sanjoy Das76293462015-11-25 00:42:19 +00004150 SmallVector<OperandBundleDef, 1> OpBundles;
Sanjoy Dasc521c7b2015-11-25 00:42:24 +00004151 CS.getOperandBundlesAsDefs(OpBundles);
Sanjoy Das76293462015-11-25 00:42:19 +00004152
Reid Kleckner257cb4e2017-04-13 20:26:38 +00004153 CallSite NewCS;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004154 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Craig Topperbb4069e2017-07-07 23:16:26 +00004155 NewCS = Builder.CreateInvoke(Callee, II->getNormalDest(),
4156 II->getUnwindDest(), Args, OpBundles);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004157 } else {
Craig Topperbb4069e2017-07-07 23:16:26 +00004158 NewCS = Builder.CreateCall(Callee, Args, OpBundles);
Reid Kleckner257cb4e2017-04-13 20:26:38 +00004159 cast<CallInst>(NewCS.getInstruction())
4160 ->setTailCallKind(cast<CallInst>(Caller)->getTailCallKind());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004161 }
Reid Kleckner257cb4e2017-04-13 20:26:38 +00004162 NewCS->takeName(Caller);
4163 NewCS.setCallingConv(CS.getCallingConv());
4164 NewCS.setAttributes(NewCallerPAL);
4165
4166 // Preserve the weight metadata for the new call instruction. The metadata
4167 // is used by SamplePGO to check callsite's hotness.
4168 uint64_t W;
4169 if (Caller->extractProfTotalWeight(W))
4170 NewCS->setProfWeight(W);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004171
4172 // Insert a cast of the return type as necessary.
Reid Kleckner257cb4e2017-04-13 20:26:38 +00004173 Instruction *NC = NewCS.getInstruction();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004174 Value *NV = NC;
4175 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
4176 if (!NV->getType()->isVoidTy()) {
David Majnemer9b6b8222015-01-06 08:41:31 +00004177 NV = NC = CastInst::CreateBitOrPointerCast(NC, OldRetTy);
Eli Friedman35211c62011-05-27 00:19:40 +00004178 NC->setDebugLoc(Caller->getDebugLoc());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004179
4180 // If this is an invoke instruction, we should insert it after the first
4181 // non-phi, instruction in the normal successor block.
4182 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Bill Wendling07efd6f2011-08-25 01:08:34 +00004183 BasicBlock::iterator I = II->getNormalDest()->getFirstInsertionPt();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004184 InsertNewInstBefore(NC, *I);
4185 } else {
Chris Lattner73989652010-12-20 08:25:06 +00004186 // Otherwise, it's a call, just insert cast right after the call.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004187 InsertNewInstBefore(NC, *Caller);
4188 }
4189 Worklist.AddUsersToWorkList(*Caller);
4190 } else {
4191 NV = UndefValue::get(Caller->getType());
4192 }
4193 }
4194
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004195 if (!Caller->use_empty())
Sanjay Patel4b198802016-02-01 22:23:39 +00004196 replaceInstUsesWith(*Caller, NV);
Frederic Rissc1892e22014-10-23 04:08:42 +00004197 else if (Caller->hasValueHandle()) {
4198 if (OldRetTy == NV->getType())
4199 ValueHandleBase::ValueIsRAUWd(Caller, NV);
4200 else
4201 // We cannot call ValueIsRAUWd with a different type, and the
4202 // actual tracked value will disappear.
4203 ValueHandleBase::ValueIsDeleted(Caller);
4204 }
Eli Friedmanb9ed18f2011-05-18 00:32:01 +00004205
Sanjay Patel4b198802016-02-01 22:23:39 +00004206 eraseInstFromFunction(*Caller);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004207 return true;
4208}
4209
Sanjay Patelcd4377c2016-01-20 22:24:38 +00004210/// Turn a call to a function created by init_trampoline / adjust_trampoline
4211/// intrinsic pair into a direct call to the underlying function.
Duncan Sandsa0984362011-09-06 13:37:06 +00004212Instruction *
4213InstCombiner::transformCallThroughTrampoline(CallSite CS,
4214 IntrinsicInst *Tramp) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004215 Value *Callee = CS.getCalledValue();
Chris Lattner229907c2011-07-18 04:54:35 +00004216 PointerType *PTy = cast<PointerType>(Callee->getType());
4217 FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00004218 AttributeList Attrs = CS.getAttributes();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004219
4220 // If the call already has the 'nest' attribute somewhere then give up -
4221 // otherwise 'nest' would occur twice after splicing in the chain.
Bill Wendling6e95ae82012-12-31 00:49:59 +00004222 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Craig Topperf40110f2014-04-25 05:29:35 +00004223 return nullptr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004224
Duncan Sandsa0984362011-09-06 13:37:06 +00004225 assert(Tramp &&
4226 "transformCallThroughTrampoline called with incorrect CallSite.");
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004227
Gabor Greif3e44ea12010-07-22 10:37:47 +00004228 Function *NestF =cast<Function>(Tramp->getArgOperand(1)->stripPointerCasts());
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00004229 FunctionType *NestFTy = cast<FunctionType>(NestF->getValueType());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004230
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00004231 AttributeList NestAttrs = NestF->getAttributes();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004232 if (!NestAttrs.isEmpty()) {
Reid Klecknerf021fab2017-04-13 23:12:13 +00004233 unsigned NestArgNo = 0;
Craig Topperf40110f2014-04-25 05:29:35 +00004234 Type *NestTy = nullptr;
Reid Klecknerc2cb5602017-04-12 00:38:00 +00004235 AttributeSet NestAttr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004236
4237 // Look for a parameter marked with the 'nest' attribute.
4238 for (FunctionType::param_iterator I = NestFTy->param_begin(),
Reid Klecknerf021fab2017-04-13 23:12:13 +00004239 E = NestFTy->param_end();
4240 I != E; ++NestArgNo, ++I) {
4241 AttributeSet AS = NestAttrs.getParamAttributes(NestArgNo);
4242 if (AS.hasAttribute(Attribute::Nest)) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004243 // Record the parameter type and any other attributes.
4244 NestTy = *I;
Reid Klecknerf021fab2017-04-13 23:12:13 +00004245 NestAttr = AS;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004246 break;
4247 }
Reid Klecknerf021fab2017-04-13 23:12:13 +00004248 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004249
4250 if (NestTy) {
4251 Instruction *Caller = CS.getInstruction();
4252 std::vector<Value*> NewArgs;
Reid Kleckner7f720332017-04-13 00:58:09 +00004253 std::vector<AttributeSet> NewArgAttrs;
Matt Arsenault5d2e85f2013-06-28 00:25:40 +00004254 NewArgs.reserve(CS.arg_size() + 1);
Reid Kleckner7f720332017-04-13 00:58:09 +00004255 NewArgAttrs.reserve(CS.arg_size());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004256
4257 // Insert the nest argument into the call argument list, which may
4258 // mean appending it. Likewise for attributes.
4259
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004260 {
Reid Klecknerf021fab2017-04-13 23:12:13 +00004261 unsigned ArgNo = 0;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004262 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
4263 do {
Reid Klecknerf021fab2017-04-13 23:12:13 +00004264 if (ArgNo == NestArgNo) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004265 // Add the chain argument and attributes.
Gabor Greif589a0b92010-06-24 12:58:35 +00004266 Value *NestVal = Tramp->getArgOperand(2);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004267 if (NestVal->getType() != NestTy)
Craig Topperbb4069e2017-07-07 23:16:26 +00004268 NestVal = Builder.CreateBitCast(NestVal, NestTy, "nest");
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004269 NewArgs.push_back(NestVal);
Reid Kleckner7f720332017-04-13 00:58:09 +00004270 NewArgAttrs.push_back(NestAttr);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004271 }
4272
4273 if (I == E)
4274 break;
4275
4276 // Add the original argument and attributes.
4277 NewArgs.push_back(*I);
Reid Klecknerf021fab2017-04-13 23:12:13 +00004278 NewArgAttrs.push_back(Attrs.getParamAttributes(ArgNo));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004279
Reid Klecknerf021fab2017-04-13 23:12:13 +00004280 ++ArgNo;
Richard Trieu7a083812016-02-18 22:09:30 +00004281 ++I;
Eugene Zelenkocdc71612016-08-11 17:20:18 +00004282 } while (true);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004283 }
4284
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004285 // The trampoline may have been bitcast to a bogus type (FTy).
4286 // Handle this by synthesizing a new function type, equal to FTy
4287 // with the chain parameter inserted.
4288
Jay Foadb804a2b2011-07-12 14:06:48 +00004289 std::vector<Type*> NewTypes;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004290 NewTypes.reserve(FTy->getNumParams()+1);
4291
4292 // Insert the chain's type into the list of parameter types, which may
4293 // mean appending it.
4294 {
Reid Klecknerf021fab2017-04-13 23:12:13 +00004295 unsigned ArgNo = 0;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004296 FunctionType::param_iterator I = FTy->param_begin(),
4297 E = FTy->param_end();
4298
4299 do {
Reid Klecknerf021fab2017-04-13 23:12:13 +00004300 if (ArgNo == NestArgNo)
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004301 // Add the chain's type.
4302 NewTypes.push_back(NestTy);
4303
4304 if (I == E)
4305 break;
4306
4307 // Add the original type.
4308 NewTypes.push_back(*I);
4309
Reid Klecknerf021fab2017-04-13 23:12:13 +00004310 ++ArgNo;
Richard Trieu7a083812016-02-18 22:09:30 +00004311 ++I;
Eugene Zelenkocdc71612016-08-11 17:20:18 +00004312 } while (true);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004313 }
4314
4315 // Replace the trampoline call with a direct call. Let the generic
4316 // code sort out any function type mismatches.
Jim Grosbach7815f562012-02-03 00:07:04 +00004317 FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004318 FTy->isVarArg());
4319 Constant *NewCallee =
4320 NestF->getType() == PointerType::getUnqual(NewFTy) ?
Jim Grosbach7815f562012-02-03 00:07:04 +00004321 NestF : ConstantExpr::getBitCast(NestF,
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004322 PointerType::getUnqual(NewFTy));
Reid Kleckner7f720332017-04-13 00:58:09 +00004323 AttributeList NewPAL =
4324 AttributeList::get(FTy->getContext(), Attrs.getFnAttributes(),
4325 Attrs.getRetAttributes(), NewArgAttrs);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004326
David Majnemer231a68c2016-04-29 08:07:20 +00004327 SmallVector<OperandBundleDef, 1> OpBundles;
4328 CS.getOperandBundlesAsDefs(OpBundles);
4329
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004330 Instruction *NewCaller;
4331 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
4332 NewCaller = InvokeInst::Create(NewCallee,
4333 II->getNormalDest(), II->getUnwindDest(),
David Majnemer231a68c2016-04-29 08:07:20 +00004334 NewArgs, OpBundles);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004335 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
4336 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
4337 } else {
David Majnemer231a68c2016-04-29 08:07:20 +00004338 NewCaller = CallInst::Create(NewCallee, NewArgs, OpBundles);
David Majnemerd5648c72016-11-25 22:35:09 +00004339 cast<CallInst>(NewCaller)->setTailCallKind(
4340 cast<CallInst>(Caller)->getTailCallKind());
4341 cast<CallInst>(NewCaller)->setCallingConv(
4342 cast<CallInst>(Caller)->getCallingConv());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004343 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
4344 }
Florian Hahn012c8f92017-12-20 17:16:59 +00004345 NewCaller->setDebugLoc(Caller->getDebugLoc());
Eli Friedman49346012011-05-18 19:57:14 +00004346
4347 return NewCaller;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004348 }
4349 }
4350
4351 // Replace the trampoline call with a direct call. Since there is no 'nest'
4352 // parameter, there is no need to adjust the argument list. Let the generic
4353 // code sort out any function type mismatches.
4354 Constant *NewCallee =
Jim Grosbach7815f562012-02-03 00:07:04 +00004355 NestF->getType() == PTy ? NestF :
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004356 ConstantExpr::getBitCast(NestF, PTy);
4357 CS.setCalledFunction(NewCallee);
4358 return CS.getInstruction();
4359}