1//===- VPlanUtils.h - VPlan-related utilities -------------------*- C++ -*-===//
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#ifndef LLVM_TRANSFORMS_VECTORIZE_VPLANUTILS_H
10#define LLVM_TRANSFORMS_VECTORIZE_VPLANUTILS_H
11
12#include "VPlan.h"
13#include "llvm/Support/BlockFrequency.h"
14#include "llvm/Support/BranchProbability.h"
15#include "llvm/Support/Compiler.h"
16
17namespace llvm {
18class DominatorTree;
19class MemoryLocation;
20class ScalarEvolution;
21class SCEV;
22class PredicatedScalarEvolution;
23} // namespace llvm
24
25namespace llvm {
26
27namespace vputils {
28/// Returns true if only the first lane of \p Def is used.
29bool onlyFirstLaneUsed(const VPValue *Def);
30
31/// Returns true if only the first part of \p Def is used.
32bool onlyFirstPartUsed(const VPValue *Def);
33
34/// Returns true if only scalar values of \p Def are used by all users.
35bool onlyScalarValuesUsed(const VPValue *Def);
36
37/// Get or create a VPValue that corresponds to the expansion of \p Expr. If \p
38/// Expr is a SCEVConstant or SCEVUnknown, return a VPValue wrapping the live-in
39/// value. Otherwise return a VPExpandSCEVRecipe to expand \p Expr. If \p Plan's
40/// pre-header already contains a recipe expanding \p Expr, return it. If not,
41/// create a new one.
42VPValue *getOrCreateVPValueForSCEVExpr(VPlan &Plan, const SCEV *Expr);
43
44/// Return the SCEV expression for \p V. Returns SCEVCouldNotCompute if no
45/// SCEV expression could be constructed.
46LLVM_ABI_FOR_TEST const SCEV *
47getSCEVExprForVPValue(const VPValue *V, PredicatedScalarEvolution &PSE,
48 const Loop *L = nullptr);
49
50/// If the pointer operand \p Addr of a memory access is an affine AddRec
51/// w.r.t. \p L with a constant stride, return the stride in units of
52/// \p AccessTy. Otherwise return std::nullopt.
53std::optional<int64_t> getConstantStride(VPValue *Addr, Type *AccessTy,
54 PredicatedScalarEvolution &PSE,
55 const Loop *L);
56
57/// Returns true if \p Addr is an address SCEV that can be passed to
58/// TTI::getAddressComputationCost, i.e. the address SCEV is loop invariant, an
59/// affine AddRec (i.e. induction ), or an add expression of such operands or a
60/// sign-extended AddRec.
61bool isAddressSCEVForCost(const SCEV *Addr, ScalarEvolution &SE, const Loop *L);
62
63/// Returns true if \p VPV is a single scalar, either because it produces the
64/// same value for all lanes or only has its first lane used.
65bool isSingleScalar(const VPValue *VPV);
66
67/// Checks if \p V is uniform across all VF lanes and UF parts. It is considered
68/// as such if it is either loop invariant (defined outside the vector region)
69/// or its operands are known to be uniform across all VFs and UFs (e.g.
70/// VPDerivedIV or the canonical IV).
71LLVM_ABI_FOR_TEST bool isUniformAcrossVFsAndUFs(const VPValue *V);
72
73/// Return true if \p V is elementwise, i.e. none of the lanes are permuted.
74bool isElementwise(const VPValue *V);
75
76/// Returns true if \p R produces scalar values for all VF lanes.
77bool doesGeneratePerAllLanes(const VPRecipeBase *R);
78
79/// Returns the header block of the first, top-level loop, or null if none
80/// exist.
81VPBasicBlock *getFirstLoopHeader(VPlan &Plan, VPDominatorTree &VPDT);
82
83/// Get the VF scaling factor applied to the recipe's output, if the recipe has
84/// one.
85unsigned getVFScaleFactor(VPRecipeBase *R);
86
87/// Return true if we do not know how to (mechanically) hoist or sink \p R.
88/// When sinking, passing \p Sinking = true ensures that assumes aren't sunk.
89/// Returns true for recipes that access memory.
90bool cannotHoistOrSinkRecipe(const VPRecipeBase &R, bool Sinking = false);
91
92/// Return the intrinsic ID underlying a call.
93template <typename Ty> Intrinsic::ID getIntrinsicID(const Ty *R) {
94 if (const auto *Intr = dyn_cast<VPWidenIntrinsicRecipe>(R))
95 return Intr->getVectorIntrinsicID();
96 if (const auto *Call = dyn_cast<VPWidenCallRecipe>(R))
97 return Call->getCalledScalarFunction()->getIntrinsicID();
98
99 auto GetCalleeIntrinsic = [&](VPValue *CalleeOp) -> Intrinsic::ID {
100 if (!isa<VPIRValue>(Val: CalleeOp))
101 return Intrinsic::not_intrinsic;
102 auto *F = cast<Function>(Val: CalleeOp->getLiveInIRValue());
103 return F->getIntrinsicID();
104 };
105 if (const auto *Rep = dyn_cast<VPReplicateRecipe>(R))
106 if (Rep->getOpcode() == Instruction::Call)
107 // The callee is the last operand, excluding the mask if predicated.
108 return GetCalleeIntrinsic(
109 Rep->getOperand(Rep->getNumOperandsWithoutMask() - 1));
110 if (const auto *VPI = dyn_cast<VPInstruction>(R)) {
111 if (VPI->getOpcode() == Instruction::Call)
112 // The callee is the last operand, excluding the mask if masked.
113 return GetCalleeIntrinsic(
114 VPI->getOperand(VPI->getNumOperandsWithoutMask() - 1));
115 if (VPI->getOpcode() == VPInstruction::Intrinsic) {
116 return cast<VPConstantInt>(VPI->getLastOperand())->getZExtValue();
117 }
118 }
119 return Intrinsic::not_intrinsic;
120}
121
122/// Return the instruction opcode for the recipe defining \p V or 0 for
123/// unsupported recipes and VPValues not defined by a recipe.
124unsigned getOpcode(const VPValue *V);
125
126/// Get the instruction opcode or intrinsic ID for the recipe defining \p V.
127/// Returns an optional pair, where the first element indicates whether it is an
128/// intrinsic ID.
129std::optional<std::pair<bool, unsigned>>
130getOpcodeOrIntrinsicID(const VPValue *V);
131
132/// Return a MemoryLocation for \p R with noalias metadata populated from
133/// \p R, if the recipe is supported and std::nullopt otherwise. The pointer of
134/// the location is conservatively set to nullptr.
135std::optional<MemoryLocation> getMemoryLocation(const VPRecipeBase &R);
136
137/// Extracts and returns NoWrap flags from \p PhiR and fast-math flags from \p
138/// ID.
139VPIRFlags getFlagsForInduction(const InductionDescriptor &ID,
140 const VPPhi *PhiR);
141
142/// Search \p Start's users for a recipe satisfying \p Pred, looking through
143/// recipes with definitions.
144template <typename PredT>
145inline VPRecipeBase *findRecipe(VPValue *Start, PredT Pred) {
146 SetVector<VPValue *> Worklist;
147 Worklist.insert(X: Start);
148 for (unsigned I = 0; I != Worklist.size(); ++I) {
149 VPValue *Cur = Worklist[I];
150 auto *R = Cur->getDefiningRecipe();
151 if (!R)
152 continue;
153 if (Pred(R))
154 return R;
155 for (VPUser *U : Cur->users()) {
156 for (VPValue *V : cast<VPRecipeBase>(Val: U)->definedValues())
157 Worklist.insert(X: V);
158 }
159 }
160 return nullptr;
161}
162
163/// Find the canonical IV increment of \p Plan's vector loop region. Returns
164/// nullptr if not found.
165VPInstruction *findCanonicalIVIncrement(VPlan &Plan);
166
167/// Returns the GEP nowrap flags for \p Ptr, looking through pointer casts
168/// mirroring Value::stripPointerCasts.
169GEPNoWrapFlags getGEPFlagsForPtr(VPValue *Ptr);
170
171/// Returns true if \p V is used as part of the address of another load or
172/// store.
173bool isUsedByLoadStoreAddress(const VPValue *V);
174
175/// Find the ComputeReductionResult recipe for \p PhiR, looking through selects
176/// inserted for predicated reductions or tail folding.
177VPInstruction *findComputeReductionResult(VPReductionPHIRecipe *PhiR);
178
179/// Finds the incoming alias-mask within the vector preheader.
180VPValue *findIncomingAliasMask(const VPlan &Plan);
181
182/// Returns the (early exiting block, exit block) pairs of \p Plan, i.e. all
183/// edges to an exit block that do not come from \p MiddleVPBB.
184SmallVector<std::pair<VPBasicBlock *, VPIRBasicBlock *>>
185getEarlyExits(const VPlan &Plan, const VPBlockBase *MiddleVPBB);
186
187/// Create a scalar-iv-steps recipe over \p Plan's canonical IV for an
188/// induction of \p Kind with \p InductionOpcode / \p FPBinOp, start value \p
189/// StartV and step \p Step, truncated to \p TruncI's type if \p TruncI is
190/// non-null, inserting recipes via \p Builder.
191VPScalarIVStepsRecipe *createScalarIVSteps(
192 VPlan &Plan, InductionDescriptor::InductionKind Kind,
193 Instruction::BinaryOps InductionOpcode, FPMathOperator *FPBinOp,
194 Instruction *TruncI, VPValue *StartV, VPValue *Step, DebugLoc DL,
195 VPBuilder &Builder, const VPIRFlags::WrapFlagsTy &Flags = {});
196
197/// Scalarize a VPWidenPointerInductionRecipe by replacing it with a PtrAdd
198/// (IndStart, ScalarIVSteps (0, Step)). This is used when the recipe only
199/// generates scalar values.
200VPValue *scalarizeVPWidenPointerInduction(VPWidenPointerInductionRecipe *PtrIV,
201 VPlan &Plan, VPBuilder &Builder);
202
203/// Returns true if \p R is dead, i.e. none of its defined values are used and
204/// it has no side effects (with the exception of conditional assumes, which are
205/// considered dead as their conditions may be flattened).
206bool isDeadRecipe(VPRecipeBase &R);
207
208/// Recursively delete \p V and any of its operands that become dead.
209void recursivelyDeleteDeadRecipes(VPValue *V);
210
211/// Collect all users of \p V, looking through recipes that define other values.
212SmallVector<VPUser *> collectUsersRecursively(VPValue *V);
213
214/// Try to fold \p R using InstSimplifyFolder. Will succeed and return a
215/// non-nullptr VPValue for a handled opcode or intrinsic ID if corresponding \p
216/// Operands are foldable live-ins.
217VPIRValue *tryToFoldLiveIns(VPSingleDefRecipe &R, ArrayRef<VPValue *> Operands,
218 const DataLayout &DL);
219
220/// Insert phis to reconstruct SSA for a single value starting from \p VPBB. \p
221/// Defs is a map of definitions at specific blocks. Returns the
222/// reconstructed value at VPBB. Use if the CFG has been modified such that a
223/// def no longer dominates all its uses. Every block leading to VPBB must be
224/// reachable from the entry and the plan must be plain-CFG (not contain any
225/// regions).
226LLVM_ABI_FOR_TEST VPValue *
227reconstructSSA(VPBasicBlock *VPBB, DenseMap<VPBasicBlock *, VPValue *> &Defs);
228
229/// Returns \p Freq as a BranchProbability, relative to the full mass.
230BranchProbability getExecutionProbability(BlockFrequency Freq);
231
232/// Computes for each block in \p Blocks, which must be in reverse post-order,
233/// the frequency with which it executes relative to the first (header) block,
234/// and whether that frequency was composed using any estimated branch weights.
235/// The frequency of a block is the sum over its incoming edges, or std::nullopt
236/// if any edge on a path reaching it lacks branch weights. Edges to blocks
237/// outside \p Blocks are ignored.
238DenseMap<const VPBasicBlock *, std::optional<VPExecutionFrequency>>
239computeExecutionFrequencies(ArrayRef<VPBasicBlock *> Blocks);
240
241namespace detail {
242
243/// Template-independent implementation for pullOutPermutations.
244void pullOutPermutationsImpl(
245 VPlan &Plan, function_ref<VPValue *(VPValue *Op)> Perm,
246 function_ref<VPSingleDefRecipe *(VPSingleDefRecipe *X)> Build);
247} // namespace detail
248
249/// Removes the permutation pattern \p Perm from any elementwise operations
250/// in the plan, by constructing a new permutation via \p Build.
251/// e.g. binop(perm(x), perm(y)) -> perm(binop(x,y)).
252template <typename Match_t, typename Builder>
253void pullOutPermutations(VPlan &Plan, Match_t Perm, Builder Build) {
254 // Convert matcher to function returing the matched VPValue.
255 auto MatchPerm = [&Perm](VPValue *Op) -> VPValue * {
256 VPValue *X;
257 return match(Op, Perm(X)) ? X : nullptr;
258 };
259 detail::pullOutPermutationsImpl(Plan, Perm: MatchPerm, Build);
260}
261
262} // namespace vputils
263
264/// Lightweight SCEV-to-VPlan expander. Converts SCEV expressions into
265/// VPInstructions and live-ins. SCEVAddRecExprs are wrapped in a
266/// VPExpandSCEVRecipe to be expanded to IR later.
267class VPSCEVExpander {
268 VPBuilder &Builder;
269 ScalarEvolution &SE;
270 DebugLoc DL;
271
272 /// When true, nested SCEVUDivExprs are expanded so that they cannot divide by
273 /// zero, matching SCEVExpander's SafeUDivMode.
274 bool SafeUDivMode = false;
275
276 /// Try to find a loop-invariant IR value in the plan's entry block whose
277 /// SCEV matches \p S. Returns the corresponding live-in VPValue, or nullptr
278 /// if none is found.
279 VPValue *tryToReuseIRValue(const SCEV *S);
280
281public:
282 VPSCEVExpander(VPBuilder &Builder, ScalarEvolution &SE, DebugLoc DL)
283 : Builder(Builder), SE(SE), DL(DL) {}
284
285 /// Expand \p S into recipes and live-ins using the builder.
286 VPValue *expand(const SCEV *S);
287};
288//===----------------------------------------------------------------------===//
289// Utilities for modifying predecessors and successors of VPlan blocks.
290//===----------------------------------------------------------------------===//
291
292/// Class that provides utilities for VPBlockBases in VPlan.
293class VPBlockUtils {
294public:
295 VPBlockUtils() = delete;
296
297 /// Insert disconnected VPBlockBase \p NewBlock after \p BlockPtr. Add \p
298 /// NewBlock as successor of \p BlockPtr and \p BlockPtr as predecessor of \p
299 /// NewBlock, and propagate \p BlockPtr parent to \p NewBlock. \p BlockPtr's
300 /// successors are moved from \p BlockPtr to \p NewBlock. \p NewBlock must
301 /// have neither successors nor predecessors.
302 static void insertBlockAfter(VPBlockBase *NewBlock, VPBlockBase *BlockPtr) {
303 assert(!NewBlock->hasSuccessors() && !NewBlock->hasPredecessors() &&
304 "Can't insert new block with predecessors or successors.");
305 NewBlock->setParent(BlockPtr->getParent());
306 transferSuccessors(Old: BlockPtr, New: NewBlock);
307 connectBlocks(From: BlockPtr, To: NewBlock);
308 }
309
310 /// Insert disconnected block \p NewBlock before \p Blockptr. First
311 /// disconnects all predecessors of \p BlockPtr and connects them to \p
312 /// NewBlock. Add \p NewBlock as predecessor of \p BlockPtr and \p BlockPtr as
313 /// successor of \p NewBlock.
314 static void insertBlockBefore(VPBlockBase *NewBlock, VPBlockBase *BlockPtr) {
315 assert(!NewBlock->hasSuccessors() && !NewBlock->hasPredecessors() &&
316 "Can't insert new block with predecessors or successors.");
317 NewBlock->setParent(BlockPtr->getParent());
318 for (VPBlockBase *Pred : to_vector(Range: BlockPtr->predecessors()))
319 replaceSuccessor(From: Pred, OldSucc: BlockPtr, NewSucc: NewBlock);
320 connectBlocks(From: NewBlock, To: BlockPtr);
321 }
322
323 /// Insert disconnected VPBlockBases \p IfTrue and \p IfFalse after \p
324 /// BlockPtr. Add \p IfTrue and \p IfFalse as succesors of \p BlockPtr and \p
325 /// BlockPtr as predecessor of \p IfTrue and \p IfFalse. Propagate \p BlockPtr
326 /// parent to \p IfTrue and \p IfFalse. \p BlockPtr must have no successors
327 /// and \p IfTrue and \p IfFalse must have neither successors nor
328 /// predecessors.
329 static void insertTwoBlocksAfter(VPBlockBase *IfTrue, VPBlockBase *IfFalse,
330 VPBlockBase *BlockPtr) {
331 assert(!IfTrue->hasSuccessors() && "Can't insert IfTrue with successors.");
332 assert(!IfFalse->hasSuccessors() &&
333 "Can't insert IfFalse with successors.");
334 BlockPtr->setTwoSuccessors(IfTrue, IfFalse);
335 IfTrue->setPredecessors({BlockPtr});
336 IfFalse->setPredecessors({BlockPtr});
337 IfTrue->setParent(BlockPtr->getParent());
338 IfFalse->setParent(BlockPtr->getParent());
339 }
340
341 /// Connect VPBlockBases \p From and \p To bi-directionally. If \p PredIdx is
342 /// -1, append \p From to the predecessors of \p To, otherwise set \p To's
343 /// predecessor at \p PredIdx to \p From. If \p SuccIdx is -1, append \p To to
344 /// the successors of \p From, otherwise set \p From's successor at \p SuccIdx
345 /// to \p To. Both VPBlockBases must have the same parent, which can be null.
346 /// Both VPBlockBases can be already connected to other VPBlockBases.
347 static void connectBlocks(VPBlockBase *From, VPBlockBase *To,
348 unsigned PredIdx = -1u, unsigned SuccIdx = -1u) {
349 assert((From->getParent() == To->getParent()) &&
350 "Can't connect two block with different parents");
351
352 if (SuccIdx == -1u)
353 From->appendSuccessor(Successor: To);
354 else
355 From->getSuccessors()[SuccIdx] = To;
356
357 if (PredIdx == -1u)
358 To->appendPredecessor(Predecessor: From);
359 else
360 To->getPredecessors()[PredIdx] = From;
361 }
362
363 /// Disconnect VPBlockBases \p From and \p To bi-directionally. Remove \p To
364 /// from the successors of \p From and \p From from the predecessors of \p To.
365 static void disconnectBlocks(VPBlockBase *From, VPBlockBase *To) {
366 assert(To && "Successor to disconnect is null.");
367 From->removeSuccessor(Successor: To);
368 To->removePredecessor(Predecessor: From);
369 }
370
371 /// Redirect the edge from \p From to \p OldSucc to \p NewSucc, keeping \p
372 /// From's successor order. \p From is removed from \p OldSucc's predecessors
373 /// and appended to \p NewSucc's.
374 static void replaceSuccessor(VPBlockBase *From, VPBlockBase *OldSucc,
375 VPBlockBase *NewSucc) {
376 From->replaceSuccessor(Old: OldSucc, New: NewSucc);
377 OldSucc->removePredecessor(Predecessor: From);
378 NewSucc->appendPredecessor(Predecessor: From);
379 }
380
381 /// Reassociate all the blocks connected to \p Old so that they now point to
382 /// \p New.
383 static void reassociateBlocks(VPBlockBase *Old, VPBlockBase *New) {
384 auto Preds = to_vector(Range&: Old->getPredecessors());
385 auto Succs = to_vector(Range&: Old->getSuccessors());
386 for (auto *Pred : Preds)
387 Pred->replaceSuccessor(Old, New);
388 for (auto *Succ : Succs)
389 Succ->replacePredecessor(Old, New);
390 New->setPredecessors(Old->getPredecessors());
391 New->setSuccessors(Old->getSuccessors());
392 Old->clearPredecessors();
393 Old->clearSuccessors();
394 }
395
396 /// Transfer successors from \p Old to \p New. \p New must have no successors.
397 static void transferSuccessors(VPBlockBase *Old, VPBlockBase *New) {
398 for (auto *Succ : Old->getSuccessors())
399 Succ->replacePredecessor(Old, New);
400 New->setSuccessors(Old->getSuccessors());
401 Old->clearSuccessors();
402 }
403
404 /// Clone the CFG for all nodes reachable from \p Entry, including cloning
405 /// the blocks and their recipes. Operands of cloned recipes will NOT be
406 /// updated. Remapping of operands must be done separately. Returns a pair
407 /// with the new entry and exiting blocks of the cloned region. If \p Entry
408 /// isn't part of a region, return nullptr for the exiting block.
409 static std::pair<VPBlockBase *, VPBlockBase *> cloneFrom(VPBlockBase *Entry);
410
411 /// Return an iterator range over \p Range which only includes \p BlockTy
412 /// blocks. The accesses are casted to \p BlockTy.
413 template <typename BlockTy, typename T> static auto blocksOnly(T &&Range) {
414 return make_isa_range<BlockTy>(std::forward<T>(Range));
415 }
416
417 /// Return an iterator range over \p Range with each block cast to \p
418 /// BlockTy. Unlike blocksOnly, all blocks in \p Range must be of type
419 /// \p BlockTy.
420 template <typename BlockTy, typename T> static auto blocksAs(T &&Range) {
421 // Create BaseTy with correct const-ness based on BlockTy.
422 using BaseTy = std::conditional_t<std::is_const<BlockTy>::value,
423 const VPBlockBase, VPBlockBase>;
424 return map_range(
425 Range, [](BaseTy *Block) -> BlockTy * { return cast<BlockTy>(Block); });
426 }
427
428 /// Returns the blocks between \p FirstBB and \p LastBB, where FirstBB
429 /// to LastBB forms a single-sucessor chain.
430 static SmallVector<VPBasicBlock *>
431 blocksInSingleSuccessorChainBetween(VPBasicBlock *FirstBB,
432 VPBasicBlock *LastBB);
433
434 /// Inserts \p BlockPtr on the edge between \p From and \p To. That is, update
435 /// \p From's successor to \p To to point to \p BlockPtr and \p To's
436 /// predecessor from \p From to \p BlockPtr. \p From and \p To are added to \p
437 /// BlockPtr's predecessors and successors respectively. There must be a
438 /// single edge between \p From and \p To.
439 static void insertOnEdge(VPBlockBase *From, VPBlockBase *To,
440 VPBlockBase *BlockPtr) {
441 unsigned SuccIdx = From->getIndexForSuccessor(Succ: To);
442 unsigned PredIx = To->getIndexForPredecessor(Pred: From);
443 VPBlockUtils::connectBlocks(From, To: BlockPtr, PredIdx: -1, SuccIdx);
444 VPBlockUtils::connectBlocks(From: BlockPtr, To, PredIdx: PredIx, SuccIdx: -1);
445 }
446
447 /// Returns true if \p VPB is a loop header, based on regions or \p VPDT in
448 /// their absence.
449 static bool isHeader(const VPBlockBase *VPB, const VPDominatorTree &VPDT);
450
451 /// Returns true if \p VPB is a loop latch, using isHeader().
452 static bool isLatch(const VPBlockBase *VPB, const VPDominatorTree &VPDT);
453
454 /// Returns the header and latch of the outermost loop of \p Plan in plain
455 /// CFG form (before regions are formed).
456 static std::pair<VPBasicBlock *, VPBasicBlock *>
457 getPlainCFGHeaderAndLatch(const VPlan &Plan);
458
459 /// Returns the middle block of \p Plan in plain CFG form (before regions
460 /// are formed).
461 static VPBasicBlock *getPlainCFGMiddleBlock(const VPlan &Plan);
462};
463
464} // namespace llvm
465
466#endif
467