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