1 //===- MVETailPredication.cpp - MVE Tail Predication ----------------------===//
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 /// Armv8.1m introduced MVE, M-Profile Vector Extension, and low-overhead
11 /// branches to help accelerate DSP applications. These two extensions can be
12 /// combined to provide implicit vector predication within a low-overhead loop.
13 /// The HardwareLoops pass inserts intrinsics identifying loops that the
14 /// backend will attempt to convert into a low-overhead loop. The vectorizer is
15 /// responsible for generating a vectorized loop in which the lanes are
16 /// predicated upon the iteration counter. This pass looks at these predicated
17 /// vector loops, that are targets for low-overhead loops, and prepares it for
18 /// code generation. Once the vectorizer has produced a masked loop, there's a
19 /// couple of final forms:
20 /// - A tail-predicated loop, with implicit predication.
21 /// - A loop containing multiple VCPT instructions, predicating multiple VPT
22 ///   blocks of instructions operating on different vector types.
23 
24 #include "ARM.h"
25 #include "ARMSubtarget.h"
26 #include "llvm/Analysis/LoopInfo.h"
27 #include "llvm/Analysis/LoopPass.h"
28 #include "llvm/Analysis/ScalarEvolution.h"
29 #include "llvm/Analysis/ScalarEvolutionExpander.h"
30 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
31 #include "llvm/Analysis/TargetTransformInfo.h"
32 #include "llvm/CodeGen/TargetPassConfig.h"
33 #include "llvm/IR/IRBuilder.h"
34 #include "llvm/IR/Instructions.h"
35 #include "llvm/IR/IntrinsicsARM.h"
36 #include "llvm/IR/PatternMatch.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
39 
40 using namespace llvm;
41 
42 #define DEBUG_TYPE "mve-tail-predication"
43 #define DESC "Transform predicated vector loops to use MVE tail predication"
44 
45 cl::opt<bool>
46 DisableTailPredication("disable-mve-tail-predication", cl::Hidden,
47                        cl::init(true),
48                        cl::desc("Disable MVE Tail Predication"));
49 namespace {
50 
51 class MVETailPredication : public LoopPass {
52   SmallVector<IntrinsicInst*, 4> MaskedInsts;
53   Loop *L = nullptr;
54   ScalarEvolution *SE = nullptr;
55   TargetTransformInfo *TTI = nullptr;
56 
57 public:
58   static char ID;
59 
60   MVETailPredication() : LoopPass(ID) { }
61 
62   void getAnalysisUsage(AnalysisUsage &AU) const override {
63     AU.addRequired<ScalarEvolutionWrapperPass>();
64     AU.addRequired<LoopInfoWrapperPass>();
65     AU.addRequired<TargetPassConfig>();
66     AU.addRequired<TargetTransformInfoWrapperPass>();
67     AU.addPreserved<LoopInfoWrapperPass>();
68     AU.setPreservesCFG();
69   }
70 
71   bool runOnLoop(Loop *L, LPPassManager&) override;
72 
73 private:
74 
75   /// Perform the relevant checks on the loop and convert if possible.
76   bool TryConvert(Value *TripCount);
77 
78   /// Return whether this is a vectorized loop, that contains masked
79   /// load/stores.
80   bool IsPredicatedVectorLoop();
81 
82   /// Compute a value for the total number of elements that the predicated
83   /// loop will process.
84   Value *ComputeElements(Value *TripCount, VectorType *VecTy);
85 
86   /// Is the icmp that generates an i1 vector, based upon a loop counter
87   /// and a limit that is defined outside the loop.
88   bool isTailPredicate(Instruction *Predicate, Value *NumElements);
89 };
90 
91 } // end namespace
92 
93 static bool IsDecrement(Instruction &I) {
94   auto *Call = dyn_cast<IntrinsicInst>(&I);
95   if (!Call)
96     return false;
97 
98   Intrinsic::ID ID = Call->getIntrinsicID();
99   return ID == Intrinsic::loop_decrement_reg;
100 }
101 
102 static bool IsMasked(Instruction *I) {
103   auto *Call = dyn_cast<IntrinsicInst>(I);
104   if (!Call)
105     return false;
106 
107   Intrinsic::ID ID = Call->getIntrinsicID();
108   // TODO: Support gather/scatter expand/compress operations.
109   return ID == Intrinsic::masked_store || ID == Intrinsic::masked_load;
110 }
111 
112 bool MVETailPredication::runOnLoop(Loop *L, LPPassManager&) {
113   if (skipLoop(L) || DisableTailPredication)
114     return false;
115 
116   Function &F = *L->getHeader()->getParent();
117   auto &TPC = getAnalysis<TargetPassConfig>();
118   auto &TM = TPC.getTM<TargetMachine>();
119   auto *ST = &TM.getSubtarget<ARMSubtarget>(F);
120   TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
121   SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
122   this->L = L;
123 
124   // The MVE and LOB extensions are combined to enable tail-predication, but
125   // there's nothing preventing us from generating VCTP instructions for v8.1m.
126   if (!ST->hasMVEIntegerOps() || !ST->hasV8_1MMainlineOps()) {
127     LLVM_DEBUG(dbgs() << "TP: Not a v8.1m.main+mve target.\n");
128     return false;
129   }
130 
131   BasicBlock *Preheader = L->getLoopPreheader();
132   if (!Preheader)
133     return false;
134 
135   auto FindLoopIterations = [](BasicBlock *BB) -> IntrinsicInst* {
136     for (auto &I : *BB) {
137       auto *Call = dyn_cast<IntrinsicInst>(&I);
138       if (!Call)
139         continue;
140 
141       Intrinsic::ID ID = Call->getIntrinsicID();
142       if (ID == Intrinsic::set_loop_iterations ||
143           ID == Intrinsic::test_set_loop_iterations)
144         return cast<IntrinsicInst>(&I);
145     }
146     return nullptr;
147   };
148 
149   // Look for the hardware loop intrinsic that sets the iteration count.
150   IntrinsicInst *Setup = FindLoopIterations(Preheader);
151 
152   // The test.set iteration could live in the pre- preheader.
153   if (!Setup) {
154     if (!Preheader->getSinglePredecessor())
155       return false;
156     Setup = FindLoopIterations(Preheader->getSinglePredecessor());
157     if (!Setup)
158       return false;
159   }
160 
161   // Search for the hardware loop intrinic that decrements the loop counter.
162   IntrinsicInst *Decrement = nullptr;
163   for (auto *BB : L->getBlocks()) {
164     for (auto &I : *BB) {
165       if (IsDecrement(I)) {
166         Decrement = cast<IntrinsicInst>(&I);
167         break;
168       }
169     }
170   }
171 
172   if (!Decrement)
173     return false;
174 
175   LLVM_DEBUG(dbgs() << "TP: Running on Loop: " << *L
176              << *Setup << "\n"
177              << *Decrement << "\n");
178   bool Changed = TryConvert(Setup->getArgOperand(0));
179   return Changed;
180 }
181 
182 bool MVETailPredication::isTailPredicate(Instruction *I, Value *NumElements) {
183   // Look for the following:
184 
185   // %trip.count.minus.1 = add i32 %N, -1
186   // %broadcast.splatinsert10 = insertelement <4 x i32> undef,
187   //                                          i32 %trip.count.minus.1, i32 0
188   // %broadcast.splat11 = shufflevector <4 x i32> %broadcast.splatinsert10,
189   //                                    <4 x i32> undef,
190   //                                    <4 x i32> zeroinitializer
191   // ...
192   // ...
193   // %index = phi i32
194   // %broadcast.splatinsert = insertelement <4 x i32> undef, i32 %index, i32 0
195   // %broadcast.splat = shufflevector <4 x i32> %broadcast.splatinsert,
196   //                                  <4 x i32> undef,
197   //                                  <4 x i32> zeroinitializer
198   // %induction = add <4 x i32> %broadcast.splat, <i32 0, i32 1, i32 2, i32 3>
199   // %pred = icmp ule <4 x i32> %induction, %broadcast.splat11
200 
201   // And return whether V == %pred.
202 
203   using namespace PatternMatch;
204 
205   CmpInst::Predicate Pred;
206   Instruction *Shuffle = nullptr;
207   Instruction *Induction = nullptr;
208 
209   // The vector icmp
210   if (!match(I, m_ICmp(Pred, m_Instruction(Induction),
211                        m_Instruction(Shuffle))) ||
212       Pred != ICmpInst::ICMP_ULE || !L->isLoopInvariant(Shuffle))
213     return false;
214 
215   // First find the stuff outside the loop which is setting up the limit
216   // vector....
217   // The invariant shuffle that broadcast the limit into a vector.
218   Instruction *Insert = nullptr;
219   if (!match(Shuffle, m_ShuffleVector(m_Instruction(Insert), m_Undef(),
220                                       m_Zero())))
221     return false;
222 
223   // Insert the limit into a vector.
224   Instruction *BECount = nullptr;
225   if (!match(Insert, m_InsertElement(m_Undef(), m_Instruction(BECount),
226                                      m_Zero())))
227     return false;
228 
229   // The limit calculation, backedge count.
230   Value *TripCount = nullptr;
231   if (!match(BECount, m_Add(m_Value(TripCount), m_AllOnes())))
232     return false;
233 
234   if (TripCount != NumElements)
235     return false;
236 
237   // Now back to searching inside the loop body...
238   // Find the add with takes the index iv and adds a constant vector to it.
239   Instruction *BroadcastSplat = nullptr;
240   Constant *Const = nullptr;
241   if (!match(Induction, m_Add(m_Instruction(BroadcastSplat),
242                               m_Constant(Const))))
243    return false;
244 
245   // Check that we're adding <0, 1, 2, 3...
246   if (auto *CDS = dyn_cast<ConstantDataSequential>(Const)) {
247     for (unsigned i = 0; i < CDS->getNumElements(); ++i) {
248       if (CDS->getElementAsInteger(i) != i)
249         return false;
250     }
251   } else
252     return false;
253 
254   // The shuffle which broadcasts the index iv into a vector.
255   if (!match(BroadcastSplat, m_ShuffleVector(m_Instruction(Insert), m_Undef(),
256                                              m_Zero())))
257     return false;
258 
259   // The insert element which initialises a vector with the index iv.
260   Instruction *IV = nullptr;
261   if (!match(Insert, m_InsertElement(m_Undef(), m_Instruction(IV), m_Zero())))
262     return false;
263 
264   // The index iv.
265   auto *Phi = dyn_cast<PHINode>(IV);
266   if (!Phi)
267     return false;
268 
269   // TODO: Don't think we need to check the entry value.
270   Value *OnEntry = Phi->getIncomingValueForBlock(L->getLoopPreheader());
271   if (!match(OnEntry, m_Zero()))
272     return false;
273 
274   Value *InLoop = Phi->getIncomingValueForBlock(L->getLoopLatch());
275   unsigned Lanes = cast<VectorType>(Insert->getType())->getNumElements();
276 
277   Instruction *LHS = nullptr;
278   if (!match(InLoop, m_Add(m_Instruction(LHS), m_SpecificInt(Lanes))))
279     return false;
280 
281   return LHS == Phi;
282 }
283 
284 static VectorType* getVectorType(IntrinsicInst *I) {
285   unsigned TypeOp = I->getIntrinsicID() == Intrinsic::masked_load ? 0 : 1;
286   auto *PtrTy = cast<PointerType>(I->getOperand(TypeOp)->getType());
287   return cast<VectorType>(PtrTy->getElementType());
288 }
289 
290 bool MVETailPredication::IsPredicatedVectorLoop() {
291   // Check that the loop contains at least one masked load/store intrinsic.
292   // We only support 'normal' vector instructions - other than masked
293   // load/stores.
294   for (auto *BB : L->getBlocks()) {
295     for (auto &I : *BB) {
296       if (IsMasked(&I)) {
297         VectorType *VecTy = getVectorType(cast<IntrinsicInst>(&I));
298         unsigned Lanes = VecTy->getNumElements();
299         unsigned ElementWidth = VecTy->getScalarSizeInBits();
300         // MVE vectors are 128-bit, but don't support 128 x i1.
301         // TODO: Can we support vectors larger than 128-bits?
302         unsigned MaxWidth = TTI->getRegisterBitWidth(true);
303         if (Lanes * ElementWidth > MaxWidth || Lanes == MaxWidth)
304           return false;
305         MaskedInsts.push_back(cast<IntrinsicInst>(&I));
306       } else if (auto *Int = dyn_cast<IntrinsicInst>(&I)) {
307         for (auto &U : Int->args()) {
308           if (isa<VectorType>(U->getType()))
309             return false;
310         }
311       }
312     }
313   }
314 
315   return !MaskedInsts.empty();
316 }
317 
318 Value* MVETailPredication::ComputeElements(Value *TripCount,
319                                            VectorType *VecTy) {
320   const SCEV *TripCountSE = SE->getSCEV(TripCount);
321   ConstantInt *VF = ConstantInt::get(cast<IntegerType>(TripCount->getType()),
322                                      VecTy->getNumElements());
323 
324   if (VF->equalsInt(1))
325     return nullptr;
326 
327   // TODO: Support constant trip counts.
328   auto VisitAdd = [&](const SCEVAddExpr *S) -> const SCEVMulExpr* {
329     if (auto *Const = dyn_cast<SCEVConstant>(S->getOperand(0))) {
330       if (Const->getAPInt() != -VF->getValue())
331         return nullptr;
332     } else
333       return nullptr;
334     return dyn_cast<SCEVMulExpr>(S->getOperand(1));
335   };
336 
337   auto VisitMul = [&](const SCEVMulExpr *S) -> const SCEVUDivExpr* {
338     if (auto *Const = dyn_cast<SCEVConstant>(S->getOperand(0))) {
339       if (Const->getValue() != VF)
340         return nullptr;
341     } else
342       return nullptr;
343     return dyn_cast<SCEVUDivExpr>(S->getOperand(1));
344   };
345 
346   auto VisitDiv = [&](const SCEVUDivExpr *S) -> const SCEV* {
347     if (auto *Const = dyn_cast<SCEVConstant>(S->getRHS())) {
348       if (Const->getValue() != VF)
349         return nullptr;
350     } else
351       return nullptr;
352 
353     if (auto *RoundUp = dyn_cast<SCEVAddExpr>(S->getLHS())) {
354       if (auto *Const = dyn_cast<SCEVConstant>(RoundUp->getOperand(0))) {
355         if (Const->getAPInt() != (VF->getValue() - 1))
356           return nullptr;
357       } else
358         return nullptr;
359 
360       return RoundUp->getOperand(1);
361     }
362     return nullptr;
363   };
364 
365   // TODO: Can we use SCEV helpers, such as findArrayDimensions, and friends to
366   // determine the numbers of elements instead? Looks like this is what is used
367   // for delinearization, but I'm not sure if it can be applied to the
368   // vectorized form - at least not without a bit more work than I feel
369   // comfortable with.
370 
371   // Search for Elems in the following SCEV:
372   // (1 + ((-VF + (VF * (((VF - 1) + %Elems) /u VF))<nuw>) /u VF))<nuw><nsw>
373   const SCEV *Elems = nullptr;
374   if (auto *TC = dyn_cast<SCEVAddExpr>(TripCountSE))
375     if (auto *Div = dyn_cast<SCEVUDivExpr>(TC->getOperand(1)))
376       if (auto *Add = dyn_cast<SCEVAddExpr>(Div->getLHS()))
377         if (auto *Mul = VisitAdd(Add))
378           if (auto *Div = VisitMul(Mul))
379             if (auto *Res = VisitDiv(Div))
380               Elems = Res;
381 
382   if (!Elems)
383     return nullptr;
384 
385   Instruction *InsertPt = L->getLoopPreheader()->getTerminator();
386   if (!isSafeToExpandAt(Elems, InsertPt, *SE))
387     return nullptr;
388 
389   auto DL = L->getHeader()->getModule()->getDataLayout();
390   SCEVExpander Expander(*SE, DL, "elements");
391   return Expander.expandCodeFor(Elems, Elems->getType(), InsertPt);
392 }
393 
394 // Look through the exit block to see whether there's a duplicate predicate
395 // instruction. This can happen when we need to perform a select on values
396 // from the last and previous iteration. Instead of doing a straight
397 // replacement of that predicate with the vctp, clone the vctp and place it
398 // in the block. This means that the VPR doesn't have to be live into the
399 // exit block which should make it easier to convert this loop into a proper
400 // tail predicated loop.
401 static void Cleanup(DenseMap<Instruction*, Instruction*> &NewPredicates,
402                     SetVector<Instruction*> &MaybeDead, Loop *L) {
403   if (BasicBlock *Exit = L->getUniqueExitBlock()) {
404     for (auto &Pair : NewPredicates) {
405       Instruction *OldPred = Pair.first;
406       Instruction *NewPred = Pair.second;
407 
408       for (auto &I : *Exit) {
409         if (I.isSameOperationAs(OldPred)) {
410           Instruction *PredClone = NewPred->clone();
411           PredClone->insertBefore(&I);
412           I.replaceAllUsesWith(PredClone);
413           MaybeDead.insert(&I);
414           break;
415         }
416       }
417     }
418   }
419 
420   // Drop references and add operands to check for dead.
421   SmallPtrSet<Instruction*, 4> Dead;
422   while (!MaybeDead.empty()) {
423     auto *I = MaybeDead.front();
424     MaybeDead.remove(I);
425     if (I->hasNUsesOrMore(1))
426       continue;
427 
428     for (auto &U : I->operands()) {
429       if (auto *OpI = dyn_cast<Instruction>(U))
430         MaybeDead.insert(OpI);
431     }
432     I->dropAllReferences();
433     Dead.insert(I);
434   }
435 
436   for (auto *I : Dead)
437     I->eraseFromParent();
438 
439   for (auto I : L->blocks())
440     DeleteDeadPHIs(I);
441 }
442 
443 bool MVETailPredication::TryConvert(Value *TripCount) {
444   if (!IsPredicatedVectorLoop())
445     return false;
446 
447   LLVM_DEBUG(dbgs() << "TP: Found predicated vector loop.\n");
448 
449   // Walk through the masked intrinsics and try to find whether the predicate
450   // operand is generated from an induction variable.
451   Module *M = L->getHeader()->getModule();
452   Type *Ty = IntegerType::get(M->getContext(), 32);
453   SetVector<Instruction*> Predicates;
454   DenseMap<Instruction*, Instruction*> NewPredicates;
455 
456   for (auto *I : MaskedInsts) {
457     Intrinsic::ID ID = I->getIntrinsicID();
458     unsigned PredOp = ID == Intrinsic::masked_load ? 2 : 3;
459     auto *Predicate = dyn_cast<Instruction>(I->getArgOperand(PredOp));
460     if (!Predicate || Predicates.count(Predicate))
461       continue;
462 
463     VectorType *VecTy = getVectorType(I);
464     Value *NumElements = ComputeElements(TripCount, VecTy);
465     if (!NumElements)
466       continue;
467 
468     if (!isTailPredicate(Predicate, NumElements)) {
469       LLVM_DEBUG(dbgs() << "TP: Not tail predicate: " << *Predicate <<  "\n");
470       continue;
471     }
472 
473     LLVM_DEBUG(dbgs() << "TP: Found tail predicate: " << *Predicate << "\n");
474     Predicates.insert(Predicate);
475 
476     // Insert a phi to count the number of elements processed by the loop.
477     IRBuilder<> Builder(L->getHeader()->getFirstNonPHI());
478     PHINode *Processed = Builder.CreatePHI(Ty, 2);
479     Processed->addIncoming(NumElements, L->getLoopPreheader());
480 
481     // Insert the intrinsic to represent the effect of tail predication.
482     Builder.SetInsertPoint(cast<Instruction>(Predicate));
483     ConstantInt *Factor =
484       ConstantInt::get(cast<IntegerType>(Ty), VecTy->getNumElements());
485     Intrinsic::ID VCTPID;
486     switch (VecTy->getNumElements()) {
487     default:
488       llvm_unreachable("unexpected number of lanes");
489     case 4:  VCTPID = Intrinsic::arm_mve_vctp32; break;
490     case 8:  VCTPID = Intrinsic::arm_mve_vctp16; break;
491     case 16: VCTPID = Intrinsic::arm_mve_vctp8; break;
492 
493       // FIXME: vctp64 currently not supported because the predicate
494       // vector wants to be <2 x i1>, but v2i1 is not a legal MVE
495       // type, so problems happen at isel time.
496       // Intrinsic::arm_mve_vctp64 exists for ACLE intrinsics
497       // purposes, but takes a v4i1 instead of a v2i1.
498     }
499     Function *VCTP = Intrinsic::getDeclaration(M, VCTPID);
500     Value *TailPredicate = Builder.CreateCall(VCTP, Processed);
501     Predicate->replaceAllUsesWith(TailPredicate);
502     NewPredicates[Predicate] = cast<Instruction>(TailPredicate);
503 
504     // Add the incoming value to the new phi.
505     // TODO: This add likely already exists in the loop.
506     Value *Remaining = Builder.CreateSub(Processed, Factor);
507     Processed->addIncoming(Remaining, L->getLoopLatch());
508     LLVM_DEBUG(dbgs() << "TP: Insert processed elements phi: "
509                << *Processed << "\n"
510                << "TP: Inserted VCTP: " << *TailPredicate << "\n");
511   }
512 
513   // Now clean up.
514   Cleanup(NewPredicates, Predicates, L);
515   return true;
516 }
517 
518 Pass *llvm::createMVETailPredicationPass() {
519   return new MVETailPredication();
520 }
521 
522 char MVETailPredication::ID = 0;
523 
524 INITIALIZE_PASS_BEGIN(MVETailPredication, DEBUG_TYPE, DESC, false, false)
525 INITIALIZE_PASS_END(MVETailPredication, DEBUG_TYPE, DESC, false, false)
526