LLVM 24.0.0git
VPlan.h
Go to the documentation of this file.
1//===- VPlan.h - Represent A Vectorizer Plan --------------------*- 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/// \file
10/// This file contains the declarations of the Vectorization Plan base classes:
11/// 1. VPBasicBlock and VPRegionBlock that inherit from a common pure virtual
12/// VPBlockBase, together implementing a Hierarchical CFG;
13/// 2. Pure virtual VPRecipeBase serving as the base class for recipes contained
14/// within VPBasicBlocks;
15/// 3. Pure virtual VPSingleDefRecipe serving as a base class for recipes that
16/// also inherit from VPValue.
17/// 4. VPInstruction, a concrete Recipe and VPUser modeling a single planned
18/// instruction;
19/// 5. The VPlan class holding a candidate for vectorization;
20/// These are documented in docs/VectorizationPlan.rst.
21//
22//===----------------------------------------------------------------------===//
23
24#ifndef LLVM_TRANSFORMS_VECTORIZE_VPLAN_H
25#define LLVM_TRANSFORMS_VECTORIZE_VPLAN_H
26
27#include "VPlanValue.h"
28#include "llvm/ADT/Bitfields.h"
29#include "llvm/ADT/MapVector.h"
30#include "llvm/ADT/SetVector.h"
33#include "llvm/ADT/Twine.h"
34#include "llvm/ADT/ilist.h"
35#include "llvm/ADT/ilist_node.h"
39#include "llvm/IR/Attributes.h"
40#include "llvm/IR/DebugLoc.h"
41#include "llvm/IR/FMF.h"
42#include "llvm/IR/Operator.h"
46#include <cassert>
47#include <cstddef>
48#include <functional>
49#include <optional>
50#include <string>
51#include <utility>
52#include <variant>
53
54namespace llvm {
55
56class BasicBlock;
57class DominatorTree;
58struct VPTransformState;
59class raw_ostream;
60class SCEV;
61class SCEVPredicate;
62class Type;
63class VPBasicBlock;
65template <typename InserterTy = VPBuilderDefaultInserter> class VPBuilderBase;
67class VPDominatorTree;
68class VPRegionBlock;
69class VPlan;
71class Value;
73
74struct VPCostContext;
75
76using VPlanPtr = std::unique_ptr<VPlan>;
77
78/// \enum UncountableExitStyle
79/// Different methods of handling early exits.
80///
82 /// No side effects to worry about, so we can process any uncountable exits
83 /// in the loop and branch either to the middle block if the trip count was
84 /// reached, or an early exitblock to determine which exit was taken.
86 /// All memory operations other than the load(s) required to determine whether
87 /// an uncountable exit occurre will be masked based on that condition. If an
88 /// uncountable exit is taken, then all lanes before the exiting lane will
89 /// complete, leaving just the final lane to execute in the scalar tail.
91};
92
93/// VPBlockBase is the building block of the Hierarchical Control-Flow Graph.
94/// A VPBlockBase can be either a VPBasicBlock or a VPRegionBlock.
96 friend class VPBlockUtils;
97
98protected:
99 /// An enumeration for keeping track of the concrete subclass of VPBlockBase
100 /// that are actually instantiated. Values of this enumeration are kept in the
101 /// SubclassID field of the VPBlockBase objects. They are used for concrete
102 /// type identification.
103 using VPBlockTy = enum : unsigned char {
104 VPRegionBlockSC,
105 VPBasicBlockSC,
106 VPIRBasicBlockSC
107 };
108
109private:
110 /// An optional name for the block.
111 std::string Name;
112
113 /// The immediate VPRegionBlock which this VPBlockBase belongs to, or null if
114 /// it is a topmost VPBlockBase.
115 VPRegionBlock *Parent = nullptr;
116
117 /// List of predecessor blocks.
119
120 /// List of successor blocks.
122
123 /// VPlan containing the block. Set when the block is created via VPlan
124 /// helpers.
125 VPlan *Plan = nullptr;
126
127 /// Subclass identifier (for isa/dyn_cast).
128 const VPBlockTy SubclassID;
129
130 /// Unique number, used as node number in the dominator tree.
131 unsigned Number;
132
133 /// Add \p Successor as the last successor to this block.
134 void appendSuccessor(VPBlockBase *Successor) {
135 assert(Successor && "Cannot add nullptr successor!");
136 Successors.push_back(Successor);
137 }
138
139 /// Add \p Predecessor as the last predecessor to this block.
140 void appendPredecessor(VPBlockBase *Predecessor) {
141 assert(Predecessor && "Cannot add nullptr predecessor!");
142 Predecessors.push_back(Predecessor);
143 }
144
145 /// Remove \p Predecessor from the predecessors of this block.
146 void removePredecessor(VPBlockBase *Predecessor) {
147 auto Pos = find(Predecessors, Predecessor);
148 assert(Pos && "Predecessor does not exist");
149 Predecessors.erase(Pos);
150 }
151
152 /// Remove \p Successor from the successors of this block.
153 void removeSuccessor(VPBlockBase *Successor) {
154 auto Pos = find(Successors, Successor);
155 assert(Pos && "Successor does not exist");
156 Successors.erase(Pos);
157 }
158
159 /// This function replaces one predecessor with another, useful when
160 /// trying to replace an old block in the CFG with a new one.
161 void replacePredecessor(VPBlockBase *Old, VPBlockBase *New) {
162 auto I = find(Predecessors, Old);
163 assert(I != Predecessors.end());
164 assert(Old->getParent() == New->getParent() &&
165 "replaced predecessor must have the same parent");
166 *I = New;
167 }
168
169 /// This function replaces one successor with another, useful when
170 /// trying to replace an old block in the CFG with a new one.
171 void replaceSuccessor(VPBlockBase *Old, VPBlockBase *New) {
172 auto I = find(Successors, Old);
173 assert(I != Successors.end());
174 assert(Old->getParent() == New->getParent() &&
175 "replaced successor must have the same parent");
176 *I = New;
177 }
178
179public:
181
182 virtual ~VPBlockBase() = default;
183
184 const std::string &getName() const { return Name; }
185
186 void setName(const Twine &newName) { Name = newName.str(); }
187
188 /// \return an ID for the concrete type of this object.
189 /// This is used to implement the classof checks. This should not be used
190 /// for any other purpose, as the values may change as LLVM evolves.
191 unsigned getVPBlockID() const { return SubclassID; }
192
193 VPRegionBlock *getParent() { return Parent; }
194 const VPRegionBlock *getParent() const { return Parent; }
195
196 /// \return A pointer to the plan containing the current block.
197 VPlan *getPlan() { return Plan; }
198 const VPlan *getPlan() const { return Plan; }
199
200 /// Sets the pointer of the plan containing the block.
201 void setPlan(VPlan *ParentPlan) { Plan = ParentPlan; }
202
203 void setParent(VPRegionBlock *P) { Parent = P; }
204
205 /// \return the VPBasicBlock that is the entry of this VPBlockBase,
206 /// recursively, if the latter is a VPRegionBlock. Otherwise, if this
207 /// VPBlockBase is a VPBasicBlock, it is returned.
208 const VPBasicBlock *getEntryBasicBlock() const;
209 VPBasicBlock *getEntryBasicBlock();
210
211 /// \return the VPBasicBlock that is the exiting this VPBlockBase,
212 /// recursively, if the latter is a VPRegionBlock. Otherwise, if this
213 /// VPBlockBase is a VPBasicBlock, it is returned.
214 const VPBasicBlock *getExitingBasicBlock() const;
215 VPBasicBlock *getExitingBasicBlock();
216
217 const VPBlocksTy &getSuccessors() const { return Successors; }
218 VPBlocksTy &getSuccessors() { return Successors; }
219
220 /// Returns true if this block has any successors.
221 bool hasSuccessors() const { return !Successors.empty(); }
222 /// Returns true if this block has any predecessors.
223 bool hasPredecessors() const { return !Predecessors.empty(); }
224
227
228 const VPBlocksTy &getPredecessors() const { return Predecessors; }
229 VPBlocksTy &getPredecessors() { return Predecessors; }
230
231 /// \return the successor of this VPBlockBase if it has a single successor.
232 /// Otherwise return a null pointer.
234 return (Successors.size() == 1 ? *Successors.begin() : nullptr);
235 }
236
237 /// \return the predecessor of this VPBlockBase if it has a single
238 /// predecessor. Otherwise return a null pointer.
240 return (Predecessors.size() == 1 ? *Predecessors.begin() : nullptr);
241 }
242
243 size_t getNumSuccessors() const { return Successors.size(); }
244 size_t getNumPredecessors() const { return Predecessors.size(); }
245
246 /// An Enclosing Block of a block B is any block containing B, including B
247 /// itself. \return the closest enclosing block starting from "this", which
248 /// has successors. \return the root enclosing block if all enclosing blocks
249 /// have no successors.
250 VPBlockBase *getEnclosingBlockWithSuccessors();
251
252 /// \return the closest enclosing block starting from "this", which has
253 /// predecessors. \return the root enclosing block if all enclosing blocks
254 /// have no predecessors.
255 VPBlockBase *getEnclosingBlockWithPredecessors();
256
257 /// \return the successors either attached directly to this VPBlockBase or, if
258 /// this VPBlockBase is the exit block of a VPRegionBlock and has no
259 /// successors of its own, search recursively for the first enclosing
260 /// VPRegionBlock that has successors and return them. If no such
261 /// VPRegionBlock exists, return the (empty) successors of the topmost
262 /// VPBlockBase reached.
264 return getEnclosingBlockWithSuccessors()->getSuccessors();
265 }
266
267 /// \return the hierarchical predecessor of this VPBlockBase if it has a
268 /// single hierarchical predecessor. Otherwise return a null pointer.
272
273 /// Set a given VPBlockBase \p Successor as the single successor of this
274 /// VPBlockBase. This VPBlockBase is not added as predecessor of \p Successor.
275 /// This VPBlockBase must have no successors.
277 assert(Successors.empty() && "Setting one successor when others exist.");
278 assert(Successor->getParent() == getParent() &&
279 "connected blocks must have the same parent");
280 appendSuccessor(Successor);
281 }
282
283 /// Set two given VPBlockBases \p IfTrue and \p IfFalse to be the two
284 /// successors of this VPBlockBase. This VPBlockBase is not added as
285 /// predecessor of \p IfTrue or \p IfFalse. This VPBlockBase must have no
286 /// successors.
287 void setTwoSuccessors(VPBlockBase *IfTrue, VPBlockBase *IfFalse) {
288 assert(Successors.empty() && "Setting two successors when others exist.");
289 appendSuccessor(IfTrue);
290 appendSuccessor(IfFalse);
291 }
292
293 /// Set each VPBasicBlock in \p NewPreds as predecessor of this VPBlockBase.
294 /// This VPBlockBase must have no predecessors. This VPBlockBase is not added
295 /// as successor of any VPBasicBlock in \p NewPreds.
297 assert(Predecessors.empty() && "Block predecessors already set.");
298 for (auto *Pred : NewPreds)
299 appendPredecessor(Pred);
300 }
301
302 /// Set each VPBasicBlock in \p NewSuccss as successor of this VPBlockBase.
303 /// This VPBlockBase must have no successors. This VPBlockBase is not added
304 /// as predecessor of any VPBasicBlock in \p NewSuccs.
306 assert(Successors.empty() && "Block successors already set.");
307 for (auto *Succ : NewSuccs)
308 appendSuccessor(Succ);
309 }
310
311 /// Remove all the predecessor of this block.
312 void clearPredecessors() { Predecessors.clear(); }
313
314 /// Remove all the successors of this block.
315 void clearSuccessors() { Successors.clear(); }
316
317 /// Swap predecessors of the block. The block must have exactly 2
318 /// predecessors.
320 assert(Predecessors.size() == 2 && "must have 2 predecessors to swap");
321 std::swap(Predecessors[0], Predecessors[1]);
322 }
323
324 /// Swap successors of the block. The block must have exactly 2 successors.
325 // TODO: This should be part of introducing conditional branch recipes rather
326 // than being independent.
328 assert(Successors.size() == 2 && "must have 2 successors to swap");
329 std::swap(Successors[0], Successors[1]);
330 }
331
332 /// Returns the index for \p Pred in the blocks predecessors list.
333 unsigned getIndexForPredecessor(const VPBlockBase *Pred) const {
334 assert(count(Predecessors, Pred) == 1 &&
335 "must have Pred exactly once in Predecessors");
336 return std::distance(Predecessors.begin(), find(Predecessors, Pred));
337 }
338
339 /// Returns the index for \p Succ in the blocks successor list.
340 unsigned getIndexForSuccessor(const VPBlockBase *Succ) const {
341 assert(count(Successors, Succ) == 1 &&
342 "must have Succ exactly once in Successors");
343 return std::distance(Successors.begin(), find(Successors, Succ));
344 }
345
346 /// Return the unique number of the block.
347 unsigned getNumber() const { return Number; }
348
349 /// Set the unique number of the block, used for dominator tree.
350 void setNumber(unsigned N) { Number = N; }
351
352 /// The method which generates the output IR that correspond to this
353 /// VPBlockBase, thereby "executing" the VPlan.
354 virtual void execute(VPTransformState *State) = 0;
355
356 /// Return the cost of the block.
358
359 void printAsOperand(raw_ostream &OS, bool PrintType = false) const {
360 OS << getName();
361 }
362
363#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
364 /// Print plain-text dump of this VPBlockBase to \p O, prefixing all lines
365 /// with \p Indent. \p SlotTracker is used to print unnamed VPValue's using
366 /// consequtive numbers.
367 ///
368 /// Note that the numbering is applied to the whole VPlan, so printing
369 /// individual blocks is consistent with the whole VPlan printing.
370 virtual void print(raw_ostream &O, const Twine &Indent,
371 VPSlotTracker &SlotTracker) const = 0;
372
373 /// Print plain-text dump of this VPlan to \p O.
374 void print(raw_ostream &O) const;
375
376 /// Print the successors of this block to \p O, prefixing all lines with \p
377 /// Indent.
378 void printSuccessors(raw_ostream &O, const Twine &Indent) const;
379
380 /// Dump this VPBlockBase to dbgs().
381 LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
382#endif
383
384 /// Clone the current block and it's recipes without updating the operands of
385 /// the cloned recipes, including all blocks in the single-entry single-exit
386 /// region for VPRegionBlocks.
387 virtual VPBlockBase *clone() = 0;
388
389protected:
390 VPBlockBase(VPBlockTy SC, const std::string &N) : Name(N), SubclassID(SC) {}
391};
392
393/// VPRecipeBase is a base class modeling a sequence of one or more output IR
394/// instructions. VPRecipeBase owns the VPValues it defines through VPDef
395/// and is responsible for deleting its defined values. Single-value
396/// recipes must inherit from VPSingleDef instead of inheriting from both
397/// VPRecipeBase and VPValue separately.
399 : public ilist_node_with_parent<VPRecipeBase, VPBasicBlock,
400 ilist_parent<VPBasicBlock>>,
401 public VPDef,
402 public VPUser {
403 friend VPBasicBlock;
404 friend class VPBlockUtils;
405
406 /// The debug location for the recipe.
407 DebugLoc DL;
408
409public:
410 /// An enumeration for keeping track of the concrete subclass of VPRecipeBase
411 /// that is actually instantiated. Values of this enumeration are kept in the
412 /// SubclassID field of the VPRecipeBase objects. They are used for concrete
413 /// type identification.
414 using VPRecipeTy = enum : unsigned char {
415 VPBranchOnMaskSC,
416 VPDerivedIVSC,
417 VPExpandSCEVSC,
418 VPExpressionSC,
419 VPIRInstructionSC,
420 VPInstructionSC,
421 VPInterleaveEVLSC,
422 VPInterleaveSC,
423 VPReductionEVLSC,
424 VPReductionSC,
425 VPReplicateSC,
426 VPScalarIVStepsSC,
427 VPVectorPointerSC,
428 VPVectorEndPointerSC,
429 VPWidenCallSC,
430 VPWidenCanonicalIVSC,
431 VPWidenCastSC,
432 VPWidenGEPSC,
433 VPWidenIntrinsicSC,
434 VPWidenMemIntrinsicSC,
435 VPWidenLoadEVLSC,
436 VPWidenLoadSC,
437 VPWidenStoreEVLSC,
438 VPWidenStoreSC,
439 VPWidenSC,
440 VPBlendSC,
441 VPHistogramSC,
442 // START: Phi-like recipes. Need to be kept together.
443 VPWidenPHISC,
444 VPPredInstPHISC,
445 // START: SubclassID for recipes that inherit VPHeaderPHIRecipe.
446 // VPHeaderPHIRecipe need to be kept together.
447 VPCurrentIterationPHISC,
448 VPActiveLaneMaskPHISC,
449 VPFirstOrderRecurrencePHISC,
450 VPWidenIntOrFpInductionSC,
451 VPWidenPointerInductionSC,
452 VPReductionPHISC,
453 VPConditionalInductionPHISC,
454 // END: SubclassID for recipes that inherit VPHeaderPHIRecipe
455 // END: Phi-like recipes
456 VPFirstPHISC = VPWidenPHISC,
457 VPFirstHeaderPHISC = VPCurrentIterationPHISC,
458 VPLastHeaderPHISC = VPConditionalInductionPHISC,
459 VPLastPHISC = VPConditionalInductionPHISC,
460 };
461
464 : VPDef(), VPUser(Operands), DL(DL), SubclassID(SC) {}
465
466 ~VPRecipeBase() override = default;
467
468 /// Clone the current recipe.
469 virtual VPRecipeBase *clone() = 0;
470
471 /// The list type holding the recipes of a VPBasicBlock. Each node, including
472 /// the sentinel, stores its parent VPBasicBlock.
474
475 /// \return the VPRegionBlock which the recipe belongs to.
477 const VPRegionBlock *getRegion() const;
478
479 /// The method which generates the output IR instructions that correspond to
480 /// this VPRecipe, thereby "executing" the VPlan.
481 virtual void execute(VPTransformState &State) = 0;
482
483 /// Return the cost of this recipe, taking into account if the cost
484 /// computation should be skipped and the ForceTargetInstructionCost flag.
485 /// Also takes care of printing the cost for debugging.
487
488 /// Insert an unlinked recipe into a basic block immediately before
489 /// the specified recipe.
490 void insertBefore(VPRecipeBase *InsertPos);
491 /// Insert an unlinked recipe immediately before the insertion point \p IP.
493
494 /// Insert an unlinked Recipe into a basic block immediately after
495 /// the specified Recipe.
496 void insertAfter(VPRecipeBase *InsertPos);
497
498 /// Unlink this recipe from its current VPBasicBlock and insert it into
499 /// the VPBasicBlock that MovePos lives in, right after MovePos.
500 void moveAfter(VPRecipeBase *MovePos);
501
502 /// Unlink this recipe and insert it before \p I.
504
505 /// This method unlinks 'this' from the containing basic block, but does not
506 /// delete it.
507 void removeFromParent();
508
509 /// This method unlinks 'this' from the containing basic block and deletes it.
510 ///
511 /// \returns an iterator pointing to the element after the erased one
513
514 /// \return an ID for the concrete type of this object.
515 VPRecipeTy getVPRecipeID() const { return SubclassID; }
516
517 /// Method to support type inquiry through isa, cast, and dyn_cast.
518 static inline bool classof(const VPDef *D) {
519 // All VPDefs are also VPRecipeBases.
520 return true;
521 }
522
523 static inline bool classof(const VPUser *U) { return true; }
524
525 /// Returns true if the recipe may have side-effects.
526 bool mayHaveSideEffects() const;
527
528 /// Return true if we can safely execute this recipe unconditionally even if
529 /// it is masked originally.
530 bool isSafeToSpeculativelyExecute() const;
531
532 /// Returns true for PHI-like recipes.
533 bool isPhi() const;
534
535 /// Returns true if the recipe may read from memory.
536 bool mayReadFromMemory() const;
537
538 /// Returns true if the recipe may write to memory.
539 bool mayWriteToMemory() const;
540
541 /// Returns true if the recipe may read from or write to memory.
542 bool mayReadOrWriteMemory() const {
544 }
545
546 /// Returns the debug location of the recipe.
547 DebugLoc getDebugLoc() const { return DL; }
548
549 /// Set the recipe's debug location to \p NewDL.
550 void setDebugLoc(DebugLoc NewDL) { DL = NewDL; }
551
552#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
553 /// Dump the recipe to stderr (for debugging).
554 void dump() const;
555
556 /// Print the recipe, delegating to printRecipe().
557 void print(raw_ostream &O, const Twine &Indent,
559#endif
560
561private:
562 /// Subclass identifier (for isa/dyn_cast).
563 const VPRecipeTy SubclassID;
564
565protected:
566 /// Compute the cost of this recipe either using a recipe's specialized
567 /// implementation or using the legacy cost model and the underlying
568 /// instructions.
569 virtual InstructionCost computeCost(ElementCount VF,
570 VPCostContext &Ctx) const;
571
572#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
573 /// Each concrete VPRecipe prints itself, without printing common information,
574 /// like debug info or metadata.
575 virtual void printRecipe(raw_ostream &O, const Twine &Indent,
576 VPSlotTracker &SlotTracker) const = 0;
577#endif
578};
579
580// Helper macro to define common classof implementations for recipes.
581#define VP_CLASSOF_IMPL(VPRecipeID) \
582 static inline bool classof(const VPRecipeBase *R) { \
583 return R->getVPRecipeID() == VPRecipeID; \
584 } \
585 static inline bool classof(const VPValue *V) { \
586 auto *R = V->getDefiningRecipe(); \
587 return R && R->getVPRecipeID() == VPRecipeID; \
588 } \
589 static inline bool classof(const VPUser *U) { \
590 auto *R = dyn_cast<VPRecipeBase>(U); \
591 return R && R->getVPRecipeID() == VPRecipeID; \
592 } \
593 static inline bool classof(const VPSingleDefRecipe *R) { \
594 return R->getVPRecipeID() == VPRecipeID; \
595 }
596
597/// Compute the scalar result type for an IR \p Opcode given \p Operands.
598LLVM_ABI Type *computeScalarTypeForInstruction(unsigned Opcode,
600
601/// VPSingleDefRecipe is a base class for recipes that model a sequence of one
602/// or more output IR that define a single result VPValue. Note that
603/// VPSingleDefRecipe must inherit from VPRecipeBase before VPSingleDefValue.
605 public VPSingleDefValue {
606public:
608 Value *UV = nullptr, DebugLoc DL = DebugLoc::getUnknown())
609 : VPRecipeBase(SC, Operands, DL), VPSingleDefValue(this, UV, ResultTy) {}
610
611 static inline bool classof(const VPRecipeBase *R) {
612 switch (R->getVPRecipeID()) {
613 case VPRecipeBase::VPDerivedIVSC:
614 case VPRecipeBase::VPExpandSCEVSC:
615 case VPRecipeBase::VPExpressionSC:
616 case VPRecipeBase::VPInstructionSC:
617 case VPRecipeBase::VPReductionEVLSC:
618 case VPRecipeBase::VPReductionSC:
619 case VPRecipeBase::VPReplicateSC:
620 case VPRecipeBase::VPScalarIVStepsSC:
621 case VPRecipeBase::VPVectorPointerSC:
622 case VPRecipeBase::VPVectorEndPointerSC:
623 case VPRecipeBase::VPWidenCallSC:
624 case VPRecipeBase::VPWidenCanonicalIVSC:
625 case VPRecipeBase::VPWidenCastSC:
626 case VPRecipeBase::VPWidenGEPSC:
627 case VPRecipeBase::VPWidenIntrinsicSC:
628 case VPRecipeBase::VPWidenMemIntrinsicSC:
629 case VPRecipeBase::VPWidenSC:
630 case VPRecipeBase::VPBlendSC:
631 case VPRecipeBase::VPPredInstPHISC:
632 case VPRecipeBase::VPCurrentIterationPHISC:
633 case VPRecipeBase::VPActiveLaneMaskPHISC:
634 case VPRecipeBase::VPFirstOrderRecurrencePHISC:
635 case VPRecipeBase::VPWidenPHISC:
636 case VPRecipeBase::VPWidenIntOrFpInductionSC:
637 case VPRecipeBase::VPWidenPointerInductionSC:
638 case VPRecipeBase::VPReductionPHISC:
639 case VPRecipeBase::VPWidenLoadEVLSC:
640 case VPRecipeBase::VPWidenLoadSC:
641 case VPRecipeBase::VPConditionalInductionPHISC:
642 return true;
643 case VPRecipeBase::VPBranchOnMaskSC:
644 case VPRecipeBase::VPInterleaveEVLSC:
645 case VPRecipeBase::VPInterleaveSC:
646 case VPRecipeBase::VPIRInstructionSC:
647 case VPRecipeBase::VPWidenStoreEVLSC:
648 case VPRecipeBase::VPWidenStoreSC:
649 case VPRecipeBase::VPHistogramSC:
650 return false;
651 }
652 llvm_unreachable("Unhandled VPRecipeID");
653 }
654
655 static inline bool classof(const VPValue *V) {
656 auto *R = V->getDefiningRecipe();
657 return R && classof(R);
658 }
659
660 static inline bool classof(const VPUser *U) {
661 auto *R = dyn_cast<VPRecipeBase>(U);
662 return R && classof(R);
663 }
664
665 VPSingleDefRecipe *clone() override = 0;
666
667 /// Returns the underlying instruction.
674
675#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
676 /// Print this VPSingleDefRecipe to dbgs() (for debugging).
677 LLVM_DUMP_METHOD void dump() const;
678#endif
679};
680
681/// Class to record and manage LLVM IR flags.
684 enum class OperationType : unsigned char {
685 Cmp,
686 FCmp,
687 OverflowingBinOp,
688 Trunc,
689 DisjointOp,
690 PossiblyExactOp,
691 GEPOp,
692 FPMathOp,
693 NonNegOp,
694 ReductionOp,
695 Other
696 };
697
698public:
699 struct WrapFlagsTy {
700 char HasNUW : 1;
701 char HasNSW : 1;
702
706 return {static_cast<bool>(HasNUW), false};
707 }
708 };
709
711 char HasNUW : 1;
712 char HasNSW : 1;
713
715 };
716
721
723 char NonNeg : 1;
724 NonNegFlagsTy(bool IsNonNeg) : NonNeg(IsNonNeg) {}
725 };
726
727private:
728 struct ExactFlagsTy {
729 char IsExact : 1;
730 ExactFlagsTy(bool Exact) : IsExact(Exact) {}
731 };
732 struct FastMathFlagsTy {
733 char AllowReassoc : 1;
734 char NoNaNs : 1;
735 char NoInfs : 1;
736 char NoSignedZeros : 1;
737 char AllowReciprocal : 1;
738 char AllowContract : 1;
739 char ApproxFunc : 1;
740
741 LLVM_ABI_FOR_TEST FastMathFlagsTy(const FastMathFlags &FMF);
742 };
743 /// Holds both the predicate and fast-math flags for floating-point
744 /// comparisons.
745 struct FCmpFlagsTy {
746 uint8_t CmpPredStorage;
747 FastMathFlagsTy FMFs;
748 };
749 /// Holds reduction-specific flags: RecurKind, IsOrdered, IsInLoop, and FMFs.
750 struct ReductionFlagsTy {
751 // RecurKind has ~26 values, needs 5 bits but uses 6 bits to account for
752 // additional kinds.
753 unsigned char Kind : 6;
754 // TODO: Derive order/in-loop from plan and remove here.
755 unsigned char IsOrdered : 1;
756 unsigned char IsInLoop : 1;
757 FastMathFlagsTy FMFs;
758
759 ReductionFlagsTy(RecurKind Kind, bool IsOrdered, bool IsInLoop,
760 FastMathFlags FMFs)
761 : Kind(static_cast<unsigned char>(Kind)), IsOrdered(IsOrdered),
762 IsInLoop(IsInLoop), FMFs(FMFs) {}
763 };
764
765 OperationType OpType;
766
767 union {
772 ExactFlagsTy ExactFlags;
775 FastMathFlagsTy FMFs;
776 FCmpFlagsTy FCmpFlags;
777 ReductionFlagsTy ReductionFlags;
779 };
780
781public:
782 VPIRFlags() : OpType(OperationType::Other), AllFlags() {}
783
785 if (auto *FCmp = dyn_cast<FCmpInst>(&I)) {
786 OpType = OperationType::FCmp;
788 FCmp->getPredicate());
789 assert(getPredicate() == FCmp->getPredicate() && "predicate truncated");
790 FCmpFlags.FMFs = FCmp->getFastMathFlags();
791 } else if (auto *Op = dyn_cast<CmpInst>(&I)) {
792 OpType = OperationType::Cmp;
794 Op->getPredicate());
795 assert(getPredicate() == Op->getPredicate() && "predicate truncated");
796 } else if (auto *Op = dyn_cast<PossiblyDisjointInst>(&I)) {
797 OpType = OperationType::DisjointOp;
798 DisjointFlags.IsDisjoint = Op->isDisjoint();
799 } else if (auto *Op = dyn_cast<OverflowingBinaryOperator>(&I)) {
800 OpType = OperationType::OverflowingBinOp;
801 WrapFlags = {Op->hasNoUnsignedWrap(), Op->hasNoSignedWrap()};
802 } else if (auto *Op = dyn_cast<TruncInst>(&I)) {
803 OpType = OperationType::Trunc;
804 TruncFlags = {Op->hasNoUnsignedWrap(), Op->hasNoSignedWrap()};
805 } else if (auto *Op = dyn_cast<PossiblyExactOperator>(&I)) {
806 OpType = OperationType::PossiblyExactOp;
807 ExactFlags.IsExact = Op->isExact();
808 } else if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
809 OpType = OperationType::GEPOp;
810 GEPFlagsStorage = GEP->getNoWrapFlags().getRaw();
811 assert(getGEPNoWrapFlags() == GEP->getNoWrapFlags() &&
812 "wrap flags truncated");
813 } else if (auto *PNNI = dyn_cast<PossiblyNonNegInst>(&I)) {
814 OpType = OperationType::NonNegOp;
815 NonNegFlags.NonNeg = PNNI->hasNonNeg();
816 } else if (auto *Op = dyn_cast<FPMathOperator>(&I)) {
817 OpType = OperationType::FPMathOp;
818 FMFs = Op->getFastMathFlags();
819 }
820 }
821
822 VPIRFlags(CmpInst::Predicate Pred) : OpType(OperationType::Cmp), AllFlags() {
824 assert(getPredicate() == Pred && "predicate truncated");
825 }
826
828 : OpType(OperationType::FCmp), AllFlags() {
830 assert(getPredicate() == Pred && "predicate truncated");
831 FCmpFlags.FMFs = FMFs;
832 }
833
835 : OpType(OperationType::OverflowingBinOp), AllFlags() {
836 this->WrapFlags = WrapFlags;
837 }
838
840 : OpType(OperationType::Trunc), AllFlags() {
841 this->TruncFlags = TruncFlags;
842 }
843
844 VPIRFlags(FastMathFlags FMFs) : OpType(OperationType::FPMathOp), AllFlags() {
845 this->FMFs = FMFs;
846 }
847
849 : OpType(OperationType::DisjointOp), AllFlags() {
850 this->DisjointFlags = DisjointFlags;
851 }
852
854 : OpType(OperationType::NonNegOp), AllFlags() {
855 this->NonNegFlags = NonNegFlags;
856 }
857
858 VPIRFlags(ExactFlagsTy ExactFlags)
859 : OpType(OperationType::PossiblyExactOp), AllFlags() {
860 this->ExactFlags = ExactFlags;
861 }
862
864 : OpType(OperationType::GEPOp), AllFlags() {
865 GEPFlagsStorage = GEPFlags.getRaw();
866 }
867
868 VPIRFlags(RecurKind Kind, bool IsOrdered, bool IsInLoop, FastMathFlags FMFs)
869 : OpType(OperationType::ReductionOp), AllFlags() {
870 ReductionFlags = ReductionFlagsTy(Kind, IsOrdered, IsInLoop, FMFs);
871 }
872
873 /// Only keep flags also present in \p Other. \p Other must have the same
874 /// OpType as the current object.
875 void intersectFlags(const VPIRFlags &Other);
876
877 /// Drop all poison-generating flags.
879 // NOTE: This needs to be kept in-sync with
880 // Instruction::dropPoisonGeneratingFlags.
881 switch (OpType) {
882 case OperationType::OverflowingBinOp:
883 WrapFlags.HasNUW = false;
884 WrapFlags.HasNSW = false;
885 break;
886 case OperationType::Trunc:
887 TruncFlags.HasNUW = false;
888 TruncFlags.HasNSW = false;
889 break;
890 case OperationType::DisjointOp:
891 DisjointFlags.IsDisjoint = false;
892 break;
893 case OperationType::PossiblyExactOp:
894 ExactFlags.IsExact = false;
895 break;
896 case OperationType::GEPOp:
897 GEPFlagsStorage = 0;
898 break;
899 case OperationType::FPMathOp:
900 case OperationType::FCmp:
901 case OperationType::ReductionOp:
902 getFMFsRef().NoNaNs = false;
903 getFMFsRef().NoInfs = false;
904 break;
905 case OperationType::NonNegOp:
906 NonNegFlags.NonNeg = false;
907 break;
908 case OperationType::Cmp:
909 case OperationType::Other:
910 break;
911 }
912 }
913
914 /// Apply the IR flags to \p I.
915 void applyFlags(Instruction &I) const {
916 switch (OpType) {
917 case OperationType::OverflowingBinOp:
918 I.setHasNoUnsignedWrap(WrapFlags.HasNUW);
919 I.setHasNoSignedWrap(WrapFlags.HasNSW);
920 break;
921 case OperationType::Trunc:
922 I.setHasNoUnsignedWrap(TruncFlags.HasNUW);
923 I.setHasNoSignedWrap(TruncFlags.HasNSW);
924 break;
925 case OperationType::DisjointOp:
926 cast<PossiblyDisjointInst>(&I)->setIsDisjoint(DisjointFlags.IsDisjoint);
927 break;
928 case OperationType::PossiblyExactOp:
929 I.setIsExact(ExactFlags.IsExact);
930 break;
931 case OperationType::GEPOp:
932 cast<GetElementPtrInst>(&I)->setNoWrapFlags(
934 break;
935 case OperationType::FPMathOp:
936 case OperationType::FCmp:
937 I.copyFastMathFlags(getFastMathFlagsOrNone());
938 break;
939 case OperationType::NonNegOp:
940 I.setNonNeg(NonNegFlags.NonNeg);
941 break;
942 case OperationType::ReductionOp:
943 llvm_unreachable("reduction ops should not use applyFlags");
944 case OperationType::Cmp:
945 case OperationType::Other:
946 break;
947 }
948 }
949
951 assert((OpType == OperationType::Cmp || OpType == OperationType::FCmp) &&
952 "recipe doesn't have a compare predicate");
953 uint8_t Storage = OpType == OperationType::FCmp ? FCmpFlags.CmpPredStorage
956 }
957
959 assert((OpType == OperationType::Cmp || OpType == OperationType::FCmp) &&
960 "recipe doesn't have a compare predicate");
961 if (OpType == OperationType::FCmp)
963 else
965 assert(getPredicate() == Pred && "predicate truncated");
966 }
967
971
972 /// Returns true if the recipe has a comparison predicate.
973 bool hasPredicate() const {
974 return OpType == OperationType::Cmp || OpType == OperationType::FCmp;
975 }
976
977 /// Returns true if the recipe has fast-math flags.
978 bool hasFastMathFlags() const {
979 return OpType == OperationType::FPMathOp || OpType == OperationType::FCmp ||
980 OpType == OperationType::ReductionOp;
981 }
982
984
985 bool hasNoUnsignedWrap() const {
986 switch (OpType) {
987 case OperationType::OverflowingBinOp:
988 return WrapFlags.HasNUW;
989 case OperationType::Trunc:
990 return TruncFlags.HasNUW;
991 default:
992 llvm_unreachable("recipe doesn't have a NUW flag");
993 }
994 }
995
996 bool hasNoSignedWrap() const {
997 switch (OpType) {
998 case OperationType::OverflowingBinOp:
999 return WrapFlags.HasNSW;
1000 case OperationType::Trunc:
1001 return TruncFlags.HasNSW;
1002 default:
1003 llvm_unreachable("recipe doesn't have a NSW flag");
1004 }
1005 }
1006
1008 switch (OpType) {
1009 case OperationType::OverflowingBinOp:
1010 case OperationType::Trunc:
1011 return {hasNoUnsignedWrap(), hasNoSignedWrap()};
1012 default:
1013 return {};
1014 }
1015 }
1016
1018 return {hasNoUnsignedWrap(), hasNoSignedWrap()};
1019 }
1020
1021 bool isDisjoint() const {
1022 assert(OpType == OperationType::DisjointOp &&
1023 "recipe cannot have a disjoing flag");
1024 return DisjointFlags.IsDisjoint;
1025 }
1026
1028 assert(OpType == OperationType::ReductionOp &&
1029 "recipe doesn't have reduction flags");
1030 return static_cast<RecurKind>(ReductionFlags.Kind);
1031 }
1032
1033 bool isReductionOrdered() const {
1034 assert(OpType == OperationType::ReductionOp &&
1035 "recipe doesn't have reduction flags");
1036 return ReductionFlags.IsOrdered;
1037 }
1038
1039 bool isReductionInLoop() const {
1040 assert(OpType == OperationType::ReductionOp &&
1041 "recipe doesn't have reduction flags");
1042 return ReductionFlags.IsInLoop;
1043 }
1044
1045private:
1046 /// Get a reference to the fast-math flags for FPMathOp, FCmp or ReductionOp.
1047 FastMathFlagsTy &getFMFsRef() {
1048 if (OpType == OperationType::FCmp)
1049 return FCmpFlags.FMFs;
1050 if (OpType == OperationType::ReductionOp)
1051 return ReductionFlags.FMFs;
1052 return FMFs;
1053 }
1054 const FastMathFlagsTy &getFMFsRef() const {
1055 if (OpType == OperationType::FCmp)
1056 return FCmpFlags.FMFs;
1057 if (OpType == OperationType::ReductionOp)
1058 return ReductionFlags.FMFs;
1059 return FMFs;
1060 }
1061
1062public:
1063 /// Returns default flags for \p Opcode and scalar \p ResultTy for opcodes
1064 /// that support it, asserts otherwise. Opcodes not supporting default flags
1065 /// include compares and ComputeReductionResult.
1066 LLVM_ABI_FOR_TEST static VPIRFlags getDefaultFlags(unsigned Opcode,
1067 Type *ResultTy = nullptr);
1068
1069#if !defined(NDEBUG)
1070 /// Returns true if the set flags are valid for \p Opcode.
1071 LLVM_ABI_FOR_TEST bool flagsValidForOpcode(unsigned Opcode) const;
1072
1073 /// Returns true if \p Opcode with scalar result type \p ResultTy has its
1074 /// required flags set.
1075 LLVM_ABI_FOR_TEST bool hasRequiredFlagsForOpcode(unsigned Opcode,
1076 Type *ResultTy) const;
1077#endif
1078
1079#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1080 void printFlags(raw_ostream &O) const;
1081#endif
1082};
1084
1085static_assert(sizeof(VPIRFlags) <= 3, "VPIRFlags should not grow");
1086
1087/// A pure-virtual common base class for recipes defining a single VPValue and
1088/// using IR flags.
1091 Type *ResultTy, const VPIRFlags &Flags,
1093 : VPSingleDefRecipe(SC, Operands, ResultTy, /*UV=*/nullptr, DL),
1094 VPIRFlags(Flags) {}
1095
1096 static inline bool classof(const VPRecipeBase *R) {
1097 return R->getVPRecipeID() == VPRecipeBase::VPBlendSC ||
1098 R->getVPRecipeID() == VPRecipeBase::VPInstructionSC ||
1099 R->getVPRecipeID() == VPRecipeBase::VPWidenSC ||
1100 R->getVPRecipeID() == VPRecipeBase::VPWidenGEPSC ||
1101 R->getVPRecipeID() == VPRecipeBase::VPWidenCallSC ||
1102 R->getVPRecipeID() == VPRecipeBase::VPWidenCastSC ||
1103 R->getVPRecipeID() == VPRecipeBase::VPWidenIntrinsicSC ||
1104 R->getVPRecipeID() == VPRecipeBase::VPWidenMemIntrinsicSC ||
1105 R->getVPRecipeID() == VPRecipeBase::VPReductionSC ||
1106 R->getVPRecipeID() == VPRecipeBase::VPReductionEVLSC ||
1107 R->getVPRecipeID() == VPRecipeBase::VPReplicateSC ||
1108 R->getVPRecipeID() == VPRecipeBase::VPVectorEndPointerSC ||
1109 R->getVPRecipeID() == VPRecipeBase::VPVectorPointerSC ||
1110 R->getVPRecipeID() == VPRecipeBase::VPWidenCanonicalIVSC ||
1111 R->getVPRecipeID() == VPRecipeBase::VPDerivedIVSC;
1112 }
1113
1114 static inline bool classof(const VPUser *U) {
1115 auto *R = dyn_cast<VPRecipeBase>(U);
1116 return R && classof(R);
1117 }
1118
1119 static inline bool classof(const VPValue *V) {
1120 auto *R = V->getDefiningRecipe();
1121 return R && classof(R);
1122 }
1123
1125
1126 static inline bool classof(const VPSingleDefRecipe *R) {
1127 return classof(static_cast<const VPRecipeBase *>(R));
1128 }
1129
1130 void execute(VPTransformState &State) override = 0;
1131
1132 /// Compute the cost for this recipe for \p VF, using \p Opcode and \p Ctx.
1134 VPCostContext &Ctx) const;
1135};
1136
1137/// The frequency with which a recipe executes, relative to the entry of the
1138/// loop region. IsEstimated is set if any branch weight it was composed from
1139/// was estimated from static heuristics.
1142 const bool IsEstimated;
1143
1146 assert(Freq > BlockFrequency() && "execution frequency must be non-zero");
1147 }
1148};
1149
1150/// Helper to manage IR metadata for recipes. It filters out metadata that
1151/// cannot be propagated.
1154
1155 /// Name of the VPlan-internal metadata kind holding the execution frequency.
1156 static constexpr StringLiteral ExecutionFrequencyMDName =
1157 "vplan.execution.frequency";
1158
1159 /// Name of the VPlan-internal metadata kind holding estimated branch weights.
1160 static constexpr StringLiteral EstimatedProfileMDName =
1161 "vplan.prof.estimated";
1162
1163 /// Returns the ID of the metadata kind named \p Kind, taking the context from
1164 /// any attached node; all belong to the context of the VPlan's function.
1165 unsigned getMDKindID(StringRef Kind) const {
1166 assert(!Metadata.empty() && "no node to take the context from");
1167 return Metadata.front().second->getContext().getMDKindID(Kind);
1168 }
1169
1170 /// Returns the node attached under the VPlan-internal metadata kind named
1171 /// \p Kind, or nullptr if there is none.
1172 MDNode *getInternalMetadata(StringRef Kind) const {
1173 return Metadata.empty() ? nullptr : getMetadata(getMDKindID(Kind));
1174 }
1175
1176public:
1177 VPIRMetadata() = default;
1178
1179 /// Adds metatadata that can be preserved from the original instruction
1180 /// \p I.
1182 getMetadataToPropagate(&I, Metadata);
1183 // Retain the branch weights of terminators. They are used to compute the
1184 // frequencies with which the blocks of the original loop execute. Also
1185 // retain !prof on selects.
1186 if (I.isTerminator() || isa<SelectInst>(&I))
1187 if (MDNode *BW = I.getMetadata(LLVMContext::MD_prof))
1188 Metadata.emplace_back(LLVMContext::MD_prof, BW);
1189 }
1190
1191 /// Copy constructor for cloning.
1193
1195
1196 /// Add all metadata to \p I.
1197 void applyMetadata(Instruction &I) const;
1198
1199 /// Set metadata with kind \p Kind to \p Node. If metadata with \p Kind
1200 /// already exists, it will be replaced. Otherwise, it will be added.
1201 void setMetadata(unsigned Kind, MDNode *Node) {
1202 auto It =
1203 llvm::find_if(Metadata, [Kind](const std::pair<unsigned, MDNode *> &P) {
1204 return P.first == Kind;
1205 });
1206 if (It != Metadata.end())
1207 It->second = Node;
1208 else
1209 Metadata.emplace_back(Kind, Node);
1210 }
1211
1212 /// Remove the metadata of kind \p Kind, if present.
1213 void eraseMetadata(unsigned Kind) {
1214 erase_if(Metadata, [Kind](const auto &P) { return P.first == Kind; });
1215 }
1216
1217 /// Intersect this VPIRMetadata object with \p MD, keeping only metadata
1218 /// nodes that are common to both.
1219 void intersect(const VPIRMetadata &MD);
1220
1221 /// Get metadata of kind \p Kind. Returns nullptr if not found.
1222 MDNode *getMetadata(unsigned Kind) const {
1223 auto It =
1224 find_if(Metadata, [Kind](const auto &P) { return P.first == Kind; });
1225 return It != Metadata.end() ? It->second : nullptr;
1226 }
1227
1228 /// Record that the recipe executes with frequency \p Freq, relative to the
1229 /// entry of the loop region.
1230 void setExecutionFrequency(std::optional<VPExecutionFrequency> Freq,
1231 LLVMContext &Ctx);
1232
1233 /// Returns the frequency recorded by setExecutionFrequency, if any.
1234 std::optional<VPExecutionFrequency> getExecutionFrequency() const;
1235
1236 /// Drop the frequency recorded by setExecutionFrequency, if any.
1237 void clearExecutionFrequency();
1238
1239 /// Returns the branch weights recorded for this terminator, preferring real
1240 /// profile data over an estimate, or nullptr if there are none.
1242 MDNode *Node = getMetadata(LLVMContext::MD_prof);
1243 return Node ? Node : getInternalMetadata(EstimatedProfileMDName);
1244 }
1245
1246 /// Returns true if the weights returned by getBranchWeights are estimated.
1248 return getInternalMetadata(EstimatedProfileMDName);
1249 }
1250
1251 /// Set estimated branch weights to \p Node.
1253 assert(!getMetadata(LLVMContext::MD_prof) &&
1254 "real profile data takes precedence over an estimate");
1255 setMetadata(Node->getContext().getMDKindID(EstimatedProfileMDName), Node);
1256 }
1257
1258#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1259 /// Print metadata with node IDs.
1260 void print(raw_ostream &O, VPSlotTracker &SlotTracker) const;
1261#endif
1262};
1263
1264class VPInstruction;
1265
1266/// Manage IR attributes for call recipes. Call VPInstructions store all
1267/// call-site attributes. Widened calls only store return and per-argument
1268/// attributes that are valid to propagate to the widened call.
1270 AttributeList CallAttrs;
1271
1272public:
1273 VPIRAttributes() = default;
1274
1275 explicit VPIRAttributes(AttributeList CallAttrs) : CallAttrs(CallAttrs) {}
1276
1277 /// Stores the return and per-arg attributes of the call VPInstruction \p
1278 /// Call that are valid for a widened call with type \p WideTy. If \p Call is
1279 /// masked, the scalar call only executes for some lanes, so argument
1280 /// attributes are only kept for widened arguments passed to a masked variant.
1282
1283 /// Keep only the attributes valid for both this and \p Other.
1285
1286 /// Apply the stored attributes to the widened call \p WideCall.
1287 void applyAttrs(CallInst &WideCall) const {
1288 WideCall.setAttributes(CallAttrs);
1289 }
1290
1291 /// Returns the memory effects of a call with these attributes to a callee
1292 /// with function attributes \p CalleeFnAttrs.
1294 return CallAttrs.getMemoryEffects() & CalleeFnAttrs.getMemoryEffects();
1295 }
1296
1297 /// Returns true if the call site or \p CalleeFnAttrs has \p Kind.
1298 bool hasFnAttr(Attribute::AttrKind Kind, AttributeSet CalleeFnAttrs) const {
1299 return CallAttrs.hasFnAttr(Kind) || CalleeFnAttrs.hasAttribute(Kind);
1300 }
1301
1302#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1303 /// Print return-value attributes carried with this object.
1304 void printRetAttrs(raw_ostream &O) const;
1305
1306 /// Print per-arg attributes for argument \p ArgIdx.
1307 void printParamAttrs(raw_ostream &O, unsigned ArgIdx) const;
1308
1309 /// Print function attributes carried with this object.
1310 void printFnAttrs(raw_ostream &O) const;
1311#endif
1312};
1313
1314/// This is a concrete Recipe that models a single VPlan-level instruction.
1315/// While as any Recipe it may generate a sequence of IR instructions when
1316/// executed, these instructions would always form a single-def expression as
1317/// the VPInstruction is also a single def-use vertex. Most VPInstruction
1318/// opcodes can take an optional mask. Masks may be assigned during
1319/// predication.
1321 public VPIRMetadata,
1322 public VPIRAttributes {
1323public:
1324 /// VPlan opcodes, extending LLVM IR with idiomatics instructions.
1325 enum {
1326 FirstOrderRecurrenceSplice = Instruction::OtherOpsEnd +
1327 1, // Combines the incoming and previous
1328 // values of a first-order recurrence.
1330 // Creates a mask where each lane is active (true) whilst the current
1331 // counter (first operand + index) is less than the second operand. i.e.
1332 // mask[i] = icmpt ult (op0 + i), op1
1333 // ActiveLaneMask is used for early-exit loops with stores, plus tail
1334 // folding for all styles except DataAndControlFlow. The size of the
1335 // mask returned is VF. When unrolled, ActiveLaneMask is duplicated.
1337 // As above, but takes an additional operand (Multiplier). The size of
1338 // the mask returned is VF * Multiplier (UF, op2).
1339 // WideActiveLaneMask is used for control flow and is unrolled by widening,
1340 // with one extract vector created per unroll part.
1342 // Signature: Vectors... -> WideVector
1343 // Concatenates all vector operands to a single wide vector.
1345 // Signature: (Multiplier, Address, Align) -> Vector
1346 // Loads a single wide vector of `Multiplier * VF` elements.
1348 // Signature: (Multiplier, Address, Alignment, Vector)
1349 // Stores a single wide vector of `Multiplier * VF` elements.
1351 // Extracts each unrolled part of a (VF * UF) widened vector/mask.
1354 // Represents the incoming loop-invariant alias-mask. All memory accesses
1355 // in the loop must stay within the active lanes.
1357 // Increment the canonical IV separately for each unrolled part.
1359 // Abstract instruction that compares two values and branches. This is
1360 // lowered to ICmp + BranchOnCond during VPlan to VPlan transformation.
1363 // Branch with 2 boolean condition operands and 3 successors. If condition
1364 // 0 is true, branches to successor 0; if condition 1 is true, branches to
1365 // successor 1; otherwise branches to successor 2. Expanded after region
1366 // dissolution into: (1) an OR of the two conditions branching to
1367 // middle.split or successor 2, and (2) middle.split branching to successor
1368 // 0 or successor 1 based on condition 0.
1371 /// Creates a fixed-width vector containing all operands. The number of
1372 /// operands matches the vector element count.
1374 /// Extracts all lanes from its (non-scalable) vector operand. This is an
1375 /// abstract VPInstruction whose single defined VPValue represents VF
1376 /// scalars extracted from a vector, to be replaced by VF ExtractElement
1377 /// VPInstructions.
1379 /// Reduce the operands to the final reduction result using the operation
1380 /// specified via the operation's VPIRFlags.
1382 // Extracts the last part of its operand. Removed during unrolling.
1384 // Extracts the last lane of its vector operand, per part.
1386 // Extracts the second-to-last lane from its operand or the second-to-last
1387 // part if it is scalar. In the latter case, the recipe will be removed
1388 // during unrolling.
1390 LogicalAnd, // Non-poison propagating logical And.
1391 LogicalOr, // Non-poison propagating logical Or.
1392 NumActiveLanes, // Counts the number of active lanes in a mask.
1393 // Add an offset in bytes (second operand) to a base pointer (first
1394 // operand). Only generates scalar values (either for the first lane only or
1395 // for all lanes, depending on its uses).
1397 // Add a vector offset in bytes (second operand) to a scalar base pointer
1398 // (first operand).
1400 // Returns a scalar boolean value, which is true if any lane of its
1401 // (boolean) vector operands is true. It produces the reduced value across
1402 // all unrolled iterations. Unrolling will add all copies of its original
1403 // operand as additional operands. Note does not block poison propagation.
1405 // Calculates the first active lane index of the vector predicate operands.
1406 // It produces the lane index across all unrolled iterations. Unrolling will
1407 // add all copies of its original operand as additional operands.
1408 // Implemented with @llvm.experimental.cttz.elts, but returns the expected
1409 // result even with operands that are all zeroes.
1411 // Calculates the last active lane index of the vector predicate operands.
1412 // The predicates must be prefix-masks (all 1s before all 0s). Used when
1413 // tail-folding to extract the correct live-out value from the last active
1414 // iteration. It produces the lane index across all unrolled iterations.
1415 // Unrolling will add all copies of its original operand as additional
1416 // operands.
1418 // Returns a reversed vector for the operand.
1420 /// Start vector for reductions with 3 operands: the original start value,
1421 /// the identity value for the reduction and an integer indicating the
1422 /// scaling factor.
1424 /// Extracts a single lane (first operand) from a set of vector operands.
1425 /// The lane specifies an index into a vector formed by combining all vector
1426 /// operands (all operands after the first one).
1428 /// Explicit user for values in the main VPlan, used by the epilogue vector
1429 /// loop. Operands are the resume value from the main vector loop and bypass
1430 /// value.
1432 /// Extracts the last active lane from a set of vectors. The first operand
1433 /// is the default value if no lanes in the masks are active. Conceptually,
1434 /// this concatenates all data vectors (odd operands), concatenates all
1435 /// masks (even operands -- ignoring the default value), and returns the
1436 /// last active value from the combined data vector using the combined mask.
1438 /// Compute the exiting value of a wide induction after vectorization, that
1439 /// is the value of the last lane of the induction increment (i.e. its
1440 /// backedge value). Has the wide induction recipe as operand.
1443 /// Scale the first operand (vector step) by the second operand
1444 /// (scalar-step). Casts both operands to the result type if needed.
1446 // Creates a step vector starting from 0 to VF with a step of 1.
1448 /// Calls a scalar intrinsic. The intrinsic ID is the last operand.
1450
1452 };
1453
1454 /// Returns true if this recipe produces scalar values for all VF lanes.
1455 bool doesGeneratePerAllLanes() const;
1456
1457 /// Return the number of operands determined by the opcode of the
1458 /// VPInstruction, excluding mask. Returns -1u if the number of operands
1459 /// cannot be determined directly by the opcode.
1460 unsigned getNumOperandsForOpcode() const;
1461
1462private:
1463 typedef unsigned char OpcodeTy;
1464 OpcodeTy Opcode;
1465
1466 /// An optional name that can be used for the generated IR instruction.
1467 std::string Name;
1468
1469 /// Whether this VPInstruction produces a single scalar value.
1470 const bool GeneratesSingleScalar;
1471
1472 /// Returns true if we can generate a single scalar, either because the recipe
1473 /// is known to generate one or because only its first lane is used.
1474 /// TODO: Replace remaining inferred cases with GeneratesSingleScalar.
1475 bool inferGeneratesSingleScalar() const;
1476
1477 /// Utility method serving execute: Generates either a single-scalar or vector
1478 /// value. \p GenerateSingleScalar determines whether to generate a
1479 /// single-scalar value.
1480 Value *generate(VPTransformState &State, bool GenerateSingleScalar);
1481
1482 /// Returns true if the VPInstruction does not need masking.
1483 bool alwaysUnmasked() const {
1485 "Should be expanded in VPlanPredicator");
1486
1487 // These VPInstruction can be (optionally) masked.
1488 if (Opcode == VPInstruction::WideVectorLoad ||
1490 return false;
1491
1492 // For now only VPInstructions with underlying values use masks.
1493 // TODO: provide masks to VPInstructions w/o underlying values.
1494 if (!getUnderlyingValue())
1495 return true;
1496
1497 return Instruction::isCast(Opcode) || Opcode == Instruction::PHI ||
1498 Opcode == Instruction::GetElementPtr ||
1499 Opcode == Instruction::ExtractValue;
1500 }
1501
1502 /// Returns true if this is an abstract instruction that can't be executed.
1503 bool isAbstract() const {
1504 return isMasked() && Opcode != VPInstruction::WideVectorLoad &&
1505 Opcode != VPInstruction::WideVectorStore;
1506 }
1507
1508public:
1509 VPInstruction(unsigned Opcode, ArrayRef<VPValue *> Operands,
1510 const VPIRFlags &Flags = {}, const VPIRMetadata &MD = {},
1511 DebugLoc DL = DebugLoc::getUnknown(), const Twine &Name = "",
1512 Type *ResultTy = nullptr, const VPIRAttributes &Attrs = {},
1513 std::optional<bool> GeneratesSingleScalar = std::nullopt);
1514
1515 VP_CLASSOF_IMPL(VPRecipeBase::VPInstructionSC)
1516
1517 VPInstruction *clone() override {
1519 }
1520
1522 Type *ResultTy = nullptr) {
1523 auto *New =
1524 new VPInstruction(Opcode, NewOperands, *this, *this, getDebugLoc(),
1525 Name, ResultTy, *this, GeneratesSingleScalar);
1526 if (getUnderlyingValue())
1527 New->setUnderlyingValue(getUnderlyingInstr());
1528 return New;
1529 }
1530
1531 unsigned getOpcode() const { return Opcode; }
1532
1533 /// Add \p Op as operand of this VPInstruction. Only supported for AnyOf,
1534 /// ComputeReductionResult, BuildVector, ExtractLane,
1535 /// ExtractLastActive, FirstActiveLane, LastActiveLane.
1536 void addOperand(VPValue *Op);
1537
1538 void execute(VPTransformState &State) override;
1539
1540 /// Return the cost of this VPInstruction.
1541 InstructionCost computeCost(ElementCount VF,
1542 VPCostContext &Ctx) const override;
1543
1544#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1545 /// Print the VPInstruction to dbgs() (for debugging).
1546 LLVM_DUMP_METHOD void dump() const;
1547#endif
1548
1549 bool hasResult() const { return !getScalarType()->isVoidTy(); }
1550
1551 /// Returns true if the VPInstruction has a mask operand.
1552 bool isMasked() const {
1553 unsigned NumOpsForOpcode = getNumOperandsForOpcode();
1554 // VPInstructions without a fixed number of operands cannot be masked.
1555 if (NumOpsForOpcode == -1u)
1556 return false;
1557 return NumOpsForOpcode + 1 == getNumOperands();
1558 }
1559
1560 /// Returns the number of operands, excluding the mask if the VPInstruction is
1561 /// masked.
1562 unsigned getNumOperandsWithoutMask() const {
1563 return getNumOperands() - isMasked();
1564 }
1565
1566 /// Add mask \p Mask to an unmasked VPInstruction, if it needs masking.
1567 void addMask(VPValue *Mask) {
1568 assert(!isMasked() && "recipe is already masked");
1569 if (alwaysUnmasked())
1570 return;
1571 assert(Mask->getScalarType()->isIntegerTy(1) &&
1572 "Mask must be an i1 (vector)");
1573 VPUser::addOperand(Mask);
1574 }
1575
1576 /// Returns the mask for the VPInstruction. Returns nullptr for unmasked
1577 /// VPInstructions.
1578 VPValue *getMask() const { return isMasked() ? getLastOperand() : nullptr; }
1579
1580 /// Returns an iterator range over the operands excluding the mask operand
1581 /// if present.
1588
1589 /// Returns true if the underlying opcode may read from or write to memory.
1590 bool opcodeMayReadOrWriteFromMemory() const;
1591
1592 /// Returns true if the recipe only uses the first lane of operand \p Op.
1593 bool usesFirstLaneOnly(const VPValue *Op) const override;
1594
1595 /// Returns true if the recipe only uses scalars of operand \p Op.
1596 bool usesScalars(const VPValue *Op) const override {
1599 }
1600
1601 /// Returns true if the recipe only uses the first part of all operands.
1602 bool usesFirstPartOnly() const override;
1603
1604 /// Returns true if this VPInstruction produces a scalar value from a vector,
1605 /// e.g. by performing a reduction or extracting a lane.
1606 bool isVectorToScalar() const;
1607
1608 /// Returns true if the recipe produces a single scalar value.
1609 bool doesGenerateSingleScalar() const { return GeneratesSingleScalar; }
1610
1611 /// Returns the symbolic name assigned to the VPInstruction.
1612 StringRef getName() const { return Name; }
1613
1614 /// Set the symbolic name for the VPInstruction.
1615 void setName(StringRef NewName) { Name = NewName.str(); }
1616
1617protected:
1618#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1619 /// Print the VPInstruction to \p O.
1620 void printRecipe(raw_ostream &O, const Twine &Indent,
1621 VPSlotTracker &SlotTracker) const override;
1622#endif
1623};
1624
1625/// Helper type to provide functions to access incoming values and blocks for
1626/// phi-like recipes.
1628protected:
1629 /// Return a VPRecipeBase* to the current object.
1630 virtual const VPRecipeBase *getAsRecipe() const = 0;
1631
1632public:
1633 virtual ~VPPhiAccessors() = default;
1634
1635 /// Returns the incoming VPValue with index \p Idx.
1636 VPValue *getIncomingValue(unsigned Idx) const {
1637 return getAsRecipe()->getOperand(Idx);
1638 }
1639
1640 /// Returns the incoming block with index \p Idx.
1641 const VPBasicBlock *getIncomingBlock(unsigned Idx) const;
1642
1643 /// Returns the incoming value for \p VPBB. \p VPBB must be an incoming block.
1645 getIncomingValueForBlock(const VPBasicBlock *VPBB) const;
1646
1647 /// Sets the incoming value for \p VPBB to \p V. \p VPBB must be an incoming
1648 /// block.
1649 void setIncomingValueForBlock(const VPBasicBlock *VPBB, VPValue *V) const;
1650
1651 /// Returns the number of incoming values, also number of incoming blocks.
1652 virtual unsigned getNumIncoming() const {
1653 return getAsRecipe()->getNumOperands();
1654 }
1655
1656 /// Returns an interator range over the incoming values.
1658 return make_range(getAsRecipe()->op_begin(),
1659 getAsRecipe()->op_begin() + getNumIncoming());
1660 }
1661
1663 detail::index_iterator, std::function<const VPBasicBlock *(size_t)>>>;
1664
1665 /// Returns an iterator range over the incoming blocks.
1667 std::function<const VPBasicBlock *(size_t)> GetBlock = [this](size_t Idx) {
1668 return getIncomingBlock(Idx);
1669 };
1670 return map_range(index_range(0, getNumIncoming()), GetBlock);
1671 }
1672
1673 /// Returns an iterator range over pairs of incoming values and corresponding
1674 /// incoming blocks.
1680
1681 /// Removes the incoming value for \p IncomingBlock, which must be a
1682 /// predecessor.
1683 void removeIncomingValueFor(VPBlockBase *IncomingBlock) const;
1684
1685 /// Append \p IncomingV as an incoming value to the phi-like recipe.
1686 void addIncoming(VPValue *IncomingV) {
1687 auto *R = const_cast<VPRecipeBase *>(getAsRecipe());
1688 assert((R->getNumOperands() == 0 ||
1689 IncomingV->getScalarType() == R->getOperand(0)->getScalarType()) &&
1690 "all incoming values must have the same type");
1691 R->addOperand(IncomingV);
1692 }
1693
1694#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1695 /// Print the recipe.
1697#endif
1698};
1699
1702 const Twine &Name = "", Type *ResultTy = nullptr)
1703 : VPInstruction(Instruction::PHI, Operands, Flags, {}, DL, Name,
1704 ResultTy) {}
1705
1706 static inline bool classof(const VPUser *U) {
1707 auto *VPI = dyn_cast<VPInstruction>(U);
1708 return VPI && VPI->getOpcode() == Instruction::PHI;
1709 }
1710
1711 static inline bool classof(const VPValue *V) {
1712 auto *VPI = dyn_cast<VPInstruction>(V);
1713 return VPI && VPI->getOpcode() == Instruction::PHI;
1714 }
1715
1716 static inline bool classof(const VPSingleDefRecipe *SDR) {
1717 auto *VPI = dyn_cast<VPInstruction>(SDR);
1718 return VPI && VPI->getOpcode() == Instruction::PHI;
1719 }
1720
1721 VPPhi *clone() override {
1722 auto *PhiR = new VPPhi(operands(), *this, getDebugLoc(), getName());
1723 PhiR->setUnderlyingValue(getUnderlyingValue());
1724 return PhiR;
1725 }
1726
1727 void execute(VPTransformState &State) override;
1728
1729protected:
1730#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1731 /// Print the recipe.
1732 void printRecipe(raw_ostream &O, const Twine &Indent,
1733 VPSlotTracker &SlotTracker) const override;
1734#endif
1735
1736 const VPRecipeBase *getAsRecipe() const override { return this; }
1737};
1738
1739/// A recipe to wrap on original IR instruction not to be modified during
1740/// execution, except for PHIs. PHIs are modeled via the VPIRPhi subclass.
1741/// Expect PHIs, VPIRInstructions cannot have any operands.
1743 Instruction &I;
1744
1745protected:
1746 /// VPIRInstruction::create() should be used to create VPIRInstructions, as
1747 /// subclasses may need to be created, e.g. VPIRPhi.
1749 : VPRecipeBase(VPRecipeBase::VPIRInstructionSC, {}), I(I) {}
1750
1751public:
1752 ~VPIRInstruction() override = default;
1753
1754 /// Create a new VPIRPhi for \p \I, if it is a PHINode, otherwise create a
1755 /// VPIRInstruction.
1757
1758 VP_CLASSOF_IMPL(VPRecipeBase::VPIRInstructionSC)
1759
1761 auto *R = create(I);
1762 for (auto *Op : operands())
1763 R->addOperand(Op);
1764 return R;
1765 }
1766
1767 void execute(VPTransformState &State) override;
1768
1769 /// Return the cost of this VPIRInstruction.
1771 computeCost(ElementCount VF, VPCostContext &Ctx) const override;
1772
1773 Instruction &getInstruction() const { return I; }
1774
1775 bool usesScalars(const VPValue *Op) const override {
1777 "Op must be an operand of the recipe");
1778 return true;
1779 }
1780
1781 /// Returns true if the recipe only uses the first part of all operands.
1782 bool usesFirstPartOnly() const override { return true; }
1783
1784 bool usesFirstLaneOnly(const VPValue *Op) const override {
1786 "Op must be an operand of the recipe");
1787 return true;
1788 }
1789
1790protected:
1791#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1792 /// Print the recipe.
1793 void printRecipe(raw_ostream &O, const Twine &Indent,
1794 VPSlotTracker &SlotTracker) const override;
1795#endif
1796};
1797
1798/// An overlay for VPIRInstructions wrapping PHI nodes enabling convenient use
1799/// cast/dyn_cast/isa and execute() implementation. A single VPValue operand is
1800/// allowed, and it is used to add a new incoming value for the single
1801/// predecessor VPBB.
1803 public VPPhiAccessors {
1805
1806 static inline bool classof(const VPRecipeBase *U) {
1807 auto *R = dyn_cast<VPIRInstruction>(U);
1808 return R && isa<PHINode>(R->getInstruction());
1809 }
1810
1811 static inline bool classof(const VPUser *U) {
1812 auto *R = dyn_cast<VPRecipeBase>(U);
1813 return R && classof(R);
1814 }
1815
1817
1818 void execute(VPTransformState &State) override;
1819
1820protected:
1821#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1822 /// Print the recipe.
1823 void printRecipe(raw_ostream &O, const Twine &Indent,
1824 VPSlotTracker &SlotTracker) const override;
1825#endif
1826
1827 const VPRecipeBase *getAsRecipe() const override { return this; }
1828};
1829
1830/// VPWidenRecipe is a recipe for producing a widened instruction using the
1831/// opcode and operands of the recipe. This recipe covers most of the
1832/// traditional vectorization cases where each recipe transforms into a
1833/// vectorized version of itself.
1835 public VPIRMetadata {
1836 unsigned Opcode;
1837
1838public:
1840 const VPIRFlags &Flags = {}, const VPIRMetadata &Metadata = {},
1841 DebugLoc DL = {})
1842 : VPWidenRecipe(I.getOpcode(), Operands, Flags, Metadata, DL) {
1843 setUnderlyingValue(&I);
1844 }
1845
1847 const VPIRFlags &Flags = {}, const VPIRMetadata &Metadata = {},
1848 DebugLoc DL = {})
1849 : VPRecipeWithIRFlags(VPRecipeBase::VPWidenSC, Operands,
1851 Flags, DL),
1852 VPIRMetadata(Metadata), Opcode(Opcode) {
1853 assert(flagsValidForOpcode(Opcode) &&
1854 "Set flags not supported for the provided opcode");
1855 assert(hasRequiredFlagsForOpcode(Opcode, getScalarType()) &&
1856 "Opcode requires specific flags to be set");
1857 }
1858
1859 ~VPWidenRecipe() override = default;
1860
1862
1864 if (auto *UV = getUnderlyingValue())
1865 return new VPWidenRecipe(*cast<Instruction>(UV), NewOperands, *this,
1866 *this, getDebugLoc());
1867 return new VPWidenRecipe(Opcode, NewOperands, *this, *this, getDebugLoc());
1868 }
1869
1870 VP_CLASSOF_IMPL(VPRecipeBase::VPWidenSC)
1871
1872 /// Produce a widened instruction using the opcode and operands of the recipe,
1873 /// processing State.VF elements.
1874 void execute(VPTransformState &State) override;
1875
1876 /// Return the cost of this VPWidenRecipe.
1877 InstructionCost computeCost(ElementCount VF,
1878 VPCostContext &Ctx) const override;
1879
1880 unsigned getOpcode() const { return Opcode; }
1881
1882protected:
1883#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1884 /// Print the recipe.
1885 void printRecipe(raw_ostream &O, const Twine &Indent,
1886 VPSlotTracker &SlotTracker) const override;
1887#endif
1888
1889 /// Returns true if the recipe only uses the first lane of operand \p Op.
1890 bool usesFirstLaneOnly(const VPValue *Op) const override {
1892 "Op must be an operand of the recipe");
1893 return Opcode == Instruction::Select && Op == getOperand(0) &&
1895 }
1896};
1897
1898/// VPWidenCastRecipe is a recipe to create vector cast instructions.
1899/// TODO: Merge with VPWidenRecipe now that type is associated to every
1900/// VPRecipeValue.
1902 public VPIRMetadata {
1903 /// Cast instruction opcode.
1904 Instruction::CastOps Opcode;
1905
1906public:
1908 CastInst *CI = nullptr, const VPIRFlags &Flags = {},
1909 const VPIRMetadata &Metadata = {},
1910 DebugLoc DL = DebugLoc::getUnknown())
1911 : VPRecipeWithIRFlags(VPRecipeBase::VPWidenCastSC, Op, ResultTy, Flags,
1912 DL),
1913 VPIRMetadata(Metadata), Opcode(Opcode) {
1914 assert(flagsValidForOpcode(Opcode) &&
1915 "Set flags not supported for the provided opcode");
1916 assert(hasRequiredFlagsForOpcode(Opcode, ResultTy) &&
1917 "Opcode requires specific flags to be set");
1918 setUnderlyingValue(CI);
1919 }
1920
1921 ~VPWidenCastRecipe() override = default;
1922
1924 return new VPWidenCastRecipe(Opcode, getOperand(0), getScalarType(),
1926 *this, *this, getDebugLoc());
1927 }
1928
1929 VP_CLASSOF_IMPL(VPRecipeBase::VPWidenCastSC)
1930
1931 /// Produce widened copies of the cast.
1932 void execute(VPTransformState &State) override;
1933
1934 /// Return the cost of this VPWidenCastRecipe.
1935 InstructionCost computeCost(ElementCount VF,
1936 VPCostContext &Ctx) const override;
1937
1938 Instruction::CastOps getOpcode() const { return Opcode; }
1939
1940protected:
1941#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1942 /// Print the recipe.
1943 void printRecipe(raw_ostream &O, const Twine &Indent,
1944 VPSlotTracker &SlotTracker) const override;
1945#endif
1946};
1947
1948/// A recipe for widening vector intrinsics.
1950 public VPIRMetadata {
1951 /// ID of the vector intrinsic to widen.
1952 Intrinsic::ID VectorIntrinsicID;
1953
1954 /// True if the intrinsic may read from memory.
1955 bool MayReadFromMemory;
1956
1957 /// True if the intrinsic may read write to memory.
1958 bool MayWriteToMemory;
1959
1960 /// True if the intrinsic may have side-effects.
1961 bool MayHaveSideEffects;
1962
1963protected:
1965 ArrayRef<VPValue *> CallArguments, Type *Ty,
1966 const VPIRFlags &Flags = {},
1967 const VPIRMetadata &MD = {},
1968 DebugLoc DL = DebugLoc::getUnknown())
1969 : VPRecipeWithIRFlags(SC, CallArguments, Ty, Flags, DL), VPIRMetadata(MD),
1970 VectorIntrinsicID(VectorIntrinsicID) {
1971 LLVMContext &Ctx = Ty->getContext();
1972 AttributeSet Attrs = Intrinsic::getFnAttributes(Ctx, VectorIntrinsicID);
1973 MemoryEffects ME = Attrs.getMemoryEffects();
1974 MayReadFromMemory = !ME.onlyWritesMemory();
1975 MayWriteToMemory = !ME.onlyReadsMemory();
1976 MayHaveSideEffects = MayWriteToMemory ||
1977 !Attrs.hasAttribute(Attribute::NoUnwind) ||
1978 !Attrs.hasAttribute(Attribute::WillReturn);
1979 }
1980
1981 /// Helper function to produce the widened intrinsic call.
1982 CallInst *createVectorCall(VPTransformState &State);
1983
1984public:
1986 ArrayRef<VPValue *> CallArguments, Type *Ty,
1987 const VPIRFlags &Flags = {},
1988 const VPIRMetadata &MD = {},
1989 DebugLoc DL = DebugLoc::getUnknown())
1990 : VPRecipeWithIRFlags(VPRecipeBase::VPWidenIntrinsicSC, CallArguments, Ty,
1991 Flags, DL),
1992 VPIRMetadata(MD), VectorIntrinsicID(VectorIntrinsicID),
1993 MayReadFromMemory(CI.mayReadFromMemory()),
1994 MayWriteToMemory(CI.mayWriteToMemory()),
1995 MayHaveSideEffects(CI.mayHaveSideEffects()) {
1996 setUnderlyingValue(&CI);
1997 }
1998
2000 ArrayRef<VPValue *> CallArguments, Type *Ty,
2001 const VPIRFlags &Flags = {},
2002 const VPIRMetadata &Metadata = {},
2003 DebugLoc DL = DebugLoc::getUnknown())
2004 : VPWidenIntrinsicRecipe(VPRecipeBase::VPWidenIntrinsicSC,
2005 VectorIntrinsicID, CallArguments, Ty, Flags,
2006 Metadata, DL) {}
2007
2008 ~VPWidenIntrinsicRecipe() override = default;
2009
2011 if (Value *CI = getUnderlyingValue())
2012 return new VPWidenIntrinsicRecipe(*cast<CallInst>(CI), VectorIntrinsicID,
2013 operands(), getScalarType(), *this,
2014 *this, getDebugLoc());
2015 return new VPWidenIntrinsicRecipe(VectorIntrinsicID, operands(),
2016 getScalarType(), *this, *this,
2017 getDebugLoc());
2018 }
2019
2020 static inline bool classof(const VPRecipeBase *R) {
2021 return R->getVPRecipeID() == VPRecipeBase::VPWidenIntrinsicSC ||
2022 R->getVPRecipeID() == VPRecipeBase::VPWidenMemIntrinsicSC;
2023 }
2024
2025 static inline bool classof(const VPUser *U) {
2026 auto *R = dyn_cast<VPRecipeBase>(U);
2027 return R && classof(R);
2028 }
2029
2030 static inline bool classof(const VPValue *V) {
2031 auto *R = V->getDefiningRecipe();
2032 return R && classof(R);
2033 }
2034
2035 static inline bool classof(const VPSingleDefRecipe *R) {
2036 return classof(static_cast<const VPRecipeBase *>(R));
2037 }
2038
2039 /// Produce a widened version of the vector intrinsic.
2040 void execute(VPTransformState &State) override;
2041
2042 /// Compute the cost of a vector intrinsic with \p ID and \p Operands.
2043 static InstructionCost computeCallCost(Intrinsic::ID ID,
2045 const VPRecipeWithIRFlags &R,
2046 ElementCount VF, VPCostContext &Ctx);
2047
2048 /// Return the cost of this vector intrinsic.
2049 InstructionCost computeCost(ElementCount VF,
2050 VPCostContext &Ctx) const override;
2051
2052 /// Return the ID of the intrinsic.
2053 Intrinsic::ID getVectorIntrinsicID() const { return VectorIntrinsicID; }
2054
2055 /// Return to name of the intrinsic as string.
2056 StringRef getIntrinsicName() const;
2057
2058 /// Returns true if the intrinsic may read from memory.
2059 bool mayReadFromMemory() const { return MayReadFromMemory; }
2060
2061 /// Returns true if the intrinsic may write to memory.
2062 bool mayWriteToMemory() const { return MayWriteToMemory; }
2063
2064 /// Returns true if the intrinsic may have side-effects.
2065 bool mayHaveSideEffects() const { return MayHaveSideEffects; }
2066
2067 bool usesFirstLaneOnly(const VPValue *Op) const override;
2068
2069protected:
2070#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2071 /// Print the recipe.
2072 void printRecipe(raw_ostream &O, const Twine &Indent,
2073 VPSlotTracker &SlotTracker) const override;
2074#endif
2075};
2076
2077/// A recipe for widening vector memory intrinsics.
2079 : public VPWidenIntrinsicRecipe {
2080 /// Alignment information for this memory access.
2081 Align Alignment;
2082
2083public:
2085 ArrayRef<VPValue *> CallArguments, Type *Ty,
2086 Align Alignment, const VPIRMetadata &MD = {},
2088 : VPWidenIntrinsicRecipe(VPRecipeBase::VPWidenMemIntrinsicSC,
2089 VectorIntrinsicID, CallArguments, Ty, {}, MD,
2090 DL),
2091 Alignment(Alignment) {
2092 assert(getVectorMemoryIntrinsicPointerArgIdx(VectorIntrinsicID) &&
2093 getVectorIntrinsicMaskArgIdx(VectorIntrinsicID) &&
2094 "Expected a masked vector load/store intrinsic");
2095 assert((!Ty->isVoidTy() ||
2096 getVectorStoreIntrinsicDataArgIdx(VectorIntrinsicID)) &&
2097 "Expected data argument for store intrinsic");
2098 }
2099
2100 ~VPWidenMemIntrinsicRecipe() override = default;
2101
2104 getScalarType(), Alignment, *this,
2105 getDebugLoc());
2106 }
2107
2108 VP_CLASSOF_IMPL(VPRecipeBase::VPWidenMemIntrinsicSC)
2109
2110 /// Produce a widened version of the vector memory intrinsic.
2111 void execute(VPTransformState &State) override;
2112
2113 /// Returns the address operand index of the VPWidenMemIntrinsicRecipe.
2114 unsigned getAddrOpIdx() const;
2115
2116 /// Returns the mask of a predicated VPWidenMemIntrinsicRecipe.
2117 VPValue *getMask() const;
2118
2119 /// Returns the data type of the memory access at \p VF.
2120 Type *getAccessType(ElementCount VF) const;
2121
2122 /// Helper function for computing the cost of vector memory intrinsic.
2123 static InstructionCost computeMemIntrinsicCost(Intrinsic::ID IID, Type *Ty,
2124 bool IsMasked, Align Alignment,
2125 VPCostContext &Ctx);
2126
2127 /// Return the cost of this vector memory intrinsic.
2128 InstructionCost computeCost(ElementCount VF,
2129 VPCostContext &Ctx) const override;
2130};
2131
2132/// A recipe for widening Call instructions using library calls.
2134 public VPIRMetadata,
2135 public VPIRAttributes {
2136 /// Variant stores a pointer to the chosen function. There is a 1:1 mapping
2137 /// between a given VF and the chosen vectorized variant, so there will be a
2138 /// different VPlan for each VF with a valid variant.
2139 Function *Variant;
2140
2141public:
2143 ArrayRef<VPValue *> CallArguments,
2144 const VPIRFlags &Flags = {},
2145 const VPIRMetadata &Metadata = {},
2146 const VPIRAttributes &Attrs = {}, DebugLoc DL = {})
2147 : VPRecipeWithIRFlags(VPRecipeBase::VPWidenCallSC, CallArguments,
2148 toScalarizedTy(Variant->getReturnType()), Flags,
2149 DL),
2150 VPIRMetadata(Metadata), VPIRAttributes(Attrs), Variant(Variant) {
2151 setUnderlyingValue(UV);
2152 assert(isa<Function>(getLastOperand()->getLiveInIRValue()) &&
2153 "last operand must be the called function");
2154 assert(cast<Function>(CallArguments.back()->getLiveInIRValue())
2155 ->getReturnType() == getScalarType() &&
2156 "Scalar type must match return type of called scalar function");
2157 }
2158
2159 ~VPWidenCallRecipe() override = default;
2160
2162 return new VPWidenCallRecipe(getUnderlyingValue(), Variant, operands(),
2163 *this, *this, *this, getDebugLoc());
2164 }
2165
2166 VP_CLASSOF_IMPL(VPRecipeBase::VPWidenCallSC)
2167
2168 /// Produce a widened version of the call instruction.
2169 void execute(VPTransformState &State) override;
2170
2171 /// Return the cost of this VPWidenCallRecipe.
2172 InstructionCost computeCost(ElementCount VF,
2173 VPCostContext &Ctx) const override;
2174
2175 /// Return the cost of widening a call using the vector function \p Variant.
2176 static InstructionCost computeCallCost(Function *Variant, VPCostContext &Ctx);
2177
2181
2184
2185 /// Returns true if the recipe only uses the first lane of operand \p Op.
2186 bool usesFirstLaneOnly(const VPValue *Op) const override;
2187
2188protected:
2189#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2190 /// Print the recipe.
2191 void printRecipe(raw_ostream &O, const Twine &Indent,
2192 VPSlotTracker &SlotTracker) const override;
2193#endif
2194};
2195
2196/// A recipe representing a sequence of load -> update -> store as part of
2197/// a histogram operation. This means there may be aliasing between vector
2198/// lanes, which is handled by the llvm.experimental.vector.histogram family
2199/// of intrinsics. Supported update operations are: add, sub, uadd.sat, umax,
2200/// and umin, where the other term is loop-invariant.
2202 /// The update operation kind for this histogram.
2203 HistogramUpdateKind UpdateKind;
2204
2205public:
2207 ArrayRef<VPValue *> Operands,
2208 const VPIRMetadata &Metadata = {},
2210 : VPRecipeBase(VPRecipeBase::VPHistogramSC, Operands, DL),
2211 VPIRMetadata(Metadata), UpdateKind(UpdateKind) {}
2212
2213 ~VPHistogramRecipe() override = default;
2214
2216 return new VPHistogramRecipe(UpdateKind, operands(), *this, getDebugLoc());
2217 }
2218
2219 VP_CLASSOF_IMPL(VPRecipeBase::VPHistogramSC);
2220
2221 /// Produce a vectorized histogram operation.
2222 void execute(VPTransformState &State) override;
2223
2224 /// Return the cost of this VPHistogramRecipe.
2226 VPCostContext &Ctx) const override;
2227
2228 /// Return the mask operand if one was provided, or a null pointer if all
2229 /// lanes should be executed unconditionally.
2230 VPValue *getMask() const {
2231 return getNumOperands() == 3 ? getOperand(2) : nullptr;
2232 }
2233
2234 /// Returns true if the recipe only uses the first lane of operand \p Op.
2235 bool usesFirstLaneOnly(const VPValue *Op) const override {
2237 "Op must be an operand of the recipe");
2238 return Op == getOperand(1);
2239 }
2240
2241private:
2242 /// Return the histogram intrinsic ID for this recipe's update kind.
2243 Intrinsic::ID getHistogramIntrinsicID() const;
2244
2245 /// Return true if the increment should be negated before passing to the
2246 /// histogram intrinsic (only for Sub).
2247 bool mustNegateIncrement() const {
2248 return UpdateKind == HistogramUpdateKind::Sub;
2249 }
2250
2251protected:
2252#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2253 /// Print the recipe
2254 void printRecipe(raw_ostream &O, const Twine &Indent,
2255 VPSlotTracker &SlotTracker) const override;
2256#endif
2257};
2258
2259/// A recipe for handling GEP instructions.
2261 Type *SourceElementTy;
2262
2263public:
2265 const VPIRFlags &Flags = {},
2267 GetElementPtrInst *UV = nullptr)
2268 : VPRecipeWithIRFlags(VPRecipeBase::VPWidenGEPSC, Operands,
2269 Operands[0]->getScalarType(), Flags, DL),
2270 SourceElementTy(SourceElementTy) {
2271 if (UV) {
2272 setUnderlyingValue(UV);
2275 assert(Metadata.empty() && "unexpected metadata on GEP");
2276 }
2277 }
2278
2279 ~VPWidenGEPRecipe() override = default;
2280
2286
2287 VP_CLASSOF_IMPL(VPRecipeBase::VPWidenGEPSC)
2288
2289 /// This recipe generates a GEP instruction.
2290 unsigned getOpcode() const { return Instruction::GetElementPtr; }
2291
2292 /// Generate the gep nodes.
2293 void execute(VPTransformState &State) override;
2294
2295 Type *getSourceElementType() const { return SourceElementTy; }
2296
2297 /// Return the cost of this VPWidenGEPRecipe.
2299 VPCostContext &Ctx) const override {
2300 // TODO: Compute accurate cost after retiring the legacy cost model.
2301 return 0;
2302 }
2303
2304 /// Returns true if the recipe only uses the first lane of operand \p Op.
2305 bool usesFirstLaneOnly(const VPValue *Op) const override;
2306
2307protected:
2308#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2309 /// Print the recipe.
2310 void printRecipe(raw_ostream &O, const Twine &Indent,
2311 VPSlotTracker &SlotTracker) const override;
2312#endif
2313};
2314
2315/// A recipe to compute a pointer to the last element of each part of a widened
2316/// memory access for widened memory accesses of SourceElementTy. Used for
2317/// VPWidenMemoryRecipes or VPInterleaveRecipes that are reversed. An extra
2318/// Offset operand is added by convertToConcreteRecipes when UF = 1, and by the
2319/// unroller otherwise.
2321 Type *SourceElementTy;
2322
2323 /// The constant stride of the pointer computed by this recipe, expressed in
2324 /// units of SourceElementTy.
2325 int64_t Stride;
2326
2327public:
2328 VPVectorEndPointerRecipe(VPValue *Ptr, VPValue *VF, Type *SourceElementTy,
2329 int64_t Stride, GEPNoWrapFlags GEPFlags, DebugLoc DL)
2330 : VPRecipeWithIRFlags(VPRecipeBase::VPVectorEndPointerSC, {Ptr, VF},
2331 Ptr->getScalarType(), GEPFlags, DL),
2332 SourceElementTy(SourceElementTy), Stride(Stride) {
2333 assert(Stride < 0 && "Stride must be negative");
2334 }
2335
2336 VP_CLASSOF_IMPL(VPRecipeBase::VPVectorEndPointerSC)
2337
2338 Type *getSourceElementType() const { return SourceElementTy; }
2339 int64_t getStride() const { return Stride; }
2340 VPValue *getPointer() const { return getOperand(0); }
2341 VPValue *getVFValue() const { return getOperand(1); }
2343 return getNumOperands() == 3 ? getOperand(2) : nullptr;
2344 }
2345
2346 /// Adds the offset operand to the recipe.
2347 /// Offset = Stride * (VF - 1) + Part * Stride * VF.
2348 void materializeOffset(unsigned Part = 0);
2349
2350 /// Append \p Offset as the offset operand. The offset is an integer index
2351 /// expressed in units of SourceElementTy.
2353 assert(Offset->getScalarType()->isIntegerTy() &&
2354 "offset must be an integer index");
2356 }
2357
2358 void execute(VPTransformState &State) override;
2359
2360 bool usesFirstLaneOnly(const VPValue *Op) const override {
2362 "Op must be an operand of the recipe");
2363 return true;
2364 }
2365
2366 /// Return the cost of this VPVectorPointerRecipe.
2368 VPCostContext &Ctx) const override {
2369 // TODO: Compute accurate cost after retiring the legacy cost model.
2370 return 0;
2371 }
2372
2373 /// Returns true if the recipe only uses the first part of all operands.
2374 bool usesFirstPartOnly() const override {
2375 assert(getNumOperands() <= 2 && "must have at most two operands");
2376 return true;
2377 }
2378
2380 auto *VEPR = new VPVectorEndPointerRecipe(
2383 if (auto *Offset = getOffset())
2384 VEPR->addOffset(Offset);
2385 return VEPR;
2386 }
2387
2388protected:
2389#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2390 /// Print the recipe.
2391 void printRecipe(raw_ostream &O, const Twine &Indent,
2392 VPSlotTracker &SlotTracker) const override;
2393#endif
2394};
2395
2396/// A recipe to compute the pointers for widened memory accesses of \p
2397/// SourceElementTy, with the \p Stride expressed in units of \p
2398/// SourceElementTy. Unrolling adds an extra \p VFxPart operand for unrolled
2399/// parts > 0 and it produces `GEP SourceElementTy Ptr, VFxPart * Stride`.
2401 Type *SourceElementTy;
2402
2403public:
2404 VPVectorPointerRecipe(VPValue *Ptr, Type *SourceElementTy, VPValue *Stride,
2405 GEPNoWrapFlags GEPFlags, DebugLoc DL)
2406 : VPRecipeWithIRFlags(VPRecipeBase::VPVectorPointerSC,
2407 ArrayRef<VPValue *>({Ptr, Stride}),
2408 Ptr->getScalarType(), GEPFlags, DL),
2409 SourceElementTy(SourceElementTy) {}
2410
2411 VP_CLASSOF_IMPL(VPRecipeBase::VPVectorPointerSC)
2412
2413 VPValue *getStride() const { return getOperand(1); }
2414
2416 return getNumOperands() > 2 ? getOperand(2) : nullptr;
2417 }
2418
2419 /// Add the per-part offset (VFxPart) used for unrolled parts > 0.
2420 void addPerPartOffset(VPValue *VFxPart) {
2421 assert(VFxPart->getScalarType()->isIntegerTy() &&
2422 "per-part offset must be an integer index");
2423 VPUser::addOperand(VFxPart);
2424 }
2425
2426 void execute(VPTransformState &State) override;
2427
2428 Type *getSourceElementType() const { return SourceElementTy; }
2429
2430 bool usesFirstLaneOnly(const VPValue *Op) const override {
2432 "Op must be an operand of the recipe");
2433 return true;
2434 }
2435
2436 /// Returns true if the recipe only uses the first part of all operands.
2437 bool usesFirstPartOnly() const override {
2438 assert(getNumOperands() <= 2 && "must have at most two operands");
2439 return true;
2440 }
2441
2443 auto *Clone =
2444 new VPVectorPointerRecipe(getOperand(0), SourceElementTy, getStride(),
2446 if (auto *VFxPart = getVFxPart())
2447 Clone->addPerPartOffset(VFxPart);
2448 return Clone;
2449 }
2450
2451 /// Return the cost of this VPHeaderPHIRecipe.
2453 VPCostContext &Ctx) const override {
2454 // TODO: Compute accurate cost after retiring the legacy cost model.
2455 return 0;
2456 }
2457
2458protected:
2459#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2460 /// Print the recipe.
2461 void printRecipe(raw_ostream &O, const Twine &Indent,
2462 VPSlotTracker &SlotTracker) const override;
2463#endif
2464};
2465
2466/// A pure virtual base class for all recipes modeling header phis, including
2467/// phis for first order recurrences, pointer inductions and reductions. The
2468/// start value is the first operand of the recipe and the incoming value from
2469/// the backedge is the second operand.
2470///
2471/// Inductions are modeled using the following sub-classes:
2472/// * VPWidenIntOrFpInductionRecipe: Generates vector values for integer and
2473/// floating point inductions with arbitrary start and step values. Produces
2474/// a vector PHI per-part.
2475/// * VPWidenPointerInductionRecipe: Generate vector and scalar values for a
2476/// pointer induction. Produces either a vector PHI per-part or scalar values
2477/// per-lane based on the canonical induction.
2478/// * VPFirstOrderRecurrencePHIRecipe
2479/// * VPReductionPHIRecipe
2480/// * VPActiveLaneMaskPHIRecipe
2481/// * VPEVLBasedIVPHIRecipe
2482///
2483/// Note that the canonical IV is modeled as a VPRegionValue associated with
2484/// its loop region.
2486 public VPPhiAccessors {
2487protected:
2488 VPHeaderPHIRecipe(VPRecipeTy VPRecipeID, Instruction *UnderlyingInstr,
2489 VPValue *Start, Type *ResultTy,
2491 : VPSingleDefRecipe(VPRecipeID, Start, ResultTy, UnderlyingInstr, DL) {}
2492
2493 const VPRecipeBase *getAsRecipe() const override { return this; }
2494
2495public:
2496 ~VPHeaderPHIRecipe() override = default;
2497
2498 /// Method to support type inquiry through isa, cast, and dyn_cast.
2499 static inline bool classof(const VPRecipeBase *R) {
2500 return R->getVPRecipeID() >= VPRecipeBase::VPFirstHeaderPHISC &&
2501 R->getVPRecipeID() <= VPRecipeBase::VPLastHeaderPHISC;
2502 }
2503 static inline bool classof(const VPValue *V) {
2504 return isa<VPHeaderPHIRecipe>(V->getDefiningRecipe());
2505 }
2506 static inline bool classof(const VPSingleDefRecipe *R) {
2507 return isa<VPHeaderPHIRecipe>(static_cast<const VPRecipeBase *>(R));
2508 }
2509
2510 /// Generate the phi nodes.
2511 void execute(VPTransformState &State) override = 0;
2512
2513 /// Return the cost of this header phi recipe.
2515 VPCostContext &Ctx) const override;
2516
2517 /// Returns the start value of the phi, if one is set.
2519 return getNumOperands() == 0 ? nullptr : getOperand(0);
2520 }
2522 return getNumOperands() == 0 ? nullptr : getOperand(0);
2523 }
2524
2525 /// Update the start value of the recipe.
2527
2528 /// Returns the incoming value from the loop backedge.
2529 virtual VPValue *getBackedgeValue() { return getOperand(1); }
2530
2531 /// Update the incoming value from the loop backedge.
2533
2534 /// Add \p V as the incoming value from the loop backedge.
2536 assert(getNumOperands() == 1 &&
2537 "backedge value must be appended right after construction");
2538 assert(V->getScalarType() == getScalarType() &&
2539 "backedge value must have the same type as the start value");
2541 }
2542
2543protected:
2544#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2545 /// Print the recipe.
2546 void printRecipe(raw_ostream &O, const Twine &Indent,
2547 VPSlotTracker &SlotTracker) const override = 0;
2548#endif
2549};
2550
2551/// Base class for widened induction (VPWidenIntOrFpInductionRecipe and
2552/// VPWidenPointerInductionRecipe), providing shared functionality, including
2553/// retrieving the step value, induction descriptor and original phi node.
2555 InductionDescriptor IndDesc;
2556
2557public:
2559 VPValue *Step, const InductionDescriptor &IndDesc,
2560 Type *ResultTy, DebugLoc DL)
2561 : VPHeaderPHIRecipe(Kind, IV, Start, ResultTy, DL), IndDesc(IndDesc) {
2562 addOperand(Step);
2563 }
2564
2565 /// After unrolling, append the splat-VF step (`VF * step`) and the value of
2566 /// the induction at the last unrolled part.
2567 void addUnrolledPartOperands(VPValue *SplatVFStep, VPValue *LastPart) {
2568 assert(LastPart->getScalarType() == getScalarType() &&
2569 "last-part value must match the induction recipe's scalar type");
2571 ? SplatVFStep->getScalarType()->isIntegerTy()
2572 : SplatVFStep->getScalarType() == getScalarType()) &&
2573 "splat-step must match the induction type for non-pointer "
2574 "inductions, or be an integer index for pointer inductions");
2575 VPUser::addOperand(SplatVFStep);
2576 VPUser::addOperand(LastPart);
2577 }
2578
2579 static inline bool classof(const VPRecipeBase *R) {
2580 return R->getVPRecipeID() == VPRecipeBase::VPWidenIntOrFpInductionSC ||
2581 R->getVPRecipeID() == VPRecipeBase::VPWidenPointerInductionSC;
2582 }
2583
2584 static inline bool classof(const VPValue *V) {
2585 auto *R = V->getDefiningRecipe();
2586 return R && classof(R);
2587 }
2588
2589 static inline bool classof(const VPSingleDefRecipe *R) {
2590 return classof(static_cast<const VPRecipeBase *>(R));
2591 }
2592
2593 void execute(VPTransformState &State) override = 0;
2594
2595 /// Returns the step value of the induction.
2597 const VPValue *getStepValue() const { return getOperand(1); }
2598
2600 const VPValue *getVFValue() const { return getOperand(2); }
2601
2602 /// Returns the number of incoming values, also number of incoming blocks.
2603 /// Note that at the moment, VPWidenPointerInductionRecipe only has a single
2604 /// incoming value, its start value.
2605 unsigned getNumIncoming() const override { return 1; }
2606
2607 /// Returns the underlying PHINode if one exists, or null otherwise.
2611
2612 /// Returns the induction descriptor for the recipe.
2613 const InductionDescriptor &getInductionDescriptor() const { return IndDesc; }
2614
2615 /// Returns the SCEV predicates associated with this induction.
2617 return IndDesc.getNoWrapPredicates();
2618 }
2619
2621 // TODO: All operands of base recipe must exist and be at same index in
2622 // derived recipe.
2624 "VPWidenIntOrFpInductionRecipe generates its own backedge value");
2625 }
2626
2627 /// Returns true if the recipe only uses the first lane of operand \p Op.
2628 bool usesFirstLaneOnly(const VPValue *Op) const override {
2630 "Op must be an operand of the recipe");
2631 // The recipe creates its own wide start value, so it only requests the
2632 // first lane of the operand.
2633 // TODO: Remove once creating the start value is modeled separately.
2634 return Op == getStartValue() || Op == getStepValue();
2635 }
2636};
2637
2638/// A recipe for handling phi nodes of integer and floating-point inductions,
2639/// producing their vector values. This is an abstract recipe and must be
2640/// converted to concrete recipes before executing.
2642 public VPIRFlags {
2643 // If this recipe is unrolled it will have 2 additional operands.
2644 bool isUnrolled() const { return getNumOperands() == 5; }
2645
2646public:
2648 VPValue *VF, const InductionDescriptor &IndDesc,
2649 const VPIRFlags &Flags, DebugLoc DL)
2650 : VPWidenInductionRecipe(VPRecipeBase::VPWidenIntOrFpInductionSC, IV,
2651 Start, Step, IndDesc, Start->getScalarType(),
2652 DL),
2653 VPIRFlags(Flags) {
2654 addOperand(VF);
2655 }
2656
2658 VPValue *VF, const InductionDescriptor &IndDesc,
2659 Type *ResultTy, const VPIRFlags &Flags,
2660 DebugLoc DL)
2661 : VPWidenInductionRecipe(VPRecipeBase::VPWidenIntOrFpInductionSC, IV,
2662 Start, Step, IndDesc, ResultTy, DL),
2663 VPIRFlags(Flags) {
2664 addOperand(VF);
2665 }
2666
2668
2674
2675 VP_CLASSOF_IMPL(VPRecipeBase::VPWidenIntOrFpInductionSC)
2676
2677 void execute(VPTransformState &State) override {
2678 llvm_unreachable("cannot execute this recipe, should be expanded via "
2679 "expandVPWidenIntOrFpInductionRecipe");
2680 }
2681
2682 /// If the recipe has been unrolled, return the VPValue for the induction
2683 /// increment, otherwise return null.
2685 return isUnrolled() ? getOperand(getNumOperands() - 2) : nullptr;
2686 }
2687
2688 /// Returns the number of incoming values, also number of incoming blocks.
2689 /// Note that at the moment, VPWidenIntOrFpInductionRecipes only have a single
2690 /// incoming value, its start value.
2691 unsigned getNumIncoming() const override { return 1; }
2692
2693 /// Returns true if this induction is evaluated in a narrower type than the
2694 /// start value.
2700
2701 /// Return the cost of this VPWidenIntOrFpInductionRecipe.
2703 VPCostContext &Ctx) const override;
2704
2705 /// Returns true if the induction is canonical, i.e. starting at 0 and
2706 /// incremented by UF * VF (= the original IV is incremented by 1) and has the
2707 /// same type as the canonical induction.
2708 bool isCanonical() const;
2709
2710 /// Returns the VPValue representing the value of this induction at
2711 /// the last unrolled part, if it exists. Returns itself if unrolling did not
2712 /// take place.
2714 return isUnrolled() ? getLastOperand() : this;
2715 }
2716
2717protected:
2718#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2719 /// Print the recipe.
2720 void printRecipe(raw_ostream &O, const Twine &Indent,
2721 VPSlotTracker &SlotTracker) const override;
2722#endif
2723};
2724
2726public:
2727 /// Create a new VPWidenPointerInductionRecipe for \p Phi with start value \p
2728 /// Start and the number of elements unrolled \p NumUnrolledElems, typically
2729 /// VF*UF.
2731 VPValue *NumUnrolledElems,
2732 const InductionDescriptor &IndDesc, DebugLoc DL)
2733 : VPWidenInductionRecipe(VPRecipeBase::VPWidenPointerInductionSC, Phi,
2734 Start, Step, IndDesc, Start->getScalarType(),
2735 DL) {
2736 addOperand(NumUnrolledElems);
2737 }
2738
2740
2746
2747 VP_CLASSOF_IMPL(VPRecipeBase::VPWidenPointerInductionSC)
2748
2749 /// Generate vector values for the pointer induction.
2750 void execute(VPTransformState &State) override {
2751 llvm_unreachable("cannot execute this recipe, should be expanded via "
2752 "expandVPWidenPointerInduction");
2753 };
2754
2755 /// Returns true if only scalar values will be generated.
2757
2758 /// Return the cost of this VPWidenPointerInductionRecipe.
2760 VPCostContext &Ctx) const override;
2761
2762protected:
2763#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2764 /// Print the recipe.
2765 void printRecipe(raw_ostream &O, const Twine &Indent,
2766 VPSlotTracker &SlotTracker) const override;
2767#endif
2768};
2769
2770/// A recipe for widened phis. Incoming values are operands of the recipe and
2771/// their operand index corresponds to the incoming predecessor block. If the
2772/// recipe is placed in an entry block to a (non-replicate) region, it must have
2773/// exactly 2 incoming values, the first from the predecessor of the region and
2774/// the second from the exiting block of the region.
2776 public VPPhiAccessors {
2777 /// Name to use for the generated IR instruction for the widened phi.
2778 std::string Name;
2779
2780public:
2781 /// Create a new VPWidenPHIRecipe with incoming values \p IncomingValues,
2782 /// debug location \p DL and \p Name.
2784 DebugLoc DL = DebugLoc::getUnknown(), const Twine &Name = "")
2785 : VPSingleDefRecipe(VPRecipeBase::VPWidenPHISC, IncomingValues,
2786 IncomingValues[0]->getScalarType(),
2787 /*UV=*/nullptr, DL),
2788 Name(Name.str()) {
2789 assert(all_of(IncomingValues,
2790 [this](VPValue *VPV) {
2791 return VPV->getScalarType() == getScalarType();
2792 }) &&
2793 "all incoming values must have the same type");
2794 }
2795
2797 return new VPWidenPHIRecipe(operands(), getDebugLoc(), Name);
2798 }
2799
2800 ~VPWidenPHIRecipe() override = default;
2801
2802 /// This recipe generates a PHI.
2803 unsigned getOpcode() const { return Instruction::PHI; }
2804
2805 VP_CLASSOF_IMPL(VPRecipeBase::VPWidenPHISC)
2806
2807 /// Generate the phi/select nodes.
2808 void execute(VPTransformState &State) override;
2809
2810 /// Return the cost of this VPWidenPHIRecipe.
2811 InstructionCost computeCost(ElementCount VF,
2812 VPCostContext &Ctx) const override;
2813
2814protected:
2815#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2816 /// Print the recipe.
2817 void printRecipe(raw_ostream &O, const Twine &Indent,
2818 VPSlotTracker &SlotTracker) const override;
2819#endif
2820
2821 const VPRecipeBase *getAsRecipe() const override { return this; }
2822};
2823
2824/// A recipe for handling first-order recurrence phis. The start value is the
2825/// first operand of the recipe and the incoming value from the backedge is the
2826/// second operand.
2829 VPValue &BackedgeValue)
2830 : VPHeaderPHIRecipe(VPRecipeBase::VPFirstOrderRecurrencePHISC, Phi,
2831 &Start, Start.getScalarType()) {
2832 addOperand(&BackedgeValue);
2833 }
2834
2835 VP_CLASSOF_IMPL(VPRecipeBase::VPFirstOrderRecurrencePHISC)
2836
2841
2842 void execute(VPTransformState &State) override;
2843
2844 /// Return the cost of this first-order recurrence phi recipe.
2846 VPCostContext &Ctx) const override;
2847
2848 /// Returns true if the recipe only uses the first lane of operand \p Op.
2849 bool usesFirstLaneOnly(const VPValue *Op) const override {
2851 "Op must be an operand of the recipe");
2852 return Op == getStartValue();
2853 }
2854
2855protected:
2856#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2857 /// Print the recipe.
2858 void printRecipe(raw_ostream &O, const Twine &Indent,
2859 VPSlotTracker &SlotTracker) const override;
2860#endif
2861};
2862
2863/// Possible variants of a reduction.
2864
2865/// This reduction is ordered and in-loop.
2866struct RdxOrdered {};
2867/// This reduction is in-loop.
2868struct RdxInLoop {};
2869/// This reduction is unordered with the partial result scaled down by some
2870/// factor.
2873};
2874using ReductionStyle = std::variant<RdxOrdered, RdxInLoop, RdxUnordered>;
2875
2876inline ReductionStyle getReductionStyle(bool InLoop, bool Ordered,
2877 unsigned ScaleFactor) {
2878 assert((!Ordered || InLoop) && "Ordered implies in-loop");
2879 if (Ordered)
2880 return RdxOrdered{};
2881 if (InLoop)
2882 return RdxInLoop{};
2883 return RdxUnordered{/*VFScaleFactor=*/ScaleFactor};
2884}
2885
2886/// A recipe for handling reduction phis. The start value is the first operand
2887/// of the recipe and the incoming value from the backedge is the second
2888/// operand.
2890 /// The recurrence kind of the reduction.
2891 const RecurKind Kind;
2892
2893 ReductionStyle Style;
2894
2895 /// The phi is part of a multi-use reduction (e.g., used in FindIV
2896 /// patterns for argmin/argmax).
2897 /// TODO: Also support cases where the phi itself has a single use, but its
2898 /// compare has multiple uses.
2899 bool HasUsesOutsideReductionChain;
2900
2901 /// Temporary flag indicating that the FindIV reduction expression has been
2902 /// sunk. While this is true, epilogue vectorization is disabled to avoid
2903 /// applying the sunk expression twice (once in the main vector loop and again
2904 /// in the epilogue), which can produce incorrect results by applying the sunk
2905 /// operation twice.
2906 /// TODO: Remove this flag once epilogue vectorization properly supports
2907 /// sunk FindIV expressions.
2908 bool ExpressionSunk = false;
2909
2910public:
2911 /// Create a new VPReductionPHIRecipe for the reduction \p Phi.
2913 VPValue &BackedgeValue, ReductionStyle Style,
2914 const VPIRFlags &Flags,
2915 bool HasUsesOutsideReductionChain = false)
2916 : VPHeaderPHIRecipe(VPRecipeBase::VPReductionPHISC, Phi, &Start,
2917 Start.getScalarType()),
2918 VPIRFlags(Flags), Kind(Kind), Style(Style),
2919 HasUsesOutsideReductionChain(HasUsesOutsideReductionChain) {
2920 addOperand(&BackedgeValue);
2921 }
2922
2923 ~VPReductionPHIRecipe() override = default;
2924
2926 VPValue *BackedgeValue) {
2927 auto *Clone = new VPReductionPHIRecipe(
2929 *Start, *BackedgeValue, Style, *this, HasUsesOutsideReductionChain);
2930 Clone->ExpressionSunk = ExpressionSunk;
2931 return Clone;
2932 }
2933
2937
2938 VP_CLASSOF_IMPL(VPRecipeBase::VPReductionPHISC)
2939
2940 /// Generate the phi/select nodes.
2941 void execute(VPTransformState &State) override;
2942
2943 /// Get the factor that the VF of this recipe's output should be scaled by, or
2944 /// 1 if it isn't scaled.
2945 unsigned getVFScaleFactor() const {
2946 auto *Partial = std::get_if<RdxUnordered>(&Style);
2947 return Partial ? Partial->VFScaleFactor : 1;
2948 }
2949
2950 /// Set the VFScaleFactor for this reduction phi. Can only be set to a factor
2951 /// > 1.
2952 void setVFScaleFactor(unsigned ScaleFactor) {
2953 assert(ScaleFactor > 1 && "must set to scale factor > 1");
2954 Style = RdxUnordered{ScaleFactor};
2955 }
2956
2957 /// Returns the recurrence kind of the reduction.
2958 RecurKind getRecurrenceKind() const { return Kind; }
2959
2960 /// Returns true, if the phi is part of an ordered reduction.
2961 bool isOrdered() const { return std::holds_alternative<RdxOrdered>(Style); }
2962
2963 /// Returns true if the phi is part of an in-loop reduction.
2964 bool isInLoop() const {
2965 return std::holds_alternative<RdxInLoop>(Style) ||
2966 std::holds_alternative<RdxOrdered>(Style);
2967 }
2968
2969 /// Returns true, if the phi is part of a multi-use reduction.
2971 return HasUsesOutsideReductionChain;
2972 }
2973
2974 void setExpressionSunk() { ExpressionSunk = true; }
2975
2976 bool isExpressionSunk() const { return ExpressionSunk; }
2977
2978 /// Returns true if the recipe only uses the first lane of operand \p Op.
2979 bool usesFirstLaneOnly(const VPValue *Op) const override {
2981 "Op must be an operand of the recipe");
2982 return isOrdered() || isInLoop();
2983 }
2984
2985protected:
2986#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2987 /// Print the recipe.
2988 void printRecipe(raw_ostream &O, const Twine &Indent,
2989 VPSlotTracker &SlotTracker) const override;
2990#endif
2991};
2992
2993/// A recipe for handling scalar conditional induction PHIs. The start value is
2994/// the first operand of the recipe and the incoming value from the backedge is
2995/// the second operand.
2997 const SCEV *StepSCEV = nullptr;
2998
2999public:
3001 VPValue &BackedgeValue, const SCEV *StepSCEV)
3002 : VPHeaderPHIRecipe(VPRecipeBase::VPConditionalInductionPHISC, &Phi,
3003 &Start, Start.getScalarType()),
3004 StepSCEV(StepSCEV) {
3005 addOperand(&BackedgeValue);
3006 }
3007
3009
3010 /// Returns the underlying PHINode.
3012
3013 /// Returns the conditional induction step SCEV expression.
3014 const SCEV *getStepSCEV() const { return StepSCEV; }
3015
3020
3021 VP_CLASSOF_IMPL(VPRecipeBase::VPConditionalInductionPHISC)
3022
3024 return R->getVPRecipeID() == VPRecipeBase::VPConditionalInductionPHISC;
3025 }
3026
3027 void execute(VPTransformState &) override {
3028 llvm_unreachable("must be expanded before final execute");
3029 }
3030
3032 VPCostContext &Ctx) const override;
3033
3034#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3035 /// Print the recipe.
3036 void printRecipe(raw_ostream &O, const Twine &Indent,
3037 VPSlotTracker &SlotTracker) const override;
3038#endif
3039
3040 /// Returns true if the recipe only uses the first lane of operand \p Op.
3041 bool usesFirstLaneOnly(const VPValue *Op) const override {
3043 "Op must be an operand of the recipe");
3044 return true;
3045 }
3046};
3047
3048/// A recipe for vectorizing a phi-node as a sequence of mask-based select
3049/// instructions.
3051public:
3052 /// The blend operation is a User of the incoming values and of their
3053 /// respective masks, ordered [I0, M0, I1, M1, I2, M2, ...]. Note that M0 can
3054 /// be omitted (implied by passing an odd number of operands) in which case
3055 /// all other incoming values are merged into it.
3057 const VPIRFlags &Flags, DebugLoc DL)
3059 Operands[0]->getScalarType(), Flags, DL) {
3060 assert(Operands.size() >= 2 && "Expected at least two operands!");
3062 [this](unsigned I) {
3063 return getIncomingValue(I)->getScalarType() ==
3064 getScalarType();
3065 }) &&
3066 "all incoming values must have the same type");
3068 [this](unsigned I) {
3069 return getMask(I)->getScalarType()->isIntegerTy(1);
3070 }) &&
3071 "masks must be a bool");
3072 assert(hasRequiredFlagsForOpcode(Instruction::PHI, getScalarType()) &&
3073 "blends require the flags of the phi they replace");
3074 setUnderlyingValue(Phi);
3075 }
3076
3078
3081 NewOperands, *this, getDebugLoc());
3082 }
3083
3084 VP_CLASSOF_IMPL(VPRecipeBase::VPBlendSC)
3085
3086 /// A normalized blend is one that has an odd number of operands, whereby the
3087 /// first operand does not have an associated mask.
3088 bool isNormalized() const { return getNumOperands() % 2; }
3089
3090 /// Return the number of incoming values, taking into account when normalized
3091 /// the first incoming value will have no mask.
3092 unsigned getNumIncomingValues() const {
3093 return (getNumOperands() + isNormalized()) / 2;
3094 }
3095
3096 /// Return incoming value number \p Idx.
3097 VPValue *getIncomingValue(unsigned Idx) const {
3098 return Idx == 0 ? getOperand(0) : getOperand(Idx * 2 - isNormalized());
3099 }
3100
3101 /// Return mask number \p Idx.
3102 VPValue *getMask(unsigned Idx) const {
3103 assert((Idx > 0 || !isNormalized()) && "First index has no mask!");
3104 return Idx == 0 ? getOperand(1) : getOperand(Idx * 2 + !isNormalized());
3105 }
3106
3107 /// Set mask number \p Idx to \p V.
3108 void setMask(unsigned Idx, VPValue *V) {
3109 assert((Idx > 0 || !isNormalized()) && "First index has no mask!");
3110 assert(V->getScalarType()->isIntegerTy(1) && "Mask must be an i1 (vector)");
3111 Idx == 0 ? setOperand(1, V) : setOperand(Idx * 2 + !isNormalized(), V);
3112 }
3113
3114 void execute(VPTransformState &State) override {
3115 llvm_unreachable("VPBlendRecipe should be expanded by simplifyBlends");
3116 }
3117
3118 /// Return the cost of this VPWidenMemoryRecipe.
3119 InstructionCost computeCost(ElementCount VF,
3120 VPCostContext &Ctx) const override;
3121
3122 /// Returns true if the recipe only uses the first lane of operand \p Op.
3123 bool usesFirstLaneOnly(const VPValue *Op) const override;
3124
3125protected:
3126#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3127 /// Print the recipe.
3128 void printRecipe(raw_ostream &O, const Twine &Indent,
3129 VPSlotTracker &SlotTracker) const override;
3130#endif
3131};
3132
3133/// A common base class for interleaved memory operations.
3134/// An Interleaved memory operation is a memory access method that combines
3135/// multiple strided loads/stores into a single wide load/store with shuffles.
3136/// The first operand is the start address. The optional operands are, in order,
3137/// the stored values and the mask.
3139 public VPIRMetadata {
3141
3142 /// Indicates if the interleave group is in a conditional block and requires a
3143 /// mask.
3144 bool HasMask = false;
3145
3146 /// Indicates if gaps between members of the group need to be masked out or if
3147 /// unusued gaps can be loaded speculatively.
3148 bool NeedsMaskForGaps = false;
3149
3150protected:
3152 ArrayRef<VPValue *> Operands,
3153 ArrayRef<VPValue *> StoredValues, VPValue *Mask,
3154 bool NeedsMaskForGaps, const VPIRMetadata &MD, DebugLoc DL)
3155 : VPRecipeBase(SC, Operands, DL), VPIRMetadata(MD), IG(IG),
3156 NeedsMaskForGaps(NeedsMaskForGaps) {
3157 // TODO: extend the masked interleaved-group support to reversed access.
3158 assert((!Mask || !IG->isReverse()) &&
3159 "Reversed masked interleave-group not supported.");
3160 if (StoredValues.empty()) {
3161 for (Instruction *Inst : IG->members()) {
3162 assert(!Inst->getType()->isVoidTy() && "must have result");
3163 new VPMultiDefValue(this, Inst, Inst->getType());
3164 }
3165 } else {
3166 for (auto *SV : StoredValues)
3167 addOperand(SV);
3168 }
3169 if (Mask) {
3170 HasMask = true;
3171 addOperand(Mask);
3172 }
3173 }
3174
3175public:
3176 VPInterleaveBase *clone() override = 0;
3177
3178 static inline bool classof(const VPRecipeBase *R) {
3179 return R->getVPRecipeID() == VPRecipeBase::VPInterleaveSC ||
3180 R->getVPRecipeID() == VPRecipeBase::VPInterleaveEVLSC;
3181 }
3182
3183 static inline bool classof(const VPUser *U) {
3184 auto *R = dyn_cast<VPRecipeBase>(U);
3185 return R && classof(R);
3186 }
3187
3188 /// Return the address accessed by this recipe.
3189 VPValue *getAddr() const {
3190 return getOperand(0); // Address is the 1st, mandatory operand.
3191 }
3192
3193 /// Return the mask used by this recipe. Note that a full mask is represented
3194 /// by a nullptr.
3195 VPValue *getMask() const {
3196 // Mask is optional and the last operand.
3197 return HasMask ? getLastOperand() : nullptr;
3198 }
3199
3200 /// Return true if the access needs a mask because of the gaps.
3201 bool needsMaskForGaps() const { return NeedsMaskForGaps; }
3202
3204
3205 Instruction *getInsertPos() const { return IG->getInsertPos(); }
3206
3207 void execute(VPTransformState &State) override {
3208 llvm_unreachable("VPInterleaveBase should not be instantiated.");
3209 }
3210
3211 /// Return the cost of this recipe.
3212 InstructionCost computeCost(ElementCount VF,
3213 VPCostContext &Ctx) const override;
3214
3215 /// Returns true if the recipe only uses the first lane of operand \p Op.
3216 bool usesFirstLaneOnly(const VPValue *Op) const override = 0;
3217
3218 /// Returns the number of stored operands of this interleave group. Returns 0
3219 /// for load interleave groups.
3220 virtual unsigned getNumStoreOperands() const = 0;
3221
3222 /// Return the VPValues stored by this interleave group. If it is a load
3223 /// interleave group, return an empty ArrayRef.
3225 return {op_end() - (getNumStoreOperands() + (HasMask ? 1 : 0)),
3227 }
3228};
3229
3230/// VPInterleaveRecipe is a recipe for transforming an interleave group of load
3231/// or stores into one wide load/store and shuffles. The first operand of a
3232/// VPInterleave recipe is the address, followed by the stored values, followed
3233/// by an optional mask.
3235public:
3237 ArrayRef<VPValue *> StoredValues, VPValue *Mask,
3238 bool NeedsMaskForGaps, const VPIRMetadata &MD, DebugLoc DL)
3239 : VPInterleaveBase(VPRecipeBase::VPInterleaveSC, IG, Addr, StoredValues,
3240 Mask, NeedsMaskForGaps, MD, DL) {}
3241
3242 ~VPInterleaveRecipe() override = default;
3243
3247 needsMaskForGaps(), *this, getDebugLoc());
3248 }
3249
3250 VP_CLASSOF_IMPL(VPRecipeBase::VPInterleaveSC)
3251
3252 /// Generate the wide load or store, and shuffles.
3253 void execute(VPTransformState &State) override;
3254
3255 bool usesFirstLaneOnly(const VPValue *Op) const override {
3257 "Op must be an operand of the recipe");
3258 return Op == getAddr() && !llvm::is_contained(getStoredValues(), Op);
3259 }
3260
3261 unsigned getNumStoreOperands() const override {
3262 return getNumOperands() - (getMask() ? 2 : 1);
3263 }
3264
3265protected:
3266#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3267 /// Print the recipe.
3268 void printRecipe(raw_ostream &O, const Twine &Indent,
3269 VPSlotTracker &SlotTracker) const override;
3270#endif
3271};
3272
3273/// A recipe for interleaved memory operations with vector-predication
3274/// intrinsics. The first operand is the address, the second operand is the
3275/// explicit vector length. Stored values and mask are optional operands.
3277public:
3279 : VPInterleaveBase(VPRecipeBase::VPInterleaveEVLSC,
3280 R.getInterleaveGroup(), {R.getAddr(), &EVL},
3281 R.getStoredValues(), Mask, R.needsMaskForGaps(), R,
3282 R.getDebugLoc()) {
3283 assert(!getInterleaveGroup()->isReverse() &&
3284 "Reversed interleave-group with tail folding is not supported.");
3285 assert(!needsMaskForGaps() && "Interleaved access with gap mask is not "
3286 "supported for scalable vector.");
3287 }
3288
3289 ~VPInterleaveEVLRecipe() override = default;
3290
3292 llvm_unreachable("cloning not implemented yet");
3293 }
3294
3295 VP_CLASSOF_IMPL(VPRecipeBase::VPInterleaveEVLSC)
3296
3297 /// The VPValue of the explicit vector length.
3298 VPValue *getEVL() const { return getOperand(1); }
3299
3300 /// Generate the wide load or store, and shuffles.
3301 void execute(VPTransformState &State) override;
3302
3303 /// The recipe only uses the first lane of the address, and EVL operand.
3304 bool usesFirstLaneOnly(const VPValue *Op) const override {
3306 "Op must be an operand of the recipe");
3307 return (Op == getAddr() && !llvm::is_contained(getStoredValues(), Op)) ||
3308 Op == getEVL();
3309 }
3310
3311 unsigned getNumStoreOperands() const override {
3312 return getNumOperands() - (getMask() ? 3 : 2);
3313 }
3314
3315protected:
3316#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3317 /// Print the recipe.
3318 void printRecipe(raw_ostream &O, const Twine &Indent,
3319 VPSlotTracker &SlotTracker) const override;
3320#endif
3321};
3322
3323/// A recipe to represent inloop, ordered or partial reduction operations. It
3324/// performs a reduction on a vector operand into a scalar (vector in the case
3325/// of a partial reduction) value, and adds the result to a chain. The Operands
3326/// are {ChainOp, VecOp, [Condition]}.
3328
3329 /// The recurrence kind for the reduction in question.
3330 RecurKind RdxKind;
3331 /// Whether the reduction is conditional.
3332 bool IsConditional = false;
3333 ReductionStyle Style;
3334
3335protected:
3338 VPValue *CondOp, ReductionStyle Style, DebugLoc DL)
3340 DL),
3341 RdxKind(RdxKind), Style(Style) {
3343 [this](VPValue *VPV) {
3344 return VPV->getScalarType() == getScalarType() ||
3345 (isa<VPInstruction>(VPV) &&
3346 cast<VPInstruction>(VPV)->getOpcode() ==
3348 }) &&
3349 "all incoming values must have the same type");
3350 if (CondOp) {
3351 assert(CondOp->getScalarType()->isIntegerTy(1) &&
3352 "CondOp must be a bool");
3353 IsConditional = true;
3354 addOperand(CondOp);
3355 }
3357 }
3358
3359public:
3361 VPValue *ChainOp, VPValue *VecOp, VPValue *CondOp,
3363 : VPReductionRecipe(VPRecipeBase::VPReductionSC, RdxKind, FMFs, I,
3364 {ChainOp, VecOp}, CondOp, Style, DL) {}
3365
3367 VPValue *ChainOp, VPValue *VecOp, VPValue *CondOp,
3369 : VPReductionRecipe(VPRecipeBase::VPReductionSC, RdxKind, FMFs, nullptr,
3370 {ChainOp, VecOp}, CondOp, Style, DL) {}
3371
3372 ~VPReductionRecipe() override = default;
3373
3375 return new VPReductionRecipe(RdxKind, getFastMathFlagsOrNone(),
3377 getCondOp(), Style, getDebugLoc());
3378 }
3379
3380 static inline bool classof(const VPRecipeBase *R) {
3381 return R->getVPRecipeID() == VPRecipeBase::VPReductionSC ||
3382 R->getVPRecipeID() == VPRecipeBase::VPReductionEVLSC;
3383 }
3384
3385 static inline bool classof(const VPUser *U) {
3386 auto *R = dyn_cast<VPRecipeBase>(U);
3387 return R && classof(R);
3388 }
3389
3390 static inline bool classof(const VPValue *VPV) {
3391 const VPRecipeBase *R = VPV->getDefiningRecipe();
3392 return R && classof(R);
3393 }
3394
3395 static inline bool classof(const VPSingleDefRecipe *R) {
3396 return classof(static_cast<const VPRecipeBase *>(R));
3397 }
3398
3399 /// Generate the reduction in the loop.
3400 void execute(VPTransformState &State) override;
3401
3402 /// Return the cost of VPReductionRecipe.
3403 InstructionCost computeCost(ElementCount VF,
3404 VPCostContext &Ctx) const override;
3405
3406 /// Return the recurrence kind for the in-loop reduction.
3407 RecurKind getRecurrenceKind() const { return RdxKind; }
3408 /// Return true if the in-loop reduction is ordered.
3409 bool isOrdered() const { return std::holds_alternative<RdxOrdered>(Style); };
3410 /// Return true if the in-loop reduction is conditional.
3411 bool isConditional() const { return IsConditional; };
3412 /// Returns true if the reduction outputs a vector with a scaled down VF.
3413 bool isPartialReduction() const {
3414 return std::holds_alternative<RdxUnordered>(Style);
3415 }
3416 /// Returns true if the reduction is in-loop.
3417 bool isInLoop() const {
3418 return std::holds_alternative<RdxInLoop>(Style) ||
3419 std::holds_alternative<RdxOrdered>(Style);
3420 }
3421 /// The VPValue of the scalar Chain being accumulated.
3422 VPValue *getChainOp() const { return getOperand(0); }
3423 /// The VPValue of the vector value to be reduced.
3424 VPValue *getVecOp() const { return getOperand(1); }
3425 /// The VPValue of the condition for the block.
3427 return isConditional() ? getLastOperand() : nullptr;
3428 }
3429 /// Get the factor that the VF of this recipe's output should be scaled by, or
3430 /// 1 if it isn't scaled.
3431 unsigned getVFScaleFactor() const {
3432 auto *Partial = std::get_if<RdxUnordered>(&Style);
3433 return Partial ? Partial->VFScaleFactor : 1;
3434 }
3435
3436protected:
3437#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3438 /// Print the recipe.
3439 void printRecipe(raw_ostream &O, const Twine &Indent,
3440 VPSlotTracker &SlotTracker) const override;
3441#endif
3442};
3443
3444/// A recipe to represent inloop reduction operations with vector-predication
3445/// intrinsics, performing a reduction on a vector operand with the explicit
3446/// vector length (EVL) into a scalar value, and adding the result to a chain.
3447/// The Operands are {ChainOp, VecOp, EVL, [Condition]}.
3449public:
3452 : VPReductionRecipe(VPRecipeBase::VPReductionEVLSC, R.getRecurrenceKind(),
3455 {R.getChainOp(), R.getVecOp(), &EVL}, CondOp,
3456 getReductionStyle(R.isInLoop(), R.isOrdered(),
3457 R.getVFScaleFactor()),
3458 DL) {}
3459
3460 ~VPReductionEVLRecipe() override = default;
3461
3463 llvm_unreachable("cloning not implemented yet");
3464 }
3465
3466 VP_CLASSOF_IMPL(VPRecipeBase::VPReductionEVLSC)
3467
3468 /// Generate the reduction in the loop
3469 void execute(VPTransformState &State) override;
3470
3471 /// The VPValue of the explicit vector length.
3472 VPValue *getEVL() const { return getOperand(2); }
3473
3474 /// Returns true if the recipe only uses the first lane of operand \p Op.
3475 bool usesFirstLaneOnly(const VPValue *Op) const override {
3477 "Op must be an operand of the recipe");
3478 return Op == getEVL();
3479 }
3480
3481protected:
3482#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3483 /// Print the recipe.
3484 void printRecipe(raw_ostream &O, const Twine &Indent,
3485 VPSlotTracker &SlotTracker) const override;
3486#endif
3487};
3488
3489/// VPReplicateRecipe replicates a given instruction producing multiple scalar
3490/// copies of the original scalar type, one per lane, instead of producing a
3491/// single copy of widened type for all lanes. If the instruction is known to be
3492/// a single scalar, only one copy will be generated.
3494 public VPIRMetadata {
3495 /// Indicator if only a single replica per lane is needed.
3496 bool IsSingleScalar;
3497
3498 /// Indicator if the replicas are also predicated.
3499 bool IsPredicated;
3500
3501public:
3503 bool IsSingleScalar, VPValue *Mask = nullptr,
3504 const VPIRFlags &Flags = {}, VPIRMetadata Metadata = {},
3505 DebugLoc DL = DebugLoc::getUnknown())
3506 : VPRecipeWithIRFlags(VPRecipeBase::VPReplicateSC, Operands,
3507 computeScalarType(I, Operands), Flags, DL),
3508 VPIRMetadata(Metadata), IsSingleScalar(IsSingleScalar),
3509 IsPredicated(Mask) {
3510 assert((!IsSingleScalar || !I->isCast()) &&
3511 "Single-scalar casts should use VPInstruction");
3512 setUnderlyingValue(I);
3513 if (Mask)
3514 addOperand(Mask);
3515 }
3516
3517 ~VPReplicateRecipe() override = default;
3518
3519 /// Compute the scalar result type for a VPReplicateRecipe wrapping \p I with
3520 /// \p Operands (excluding any predicate mask).
3521 static Type *computeScalarType(const Instruction *I,
3523
3525
3527 return new VPReplicateRecipe(
3528 getUnderlyingInstr(), NewOperands, IsSingleScalar,
3529 isPredicated() ? getMask() : nullptr, *this, *this, getDebugLoc());
3530 }
3531
3532 VP_CLASSOF_IMPL(VPRecipeBase::VPReplicateSC)
3533
3534 /// Generate replicas of the desired Ingredient. Replicas will be generated
3535 /// for all parts and lanes unless a specific part and lane are specified in
3536 /// the \p State.
3537 void execute(VPTransformState &State) override;
3538
3539 /// Return the cost of this VPReplicateRecipe.
3540 InstructionCost computeCost(ElementCount VF,
3541 VPCostContext &Ctx) const override;
3542
3543 /// Return the cost of scalarizing a call to \p CalledFn with argument
3544 /// operands \p ArgOps for a given \p VF.
3545 static InstructionCost computeCallCost(Function *CalledFn, Type *ResultTy,
3547 bool IsSingleScalar, ElementCount VF,
3548 VPCostContext &Ctx);
3549
3550 /// Returns true if the recipe produces a single scalar value.
3551 bool isSingleScalar() const { return IsSingleScalar; }
3552
3553 /// Returns true if the recipe produces scalar values for all VF lanes.
3554 bool doesGeneratePerAllLanes() const { return !IsSingleScalar; }
3555
3556 bool isPredicated() const { return IsPredicated; }
3557
3558 /// Returns true if the recipe only uses the first lane of operand \p Op.
3559 bool usesFirstLaneOnly(const VPValue *Op) const override {
3561 "Op must be an operand of the recipe");
3562 return isSingleScalar();
3563 }
3564
3565 /// Returns true if the recipe uses scalars of operand \p Op.
3566 bool usesScalars(const VPValue *Op) const override {
3568 "Op must be an operand of the recipe");
3569 return true;
3570 }
3571
3572 /// Return the mask of a predicated VPReplicateRecipe.
3574 assert(isPredicated() && "Trying to get the mask of a unpredicated recipe");
3575 return getLastOperand();
3576 }
3577
3578 /// Return the recipe's operands, excluding the mask of a predicated recipe.
3582
3583 /// Returns the number of operands, excluding the mask if the recipe is
3584 /// predicated.
3585 unsigned getNumOperandsWithoutMask() const {
3586 return getNumOperands() - isPredicated();
3587 }
3588
3589 unsigned getOpcode() const { return getUnderlyingInstr()->getOpcode(); }
3590
3591protected:
3592#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3593 /// Print the recipe.
3594 void printRecipe(raw_ostream &O, const Twine &Indent,
3595 VPSlotTracker &SlotTracker) const override;
3596#endif
3597};
3598
3599/// A recipe for generating conditional branches on the bits of a mask.
3601 public VPIRMetadata {
3602public:
3604 const VPIRMetadata &Metadata = {})
3605 : VPRecipeBase(VPRecipeBase::VPBranchOnMaskSC, {BlockInMask}, DL),
3606 VPIRMetadata(Metadata) {}
3607
3609 return new VPBranchOnMaskRecipe(getOperand(0), getDebugLoc(), *this);
3610 }
3611
3612 VP_CLASSOF_IMPL(VPRecipeBase::VPBranchOnMaskSC)
3613
3614 /// Generate the extraction of the appropriate bit from the block mask and the
3615 /// conditional branch.
3616 void execute(VPTransformState &State) override;
3617
3618 /// Return the cost of this VPBranchOnMaskRecipe.
3619 InstructionCost computeCost(ElementCount VF,
3620 VPCostContext &Ctx) const override;
3621
3622#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3623 /// Print the recipe.
3624 void printRecipe(raw_ostream &O, const Twine &Indent,
3625 VPSlotTracker &SlotTracker) const override {
3626 O << Indent << "BRANCH-ON-MASK ";
3628 }
3629#endif
3630
3631 /// Returns true if the recipe uses scalars of operand \p Op.
3632 bool usesScalars(const VPValue *Op) const override {
3634 "Op must be an operand of the recipe");
3635 return true;
3636 }
3637};
3638
3639/// A recipe to combine multiple recipes into a single 'expression' recipe,
3640/// which should be considered a single entity for cost-modeling and transforms.
3641/// The recipe needs to be 'decomposed', i.e. replaced by its individual
3642/// expression recipes, before execute. The individual expression recipes are
3643/// completely disconnected from the def-use graph of other recipes not part of
3644/// the expression. Def-use edges between pairs of expression recipes remain
3645/// intact, whereas every edge between an expression recipe and a recipe outside
3646/// the expression is elevated to connect the non-expression recipe with the
3647/// VPExpressionRecipe itself.
3649 /// Recipes included in this VPExpressionRecipe. This could contain
3650 /// duplicates.
3651 SmallVector<VPSingleDefRecipe *> ExpressionRecipes;
3652
3653 /// Temporary VPValues used for external operands of the expression, i.e.
3654 /// operands not defined by recipes in the expression.
3655 SmallVector<VPValue *> LiveInPlaceholders;
3656
3657 enum class ExpressionTypes {
3658 /// Represents an inloop extended reduction operation, performing a
3659 /// reduction on an extended vector operand into a scalar value, and adding
3660 /// the result to a chain.
3661 ExtendedReduction,
3662 /// Represents an inloop extended reduction operation, which is negated,
3663 /// then reduced before adding the result to a chain.
3664 NegatedExtendedReduction,
3665 /// Represent an inloop multiply-accumulate reduction, multiplying the
3666 /// extended vector operands, performing a reduction.add on the result, and
3667 /// adding the scalar result to a chain.
3668 ExtMulAccReduction,
3669 /// Represent an inloop multiply-accumulate reduction, multiplying the
3670 /// vector operands, performing a reduction.add on the result, and adding
3671 /// the scalar result to a chain.
3672 MulAccReduction,
3673 /// Represent an inloop multiply-accumulate reduction, multiplying the
3674 /// extended vector operands, negating the multiplication, performing a
3675 /// reduction.add on the result, and adding the scalar result to a chain.
3676 ExtNegatedMulAccReduction,
3677 /// Represent a chain of recipes whose last recipe will be optimized away.
3678 /// Currently only supports folding vp.merge with an in-loop operation, so
3679 /// LV does not account for the cost or register pressure of vp.merge.
3680 FoldedVPMerge,
3681 };
3682
3683 /// Type of the expression.
3684 ExpressionTypes ExpressionType;
3685
3686public:
3687 /// Construct a new VPExpressionRecipe by internalizing recipes in \p
3688 /// ExpressionRecipes. External operands (i.e. not defined by another recipe
3689 /// in the expression) are replaced by temporary VPValues and the original
3690 /// operands are transferred to the VPExpressionRecipe itself. Clone recipes
3691 /// as needed (excluding last) to ensure they are only used by other recipes
3692 /// in the expression.
3693 VPExpressionRecipe(ExpressionTypes ExpressionType,
3694 ArrayRef<VPSingleDefRecipe *> ExpressionRecipes);
3695
3697 : VPExpressionRecipe(ExpressionTypes::ExtendedReduction, {Ext, Red}) {}
3699 VPReductionRecipe *Red)
3700 : VPExpressionRecipe(ExpressionTypes::NegatedExtendedReduction,
3701 {Ext, Neg, Red}) {
3702 assert((Red->getRecurrenceKind() == RecurKind::Add ||
3703 Red->getRecurrenceKind() == RecurKind::FAdd ||
3704 Red->getRecurrenceKind() == RecurKind::AddChainWithSubs) &&
3705 "Expected an add or add-chain-with-subs reduction");
3706 if (Neg->getOpcode() == Instruction::Sub) {
3707 [[maybe_unused]] auto *SubConst = dyn_cast<VPConstantInt>(getOperand(1));
3708 assert(SubConst && SubConst->isZero() && "Expected a negating sub");
3709 } else
3710 assert(Neg->getOpcode() == Instruction::FNeg && "Unexpected opcode");
3711 }
3713 : VPExpressionRecipe(ExpressionTypes::MulAccReduction, {Mul, Red}) {}
3716 : VPExpressionRecipe(ExpressionTypes::ExtMulAccReduction,
3717 {Ext0, Ext1, Mul, Red}) {}
3720 VPReductionRecipe *Red)
3721 : VPExpressionRecipe(ExpressionTypes::ExtNegatedMulAccReduction,
3722 {Ext0, Ext1, Mul, Neg, Red}) {
3723 assert((Mul->getOpcode() == Instruction::Mul ||
3724 Mul->getOpcode() == Instruction::FMul) &&
3725 "Expected a mul");
3726 assert((Red->getRecurrenceKind() == RecurKind::Add ||
3727 Red->getRecurrenceKind() == RecurKind::FAdd ||
3728 Red->getRecurrenceKind() == RecurKind::AddChainWithSubs) &&
3729 "Expected an add or add-chain-with-subs reduction");
3730 assert(getNumOperands() >= 3 && "Expected at least three operands");
3731 if (Neg->getOpcode() == Instruction::Sub) {
3732 [[maybe_unused]] auto *SubConst = dyn_cast<VPConstantInt>(getOperand(2));
3733 assert(SubConst && SubConst->isZero() &&
3734 Neg->getOpcode() == Instruction::Sub && "Expected a negating sub");
3735 } else
3736 assert(Neg->getOpcode() == Instruction::FNeg && "Unexpected opcode");
3737 }
3739 VPWidenIntrinsicRecipe *VPMerge)
3740 : VPExpressionRecipe(ExpressionTypes::FoldedVPMerge,
3741 {InLoopOp, VPMerge}) {
3742 assert(VPMerge->getVectorIntrinsicID() == Intrinsic::vp_merge &&
3743 "Expected a vp.merge");
3744 }
3745
3747 SmallPtrSet<VPSingleDefRecipe *, 4> ExpressionRecipesSeen;
3748 for (auto *R : reverse(ExpressionRecipes)) {
3749 if (ExpressionRecipesSeen.insert(R).second)
3750 delete R;
3751 }
3752 for (VPValue *T : LiveInPlaceholders)
3753 delete T;
3754 }
3755
3756 VP_CLASSOF_IMPL(VPRecipeBase::VPExpressionSC)
3757
3759 assert(!ExpressionRecipes.empty() && "empty expressions should be removed");
3760 SmallVector<VPSingleDefRecipe *> NewExpressiondRecipes;
3761 for (auto *R : ExpressionRecipes)
3762 NewExpressiondRecipes.push_back(R->clone());
3763 for (auto *New : NewExpressiondRecipes) {
3764 for (const auto &[Idx, Old] : enumerate(ExpressionRecipes))
3765 New->replaceUsesOfWith(Old, NewExpressiondRecipes[Idx]);
3766 // Update placeholder operands in the cloned recipe to use the external
3767 // operands, to be internalized when the cloned expression is constructed.
3768 for (const auto &[Placeholder, OutsideOp] :
3769 zip(LiveInPlaceholders, operands()))
3770 New->replaceUsesOfWith(Placeholder, OutsideOp);
3771 }
3772 return new VPExpressionRecipe(ExpressionType, NewExpressiondRecipes);
3773 }
3774
3775 /// Return and insert the recipes of the expression back into the VPlan,
3776 /// directly before the current recipe. Leaves the expression recipe empty,
3777 /// which must be removed before codegen.
3779
3780 /// Returns the expression type of this recipe.
3781 ExpressionTypes getExpressionType() const { return ExpressionType; }
3782
3783 unsigned getVFScaleFactor() const {
3784 auto *PR = dyn_cast<VPReductionRecipe>(ExpressionRecipes.back());
3785 return PR ? PR->getVFScaleFactor() : 1;
3786 }
3787
3788 /// Method for generating code, must not be called as this recipe is abstract.
3789 void execute(VPTransformState &State) override {
3790 llvm_unreachable("recipe must be removed before execute");
3791 }
3792
3794 VPCostContext &Ctx) const override;
3795
3796 /// Returns true if the recipe only uses the first lane of operand \p Op.
3797 bool usesFirstLaneOnly(const VPValue *Op) const override;
3798
3799 /// Returns true if this expression contains recipes that may read from or
3800 /// write to memory.
3801 bool mayReadOrWriteMemory() const;
3802
3803 /// Returns true if this expression contains recipes that may have side
3804 /// effects.
3805 bool mayHaveSideEffects() const;
3806
3807 /// Returns true if this VPExpressionRecipe produces a single scalar.
3808 bool isVectorToScalar() const;
3809
3810protected:
3811#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3812 /// Print the recipe.
3813 void printRecipe(raw_ostream &O, const Twine &Indent,
3814 VPSlotTracker &SlotTracker) const override;
3815#endif
3816};
3817
3818/// VPPredInstPHIRecipe is a recipe for generating the phi nodes needed when
3819/// control converges back from a Branch-on-Mask. The phi nodes are needed in
3820/// order to merge values that are set under such a branch and feed their uses.
3821/// The phi nodes can be scalar or vector depending on the users of the value.
3822/// This recipe works in concert with VPBranchOnMaskRecipe.
3824public:
3825 /// Construct a VPPredInstPHIRecipe given \p PredInst whose value needs a phi
3826 /// nodes after merging back from a Branch-on-Mask.
3828 : VPSingleDefRecipe(VPRecipeBase::VPPredInstPHISC, PredV,
3829 PredV->getScalarType(), /*UV=*/nullptr, DL) {}
3830 ~VPPredInstPHIRecipe() override = default;
3831
3833 return new VPPredInstPHIRecipe(getOperand(0), getDebugLoc());
3834 }
3835
3836 VP_CLASSOF_IMPL(VPRecipeBase::VPPredInstPHISC)
3837
3838 /// Generates phi nodes for live-outs (from a replicate region) as needed to
3839 /// retain SSA form.
3840 void execute(VPTransformState &State) override;
3841
3842 /// Return the cost of this VPPredInstPHIRecipe.
3844 VPCostContext &Ctx) const override {
3845 // TODO: Compute accurate cost after retiring the legacy cost model.
3846 return 0;
3847 }
3848
3849protected:
3850#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3851 /// Print the recipe.
3852 void printRecipe(raw_ostream &O, const Twine &Indent,
3853 VPSlotTracker &SlotTracker) const override;
3854#endif
3855};
3856
3857/// A common mixin class for widening memory operations. An optional mask can be
3858/// provided as the last operand.
3860protected:
3862
3863 /// Alignment information for this memory access.
3865
3866 /// Whether the accessed addresses are consecutive.
3868
3869 /// Whether the memory access is masked.
3870 bool IsMasked = false;
3871
3872 void setMask(VPValue *Mask) {
3873 assert(!IsMasked && "cannot re-set mask");
3874 if (!Mask)
3875 return;
3876 assert(Mask->getScalarType()->isIntegerTy(1) &&
3877 "Mask must be an i1 (vector)");
3878 getAsRecipe()->addOperand(Mask);
3879 IsMasked = true;
3880 }
3881
3886
3887public:
3888 virtual ~VPWidenMemoryRecipe() = default;
3889
3890 /// Return a VPRecipeBase* to the current object.
3892 virtual const VPRecipeBase *getAsRecipe() const = 0;
3893
3894 /// Return whether the loaded-from / stored-to addresses are consecutive.
3895 bool isConsecutive() const { return Consecutive; }
3896
3897 /// Return the address accessed by this recipe.
3898 VPValue *getAddr() const { return getAsRecipe()->getOperand(0); }
3899
3900 /// Returns true if the recipe is masked.
3901 bool isMasked() const { return IsMasked; }
3902
3903 /// Return the mask used by this recipe. Note that a full mask is represented
3904 /// by a nullptr.
3905 VPValue *getMask() const {
3906 // Mask is optional and therefore the last operand.
3907 const VPRecipeBase *R = getAsRecipe();
3908 return isMasked() ? R->getLastOperand() : nullptr;
3909 }
3910
3911 /// Returns the alignment of the memory access.
3912 Align getAlign() const { return Alignment; }
3913
3914 /// Return the cost of this VPWidenMemoryRecipe.
3915 InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const;
3916
3918};
3919
3920/// A recipe for widening load operations, using the address to load from and an
3921/// optional mask.
3923 public VPWidenMemoryRecipe {
3926 const VPIRMetadata &Metadata, DebugLoc DL)
3927 : VPSingleDefRecipe(VPRecipeBase::VPWidenLoadSC, {Addr}, Load.getType(),
3928 &Load, DL),
3929 VPWidenMemoryRecipe(Load, Alignment, Consecutive, Metadata) {
3930 setMask(Mask);
3931 }
3932
3935 getMask(), Consecutive, getAlign(), *this,
3936 getDebugLoc());
3937 }
3938
3939 VP_CLASSOF_IMPL(VPRecipeBase::VPWidenLoadSC);
3940
3941 /// Returns the opcode of the widened load.
3942 unsigned getOpcode() const { return Instruction::Load; }
3943
3944 /// Generate a wide load or gather.
3945 void execute(VPTransformState &State) override;
3946
3947 /// Return the cost of this VPWidenLoadRecipe.
3949 VPCostContext &Ctx) const override {
3950 return VPWidenMemoryRecipe::computeCost(VF, Ctx);
3951 }
3952
3953 /// Returns true if the recipe only uses the first lane of operand \p Op.
3954 bool usesFirstLaneOnly(const VPValue *Op) const override {
3956 "Op must be an operand of the recipe");
3957 // Widened, consecutive loads operations only demand the first lane of
3958 // their address.
3959 return Op == getAddr() && isConsecutive();
3960 }
3961
3962protected:
3963 VPRecipeBase *getAsRecipe() override;
3964 const VPRecipeBase *getAsRecipe() const override;
3965
3966#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3967 /// Print the recipe.
3968 void printRecipe(raw_ostream &O, const Twine &Indent,
3969 VPSlotTracker &SlotTracker) const override;
3970#endif
3971};
3972
3973/// A recipe for widening load operations with vector-predication intrinsics,
3974/// using the address to load from, the explicit vector length and an optional
3975/// mask.
3977 : public VPSingleDefRecipe,
3978 public VPWidenMemoryRecipe {
3980 VPValue *Mask)
3981 : VPSingleDefRecipe(VPRecipeBase::VPWidenLoadEVLSC, {Addr, &EVL},
3982 L.getIngredient().getType(), &L.getIngredient(),
3983 L.getDebugLoc()),
3984 VPWidenMemoryRecipe(L.getIngredient(), L.getAlign(), L.isConsecutive(),
3985 L) {
3986 setMask(Mask);
3987 }
3988
3990 llvm_unreachable("cloning not supported");
3991 }
3992
3993 VP_CLASSOF_IMPL(VPRecipeBase::VPWidenLoadEVLSC)
3994
3995 /// Returns the opcode of the widened load.
3996 unsigned getOpcode() const { return Instruction::Load; }
3997
3998 /// Return the EVL operand.
3999 VPValue *getEVL() const { return getOperand(1); }
4000
4001 /// Generate the wide load or gather.
4002 void execute(VPTransformState &State) override;
4003
4004 /// Return the cost of this VPWidenLoadEVLRecipe.
4005 InstructionCost computeCost(ElementCount VF,
4006 VPCostContext &Ctx) const override;
4007
4008 /// Returns true if the recipe only uses the first lane of operand \p Op.
4009 bool usesFirstLaneOnly(const VPValue *Op) const override {
4011 "Op must be an operand of the recipe");
4012 // Widened loads only demand the first lane of EVL and consecutive loads
4013 // only demand the first lane of their address.
4014 return Op == getEVL() || (Op == getAddr() && isConsecutive());
4015 }
4016
4017protected:
4018 VPRecipeBase *getAsRecipe() override;
4019 const VPRecipeBase *getAsRecipe() const override;
4020
4021#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4022 /// Print the recipe.
4023 void printRecipe(raw_ostream &O, const Twine &Indent,
4024 VPSlotTracker &SlotTracker) const override;
4025#endif
4026};
4027
4028/// A recipe for widening store operations, using the stored value, the address
4029/// to store to and an optional mask.
4031 public VPWidenMemoryRecipe {
4033 VPValue *Mask, bool Consecutive, Align Alignment,
4034 const VPIRMetadata &Metadata, DebugLoc DL)
4035 : VPRecipeBase(VPRecipeBase::VPWidenStoreSC, {Addr, StoredVal}, DL),
4036 VPWidenMemoryRecipe(Store, Alignment, Consecutive, Metadata) {
4037 setMask(Mask);
4038 }
4039
4045
4046 VP_CLASSOF_IMPL(VPRecipeBase::VPWidenStoreSC);
4047
4048 /// Return the value stored by this recipe.
4049 VPValue *getStoredValue() const { return getOperand(1); }
4050
4051 /// Generate a wide store or scatter.
4052 void execute(VPTransformState &State) override;
4053
4054 /// Return the cost of this VPWidenStoreRecipe.
4056 VPCostContext &Ctx) const override {
4057 return VPWidenMemoryRecipe::computeCost(VF, Ctx);
4058 }
4059
4060 /// Returns true if the recipe only uses the first lane of operand \p Op.
4061 bool usesFirstLaneOnly(const VPValue *Op) const override {
4063 "Op must be an operand of the recipe");
4064 // Widened, consecutive stores only demand the first lane of their address,
4065 // unless the same operand is also stored.
4066 return Op == getAddr() && isConsecutive() && Op != getStoredValue();
4067 }
4068
4069protected:
4070 VPRecipeBase *getAsRecipe() override;
4071 const VPRecipeBase *getAsRecipe() const override;
4072
4073#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4074 /// Print the recipe.
4075 void printRecipe(raw_ostream &O, const Twine &Indent,
4076 VPSlotTracker &SlotTracker) const override;
4077#endif
4078};
4079
4080/// A recipe for widening store operations with vector-predication intrinsics,
4081/// using the value to store, the address to store to, the explicit vector
4082/// length and an optional mask.
4084 : public VPRecipeBase,
4085 public VPWidenMemoryRecipe {
4087 VPValue *StoredVal, VPValue &EVL, VPValue *Mask)
4088 : VPRecipeBase(VPRecipeBase::VPWidenStoreEVLSC, {Addr, StoredVal, &EVL},
4089 S.getDebugLoc()),
4090 VPWidenMemoryRecipe(S.getIngredient(), S.getAlign(), S.isConsecutive(),
4091 S) {
4092 setMask(Mask);
4093 }
4094
4096 llvm_unreachable("cloning not supported");
4097 }
4098
4099 VP_CLASSOF_IMPL(VPRecipeBase::VPWidenStoreEVLSC)
4100
4101 /// Return the address accessed by this recipe.
4102 VPValue *getStoredValue() const { return getOperand(1); }
4103
4104 /// Return the EVL operand.
4105 VPValue *getEVL() const { return getOperand(2); }
4106
4107 /// Generate the wide store or scatter.
4108 void execute(VPTransformState &State) override;
4109
4110 /// Return the cost of this VPWidenStoreEVLRecipe.
4111 InstructionCost computeCost(ElementCount VF,
4112 VPCostContext &Ctx) const override;
4113
4114 /// Returns true if the recipe only uses the first lane of operand \p Op.
4115 bool usesFirstLaneOnly(const VPValue *Op) const override {
4117 "Op must be an operand of the recipe");
4118 if (Op == getEVL()) {
4119 assert(getStoredValue() != Op && "unexpected store of EVL");
4120 return true;
4121 }
4122 // Widened, consecutive memory operations only demand the first lane of
4123 // their address, unless the same operand is also stored. That latter can
4124 // happen with opaque pointers.
4125 return Op == getAddr() && isConsecutive() && Op != getStoredValue();
4126 }
4127
4128protected:
4129 VPRecipeBase *getAsRecipe() override;
4130 const VPRecipeBase *getAsRecipe() const override;
4131
4132#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4133 /// Print the recipe.
4134 void printRecipe(raw_ostream &O, const Twine &Indent,
4135 VPSlotTracker &SlotTracker) const override;
4136#endif
4137};
4138
4139/// Recipe to expand a SCEV expression.
4141 const SCEV *Expr;
4142
4143 /// Whether \p Expr must be expanded in IR, which hoists it out of the loops
4144 /// it is invariant in, instead of as VPInstructions.
4145 bool ExpandInIR;
4146
4147public:
4148 VPExpandSCEVRecipe(const SCEV *Expr, bool ExpandInIR = false);
4149
4150 ~VPExpandSCEVRecipe() override = default;
4151
4153 return new VPExpandSCEVRecipe(Expr, ExpandInIR);
4154 }
4155
4156 VP_CLASSOF_IMPL(VPRecipeBase::VPExpandSCEVSC)
4157
4158 void execute(VPTransformState &State) override {
4159 llvm_unreachable("SCEV expressions must be expanded before final execute");
4160 }
4161
4162 /// Return the cost of this VPExpandSCEVRecipe.
4164 VPCostContext &Ctx) const override {
4165 // TODO: Compute accurate cost after retiring the legacy cost model.
4166 return 0;
4167 }
4168
4169 const SCEV *getSCEV() const { return Expr; }
4170
4171 bool expandInIR() const { return ExpandInIR; }
4172
4173protected:
4174#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4175 /// Print the recipe.
4176 void printRecipe(raw_ostream &O, const Twine &Indent,
4177 VPSlotTracker &SlotTracker) const override;
4178#endif
4179};
4180
4181/// A recipe for generating the active lane mask for the vector loop that is
4182/// used to predicate the vector operations.
4184public:
4186 : VPHeaderPHIRecipe(VPRecipeBase::VPActiveLaneMaskPHISC, nullptr,
4187 StartMask, StartMask->getScalarType(), DL) {}
4188
4189 ~VPActiveLaneMaskPHIRecipe() override = default;
4190
4193 if (getNumOperands() == 2)
4194 R->addBackedgeValue(getOperand(1));
4195 return R;
4196 }
4197
4198 VP_CLASSOF_IMPL(VPRecipeBase::VPActiveLaneMaskPHISC)
4199
4200 /// Generate the active lane mask phi of the vector loop.
4201 void execute(VPTransformState &State) override;
4202
4203protected:
4204#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4205 /// Print the recipe.
4206 void printRecipe(raw_ostream &O, const Twine &Indent,
4207 VPSlotTracker &SlotTracker) const override;
4208#endif
4209};
4210
4211/// A recipe for generating the phi node tracking the current scalar iteration
4212/// index. It starts at the start value of the canonical induction and gets
4213/// incremented by the number of scalar iterations processed by the vector loop
4214/// iteration. The increment does not have to be loop invariant.
4216public:
4218 : VPHeaderPHIRecipe(VPRecipeBase::VPCurrentIterationPHISC, nullptr,
4219 StartIV, StartIV->getScalarType(), DL) {}
4220
4221 ~VPCurrentIterationPHIRecipe() override = default;
4222
4224 llvm_unreachable("cloning not implemented yet");
4225 }
4226
4227 VP_CLASSOF_IMPL(VPRecipeBase::VPCurrentIterationPHISC)
4228
4229 void execute(VPTransformState &State) override {
4230 llvm_unreachable("cannot execute this recipe, should be replaced by a "
4231 "scalar phi recipe");
4232 }
4233
4234 /// Return the cost of this VPCurrentIterationPHIRecipe.
4236 VPCostContext &Ctx) const override {
4237 // For now, match the behavior of the legacy cost model.
4238 return 0;
4239 }
4240
4241 /// Returns true if the recipe only uses the first lane of operand \p Op.
4242 bool usesFirstLaneOnly(const VPValue *Op) const override {
4244 "Op must be an operand of the recipe");
4245 return true;
4246 }
4247
4248protected:
4249#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4250 /// Print the recipe.
4251 void printRecipe(raw_ostream &O, const Twine &Indent,
4252 VPSlotTracker &SlotTracker) const override;
4253#endif
4254};
4255
4256/// A Recipe for widening the canonical induction variable of the vector loop.
4257/// First operand is the canonical IV recipe, a second step operand (VF * Part)
4258/// is added during unrolling.
4260public:
4262 const VPIRFlags::WrapFlagsTy &Flags = {})
4263 : VPRecipeWithIRFlags(VPRecipeBase::VPWidenCanonicalIVSC, CanonicalIV,
4264 CanonicalIV->getType(), Flags) {}
4265
4266 ~VPWidenCanonicalIVRecipe() override = default;
4267
4269 auto *WideCanIV =
4271 if (VPValue *Step = getStepValue())
4272 WideCanIV->addPerPartStep(Step);
4273 return WideCanIV;
4274 }
4275
4276 VP_CLASSOF_IMPL(VPRecipeBase::VPWidenCanonicalIVSC)
4277
4278 void execute(VPTransformState &State) override {
4279 llvm_unreachable("Expected prior expansion of WidenCanonicalIV recipes");
4280 }
4281
4282 /// Return the cost of this VPWidenCanonicalIVPHIRecipe.
4284 VPCostContext &Ctx) const override {
4285 // TODO: Compute accurate cost after retiring the legacy cost model.
4286 return 0;
4287 }
4288
4289 /// Return the canonical IV being widened.
4293
4295 return getNumOperands() == 2 ? getOperand(1) : nullptr;
4296 }
4297
4298 /// Add the per-part step (VF * Part) used for unrolled parts.
4300 assert(Step->getScalarType() == getScalarType() &&
4301 "per-part step must have the same type as the canonical IV");
4302 VPUser::addOperand(Step);
4303 }
4304
4305protected:
4306#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4307 /// Print the recipe.
4308 void printRecipe(raw_ostream &O, const Twine &Indent,
4309 VPSlotTracker &SlotTracker) const override;
4310#endif
4311};
4312
4313/// A recipe for converting \p Current into \p Start + \p Current * \p Step.
4314/// FastMathFlags are derived from the \p FPBinOp in the case of FP inductions,
4315/// and the passed NoWrap \p Flags apply in the case of Ptr and Int inductions.
4317 /// Kind of the induction.
4319 /// If not nullptr, the floating point induction binary operator. Must be set
4320 /// for floating point inductions.
4321 const FPMathOperator *FPBinOp;
4322
4323public:
4325 const FPMathOperator *FPBinOp, VPValue *Start,
4326 VPValue *Current, VPValue *Step,
4327 const VPIRFlags::WrapFlagsTy &Flags = {})
4328 : VPRecipeWithIRFlags(VPRecipeBase::VPDerivedIVSC, {Start, Current, Step},
4329 Start->getScalarType(), Flags),
4330 Kind(Kind), FPBinOp(FPBinOp) {}
4331
4332 ~VPDerivedIVRecipe() override = default;
4333
4335 return new VPDerivedIVRecipe(Kind, FPBinOp, getStartValue(), getOperand(1),
4337 }
4338
4339 VP_CLASSOF_IMPL(VPRecipeBase::VPDerivedIVSC)
4340
4341 void execute(VPTransformState &State) override {
4342 llvm_unreachable("Expected prior expansion of this recipe");
4343 }
4344
4345 /// Return the cost of this VPDerivedIVRecipe.
4346 InstructionCost computeCost(ElementCount VF,
4347 VPCostContext &Ctx) const override;
4348
4349 VPValue *getStartValue() const { return getOperand(0); }
4350 VPValue *getIndex() const { return getOperand(1); }
4351 VPValue *getStepValue() const { return getOperand(2); }
4352 const FPMathOperator *getFPBinOp() const { return FPBinOp; }
4354
4355 /// Returns true if the recipe only uses the first lane of operand \p Op.
4356 bool usesFirstLaneOnly(const VPValue *Op) const override {
4358 "Op must be an operand of the recipe");
4359 return true;
4360 }
4361
4362protected:
4363#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4364 /// Print the recipe.
4365 void printRecipe(raw_ostream &O, const Twine &Indent,
4366 VPSlotTracker &SlotTracker) const override;
4367#endif
4368};
4369
4370/// A recipe for handling phi nodes of integer and floating-point inductions,
4371/// producing their scalar values. Before unrolling by UF the recipe represents
4372/// the VF*UF scalar values to be produced, or UF scalar values if only first
4373/// lane is used, and has 3 operands: IV, step and VF. Unrolling adds one extra
4374/// operand StartIndex to all unroll parts except part 0, as the recipe
4375/// represents the VF scalar values (this number of values is taken from
4376/// State.VF rather than from the VF operand) starting at IV + StartIndex.
4378 Instruction::BinaryOps InductionOpcode;
4379
4380public:
4384 : VPRecipeWithIRFlags(VPRecipeBase::VPScalarIVStepsSC, {IV, Step, VF},
4385 IV->getScalarType(), FMFs, DL),
4386 InductionOpcode(Opcode) {}
4387
4388 ~VPScalarIVStepsRecipe() override = default;
4389
4391 auto *NewR = new VPScalarIVStepsRecipe(
4392 getOperand(0), getOperand(1), getOperand(2), InductionOpcode,
4394 if (VPValue *StartIndex = getStartIndex())
4395 NewR->setStartIndex(StartIndex);
4396 return NewR;
4397 }
4398
4399 VP_CLASSOF_IMPL(VPRecipeBase::VPScalarIVStepsSC)
4400
4401 /// Generate the scalarized versions of the phi node as needed by their users.
4402 void execute(VPTransformState &State) override;
4403
4404 /// Return the cost of this VPScalarIVStepsRecipe.
4405 InstructionCost computeCost(ElementCount VF,
4406 VPCostContext &Ctx) const override;
4407
4408 VPValue *getStepValue() const { return getOperand(1); }
4409
4410 /// Return the number of scalars to produce per unroll part, used to compute
4411 /// StartIndex during unrolling.
4412 VPValue *getVFValue() const { return getOperand(2); }
4413
4414 /// Return the StartIndex, or null if known to be zero, valid only after
4415 /// unrolling.
4417 return getNumOperands() == 4 ? getOperand(3) : nullptr;
4418 }
4419
4420 /// Set or add the StartIndex operand.
4421 void setStartIndex(VPValue *StartIndex) {
4422 if (getNumOperands() == 4)
4423 setOperand(3, StartIndex);
4424 else
4425 addOperand(StartIndex);
4426 }
4427
4428 /// Returns true if this recipe produces scalar values for all VF lanes.
4429 bool doesGeneratePerAllLanes() const;
4430
4431 /// Returns true if the recipe only uses the first lane of operand \p Op.
4432 bool usesFirstLaneOnly(const VPValue *Op) const override {
4434 "Op must be an operand of the recipe");
4435 return true;
4436 }
4437
4438 Instruction::BinaryOps getInductionOpcode() const { return InductionOpcode; }
4439
4440protected:
4441#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4442 /// Print the recipe.
4443 void printRecipe(raw_ostream &O, const Twine &Indent,
4444 VPSlotTracker &SlotTracker) const override;
4445#endif
4446};
4447
4448/// CastInfo helper for casting from VPRecipeBase to a mixin class that is not
4449/// part of the VPRecipeBase class hierarchy (e.g. VPPhiAccessors,
4450/// VPIRMetadata).
4451namespace vpdetail {
4452template <typename VPMixin, typename... RecipeTys>
4454 : public DefaultDoCastIfPossible<VPMixin *, VPRecipeBase *,
4455 CastInfoMixinImpl<VPMixin, RecipeTys...>> {
4456 static_assert((std::is_base_of_v<VPMixin, RecipeTys> && ...),
4457 "Each type in RecipeTys must derive from VPMixin");
4458
4459 /// Used by isa.
4460 static bool isPossible(VPRecipeBase *R) { return isa<RecipeTys...>(R); }
4461
4462 /// Used by cast.
4463 static VPMixin *doCast(VPRecipeBase *R) {
4464 VPMixin *Out = nullptr;
4465 ((Out = dyn_cast<RecipeTys>(R)) || ...);
4466 assert(Out && "Illegal recipe for cast");
4467 return Out;
4468 }
4469 static VPMixin *castFailed() { return nullptr; }
4470};
4471} // namespace vpdetail
4472
4473/// Support casting from VPRecipeBase -> VPPhiAccessors.
4474template <>
4479
4480template <>
4485template <>
4487 : public ForwardToPointerCast<VPPhiAccessors, VPRecipeBase *,
4488 CastInfo<VPPhiAccessors, VPRecipeBase *>> {};
4489
4490/// Support casting from VPRecipeBase / VPUser -> VPWidenMemoryRecipe.
4491template <>
4496template <>
4501
4502/// Support casting from VPSingleDefRecipe -> VPWidenMemoryRecipe (loads only).
4503template <>
4507template <>
4512
4513/// Support casting from VPRecipeBase -> VPIRMetadata.
4514template <>
4521
4522template <>
4527template <>
4529 : public ForwardToPointerCast<VPIRMetadata, VPRecipeBase *,
4530 CastInfo<VPIRMetadata, VPRecipeBase *>> {};
4531
4532/// Support casting from VPSingleDefRecipe -> VPIRMetadata.
4533template <>
4536template <>
4541
4542/// VPBasicBlock serves as the leaf of the Hierarchical Control-Flow Graph. It
4543/// holds a sequence of zero or more VPRecipe's each representing a sequence of
4544/// output IR instructions. All PHI-like recipes must come before any non-PHI
4545/// recipes.
4546class LLVM_ABI_FOR_TEST VPBasicBlock : public VPBlockBase {
4547 friend class VPlan;
4548
4549 /// Use VPlan::createVPBasicBlock to create VPBasicBlocks.
4550 VPBasicBlock(const Twine &Name = "", VPRecipeBase *Recipe = nullptr)
4551 : VPBasicBlock(VPBasicBlockSC, Name) {
4552 if (Recipe)
4553 appendRecipe(Recipe);
4554 }
4555
4556public:
4558
4559protected:
4560 /// The VPRecipes held in the order of output instructions to generate.
4562
4563 VPBasicBlock(VPBlockTy BlockSC, const Twine &Name = "")
4564 : VPBlockBase(BlockSC, Name.str()) {
4565 // Set the parent of the list's sentinel, so end() iterators know their
4566 // block.
4567 Recipes.end().getNodePtr()->setParent(this);
4568 }
4569
4570public:
4571 ~VPBasicBlock() override {
4572 while (!Recipes.empty())
4573 Recipes.pop_back();
4574 }
4575
4576 /// Instruction iterators...
4581
4582 //===--------------------------------------------------------------------===//
4583 /// Recipe iterator methods
4584 ///
4585 inline iterator begin() { return Recipes.begin(); }
4586 inline const_iterator begin() const { return Recipes.begin(); }
4587 inline iterator end() { return Recipes.end(); }
4588 inline const_iterator end() const { return Recipes.end(); }
4589
4590 inline reverse_iterator rbegin() { return Recipes.rbegin(); }
4591 inline const_reverse_iterator rbegin() const { return Recipes.rbegin(); }
4592 inline reverse_iterator rend() { return Recipes.rend(); }
4593 inline const_reverse_iterator rend() const { return Recipes.rend(); }
4594
4595 inline size_t size() const { return Recipes.size(); }
4596 inline bool empty() const { return Recipes.empty(); }
4597 inline const VPRecipeBase &front() const { return Recipes.front(); }
4598 inline VPRecipeBase &front() { return Recipes.front(); }
4599 inline const VPRecipeBase &back() const { return Recipes.back(); }
4600 inline VPRecipeBase &back() { return Recipes.back(); }
4601
4602 /// Returns a reference to the list of recipes.
4604
4605 /// Returns a pointer to a member of the recipe list.
4606 static RecipeListTy VPBasicBlock::*getSublistAccess(VPRecipeBase *) {
4607 return &VPBasicBlock::Recipes;
4608 }
4609
4610 /// Method to support type inquiry through isa, cast, and dyn_cast.
4611 static inline bool classof(const VPBlockBase *V) {
4612 return V->getVPBlockID() == VPBlockBase::VPBasicBlockSC ||
4613 V->getVPBlockID() == VPBlockBase::VPIRBasicBlockSC;
4614 }
4615
4616 void insert(VPRecipeBase *Recipe, iterator InsertPt) {
4617 assert(Recipe && "No recipe to append.");
4618 assert(!Recipe->getParent() && "Recipe already in VPlan");
4619 assert(InsertPt.getNodeParent() == this &&
4620 "Insertion position not in this VPBasicBlock");
4621 Recipe->setParent(this);
4622 Recipes.insert(InsertPt, Recipe);
4623 }
4624
4625 /// Augment the existing recipes of a VPBasicBlock with an additional
4626 /// \p Recipe as the last recipe.
4627 void appendRecipe(VPRecipeBase *Recipe) { insert(Recipe, end()); }
4628
4629 /// The method which generates the output IR instructions that correspond to
4630 /// this VPBasicBlock, thereby "executing" the VPlan.
4631 void execute(VPTransformState *State) override;
4632
4633 /// Return the cost of this VPBasicBlock.
4634 InstructionCost cost(ElementCount VF, VPCostContext &Ctx) override;
4635
4636 /// Return the position of the first non-phi node recipe in the block.
4637 iterator getFirstNonPhi();
4638
4639 /// Returns an iterator range over the PHI-like recipes in the block.
4643
4644 /// Split current block at \p SplitAt by inserting a new block between the
4645 /// current block and its successors and moving all recipes starting at
4646 /// SplitAt to the new block. Returns the new block.
4647 VPBasicBlock *splitAt(iterator SplitAt);
4648
4649 VPRegionBlock *getEnclosingLoopRegion();
4650 const VPRegionBlock *getEnclosingLoopRegion() const;
4651
4652#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4653 /// Print this VPBsicBlock to \p O, prefixing all lines with \p Indent. \p
4654 /// SlotTracker is used to print unnamed VPValue's using consequtive numbers.
4655 ///
4656 /// Note that the numbering is applied to the whole VPlan, so printing
4657 /// individual blocks is consistent with the whole VPlan printing.
4658 void print(raw_ostream &O, const Twine &Indent,
4659 VPSlotTracker &SlotTracker) const override;
4660 using VPBlockBase::print; // Get the print(raw_stream &O) version.
4661#endif
4662
4663 /// If the block has multiple successors, return the branch recipe terminating
4664 /// the block. If there are no or only a single successor, return nullptr;
4665 VPRecipeBase *getTerminator();
4666 const VPRecipeBase *getTerminator() const;
4667
4668 /// Returns true if the block is exiting it's parent region.
4669 bool isExiting() const;
4670
4671 /// Clone the current block and it's recipes, without updating the operands of
4672 /// the cloned recipes.
4673 VPBasicBlock *clone() override;
4674
4675 /// Returns the predecessor block at index \p Idx with the predecessors as per
4676 /// the corresponding plain CFG. If the block is an entry block to a region,
4677 /// the first predecessor is the single predecessor of a region, and the
4678 /// second predecessor is the exiting block of the region.
4679 const VPBasicBlock *getCFGPredecessor(unsigned Idx) const;
4680
4681protected:
4682 /// Execute the recipes in the IR basic block \p BB.
4683 void executeRecipes(VPTransformState *State, BasicBlock *BB);
4684
4685 /// Connect the VPBBs predecessors' in the VPlan CFG to the IR basic block
4686 /// generated for this VPBB.
4687 void connectToPredecessors(VPTransformState &State);
4688
4689private:
4690 /// Create an IR BasicBlock to hold the output instructions generated by this
4691 /// VPBasicBlock, and return it. Update the CFGState accordingly.
4692 BasicBlock *createEmptyBasicBlock(VPTransformState &State);
4693};
4694
4695inline const VPBasicBlock *
4697 return getAsRecipe()->getParent()->getCFGPredecessor(Idx);
4698}
4699
4700/// A special type of VPBasicBlock that wraps an existing IR basic block.
4701/// Recipes of the block get added before the first non-phi instruction in the
4702/// wrapped block.
4703/// Note: At the moment, VPIRBasicBlock can only be used to wrap VPlan's
4704/// preheader block.
4705class VPIRBasicBlock : public VPBasicBlock {
4706 friend class VPlan;
4707
4708 BasicBlock *IRBB;
4709
4710 /// Use VPlan::createVPIRBasicBlock to create VPIRBasicBlocks.
4711 VPIRBasicBlock(BasicBlock *IRBB)
4712 : VPBasicBlock(VPIRBasicBlockSC,
4713 (Twine("ir-bb<") + IRBB->getName() + Twine(">")).str()),
4714 IRBB(IRBB) {}
4715
4716public:
4717 ~VPIRBasicBlock() override = default;
4718
4719 static inline bool classof(const VPBlockBase *V) {
4720 return V->getVPBlockID() == VPBlockBase::VPIRBasicBlockSC;
4721 }
4722
4723 /// The method which generates the output IR instructions that correspond to
4724 /// this VPBasicBlock, thereby "executing" the VPlan.
4725 void execute(VPTransformState *State) override;
4726
4727 VPIRBasicBlock *clone() override;
4728
4729 BasicBlock *getIRBasicBlock() const { return IRBB; }
4730};
4731
4732/// Track information about the canonical IV and header mask of a loop region.
4733/// TODO: Have it also track the canonical IV increment, subject of NUW flag.
4735 /// VPRegionValue for the canonical IV, whose allocation is managed by
4736 /// VPCanonicalIVInfo.
4737 std::unique_ptr<VPRegionValue> CanIV;
4738
4739 /// Optional VPRegionValue for the header mask, set when tail folding.
4740 std::unique_ptr<VPRegionValue> HeaderMask;
4741
4742 /// Whether the increment of the canonical IV may unsigned wrap or not.
4743 bool HasNUW = true;
4744
4745public:
4747 : CanIV(std::make_unique<VPRegionValue>(Ty, DL, Region)) {}
4748
4749 VPRegionValue *getRegionValue() { return CanIV.get(); }
4750 const VPRegionValue *getRegionValue() const { return CanIV.get(); }
4751
4752 VPRegionValue *getHeaderMask() const { return HeaderMask.get(); }
4753
4754 /// Create the header mask for the region and return it. Must only be called
4755 /// when no header mask exists yet.
4757 assert(!HeaderMask && "Header mask already created");
4758 HeaderMask = std::make_unique<VPRegionValue>(
4759 Type::getInt1Ty(CanIV->getType()->getContext()), DebugLoc::getUnknown(),
4760 CanIV->getDefiningRegion());
4761 return HeaderMask.get();
4762 }
4763
4764 bool hasNUW() const { return HasNUW; }
4765
4766 void clearNUW() { HasNUW = false; }
4767};
4768
4769/// VPRegionBlock represents a collection of VPBasicBlocks and VPRegionBlocks
4770/// which form a Single-Entry-Single-Exiting subgraph of the output IR CFG.
4771/// A VPRegionBlock may indicate that its contents are to be replicated several
4772/// times. This is designed to support predicated scalarization, in which a
4773/// scalar if-then code structure needs to be generated VF * UF times. Having
4774/// this replication indicator helps to keep a single model for multiple
4775/// candidate VF's. The actual replication takes place only once the desired VF
4776/// and UF have been determined.
4777class LLVM_ABI_FOR_TEST VPRegionBlock : public VPBlockBase {
4778 friend class VPlan;
4779
4780 /// Hold the Single Entry of the SESE region modelled by the VPRegionBlock.
4781 VPBlockBase *Entry;
4782
4783 /// Hold the Single Exiting block of the SESE region modelled by the
4784 /// VPRegionBlock.
4785 VPBlockBase *Exiting;
4786
4787 /// Holds the Canonical IV of the loop region along with additional
4788 /// information. If CanIVInfo is nullptr, the region is a replicating region.
4789 /// Loop regions retain their canonical IVs until they are dissolved, even if
4790 /// the canonical IV has no users.
4791 std::unique_ptr<VPCanonicalIVInfo> CanIVInfo;
4792
4793 /// Use VPlan::createLoopRegion() and VPlan::createReplicateRegion() to create
4794 /// VPRegionBlocks.
4795 VPRegionBlock(VPBlockBase *Entry, VPBlockBase *Exiting,
4796 const std::string &Name = "")
4797 : VPBlockBase(VPRegionBlockSC, Name), Entry(Entry), Exiting(Exiting) {
4798 if (Entry) {
4799 assert(!Entry->hasPredecessors() && "Entry block has predecessors.");
4800 assert(Exiting && "Must also pass Exiting if Entry is passed.");
4801 assert(!Exiting->hasSuccessors() && "Exit block has successors.");
4802 Entry->setParent(this);
4803 Exiting->setParent(this);
4804 }
4805 }
4806
4807 VPRegionBlock(Type *CanIVTy, DebugLoc DL, VPBlockBase *Entry,
4808 VPBlockBase *Exiting, const std::string &Name = "")
4809 : VPRegionBlock(Entry, Exiting, Name) {
4810 CanIVInfo = std::make_unique<VPCanonicalIVInfo>(CanIVTy, DL, this);
4811 }
4812
4813public:
4814 ~VPRegionBlock() override = default;
4815
4816 /// Method to support type inquiry through isa, cast, and dyn_cast.
4817 static inline bool classof(const VPBlockBase *V) {
4818 return V->getVPBlockID() == VPBlockBase::VPRegionBlockSC;
4819 }
4820
4821 const VPBlockBase *getEntry() const { return Entry; }
4822 VPBlockBase *getEntry() { return Entry; }
4823
4824 /// Set \p EntryBlock as the entry VPBlockBase of this VPRegionBlock. \p
4825 /// EntryBlock must have no predecessors.
4826 void setEntry(VPBlockBase *EntryBlock) {
4827 assert(!EntryBlock->hasPredecessors() &&
4828 "Entry block cannot have predecessors.");
4829 Entry = EntryBlock;
4830 EntryBlock->setParent(this);
4831 }
4832
4833 const VPBlockBase *getExiting() const { return Exiting; }
4834 VPBlockBase *getExiting() { return Exiting; }
4835
4836 /// Set \p ExitingBlock as the exiting VPBlockBase of this VPRegionBlock. \p
4837 /// ExitingBlock must have no successors.
4838 void setExiting(VPBlockBase *ExitingBlock) {
4839 assert(!ExitingBlock->hasSuccessors() &&
4840 "Exit block cannot have successors.");
4841 Exiting = ExitingBlock;
4842 ExitingBlock->setParent(this);
4843 }
4844
4845 /// Returns the pre-header VPBasicBlock of the loop region.
4847 assert(!isReplicator() && "should only get pre-header of loop regions");
4848 return getSinglePredecessor()->getExitingBasicBlock();
4849 }
4850
4851 /// An indicator whether this region is to generate multiple replicated
4852 /// instances of output IR corresponding to its VPBlockBases.
4853 bool isReplicator() const { return !CanIVInfo; }
4854
4855 /// Return the VPBranchOnMaskRecipe from the entry block of this replicating
4856 /// region.
4857 const VPBranchOnMaskRecipe *getEntryBranchOnMask() const;
4859 return const_cast<VPBranchOnMaskRecipe *>(
4860 static_cast<const VPRegionBlock *>(this)->getEntryBranchOnMask());
4861 }
4862
4863 /// The method which generates the output IR instructions that correspond to
4864 /// this VPRegionBlock, thereby "executing" the VPlan.
4865 void execute(VPTransformState *State) override;
4866
4867 // Return the cost of this region.
4868 InstructionCost cost(ElementCount VF, VPCostContext &Ctx) override;
4869
4870#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4871 /// Print this VPRegionBlock to \p O (recursively), prefixing all lines with
4872 /// \p Indent. \p SlotTracker is used to print unnamed VPValue's using
4873 /// consequtive numbers.
4874 ///
4875 /// Note that the numbering is applied to the whole VPlan, so printing
4876 /// individual regions is consistent with the whole VPlan printing.
4877 void print(raw_ostream &O, const Twine &Indent,
4878 VPSlotTracker &SlotTracker) const override;
4879 using VPBlockBase::print; // Get the print(raw_stream &O) version.
4880#endif
4881
4882 /// Clone all blocks in the single-entry single-exit region of the block and
4883 /// their recipes without updating the operands of the cloned recipes.
4884 VPRegionBlock *clone() override;
4885
4886 /// Remove the current region from its VPlan, connecting its predecessor to
4887 /// its entry, and its exiting block to its successor.
4888 void dissolveToCFGLoop();
4889
4890 /// Get the canonical IV increment instruction if it exists. Otherwise, create
4891 /// a new increment before the terminator and return it. The canonical IV
4892 /// increment is subject to DCE if unused, unlike the canonical IV itself.
4893 VPInstruction *getOrCreateCanonicalIVIncrement();
4894
4895 /// Return the canonical induction variable of the region, null for
4896 /// replicating regions.
4898 return CanIVInfo ? CanIVInfo->getRegionValue() : nullptr;
4899 }
4901 return CanIVInfo ? CanIVInfo->getRegionValue() : nullptr;
4902 }
4903
4904 /// Return the type of the canonical IV for loop regions.
4906 return CanIVInfo->getRegionValue()->getType();
4907 }
4908
4909 /// Return the header mask of the region, or null if not set.
4911 return CanIVInfo ? CanIVInfo->getHeaderMask() : nullptr;
4912 }
4913
4914 /// Return the header mask if it exists and is used, or null otherwise. The
4915 /// mask is materialized into concrete recipes only after costing, so cost and
4916 /// codegen accounting sites use this to skip an unused mask.
4918 VPRegionValue *HeaderMask = getHeaderMask();
4919 return HeaderMask && HeaderMask->getNumUsers() > 0 ? HeaderMask : nullptr;
4920 }
4921
4922 /// Create the header mask for the region and return it. Must only be called
4923 /// on loop regions that don't already have a header mask.
4925 assert(CanIVInfo && "Can only create header mask for loop regions");
4926 return CanIVInfo->createHeaderMask();
4927 }
4928
4929 /// Return the region values of the loop region (canonical IV, header mask)
4930 /// or an empty vector for replicate regions.
4932 if (!CanIVInfo)
4933 return {};
4934 SmallVector<VPRegionValue *, 2> R = {CanIVInfo->getRegionValue()};
4935 if (auto *HM = CanIVInfo->getHeaderMask())
4936 R.push_back(HM);
4937 return R;
4938 }
4939
4940 /// Indicates if NUW is set for the canonical IV increment, for loop regions.
4941 bool hasCanonicalIVNUW() const { return CanIVInfo->hasNUW(); }
4942
4943 /// Unsets NUW for the canonical IV increment \p Increment, for loop regions.
4945 assert(Increment && "Must provide increment to clear");
4946 Increment->dropPoisonGeneratingFlags();
4947 CanIVInfo->clearNUW();
4948 }
4949};
4950
4952 return getParent()->getParent();
4953}
4954
4956 return getParent()->getParent();
4957}
4958
4959/// VPlan models a candidate for vectorization, encoding various decisions take
4960/// to produce efficient output IR, including which branches, basic-blocks and
4961/// output IR instructions to generate, and their cost. VPlan holds a
4962/// Hierarchical-CFG of VPBasicBlocks and VPRegionBlocks rooted at an Entry
4963/// VPBasicBlock.
4964class VPlan {
4965 friend class VPlanPrinter;
4966 friend class VPSlotTracker;
4967
4968 /// VPBasicBlock corresponding to the original preheader. Used to place
4969 /// VPExpandSCEV recipes for expressions used during VPlan execution.
4970 /// When this VPlan is used for the epilogue vector loop, the entry models the
4971 /// main plan's entry and its edges move to the epilogue iteration check (see
4972 /// VPlanTransforms::modelGeneratedMainLoopBlocks).
4973 VPBasicBlock *Entry;
4974
4975 /// VPIRBasicBlock wrapping the header of the original scalar loop.
4976 VPIRBasicBlock *ScalarHeader;
4977
4978 /// Immutable list of VPIRBasicBlocks wrapping the exit blocks of the original
4979 /// scalar loop. Note that some exit blocks may be unreachable at the moment,
4980 /// e.g. if the scalar epilogue always executes.
4982
4983 /// Holds the VFs applicable to this VPlan.
4985
4986 /// Holds the UFs applicable to this VPlan. If empty, the VPlan is valid for
4987 /// any UF.
4989
4990 /// Holds the name of the VPlan, for printing.
4991 std::string Name;
4992
4993 /// Represents the trip count of the original loop, for folding
4994 /// the tail.
4995 VPValue *TripCount = nullptr;
4996
4997 /// Represents the vector trip count.
4998 VPSymbolicValue VectorTripCount;
4999
5000 /// Represents the vectorization factor of the loop.
5001 VPSymbolicValue VF;
5002
5003 /// Represents the unroll factor of the loop.
5004 VPSymbolicValue UF;
5005
5006 /// Represents the loop-invariant VF * UF of the vector loop region.
5007 VPSymbolicValue VFxUF;
5008
5009 /// Contains all the external definitions created for this VPlan, as a mapping
5010 /// from IR Values to VPIRValues.
5012
5013 /// Blocks allocated and owned by the VPlan. They will be deleted once the
5014 /// VPlan is destroyed.
5015 SmallVector<VPBlockBase *> CreatedBlocks;
5016
5017 /// Construct a VPlan with \p Entry to the plan and with \p ScalarHeader
5018 /// wrapping the original header of the scalar loop. The vector loop will have
5019 /// index type \p IdxTy.
5020 VPlan(VPBasicBlock *Entry, VPIRBasicBlock *ScalarHeader, Type *IdxTy)
5021 : Entry(Entry), ScalarHeader(ScalarHeader), VectorTripCount(IdxTy),
5022 VF(IdxTy), UF(IdxTy), VFxUF(IdxTy) {
5023 Entry->setPlan(this);
5024 assert(ScalarHeader->getNumSuccessors() == 0 &&
5025 "scalar header must be a leaf node");
5026 }
5027
5028public:
5029 /// Construct a VPlan for \p L. This will create VPIRBasicBlocks wrapping the
5030 /// original preheader and scalar header of \p L, to be used as entry and
5031 /// scalar header blocks of the new VPlan. The vector loop will have index
5032 /// type \p IdxTy.
5033 VPlan(Loop *L, Type *IdxTy);
5034
5035 /// Construct a VPlan with a new VPBasicBlock as entry, a VPIRBasicBlock
5036 /// wrapping \p ScalarHeaderBB and vector loop index of type \p IdxTy.
5037 VPlan(BasicBlock *ScalarHeaderBB, Type *IdxTy)
5038 : VectorTripCount(IdxTy), VF(IdxTy), UF(IdxTy), VFxUF(IdxTy) {
5039 setEntry(createVPBasicBlock("preheader"));
5040 ScalarHeader = createVPIRBasicBlock(ScalarHeaderBB);
5041 }
5042
5044
5046 Entry = VPBB;
5047 VPBB->setPlan(this);
5048 }
5049
5050 /// Generate the IR code for this VPlan.
5051 void execute(VPTransformState *State);
5052
5053 /// Return the cost of this plan.
5055
5056 VPBasicBlock *getEntry() { return Entry; }
5057 const VPBasicBlock *getEntry() const { return Entry; }
5058
5059 /// Returns the preheader of the vector loop region, if one exists, or null
5060 /// otherwise.
5062 const VPRegionBlock *VectorRegion = getVectorLoopRegion();
5063 return VectorRegion
5064 ? cast<VPBasicBlock>(VectorRegion->getSinglePredecessor())
5065 : nullptr;
5066 }
5067
5068 /// Returns the VPRegionBlock of the vector loop.
5071
5072 /// Returns true if this VPlan is for an outer loop, i.e., its vector
5073 /// loop region contains a nested loop region.
5074 LLVM_ABI_FOR_TEST bool isOuterLoop() const;
5075
5076 /// Returns true if the vector loop region is tail-folded.
5077 bool hasTailFolded() const {
5078 const VPRegionBlock *LoopRegion = getVectorLoopRegion();
5079 return LoopRegion && LoopRegion->getHeaderMask();
5080 }
5081
5082 /// Returns true if the plan requires a scalar epilogue after the vector
5083 /// loop. Must be called before removeBranchOnConst.
5085 const VPBasicBlock *MiddleVPBB = getMiddleBlock();
5086 return MiddleVPBB->getSingleSuccessor() == getScalarPreheader();
5087 }
5088
5089 /// Returns the 'middle' block of the plan, that is the block that selects
5090 /// whether to execute the scalar tail loop or the exit block from the loop
5091 /// latch. If there is an early exit from the vector loop, the middle block
5092 /// conceptully has the early exit block as third successor, split accross 2
5093 /// VPBBs. In that case, the second VPBB selects whether to execute the scalar
5094 /// tail loop or the exit block. If the scalar tail loop or exit block are
5095 /// known to always execute, the middle block may branch directly to that
5096 /// block. This function cannot be called once the vector loop region has been
5097 /// removed.
5099 VPRegionBlock *LoopRegion = getVectorLoopRegion();
5100 assert(
5101 LoopRegion &&
5102 "cannot call the function after vector loop region has been removed");
5103 // The middle block is always the last successor of the region.
5104 return cast<VPBasicBlock>(LoopRegion->getSuccessors().back());
5105 }
5106
5108 return const_cast<VPlan *>(this)->getMiddleBlock();
5109 }
5110
5111 /// Return the VPBasicBlock for the preheader of the scalar loop.
5114 getScalarHeader()->getSinglePredecessor());
5115 }
5116
5117 /// Return the VPIRBasicBlock wrapping the header of the scalar loop.
5118 VPIRBasicBlock *getScalarHeader() const { return ScalarHeader; }
5119
5120 /// Return an ArrayRef containing VPIRBasicBlocks wrapping the exit blocks of
5121 /// the original scalar loop.
5122 ArrayRef<VPIRBasicBlock *> getExitBlocks() const { return ExitBlocks; }
5123
5124 /// Returns true if \p VPBB is an exit block.
5125 bool isExitBlock(VPBlockBase *VPBB);
5126
5127 /// The trip count of the original loop.
5129 assert(TripCount && "trip count needs to be set before accessing it");
5130 return TripCount;
5131 }
5132
5133 /// Set the trip count assuming it is currently null; if it is not - use
5134 /// resetTripCount().
5135 void setTripCount(VPValue *NewTripCount) {
5136 assert(!TripCount && NewTripCount && "TripCount should not be set yet.");
5137 TripCount = NewTripCount;
5138 }
5139
5140 /// Resets the trip count for the VPlan. The caller must make sure all uses of
5141 /// the original trip count have been replaced.
5142 void resetTripCount(VPValue *NewTripCount) {
5143 assert(TripCount && NewTripCount && TripCount->user_empty() &&
5144 "TripCount must be set when resetting");
5145 TripCount = NewTripCount;
5146 }
5147
5148 /// The vector trip count.
5149 VPSymbolicValue &getVectorTripCount() { return VectorTripCount; }
5150
5151 /// Returns the VF of the vector loop region.
5152 VPSymbolicValue &getVF() { return VF; };
5153 const VPSymbolicValue &getVF() const { return VF; };
5154
5155 /// Returns the UF of the vector loop region.
5156 VPSymbolicValue &getUF() { return UF; };
5157
5158 /// Returns VF * UF of the vector loop region.
5159 VPSymbolicValue &getVFxUF() { return VFxUF; }
5160
5163 }
5164
5165 const DataLayout &getDataLayout() const {
5167 }
5168
5171 }
5172
5173 void addVF(ElementCount VF) { VFs.insert(VF); }
5174
5176 assert(hasVF(VF) && "Cannot set VF not already in plan");
5177 VFs.clear();
5178 VFs.insert(VF);
5179 }
5180
5181 /// Remove \p VF from the plan.
5183 assert(hasVF(VF) && "tried to remove VF not present in plan");
5184 VFs.remove(VF);
5185 }
5186
5187 bool hasVF(ElementCount VF) const { return VFs.count(VF); }
5188 bool hasScalableVF() const {
5189 return any_of(VFs, [](ElementCount VF) { return VF.isScalable(); });
5190 }
5191
5192 /// Returns an iterator range over all VFs of the plan.
5195 return VFs;
5196 }
5197
5198 /// Returns the single VF of the plan, asserting that the plan has exactly
5199 /// one VF.
5201 assert(VFs.size() == 1 && "expected plan with single VF");
5202 return VFs[0];
5203 }
5204
5205 bool hasScalarVFOnly() const {
5206 bool HasScalarVFOnly = VFs.size() == 1 && VFs[0].isScalar();
5207 assert(HasScalarVFOnly == hasVF(ElementCount::getFixed(1)) &&
5208 "Plan with scalar VF should only have a single VF");
5209 return HasScalarVFOnly;
5210 }
5211
5212 bool hasUF(unsigned UF) const { return UFs.empty() || UFs.contains(UF); }
5213
5214 /// Returns the concrete UF of the plan, after unrolling.
5215 unsigned getConcreteUF() const {
5216 assert(UFs.size() == 1 && "Expected a single UF");
5217 return UFs[0];
5218 }
5219
5220 void setUF(unsigned UF) {
5221 assert(hasUF(UF) && "Cannot set the UF not already in plan");
5222 UFs.clear();
5223 UFs.insert(UF);
5224 }
5225
5226 /// Returns true if the VPlan already has been unrolled, i.e. it has a single
5227 /// concrete UF.
5228 bool isUnrolled() const { return UFs.size() == 1; }
5229
5230 /// Return a string with the name of the plan and the applicable VFs and UFs.
5231 std::string getName() const;
5232
5233 void setName(const Twine &newName) { Name = newName.str(); }
5234
5235 /// Gets the live-in VPIRValue for \p V or adds a new live-in (if none exists
5236 /// yet) for \p V.
5238 assert(V && "Trying to get or add the VPIRValue of a null Value");
5239 auto [It, Inserted] = LiveIns.try_emplace(V);
5240 if (Inserted) {
5241 if (auto *CI = dyn_cast<ConstantInt>(V))
5242 It->second = new VPConstantInt(CI);
5243 else
5244 It->second = new VPIRValue(V);
5245 }
5246
5247 assert(isa<VPIRValue>(It->second) &&
5248 "Only VPIRValues should be in mapping");
5249 return It->second;
5250 }
5252 assert(V && "Trying to get or add the VPIRValue of a null VPIRValue");
5253 return getOrAddLiveIn(V->getValue());
5254 }
5255
5256 /// Return a VPIRValue wrapping i1 true.
5257 VPIRValue *getTrue() { return getConstantInt(1, 1); }
5258
5259 /// Return a VPIRValue wrapping i1 false.
5260 VPIRValue *getFalse() { return getConstantInt(1, 0); }
5261
5262 /// Return a VPIRValue wrapping the null value of type \p Ty.
5263 VPIRValue *getZero(Type *Ty) { return getConstantInt(Ty, 0); }
5264
5265 /// Return a VPIRValue wrapping the AllOnes value of type \p Ty.
5267 return getConstantInt(APInt::getAllOnes(Ty->getIntegerBitWidth()));
5268 }
5269
5270 /// Return a VPIRValue wrapping a ConstantInt with the given type and value.
5271 VPIRValue *getConstantInt(Type *Ty, uint64_t Val, bool IsSigned = false) {
5272 return getOrAddLiveIn(ConstantInt::get(Ty, Val, IsSigned));
5273 }
5274
5275 /// Return a VPIRValue wrapping a ConstantInt with the given bitwidth and
5276 /// value.
5278 bool IsSigned = false) {
5279 return getConstantInt(APInt(BitWidth, Val, IsSigned));
5280 }
5281
5282 /// Return a VPIRValue wrapping a ConstantInt with the given APInt value.
5284 return getOrAddLiveIn(ConstantInt::get(getContext(), Val));
5285 }
5286
5287 /// Return a VPIRValue wrapping a poison value of type \p Ty.
5289 return getOrAddLiveIn(PoisonValue::get(Ty));
5290 }
5291
5292 /// Return the live-in VPIRValue for \p V, if there is one or nullptr
5293 /// otherwise.
5294 VPIRValue *getLiveIn(Value *V) const { return LiveIns.lookup(V); }
5295
5296 /// Return the list of live-in VPValues available in the VPlan.
5297 auto getLiveIns() const { return LiveIns.values(); }
5298
5299#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
5300 /// Print the live-ins of this VPlan to \p O.
5301 void printLiveIns(raw_ostream &O) const;
5302
5303 /// Print this VPlan to \p O.
5304 LLVM_ABI_FOR_TEST void print(raw_ostream &O) const;
5305
5306 /// Print this VPlan in DOT format to \p O.
5307 LLVM_ABI_FOR_TEST void printDOT(raw_ostream &O) const;
5308
5309 /// Dump the plan to stderr (for debugging).
5310 LLVM_DUMP_METHOD void dump() const;
5311#endif
5312
5313 /// Clone the current VPlan, update all VPValues of the new VPlan and cloned
5314 /// recipes to refer to the clones, and return it.
5316
5317 /// Create a new VPBasicBlock with \p Name and containing \p Recipe if
5318 /// present. The returned block is owned by the VPlan and deleted once the
5319 /// VPlan is destroyed.
5321 VPRecipeBase *Recipe = nullptr) {
5322 auto *VPB = new VPBasicBlock(Name, Recipe);
5323 VPB->setPlan(this);
5324 VPB->setNumber(CreatedBlocks.size());
5325 CreatedBlocks.push_back(VPB);
5326 return VPB;
5327 }
5328
5329 /// Create a new loop region with a canonical IV using \p CanIVTy and
5330 /// \p DL. Use \p Name as the region's name and set entry and exiting blocks
5331 /// to \p Entry and \p Exiting respectively, if provided. The returned block
5332 /// is owned by the VPlan and deleted once the VPlan is destroyed.
5334 const std::string &Name = "",
5335 VPBlockBase *Entry = nullptr,
5336 VPBlockBase *Exiting = nullptr) {
5337 auto *VPB = new VPRegionBlock(CanIVTy, DL, Entry, Exiting, Name);
5338 VPB->setPlan(this);
5339 VPB->setNumber(CreatedBlocks.size());
5340 CreatedBlocks.push_back(VPB);
5341 return VPB;
5342 }
5343
5344 /// Create a new replicate region with \p Entry, \p Exiting and \p Name. The
5345 /// returned block is owned by the VPlan and deleted once the VPlan is
5346 /// destroyed.
5348 const std::string &Name = "") {
5349 auto *VPB = new VPRegionBlock(Entry, Exiting, Name);
5350 VPB->setPlan(this);
5351 VPB->setNumber(CreatedBlocks.size());
5352 CreatedBlocks.push_back(VPB);
5353 return VPB;
5354 }
5355
5356 /// Create a VPIRBasicBlock wrapping \p IRBB, but do not create
5357 /// VPIRInstructions wrapping the instructions in t\p IRBB. The returned
5358 /// block is owned by the VPlan and deleted once the VPlan is destroyed.
5360
5361 /// Create a VPIRBasicBlock from \p IRBB containing VPIRInstructions for all
5362 /// instructions in \p IRBB, except its terminator which is managed by the
5363 /// successors of the block in VPlan. The returned block is owned by the VPlan
5364 /// and deleted once the VPlan is destroyed.
5366
5367 unsigned getMaxBlockNumber() const { return CreatedBlocks.size(); }
5368
5369 /// Returns true if the VPlan is based on a loop with an early exit. Must be
5370 /// called before regions are dissolved.
5371 bool hasEarlyExit() const {
5372 // An early exit plan uses BranchOnTwoConds in the vector loop region latch.
5373 const VPRegionBlock *LoopRegion = getVectorLoopRegion();
5374 assert(LoopRegion && "vector loop region already dissolved");
5375 return LoopRegion->getNumSuccessors() > 1;
5376 }
5377
5378 /// Returns true if the scalar tail may execute after the vector loop, i.e.
5379 /// if the middle block is a predecessor of the scalar preheader. Note that
5380 /// this relies on unneeded branches to the scalar tail loop being removed.
5381 bool hasScalarTail() const {
5382 auto *ScalarPH = getScalarPreheader();
5383 return ScalarPH &&
5384 is_contained(ScalarPH->getPredecessors(), getMiddleBlock());
5385 }
5386
5387 /// The type of the canonical induction variable of the vector loop.
5388 Type *getIndexType() const { return VF.getType(); }
5389};
5390
5391#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
5392inline raw_ostream &operator<<(raw_ostream &OS, const VPlan &Plan) {
5393 Plan.print(OS);
5394 return OS;
5395}
5396#endif
5397
5398} // end namespace llvm
5399
5400#endif // LLVM_TRANSFORMS_VECTORIZE_VPLAN_H
bool IsScalable
SDValue Pred
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
aarch64 promote const
uint64_t uint64_t
static MCDisassembler::DecodeStatus addOperand(MCInst &Inst, const MCOperand &Opnd)
Rewrite undef for PHI
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
always inline
static void print(raw_ostream &Out, object::Archive::Kind Kind, T Val)
This file contains the simple types necessary to represent the attributes associated with functions a...
This file implements methods to test, set and extract typed bits from packed unsigned integers.
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
#define LLVM_ABI
Definition Compiler.h:211
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Definition Compiler.h:702
#define LLVM_ABI_FOR_TEST
Definition Compiler.h:216
#define LLVM_PACKED_START
Definition Compiler.h:583
dxil translate DXIL Translate Metadata
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
Hexagon Common GEP
static MaybeAlign getAlign(Value *Ptr)
This file defines an InstructionCost class that is used when calculating the cost of an instruction,...
static std::pair< Value *, APInt > getMask(Value *WideMask, unsigned Factor, ElementCount LeafValueEC)
static MemAccessTy getAccessType(const TargetTransformInfo &TTI, Instruction *Inst, Value *OperandVal)
Return the type of the memory being accessed.
#define I(x, y, z)
Definition MD5.cpp:57
This file implements a map that provides insertion order iteration.
static Interval intersect(const Interval &I1, const Interval &I2)
This file provides utility analysis objects describing memory locations.
#define T
#define P(N)
static StringRef getName(Value *V)
static bool mayHaveSideEffects(MachineInstr &MI)
SI Fold Operands
Func MI getDebugLoc()))
This file implements a set that has insertion order iteration characteristics.
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
static SymbolRef::Type getType(const Symbol *Sym)
Definition TapiFile.cpp:39
static const BasicSubtargetSubTypeKV * find(StringRef S, ArrayRef< BasicSubtargetSubTypeKV > A)
Find KV in array using binary search.
This file contains the declarations of the entities induced by Vectorization Plans,...
#define VP_CLASSOF_IMPL(VPRecipeID)
Definition VPlan.h:581
static const uint32_t IV[8]
Definition blake3_impl.h:83
Class for arbitrary precision integers.
Definition APInt.h:78
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
Definition APInt.h:230
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
const T & back() const
Get the last element.
Definition ArrayRef.h:150
bool empty() const
Check if the array is empty.
Definition ArrayRef.h:136
This class holds the attributes for a particular argument, parameter, function, or return value.
Definition Attributes.h:448
LLVM_ABI MemoryEffects getMemoryEffects() const
bool hasAttribute(Attribute::AttrKind Kind) const
Return true if the attribute exists in this set.
Definition Attributes.h:532
AttrKind
This enumeration lists the attributes that can be associated with parameters, function results,...
Definition Attributes.h:126
LLVM Basic Block Representation.
Definition BasicBlock.h:62
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this basic block belongs to.
LLVM_ABI LLVMContext & getContext() const
Get the context in which this basic block lives.
void setAttributes(AttributeList A)
Set the attributes for this call.
This class represents a function call, abstracting a target machine's calling convention.
This is the base class for all instructions that perform data casts.
Definition InstrTypes.h:512
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:740
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
A debug info location.
Definition DebugLoc.h:127
static DebugLoc getUnknown()
Definition DebugLoc.h:154
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
static constexpr ElementCount getFixed(ScalarTy MinVal)
Definition TypeSize.h:306
Utility class for floating point operations which can have information about relaxed accuracy require...
Definition Operator.h:202
Convenience struct for specifying and reasoning about fast-math flags.
Definition FMF.h:23
Class to represent function types.
Represents flags for the getelementptr instruction/expression.
static GEPNoWrapFlags fromRaw(unsigned Flags)
unsigned getRaw() const
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
A struct for saving information about induction variables.
InductionKind
This enum represents the kinds of inductions that we support.
bool isCast() const
The group of interleaved loads/stores sharing the same stride and close to each other.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
An instruction for reading from memory.
LoopVectorizationCostModel - estimates the expected speedups due to vectorization.
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
Metadata node.
Definition Metadata.h:1087
Root of the metadata hierarchy.
Definition Metadata.h:65
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
This class represents an assumption made using SCEV expressions which can be checked at run-time.
This class represents an analyzed expression in the program.
This class provides computation of slot numbers for LLVM Assembly writing.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
A SetVector that performs no allocations if smaller than a certain size.
Definition SetVector.h:346
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
iterator erase(const_iterator CI)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
An instruction for storing to memory.
A wrapper around a string literal that serves as a proxy for constructing global tables of StringRefs...
Definition StringRef.h:880
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
std::string str() const
Get the contents as an std::string.
Definition StringRef.h:222
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
LLVM_ABI std::string str() const
Return the twine contents as a std::string.
Definition Twine.cpp:17
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition Type.cpp:187
static LLVM_ABI IntegerType * getInt1Ty(LLVMContext &C)
Definition Type.cpp:291
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:252
void execute(VPTransformState &State) override
Generate the active lane mask phi of the vector loop.
VPActiveLaneMaskPHIRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:4191
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
VPActiveLaneMaskPHIRecipe(VPValue *StartMask, DebugLoc DL)
Definition VPlan.h:4185
~VPActiveLaneMaskPHIRecipe() override=default
VPBasicBlock serves as the leaf of the Hierarchical Control-Flow Graph.
Definition VPlan.h:4546
VPRecipeBase::RecipeListTy RecipeListTy
Definition VPlan.h:4557
RecipeListTy::const_iterator const_iterator
Definition VPlan.h:4578
void appendRecipe(VPRecipeBase *Recipe)
Augment the existing recipes of a VPBasicBlock with an additional Recipe as the last recipe.
Definition VPlan.h:4627
RecipeListTy::const_reverse_iterator const_reverse_iterator
Definition VPlan.h:4580
RecipeListTy::iterator iterator
Instruction iterators...
Definition VPlan.h:4577
RecipeListTy & getRecipeList()
Returns a reference to the list of recipes.
Definition VPlan.h:4603
iterator end()
Definition VPlan.h:4587
iterator begin()
Recipe iterator methods.
Definition VPlan.h:4585
RecipeListTy::reverse_iterator reverse_iterator
Definition VPlan.h:4579
iterator_range< iterator > phis()
Returns an iterator range over the PHI-like recipes in the block.
Definition VPlan.h:4640
iterator getFirstNonPhi()
Return the position of the first non-phi node recipe in the block.
Definition VPlan.cpp:224
~VPBasicBlock() override
Definition VPlan.h:4571
const_reverse_iterator rbegin() const
Definition VPlan.h:4591
reverse_iterator rend()
Definition VPlan.h:4592
RecipeListTy Recipes
The VPRecipes held in the order of output instructions to generate.
Definition VPlan.h:4561
VPRecipeBase & back()
Definition VPlan.h:4600
const VPRecipeBase & front() const
Definition VPlan.h:4597
const_iterator begin() const
Definition VPlan.h:4586
VPRecipeBase & front()
Definition VPlan.h:4598
const VPRecipeBase & back() const
Definition VPlan.h:4599
void insert(VPRecipeBase *Recipe, iterator InsertPt)
Definition VPlan.h:4616
bool empty() const
Definition VPlan.h:4596
const_iterator end() const
Definition VPlan.h:4588
static bool classof(const VPBlockBase *V)
Method to support type inquiry through isa, cast, and dyn_cast.
Definition VPlan.h:4611
static RecipeListTy VPBasicBlock::* getSublistAccess(VPRecipeBase *)
Returns a pointer to a member of the recipe list.
Definition VPlan.h:4606
reverse_iterator rbegin()
Definition VPlan.h:4590
friend class VPlan
Definition VPlan.h:4547
size_t size() const
Definition VPlan.h:4595
const_reverse_iterator rend() const
Definition VPlan.h:4593
VPBasicBlock(VPBlockTy BlockSC, const Twine &Name="")
Definition VPlan.h:4563
VPValue * getIncomingValue(unsigned Idx) const
Return incoming value number Idx.
Definition VPlan.h:3097
VPValue * getMask(unsigned Idx) const
Return mask number Idx.
Definition VPlan.h:3102
VPBlendRecipe(PHINode *Phi, ArrayRef< VPValue * > Operands, const VPIRFlags &Flags, DebugLoc DL)
The blend operation is a User of the incoming values and of their respective masks,...
Definition VPlan.h:3056
unsigned getNumIncomingValues() const
Return the number of incoming values, taking into account when normalized the first incoming value wi...
Definition VPlan.h:3092
void execute(VPTransformState &State) override
The method which generates the output IR instructions that correspond to this VPRecipe,...
Definition VPlan.h:3114
VPBlendRecipe * cloneWithOperands(ArrayRef< VPValue * > NewOperands)
Definition VPlan.h:3079
VPBlendRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:3077
void setMask(unsigned Idx, VPValue *V)
Set mask number Idx to V.
Definition VPlan.h:3108
bool isNormalized() const
A normalized blend is one that has an odd number of operands, whereby the first operand does not have...
Definition VPlan.h:3088
VPBlockBase is the building block of the Hierarchical Control-Flow Graph.
Definition VPlan.h:95
void setSuccessors(ArrayRef< VPBlockBase * > NewSuccs)
Set each VPBasicBlock in NewSuccss as successor of this VPBlockBase.
Definition VPlan.h:305
VPRegionBlock * getParent()
Definition VPlan.h:193
const VPlan * getPlan() const
Definition VPlan.h:198
void setPlan(VPlan *ParentPlan)
Sets the pointer of the plan containing the block.
Definition VPlan.h:201
VPBlocksTy & getPredecessors()
Definition VPlan.h:229
iterator_range< VPBlockBase ** > predecessors()
Definition VPlan.h:226
LLVM_DUMP_METHOD void dump() const
Dump this VPBlockBase to dbgs().
Definition VPlan.h:381
void setName(const Twine &newName)
Definition VPlan.h:186
size_t getNumSuccessors() const
Definition VPlan.h:243
iterator_range< VPBlockBase ** > successors()
Definition VPlan.h:225
virtual void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const =0
Print plain-text dump of this VPBlockBase to O, prefixing all lines with Indent.
bool hasPredecessors() const
Returns true if this block has any predecessors.
Definition VPlan.h:223
void swapSuccessors()
Swap successors of the block. The block must have exactly 2 successors.
Definition VPlan.h:327
void printSuccessors(raw_ostream &O, const Twine &Indent) const
Print the successors of this block to O, prefixing all lines with Indent.
Definition VPlan.cpp:626
SmallVectorImpl< VPBlockBase * > VPBlocksTy
Definition VPlan.h:180
virtual ~VPBlockBase()=default
unsigned getNumber() const
Return the unique number of the block.
Definition VPlan.h:347
void setNumber(unsigned N)
Set the unique number of the block, used for dominator tree.
Definition VPlan.h:350
unsigned getIndexForSuccessor(const VPBlockBase *Succ) const
Returns the index for Succ in the blocks successor list.
Definition VPlan.h:340
size_t getNumPredecessors() const
Definition VPlan.h:244
void setPredecessors(ArrayRef< VPBlockBase * > NewPreds)
Set each VPBasicBlock in NewPreds as predecessor of this VPBlockBase.
Definition VPlan.h:296
VPBlockBase * getEnclosingBlockWithPredecessors()
Definition VPlan.cpp:216
unsigned getIndexForPredecessor(const VPBlockBase *Pred) const
Returns the index for Pred in the blocks predecessors list.
Definition VPlan.h:333
enum :unsigned char { VPRegionBlockSC, VPBasicBlockSC, VPIRBasicBlockSC } VPBlockTy
An enumeration for keeping track of the concrete subclass of VPBlockBase that are actually instantiat...
Definition VPlan.h:103
bool hasSuccessors() const
Returns true if this block has any successors.
Definition VPlan.h:221
const VPBlocksTy & getPredecessors() const
Definition VPlan.h:228
virtual VPBlockBase * clone()=0
Clone the current block and it's recipes without updating the operands of the cloned recipes,...
virtual InstructionCost cost(ElementCount VF, VPCostContext &Ctx)=0
Return the cost of the block.
VPlan * getPlan()
Definition VPlan.h:197
const VPRegionBlock * getParent() const
Definition VPlan.h:194
const std::string & getName() const
Definition VPlan.h:184
void clearSuccessors()
Remove all the successors of this block.
Definition VPlan.h:315
void setTwoSuccessors(VPBlockBase *IfTrue, VPBlockBase *IfFalse)
Set two given VPBlockBases IfTrue and IfFalse to be the two successors of this VPBlockBase.
Definition VPlan.h:287
VPBlockBase * getSinglePredecessor() const
Definition VPlan.h:239
virtual void execute(VPTransformState *State)=0
The method which generates the output IR that correspond to this VPBlockBase, thereby "executing" the...
const VPBlocksTy & getHierarchicalSuccessors()
Definition VPlan.h:263
void clearPredecessors()
Remove all the predecessor of this block.
Definition VPlan.h:312
friend class VPBlockUtils
Definition VPlan.h:96
unsigned getVPBlockID() const
Definition VPlan.h:191
void printAsOperand(raw_ostream &OS, bool PrintType=false) const
Definition VPlan.h:359
void swapPredecessors()
Swap predecessors of the block.
Definition VPlan.h:319
VPBlocksTy & getSuccessors()
Definition VPlan.h:218
VPBlockBase * getEnclosingBlockWithSuccessors()
An Enclosing Block of a block B is any block containing B, including B itself.
Definition VPlan.cpp:208
void setOneSuccessor(VPBlockBase *Successor)
Set a given VPBlockBase Successor as the single successor of this VPBlockBase.
Definition VPlan.h:276
void setParent(VPRegionBlock *P)
Definition VPlan.h:203
VPBlockBase * getSingleHierarchicalPredecessor()
Definition VPlan.h:269
VPBlockBase * getSingleSuccessor() const
Definition VPlan.h:233
const VPBlocksTy & getSuccessors() const
Definition VPlan.h:217
VPBlockBase(VPBlockTy SC, const std::string &N)
Definition VPlan.h:390
A recipe for generating conditional branches on the bits of a mask.
Definition VPlan.h:3601
VPBranchOnMaskRecipe(VPValue *BlockInMask, DebugLoc DL, const VPIRMetadata &Metadata={})
Definition VPlan.h:3603
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
Definition VPlan.h:3624
VPBranchOnMaskRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:3608
bool usesScalars(const VPValue *Op) const override
Returns true if the recipe uses scalars of operand Op.
Definition VPlan.h:3632
VPlan-based builder utility similar to IRBuilder.
VPRegionValue * createHeaderMask()
Create the header mask for the region and return it.
Definition VPlan.h:4756
VPRegionValue * getHeaderMask() const
Definition VPlan.h:4752
VPRegionValue * getRegionValue()
Definition VPlan.h:4749
VPCanonicalIVInfo(Type *Ty, DebugLoc DL, VPRegionBlock *Region)
Definition VPlan.h:4746
const VPRegionValue * getRegionValue() const
Definition VPlan.h:4750
bool hasNUW() const
Definition VPlan.h:4764
A recipe for handling scalar conditional induction PHIs.
Definition VPlan.h:2996
const SCEV * getStepSCEV() const
Returns the conditional induction step SCEV expression.
Definition VPlan.h:3014
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Compute the cost of this recipe either using a recipe's specialized implementation or using the legac...
VPConditionalInductionPHIRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:3016
PHINode * getPHINode() const
Returns the underlying PHINode.
Definition VPlan.h:3011
VPConditionalInductionPHIRecipe(PHINode &Phi, VPValue &Start, VPValue &BackedgeValue, const SCEV *StepSCEV)
Definition VPlan.h:3000
bool usesFirstLaneOnly(const VPValue *Op) const override
Returns true if the recipe only uses the first lane of operand Op.
Definition VPlan.h:3041
void execute(VPTransformState &) override
Generate the phi nodes.
Definition VPlan.h:3027
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
~VPConditionalInductionPHIRecipe() override=default
static bool classof(const VPHeaderPHIRecipe *R)
Definition VPlan.h:3023
VPCurrentIterationPHIRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:4223
VPCurrentIterationPHIRecipe(VPValue *StartIV, DebugLoc DL)
Definition VPlan.h:4217
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPCurrentIterationPHIRecipe.
Definition VPlan.h:4235
void execute(VPTransformState &State) override
Generate the phi nodes.
Definition VPlan.h:4229
bool usesFirstLaneOnly(const VPValue *Op) const override
Returns true if the recipe only uses the first lane of operand Op.
Definition VPlan.h:4242
~VPCurrentIterationPHIRecipe() override=default
InductionDescriptor::InductionKind getInductionKind() const
Definition VPlan.h:4353
VPValue * getIndex() const
Definition VPlan.h:4350
const FPMathOperator * getFPBinOp() const
Definition VPlan.h:4352
VPDerivedIVRecipe(InductionDescriptor::InductionKind Kind, const FPMathOperator *FPBinOp, VPValue *Start, VPValue *Current, VPValue *Step, const VPIRFlags::WrapFlagsTy &Flags={})
Definition VPlan.h:4324
VPValue * getStepValue() const
Definition VPlan.h:4351
void execute(VPTransformState &State) override
The method which generates the output IR instructions that correspond to this VPRecipe,...
Definition VPlan.h:4341
VPDerivedIVRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:4334
~VPDerivedIVRecipe() override=default
bool usesFirstLaneOnly(const VPValue *Op) const override
Returns true if the recipe only uses the first lane of operand Op.
Definition VPlan.h:4356
VPValue * getStartValue() const
Definition VPlan.h:4349
Template specialization of the standard LLVM dominator tree utility for VPBlockBases.
void execute(VPTransformState &State) override
The method which generates the output IR instructions that correspond to this VPRecipe,...
Definition VPlan.h:4158
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPExpandSCEVRecipe.
Definition VPlan.h:4163
VPExpandSCEVRecipe(const SCEV *Expr, bool ExpandInIR=false)
bool expandInIR() const
Definition VPlan.h:4171
const SCEV * getSCEV() const
Definition VPlan.h:4169
VPExpandSCEVRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:4152
~VPExpandSCEVRecipe() override=default
void execute(VPTransformState &State) override
Method for generating code, must not be called as this recipe is abstract.
Definition VPlan.h:3789
bool isVectorToScalar() const
Returns true if this VPExpressionRecipe produces a single scalar.
VPExpressionRecipe(VPWidenCastRecipe *Ext, VPWidenRecipe *Neg, VPReductionRecipe *Red)
Definition VPlan.h:3698
VPExpressionRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:3758
SmallVector< VPSingleDefRecipe * > decompose()
Return and insert the recipes of the expression back into the VPlan, directly before the current reci...
bool usesFirstLaneOnly(const VPValue *Op) const override
Returns true if the recipe only uses the first lane of operand Op.
~VPExpressionRecipe() override
Definition VPlan.h:3746
VPExpressionRecipe(VPSingleDefRecipe *InLoopOp, VPWidenIntrinsicRecipe *VPMerge)
Definition VPlan.h:3738
ExpressionTypes getExpressionType() const
Returns the expression type of this recipe.
Definition VPlan.h:3781
VPExpressionRecipe(VPWidenCastRecipe *Ext, VPReductionRecipe *Red)
Definition VPlan.h:3696
bool mayHaveSideEffects() const
Returns true if this expression contains recipes that may have side effects.
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Compute the cost of this recipe either using a recipe's specialized implementation or using the legac...
bool mayReadOrWriteMemory() const
Returns true if this expression contains recipes that may read from or write to memory.
VPExpressionRecipe(VPWidenCastRecipe *Ext0, VPWidenCastRecipe *Ext1, VPWidenRecipe *Mul, VPReductionRecipe *Red)
Definition VPlan.h:3714
VPExpressionRecipe(ExpressionTypes ExpressionType, ArrayRef< VPSingleDefRecipe * > ExpressionRecipes)
Construct a new VPExpressionRecipe by internalizing recipes in ExpressionRecipes.
VPExpressionRecipe(VPWidenCastRecipe *Ext0, VPWidenCastRecipe *Ext1, VPWidenRecipe *Mul, VPWidenRecipe *Neg, VPReductionRecipe *Red)
Definition VPlan.h:3718
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
unsigned getVFScaleFactor() const
Definition VPlan.h:3783
VPExpressionRecipe(VPWidenRecipe *Mul, VPReductionRecipe *Red)
Definition VPlan.h:3712
A pure virtual base class for all recipes modeling header phis, including phis for first order recurr...
Definition VPlan.h:2486
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this header phi recipe.
const VPRecipeBase * getAsRecipe() const override
Return a VPRecipeBase* to the current object.
Definition VPlan.h:2493
void addBackedgeValue(VPValue *V)
Add V as the incoming value from the loop backedge.
Definition VPlan.h:2535
static bool classof(const VPSingleDefRecipe *R)
Definition VPlan.h:2506
static bool classof(const VPValue *V)
Definition VPlan.h:2503
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override=0
Print the recipe.
VPHeaderPHIRecipe(VPRecipeTy VPRecipeID, Instruction *UnderlyingInstr, VPValue *Start, Type *ResultTy, DebugLoc DL=DebugLoc::getUnknown())
Definition VPlan.h:2488
virtual VPValue * getBackedgeValue()
Returns the incoming value from the loop backedge.
Definition VPlan.h:2529
void setBackedgeValue(VPValue *V)
Update the incoming value from the loop backedge.
Definition VPlan.h:2532
VPValue * getStartValue()
Returns the start value of the phi, if one is set.
Definition VPlan.h:2518
void setStartValue(VPValue *V)
Update the start value of the recipe.
Definition VPlan.h:2526
static bool classof(const VPRecipeBase *R)
Method to support type inquiry through isa, cast, and dyn_cast.
Definition VPlan.h:2499
VPValue * getStartValue() const
Definition VPlan.h:2521
void execute(VPTransformState &State) override=0
Generate the phi nodes.
~VPHeaderPHIRecipe() override=default
A recipe representing a sequence of load -> update -> store as part of a histogram operation.
Definition VPlan.h:2201
VPHistogramRecipe(HistogramUpdateKind UpdateKind, ArrayRef< VPValue * > Operands, const VPIRMetadata &Metadata={}, DebugLoc DL=DebugLoc::getUnknown())
Definition VPlan.h:2206
void execute(VPTransformState &State) override
Produce a vectorized histogram operation.
bool usesFirstLaneOnly(const VPValue *Op) const override
Returns true if the recipe only uses the first lane of operand Op.
Definition VPlan.h:2235
VPHistogramRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:2215
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPHistogramRecipe.
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
VPValue * getMask() const
Return the mask operand if one was provided, or a null pointer if all lanes should be executed uncond...
Definition VPlan.h:2230
VP_CLASSOF_IMPL(VPRecipeBase::VPHistogramSC)
~VPHistogramRecipe() override=default
Manage IR attributes for call recipes.
Definition VPlan.h:1269
void printFnAttrs(raw_ostream &O) const
Print function attributes carried with this object.
void printRetAttrs(raw_ostream &O) const
Print return-value attributes carried with this object.
MemoryEffects getMemoryEffects(AttributeSet CalleeFnAttrs) const
Returns the memory effects of a call with these attributes to a callee with function attributes Calle...
Definition VPlan.h:1293
VPIRAttributes()=default
VPIRAttributes(AttributeList CallAttrs)
Definition VPlan.h:1275
bool hasFnAttr(Attribute::AttrKind Kind, AttributeSet CalleeFnAttrs) const
Returns true if the call site or CalleeFnAttrs has Kind.
Definition VPlan.h:1298
void intersectAttrs(const VPIRAttributes &Other, LLVMContext &Ctx)
Keep only the attributes valid for both this and Other.
void printParamAttrs(raw_ostream &O, unsigned ArgIdx) const
Print per-arg attributes for argument ArgIdx.
void applyAttrs(CallInst &WideCall) const
Apply the stored attributes to the widened call WideCall.
Definition VPlan.h:1287
A special type of VPBasicBlock that wraps an existing IR basic block.
Definition VPlan.h:4705
void execute(VPTransformState *State) override
The method which generates the output IR instructions that correspond to this VPBasicBlock,...
Definition VPlan.cpp:438
BasicBlock * getIRBasicBlock() const
Definition VPlan.h:4729
static bool classof(const VPBlockBase *V)
Definition VPlan.h:4719
~VPIRBasicBlock() override=default
friend class VPlan
Definition VPlan.h:4706
VPIRBasicBlock * clone() override
Clone the current block and it's recipes, without updating the operands of the cloned recipes.
Definition VPlan.cpp:463
Class to record and manage LLVM IR flags.
Definition VPlan.h:683
WrapFlagsTy getNoWrapFlagsOrNone() const
Definition VPlan.h:1007
FastMathFlagsTy FMFs
Definition VPlan.h:775
ReductionFlagsTy ReductionFlags
Definition VPlan.h:777
VPIRFlags(RecurKind Kind, bool IsOrdered, bool IsInLoop, FastMathFlags FMFs)
Definition VPlan.h:868
LLVM_ABI_FOR_TEST bool flagsValidForOpcode(unsigned Opcode) const
Returns true if the set flags are valid for Opcode.
VPIRFlags(DisjointFlagsTy DisjointFlags)
Definition VPlan.h:848
VPIRFlags(WrapFlagsTy WrapFlags)
Definition VPlan.h:834
WrapFlagsTy WrapFlags
Definition VPlan.h:769
void printFlags(raw_ostream &O) const
VPIRFlags(CmpInst::Predicate Pred, FastMathFlags FMFs)
Definition VPlan.h:827
bool hasFastMathFlags() const
Returns true if the recipe has fast-math flags.
Definition VPlan.h:978
static LLVM_ABI_FOR_TEST VPIRFlags getDefaultFlags(unsigned Opcode, Type *ResultTy=nullptr)
Returns default flags for Opcode and scalar ResultTy for opcodes that support it, asserts otherwise.
bool isReductionOrdered() const
Definition VPlan.h:1033
TruncFlagsTy TruncFlags
Definition VPlan.h:770
CmpInst::Predicate getPredicate() const
Definition VPlan.h:950
WrapFlagsTy getNoWrapFlags() const
Definition VPlan.h:1017
LLVM_ABI_FOR_TEST FastMathFlags getFastMathFlagsOrNone() const
uint8_t AllFlags[2]
Definition VPlan.h:778
ExactFlagsTy ExactFlags
Definition VPlan.h:772
bool hasNoSignedWrap() const
Definition VPlan.h:996
void intersectFlags(const VPIRFlags &Other)
Only keep flags also present in Other.
bool isDisjoint() const
Definition VPlan.h:1021
VPIRFlags(TruncFlagsTy TruncFlags)
Definition VPlan.h:839
VPIRFlags(FastMathFlags FMFs)
Definition VPlan.h:844
VPIRFlags(NonNegFlagsTy NonNegFlags)
Definition VPlan.h:853
VPIRFlags(CmpInst::Predicate Pred)
Definition VPlan.h:822
uint8_t GEPFlagsStorage
Definition VPlan.h:773
VPIRFlags(ExactFlagsTy ExactFlags)
Definition VPlan.h:858
GEPNoWrapFlags getGEPNoWrapFlags() const
Definition VPlan.h:968
bool hasPredicate() const
Returns true if the recipe has a comparison predicate.
Definition VPlan.h:973
LLVM_ABI_FOR_TEST bool hasRequiredFlagsForOpcode(unsigned Opcode, Type *ResultTy) const
Returns true if Opcode with scalar result type ResultTy has its required flags set.
DisjointFlagsTy DisjointFlags
Definition VPlan.h:771
void setPredicate(CmpInst::Predicate Pred)
Definition VPlan.h:958
bool hasNoUnsignedWrap() const
Definition VPlan.h:985
FCmpFlagsTy FCmpFlags
Definition VPlan.h:776
NonNegFlagsTy NonNegFlags
Definition VPlan.h:774
bool isReductionInLoop() const
Definition VPlan.h:1039
void dropPoisonGeneratingFlags()
Drop all poison-generating flags.
Definition VPlan.h:878
void applyFlags(Instruction &I) const
Apply the IR flags to I.
Definition VPlan.h:915
VPIRFlags(GEPNoWrapFlags GEPFlags)
Definition VPlan.h:863
uint8_t CmpPredStorage
Definition VPlan.h:768
RecurKind getRecurKind() const
Definition VPlan.h:1027
VPIRFlags(Instruction &I)
Definition VPlan.h:784
Instruction & getInstruction() const
Definition VPlan.h:1773
bool usesFirstPartOnly() const override
Returns true if the recipe only uses the first part of all operands.
Definition VPlan.h:1782
~VPIRInstruction() override=default
void execute(VPTransformState &State) override
The method which generates the output IR instructions that correspond to this VPRecipe,...
VPIRInstruction * clone() override
Clone the current recipe.
Definition VPlan.h:1760
bool usesFirstLaneOnly(const VPValue *Op) const override
Returns true if the VPUser only uses the first lane of operand Op.
Definition VPlan.h:1784
static LLVM_ABI_FOR_TEST VPIRInstruction * create(Instruction &I)
Create a new VPIRPhi for \I , if it is a PHINode, otherwise create a VPIRInstruction.
LLVM_ABI_FOR_TEST InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPIRInstruction.
bool usesScalars(const VPValue *Op) const override
Returns true if the VPUser uses scalars of operand Op.
Definition VPlan.h:1775
VPIRInstruction(Instruction &I)
VPIRInstruction::create() should be used to create VPIRInstructions, as subclasses may need to be cre...
Definition VPlan.h:1748
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
Helper to manage IR metadata for recipes.
Definition VPlan.h:1152
MDNode * getBranchWeights() const
Returns the branch weights recorded for this terminator, preferring real profile data over an estimat...
Definition VPlan.h:1241
VPIRMetadata & operator=(const VPIRMetadata &Other)=default
MDNode * getMetadata(unsigned Kind) const
Get metadata of kind Kind. Returns nullptr if not found.
Definition VPlan.h:1222
VPIRMetadata(Instruction &I)
Adds metatadata that can be preserved from the original instruction I.
Definition VPlan.h:1181
VPIRMetadata(const VPIRMetadata &Other)=default
Copy constructor for cloning.
VPIRMetadata()=default
void setEstimatedBranchWeights(MDNode *Node)
Set estimated branch weights to Node.
Definition VPlan.h:1252
void applyMetadata(Instruction &I) const
Add all metadata to I.
void setMetadata(unsigned Kind, MDNode *Node)
Set metadata with kind Kind to Node.
Definition VPlan.h:1201
void eraseMetadata(unsigned Kind)
Remove the metadata of kind Kind, if present.
Definition VPlan.h:1213
bool hasEstimatedBranchWeights() const
Returns true if the weights returned by getBranchWeights are estimated.
Definition VPlan.h:1247
This is a concrete Recipe that models a single VPlan-level instruction.
Definition VPlan.h:1322
unsigned getNumOperandsWithoutMask() const
Returns the number of operands, excluding the mask if the VPInstruction is masked.
Definition VPlan.h:1562
bool doesGenerateSingleScalar() const
Returns true if the recipe produces a single scalar value.
Definition VPlan.h:1609
iterator_range< operand_iterator > operandsWithoutMask()
Returns an iterator range over the operands excluding the mask operand if present.
Definition VPlan.h:1582
VPInstruction * clone() override
Clone the current recipe.
Definition VPlan.h:1517
@ ExtractLastActive
Extracts the last active lane from a set of vectors.
Definition VPlan.h:1437
@ Intrinsic
Calls a scalar intrinsic. The intrinsic ID is the last operand.
Definition VPlan.h:1449
@ ExtractLane
Extracts a single lane (first operand) from a set of vector operands.
Definition VPlan.h:1427
@ ExitingIVValue
Compute the exiting value of a wide induction after vectorization, that is the value of the last lane...
Definition VPlan.h:1441
@ WideIVStep
Scale the first operand (vector step) by the second operand (scalar-step).
Definition VPlan.h:1445
@ ResumeForEpilogue
Explicit user for values in the main VPlan, used by the epilogue vector loop.
Definition VPlan.h:1431
@ Unpack
Extracts all lanes from its (non-scalable) vector operand.
Definition VPlan.h:1378
@ ReductionStartVector
Start vector for reductions with 3 operands: the original start value, the identity value for the red...
Definition VPlan.h:1423
@ BuildVector
Creates a fixed-width vector containing all operands.
Definition VPlan.h:1373
@ CanonicalIVIncrementForPart
Definition VPlan.h:1358
@ ComputeReductionResult
Reduce the operands to the final reduction result using the operation specified via the operation's V...
Definition VPlan.h:1381
bool hasResult() const
Definition VPlan.h:1549
iterator_range< const_operand_iterator > operandsWithoutMask() const
Definition VPlan.h:1585
void addMask(VPValue *Mask)
Add mask Mask to an unmasked VPInstruction, if it needs masking.
Definition VPlan.h:1567
StringRef getName() const
Returns the symbolic name assigned to the VPInstruction.
Definition VPlan.h:1612
VPInstruction(unsigned Opcode, ArrayRef< VPValue * > Operands, const VPIRFlags &Flags={}, const VPIRMetadata &MD={}, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="", Type *ResultTy=nullptr, const VPIRAttributes &Attrs={}, std::optional< bool > GeneratesSingleScalar=std::nullopt)
unsigned getOpcode() const
Definition VPlan.h:1531
void setName(StringRef NewName)
Set the symbolic name for the VPInstruction.
Definition VPlan.h:1615
bool usesScalars(const VPValue *Op) const override
Returns true if the recipe only uses scalars of operand Op.
Definition VPlan.h:1596
bool usesFirstLaneOnly(const VPValue *Op) const override
Returns true if the recipe only uses the first lane of operand Op.
VPValue * getMask() const
Returns the mask for the VPInstruction.
Definition VPlan.h:1578
VPInstruction * cloneWithOperands(ArrayRef< VPValue * > NewOperands, Type *ResultTy=nullptr)
Definition VPlan.h:1521
unsigned getNumOperandsForOpcode() const
Return the number of operands determined by the opcode of the VPInstruction, excluding mask.
bool isMasked() const
Returns true if the VPInstruction has a mask operand.
Definition VPlan.h:1552
A common base class for interleaved memory operations.
Definition VPlan.h:3139
virtual unsigned getNumStoreOperands() const =0
Returns the number of stored operands of this interleave group.
VPInterleaveBase(VPRecipeTy SC, const InterleaveGroup< Instruction > *IG, ArrayRef< VPValue * > Operands, ArrayRef< VPValue * > StoredValues, VPValue *Mask, bool NeedsMaskForGaps, const VPIRMetadata &MD, DebugLoc DL)
Definition VPlan.h:3151
bool usesFirstLaneOnly(const VPValue *Op) const override=0
Returns true if the recipe only uses the first lane of operand Op.
bool needsMaskForGaps() const
Return true if the access needs a mask because of the gaps.
Definition VPlan.h:3201
void execute(VPTransformState &State) override
The method which generates the output IR instructions that correspond to this VPRecipe,...
Definition VPlan.h:3207
static bool classof(const VPUser *U)
Definition VPlan.h:3183
Instruction * getInsertPos() const
Definition VPlan.h:3205
static bool classof(const VPRecipeBase *R)
Definition VPlan.h:3178
const InterleaveGroup< Instruction > * getInterleaveGroup() const
Definition VPlan.h:3203
VPValue * getMask() const
Return the mask used by this recipe.
Definition VPlan.h:3195
ArrayRef< VPValue * > getStoredValues() const
Return the VPValues stored by this interleave group.
Definition VPlan.h:3224
VPInterleaveBase * clone() override=0
Clone the current recipe.
VPValue * getAddr() const
Return the address accessed by this recipe.
Definition VPlan.h:3189
bool usesFirstLaneOnly(const VPValue *Op) const override
The recipe only uses the first lane of the address, and EVL operand.
Definition VPlan.h:3304
VPValue * getEVL() const
The VPValue of the explicit vector length.
Definition VPlan.h:3298
~VPInterleaveEVLRecipe() override=default
unsigned getNumStoreOperands() const override
Returns the number of stored operands of this interleave group.
Definition VPlan.h:3311
VPInterleaveEVLRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:3291
VPInterleaveEVLRecipe(VPInterleaveRecipe &R, VPValue &EVL, VPValue *Mask)
Definition VPlan.h:3278
VPInterleaveRecipe is a recipe for transforming an interleave group of load or stores into one wide l...
Definition VPlan.h:3234
unsigned getNumStoreOperands() const override
Returns the number of stored operands of this interleave group.
Definition VPlan.h:3261
~VPInterleaveRecipe() override=default
VPInterleaveRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:3244
bool usesFirstLaneOnly(const VPValue *Op) const override
Returns true if the recipe only uses the first lane of operand Op.
Definition VPlan.h:3255
VPInterleaveRecipe(const InterleaveGroup< Instruction > *IG, VPValue *Addr, ArrayRef< VPValue * > StoredValues, VPValue *Mask, bool NeedsMaskForGaps, const VPIRMetadata &MD, DebugLoc DL)
Definition VPlan.h:3236
A VPRecipeValue defined by a multi-def recipe, stores a pointer to it.
Definition VPlanValue.h:376
Helper type to provide functions to access incoming values and blocks for phi-like recipes.
Definition VPlan.h:1627
virtual const VPRecipeBase * getAsRecipe() const =0
Return a VPRecipeBase* to the current object.
LLVM_ABI_FOR_TEST VPValue * getIncomingValueForBlock(const VPBasicBlock *VPBB) const
Returns the incoming value for VPBB. VPBB must be an incoming block.
VPUser::const_operand_range incoming_values() const
Returns an interator range over the incoming values.
Definition VPlan.h:1657
void addIncoming(VPValue *IncomingV)
Append IncomingV as an incoming value to the phi-like recipe.
Definition VPlan.h:1686
virtual unsigned getNumIncoming() const
Returns the number of incoming values, also number of incoming blocks.
Definition VPlan.h:1652
void removeIncomingValueFor(VPBlockBase *IncomingBlock) const
Removes the incoming value for IncomingBlock, which must be a predecessor.
const VPBasicBlock * getIncomingBlock(unsigned Idx) const
Returns the incoming block with index Idx.
Definition VPlan.h:4696
detail::zippy< llvm::detail::zip_first, VPUser::const_operand_range, const_incoming_blocks_range > incoming_values_and_blocks() const
Returns an iterator range over pairs of incoming values and corresponding incoming blocks.
Definition VPlan.h:1677
VPValue * getIncomingValue(unsigned Idx) const
Returns the incoming VPValue with index Idx.
Definition VPlan.h:1636
virtual ~VPPhiAccessors()=default
void printPhiOperands(raw_ostream &O, VPSlotTracker &SlotTracker) const
Print the recipe.
void setIncomingValueForBlock(const VPBasicBlock *VPBB, VPValue *V) const
Sets the incoming value for VPBB to V.
iterator_range< mapped_iterator< detail::index_iterator, std::function< const VPBasicBlock *(size_t)> > > const_incoming_blocks_range
Definition VPlan.h:1662
const_incoming_blocks_range incoming_blocks() const
Returns an iterator range over the incoming blocks.
Definition VPlan.h:1666
~VPPredInstPHIRecipe() override=default
VPPredInstPHIRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:3832
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPPredInstPHIRecipe.
Definition VPlan.h:3843
VPPredInstPHIRecipe(VPValue *PredV, DebugLoc DL)
Construct a VPPredInstPHIRecipe given PredInst whose value needs a phi nodes after merging back from ...
Definition VPlan.h:3827
VPRecipeBase is a base class modeling a sequence of one or more output IR instructions.
Definition VPlan.h:402
bool mayReadFromMemory() const
Returns true if the recipe may read from memory.
void moveBefore(RecipeListTy::iterator I)
Unlink this recipe and insert it before I.
bool mayReadOrWriteMemory() const
Returns true if the recipe may read from or write to memory.
Definition VPlan.h:542
virtual void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const =0
Each concrete VPRecipe prints itself, without printing common information, like debug info or metadat...
VPRegionBlock * getRegion()
Definition VPlan.h:4951
RecipeListTy::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
void setDebugLoc(DebugLoc NewDL)
Set the recipe's debug location to NewDL.
Definition VPlan.h:550
bool mayWriteToMemory() const
Returns true if the recipe may write to memory.
VPRecipeTy getVPRecipeID() const
Definition VPlan.h:515
~VPRecipeBase() override=default
DebugLoc getDebugLoc() const
Returns the debug location of the recipe.
Definition VPlan.h:547
virtual void execute(VPTransformState &State)=0
The method which generates the output IR instructions that correspond to this VPRecipe,...
iplist< VPRecipeBase, ilist_parent< VPBasicBlock > > RecipeListTy
The list type holding the recipes of a VPBasicBlock.
Definition VPlan.h:473
void insertBefore(VPRecipeBase *InsertPos)
Insert an unlinked recipe into a basic block immediately before the specified recipe.
void insertAfter(VPRecipeBase *InsertPos)
Insert an unlinked Recipe into a basic block immediately after the specified Recipe.
static bool classof(const VPDef *D)
Method to support type inquiry through isa, cast, and dyn_cast.
Definition VPlan.h:518
virtual VPRecipeBase * clone()=0
Clone the current recipe.
friend class VPBlockUtils
Definition VPlan.h:404
VPRecipeBase(VPRecipeTy SC, ArrayRef< VPValue * > Operands, DebugLoc DL=DebugLoc::getUnknown())
Definition VPlan.h:462
InstructionCost cost(ElementCount VF, VPCostContext &Ctx)
Return the cost of this recipe, taking into account if the cost computation should be skipped and the...
static bool classof(const VPUser *U)
Definition VPlan.h:523
void removeFromParent()
This method unlinks 'this' from the containing basic block, but does not delete it.
enum :unsigned char { VPBranchOnMaskSC, VPDerivedIVSC, VPExpandSCEVSC, VPExpressionSC, VPIRInstructionSC, VPInstructionSC, VPInterleaveEVLSC, VPInterleaveSC, VPReductionEVLSC, VPReductionSC, VPReplicateSC, VPScalarIVStepsSC, VPVectorPointerSC, VPVectorEndPointerSC, VPWidenCallSC, VPWidenCanonicalIVSC, VPWidenCastSC, VPWidenGEPSC, VPWidenIntrinsicSC, VPWidenMemIntrinsicSC, VPWidenLoadEVLSC, VPWidenLoadSC, VPWidenStoreEVLSC, VPWidenStoreSC, VPWidenSC, VPBlendSC, VPHistogramSC, VPWidenPHISC, VPPredInstPHISC, VPCurrentIterationPHISC, VPActiveLaneMaskPHISC, VPFirstOrderRecurrencePHISC, VPWidenIntOrFpInductionSC, VPWidenPointerInductionSC, VPReductionPHISC, VPConditionalInductionPHISC, VPFirstPHISC=VPWidenPHISC, VPFirstHeaderPHISC=VPCurrentIterationPHISC, VPLastHeaderPHISC=VPConditionalInductionPHISC, VPLastPHISC=VPConditionalInductionPHISC, } VPRecipeTy
An enumeration for keeping track of the concrete subclass of VPRecipeBase that is actually instantiat...
Definition VPlan.h:414
void moveAfter(VPRecipeBase *MovePos)
Unlink this recipe from its current VPBasicBlock and insert it into the VPBasicBlock that MovePos liv...
Type * getScalarType() const
Returns the scalar type of this VPRecipeValue.
Definition VPlanValue.h:349
VPValue * getEVL() const
The VPValue of the explicit vector length.
Definition VPlan.h:3472
VPReductionEVLRecipe(VPReductionRecipe &R, VPValue &EVL, VPValue *CondOp, DebugLoc DL=DebugLoc::getUnknown())
Definition VPlan.h:3450
bool usesFirstLaneOnly(const VPValue *Op) const override
Returns true if the recipe only uses the first lane of operand Op.
Definition VPlan.h:3475
VPReductionEVLRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:3462
~VPReductionEVLRecipe() override=default
bool isOrdered() const
Returns true, if the phi is part of an ordered reduction.
Definition VPlan.h:2961
void setVFScaleFactor(unsigned ScaleFactor)
Set the VFScaleFactor for this reduction phi.
Definition VPlan.h:2952
VPReductionPHIRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:2934
unsigned getVFScaleFactor() const
Get the factor that the VF of this recipe's output should be scaled by, or 1 if it isn't scaled.
Definition VPlan.h:2945
~VPReductionPHIRecipe() override=default
bool isExpressionSunk() const
Definition VPlan.h:2976
bool hasUsesOutsideReductionChain() const
Returns true, if the phi is part of a multi-use reduction.
Definition VPlan.h:2970
VPReductionPHIRecipe(PHINode *Phi, RecurKind Kind, VPValue &Start, VPValue &BackedgeValue, ReductionStyle Style, const VPIRFlags &Flags, bool HasUsesOutsideReductionChain=false)
Create a new VPReductionPHIRecipe for the reduction Phi.
Definition VPlan.h:2912
bool isInLoop() const
Returns true if the phi is part of an in-loop reduction.
Definition VPlan.h:2964
bool usesFirstLaneOnly(const VPValue *Op) const override
Returns true if the recipe only uses the first lane of operand Op.
Definition VPlan.h:2979
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
void execute(VPTransformState &State) override
Generate the phi/select nodes.
VPReductionPHIRecipe * cloneWithOperands(VPValue *Start, VPValue *BackedgeValue)
Definition VPlan.h:2925
RecurKind getRecurrenceKind() const
Returns the recurrence kind of the reduction.
Definition VPlan.h:2958
A recipe to represent inloop, ordered or partial reduction operations.
Definition VPlan.h:3327
bool isConditional() const
Return true if the in-loop reduction is conditional.
Definition VPlan.h:3411
static bool classof(const VPRecipeBase *R)
Definition VPlan.h:3380
static bool classof(const VPSingleDefRecipe *R)
Definition VPlan.h:3395
VPValue * getVecOp() const
The VPValue of the vector value to be reduced.
Definition VPlan.h:3424
VPValue * getCondOp() const
The VPValue of the condition for the block.
Definition VPlan.h:3426
RecurKind getRecurrenceKind() const
Return the recurrence kind for the in-loop reduction.
Definition VPlan.h:3407
VPReductionRecipe(RecurKind RdxKind, FastMathFlags FMFs, Instruction *I, VPValue *ChainOp, VPValue *VecOp, VPValue *CondOp, ReductionStyle Style, DebugLoc DL=DebugLoc::getUnknown())
Definition VPlan.h:3360
bool isOrdered() const
Return true if the in-loop reduction is ordered.
Definition VPlan.h:3409
VPReductionRecipe(const RecurKind RdxKind, FastMathFlags FMFs, VPValue *ChainOp, VPValue *VecOp, VPValue *CondOp, ReductionStyle Style, DebugLoc DL=DebugLoc::getUnknown())
Definition VPlan.h:3366
VPReductionRecipe(VPRecipeTy SC, RecurKind RdxKind, FastMathFlags FMFs, Instruction *I, ArrayRef< VPValue * > Operands, VPValue *CondOp, ReductionStyle Style, DebugLoc DL)
Definition VPlan.h:3336
bool isPartialReduction() const
Returns true if the reduction outputs a vector with a scaled down VF.
Definition VPlan.h:3413
~VPReductionRecipe() override=default
VPValue * getChainOp() const
The VPValue of the scalar Chain being accumulated.
Definition VPlan.h:3422
bool isInLoop() const
Returns true if the reduction is in-loop.
Definition VPlan.h:3417
VPReductionRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:3374
static bool classof(const VPUser *U)
Definition VPlan.h:3385
static bool classof(const VPValue *VPV)
Definition VPlan.h:3390
unsigned getVFScaleFactor() const
Get the factor that the VF of this recipe's output should be scaled by, or 1 if it isn't scaled.
Definition VPlan.h:3431
VPRegionBlock represents a collection of VPBasicBlocks and VPRegionBlocks which form a Single-Entry-S...
Definition VPlan.h:4777
const VPBlockBase * getEntry() const
Definition VPlan.h:4821
bool isReplicator() const
An indicator whether this region is to generate multiple replicated instances of output IR correspond...
Definition VPlan.h:4853
~VPRegionBlock() override=default
VPRegionValue * createHeaderMask()
Create the header mask for the region and return it.
Definition VPlan.h:4924
VPRegionValue * getUsedHeaderMask() const
Return the header mask if it exists and is used, or null otherwise.
Definition VPlan.h:4917
void setExiting(VPBlockBase *ExitingBlock)
Set ExitingBlock as the exiting VPBlockBase of this VPRegionBlock.
Definition VPlan.h:4838
VPBlockBase * getExiting()
Definition VPlan.h:4834
VPBranchOnMaskRecipe * getEntryBranchOnMask()
Definition VPlan.h:4858
const VPRegionValue * getCanonicalIV() const
Definition VPlan.h:4900
SmallVector< VPRegionValue *, 2 > getRegionValues() const
Return the region values of the loop region (canonical IV, header mask) or an empty vector for replic...
Definition VPlan.h:4931
void setEntry(VPBlockBase *EntryBlock)
Set EntryBlock as the entry VPBlockBase of this VPRegionBlock.
Definition VPlan.h:4826
Type * getCanonicalIVType() const
Return the type of the canonical IV for loop regions.
Definition VPlan.h:4905
bool hasCanonicalIVNUW() const
Indicates if NUW is set for the canonical IV increment, for loop regions.
Definition VPlan.h:4941
void clearCanonicalIVNUW(VPInstruction *Increment)
Unsets NUW for the canonical IV increment Increment, for loop regions.
Definition VPlan.h:4944
VPRegionValue * getCanonicalIV()
Return the canonical induction variable of the region, null for replicating regions.
Definition VPlan.h:4897
const VPBlockBase * getExiting() const
Definition VPlan.h:4833
VPBlockBase * getEntry()
Definition VPlan.h:4822
VPBasicBlock * getPreheaderVPBB()
Returns the pre-header VPBasicBlock of the loop region.
Definition VPlan.h:4846
VPRegionValue * getHeaderMask() const
Return the header mask of the region, or null if not set.
Definition VPlan.h:4910
friend class VPlan
Definition VPlan.h:4778
static bool classof(const VPBlockBase *V)
Method to support type inquiry through isa, cast, and dyn_cast.
Definition VPlan.h:4817
VPValues are defined by a VPRegionBlock, like the canonical IV.
Definition VPlanValue.h:247
VPReplicateRecipe replicates a given instruction producing multiple scalar copies of the original sca...
Definition VPlan.h:3494
bool isSingleScalar() const
Returns true if the recipe produces a single scalar value.
Definition VPlan.h:3551
unsigned getNumOperandsWithoutMask() const
Returns the number of operands, excluding the mask if the recipe is predicated.
Definition VPlan.h:3585
VPReplicateRecipe(Instruction *I, ArrayRef< VPValue * > Operands, bool IsSingleScalar, VPValue *Mask=nullptr, const VPIRFlags &Flags={}, VPIRMetadata Metadata={}, DebugLoc DL=DebugLoc::getUnknown())
Definition VPlan.h:3502
~VPReplicateRecipe() override=default
static Type * computeScalarType(const Instruction *I, ArrayRef< VPValue * > Operands)
Compute the scalar result type for a VPReplicateRecipe wrapping I with Operands (excluding any predic...
VPReplicateRecipe * cloneWithOperands(ArrayRef< VPValue * > NewOperands)
Definition VPlan.h:3526
bool usesScalars(const VPValue *Op) const override
Returns true if the recipe uses scalars of operand Op.
Definition VPlan.h:3566
operand_range operandsWithoutMask()
Return the recipe's operands, excluding the mask of a predicated recipe.
Definition VPlan.h:3579
bool isPredicated() const
Definition VPlan.h:3556
VPReplicateRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:3524
bool doesGeneratePerAllLanes() const
Returns true if the recipe produces scalar values for all VF lanes.
Definition VPlan.h:3554
bool usesFirstLaneOnly(const VPValue *Op) const override
Returns true if the recipe only uses the first lane of operand Op.
Definition VPlan.h:3559
unsigned getOpcode() const
Definition VPlan.h:3589
VPValue * getMask()
Return the mask of a predicated VPReplicateRecipe.
Definition VPlan.h:3573
Instruction::BinaryOps getInductionOpcode() const
Definition VPlan.h:4438
VPValue * getStepValue() const
Definition VPlan.h:4408
void setStartIndex(VPValue *StartIndex)
Set or add the StartIndex operand.
Definition VPlan.h:4421
VPScalarIVStepsRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:4390
VPValue * getStartIndex() const
Return the StartIndex, or null if known to be zero, valid only after unrolling.
Definition VPlan.h:4416
VPValue * getVFValue() const
Return the number of scalars to produce per unroll part, used to compute StartIndex during unrolling.
Definition VPlan.h:4412
VPScalarIVStepsRecipe(VPValue *IV, VPValue *Step, VPValue *VF, Instruction::BinaryOps Opcode, FastMathFlags FMFs={}, DebugLoc DL=DebugLoc::getUnknown())
Definition VPlan.h:4381
~VPScalarIVStepsRecipe() override=default
bool usesFirstLaneOnly(const VPValue *Op) const override
Returns true if the recipe only uses the first lane of operand Op.
Definition VPlan.h:4432
VPSingleDefRecipe is a base class for recipes that model a sequence of one or more output IR that def...
Definition VPlan.h:605
static bool classof(const VPValue *V)
Definition VPlan.h:655
Instruction * getUnderlyingInstr()
Returns the underlying instruction.
Definition VPlan.h:668
static bool classof(const VPRecipeBase *R)
Definition VPlan.h:611
const Instruction * getUnderlyingInstr() const
Definition VPlan.h:671
VPSingleDefRecipe(VPRecipeTy SC, ArrayRef< VPValue * > Operands, Type *ResultTy, Value *UV=nullptr, DebugLoc DL=DebugLoc::getUnknown())
Definition VPlan.h:607
static bool classof(const VPUser *U)
Definition VPlan.h:660
VPSingleDefRecipe * clone() override=0
Clone the current recipe.
VPSingleDefValue(VPSingleDefRecipe *Def, Value *UV=nullptr, Type *Ty=nullptr)
Construct a VPSingleDefValue. Must only be used by VPSingleDefRecipe.
Definition VPlan.cpp:158
This class can be used to assign names to VPValues.
A symbolic live-in VPValue, used for values like vector trip count, VF, and VFxUF.
Definition VPlanValue.h:212
This class augments VPValue with operands which provide the inverse def-use edges from VPValue's user...
Definition VPlanValue.h:396
void printOperands(raw_ostream &O, VPSlotTracker &SlotTracker) const
Print the operands to O.
Definition VPlan.cpp:1515
operand_range operands()
Definition VPlanValue.h:472
void setOperand(unsigned I, VPValue *New)
Definition VPlanValue.h:445
unsigned getNumOperands() const
Definition VPlanValue.h:436
operand_iterator op_end()
Definition VPlanValue.h:470
operand_iterator op_begin()
Definition VPlanValue.h:468
VPValue * getOperand(unsigned N) const
Definition VPlanValue.h:437
VPUser(ArrayRef< VPValue * > Operands)
Definition VPlanValue.h:417
iterator_range< const_operand_iterator > const_operand_range
Definition VPlanValue.h:466
VPValue * getLastOperand() const
Returns the last operand.
Definition VPlanValue.h:443
iterator_range< operand_iterator > operand_range
Definition VPlanValue.h:465
void addOperand(VPValue *Operand)
Definition VPlanValue.h:422
This is the base class of the VPlan Def/Use graph, used for modeling the data flow into,...
Definition VPlanValue.h:50
Type * getScalarType() const
Returns the scalar type of this VPValue, dispatching based on the concrete subclass.
Definition VPlan.cpp:138
Value * getLiveInIRValue() const
Return the underlying IR value for a VPIRValue.
Definition VPlan.cpp:132
VPRecipeBase * getDefiningRecipe()
Returns the recipe defining this VPValue or nullptr if it is not defined by a recipe,...
Definition VPlan.cpp:119
Value * getUnderlyingValue() const
Return the underlying Value attached to this VPValue.
Definition VPlanValue.h:75
bool user_empty() const
Definition VPlanValue.h:161
void setUnderlyingValue(Value *Val)
Definition VPlanValue.h:204
unsigned getNumUsers() const
Definition VPlanValue.h:115
bool usesFirstLaneOnly(const VPValue *Op) const override
Returns true if the VPUser only uses the first lane of operand Op.
Definition VPlan.h:2360
VPValue * getVFValue() const
Definition VPlan.h:2341
void execute(VPTransformState &State) override
The method which generates the output IR instructions that correspond to this VPRecipe,...
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
Type * getSourceElementType() const
Definition VPlan.h:2338
bool usesFirstPartOnly() const override
Returns true if the recipe only uses the first part of all operands.
Definition VPlan.h:2374
int64_t getStride() const
Definition VPlan.h:2339
VPVectorEndPointerRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:2379
VPValue * getOffset() const
Definition VPlan.h:2342
void addOffset(VPValue *Offset)
Append Offset as the offset operand.
Definition VPlan.h:2352
VPVectorEndPointerRecipe(VPValue *Ptr, VPValue *VF, Type *SourceElementTy, int64_t Stride, GEPNoWrapFlags GEPFlags, DebugLoc DL)
Definition VPlan.h:2328
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPVectorPointerRecipe.
Definition VPlan.h:2367
VPValue * getPointer() const
Definition VPlan.h:2340
void materializeOffset(unsigned Part=0)
Adds the offset operand to the recipe.
void addPerPartOffset(VPValue *VFxPart)
Add the per-part offset (VFxPart) used for unrolled parts > 0.
Definition VPlan.h:2420
VPValue * getStride() const
Definition VPlan.h:2413
Type * getSourceElementType() const
Definition VPlan.h:2428
bool usesFirstLaneOnly(const VPValue *Op) const override
Returns true if the VPUser only uses the first lane of operand Op.
Definition VPlan.h:2430
bool usesFirstPartOnly() const override
Returns true if the recipe only uses the first part of all operands.
Definition VPlan.h:2437
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
void execute(VPTransformState &State) override
The method which generates the output IR instructions that correspond to this VPRecipe,...
VPVectorPointerRecipe(VPValue *Ptr, Type *SourceElementTy, VPValue *Stride, GEPNoWrapFlags GEPFlags, DebugLoc DL)
Definition VPlan.h:2404
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPHeaderPHIRecipe.
Definition VPlan.h:2452
VPVectorPointerRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:2442
VPValue * getVFxPart() const
Definition VPlan.h:2415
A recipe for widening Call instructions using library calls.
Definition VPlan.h:2135
const_operand_range args() const
Definition VPlan.h:2183
VPWidenCallRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:2161
operand_range args()
Definition VPlan.h:2182
Function * getCalledScalarFunction() const
Definition VPlan.h:2178
VPWidenCallRecipe(Value *UV, Function *Variant, ArrayRef< VPValue * > CallArguments, const VPIRFlags &Flags={}, const VPIRMetadata &Metadata={}, const VPIRAttributes &Attrs={}, DebugLoc DL={})
Definition VPlan.h:2142
~VPWidenCallRecipe() override=default
~VPWidenCanonicalIVRecipe() override=default
VPValue * getStepValue() const
Definition VPlan.h:4294
void addPerPartStep(VPValue *Step)
Add the per-part step (VF * Part) used for unrolled parts.
Definition VPlan.h:4299
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPWidenCanonicalIVPHIRecipe.
Definition VPlan.h:4283
VPRegionValue * getCanonicalIV() const
Return the canonical IV being widened.
Definition VPlan.h:4290
VPWidenCanonicalIVRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:4268
VPWidenCanonicalIVRecipe(VPRegionValue *CanonicalIV, const VPIRFlags::WrapFlagsTy &Flags={})
Definition VPlan.h:4261
void execute(VPTransformState &State) override
The method which generates the output IR instructions that correspond to this VPRecipe,...
Definition VPlan.h:4278
VPWidenCastRecipe is a recipe to create vector cast instructions.
Definition VPlan.h:1902
Instruction::CastOps getOpcode() const
Definition VPlan.h:1938
~VPWidenCastRecipe() override=default
VPWidenCastRecipe(Instruction::CastOps Opcode, VPValue *Op, Type *ResultTy, CastInst *CI=nullptr, const VPIRFlags &Flags={}, const VPIRMetadata &Metadata={}, DebugLoc DL=DebugLoc::getUnknown())
Definition VPlan.h:1907
VPWidenCastRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:1923
unsigned getOpcode() const
This recipe generates a GEP instruction.
Definition VPlan.h:2290
Type * getSourceElementType() const
Definition VPlan.h:2295
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPWidenGEPRecipe.
Definition VPlan.h:2298
VPWidenGEPRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:2281
~VPWidenGEPRecipe() override=default
VPWidenGEPRecipe(Type *SourceElementTy, ArrayRef< VPValue * > Operands, const VPIRFlags &Flags={}, DebugLoc DL=DebugLoc::getUnknown(), GetElementPtrInst *UV=nullptr)
Definition VPlan.h:2264
void execute(VPTransformState &State) override=0
Generate the phi nodes.
ArrayRef< const SCEVPredicate * > getNoWrapPredicates() const
Returns the SCEV predicates associated with this induction.
Definition VPlan.h:2616
bool usesFirstLaneOnly(const VPValue *Op) const override
Returns true if the recipe only uses the first lane of operand Op.
Definition VPlan.h:2628
static bool classof(const VPValue *V)
Definition VPlan.h:2584
VPValue * getBackedgeValue() override
Returns the incoming value from the loop backedge.
Definition VPlan.h:2620
unsigned getNumIncoming() const override
Returns the number of incoming values, also number of incoming blocks.
Definition VPlan.h:2605
PHINode * getPHINode() const
Returns the underlying PHINode if one exists, or null otherwise.
Definition VPlan.h:2608
VPValue * getStepValue()
Returns the step value of the induction.
Definition VPlan.h:2596
const InductionDescriptor & getInductionDescriptor() const
Returns the induction descriptor for the recipe.
Definition VPlan.h:2613
static bool classof(const VPRecipeBase *R)
Definition VPlan.h:2579
VPWidenInductionRecipe(VPRecipeTy Kind, PHINode *IV, VPValue *Start, VPValue *Step, const InductionDescriptor &IndDesc, Type *ResultTy, DebugLoc DL)
Definition VPlan.h:2558
const VPValue * getVFValue() const
Definition VPlan.h:2600
static bool classof(const VPSingleDefRecipe *R)
Definition VPlan.h:2589
const VPValue * getStepValue() const
Definition VPlan.h:2597
void addUnrolledPartOperands(VPValue *SplatVFStep, VPValue *LastPart)
After unrolling, append the splat-VF step (VF * step) and the value of the induction at the last unro...
Definition VPlan.h:2567
void execute(VPTransformState &State) override
Generate the phi nodes.
Definition VPlan.h:2677
~VPWidenIntOrFpInductionRecipe() override=default
VPValue * getSplatVFValue() const
If the recipe has been unrolled, return the VPValue for the induction increment, otherwise return nul...
Definition VPlan.h:2684
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPWidenIntOrFpInductionRecipe.
VPWidenIntOrFpInductionRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:2669
VPWidenIntOrFpInductionRecipe(PHINode *IV, VPValue *Start, VPValue *Step, VPValue *VF, const InductionDescriptor &IndDesc, const VPIRFlags &Flags, DebugLoc DL)
Definition VPlan.h:2647
bool isTruncated() const
Returns true if this induction is evaluated in a narrower type than the start value.
Definition VPlan.h:2695
VPWidenIntOrFpInductionRecipe(PHINode *IV, VPValue *Start, VPValue *Step, VPValue *VF, const InductionDescriptor &IndDesc, Type *ResultTy, const VPIRFlags &Flags, DebugLoc DL)
Definition VPlan.h:2657
VPValue * getLastUnrolledPartOperand()
Returns the VPValue representing the value of this induction at the last unrolled part,...
Definition VPlan.h:2713
unsigned getNumIncoming() const override
Returns the number of incoming values, also number of incoming blocks.
Definition VPlan.h:2691
bool isCanonical() const
Returns true if the induction is canonical, i.e.
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
A recipe for widening vector intrinsics.
Definition VPlan.h:1950
VPWidenIntrinsicRecipe(VPRecipeTy SC, Intrinsic::ID VectorIntrinsicID, ArrayRef< VPValue * > CallArguments, Type *Ty, const VPIRFlags &Flags={}, const VPIRMetadata &MD={}, DebugLoc DL=DebugLoc::getUnknown())
Definition VPlan.h:1964
VPWidenIntrinsicRecipe(Intrinsic::ID VectorIntrinsicID, ArrayRef< VPValue * > CallArguments, Type *Ty, const VPIRFlags &Flags={}, const VPIRMetadata &Metadata={}, DebugLoc DL=DebugLoc::getUnknown())
Definition VPlan.h:1999
Intrinsic::ID getVectorIntrinsicID() const
Return the ID of the intrinsic.
Definition VPlan.h:2053
bool mayReadFromMemory() const
Returns true if the intrinsic may read from memory.
Definition VPlan.h:2059
VPWidenIntrinsicRecipe(CallInst &CI, Intrinsic::ID VectorIntrinsicID, ArrayRef< VPValue * > CallArguments, Type *Ty, const VPIRFlags &Flags={}, const VPIRMetadata &MD={}, DebugLoc DL=DebugLoc::getUnknown())
Definition VPlan.h:1985
bool mayHaveSideEffects() const
Returns true if the intrinsic may have side-effects.
Definition VPlan.h:2065
static bool classof(const VPSingleDefRecipe *R)
Definition VPlan.h:2035
static bool classof(const VPValue *V)
Definition VPlan.h:2030
VPWidenIntrinsicRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:2010
bool mayWriteToMemory() const
Returns true if the intrinsic may write to memory.
Definition VPlan.h:2062
~VPWidenIntrinsicRecipe() override=default
static bool classof(const VPRecipeBase *R)
Definition VPlan.h:2020
static bool classof(const VPUser *U)
Definition VPlan.h:2025
~VPWidenMemIntrinsicRecipe() override=default
VPWidenMemIntrinsicRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:2102
VPWidenMemIntrinsicRecipe(Intrinsic::ID VectorIntrinsicID, ArrayRef< VPValue * > CallArguments, Type *Ty, Align Alignment, const VPIRMetadata &MD={}, DebugLoc DL=DebugLoc::getUnknown())
Definition VPlan.h:2084
A common mixin class for widening memory operations.
Definition VPlan.h:3859
bool IsMasked
Whether the memory access is masked.
Definition VPlan.h:3870
bool isConsecutive() const
Return whether the loaded-from / stored-to addresses are consecutive.
Definition VPlan.h:3895
virtual ~VPWidenMemoryRecipe()=default
Instruction & Ingredient
Definition VPlan.h:3861
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const
Return the cost of this VPWidenMemoryRecipe.
Instruction & getIngredient() const
Definition VPlan.h:3917
bool Consecutive
Whether the accessed addresses are consecutive.
Definition VPlan.h:3867
VPWidenMemoryRecipe(Instruction &I, Align Alignment, bool Consecutive, const VPIRMetadata &Metadata)
Definition VPlan.h:3882
virtual const VPRecipeBase * getAsRecipe() const =0
VPValue * getMask() const
Return the mask used by this recipe.
Definition VPlan.h:3905
Align Alignment
Alignment information for this memory access.
Definition VPlan.h:3864
virtual VPRecipeBase * getAsRecipe()=0
Return a VPRecipeBase* to the current object.
bool isMasked() const
Returns true if the recipe is masked.
Definition VPlan.h:3901
void setMask(VPValue *Mask)
Definition VPlan.h:3872
Align getAlign() const
Returns the alignment of the memory access.
Definition VPlan.h:3912
VPValue * getAddr() const
Return the address accessed by this recipe.
Definition VPlan.h:3898
A recipe for widened phis.
Definition VPlan.h:2776
const VPRecipeBase * getAsRecipe() const override
Return a VPRecipeBase* to the current object.
Definition VPlan.h:2821
unsigned getOpcode() const
This recipe generates a PHI.
Definition VPlan.h:2803
VPWidenPHIRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:2796
~VPWidenPHIRecipe() override=default
VPWidenPHIRecipe(ArrayRef< VPValue * > IncomingValues, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="")
Create a new VPWidenPHIRecipe with incoming values IncomingValues, debug location DL and Name.
Definition VPlan.h:2783
VPWidenPointerInductionRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:2741
~VPWidenPointerInductionRecipe() override=default
bool onlyScalarsGenerated(bool IsScalable)
Returns true if only scalar values will be generated.
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
void execute(VPTransformState &State) override
Generate vector values for the pointer induction.
Definition VPlan.h:2750
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPWidenPointerInductionRecipe.
VPWidenPointerInductionRecipe(PHINode *Phi, VPValue *Start, VPValue *Step, VPValue *NumUnrolledElems, const InductionDescriptor &IndDesc, DebugLoc DL)
Create a new VPWidenPointerInductionRecipe for Phi with start value Start and the number of elements ...
Definition VPlan.h:2730
VPWidenRecipe is a recipe for producing a widened instruction using the opcode and operands of the re...
Definition VPlan.h:1835
VPWidenRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:1861
bool usesFirstLaneOnly(const VPValue *Op) const override
Returns true if the recipe only uses the first lane of operand Op.
Definition VPlan.h:1890
VPWidenRecipe(Instruction &I, ArrayRef< VPValue * > Operands, const VPIRFlags &Flags={}, const VPIRMetadata &Metadata={}, DebugLoc DL={})
Definition VPlan.h:1839
VPWidenRecipe(unsigned Opcode, ArrayRef< VPValue * > Operands, const VPIRFlags &Flags={}, const VPIRMetadata &Metadata={}, DebugLoc DL={})
Definition VPlan.h:1846
~VPWidenRecipe() override=default
VPWidenRecipe * cloneWithOperands(ArrayRef< VPValue * > NewOperands)
Definition VPlan.h:1863
unsigned getOpcode() const
Definition VPlan.h:1880
VPlan models a candidate for vectorization, encoding various decisions take to produce efficient outp...
Definition VPlan.h:4964
VPIRValue * getLiveIn(Value *V) const
Return the live-in VPIRValue for V, if there is one or nullptr otherwise.
Definition VPlan.h:5294
LLVM_ABI_FOR_TEST void printDOT(raw_ostream &O) const
Print this VPlan in DOT format to O.
Definition VPlan.cpp:1173
friend class VPSlotTracker
Definition VPlan.h:4966
std::string getName() const
Return a string with the name of the plan and the applicable VFs and UFs.
Definition VPlan.cpp:1149
bool hasVF(ElementCount VF) const
Definition VPlan.h:5187
ElementCount getSingleVF() const
Returns the single VF of the plan, asserting that the plan has exactly one VF.
Definition VPlan.h:5200
const DataLayout & getDataLayout() const
Definition VPlan.h:5165
LLVMContext & getContext() const
Definition VPlan.h:5161
VPBasicBlock * getEntry()
Definition VPlan.h:5056
Type * getIndexType() const
The type of the canonical induction variable of the vector loop.
Definition VPlan.h:5388
void setName(const Twine &newName)
Definition VPlan.h:5233
bool hasScalableVF() const
Definition VPlan.h:5188
VPValue * getTripCount() const
The trip count of the original loop.
Definition VPlan.h:5128
iterator_range< SmallSetVector< ElementCount, 2 >::iterator > vectorFactors() const
Returns an iterator range over all VFs of the plan.
Definition VPlan.h:5194
LLVM_ABI_FOR_TEST ~VPlan()
Definition VPlan.cpp:909
VPIRValue * getOrAddLiveIn(VPIRValue *V)
Definition VPlan.h:5251
bool isExitBlock(VPBlockBase *VPBB)
Returns true if VPBB is an exit block.
Definition VPlan.cpp:927
const VPBasicBlock * getEntry() const
Definition VPlan.h:5057
friend class VPlanPrinter
Definition VPlan.h:4965
VPIRValue * getFalse()
Return a VPIRValue wrapping i1 false.
Definition VPlan.h:5260
VPIRValue * getConstantInt(const APInt &Val)
Return a VPIRValue wrapping a ConstantInt with the given APInt value.
Definition VPlan.h:5283
VPSymbolicValue & getVFxUF()
Returns VF * UF of the vector loop region.
Definition VPlan.h:5159
VPIRValue * getAllOnesValue(Type *Ty)
Return a VPIRValue wrapping the AllOnes value of type Ty.
Definition VPlan.h:5266
VPRegionBlock * createReplicateRegion(VPBlockBase *Entry, VPBlockBase *Exiting, const std::string &Name="")
Create a new replicate region with Entry, Exiting and Name.
Definition VPlan.h:5347
VPIRBasicBlock * createEmptyVPIRBasicBlock(BasicBlock *IRBB)
Create a VPIRBasicBlock wrapping IRBB, but do not create VPIRInstructions wrapping the instructions i...
Definition VPlan.cpp:1306
auto getLiveIns() const
Return the list of live-in VPValues available in the VPlan.
Definition VPlan.h:5297
bool hasUF(unsigned UF) const
Definition VPlan.h:5212
VPIRValue * getPoison(Type *Ty)
Return a VPIRValue wrapping a poison value of type Ty.
Definition VPlan.h:5288
ArrayRef< VPIRBasicBlock * > getExitBlocks() const
Return an ArrayRef containing VPIRBasicBlocks wrapping the exit blocks of the original scalar loop.
Definition VPlan.h:5122
VPlan(BasicBlock *ScalarHeaderBB, Type *IdxTy)
Construct a VPlan with a new VPBasicBlock as entry, a VPIRBasicBlock wrapping ScalarHeaderBB and vect...
Definition VPlan.h:5037
VPSymbolicValue & getVectorTripCount()
The vector trip count.
Definition VPlan.h:5149
VPIRValue * getOrAddLiveIn(Value *V)
Gets the live-in VPIRValue for V or adds a new live-in (if none exists yet) for V.
Definition VPlan.h:5237
VPRegionBlock * createLoopRegion(Type *CanIVTy, DebugLoc DL, const std::string &Name="", VPBlockBase *Entry=nullptr, VPBlockBase *Exiting=nullptr)
Create a new loop region with a canonical IV using CanIVTy and DL.
Definition VPlan.h:5333
VPIRValue * getZero(Type *Ty)
Return a VPIRValue wrapping the null value of type Ty.
Definition VPlan.h:5263
void setVF(ElementCount VF)
Definition VPlan.h:5175
unsigned getMaxBlockNumber() const
Definition VPlan.h:5367
bool isUnrolled() const
Returns true if the VPlan already has been unrolled, i.e.
Definition VPlan.h:5228
Function * getIRFunction() const
Definition VPlan.h:5169
LLVM_ABI_FOR_TEST VPRegionBlock * getVectorLoopRegion()
Returns the VPRegionBlock of the vector loop.
Definition VPlan.cpp:1060
bool hasEarlyExit() const
Returns true if the VPlan is based on a loop with an early exit.
Definition VPlan.h:5371
InstructionCost cost(ElementCount VF, VPCostContext &Ctx)
Return the cost of this plan.
Definition VPlan.cpp:1042
LLVM_ABI_FOR_TEST bool isOuterLoop() const
Returns true if this VPlan is for an outer loop, i.e., its vector loop region contains a nested loop ...
Definition VPlan.cpp:1085
unsigned getConcreteUF() const
Returns the concrete UF of the plan, after unrolling.
Definition VPlan.h:5215
VPIRValue * getConstantInt(unsigned BitWidth, uint64_t Val, bool IsSigned=false)
Return a VPIRValue wrapping a ConstantInt with the given bitwidth and value.
Definition VPlan.h:5277
const VPBasicBlock * getMiddleBlock() const
Definition VPlan.h:5107
void setTripCount(VPValue *NewTripCount)
Set the trip count assuming it is currently null; if it is not - use resetTripCount().
Definition VPlan.h:5135
void resetTripCount(VPValue *NewTripCount)
Resets the trip count for the VPlan.
Definition VPlan.h:5142
VPBasicBlock * getMiddleBlock()
Returns the 'middle' block of the plan, that is the block that selects whether to execute the scalar ...
Definition VPlan.h:5098
void setEntry(VPBasicBlock *VPBB)
Definition VPlan.h:5045
VPBasicBlock * createVPBasicBlock(const Twine &Name, VPRecipeBase *Recipe=nullptr)
Create a new VPBasicBlock with Name and containing Recipe if present.
Definition VPlan.h:5320
LLVM_ABI_FOR_TEST VPIRBasicBlock * createVPIRBasicBlock(BasicBlock *IRBB)
Create a VPIRBasicBlock from IRBB containing VPIRInstructions for all instructions in IRBB,...
Definition VPlan.cpp:1314
void removeVF(ElementCount VF)
Remove VF from the plan.
Definition VPlan.h:5182
VPIRValue * getTrue()
Return a VPIRValue wrapping i1 true.
Definition VPlan.h:5257
VPBasicBlock * getVectorPreheader() const
Returns the preheader of the vector loop region, if one exists, or null otherwise.
Definition VPlan.h:5061
bool requiresScalarEpilogue() const
Returns true if the plan requires a scalar epilogue after the vector loop.
Definition VPlan.h:5084
LLVM_DUMP_METHOD void dump() const
Dump the plan to stderr (for debugging).
Definition VPlan.cpp:1179
VPSymbolicValue & getUF()
Returns the UF of the vector loop region.
Definition VPlan.h:5156
bool hasScalarVFOnly() const
Definition VPlan.h:5205
VPBasicBlock * getScalarPreheader() const
Return the VPBasicBlock for the preheader of the scalar loop.
Definition VPlan.h:5112
void execute(VPTransformState *State)
Generate the IR code for this VPlan.
Definition VPlan.cpp:937
LLVM_ABI_FOR_TEST void print(raw_ostream &O) const
Print this VPlan to O.
Definition VPlan.cpp:1132
bool hasTailFolded() const
Returns true if the vector loop region is tail-folded.
Definition VPlan.h:5077
void addVF(ElementCount VF)
Definition VPlan.h:5173
VPIRBasicBlock * getScalarHeader() const
Return the VPIRBasicBlock wrapping the header of the scalar loop.
Definition VPlan.h:5118
void printLiveIns(raw_ostream &O) const
Print the live-ins of this VPlan to O.
Definition VPlan.cpp:1094
VPSymbolicValue & getVF()
Returns the VF of the vector loop region.
Definition VPlan.h:5152
void setUF(unsigned UF)
Definition VPlan.h:5220
const VPSymbolicValue & getVF() const
Definition VPlan.h:5153
bool hasScalarTail() const
Returns true if the scalar tail may execute after the vector loop, i.e.
Definition VPlan.h:5381
LLVM_ABI_FOR_TEST VPlan * duplicate()
Clone the current VPlan, update all VPValues of the new VPlan and cloned recipes to refer to the clon...
Definition VPlan.cpp:1220
VPIRValue * getConstantInt(Type *Ty, uint64_t Val, bool IsSigned=false)
Return a VPIRValue wrapping a ConstantInt with the given type and value.
Definition VPlan.h:5271
LLVM Value Representation.
Definition Value.h:75
const ParentTy * getParent() const
Definition ilist_node.h:34
void setParent(ParentTy *Parent)
Definition ilist_node.h:40
Increasing range of size_t indices.
Definition STLExtras.h:2528
typename base_list_type::const_reverse_iterator const_reverse_iterator
Definition ilist.h:124
typename base_list_type::reverse_iterator reverse_iterator
Definition ilist.h:123
typename base_list_type::iterator iterator
Definition ilist.h:121
typename base_list_type::const_iterator const_iterator
Definition ilist.h:122
An intrusive list with ownership and callbacks specified/controlled by ilist_traits,...
Definition ilist.h:328
A range adaptor for a pair of iterators.
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
CallInst * Call
This file defines classes to implement an intrusive doubly linked list class (i.e.
This file defines the ilist_node class template, which is a convenient base class for creating classe...
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Attrs[]
Key for Kernel::Metadata::mAttrs.
std::variant< std::monostate, Loc::Single, Loc::Multi, Loc::MMI, Loc::EntryValue > Variant
Alias for the std::variant specialization base class of DbgVariable.
Definition DwarfDebug.h:190
CastInfo helper for casting from VPRecipeBase to a mixin class that is not part of the VPRecipeBase c...
Definition VPlan.h:4451
unsigned getOpcode(const VPValue *V)
Return the instruction opcode for the recipe defining V or 0 for unsupported recipes and VPValues not...
This is an optimization pass for GlobalISel generic memory operations.
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
@ Offset
Definition DWP.cpp:577
detail::zippy< detail::zip_shortest, T, U, Args... > zip(T &&t, U &&u, Args &&...args)
zip iterator for two or more iteratable types.
Definition STLExtras.h:846
LLVM_PACKED_END
Definition VPlan.h:1085
auto cast_if_present(const Y &Val)
cast_if_present<X> - Functionally identical to cast, except that a null value is accepted.
Definition Casting.h:683
auto find(R &&Range, const T &Val)
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1781
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
detail::zippy< detail::zip_first, T, U, Args... > zip_equal(T &&t, U &&u, Args &&...args)
zip iterator that assumes that all iteratees have the same length.
Definition STLExtras.h:856
ReductionStyle getReductionStyle(bool InLoop, bool Ordered, unsigned ScaleFactor)
Definition VPlan.h:2876
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition STLExtras.h:2575
Type * toScalarizedTy(Type *Ty)
A helper for converting vectorized types to scalarized (non-vector) types.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
@ Load
The value being inserted comes from a load (InsertElement only).
@ Store
The extracted value is stored (ExtractElement only).
VPBuilderBase<> VPBuilder
Definition VPlan.h:66
LLVM_ABI void getMetadataToPropagate(Instruction *Inst, SmallVectorImpl< std::pair< unsigned, MDNode * > > &Metadata)
Add metadata from Inst to Metadata, if it can be preserved after vectorization.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
HistogramUpdateKind
The kind of update operation performed on the buckets of a histogram, i.e.
auto cast_or_null(const Y &Val)
Definition Casting.h:714
MemoryEffectsBase< IRMemLocation > MemoryEffects
Summary of how a function affects memory in the program.
Definition ModRef.h:356
LLVM_ABI bool isSafeToSpeculativelyExecute(const Instruction *I, const Instruction *CtxI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr, const TargetLibraryInfo *TLI=nullptr, bool UseVariableInfo=true, bool IgnoreUBImplyingAttrs=true)
Return true if the instruction does not have any effects besides calculating the result and does not ...
auto map_range(ContainerTy &&C, FuncTy F)
Return a range that applies F to the elements of C.
Definition STLExtras.h:366
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
UncountableExitStyle
Different methods of handling early exits.
Definition VPlan.h:81
@ MaskedHandleExitInScalarLoop
All memory operations other than the load(s) required to determine whether an uncountable exit occurr...
Definition VPlan.h:90
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
bool isPointerTy(const Type *T)
Definition SPIRVUtils.h:373
LLVM_ABI Type * computeScalarTypeForInstruction(unsigned Opcode, ArrayRef< VPValue * > Operands)
Compute the scalar result type for an IR Opcode given Operands.
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
auto drop_end(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the last N elements excluded.
Definition STLExtras.h:323
@ Other
Any other memory.
Definition ModRef.h:68
RecurKind
These are the kinds of recurrences that we support.
@ Mul
Product of integers.
@ Add
Sum of integers.
@ AddChainWithSubs
A chain of adds and subs.
@ FAdd
Sum of floats.
auto count(R &&Range, const E &Element)
Wrapper function around std::count to count the number of times an element Element occurs in the give...
Definition STLExtras.h:2028
DWARFExpression::Operation Op
raw_ostream & operator<<(raw_ostream &OS, const APFixedPoint &FX)
ArrayRef(const T &OneElt) -> ArrayRef< T >
constexpr unsigned BitWidth
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1788
constexpr auto seq(T Begin, T End)
Iterate over an integral type from Begin up to - but not including - End.
Definition Sequence.h:341
void erase_if(Container &C, UnaryPredicate P)
Provide a container algorithm similar to C++ Library Fundamentals v2's erase_if which is equivalent t...
Definition STLExtras.h:2210
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
std::variant< RdxOrdered, RdxInLoop, RdxUnordered > ReductionStyle
Definition VPlan.h:2874
@ Increment
Incrementally increasing token ID.
Definition AllocToken.h:26
std::unique_ptr< VPlan > VPlanPtr
Definition VPlan.h:76
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:879
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:881
#define N
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
static Bitfield::Type get(StorageType Packed)
Unpacks the field from the Packed value.
Definition Bitfields.h:207
static void set(StorageType &Packed, typename Bitfield::Type Value)
Sets the typed value in the provided Packed value.
Definition Bitfields.h:223
This struct provides a method for customizing the way a cast is performed.
Definition Casting.h:476
Provides a cast trait that strips const from types to make it easier to implement a const-version of ...
Definition Casting.h:388
This cast trait just provides the default implementation of doCastIfPossible to make CastInfo special...
Definition Casting.h:309
Provides a cast trait that uses a defined pointer to pointer cast as a base for reference-to-referenc...
Definition Casting.h:423
This reduction is in-loop.
Definition VPlan.h:2868
Possible variants of a reduction.
Definition VPlan.h:2866
This reduction is unordered with the partial result scaled down by some factor.
Definition VPlan.h:2871
unsigned VFScaleFactor
Definition VPlan.h:2872
A MapVector that performs no allocations if smaller than a certain size.
Definition MapVector.h:344
Default inserter for VPBuilderBase, inserting R before It.
An overlay on VPConstant for VPValues that wrap a ConstantInt.
Definition VPlanValue.h:305
Struct to hold various analysis needed for cost computations.
const BlockFrequency Freq
Definition VPlan.h:1141
VPExecutionFrequency(BlockFrequency Freq, bool IsEstimated)
Definition VPlan.h:1144
void execute(VPTransformState &State) override
Generate the phi nodes.
VPFirstOrderRecurrencePHIRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:2837
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this first-order recurrence phi recipe.
bool usesFirstLaneOnly(const VPValue *Op) const override
Returns true if the recipe only uses the first lane of operand Op.
Definition VPlan.h:2849
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
VPFirstOrderRecurrencePHIRecipe(PHINode *Phi, VPValue &Start, VPValue &BackedgeValue)
Definition VPlan.h:2828
DisjointFlagsTy(bool IsDisjoint)
Definition VPlan.h:719
NonNegFlagsTy(bool IsNonNeg)
Definition VPlan.h:724
TruncFlagsTy(bool HasNUW, bool HasNSW)
Definition VPlan.h:714
WrapFlagsTy(bool HasNUW, bool HasNSW)
Definition VPlan.h:703
WrapFlagsTy withoutNoSignedWrap()
Definition VPlan.h:705
An overlay for VPIRInstructions wrapping PHI nodes enabling convenient use cast/dyn_cast/isa and exec...
Definition VPlan.h:1803
VPIRPhi(PHINode &PN)
Definition VPlan.h:1804
static bool classof(const VPRecipeBase *U)
Definition VPlan.h:1806
static bool classof(const VPUser *U)
Definition VPlan.h:1811
PHINode & getIRPhi() const
Definition VPlan.h:1816
const VPRecipeBase * getAsRecipe() const override
Return a VPRecipeBase* to the current object.
Definition VPlan.h:1827
A VPValue representing a live-in from the input IR or a constant.
Definition VPlanValue.h:274
static bool classof(const VPUser *U)
Definition VPlan.h:1706
VPPhi * clone() override
Clone the current recipe.
Definition VPlan.h:1721
const VPRecipeBase * getAsRecipe() const override
Return a VPRecipeBase* to the current object.
Definition VPlan.h:1736
static bool classof(const VPSingleDefRecipe *SDR)
Definition VPlan.h:1716
static bool classof(const VPValue *V)
Definition VPlan.h:1711
VPPhi(ArrayRef< VPValue * > Operands, const VPIRFlags &Flags, DebugLoc DL, const Twine &Name="", Type *ResultTy=nullptr)
Definition VPlan.h:1701
A pure-virtual common base class for recipes defining a single VPValue and using IR flags.
Definition VPlan.h:1089
static bool classof(const VPSingleDefRecipe *R)
Definition VPlan.h:1126
static bool classof(const VPRecipeBase *R)
Definition VPlan.h:1096
InstructionCost getCostForRecipeWithOpcode(unsigned Opcode, ElementCount VF, VPCostContext &Ctx) const
Compute the cost for this recipe for VF, using Opcode and Ctx.
static bool classof(const VPValue *V)
Definition VPlan.h:1119
VPRecipeWithIRFlags(VPRecipeTy SC, ArrayRef< VPValue * > Operands, Type *ResultTy, const VPIRFlags &Flags, DebugLoc DL=DebugLoc::getUnknown())
Definition VPlan.h:1090
void execute(VPTransformState &State) override=0
The method which generates the output IR instructions that correspond to this VPRecipe,...
VPRecipeWithIRFlags * clone() override=0
Clone the current recipe.
static bool classof(const VPUser *U)
Definition VPlan.h:1114
VPTransformState holds information passed down when "executing" a VPlan, needed for generating the ou...
A recipe for widening load operations with vector-predication intrinsics, using the address to load f...
Definition VPlan.h:3978
VPWidenLoadEVLRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:3989
unsigned getOpcode() const
Returns the opcode of the widened load.
Definition VPlan.h:3996
VPValue * getEVL() const
Return the EVL operand.
Definition VPlan.h:3999
VPWidenLoadEVLRecipe(VPWidenLoadRecipe &L, VPValue *Addr, VPValue &EVL, VPValue *Mask)
Definition VPlan.h:3979
bool usesFirstLaneOnly(const VPValue *Op) const override
Returns true if the recipe only uses the first lane of operand Op.
Definition VPlan.h:4009
A recipe for widening load operations, using the address to load from and an optional mask.
Definition VPlan.h:3923
bool usesFirstLaneOnly(const VPValue *Op) const override
Returns true if the recipe only uses the first lane of operand Op.
Definition VPlan.h:3954
unsigned getOpcode() const
Returns the opcode of the widened load.
Definition VPlan.h:3942
VPWidenLoadRecipe(LoadInst &Load, VPValue *Addr, VPValue *Mask, bool Consecutive, Align Alignment, const VPIRMetadata &Metadata, DebugLoc DL)
Definition VPlan.h:3924
VPWidenLoadRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:3933
VP_CLASSOF_IMPL(VPRecipeBase::VPWidenLoadSC)
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPWidenLoadRecipe.
Definition VPlan.h:3948
A recipe for widening store operations with vector-predication intrinsics, using the value to store,...
Definition VPlan.h:4085
VPValue * getStoredValue() const
Return the address accessed by this recipe.
Definition VPlan.h:4102
VPWidenStoreEVLRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:4095
VPWidenStoreEVLRecipe(VPWidenStoreRecipe &S, VPValue *Addr, VPValue *StoredVal, VPValue &EVL, VPValue *Mask)
Definition VPlan.h:4086
bool usesFirstLaneOnly(const VPValue *Op) const override
Returns true if the recipe only uses the first lane of operand Op.
Definition VPlan.h:4115
VPValue * getEVL() const
Return the EVL operand.
Definition VPlan.h:4105
A recipe for widening store operations, using the stored value, the address to store to and an option...
Definition VPlan.h:4031
VPWidenStoreRecipe(StoreInst &Store, VPValue *Addr, VPValue *StoredVal, VPValue *Mask, bool Consecutive, Align Alignment, const VPIRMetadata &Metadata, DebugLoc DL)
Definition VPlan.h:4032
VP_CLASSOF_IMPL(VPRecipeBase::VPWidenStoreSC)
VPValue * getStoredValue() const
Return the value stored by this recipe.
Definition VPlan.h:4049
VPWidenStoreRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:4040
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPWidenStoreRecipe.
Definition VPlan.h:4055
bool usesFirstLaneOnly(const VPValue *Op) const override
Returns true if the recipe only uses the first lane of operand Op.
Definition VPlan.h:4061
static VPMixin * castFailed()
Definition VPlan.h:4469
static bool isPossible(VPRecipeBase *R)
Used by isa.
Definition VPlan.h:4460
static VPMixin * doCast(VPRecipeBase *R)
Used by cast.
Definition VPlan.h:4463