1fe6060f1SDimitry Andric //===----- CodeGen/ExpandVectorPredication.cpp - Expand VP intrinsics -----===//
2fe6060f1SDimitry Andric //
3fe6060f1SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4fe6060f1SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5fe6060f1SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6fe6060f1SDimitry Andric //
7fe6060f1SDimitry Andric //===----------------------------------------------------------------------===//
8fe6060f1SDimitry Andric //
9fe6060f1SDimitry Andric // This pass implements IR expansion for vector predication intrinsics, allowing
10fe6060f1SDimitry Andric // targets to enable vector predication until just before codegen.
11fe6060f1SDimitry Andric //
12fe6060f1SDimitry Andric //===----------------------------------------------------------------------===//
13fe6060f1SDimitry Andric 
14fe6060f1SDimitry Andric #include "llvm/CodeGen/ExpandVectorPredication.h"
15fe6060f1SDimitry Andric #include "llvm/ADT/Statistic.h"
16fe6060f1SDimitry Andric #include "llvm/Analysis/TargetTransformInfo.h"
17fe6060f1SDimitry Andric #include "llvm/Analysis/ValueTracking.h"
18fcaf7f86SDimitry Andric #include "llvm/Analysis/VectorUtils.h"
19fe6060f1SDimitry Andric #include "llvm/CodeGen/Passes.h"
20fe6060f1SDimitry Andric #include "llvm/IR/Constants.h"
21fe6060f1SDimitry Andric #include "llvm/IR/Function.h"
22fe6060f1SDimitry Andric #include "llvm/IR/IRBuilder.h"
23fe6060f1SDimitry Andric #include "llvm/IR/InstIterator.h"
24fe6060f1SDimitry Andric #include "llvm/IR/Instructions.h"
25fe6060f1SDimitry Andric #include "llvm/IR/IntrinsicInst.h"
26fe6060f1SDimitry Andric #include "llvm/IR/Intrinsics.h"
27fe6060f1SDimitry Andric #include "llvm/InitializePasses.h"
28fe6060f1SDimitry Andric #include "llvm/Pass.h"
29fe6060f1SDimitry Andric #include "llvm/Support/CommandLine.h"
30fe6060f1SDimitry Andric #include "llvm/Support/Compiler.h"
31fe6060f1SDimitry Andric #include "llvm/Support/Debug.h"
32bdd1243dSDimitry Andric #include <optional>
33fe6060f1SDimitry Andric 
34fe6060f1SDimitry Andric using namespace llvm;
35fe6060f1SDimitry Andric 
36fe6060f1SDimitry Andric using VPLegalization = TargetTransformInfo::VPLegalization;
37fe6060f1SDimitry Andric using VPTransform = TargetTransformInfo::VPLegalization::VPTransform;
38fe6060f1SDimitry Andric 
39fe6060f1SDimitry Andric // Keep this in sync with TargetTransformInfo::VPLegalization.
40fe6060f1SDimitry Andric #define VPINTERNAL_VPLEGAL_CASES                                               \
41fe6060f1SDimitry Andric   VPINTERNAL_CASE(Legal)                                                       \
42fe6060f1SDimitry Andric   VPINTERNAL_CASE(Discard)                                                     \
43fe6060f1SDimitry Andric   VPINTERNAL_CASE(Convert)
44fe6060f1SDimitry Andric 
45fe6060f1SDimitry Andric #define VPINTERNAL_CASE(X) "|" #X
46fe6060f1SDimitry Andric 
47fe6060f1SDimitry Andric // Override options.
48fe6060f1SDimitry Andric static cl::opt<std::string> EVLTransformOverride(
49fe6060f1SDimitry Andric     "expandvp-override-evl-transform", cl::init(""), cl::Hidden,
50fe6060f1SDimitry Andric     cl::desc("Options: <empty>" VPINTERNAL_VPLEGAL_CASES
51fe6060f1SDimitry Andric              ". If non-empty, ignore "
52fe6060f1SDimitry Andric              "TargetTransformInfo and "
53fe6060f1SDimitry Andric              "always use this transformation for the %evl parameter (Used in "
54fe6060f1SDimitry Andric              "testing)."));
55fe6060f1SDimitry Andric 
56fe6060f1SDimitry Andric static cl::opt<std::string> MaskTransformOverride(
57fe6060f1SDimitry Andric     "expandvp-override-mask-transform", cl::init(""), cl::Hidden,
58fe6060f1SDimitry Andric     cl::desc("Options: <empty>" VPINTERNAL_VPLEGAL_CASES
59fe6060f1SDimitry Andric              ". If non-empty, Ignore "
60fe6060f1SDimitry Andric              "TargetTransformInfo and "
61fe6060f1SDimitry Andric              "always use this transformation for the %mask parameter (Used in "
62fe6060f1SDimitry Andric              "testing)."));
63fe6060f1SDimitry Andric 
64fe6060f1SDimitry Andric #undef VPINTERNAL_CASE
65fe6060f1SDimitry Andric #define VPINTERNAL_CASE(X) .Case(#X, VPLegalization::X)
66fe6060f1SDimitry Andric 
67fe6060f1SDimitry Andric static VPTransform parseOverrideOption(const std::string &TextOpt) {
68fe6060f1SDimitry Andric   return StringSwitch<VPTransform>(TextOpt) VPINTERNAL_VPLEGAL_CASES;
69fe6060f1SDimitry Andric }
70fe6060f1SDimitry Andric 
71fe6060f1SDimitry Andric #undef VPINTERNAL_VPLEGAL_CASES
72fe6060f1SDimitry Andric 
73fe6060f1SDimitry Andric // Whether any override options are set.
74fe6060f1SDimitry Andric static bool anyExpandVPOverridesSet() {
75fe6060f1SDimitry Andric   return !EVLTransformOverride.empty() || !MaskTransformOverride.empty();
76fe6060f1SDimitry Andric }
77fe6060f1SDimitry Andric 
78fe6060f1SDimitry Andric #define DEBUG_TYPE "expandvp"
79fe6060f1SDimitry Andric 
80fe6060f1SDimitry Andric STATISTIC(NumFoldedVL, "Number of folded vector length params");
81fe6060f1SDimitry Andric STATISTIC(NumLoweredVPOps, "Number of folded vector predication operations");
82fe6060f1SDimitry Andric 
83fe6060f1SDimitry Andric ///// Helpers {
84fe6060f1SDimitry Andric 
85fe6060f1SDimitry Andric /// \returns Whether the vector mask \p MaskVal has all lane bits set.
86fe6060f1SDimitry Andric static bool isAllTrueMask(Value *MaskVal) {
87fcaf7f86SDimitry Andric   if (Value *SplattedVal = getSplatValue(MaskVal))
88fcaf7f86SDimitry Andric     if (auto *ConstValue = dyn_cast<Constant>(SplattedVal))
89fcaf7f86SDimitry Andric       return ConstValue->isAllOnesValue();
90fcaf7f86SDimitry Andric 
91fcaf7f86SDimitry Andric   return false;
92fe6060f1SDimitry Andric }
93fe6060f1SDimitry Andric 
94fe6060f1SDimitry Andric /// \returns A non-excepting divisor constant for this type.
95fe6060f1SDimitry Andric static Constant *getSafeDivisor(Type *DivTy) {
96fe6060f1SDimitry Andric   assert(DivTy->isIntOrIntVectorTy() && "Unsupported divisor type");
97fe6060f1SDimitry Andric   return ConstantInt::get(DivTy, 1u, false);
98fe6060f1SDimitry Andric }
99fe6060f1SDimitry Andric 
100fe6060f1SDimitry Andric /// Transfer operation properties from \p OldVPI to \p NewVal.
101fe6060f1SDimitry Andric static void transferDecorations(Value &NewVal, VPIntrinsic &VPI) {
102fe6060f1SDimitry Andric   auto *NewInst = dyn_cast<Instruction>(&NewVal);
103fe6060f1SDimitry Andric   if (!NewInst || !isa<FPMathOperator>(NewVal))
104fe6060f1SDimitry Andric     return;
105fe6060f1SDimitry Andric 
106fe6060f1SDimitry Andric   auto *OldFMOp = dyn_cast<FPMathOperator>(&VPI);
107fe6060f1SDimitry Andric   if (!OldFMOp)
108fe6060f1SDimitry Andric     return;
109fe6060f1SDimitry Andric 
110fe6060f1SDimitry Andric   NewInst->setFastMathFlags(OldFMOp->getFastMathFlags());
111fe6060f1SDimitry Andric }
112fe6060f1SDimitry Andric 
113fe6060f1SDimitry Andric /// Transfer all properties from \p OldOp to \p NewOp and replace all uses.
114fe6060f1SDimitry Andric /// OldVP gets erased.
115fe6060f1SDimitry Andric static void replaceOperation(Value &NewOp, VPIntrinsic &OldOp) {
116fe6060f1SDimitry Andric   transferDecorations(NewOp, OldOp);
117fe6060f1SDimitry Andric   OldOp.replaceAllUsesWith(&NewOp);
118fe6060f1SDimitry Andric   OldOp.eraseFromParent();
119fe6060f1SDimitry Andric }
120fe6060f1SDimitry Andric 
12181ad6265SDimitry Andric static bool maySpeculateLanes(VPIntrinsic &VPI) {
12281ad6265SDimitry Andric   // The result of VP reductions depends on the mask and evl.
12381ad6265SDimitry Andric   if (isa<VPReductionIntrinsic>(VPI))
12481ad6265SDimitry Andric     return false;
12581ad6265SDimitry Andric   // Fallback to whether the intrinsic is speculatable.
126bdd1243dSDimitry Andric   std::optional<unsigned> OpcOpt = VPI.getFunctionalOpcode();
12781ad6265SDimitry Andric   unsigned FunctionalOpc = OpcOpt.value_or((unsigned)Instruction::Call);
128753f127fSDimitry Andric   return isSafeToSpeculativelyExecuteWithOpcode(FunctionalOpc, &VPI);
12981ad6265SDimitry Andric }
13081ad6265SDimitry Andric 
131fe6060f1SDimitry Andric //// } Helpers
132fe6060f1SDimitry Andric 
133fe6060f1SDimitry Andric namespace {
134fe6060f1SDimitry Andric 
135fe6060f1SDimitry Andric // Expansion pass state at function scope.
136fe6060f1SDimitry Andric struct CachingVPExpander {
137fe6060f1SDimitry Andric   Function &F;
138fe6060f1SDimitry Andric   const TargetTransformInfo &TTI;
139fe6060f1SDimitry Andric 
140fe6060f1SDimitry Andric   /// \returns A (fixed length) vector with ascending integer indices
141fe6060f1SDimitry Andric   /// (<0, 1, ..., NumElems-1>).
142fe6060f1SDimitry Andric   /// \p Builder
143fe6060f1SDimitry Andric   ///    Used for instruction creation.
144fe6060f1SDimitry Andric   /// \p LaneTy
145fe6060f1SDimitry Andric   ///    Integer element type of the result vector.
146fe6060f1SDimitry Andric   /// \p NumElems
147fe6060f1SDimitry Andric   ///    Number of vector elements.
148fe6060f1SDimitry Andric   Value *createStepVector(IRBuilder<> &Builder, Type *LaneTy,
149fe6060f1SDimitry Andric                           unsigned NumElems);
150fe6060f1SDimitry Andric 
151fe6060f1SDimitry Andric   /// \returns A bitmask that is true where the lane position is less-than \p
152fe6060f1SDimitry Andric   /// EVLParam
153fe6060f1SDimitry Andric   ///
154fe6060f1SDimitry Andric   /// \p Builder
155fe6060f1SDimitry Andric   ///    Used for instruction creation.
156fe6060f1SDimitry Andric   /// \p VLParam
157fe6060f1SDimitry Andric   ///    The explicit vector length parameter to test against the lane
158fe6060f1SDimitry Andric   ///    positions.
159fe6060f1SDimitry Andric   /// \p ElemCount
160fe6060f1SDimitry Andric   ///    Static (potentially scalable) number of vector elements.
161fe6060f1SDimitry Andric   Value *convertEVLToMask(IRBuilder<> &Builder, Value *EVLParam,
162fe6060f1SDimitry Andric                           ElementCount ElemCount);
163fe6060f1SDimitry Andric 
164fe6060f1SDimitry Andric   Value *foldEVLIntoMask(VPIntrinsic &VPI);
165fe6060f1SDimitry Andric 
166fe6060f1SDimitry Andric   /// "Remove" the %evl parameter of \p PI by setting it to the static vector
167fe6060f1SDimitry Andric   /// length of the operation.
168fe6060f1SDimitry Andric   void discardEVLParameter(VPIntrinsic &PI);
169fe6060f1SDimitry Andric 
170bdd1243dSDimitry Andric   /// Lower this VP binary operator to a unpredicated binary operator.
171fe6060f1SDimitry Andric   Value *expandPredicationInBinaryOperator(IRBuilder<> &Builder,
172fe6060f1SDimitry Andric                                            VPIntrinsic &PI);
173fe6060f1SDimitry Andric 
174*fe013be4SDimitry Andric   /// Lower this VP fp call to a unpredicated fp call.
175*fe013be4SDimitry Andric   Value *expandPredicationToFPCall(IRBuilder<> &Builder, VPIntrinsic &PI,
176*fe013be4SDimitry Andric                                    unsigned UnpredicatedIntrinsicID);
177*fe013be4SDimitry Andric 
178bdd1243dSDimitry Andric   /// Lower this VP reduction to a call to an unpredicated reduction intrinsic.
179349cc55cSDimitry Andric   Value *expandPredicationInReduction(IRBuilder<> &Builder,
180349cc55cSDimitry Andric                                       VPReductionIntrinsic &PI);
181349cc55cSDimitry Andric 
182bdd1243dSDimitry Andric   /// Lower this VP memory operation to a non-VP intrinsic.
183fcaf7f86SDimitry Andric   Value *expandPredicationInMemoryIntrinsic(IRBuilder<> &Builder,
184fcaf7f86SDimitry Andric                                             VPIntrinsic &VPI);
185fcaf7f86SDimitry Andric 
186bdd1243dSDimitry Andric   /// Lower this VP comparison to a call to an unpredicated comparison.
187bdd1243dSDimitry Andric   Value *expandPredicationInComparison(IRBuilder<> &Builder,
188bdd1243dSDimitry Andric                                        VPCmpIntrinsic &PI);
189bdd1243dSDimitry Andric 
190bdd1243dSDimitry Andric   /// Query TTI and expand the vector predication in \p P accordingly.
191fe6060f1SDimitry Andric   Value *expandPredication(VPIntrinsic &PI);
192fe6060f1SDimitry Andric 
193bdd1243dSDimitry Andric   /// Determine how and whether the VPIntrinsic \p VPI shall be expanded. This
194bdd1243dSDimitry Andric   /// overrides TTI with the cl::opts listed at the top of this file.
195fe6060f1SDimitry Andric   VPLegalization getVPLegalizationStrategy(const VPIntrinsic &VPI) const;
196fe6060f1SDimitry Andric   bool UsingTTIOverrides;
197fe6060f1SDimitry Andric 
198fe6060f1SDimitry Andric public:
199fe6060f1SDimitry Andric   CachingVPExpander(Function &F, const TargetTransformInfo &TTI)
200fe6060f1SDimitry Andric       : F(F), TTI(TTI), UsingTTIOverrides(anyExpandVPOverridesSet()) {}
201fe6060f1SDimitry Andric 
202fe6060f1SDimitry Andric   bool expandVectorPredication();
203fe6060f1SDimitry Andric };
204fe6060f1SDimitry Andric 
205fe6060f1SDimitry Andric //// CachingVPExpander {
206fe6060f1SDimitry Andric 
207fe6060f1SDimitry Andric Value *CachingVPExpander::createStepVector(IRBuilder<> &Builder, Type *LaneTy,
208fe6060f1SDimitry Andric                                            unsigned NumElems) {
209fe6060f1SDimitry Andric   // TODO add caching
210fe6060f1SDimitry Andric   SmallVector<Constant *, 16> ConstElems;
211fe6060f1SDimitry Andric 
212fe6060f1SDimitry Andric   for (unsigned Idx = 0; Idx < NumElems; ++Idx)
213fe6060f1SDimitry Andric     ConstElems.push_back(ConstantInt::get(LaneTy, Idx, false));
214fe6060f1SDimitry Andric 
215fe6060f1SDimitry Andric   return ConstantVector::get(ConstElems);
216fe6060f1SDimitry Andric }
217fe6060f1SDimitry Andric 
218fe6060f1SDimitry Andric Value *CachingVPExpander::convertEVLToMask(IRBuilder<> &Builder,
219fe6060f1SDimitry Andric                                            Value *EVLParam,
220fe6060f1SDimitry Andric                                            ElementCount ElemCount) {
221fe6060f1SDimitry Andric   // TODO add caching
222fe6060f1SDimitry Andric   // Scalable vector %evl conversion.
223fe6060f1SDimitry Andric   if (ElemCount.isScalable()) {
224fe6060f1SDimitry Andric     auto *M = Builder.GetInsertBlock()->getModule();
225fe6060f1SDimitry Andric     Type *BoolVecTy = VectorType::get(Builder.getInt1Ty(), ElemCount);
226fe6060f1SDimitry Andric     Function *ActiveMaskFunc = Intrinsic::getDeclaration(
227fe6060f1SDimitry Andric         M, Intrinsic::get_active_lane_mask, {BoolVecTy, EVLParam->getType()});
228fe6060f1SDimitry Andric     // `get_active_lane_mask` performs an implicit less-than comparison.
229fe6060f1SDimitry Andric     Value *ConstZero = Builder.getInt32(0);
230fe6060f1SDimitry Andric     return Builder.CreateCall(ActiveMaskFunc, {ConstZero, EVLParam});
231fe6060f1SDimitry Andric   }
232fe6060f1SDimitry Andric 
233fe6060f1SDimitry Andric   // Fixed vector %evl conversion.
234fe6060f1SDimitry Andric   Type *LaneTy = EVLParam->getType();
235fe6060f1SDimitry Andric   unsigned NumElems = ElemCount.getFixedValue();
236fe6060f1SDimitry Andric   Value *VLSplat = Builder.CreateVectorSplat(NumElems, EVLParam);
237fe6060f1SDimitry Andric   Value *IdxVec = createStepVector(Builder, LaneTy, NumElems);
238fe6060f1SDimitry Andric   return Builder.CreateICmp(CmpInst::ICMP_ULT, IdxVec, VLSplat);
239fe6060f1SDimitry Andric }
240fe6060f1SDimitry Andric 
241fe6060f1SDimitry Andric Value *
242fe6060f1SDimitry Andric CachingVPExpander::expandPredicationInBinaryOperator(IRBuilder<> &Builder,
243fe6060f1SDimitry Andric                                                      VPIntrinsic &VPI) {
24481ad6265SDimitry Andric   assert((maySpeculateLanes(VPI) || VPI.canIgnoreVectorLengthParam()) &&
245fe6060f1SDimitry Andric          "Implicitly dropping %evl in non-speculatable operator!");
246fe6060f1SDimitry Andric 
247fe6060f1SDimitry Andric   auto OC = static_cast<Instruction::BinaryOps>(*VPI.getFunctionalOpcode());
248fe6060f1SDimitry Andric   assert(Instruction::isBinaryOp(OC));
249fe6060f1SDimitry Andric 
250fe6060f1SDimitry Andric   Value *Op0 = VPI.getOperand(0);
251fe6060f1SDimitry Andric   Value *Op1 = VPI.getOperand(1);
252fe6060f1SDimitry Andric   Value *Mask = VPI.getMaskParam();
253fe6060f1SDimitry Andric 
254fe6060f1SDimitry Andric   // Blend in safe operands.
255fe6060f1SDimitry Andric   if (Mask && !isAllTrueMask(Mask)) {
256fe6060f1SDimitry Andric     switch (OC) {
257fe6060f1SDimitry Andric     default:
258fe6060f1SDimitry Andric       // Can safely ignore the predicate.
259fe6060f1SDimitry Andric       break;
260fe6060f1SDimitry Andric 
261fe6060f1SDimitry Andric     // Division operators need a safe divisor on masked-off lanes (1).
262fe6060f1SDimitry Andric     case Instruction::UDiv:
263fe6060f1SDimitry Andric     case Instruction::SDiv:
264fe6060f1SDimitry Andric     case Instruction::URem:
265fe6060f1SDimitry Andric     case Instruction::SRem:
266fe6060f1SDimitry Andric       // 2nd operand must not be zero.
267fe6060f1SDimitry Andric       Value *SafeDivisor = getSafeDivisor(VPI.getType());
268fe6060f1SDimitry Andric       Op1 = Builder.CreateSelect(Mask, Op1, SafeDivisor);
269fe6060f1SDimitry Andric     }
270fe6060f1SDimitry Andric   }
271fe6060f1SDimitry Andric 
272fe6060f1SDimitry Andric   Value *NewBinOp = Builder.CreateBinOp(OC, Op0, Op1, VPI.getName());
273fe6060f1SDimitry Andric 
274fe6060f1SDimitry Andric   replaceOperation(*NewBinOp, VPI);
275fe6060f1SDimitry Andric   return NewBinOp;
276fe6060f1SDimitry Andric }
277fe6060f1SDimitry Andric 
278*fe013be4SDimitry Andric Value *CachingVPExpander::expandPredicationToFPCall(
279*fe013be4SDimitry Andric     IRBuilder<> &Builder, VPIntrinsic &VPI, unsigned UnpredicatedIntrinsicID) {
280*fe013be4SDimitry Andric   assert((maySpeculateLanes(VPI) || VPI.canIgnoreVectorLengthParam()) &&
281*fe013be4SDimitry Andric          "Implicitly dropping %evl in non-speculatable operator!");
282*fe013be4SDimitry Andric 
283*fe013be4SDimitry Andric   switch (UnpredicatedIntrinsicID) {
284*fe013be4SDimitry Andric   case Intrinsic::fabs:
285*fe013be4SDimitry Andric   case Intrinsic::sqrt: {
286*fe013be4SDimitry Andric     Value *Op0 = VPI.getOperand(0);
287*fe013be4SDimitry Andric     Function *Fn = Intrinsic::getDeclaration(
288*fe013be4SDimitry Andric         VPI.getModule(), UnpredicatedIntrinsicID, {VPI.getType()});
289*fe013be4SDimitry Andric     Value *NewOp = Builder.CreateCall(Fn, {Op0}, VPI.getName());
290*fe013be4SDimitry Andric     replaceOperation(*NewOp, VPI);
291*fe013be4SDimitry Andric     return NewOp;
292*fe013be4SDimitry Andric   }
293*fe013be4SDimitry Andric   case Intrinsic::experimental_constrained_fma:
294*fe013be4SDimitry Andric   case Intrinsic::experimental_constrained_fmuladd: {
295*fe013be4SDimitry Andric     Value *Op0 = VPI.getOperand(0);
296*fe013be4SDimitry Andric     Value *Op1 = VPI.getOperand(1);
297*fe013be4SDimitry Andric     Value *Op2 = VPI.getOperand(2);
298*fe013be4SDimitry Andric     Function *Fn = Intrinsic::getDeclaration(
299*fe013be4SDimitry Andric         VPI.getModule(), UnpredicatedIntrinsicID, {VPI.getType()});
300*fe013be4SDimitry Andric     Value *NewOp =
301*fe013be4SDimitry Andric         Builder.CreateConstrainedFPCall(Fn, {Op0, Op1, Op2}, VPI.getName());
302*fe013be4SDimitry Andric     replaceOperation(*NewOp, VPI);
303*fe013be4SDimitry Andric     return NewOp;
304*fe013be4SDimitry Andric   }
305*fe013be4SDimitry Andric   }
306*fe013be4SDimitry Andric 
307*fe013be4SDimitry Andric   return nullptr;
308*fe013be4SDimitry Andric }
309*fe013be4SDimitry Andric 
310349cc55cSDimitry Andric static Value *getNeutralReductionElement(const VPReductionIntrinsic &VPI,
311349cc55cSDimitry Andric                                          Type *EltTy) {
312349cc55cSDimitry Andric   bool Negative = false;
313349cc55cSDimitry Andric   unsigned EltBits = EltTy->getScalarSizeInBits();
314349cc55cSDimitry Andric   switch (VPI.getIntrinsicID()) {
315349cc55cSDimitry Andric   default:
316349cc55cSDimitry Andric     llvm_unreachable("Expecting a VP reduction intrinsic");
317349cc55cSDimitry Andric   case Intrinsic::vp_reduce_add:
318349cc55cSDimitry Andric   case Intrinsic::vp_reduce_or:
319349cc55cSDimitry Andric   case Intrinsic::vp_reduce_xor:
320349cc55cSDimitry Andric   case Intrinsic::vp_reduce_umax:
321349cc55cSDimitry Andric     return Constant::getNullValue(EltTy);
322349cc55cSDimitry Andric   case Intrinsic::vp_reduce_mul:
323349cc55cSDimitry Andric     return ConstantInt::get(EltTy, 1, /*IsSigned*/ false);
324349cc55cSDimitry Andric   case Intrinsic::vp_reduce_and:
325349cc55cSDimitry Andric   case Intrinsic::vp_reduce_umin:
326349cc55cSDimitry Andric     return ConstantInt::getAllOnesValue(EltTy);
327349cc55cSDimitry Andric   case Intrinsic::vp_reduce_smin:
328349cc55cSDimitry Andric     return ConstantInt::get(EltTy->getContext(),
329349cc55cSDimitry Andric                             APInt::getSignedMaxValue(EltBits));
330349cc55cSDimitry Andric   case Intrinsic::vp_reduce_smax:
331349cc55cSDimitry Andric     return ConstantInt::get(EltTy->getContext(),
332349cc55cSDimitry Andric                             APInt::getSignedMinValue(EltBits));
333349cc55cSDimitry Andric   case Intrinsic::vp_reduce_fmax:
334349cc55cSDimitry Andric     Negative = true;
335bdd1243dSDimitry Andric     [[fallthrough]];
336349cc55cSDimitry Andric   case Intrinsic::vp_reduce_fmin: {
337349cc55cSDimitry Andric     FastMathFlags Flags = VPI.getFastMathFlags();
338349cc55cSDimitry Andric     const fltSemantics &Semantics = EltTy->getFltSemantics();
339349cc55cSDimitry Andric     return !Flags.noNaNs() ? ConstantFP::getQNaN(EltTy, Negative)
340349cc55cSDimitry Andric            : !Flags.noInfs()
341349cc55cSDimitry Andric                ? ConstantFP::getInfinity(EltTy, Negative)
342349cc55cSDimitry Andric                : ConstantFP::get(EltTy,
343349cc55cSDimitry Andric                                  APFloat::getLargest(Semantics, Negative));
344349cc55cSDimitry Andric   }
345349cc55cSDimitry Andric   case Intrinsic::vp_reduce_fadd:
346349cc55cSDimitry Andric     return ConstantFP::getNegativeZero(EltTy);
347349cc55cSDimitry Andric   case Intrinsic::vp_reduce_fmul:
348349cc55cSDimitry Andric     return ConstantFP::get(EltTy, 1.0);
349349cc55cSDimitry Andric   }
350349cc55cSDimitry Andric }
351349cc55cSDimitry Andric 
352349cc55cSDimitry Andric Value *
353349cc55cSDimitry Andric CachingVPExpander::expandPredicationInReduction(IRBuilder<> &Builder,
354349cc55cSDimitry Andric                                                 VPReductionIntrinsic &VPI) {
35581ad6265SDimitry Andric   assert((maySpeculateLanes(VPI) || VPI.canIgnoreVectorLengthParam()) &&
356349cc55cSDimitry Andric          "Implicitly dropping %evl in non-speculatable operator!");
357349cc55cSDimitry Andric 
358349cc55cSDimitry Andric   Value *Mask = VPI.getMaskParam();
359349cc55cSDimitry Andric   Value *RedOp = VPI.getOperand(VPI.getVectorParamPos());
360349cc55cSDimitry Andric 
361349cc55cSDimitry Andric   // Insert neutral element in masked-out positions
362349cc55cSDimitry Andric   if (Mask && !isAllTrueMask(Mask)) {
363349cc55cSDimitry Andric     auto *NeutralElt = getNeutralReductionElement(VPI, VPI.getType());
364349cc55cSDimitry Andric     auto *NeutralVector = Builder.CreateVectorSplat(
365349cc55cSDimitry Andric         cast<VectorType>(RedOp->getType())->getElementCount(), NeutralElt);
366349cc55cSDimitry Andric     RedOp = Builder.CreateSelect(Mask, RedOp, NeutralVector);
367349cc55cSDimitry Andric   }
368349cc55cSDimitry Andric 
369349cc55cSDimitry Andric   Value *Reduction;
370349cc55cSDimitry Andric   Value *Start = VPI.getOperand(VPI.getStartParamPos());
371349cc55cSDimitry Andric 
372349cc55cSDimitry Andric   switch (VPI.getIntrinsicID()) {
373349cc55cSDimitry Andric   default:
374349cc55cSDimitry Andric     llvm_unreachable("Impossible reduction kind");
375349cc55cSDimitry Andric   case Intrinsic::vp_reduce_add:
376349cc55cSDimitry Andric     Reduction = Builder.CreateAddReduce(RedOp);
377349cc55cSDimitry Andric     Reduction = Builder.CreateAdd(Reduction, Start);
378349cc55cSDimitry Andric     break;
379349cc55cSDimitry Andric   case Intrinsic::vp_reduce_mul:
380349cc55cSDimitry Andric     Reduction = Builder.CreateMulReduce(RedOp);
381349cc55cSDimitry Andric     Reduction = Builder.CreateMul(Reduction, Start);
382349cc55cSDimitry Andric     break;
383349cc55cSDimitry Andric   case Intrinsic::vp_reduce_and:
384349cc55cSDimitry Andric     Reduction = Builder.CreateAndReduce(RedOp);
385349cc55cSDimitry Andric     Reduction = Builder.CreateAnd(Reduction, Start);
386349cc55cSDimitry Andric     break;
387349cc55cSDimitry Andric   case Intrinsic::vp_reduce_or:
388349cc55cSDimitry Andric     Reduction = Builder.CreateOrReduce(RedOp);
389349cc55cSDimitry Andric     Reduction = Builder.CreateOr(Reduction, Start);
390349cc55cSDimitry Andric     break;
391349cc55cSDimitry Andric   case Intrinsic::vp_reduce_xor:
392349cc55cSDimitry Andric     Reduction = Builder.CreateXorReduce(RedOp);
393349cc55cSDimitry Andric     Reduction = Builder.CreateXor(Reduction, Start);
394349cc55cSDimitry Andric     break;
395349cc55cSDimitry Andric   case Intrinsic::vp_reduce_smax:
396349cc55cSDimitry Andric     Reduction = Builder.CreateIntMaxReduce(RedOp, /*IsSigned*/ true);
397349cc55cSDimitry Andric     Reduction =
398349cc55cSDimitry Andric         Builder.CreateBinaryIntrinsic(Intrinsic::smax, Reduction, Start);
399349cc55cSDimitry Andric     break;
400349cc55cSDimitry Andric   case Intrinsic::vp_reduce_smin:
401349cc55cSDimitry Andric     Reduction = Builder.CreateIntMinReduce(RedOp, /*IsSigned*/ true);
402349cc55cSDimitry Andric     Reduction =
403349cc55cSDimitry Andric         Builder.CreateBinaryIntrinsic(Intrinsic::smin, Reduction, Start);
404349cc55cSDimitry Andric     break;
405349cc55cSDimitry Andric   case Intrinsic::vp_reduce_umax:
406349cc55cSDimitry Andric     Reduction = Builder.CreateIntMaxReduce(RedOp, /*IsSigned*/ false);
407349cc55cSDimitry Andric     Reduction =
408349cc55cSDimitry Andric         Builder.CreateBinaryIntrinsic(Intrinsic::umax, Reduction, Start);
409349cc55cSDimitry Andric     break;
410349cc55cSDimitry Andric   case Intrinsic::vp_reduce_umin:
411349cc55cSDimitry Andric     Reduction = Builder.CreateIntMinReduce(RedOp, /*IsSigned*/ false);
412349cc55cSDimitry Andric     Reduction =
413349cc55cSDimitry Andric         Builder.CreateBinaryIntrinsic(Intrinsic::umin, Reduction, Start);
414349cc55cSDimitry Andric     break;
415349cc55cSDimitry Andric   case Intrinsic::vp_reduce_fmax:
416349cc55cSDimitry Andric     Reduction = Builder.CreateFPMaxReduce(RedOp);
417349cc55cSDimitry Andric     transferDecorations(*Reduction, VPI);
418349cc55cSDimitry Andric     Reduction =
419349cc55cSDimitry Andric         Builder.CreateBinaryIntrinsic(Intrinsic::maxnum, Reduction, Start);
420349cc55cSDimitry Andric     break;
421349cc55cSDimitry Andric   case Intrinsic::vp_reduce_fmin:
422349cc55cSDimitry Andric     Reduction = Builder.CreateFPMinReduce(RedOp);
423349cc55cSDimitry Andric     transferDecorations(*Reduction, VPI);
424349cc55cSDimitry Andric     Reduction =
425349cc55cSDimitry Andric         Builder.CreateBinaryIntrinsic(Intrinsic::minnum, Reduction, Start);
426349cc55cSDimitry Andric     break;
427349cc55cSDimitry Andric   case Intrinsic::vp_reduce_fadd:
428349cc55cSDimitry Andric     Reduction = Builder.CreateFAddReduce(Start, RedOp);
429349cc55cSDimitry Andric     break;
430349cc55cSDimitry Andric   case Intrinsic::vp_reduce_fmul:
431349cc55cSDimitry Andric     Reduction = Builder.CreateFMulReduce(Start, RedOp);
432349cc55cSDimitry Andric     break;
433349cc55cSDimitry Andric   }
434349cc55cSDimitry Andric 
435349cc55cSDimitry Andric   replaceOperation(*Reduction, VPI);
436349cc55cSDimitry Andric   return Reduction;
437349cc55cSDimitry Andric }
438349cc55cSDimitry Andric 
439fcaf7f86SDimitry Andric Value *
440fcaf7f86SDimitry Andric CachingVPExpander::expandPredicationInMemoryIntrinsic(IRBuilder<> &Builder,
441fcaf7f86SDimitry Andric                                                       VPIntrinsic &VPI) {
442fcaf7f86SDimitry Andric   assert(VPI.canIgnoreVectorLengthParam());
443fcaf7f86SDimitry Andric 
444fcaf7f86SDimitry Andric   const auto &DL = F.getParent()->getDataLayout();
445fcaf7f86SDimitry Andric 
446fcaf7f86SDimitry Andric   Value *MaskParam = VPI.getMaskParam();
447fcaf7f86SDimitry Andric   Value *PtrParam = VPI.getMemoryPointerParam();
448fcaf7f86SDimitry Andric   Value *DataParam = VPI.getMemoryDataParam();
449fcaf7f86SDimitry Andric   bool IsUnmasked = isAllTrueMask(MaskParam);
450fcaf7f86SDimitry Andric 
451fcaf7f86SDimitry Andric   MaybeAlign AlignOpt = VPI.getPointerAlignment();
452fcaf7f86SDimitry Andric 
453fcaf7f86SDimitry Andric   Value *NewMemoryInst = nullptr;
454fcaf7f86SDimitry Andric   switch (VPI.getIntrinsicID()) {
455fcaf7f86SDimitry Andric   default:
456fcaf7f86SDimitry Andric     llvm_unreachable("Not a VP memory intrinsic");
457fcaf7f86SDimitry Andric   case Intrinsic::vp_store:
458fcaf7f86SDimitry Andric     if (IsUnmasked) {
459fcaf7f86SDimitry Andric       StoreInst *NewStore =
460fcaf7f86SDimitry Andric           Builder.CreateStore(DataParam, PtrParam, /*IsVolatile*/ false);
461fcaf7f86SDimitry Andric       if (AlignOpt.has_value())
462bdd1243dSDimitry Andric         NewStore->setAlignment(*AlignOpt);
463fcaf7f86SDimitry Andric       NewMemoryInst = NewStore;
464fcaf7f86SDimitry Andric     } else
465fcaf7f86SDimitry Andric       NewMemoryInst = Builder.CreateMaskedStore(
466fcaf7f86SDimitry Andric           DataParam, PtrParam, AlignOpt.valueOrOne(), MaskParam);
467fcaf7f86SDimitry Andric 
468fcaf7f86SDimitry Andric     break;
469fcaf7f86SDimitry Andric   case Intrinsic::vp_load:
470fcaf7f86SDimitry Andric     if (IsUnmasked) {
471fcaf7f86SDimitry Andric       LoadInst *NewLoad =
472fcaf7f86SDimitry Andric           Builder.CreateLoad(VPI.getType(), PtrParam, /*IsVolatile*/ false);
473fcaf7f86SDimitry Andric       if (AlignOpt.has_value())
474bdd1243dSDimitry Andric         NewLoad->setAlignment(*AlignOpt);
475fcaf7f86SDimitry Andric       NewMemoryInst = NewLoad;
476fcaf7f86SDimitry Andric     } else
477fcaf7f86SDimitry Andric       NewMemoryInst = Builder.CreateMaskedLoad(
478fcaf7f86SDimitry Andric           VPI.getType(), PtrParam, AlignOpt.valueOrOne(), MaskParam);
479fcaf7f86SDimitry Andric 
480fcaf7f86SDimitry Andric     break;
481fcaf7f86SDimitry Andric   case Intrinsic::vp_scatter: {
482fcaf7f86SDimitry Andric     auto *ElementType =
483fcaf7f86SDimitry Andric         cast<VectorType>(DataParam->getType())->getElementType();
484fcaf7f86SDimitry Andric     NewMemoryInst = Builder.CreateMaskedScatter(
485fcaf7f86SDimitry Andric         DataParam, PtrParam,
486fcaf7f86SDimitry Andric         AlignOpt.value_or(DL.getPrefTypeAlign(ElementType)), MaskParam);
487fcaf7f86SDimitry Andric     break;
488fcaf7f86SDimitry Andric   }
489fcaf7f86SDimitry Andric   case Intrinsic::vp_gather: {
490fcaf7f86SDimitry Andric     auto *ElementType = cast<VectorType>(VPI.getType())->getElementType();
491fcaf7f86SDimitry Andric     NewMemoryInst = Builder.CreateMaskedGather(
492fcaf7f86SDimitry Andric         VPI.getType(), PtrParam,
493fcaf7f86SDimitry Andric         AlignOpt.value_or(DL.getPrefTypeAlign(ElementType)), MaskParam, nullptr,
494fcaf7f86SDimitry Andric         VPI.getName());
495fcaf7f86SDimitry Andric     break;
496fcaf7f86SDimitry Andric   }
497fcaf7f86SDimitry Andric   }
498fcaf7f86SDimitry Andric 
499fcaf7f86SDimitry Andric   assert(NewMemoryInst);
500fcaf7f86SDimitry Andric   replaceOperation(*NewMemoryInst, VPI);
501fcaf7f86SDimitry Andric   return NewMemoryInst;
502fcaf7f86SDimitry Andric }
503fcaf7f86SDimitry Andric 
504bdd1243dSDimitry Andric Value *CachingVPExpander::expandPredicationInComparison(IRBuilder<> &Builder,
505bdd1243dSDimitry Andric                                                         VPCmpIntrinsic &VPI) {
506bdd1243dSDimitry Andric   assert((maySpeculateLanes(VPI) || VPI.canIgnoreVectorLengthParam()) &&
507bdd1243dSDimitry Andric          "Implicitly dropping %evl in non-speculatable operator!");
508bdd1243dSDimitry Andric 
509bdd1243dSDimitry Andric   assert(*VPI.getFunctionalOpcode() == Instruction::ICmp ||
510bdd1243dSDimitry Andric          *VPI.getFunctionalOpcode() == Instruction::FCmp);
511bdd1243dSDimitry Andric 
512bdd1243dSDimitry Andric   Value *Op0 = VPI.getOperand(0);
513bdd1243dSDimitry Andric   Value *Op1 = VPI.getOperand(1);
514bdd1243dSDimitry Andric   auto Pred = VPI.getPredicate();
515bdd1243dSDimitry Andric 
516bdd1243dSDimitry Andric   auto *NewCmp = Builder.CreateCmp(Pred, Op0, Op1);
517bdd1243dSDimitry Andric 
518bdd1243dSDimitry Andric   replaceOperation(*NewCmp, VPI);
519bdd1243dSDimitry Andric   return NewCmp;
520bdd1243dSDimitry Andric }
521bdd1243dSDimitry Andric 
522fe6060f1SDimitry Andric void CachingVPExpander::discardEVLParameter(VPIntrinsic &VPI) {
523fe6060f1SDimitry Andric   LLVM_DEBUG(dbgs() << "Discard EVL parameter in " << VPI << "\n");
524fe6060f1SDimitry Andric 
525fe6060f1SDimitry Andric   if (VPI.canIgnoreVectorLengthParam())
526fe6060f1SDimitry Andric     return;
527fe6060f1SDimitry Andric 
528fe6060f1SDimitry Andric   Value *EVLParam = VPI.getVectorLengthParam();
529fe6060f1SDimitry Andric   if (!EVLParam)
530fe6060f1SDimitry Andric     return;
531fe6060f1SDimitry Andric 
532fe6060f1SDimitry Andric   ElementCount StaticElemCount = VPI.getStaticVectorLength();
533fe6060f1SDimitry Andric   Value *MaxEVL = nullptr;
534fe6060f1SDimitry Andric   Type *Int32Ty = Type::getInt32Ty(VPI.getContext());
535fe6060f1SDimitry Andric   if (StaticElemCount.isScalable()) {
536fe6060f1SDimitry Andric     // TODO add caching
537fe6060f1SDimitry Andric     auto *M = VPI.getModule();
538fe6060f1SDimitry Andric     Function *VScaleFunc =
539fe6060f1SDimitry Andric         Intrinsic::getDeclaration(M, Intrinsic::vscale, Int32Ty);
540fe6060f1SDimitry Andric     IRBuilder<> Builder(VPI.getParent(), VPI.getIterator());
541fe6060f1SDimitry Andric     Value *FactorConst = Builder.getInt32(StaticElemCount.getKnownMinValue());
542fe6060f1SDimitry Andric     Value *VScale = Builder.CreateCall(VScaleFunc, {}, "vscale");
543fe6060f1SDimitry Andric     MaxEVL = Builder.CreateMul(VScale, FactorConst, "scalable_size",
544fe6060f1SDimitry Andric                                /*NUW*/ true, /*NSW*/ false);
545fe6060f1SDimitry Andric   } else {
546fe6060f1SDimitry Andric     MaxEVL = ConstantInt::get(Int32Ty, StaticElemCount.getFixedValue(), false);
547fe6060f1SDimitry Andric   }
548fe6060f1SDimitry Andric   VPI.setVectorLengthParam(MaxEVL);
549fe6060f1SDimitry Andric }
550fe6060f1SDimitry Andric 
551fe6060f1SDimitry Andric Value *CachingVPExpander::foldEVLIntoMask(VPIntrinsic &VPI) {
552fe6060f1SDimitry Andric   LLVM_DEBUG(dbgs() << "Folding vlen for " << VPI << '\n');
553fe6060f1SDimitry Andric 
554fe6060f1SDimitry Andric   IRBuilder<> Builder(&VPI);
555fe6060f1SDimitry Andric 
556fe6060f1SDimitry Andric   // Ineffective %evl parameter and so nothing to do here.
557fe6060f1SDimitry Andric   if (VPI.canIgnoreVectorLengthParam())
558fe6060f1SDimitry Andric     return &VPI;
559fe6060f1SDimitry Andric 
560fe6060f1SDimitry Andric   // Only VP intrinsics can have an %evl parameter.
561fe6060f1SDimitry Andric   Value *OldMaskParam = VPI.getMaskParam();
562fe6060f1SDimitry Andric   Value *OldEVLParam = VPI.getVectorLengthParam();
563fe6060f1SDimitry Andric   assert(OldMaskParam && "no mask param to fold the vl param into");
564fe6060f1SDimitry Andric   assert(OldEVLParam && "no EVL param to fold away");
565fe6060f1SDimitry Andric 
566fe6060f1SDimitry Andric   LLVM_DEBUG(dbgs() << "OLD evl: " << *OldEVLParam << '\n');
567fe6060f1SDimitry Andric   LLVM_DEBUG(dbgs() << "OLD mask: " << *OldMaskParam << '\n');
568fe6060f1SDimitry Andric 
569fe6060f1SDimitry Andric   // Convert the %evl predication into vector mask predication.
570fe6060f1SDimitry Andric   ElementCount ElemCount = VPI.getStaticVectorLength();
571fe6060f1SDimitry Andric   Value *VLMask = convertEVLToMask(Builder, OldEVLParam, ElemCount);
572fe6060f1SDimitry Andric   Value *NewMaskParam = Builder.CreateAnd(VLMask, OldMaskParam);
573fe6060f1SDimitry Andric   VPI.setMaskParam(NewMaskParam);
574fe6060f1SDimitry Andric 
575fe6060f1SDimitry Andric   // Drop the %evl parameter.
576fe6060f1SDimitry Andric   discardEVLParameter(VPI);
577fe6060f1SDimitry Andric   assert(VPI.canIgnoreVectorLengthParam() &&
578fe6060f1SDimitry Andric          "transformation did not render the evl param ineffective!");
579fe6060f1SDimitry Andric 
580fe6060f1SDimitry Andric   // Reassess the modified instruction.
581fe6060f1SDimitry Andric   return &VPI;
582fe6060f1SDimitry Andric }
583fe6060f1SDimitry Andric 
584fe6060f1SDimitry Andric Value *CachingVPExpander::expandPredication(VPIntrinsic &VPI) {
585fe6060f1SDimitry Andric   LLVM_DEBUG(dbgs() << "Lowering to unpredicated op: " << VPI << '\n');
586fe6060f1SDimitry Andric 
587fe6060f1SDimitry Andric   IRBuilder<> Builder(&VPI);
588fe6060f1SDimitry Andric 
589fe6060f1SDimitry Andric   // Try lowering to a LLVM instruction first.
590fe6060f1SDimitry Andric   auto OC = VPI.getFunctionalOpcode();
591fe6060f1SDimitry Andric 
592fe6060f1SDimitry Andric   if (OC && Instruction::isBinaryOp(*OC))
593fe6060f1SDimitry Andric     return expandPredicationInBinaryOperator(Builder, VPI);
594fe6060f1SDimitry Andric 
595349cc55cSDimitry Andric   if (auto *VPRI = dyn_cast<VPReductionIntrinsic>(&VPI))
596349cc55cSDimitry Andric     return expandPredicationInReduction(Builder, *VPRI);
597349cc55cSDimitry Andric 
598bdd1243dSDimitry Andric   if (auto *VPCmp = dyn_cast<VPCmpIntrinsic>(&VPI))
599bdd1243dSDimitry Andric     return expandPredicationInComparison(Builder, *VPCmp);
600bdd1243dSDimitry Andric 
601fcaf7f86SDimitry Andric   switch (VPI.getIntrinsicID()) {
602fcaf7f86SDimitry Andric   default:
603fcaf7f86SDimitry Andric     break;
604*fe013be4SDimitry Andric   case Intrinsic::vp_fneg: {
605*fe013be4SDimitry Andric     Value *NewNegOp = Builder.CreateFNeg(VPI.getOperand(0), VPI.getName());
606*fe013be4SDimitry Andric     replaceOperation(*NewNegOp, VPI);
607*fe013be4SDimitry Andric     return NewNegOp;
608*fe013be4SDimitry Andric   }
609*fe013be4SDimitry Andric   case Intrinsic::vp_fabs:
610*fe013be4SDimitry Andric     return expandPredicationToFPCall(Builder, VPI, Intrinsic::fabs);
611*fe013be4SDimitry Andric   case Intrinsic::vp_sqrt:
612*fe013be4SDimitry Andric     return expandPredicationToFPCall(Builder, VPI, Intrinsic::sqrt);
613fcaf7f86SDimitry Andric   case Intrinsic::vp_load:
614fcaf7f86SDimitry Andric   case Intrinsic::vp_store:
615fcaf7f86SDimitry Andric   case Intrinsic::vp_gather:
616fcaf7f86SDimitry Andric   case Intrinsic::vp_scatter:
617fcaf7f86SDimitry Andric     return expandPredicationInMemoryIntrinsic(Builder, VPI);
618fcaf7f86SDimitry Andric   }
619fcaf7f86SDimitry Andric 
620*fe013be4SDimitry Andric   if (auto CID = VPI.getConstrainedIntrinsicID())
621*fe013be4SDimitry Andric     if (Value *Call = expandPredicationToFPCall(Builder, VPI, *CID))
622*fe013be4SDimitry Andric       return Call;
623*fe013be4SDimitry Andric 
624fe6060f1SDimitry Andric   return &VPI;
625fe6060f1SDimitry Andric }
626fe6060f1SDimitry Andric 
627fe6060f1SDimitry Andric //// } CachingVPExpander
628fe6060f1SDimitry Andric 
629fe6060f1SDimitry Andric struct TransformJob {
630fe6060f1SDimitry Andric   VPIntrinsic *PI;
631fe6060f1SDimitry Andric   TargetTransformInfo::VPLegalization Strategy;
632fe6060f1SDimitry Andric   TransformJob(VPIntrinsic *PI, TargetTransformInfo::VPLegalization InitStrat)
633fe6060f1SDimitry Andric       : PI(PI), Strategy(InitStrat) {}
634fe6060f1SDimitry Andric 
635fe6060f1SDimitry Andric   bool isDone() const { return Strategy.shouldDoNothing(); }
636fe6060f1SDimitry Andric };
637fe6060f1SDimitry Andric 
63881ad6265SDimitry Andric void sanitizeStrategy(VPIntrinsic &VPI, VPLegalization &LegalizeStrat) {
63981ad6265SDimitry Andric   // Operations with speculatable lanes do not strictly need predication.
64081ad6265SDimitry Andric   if (maySpeculateLanes(VPI)) {
641fe6060f1SDimitry Andric     // Converting a speculatable VP intrinsic means dropping %mask and %evl.
642fe6060f1SDimitry Andric     // No need to expand %evl into the %mask only to ignore that code.
643fe6060f1SDimitry Andric     if (LegalizeStrat.OpStrategy == VPLegalization::Convert)
644fe6060f1SDimitry Andric       LegalizeStrat.EVLParamStrategy = VPLegalization::Discard;
645fe6060f1SDimitry Andric     return;
646fe6060f1SDimitry Andric   }
647fe6060f1SDimitry Andric 
648fe6060f1SDimitry Andric   // We have to preserve the predicating effect of %evl for this
649fe6060f1SDimitry Andric   // non-speculatable VP intrinsic.
650fe6060f1SDimitry Andric   // 1) Never discard %evl.
651fe6060f1SDimitry Andric   // 2) If this VP intrinsic will be expanded to non-VP code, make sure that
652fe6060f1SDimitry Andric   //    %evl gets folded into %mask.
653fe6060f1SDimitry Andric   if ((LegalizeStrat.EVLParamStrategy == VPLegalization::Discard) ||
654fe6060f1SDimitry Andric       (LegalizeStrat.OpStrategy == VPLegalization::Convert)) {
655fe6060f1SDimitry Andric     LegalizeStrat.EVLParamStrategy = VPLegalization::Convert;
656fe6060f1SDimitry Andric   }
657fe6060f1SDimitry Andric }
658fe6060f1SDimitry Andric 
659fe6060f1SDimitry Andric VPLegalization
660fe6060f1SDimitry Andric CachingVPExpander::getVPLegalizationStrategy(const VPIntrinsic &VPI) const {
661fe6060f1SDimitry Andric   auto VPStrat = TTI.getVPLegalizationStrategy(VPI);
662fe6060f1SDimitry Andric   if (LLVM_LIKELY(!UsingTTIOverrides)) {
663fe6060f1SDimitry Andric     // No overrides - we are in production.
664fe6060f1SDimitry Andric     return VPStrat;
665fe6060f1SDimitry Andric   }
666fe6060f1SDimitry Andric 
667fe6060f1SDimitry Andric   // Overrides set - we are in testing, the following does not need to be
668fe6060f1SDimitry Andric   // efficient.
669fe6060f1SDimitry Andric   VPStrat.EVLParamStrategy = parseOverrideOption(EVLTransformOverride);
670fe6060f1SDimitry Andric   VPStrat.OpStrategy = parseOverrideOption(MaskTransformOverride);
671fe6060f1SDimitry Andric   return VPStrat;
672fe6060f1SDimitry Andric }
673fe6060f1SDimitry Andric 
674bdd1243dSDimitry Andric /// Expand llvm.vp.* intrinsics as requested by \p TTI.
675fe6060f1SDimitry Andric bool CachingVPExpander::expandVectorPredication() {
676fe6060f1SDimitry Andric   SmallVector<TransformJob, 16> Worklist;
677fe6060f1SDimitry Andric 
678fe6060f1SDimitry Andric   // Collect all VPIntrinsics that need expansion and determine their expansion
679fe6060f1SDimitry Andric   // strategy.
680fe6060f1SDimitry Andric   for (auto &I : instructions(F)) {
681fe6060f1SDimitry Andric     auto *VPI = dyn_cast<VPIntrinsic>(&I);
682fe6060f1SDimitry Andric     if (!VPI)
683fe6060f1SDimitry Andric       continue;
684fe6060f1SDimitry Andric     auto VPStrat = getVPLegalizationStrategy(*VPI);
68581ad6265SDimitry Andric     sanitizeStrategy(*VPI, VPStrat);
686fe6060f1SDimitry Andric     if (!VPStrat.shouldDoNothing())
687fe6060f1SDimitry Andric       Worklist.emplace_back(VPI, VPStrat);
688fe6060f1SDimitry Andric   }
689fe6060f1SDimitry Andric   if (Worklist.empty())
690fe6060f1SDimitry Andric     return false;
691fe6060f1SDimitry Andric 
692fe6060f1SDimitry Andric   // Transform all VPIntrinsics on the worklist.
693fe6060f1SDimitry Andric   LLVM_DEBUG(dbgs() << "\n:::: Transforming " << Worklist.size()
694fe6060f1SDimitry Andric                     << " instructions ::::\n");
695fe6060f1SDimitry Andric   for (TransformJob Job : Worklist) {
696fe6060f1SDimitry Andric     // Transform the EVL parameter.
697fe6060f1SDimitry Andric     switch (Job.Strategy.EVLParamStrategy) {
698fe6060f1SDimitry Andric     case VPLegalization::Legal:
699fe6060f1SDimitry Andric       break;
700fe6060f1SDimitry Andric     case VPLegalization::Discard:
701fe6060f1SDimitry Andric       discardEVLParameter(*Job.PI);
702fe6060f1SDimitry Andric       break;
703fe6060f1SDimitry Andric     case VPLegalization::Convert:
704fe6060f1SDimitry Andric       if (foldEVLIntoMask(*Job.PI))
705fe6060f1SDimitry Andric         ++NumFoldedVL;
706fe6060f1SDimitry Andric       break;
707fe6060f1SDimitry Andric     }
708fe6060f1SDimitry Andric     Job.Strategy.EVLParamStrategy = VPLegalization::Legal;
709fe6060f1SDimitry Andric 
710fe6060f1SDimitry Andric     // Replace with a non-predicated operation.
711fe6060f1SDimitry Andric     switch (Job.Strategy.OpStrategy) {
712fe6060f1SDimitry Andric     case VPLegalization::Legal:
713fe6060f1SDimitry Andric       break;
714fe6060f1SDimitry Andric     case VPLegalization::Discard:
715fe6060f1SDimitry Andric       llvm_unreachable("Invalid strategy for operators.");
716fe6060f1SDimitry Andric     case VPLegalization::Convert:
717fe6060f1SDimitry Andric       expandPredication(*Job.PI);
718fe6060f1SDimitry Andric       ++NumLoweredVPOps;
719fe6060f1SDimitry Andric       break;
720fe6060f1SDimitry Andric     }
721fe6060f1SDimitry Andric     Job.Strategy.OpStrategy = VPLegalization::Legal;
722fe6060f1SDimitry Andric 
723fe6060f1SDimitry Andric     assert(Job.isDone() && "incomplete transformation");
724fe6060f1SDimitry Andric   }
725fe6060f1SDimitry Andric 
726fe6060f1SDimitry Andric   return true;
727fe6060f1SDimitry Andric }
728fe6060f1SDimitry Andric class ExpandVectorPredication : public FunctionPass {
729fe6060f1SDimitry Andric public:
730fe6060f1SDimitry Andric   static char ID;
731fe6060f1SDimitry Andric   ExpandVectorPredication() : FunctionPass(ID) {
732fe6060f1SDimitry Andric     initializeExpandVectorPredicationPass(*PassRegistry::getPassRegistry());
733fe6060f1SDimitry Andric   }
734fe6060f1SDimitry Andric 
735fe6060f1SDimitry Andric   bool runOnFunction(Function &F) override {
736fe6060f1SDimitry Andric     const auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
737fe6060f1SDimitry Andric     CachingVPExpander VPExpander(F, *TTI);
738fe6060f1SDimitry Andric     return VPExpander.expandVectorPredication();
739fe6060f1SDimitry Andric   }
740fe6060f1SDimitry Andric 
741fe6060f1SDimitry Andric   void getAnalysisUsage(AnalysisUsage &AU) const override {
742fe6060f1SDimitry Andric     AU.addRequired<TargetTransformInfoWrapperPass>();
743fe6060f1SDimitry Andric     AU.setPreservesCFG();
744fe6060f1SDimitry Andric   }
745fe6060f1SDimitry Andric };
746fe6060f1SDimitry Andric } // namespace
747fe6060f1SDimitry Andric 
748fe6060f1SDimitry Andric char ExpandVectorPredication::ID;
749fe6060f1SDimitry Andric INITIALIZE_PASS_BEGIN(ExpandVectorPredication, "expandvp",
750fe6060f1SDimitry Andric                       "Expand vector predication intrinsics", false, false)
751fe6060f1SDimitry Andric INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
752fe6060f1SDimitry Andric INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
753fe6060f1SDimitry Andric INITIALIZE_PASS_END(ExpandVectorPredication, "expandvp",
754fe6060f1SDimitry Andric                     "Expand vector predication intrinsics", false, false)
755fe6060f1SDimitry Andric 
756fe6060f1SDimitry Andric FunctionPass *llvm::createExpandVectorPredicationPass() {
757fe6060f1SDimitry Andric   return new ExpandVectorPredication();
758fe6060f1SDimitry Andric }
759fe6060f1SDimitry Andric 
760fe6060f1SDimitry Andric PreservedAnalyses
761fe6060f1SDimitry Andric ExpandVectorPredicationPass::run(Function &F, FunctionAnalysisManager &AM) {
762fe6060f1SDimitry Andric   const auto &TTI = AM.getResult<TargetIRAnalysis>(F);
763fe6060f1SDimitry Andric   CachingVPExpander VPExpander(F, TTI);
764fe6060f1SDimitry Andric   if (!VPExpander.expandVectorPredication())
765fe6060f1SDimitry Andric     return PreservedAnalyses::all();
766fe6060f1SDimitry Andric   PreservedAnalyses PA;
767fe6060f1SDimitry Andric   PA.preserveSet<CFGAnalyses>();
768fe6060f1SDimitry Andric   return PA;
769fe6060f1SDimitry Andric }
770