1 //===- AMDGPInstCombineIntrinsic.cpp - AMDGPU specific InstCombine pass ---===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // \file
10 // This file implements a TargetTransformInfo analysis pass specific to the
11 // AMDGPU target machine. It uses the target's detailed information to provide
12 // more precise answers to certain TTI queries, while letting the target
13 // independent and default TTI implementations handle the rest.
14 //
15 //===----------------------------------------------------------------------===//
16 
17 #include "AMDGPUInstrInfo.h"
18 #include "AMDGPUTargetTransformInfo.h"
19 #include "GCNSubtarget.h"
20 #include "llvm/IR/IntrinsicsAMDGPU.h"
21 #include "llvm/Transforms/InstCombine/InstCombiner.h"
22 
23 using namespace llvm;
24 
25 #define DEBUG_TYPE "AMDGPUtti"
26 
27 namespace {
28 
29 struct AMDGPUImageDMaskIntrinsic {
30   unsigned Intr;
31 };
32 
33 #define GET_AMDGPUImageDMaskIntrinsicTable_IMPL
34 #include "InstCombineTables.inc"
35 
36 } // end anonymous namespace
37 
38 // Constant fold llvm.amdgcn.fmed3 intrinsics for standard inputs.
39 //
40 // A single NaN input is folded to minnum, so we rely on that folding for
41 // handling NaNs.
42 static APFloat fmed3AMDGCN(const APFloat &Src0, const APFloat &Src1,
43                            const APFloat &Src2) {
44   APFloat Max3 = maxnum(maxnum(Src0, Src1), Src2);
45 
46   APFloat::cmpResult Cmp0 = Max3.compare(Src0);
47   assert(Cmp0 != APFloat::cmpUnordered && "nans handled separately");
48   if (Cmp0 == APFloat::cmpEqual)
49     return maxnum(Src1, Src2);
50 
51   APFloat::cmpResult Cmp1 = Max3.compare(Src1);
52   assert(Cmp1 != APFloat::cmpUnordered && "nans handled separately");
53   if (Cmp1 == APFloat::cmpEqual)
54     return maxnum(Src0, Src2);
55 
56   return maxnum(Src0, Src1);
57 }
58 
59 // Check if a value can be converted to a 16-bit value without losing
60 // precision.
61 // The value is expected to be either a float (IsFloat = true) or an unsigned
62 // integer (IsFloat = false).
63 static bool canSafelyConvertTo16Bit(Value &V, bool IsFloat) {
64   Type *VTy = V.getType();
65   if (VTy->isHalfTy() || VTy->isIntegerTy(16)) {
66     // The value is already 16-bit, so we don't want to convert to 16-bit again!
67     return false;
68   }
69   if (IsFloat) {
70     if (ConstantFP *ConstFloat = dyn_cast<ConstantFP>(&V)) {
71       // We need to check that if we cast the index down to a half, we do not
72       // lose precision.
73       APFloat FloatValue(ConstFloat->getValueAPF());
74       bool LosesInfo = true;
75       FloatValue.convert(APFloat::IEEEhalf(), APFloat::rmTowardZero,
76                          &LosesInfo);
77       return !LosesInfo;
78     }
79   } else {
80     if (ConstantInt *ConstInt = dyn_cast<ConstantInt>(&V)) {
81       // We need to check that if we cast the index down to an i16, we do not
82       // lose precision.
83       APInt IntValue(ConstInt->getValue());
84       return IntValue.getActiveBits() <= 16;
85     }
86   }
87 
88   Value *CastSrc;
89   bool IsExt = IsFloat ? match(&V, m_FPExt(PatternMatch::m_Value(CastSrc)))
90                        : match(&V, m_ZExt(PatternMatch::m_Value(CastSrc)));
91   if (IsExt) {
92     Type *CastSrcTy = CastSrc->getType();
93     if (CastSrcTy->isHalfTy() || CastSrcTy->isIntegerTy(16))
94       return true;
95   }
96 
97   return false;
98 }
99 
100 // Convert a value to 16-bit.
101 static Value *convertTo16Bit(Value &V, InstCombiner::BuilderTy &Builder) {
102   Type *VTy = V.getType();
103   if (isa<FPExtInst>(&V) || isa<SExtInst>(&V) || isa<ZExtInst>(&V))
104     return cast<Instruction>(&V)->getOperand(0);
105   if (VTy->isIntegerTy())
106     return Builder.CreateIntCast(&V, Type::getInt16Ty(V.getContext()), false);
107   if (VTy->isFloatingPointTy())
108     return Builder.CreateFPCast(&V, Type::getHalfTy(V.getContext()));
109 
110   llvm_unreachable("Should never be called!");
111 }
112 
113 /// Applies Func(OldIntr.Args, OldIntr.ArgTys), creates intrinsic call with
114 /// modified arguments (based on OldIntr) and replaces InstToReplace with
115 /// this newly created intrinsic call.
116 static Optional<Instruction *> modifyIntrinsicCall(
117     IntrinsicInst &OldIntr, Instruction &InstToReplace, unsigned NewIntr,
118     InstCombiner &IC,
119     std::function<void(SmallVectorImpl<Value *> &, SmallVectorImpl<Type *> &)>
120         Func) {
121   SmallVector<Type *, 4> ArgTys;
122   if (!Intrinsic::getIntrinsicSignature(OldIntr.getCalledFunction(), ArgTys))
123     return None;
124 
125   SmallVector<Value *, 8> Args(OldIntr.args());
126 
127   // Modify arguments and types
128   Func(Args, ArgTys);
129 
130   Function *I = Intrinsic::getDeclaration(OldIntr.getModule(), NewIntr, ArgTys);
131 
132   CallInst *NewCall = IC.Builder.CreateCall(I, Args);
133   NewCall->takeName(&OldIntr);
134   NewCall->copyMetadata(OldIntr);
135   if (isa<FPMathOperator>(NewCall))
136     NewCall->copyFastMathFlags(&OldIntr);
137 
138   // Erase and replace uses
139   if (!InstToReplace.getType()->isVoidTy())
140     IC.replaceInstUsesWith(InstToReplace, NewCall);
141 
142   bool RemoveOldIntr = &OldIntr != &InstToReplace;
143 
144   auto RetValue = IC.eraseInstFromFunction(InstToReplace);
145   if (RemoveOldIntr)
146     IC.eraseInstFromFunction(OldIntr);
147 
148   return RetValue;
149 }
150 
151 static Optional<Instruction *>
152 simplifyAMDGCNImageIntrinsic(const GCNSubtarget *ST,
153                              const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr,
154                              IntrinsicInst &II, InstCombiner &IC) {
155   // Optimize _L to _LZ when _L is zero
156   if (const auto *LZMappingInfo =
157           AMDGPU::getMIMGLZMappingInfo(ImageDimIntr->BaseOpcode)) {
158     if (auto *ConstantLod =
159             dyn_cast<ConstantFP>(II.getOperand(ImageDimIntr->LodIndex))) {
160       if (ConstantLod->isZero() || ConstantLod->isNegative()) {
161         const AMDGPU::ImageDimIntrinsicInfo *NewImageDimIntr =
162             AMDGPU::getImageDimIntrinsicByBaseOpcode(LZMappingInfo->LZ,
163                                                      ImageDimIntr->Dim);
164         return modifyIntrinsicCall(
165             II, II, NewImageDimIntr->Intr, IC, [&](auto &Args, auto &ArgTys) {
166               Args.erase(Args.begin() + ImageDimIntr->LodIndex);
167             });
168       }
169     }
170   }
171 
172   // Optimize _mip away, when 'lod' is zero
173   if (const auto *MIPMappingInfo =
174           AMDGPU::getMIMGMIPMappingInfo(ImageDimIntr->BaseOpcode)) {
175     if (auto *ConstantMip =
176             dyn_cast<ConstantInt>(II.getOperand(ImageDimIntr->MipIndex))) {
177       if (ConstantMip->isZero()) {
178         const AMDGPU::ImageDimIntrinsicInfo *NewImageDimIntr =
179             AMDGPU::getImageDimIntrinsicByBaseOpcode(MIPMappingInfo->NONMIP,
180                                                      ImageDimIntr->Dim);
181         return modifyIntrinsicCall(
182             II, II, NewImageDimIntr->Intr, IC, [&](auto &Args, auto &ArgTys) {
183               Args.erase(Args.begin() + ImageDimIntr->MipIndex);
184             });
185       }
186     }
187   }
188 
189   // Optimize _bias away when 'bias' is zero
190   if (const auto *BiasMappingInfo =
191           AMDGPU::getMIMGBiasMappingInfo(ImageDimIntr->BaseOpcode)) {
192     if (auto *ConstantBias =
193             dyn_cast<ConstantFP>(II.getOperand(ImageDimIntr->BiasIndex))) {
194       if (ConstantBias->isZero()) {
195         const AMDGPU::ImageDimIntrinsicInfo *NewImageDimIntr =
196             AMDGPU::getImageDimIntrinsicByBaseOpcode(BiasMappingInfo->NoBias,
197                                                      ImageDimIntr->Dim);
198         return modifyIntrinsicCall(
199             II, II, NewImageDimIntr->Intr, IC, [&](auto &Args, auto &ArgTys) {
200               Args.erase(Args.begin() + ImageDimIntr->BiasIndex);
201               ArgTys.erase(ArgTys.begin() + ImageDimIntr->BiasTyArg);
202             });
203       }
204     }
205   }
206 
207   // Optimize _offset away when 'offset' is zero
208   if (const auto *OffsetMappingInfo =
209           AMDGPU::getMIMGOffsetMappingInfo(ImageDimIntr->BaseOpcode)) {
210     if (auto *ConstantOffset =
211             dyn_cast<ConstantInt>(II.getOperand(ImageDimIntr->OffsetIndex))) {
212       if (ConstantOffset->isZero()) {
213         const AMDGPU::ImageDimIntrinsicInfo *NewImageDimIntr =
214             AMDGPU::getImageDimIntrinsicByBaseOpcode(
215                 OffsetMappingInfo->NoOffset, ImageDimIntr->Dim);
216         return modifyIntrinsicCall(
217             II, II, NewImageDimIntr->Intr, IC, [&](auto &Args, auto &ArgTys) {
218               Args.erase(Args.begin() + ImageDimIntr->OffsetIndex);
219             });
220       }
221     }
222   }
223 
224   // Try to use D16
225   if (ST->hasD16Images()) {
226 
227     const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
228         AMDGPU::getMIMGBaseOpcodeInfo(ImageDimIntr->BaseOpcode);
229 
230     if (BaseOpcode->HasD16) {
231 
232       // If the only use of image intrinsic is a fptrunc (with conversion to
233       // half) then both fptrunc and image intrinsic will be replaced with image
234       // intrinsic with D16 flag.
235       if (II.hasOneUse()) {
236         Instruction *User = II.user_back();
237 
238         if (User->getOpcode() == Instruction::FPTrunc &&
239             User->getType()->getScalarType()->isHalfTy()) {
240 
241           return modifyIntrinsicCall(II, *User, ImageDimIntr->Intr, IC,
242                                      [&](auto &Args, auto &ArgTys) {
243                                        // Change return type of image intrinsic.
244                                        // Set it to return type of fptrunc.
245                                        ArgTys[0] = User->getType();
246                                      });
247         }
248       }
249     }
250   }
251 
252   // Try to use A16 or G16
253   if (!ST->hasA16() && !ST->hasG16())
254     return None;
255 
256   // Address is interpreted as float if the instruction has a sampler or as
257   // unsigned int if there is no sampler.
258   bool HasSampler =
259       AMDGPU::getMIMGBaseOpcodeInfo(ImageDimIntr->BaseOpcode)->Sampler;
260   bool FloatCoord = false;
261   // true means derivatives can be converted to 16 bit, coordinates not
262   bool OnlyDerivatives = false;
263 
264   for (unsigned OperandIndex = ImageDimIntr->GradientStart;
265        OperandIndex < ImageDimIntr->VAddrEnd; OperandIndex++) {
266     Value *Coord = II.getOperand(OperandIndex);
267     // If the values are not derived from 16-bit values, we cannot optimize.
268     if (!canSafelyConvertTo16Bit(*Coord, HasSampler)) {
269       if (OperandIndex < ImageDimIntr->CoordStart ||
270           ImageDimIntr->GradientStart == ImageDimIntr->CoordStart) {
271         return None;
272       }
273       // All gradients can be converted, so convert only them
274       OnlyDerivatives = true;
275       break;
276     }
277 
278     assert(OperandIndex == ImageDimIntr->GradientStart ||
279            FloatCoord == Coord->getType()->isFloatingPointTy());
280     FloatCoord = Coord->getType()->isFloatingPointTy();
281   }
282 
283   if (!OnlyDerivatives && !ST->hasA16())
284     OnlyDerivatives = true; // Only supports G16
285 
286   // Check if there is a bias parameter and if it can be converted to f16
287   if (!OnlyDerivatives && ImageDimIntr->NumBiasArgs != 0) {
288     Value *Bias = II.getOperand(ImageDimIntr->BiasIndex);
289     assert(HasSampler &&
290            "Only image instructions with a sampler can have a bias");
291     if (!canSafelyConvertTo16Bit(*Bias, HasSampler))
292       OnlyDerivatives = true;
293   }
294 
295   if (OnlyDerivatives && (!ST->hasG16() || ImageDimIntr->GradientStart ==
296                                                ImageDimIntr->CoordStart))
297     return None;
298 
299   Type *CoordType = FloatCoord ? Type::getHalfTy(II.getContext())
300                                : Type::getInt16Ty(II.getContext());
301 
302   return modifyIntrinsicCall(
303       II, II, II.getIntrinsicID(), IC, [&](auto &Args, auto &ArgTys) {
304         ArgTys[ImageDimIntr->GradientTyArg] = CoordType;
305         if (!OnlyDerivatives) {
306           ArgTys[ImageDimIntr->CoordTyArg] = CoordType;
307 
308           // Change the bias type
309           if (ImageDimIntr->NumBiasArgs != 0)
310             ArgTys[ImageDimIntr->BiasTyArg] = Type::getHalfTy(II.getContext());
311         }
312 
313         unsigned EndIndex =
314             OnlyDerivatives ? ImageDimIntr->CoordStart : ImageDimIntr->VAddrEnd;
315         for (unsigned OperandIndex = ImageDimIntr->GradientStart;
316              OperandIndex < EndIndex; OperandIndex++) {
317           Args[OperandIndex] =
318               convertTo16Bit(*II.getOperand(OperandIndex), IC.Builder);
319         }
320 
321         // Convert the bias
322         if (!OnlyDerivatives && ImageDimIntr->NumBiasArgs != 0) {
323           Value *Bias = II.getOperand(ImageDimIntr->BiasIndex);
324           Args[ImageDimIntr->BiasIndex] = convertTo16Bit(*Bias, IC.Builder);
325         }
326       });
327 }
328 
329 bool GCNTTIImpl::canSimplifyLegacyMulToMul(const Value *Op0, const Value *Op1,
330                                            InstCombiner &IC) const {
331   // The legacy behaviour is that multiplying +/-0.0 by anything, even NaN or
332   // infinity, gives +0.0. If we can prove we don't have one of the special
333   // cases then we can use a normal multiply instead.
334   // TODO: Create and use isKnownFiniteNonZero instead of just matching
335   // constants here.
336   if (match(Op0, PatternMatch::m_FiniteNonZero()) ||
337       match(Op1, PatternMatch::m_FiniteNonZero())) {
338     // One operand is not zero or infinity or NaN.
339     return true;
340   }
341   auto *TLI = &IC.getTargetLibraryInfo();
342   if (isKnownNeverInfinity(Op0, TLI) && isKnownNeverNaN(Op0, TLI) &&
343       isKnownNeverInfinity(Op1, TLI) && isKnownNeverNaN(Op1, TLI)) {
344     // Neither operand is infinity or NaN.
345     return true;
346   }
347   return false;
348 }
349 
350 Optional<Instruction *>
351 GCNTTIImpl::instCombineIntrinsic(InstCombiner &IC, IntrinsicInst &II) const {
352   Intrinsic::ID IID = II.getIntrinsicID();
353   switch (IID) {
354   case Intrinsic::amdgcn_rcp: {
355     Value *Src = II.getArgOperand(0);
356 
357     // TODO: Move to ConstantFolding/InstSimplify?
358     if (isa<UndefValue>(Src)) {
359       Type *Ty = II.getType();
360       auto *QNaN = ConstantFP::get(Ty, APFloat::getQNaN(Ty->getFltSemantics()));
361       return IC.replaceInstUsesWith(II, QNaN);
362     }
363 
364     if (II.isStrictFP())
365       break;
366 
367     if (const ConstantFP *C = dyn_cast<ConstantFP>(Src)) {
368       const APFloat &ArgVal = C->getValueAPF();
369       APFloat Val(ArgVal.getSemantics(), 1);
370       Val.divide(ArgVal, APFloat::rmNearestTiesToEven);
371 
372       // This is more precise than the instruction may give.
373       //
374       // TODO: The instruction always flushes denormal results (except for f16),
375       // should this also?
376       return IC.replaceInstUsesWith(II, ConstantFP::get(II.getContext(), Val));
377     }
378 
379     break;
380   }
381   case Intrinsic::amdgcn_rsq: {
382     Value *Src = II.getArgOperand(0);
383 
384     // TODO: Move to ConstantFolding/InstSimplify?
385     if (isa<UndefValue>(Src)) {
386       Type *Ty = II.getType();
387       auto *QNaN = ConstantFP::get(Ty, APFloat::getQNaN(Ty->getFltSemantics()));
388       return IC.replaceInstUsesWith(II, QNaN);
389     }
390 
391     break;
392   }
393   case Intrinsic::amdgcn_frexp_mant:
394   case Intrinsic::amdgcn_frexp_exp: {
395     Value *Src = II.getArgOperand(0);
396     if (const ConstantFP *C = dyn_cast<ConstantFP>(Src)) {
397       int Exp;
398       APFloat Significand =
399           frexp(C->getValueAPF(), Exp, APFloat::rmNearestTiesToEven);
400 
401       if (IID == Intrinsic::amdgcn_frexp_mant) {
402         return IC.replaceInstUsesWith(
403             II, ConstantFP::get(II.getContext(), Significand));
404       }
405 
406       // Match instruction special case behavior.
407       if (Exp == APFloat::IEK_NaN || Exp == APFloat::IEK_Inf)
408         Exp = 0;
409 
410       return IC.replaceInstUsesWith(II, ConstantInt::get(II.getType(), Exp));
411     }
412 
413     if (isa<UndefValue>(Src)) {
414       return IC.replaceInstUsesWith(II, UndefValue::get(II.getType()));
415     }
416 
417     break;
418   }
419   case Intrinsic::amdgcn_class: {
420     enum {
421       S_NAN = 1 << 0,       // Signaling NaN
422       Q_NAN = 1 << 1,       // Quiet NaN
423       N_INFINITY = 1 << 2,  // Negative infinity
424       N_NORMAL = 1 << 3,    // Negative normal
425       N_SUBNORMAL = 1 << 4, // Negative subnormal
426       N_ZERO = 1 << 5,      // Negative zero
427       P_ZERO = 1 << 6,      // Positive zero
428       P_SUBNORMAL = 1 << 7, // Positive subnormal
429       P_NORMAL = 1 << 8,    // Positive normal
430       P_INFINITY = 1 << 9   // Positive infinity
431     };
432 
433     const uint32_t FullMask = S_NAN | Q_NAN | N_INFINITY | N_NORMAL |
434                               N_SUBNORMAL | N_ZERO | P_ZERO | P_SUBNORMAL |
435                               P_NORMAL | P_INFINITY;
436 
437     Value *Src0 = II.getArgOperand(0);
438     Value *Src1 = II.getArgOperand(1);
439     const ConstantInt *CMask = dyn_cast<ConstantInt>(Src1);
440     if (!CMask) {
441       if (isa<UndefValue>(Src0)) {
442         return IC.replaceInstUsesWith(II, UndefValue::get(II.getType()));
443       }
444 
445       if (isa<UndefValue>(Src1)) {
446         return IC.replaceInstUsesWith(II,
447                                       ConstantInt::get(II.getType(), false));
448       }
449       break;
450     }
451 
452     uint32_t Mask = CMask->getZExtValue();
453 
454     // If all tests are made, it doesn't matter what the value is.
455     if ((Mask & FullMask) == FullMask) {
456       return IC.replaceInstUsesWith(II, ConstantInt::get(II.getType(), true));
457     }
458 
459     if ((Mask & FullMask) == 0) {
460       return IC.replaceInstUsesWith(II, ConstantInt::get(II.getType(), false));
461     }
462 
463     if (Mask == (S_NAN | Q_NAN)) {
464       // Equivalent of isnan. Replace with standard fcmp.
465       Value *FCmp = IC.Builder.CreateFCmpUNO(Src0, Src0);
466       FCmp->takeName(&II);
467       return IC.replaceInstUsesWith(II, FCmp);
468     }
469 
470     if (Mask == (N_ZERO | P_ZERO)) {
471       // Equivalent of == 0.
472       Value *FCmp =
473           IC.Builder.CreateFCmpOEQ(Src0, ConstantFP::get(Src0->getType(), 0.0));
474 
475       FCmp->takeName(&II);
476       return IC.replaceInstUsesWith(II, FCmp);
477     }
478 
479     // fp_class (nnan x), qnan|snan|other -> fp_class (nnan x), other
480     if (((Mask & S_NAN) || (Mask & Q_NAN)) &&
481         isKnownNeverNaN(Src0, &IC.getTargetLibraryInfo())) {
482       return IC.replaceOperand(
483           II, 1, ConstantInt::get(Src1->getType(), Mask & ~(S_NAN | Q_NAN)));
484     }
485 
486     const ConstantFP *CVal = dyn_cast<ConstantFP>(Src0);
487     if (!CVal) {
488       if (isa<UndefValue>(Src0)) {
489         return IC.replaceInstUsesWith(II, UndefValue::get(II.getType()));
490       }
491 
492       // Clamp mask to used bits
493       if ((Mask & FullMask) != Mask) {
494         CallInst *NewCall = IC.Builder.CreateCall(
495             II.getCalledFunction(),
496             {Src0, ConstantInt::get(Src1->getType(), Mask & FullMask)});
497 
498         NewCall->takeName(&II);
499         return IC.replaceInstUsesWith(II, NewCall);
500       }
501 
502       break;
503     }
504 
505     const APFloat &Val = CVal->getValueAPF();
506 
507     bool Result =
508         ((Mask & S_NAN) && Val.isNaN() && Val.isSignaling()) ||
509         ((Mask & Q_NAN) && Val.isNaN() && !Val.isSignaling()) ||
510         ((Mask & N_INFINITY) && Val.isInfinity() && Val.isNegative()) ||
511         ((Mask & N_NORMAL) && Val.isNormal() && Val.isNegative()) ||
512         ((Mask & N_SUBNORMAL) && Val.isDenormal() && Val.isNegative()) ||
513         ((Mask & N_ZERO) && Val.isZero() && Val.isNegative()) ||
514         ((Mask & P_ZERO) && Val.isZero() && !Val.isNegative()) ||
515         ((Mask & P_SUBNORMAL) && Val.isDenormal() && !Val.isNegative()) ||
516         ((Mask & P_NORMAL) && Val.isNormal() && !Val.isNegative()) ||
517         ((Mask & P_INFINITY) && Val.isInfinity() && !Val.isNegative());
518 
519     return IC.replaceInstUsesWith(II, ConstantInt::get(II.getType(), Result));
520   }
521   case Intrinsic::amdgcn_cvt_pkrtz: {
522     Value *Src0 = II.getArgOperand(0);
523     Value *Src1 = II.getArgOperand(1);
524     if (const ConstantFP *C0 = dyn_cast<ConstantFP>(Src0)) {
525       if (const ConstantFP *C1 = dyn_cast<ConstantFP>(Src1)) {
526         const fltSemantics &HalfSem =
527             II.getType()->getScalarType()->getFltSemantics();
528         bool LosesInfo;
529         APFloat Val0 = C0->getValueAPF();
530         APFloat Val1 = C1->getValueAPF();
531         Val0.convert(HalfSem, APFloat::rmTowardZero, &LosesInfo);
532         Val1.convert(HalfSem, APFloat::rmTowardZero, &LosesInfo);
533 
534         Constant *Folded =
535             ConstantVector::get({ConstantFP::get(II.getContext(), Val0),
536                                  ConstantFP::get(II.getContext(), Val1)});
537         return IC.replaceInstUsesWith(II, Folded);
538       }
539     }
540 
541     if (isa<UndefValue>(Src0) && isa<UndefValue>(Src1)) {
542       return IC.replaceInstUsesWith(II, UndefValue::get(II.getType()));
543     }
544 
545     break;
546   }
547   case Intrinsic::amdgcn_cvt_pknorm_i16:
548   case Intrinsic::amdgcn_cvt_pknorm_u16:
549   case Intrinsic::amdgcn_cvt_pk_i16:
550   case Intrinsic::amdgcn_cvt_pk_u16: {
551     Value *Src0 = II.getArgOperand(0);
552     Value *Src1 = II.getArgOperand(1);
553 
554     if (isa<UndefValue>(Src0) && isa<UndefValue>(Src1)) {
555       return IC.replaceInstUsesWith(II, UndefValue::get(II.getType()));
556     }
557 
558     break;
559   }
560   case Intrinsic::amdgcn_ubfe:
561   case Intrinsic::amdgcn_sbfe: {
562     // Decompose simple cases into standard shifts.
563     Value *Src = II.getArgOperand(0);
564     if (isa<UndefValue>(Src)) {
565       return IC.replaceInstUsesWith(II, Src);
566     }
567 
568     unsigned Width;
569     Type *Ty = II.getType();
570     unsigned IntSize = Ty->getIntegerBitWidth();
571 
572     ConstantInt *CWidth = dyn_cast<ConstantInt>(II.getArgOperand(2));
573     if (CWidth) {
574       Width = CWidth->getZExtValue();
575       if ((Width & (IntSize - 1)) == 0) {
576         return IC.replaceInstUsesWith(II, ConstantInt::getNullValue(Ty));
577       }
578 
579       // Hardware ignores high bits, so remove those.
580       if (Width >= IntSize) {
581         return IC.replaceOperand(
582             II, 2, ConstantInt::get(CWidth->getType(), Width & (IntSize - 1)));
583       }
584     }
585 
586     unsigned Offset;
587     ConstantInt *COffset = dyn_cast<ConstantInt>(II.getArgOperand(1));
588     if (COffset) {
589       Offset = COffset->getZExtValue();
590       if (Offset >= IntSize) {
591         return IC.replaceOperand(
592             II, 1,
593             ConstantInt::get(COffset->getType(), Offset & (IntSize - 1)));
594       }
595     }
596 
597     bool Signed = IID == Intrinsic::amdgcn_sbfe;
598 
599     if (!CWidth || !COffset)
600       break;
601 
602     // The case of Width == 0 is handled above, which makes this transformation
603     // safe.  If Width == 0, then the ashr and lshr instructions become poison
604     // value since the shift amount would be equal to the bit size.
605     assert(Width != 0);
606 
607     // TODO: This allows folding to undef when the hardware has specific
608     // behavior?
609     if (Offset + Width < IntSize) {
610       Value *Shl = IC.Builder.CreateShl(Src, IntSize - Offset - Width);
611       Value *RightShift = Signed ? IC.Builder.CreateAShr(Shl, IntSize - Width)
612                                  : IC.Builder.CreateLShr(Shl, IntSize - Width);
613       RightShift->takeName(&II);
614       return IC.replaceInstUsesWith(II, RightShift);
615     }
616 
617     Value *RightShift = Signed ? IC.Builder.CreateAShr(Src, Offset)
618                                : IC.Builder.CreateLShr(Src, Offset);
619 
620     RightShift->takeName(&II);
621     return IC.replaceInstUsesWith(II, RightShift);
622   }
623   case Intrinsic::amdgcn_exp:
624   case Intrinsic::amdgcn_exp_compr: {
625     ConstantInt *En = cast<ConstantInt>(II.getArgOperand(1));
626     unsigned EnBits = En->getZExtValue();
627     if (EnBits == 0xf)
628       break; // All inputs enabled.
629 
630     bool IsCompr = IID == Intrinsic::amdgcn_exp_compr;
631     bool Changed = false;
632     for (int I = 0; I < (IsCompr ? 2 : 4); ++I) {
633       if ((!IsCompr && (EnBits & (1 << I)) == 0) ||
634           (IsCompr && ((EnBits & (0x3 << (2 * I))) == 0))) {
635         Value *Src = II.getArgOperand(I + 2);
636         if (!isa<UndefValue>(Src)) {
637           IC.replaceOperand(II, I + 2, UndefValue::get(Src->getType()));
638           Changed = true;
639         }
640       }
641     }
642 
643     if (Changed) {
644       return &II;
645     }
646 
647     break;
648   }
649   case Intrinsic::amdgcn_fmed3: {
650     // Note this does not preserve proper sNaN behavior if IEEE-mode is enabled
651     // for the shader.
652 
653     Value *Src0 = II.getArgOperand(0);
654     Value *Src1 = II.getArgOperand(1);
655     Value *Src2 = II.getArgOperand(2);
656 
657     // Checking for NaN before canonicalization provides better fidelity when
658     // mapping other operations onto fmed3 since the order of operands is
659     // unchanged.
660     CallInst *NewCall = nullptr;
661     if (match(Src0, PatternMatch::m_NaN()) || isa<UndefValue>(Src0)) {
662       NewCall = IC.Builder.CreateMinNum(Src1, Src2);
663     } else if (match(Src1, PatternMatch::m_NaN()) || isa<UndefValue>(Src1)) {
664       NewCall = IC.Builder.CreateMinNum(Src0, Src2);
665     } else if (match(Src2, PatternMatch::m_NaN()) || isa<UndefValue>(Src2)) {
666       NewCall = IC.Builder.CreateMaxNum(Src0, Src1);
667     }
668 
669     if (NewCall) {
670       NewCall->copyFastMathFlags(&II);
671       NewCall->takeName(&II);
672       return IC.replaceInstUsesWith(II, NewCall);
673     }
674 
675     bool Swap = false;
676     // Canonicalize constants to RHS operands.
677     //
678     // fmed3(c0, x, c1) -> fmed3(x, c0, c1)
679     if (isa<Constant>(Src0) && !isa<Constant>(Src1)) {
680       std::swap(Src0, Src1);
681       Swap = true;
682     }
683 
684     if (isa<Constant>(Src1) && !isa<Constant>(Src2)) {
685       std::swap(Src1, Src2);
686       Swap = true;
687     }
688 
689     if (isa<Constant>(Src0) && !isa<Constant>(Src1)) {
690       std::swap(Src0, Src1);
691       Swap = true;
692     }
693 
694     if (Swap) {
695       II.setArgOperand(0, Src0);
696       II.setArgOperand(1, Src1);
697       II.setArgOperand(2, Src2);
698       return &II;
699     }
700 
701     if (const ConstantFP *C0 = dyn_cast<ConstantFP>(Src0)) {
702       if (const ConstantFP *C1 = dyn_cast<ConstantFP>(Src1)) {
703         if (const ConstantFP *C2 = dyn_cast<ConstantFP>(Src2)) {
704           APFloat Result = fmed3AMDGCN(C0->getValueAPF(), C1->getValueAPF(),
705                                        C2->getValueAPF());
706           return IC.replaceInstUsesWith(
707               II, ConstantFP::get(IC.Builder.getContext(), Result));
708         }
709       }
710     }
711 
712     break;
713   }
714   case Intrinsic::amdgcn_icmp:
715   case Intrinsic::amdgcn_fcmp: {
716     const ConstantInt *CC = cast<ConstantInt>(II.getArgOperand(2));
717     // Guard against invalid arguments.
718     int64_t CCVal = CC->getZExtValue();
719     bool IsInteger = IID == Intrinsic::amdgcn_icmp;
720     if ((IsInteger && (CCVal < CmpInst::FIRST_ICMP_PREDICATE ||
721                        CCVal > CmpInst::LAST_ICMP_PREDICATE)) ||
722         (!IsInteger && (CCVal < CmpInst::FIRST_FCMP_PREDICATE ||
723                         CCVal > CmpInst::LAST_FCMP_PREDICATE)))
724       break;
725 
726     Value *Src0 = II.getArgOperand(0);
727     Value *Src1 = II.getArgOperand(1);
728 
729     if (auto *CSrc0 = dyn_cast<Constant>(Src0)) {
730       if (auto *CSrc1 = dyn_cast<Constant>(Src1)) {
731         Constant *CCmp = ConstantExpr::getCompare(CCVal, CSrc0, CSrc1);
732         if (CCmp->isNullValue()) {
733           return IC.replaceInstUsesWith(
734               II, ConstantExpr::getSExt(CCmp, II.getType()));
735         }
736 
737         // The result of V_ICMP/V_FCMP assembly instructions (which this
738         // intrinsic exposes) is one bit per thread, masked with the EXEC
739         // register (which contains the bitmask of live threads). So a
740         // comparison that always returns true is the same as a read of the
741         // EXEC register.
742         Function *NewF = Intrinsic::getDeclaration(
743             II.getModule(), Intrinsic::read_register, II.getType());
744         Metadata *MDArgs[] = {MDString::get(II.getContext(), "exec")};
745         MDNode *MD = MDNode::get(II.getContext(), MDArgs);
746         Value *Args[] = {MetadataAsValue::get(II.getContext(), MD)};
747         CallInst *NewCall = IC.Builder.CreateCall(NewF, Args);
748         NewCall->addFnAttr(Attribute::Convergent);
749         NewCall->takeName(&II);
750         return IC.replaceInstUsesWith(II, NewCall);
751       }
752 
753       // Canonicalize constants to RHS.
754       CmpInst::Predicate SwapPred =
755           CmpInst::getSwappedPredicate(static_cast<CmpInst::Predicate>(CCVal));
756       II.setArgOperand(0, Src1);
757       II.setArgOperand(1, Src0);
758       II.setArgOperand(
759           2, ConstantInt::get(CC->getType(), static_cast<int>(SwapPred)));
760       return &II;
761     }
762 
763     if (CCVal != CmpInst::ICMP_EQ && CCVal != CmpInst::ICMP_NE)
764       break;
765 
766     // Canonicalize compare eq with true value to compare != 0
767     // llvm.amdgcn.icmp(zext (i1 x), 1, eq)
768     //   -> llvm.amdgcn.icmp(zext (i1 x), 0, ne)
769     // llvm.amdgcn.icmp(sext (i1 x), -1, eq)
770     //   -> llvm.amdgcn.icmp(sext (i1 x), 0, ne)
771     Value *ExtSrc;
772     if (CCVal == CmpInst::ICMP_EQ &&
773         ((match(Src1, PatternMatch::m_One()) &&
774           match(Src0, m_ZExt(PatternMatch::m_Value(ExtSrc)))) ||
775          (match(Src1, PatternMatch::m_AllOnes()) &&
776           match(Src0, m_SExt(PatternMatch::m_Value(ExtSrc))))) &&
777         ExtSrc->getType()->isIntegerTy(1)) {
778       IC.replaceOperand(II, 1, ConstantInt::getNullValue(Src1->getType()));
779       IC.replaceOperand(II, 2,
780                         ConstantInt::get(CC->getType(), CmpInst::ICMP_NE));
781       return &II;
782     }
783 
784     CmpInst::Predicate SrcPred;
785     Value *SrcLHS;
786     Value *SrcRHS;
787 
788     // Fold compare eq/ne with 0 from a compare result as the predicate to the
789     // intrinsic. The typical use is a wave vote function in the library, which
790     // will be fed from a user code condition compared with 0. Fold in the
791     // redundant compare.
792 
793     // llvm.amdgcn.icmp([sz]ext ([if]cmp pred a, b), 0, ne)
794     //   -> llvm.amdgcn.[if]cmp(a, b, pred)
795     //
796     // llvm.amdgcn.icmp([sz]ext ([if]cmp pred a, b), 0, eq)
797     //   -> llvm.amdgcn.[if]cmp(a, b, inv pred)
798     if (match(Src1, PatternMatch::m_Zero()) &&
799         match(Src0, PatternMatch::m_ZExtOrSExt(
800                         m_Cmp(SrcPred, PatternMatch::m_Value(SrcLHS),
801                               PatternMatch::m_Value(SrcRHS))))) {
802       if (CCVal == CmpInst::ICMP_EQ)
803         SrcPred = CmpInst::getInversePredicate(SrcPred);
804 
805       Intrinsic::ID NewIID = CmpInst::isFPPredicate(SrcPred)
806                                  ? Intrinsic::amdgcn_fcmp
807                                  : Intrinsic::amdgcn_icmp;
808 
809       Type *Ty = SrcLHS->getType();
810       if (auto *CmpType = dyn_cast<IntegerType>(Ty)) {
811         // Promote to next legal integer type.
812         unsigned Width = CmpType->getBitWidth();
813         unsigned NewWidth = Width;
814 
815         // Don't do anything for i1 comparisons.
816         if (Width == 1)
817           break;
818 
819         if (Width <= 16)
820           NewWidth = 16;
821         else if (Width <= 32)
822           NewWidth = 32;
823         else if (Width <= 64)
824           NewWidth = 64;
825         else if (Width > 64)
826           break; // Can't handle this.
827 
828         if (Width != NewWidth) {
829           IntegerType *CmpTy = IC.Builder.getIntNTy(NewWidth);
830           if (CmpInst::isSigned(SrcPred)) {
831             SrcLHS = IC.Builder.CreateSExt(SrcLHS, CmpTy);
832             SrcRHS = IC.Builder.CreateSExt(SrcRHS, CmpTy);
833           } else {
834             SrcLHS = IC.Builder.CreateZExt(SrcLHS, CmpTy);
835             SrcRHS = IC.Builder.CreateZExt(SrcRHS, CmpTy);
836           }
837         }
838       } else if (!Ty->isFloatTy() && !Ty->isDoubleTy() && !Ty->isHalfTy())
839         break;
840 
841       Function *NewF = Intrinsic::getDeclaration(
842           II.getModule(), NewIID, {II.getType(), SrcLHS->getType()});
843       Value *Args[] = {SrcLHS, SrcRHS,
844                        ConstantInt::get(CC->getType(), SrcPred)};
845       CallInst *NewCall = IC.Builder.CreateCall(NewF, Args);
846       NewCall->takeName(&II);
847       return IC.replaceInstUsesWith(II, NewCall);
848     }
849 
850     break;
851   }
852   case Intrinsic::amdgcn_ballot: {
853     if (auto *Src = dyn_cast<ConstantInt>(II.getArgOperand(0))) {
854       if (Src->isZero()) {
855         // amdgcn.ballot(i1 0) is zero.
856         return IC.replaceInstUsesWith(II, Constant::getNullValue(II.getType()));
857       }
858 
859       if (Src->isOne()) {
860         // amdgcn.ballot(i1 1) is exec.
861         const char *RegName = "exec";
862         if (II.getType()->isIntegerTy(32))
863           RegName = "exec_lo";
864         else if (!II.getType()->isIntegerTy(64))
865           break;
866 
867         Function *NewF = Intrinsic::getDeclaration(
868             II.getModule(), Intrinsic::read_register, II.getType());
869         Metadata *MDArgs[] = {MDString::get(II.getContext(), RegName)};
870         MDNode *MD = MDNode::get(II.getContext(), MDArgs);
871         Value *Args[] = {MetadataAsValue::get(II.getContext(), MD)};
872         CallInst *NewCall = IC.Builder.CreateCall(NewF, Args);
873         NewCall->addFnAttr(Attribute::Convergent);
874         NewCall->takeName(&II);
875         return IC.replaceInstUsesWith(II, NewCall);
876       }
877     }
878     break;
879   }
880   case Intrinsic::amdgcn_wqm_vote: {
881     // wqm_vote is identity when the argument is constant.
882     if (!isa<Constant>(II.getArgOperand(0)))
883       break;
884 
885     return IC.replaceInstUsesWith(II, II.getArgOperand(0));
886   }
887   case Intrinsic::amdgcn_kill: {
888     const ConstantInt *C = dyn_cast<ConstantInt>(II.getArgOperand(0));
889     if (!C || !C->getZExtValue())
890       break;
891 
892     // amdgcn.kill(i1 1) is a no-op
893     return IC.eraseInstFromFunction(II);
894   }
895   case Intrinsic::amdgcn_update_dpp: {
896     Value *Old = II.getArgOperand(0);
897 
898     auto *BC = cast<ConstantInt>(II.getArgOperand(5));
899     auto *RM = cast<ConstantInt>(II.getArgOperand(3));
900     auto *BM = cast<ConstantInt>(II.getArgOperand(4));
901     if (BC->isZeroValue() || RM->getZExtValue() != 0xF ||
902         BM->getZExtValue() != 0xF || isa<UndefValue>(Old))
903       break;
904 
905     // If bound_ctrl = 1, row mask = bank mask = 0xf we can omit old value.
906     return IC.replaceOperand(II, 0, UndefValue::get(Old->getType()));
907   }
908   case Intrinsic::amdgcn_permlane16:
909   case Intrinsic::amdgcn_permlanex16: {
910     // Discard vdst_in if it's not going to be read.
911     Value *VDstIn = II.getArgOperand(0);
912     if (isa<UndefValue>(VDstIn))
913       break;
914 
915     ConstantInt *FetchInvalid = cast<ConstantInt>(II.getArgOperand(4));
916     ConstantInt *BoundCtrl = cast<ConstantInt>(II.getArgOperand(5));
917     if (!FetchInvalid->getZExtValue() && !BoundCtrl->getZExtValue())
918       break;
919 
920     return IC.replaceOperand(II, 0, UndefValue::get(VDstIn->getType()));
921   }
922   case Intrinsic::amdgcn_permlane64:
923     // A constant value is trivially uniform.
924     if (Constant *C = dyn_cast<Constant>(II.getArgOperand(0))) {
925       return IC.replaceInstUsesWith(II, C);
926     }
927     break;
928   case Intrinsic::amdgcn_readfirstlane:
929   case Intrinsic::amdgcn_readlane: {
930     // A constant value is trivially uniform.
931     if (Constant *C = dyn_cast<Constant>(II.getArgOperand(0))) {
932       return IC.replaceInstUsesWith(II, C);
933     }
934 
935     // The rest of these may not be safe if the exec may not be the same between
936     // the def and use.
937     Value *Src = II.getArgOperand(0);
938     Instruction *SrcInst = dyn_cast<Instruction>(Src);
939     if (SrcInst && SrcInst->getParent() != II.getParent())
940       break;
941 
942     // readfirstlane (readfirstlane x) -> readfirstlane x
943     // readlane (readfirstlane x), y -> readfirstlane x
944     if (match(Src,
945               PatternMatch::m_Intrinsic<Intrinsic::amdgcn_readfirstlane>())) {
946       return IC.replaceInstUsesWith(II, Src);
947     }
948 
949     if (IID == Intrinsic::amdgcn_readfirstlane) {
950       // readfirstlane (readlane x, y) -> readlane x, y
951       if (match(Src, PatternMatch::m_Intrinsic<Intrinsic::amdgcn_readlane>())) {
952         return IC.replaceInstUsesWith(II, Src);
953       }
954     } else {
955       // readlane (readlane x, y), y -> readlane x, y
956       if (match(Src, PatternMatch::m_Intrinsic<Intrinsic::amdgcn_readlane>(
957                          PatternMatch::m_Value(),
958                          PatternMatch::m_Specific(II.getArgOperand(1))))) {
959         return IC.replaceInstUsesWith(II, Src);
960       }
961     }
962 
963     break;
964   }
965   case Intrinsic::amdgcn_ldexp: {
966     // FIXME: This doesn't introduce new instructions and belongs in
967     // InstructionSimplify.
968     Type *Ty = II.getType();
969     Value *Op0 = II.getArgOperand(0);
970     Value *Op1 = II.getArgOperand(1);
971 
972     // Folding undef to qnan is safe regardless of the FP mode.
973     if (isa<UndefValue>(Op0)) {
974       auto *QNaN = ConstantFP::get(Ty, APFloat::getQNaN(Ty->getFltSemantics()));
975       return IC.replaceInstUsesWith(II, QNaN);
976     }
977 
978     const APFloat *C = nullptr;
979     match(Op0, PatternMatch::m_APFloat(C));
980 
981     // FIXME: Should flush denorms depending on FP mode, but that's ignored
982     // everywhere else.
983     //
984     // These cases should be safe, even with strictfp.
985     // ldexp(0.0, x) -> 0.0
986     // ldexp(-0.0, x) -> -0.0
987     // ldexp(inf, x) -> inf
988     // ldexp(-inf, x) -> -inf
989     if (C && (C->isZero() || C->isInfinity())) {
990       return IC.replaceInstUsesWith(II, Op0);
991     }
992 
993     // With strictfp, be more careful about possibly needing to flush denormals
994     // or not, and snan behavior depends on ieee_mode.
995     if (II.isStrictFP())
996       break;
997 
998     if (C && C->isNaN()) {
999       // FIXME: We just need to make the nan quiet here, but that's unavailable
1000       // on APFloat, only IEEEfloat
1001       auto *Quieted =
1002           ConstantFP::get(Ty, scalbn(*C, 0, APFloat::rmNearestTiesToEven));
1003       return IC.replaceInstUsesWith(II, Quieted);
1004     }
1005 
1006     // ldexp(x, 0) -> x
1007     // ldexp(x, undef) -> x
1008     if (isa<UndefValue>(Op1) || match(Op1, PatternMatch::m_ZeroInt())) {
1009       return IC.replaceInstUsesWith(II, Op0);
1010     }
1011 
1012     break;
1013   }
1014   case Intrinsic::amdgcn_fmul_legacy: {
1015     Value *Op0 = II.getArgOperand(0);
1016     Value *Op1 = II.getArgOperand(1);
1017 
1018     // The legacy behaviour is that multiplying +/-0.0 by anything, even NaN or
1019     // infinity, gives +0.0.
1020     // TODO: Move to InstSimplify?
1021     if (match(Op0, PatternMatch::m_AnyZeroFP()) ||
1022         match(Op1, PatternMatch::m_AnyZeroFP()))
1023       return IC.replaceInstUsesWith(II, ConstantFP::getNullValue(II.getType()));
1024 
1025     // If we can prove we don't have one of the special cases then we can use a
1026     // normal fmul instruction instead.
1027     if (canSimplifyLegacyMulToMul(Op0, Op1, IC)) {
1028       auto *FMul = IC.Builder.CreateFMulFMF(Op0, Op1, &II);
1029       FMul->takeName(&II);
1030       return IC.replaceInstUsesWith(II, FMul);
1031     }
1032     break;
1033   }
1034   case Intrinsic::amdgcn_fma_legacy: {
1035     Value *Op0 = II.getArgOperand(0);
1036     Value *Op1 = II.getArgOperand(1);
1037     Value *Op2 = II.getArgOperand(2);
1038 
1039     // The legacy behaviour is that multiplying +/-0.0 by anything, even NaN or
1040     // infinity, gives +0.0.
1041     // TODO: Move to InstSimplify?
1042     if (match(Op0, PatternMatch::m_AnyZeroFP()) ||
1043         match(Op1, PatternMatch::m_AnyZeroFP())) {
1044       // It's tempting to just return Op2 here, but that would give the wrong
1045       // result if Op2 was -0.0.
1046       auto *Zero = ConstantFP::getNullValue(II.getType());
1047       auto *FAdd = IC.Builder.CreateFAddFMF(Zero, Op2, &II);
1048       FAdd->takeName(&II);
1049       return IC.replaceInstUsesWith(II, FAdd);
1050     }
1051 
1052     // If we can prove we don't have one of the special cases then we can use a
1053     // normal fma instead.
1054     if (canSimplifyLegacyMulToMul(Op0, Op1, IC)) {
1055       II.setCalledOperand(Intrinsic::getDeclaration(
1056           II.getModule(), Intrinsic::fma, II.getType()));
1057       return &II;
1058     }
1059     break;
1060   }
1061   case Intrinsic::amdgcn_is_shared:
1062   case Intrinsic::amdgcn_is_private: {
1063     if (isa<UndefValue>(II.getArgOperand(0)))
1064       return IC.replaceInstUsesWith(II, UndefValue::get(II.getType()));
1065 
1066     if (isa<ConstantPointerNull>(II.getArgOperand(0)))
1067       return IC.replaceInstUsesWith(II, ConstantInt::getFalse(II.getType()));
1068     break;
1069   }
1070   default: {
1071     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
1072             AMDGPU::getImageDimIntrinsicInfo(II.getIntrinsicID())) {
1073       return simplifyAMDGCNImageIntrinsic(ST, ImageDimIntr, II, IC);
1074     }
1075   }
1076   }
1077   return None;
1078 }
1079 
1080 /// Implement SimplifyDemandedVectorElts for amdgcn buffer and image intrinsics.
1081 ///
1082 /// Note: This only supports non-TFE/LWE image intrinsic calls; those have
1083 ///       struct returns.
1084 static Value *simplifyAMDGCNMemoryIntrinsicDemanded(InstCombiner &IC,
1085                                                     IntrinsicInst &II,
1086                                                     APInt DemandedElts,
1087                                                     int DMaskIdx = -1) {
1088 
1089   auto *IIVTy = cast<FixedVectorType>(II.getType());
1090   unsigned VWidth = IIVTy->getNumElements();
1091   if (VWidth == 1)
1092     return nullptr;
1093 
1094   IRBuilderBase::InsertPointGuard Guard(IC.Builder);
1095   IC.Builder.SetInsertPoint(&II);
1096 
1097   // Assume the arguments are unchanged and later override them, if needed.
1098   SmallVector<Value *, 16> Args(II.args());
1099 
1100   if (DMaskIdx < 0) {
1101     // Buffer case.
1102 
1103     const unsigned ActiveBits = DemandedElts.getActiveBits();
1104     const unsigned UnusedComponentsAtFront = DemandedElts.countTrailingZeros();
1105 
1106     // Start assuming the prefix of elements is demanded, but possibly clear
1107     // some other bits if there are trailing zeros (unused components at front)
1108     // and update offset.
1109     DemandedElts = (1 << ActiveBits) - 1;
1110 
1111     if (UnusedComponentsAtFront > 0) {
1112       static const unsigned InvalidOffsetIdx = 0xf;
1113 
1114       unsigned OffsetIdx;
1115       switch (II.getIntrinsicID()) {
1116       case Intrinsic::amdgcn_raw_buffer_load:
1117         OffsetIdx = 1;
1118         break;
1119       case Intrinsic::amdgcn_s_buffer_load:
1120         // If resulting type is vec3, there is no point in trimming the
1121         // load with updated offset, as the vec3 would most likely be widened to
1122         // vec4 anyway during lowering.
1123         if (ActiveBits == 4 && UnusedComponentsAtFront == 1)
1124           OffsetIdx = InvalidOffsetIdx;
1125         else
1126           OffsetIdx = 1;
1127         break;
1128       case Intrinsic::amdgcn_struct_buffer_load:
1129         OffsetIdx = 2;
1130         break;
1131       default:
1132         // TODO: handle tbuffer* intrinsics.
1133         OffsetIdx = InvalidOffsetIdx;
1134         break;
1135       }
1136 
1137       if (OffsetIdx != InvalidOffsetIdx) {
1138         // Clear demanded bits and update the offset.
1139         DemandedElts &= ~((1 << UnusedComponentsAtFront) - 1);
1140         auto *Offset = II.getArgOperand(OffsetIdx);
1141         unsigned SingleComponentSizeInBits =
1142             IC.getDataLayout().getTypeSizeInBits(II.getType()->getScalarType());
1143         unsigned OffsetAdd =
1144             UnusedComponentsAtFront * SingleComponentSizeInBits / 8;
1145         auto *OffsetAddVal = ConstantInt::get(Offset->getType(), OffsetAdd);
1146         Args[OffsetIdx] = IC.Builder.CreateAdd(Offset, OffsetAddVal);
1147       }
1148     }
1149   } else {
1150     // Image case.
1151 
1152     ConstantInt *DMask = cast<ConstantInt>(II.getArgOperand(DMaskIdx));
1153     unsigned DMaskVal = DMask->getZExtValue() & 0xf;
1154 
1155     // Mask off values that are undefined because the dmask doesn't cover them
1156     DemandedElts &= (1 << countPopulation(DMaskVal)) - 1;
1157 
1158     unsigned NewDMaskVal = 0;
1159     unsigned OrigLoadIdx = 0;
1160     for (unsigned SrcIdx = 0; SrcIdx < 4; ++SrcIdx) {
1161       const unsigned Bit = 1 << SrcIdx;
1162       if (!!(DMaskVal & Bit)) {
1163         if (!!DemandedElts[OrigLoadIdx])
1164           NewDMaskVal |= Bit;
1165         OrigLoadIdx++;
1166       }
1167     }
1168 
1169     if (DMaskVal != NewDMaskVal)
1170       Args[DMaskIdx] = ConstantInt::get(DMask->getType(), NewDMaskVal);
1171   }
1172 
1173   unsigned NewNumElts = DemandedElts.countPopulation();
1174   if (!NewNumElts)
1175     return UndefValue::get(II.getType());
1176 
1177   if (NewNumElts >= VWidth && DemandedElts.isMask()) {
1178     if (DMaskIdx >= 0)
1179       II.setArgOperand(DMaskIdx, Args[DMaskIdx]);
1180     return nullptr;
1181   }
1182 
1183   // Validate function argument and return types, extracting overloaded types
1184   // along the way.
1185   SmallVector<Type *, 6> OverloadTys;
1186   if (!Intrinsic::getIntrinsicSignature(II.getCalledFunction(), OverloadTys))
1187     return nullptr;
1188 
1189   Module *M = II.getParent()->getParent()->getParent();
1190   Type *EltTy = IIVTy->getElementType();
1191   Type *NewTy =
1192       (NewNumElts == 1) ? EltTy : FixedVectorType::get(EltTy, NewNumElts);
1193 
1194   OverloadTys[0] = NewTy;
1195   Function *NewIntrin =
1196       Intrinsic::getDeclaration(M, II.getIntrinsicID(), OverloadTys);
1197 
1198   CallInst *NewCall = IC.Builder.CreateCall(NewIntrin, Args);
1199   NewCall->takeName(&II);
1200   NewCall->copyMetadata(II);
1201 
1202   if (NewNumElts == 1) {
1203     return IC.Builder.CreateInsertElement(UndefValue::get(II.getType()),
1204                                           NewCall,
1205                                           DemandedElts.countTrailingZeros());
1206   }
1207 
1208   SmallVector<int, 8> EltMask;
1209   unsigned NewLoadIdx = 0;
1210   for (unsigned OrigLoadIdx = 0; OrigLoadIdx < VWidth; ++OrigLoadIdx) {
1211     if (!!DemandedElts[OrigLoadIdx])
1212       EltMask.push_back(NewLoadIdx++);
1213     else
1214       EltMask.push_back(NewNumElts);
1215   }
1216 
1217   Value *Shuffle = IC.Builder.CreateShuffleVector(NewCall, EltMask);
1218 
1219   return Shuffle;
1220 }
1221 
1222 Optional<Value *> GCNTTIImpl::simplifyDemandedVectorEltsIntrinsic(
1223     InstCombiner &IC, IntrinsicInst &II, APInt DemandedElts, APInt &UndefElts,
1224     APInt &UndefElts2, APInt &UndefElts3,
1225     std::function<void(Instruction *, unsigned, APInt, APInt &)>
1226         SimplifyAndSetOp) const {
1227   switch (II.getIntrinsicID()) {
1228   case Intrinsic::amdgcn_buffer_load:
1229   case Intrinsic::amdgcn_buffer_load_format:
1230   case Intrinsic::amdgcn_raw_buffer_load:
1231   case Intrinsic::amdgcn_raw_buffer_load_format:
1232   case Intrinsic::amdgcn_raw_tbuffer_load:
1233   case Intrinsic::amdgcn_s_buffer_load:
1234   case Intrinsic::amdgcn_struct_buffer_load:
1235   case Intrinsic::amdgcn_struct_buffer_load_format:
1236   case Intrinsic::amdgcn_struct_tbuffer_load:
1237   case Intrinsic::amdgcn_tbuffer_load:
1238     return simplifyAMDGCNMemoryIntrinsicDemanded(IC, II, DemandedElts);
1239   default: {
1240     if (getAMDGPUImageDMaskIntrinsic(II.getIntrinsicID())) {
1241       return simplifyAMDGCNMemoryIntrinsicDemanded(IC, II, DemandedElts, 0);
1242     }
1243     break;
1244   }
1245   }
1246   return None;
1247 }
1248