LLVM 23.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"
32#include "llvm/ADT/Twine.h"
33#include "llvm/ADT/ilist.h"
34#include "llvm/ADT/ilist_node.h"
38#include "llvm/IR/DebugLoc.h"
39#include "llvm/IR/FMF.h"
40#include "llvm/IR/Operator.h"
43#include <cassert>
44#include <cstddef>
45#include <functional>
46#include <string>
47#include <utility>
48#include <variant>
49
50namespace llvm {
51
52class BasicBlock;
53class DominatorTree;
55class IRBuilderBase;
56struct VPTransformState;
57class raw_ostream;
59class SCEV;
60class Type;
61class VPBasicBlock;
62class VPBuilder;
63class VPDominatorTree;
64class VPRegionBlock;
65class VPlan;
66class VPLane;
68class VPlanSlp;
69class Value;
71
72struct VPCostContext;
73
74namespace Intrinsic {
75typedef unsigned ID;
76}
77
78using VPlanPtr = std::unique_ptr<VPlan>;
79
80/// VPBlockBase is the building block of the Hierarchical Control-Flow Graph.
81/// A VPBlockBase can be either a VPBasicBlock or a VPRegionBlock.
83 friend class VPBlockUtils;
84
85 const unsigned char SubclassID; ///< Subclass identifier (for isa/dyn_cast).
86
87 /// An optional name for the block.
88 std::string Name;
89
90 /// The immediate VPRegionBlock which this VPBlockBase belongs to, or null if
91 /// it is a topmost VPBlockBase.
92 VPRegionBlock *Parent = nullptr;
93
94 /// List of predecessor blocks.
96
97 /// List of successor blocks.
99
100 /// VPlan containing the block. Can only be set on the entry block of the
101 /// plan.
102 VPlan *Plan = nullptr;
103
104 /// Add \p Successor as the last successor to this block.
105 void appendSuccessor(VPBlockBase *Successor) {
106 assert(Successor && "Cannot add nullptr successor!");
107 Successors.push_back(Successor);
108 }
109
110 /// Add \p Predecessor as the last predecessor to this block.
111 void appendPredecessor(VPBlockBase *Predecessor) {
112 assert(Predecessor && "Cannot add nullptr predecessor!");
113 Predecessors.push_back(Predecessor);
114 }
115
116 /// Remove \p Predecessor from the predecessors of this block.
117 void removePredecessor(VPBlockBase *Predecessor) {
118 auto Pos = find(Predecessors, Predecessor);
119 assert(Pos && "Predecessor does not exist");
120 Predecessors.erase(Pos);
121 }
122
123 /// Remove \p Successor from the successors of this block.
124 void removeSuccessor(VPBlockBase *Successor) {
125 auto Pos = find(Successors, Successor);
126 assert(Pos && "Successor does not exist");
127 Successors.erase(Pos);
128 }
129
130 /// This function replaces one predecessor with another, useful when
131 /// trying to replace an old block in the CFG with a new one.
132 void replacePredecessor(VPBlockBase *Old, VPBlockBase *New) {
133 auto I = find(Predecessors, Old);
134 assert(I != Predecessors.end());
135 assert(Old->getParent() == New->getParent() &&
136 "replaced predecessor must have the same parent");
137 *I = New;
138 }
139
140 /// This function replaces one successor with another, useful when
141 /// trying to replace an old block in the CFG with a new one.
142 void replaceSuccessor(VPBlockBase *Old, VPBlockBase *New) {
143 auto I = find(Successors, Old);
144 assert(I != Successors.end());
145 assert(Old->getParent() == New->getParent() &&
146 "replaced successor must have the same parent");
147 *I = New;
148 }
149
150protected:
151 VPBlockBase(const unsigned char SC, const std::string &N)
152 : SubclassID(SC), Name(N) {}
153
154public:
155 /// An enumeration for keeping track of the concrete subclass of VPBlockBase
156 /// that are actually instantiated. Values of this enumeration are kept in the
157 /// SubclassID field of the VPBlockBase objects. They are used for concrete
158 /// type identification.
159 using VPBlockTy = enum { VPRegionBlockSC, VPBasicBlockSC, VPIRBasicBlockSC };
160
162
163 virtual ~VPBlockBase() = default;
164
165 const std::string &getName() const { return Name; }
166
167 void setName(const Twine &newName) { Name = newName.str(); }
168
169 /// \return an ID for the concrete type of this object.
170 /// This is used to implement the classof checks. This should not be used
171 /// for any other purpose, as the values may change as LLVM evolves.
172 unsigned getVPBlockID() const { return SubclassID; }
173
174 VPRegionBlock *getParent() { return Parent; }
175 const VPRegionBlock *getParent() const { return Parent; }
176
177 /// \return A pointer to the plan containing the current block.
178 VPlan *getPlan();
179 const VPlan *getPlan() const;
180
181 /// Sets the pointer of the plan containing the block. The block must be the
182 /// entry block into the VPlan.
183 void setPlan(VPlan *ParentPlan);
184
185 void setParent(VPRegionBlock *P) { Parent = P; }
186
187 /// \return the VPBasicBlock that is the entry of this VPBlockBase,
188 /// recursively, if the latter is a VPRegionBlock. Otherwise, if this
189 /// VPBlockBase is a VPBasicBlock, it is returned.
190 const VPBasicBlock *getEntryBasicBlock() const;
191 VPBasicBlock *getEntryBasicBlock();
192
193 /// \return the VPBasicBlock that is the exiting this VPBlockBase,
194 /// recursively, if the latter is a VPRegionBlock. Otherwise, if this
195 /// VPBlockBase is a VPBasicBlock, it is returned.
196 const VPBasicBlock *getExitingBasicBlock() const;
197 VPBasicBlock *getExitingBasicBlock();
198
199 const VPBlocksTy &getSuccessors() const { return Successors; }
200 VPBlocksTy &getSuccessors() { return Successors; }
201
204
205 const VPBlocksTy &getPredecessors() const { return Predecessors; }
206 VPBlocksTy &getPredecessors() { return Predecessors; }
207
208 /// \return the successor of this VPBlockBase if it has a single successor.
209 /// Otherwise return a null pointer.
211 return (Successors.size() == 1 ? *Successors.begin() : nullptr);
212 }
213
214 /// \return the predecessor of this VPBlockBase if it has a single
215 /// predecessor. Otherwise return a null pointer.
217 return (Predecessors.size() == 1 ? *Predecessors.begin() : nullptr);
218 }
219
220 size_t getNumSuccessors() const { return Successors.size(); }
221 size_t getNumPredecessors() const { return Predecessors.size(); }
222
223 /// Returns true if this block has any predecessors.
224 bool hasPredecessors() const { return !Predecessors.empty(); }
225
226 /// An Enclosing Block of a block B is any block containing B, including B
227 /// itself. \return the closest enclosing block starting from "this", which
228 /// has successors. \return the root enclosing block if all enclosing blocks
229 /// have no successors.
230 VPBlockBase *getEnclosingBlockWithSuccessors();
231
232 /// \return the closest enclosing block starting from "this", which has
233 /// predecessors. \return the root enclosing block if all enclosing blocks
234 /// have no predecessors.
235 VPBlockBase *getEnclosingBlockWithPredecessors();
236
237 /// \return the successors either attached directly to this VPBlockBase or, if
238 /// this VPBlockBase is the exit block of a VPRegionBlock and has no
239 /// successors of its own, search recursively for the first enclosing
240 /// VPRegionBlock that has successors and return them. If no such
241 /// VPRegionBlock exists, return the (empty) successors of the topmost
242 /// VPBlockBase reached.
244 return getEnclosingBlockWithSuccessors()->getSuccessors();
245 }
246
247 /// \return the hierarchical successor of this VPBlockBase if it has a single
248 /// hierarchical successor. Otherwise return a null pointer.
250 return getEnclosingBlockWithSuccessors()->getSingleSuccessor();
251 }
252
253 /// \return the predecessors either attached directly to this VPBlockBase or,
254 /// if this VPBlockBase is the entry block of a VPRegionBlock and has no
255 /// predecessors of its own, search recursively for the first enclosing
256 /// VPRegionBlock that has predecessors and return them. If no such
257 /// VPRegionBlock exists, return the (empty) predecessors of the topmost
258 /// VPBlockBase reached.
260 return getEnclosingBlockWithPredecessors()->getPredecessors();
261 }
262
263 /// \return the hierarchical predecessor of this VPBlockBase if it has a
264 /// single hierarchical predecessor. Otherwise return a null pointer.
268
269 /// Set a given VPBlockBase \p Successor as the single successor of this
270 /// VPBlockBase. This VPBlockBase is not added as predecessor of \p Successor.
271 /// This VPBlockBase must have no successors.
273 assert(Successors.empty() && "Setting one successor when others exist.");
274 assert(Successor->getParent() == getParent() &&
275 "connected blocks must have the same parent");
276 appendSuccessor(Successor);
277 }
278
279 /// Set two given VPBlockBases \p IfTrue and \p IfFalse to be the two
280 /// successors of this VPBlockBase. This VPBlockBase is not added as
281 /// predecessor of \p IfTrue or \p IfFalse. This VPBlockBase must have no
282 /// successors.
283 void setTwoSuccessors(VPBlockBase *IfTrue, VPBlockBase *IfFalse) {
284 assert(Successors.empty() && "Setting two successors when others exist.");
285 appendSuccessor(IfTrue);
286 appendSuccessor(IfFalse);
287 }
288
289 /// Set each VPBasicBlock in \p NewPreds as predecessor of this VPBlockBase.
290 /// This VPBlockBase must have no predecessors. This VPBlockBase is not added
291 /// as successor of any VPBasicBlock in \p NewPreds.
293 assert(Predecessors.empty() && "Block predecessors already set.");
294 for (auto *Pred : NewPreds)
295 appendPredecessor(Pred);
296 }
297
298 /// Set each VPBasicBlock in \p NewSuccss as successor of this VPBlockBase.
299 /// This VPBlockBase must have no successors. This VPBlockBase is not added
300 /// as predecessor of any VPBasicBlock in \p NewSuccs.
302 assert(Successors.empty() && "Block successors already set.");
303 for (auto *Succ : NewSuccs)
304 appendSuccessor(Succ);
305 }
306
307 /// Remove all the predecessor of this block.
308 void clearPredecessors() { Predecessors.clear(); }
309
310 /// Remove all the successors of this block.
311 void clearSuccessors() { Successors.clear(); }
312
313 /// Swap predecessors of the block. The block must have exactly 2
314 /// predecessors.
316 assert(Predecessors.size() == 2 && "must have 2 predecessors to swap");
317 std::swap(Predecessors[0], Predecessors[1]);
318 }
319
320 /// Swap successors of the block. The block must have exactly 2 successors.
321 // TODO: This should be part of introducing conditional branch recipes rather
322 // than being independent.
324 assert(Successors.size() == 2 && "must have 2 successors to swap");
325 std::swap(Successors[0], Successors[1]);
326 }
327
328 /// Returns the index for \p Pred in the blocks predecessors list.
329 unsigned getIndexForPredecessor(const VPBlockBase *Pred) const {
330 assert(count(Predecessors, Pred) == 1 &&
331 "must have Pred exactly once in Predecessors");
332 return std::distance(Predecessors.begin(), find(Predecessors, Pred));
333 }
334
335 /// Returns the index for \p Succ in the blocks successor list.
336 unsigned getIndexForSuccessor(const VPBlockBase *Succ) const {
337 assert(count(Successors, Succ) == 1 &&
338 "must have Succ exactly once in Successors");
339 return std::distance(Successors.begin(), find(Successors, Succ));
340 }
341
342 /// The method which generates the output IR that correspond to this
343 /// VPBlockBase, thereby "executing" the VPlan.
344 virtual void execute(VPTransformState *State) = 0;
345
346 /// Return the cost of the block.
348
349#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
350 void printAsOperand(raw_ostream &OS, bool PrintType = false) const {
351 OS << getName();
352 }
353
354 /// Print plain-text dump of this VPBlockBase to \p O, prefixing all lines
355 /// with \p Indent. \p SlotTracker is used to print unnamed VPValue's using
356 /// consequtive numbers.
357 ///
358 /// Note that the numbering is applied to the whole VPlan, so printing
359 /// individual blocks is consistent with the whole VPlan printing.
360 virtual void print(raw_ostream &O, const Twine &Indent,
361 VPSlotTracker &SlotTracker) const = 0;
362
363 /// Print plain-text dump of this VPlan to \p O.
364 void print(raw_ostream &O) const;
365
366 /// Print the successors of this block to \p O, prefixing all lines with \p
367 /// Indent.
368 void printSuccessors(raw_ostream &O, const Twine &Indent) const;
369
370 /// Dump this VPBlockBase to dbgs().
371 LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
372#endif
373
374 /// Clone the current block and it's recipes without updating the operands of
375 /// the cloned recipes, including all blocks in the single-entry single-exit
376 /// region for VPRegionBlocks.
377 virtual VPBlockBase *clone() = 0;
378};
379
380/// VPRecipeBase is a base class modeling a sequence of one or more output IR
381/// instructions. VPRecipeBase owns the VPValues it defines through VPDef
382/// and is responsible for deleting its defined values. Single-value
383/// recipes must inherit from VPSingleDef instead of inheriting from both
384/// VPRecipeBase and VPValue separately.
386 : public ilist_node_with_parent<VPRecipeBase, VPBasicBlock>,
387 public VPDef,
388 public VPUser {
389 friend VPBasicBlock;
390 friend class VPBlockUtils;
391
392 /// Subclass identifier (for isa/dyn_cast).
393 const unsigned char SubclassID;
394
395 /// Each VPRecipe belongs to a single VPBasicBlock.
396 VPBasicBlock *Parent = nullptr;
397
398 /// The debug location for the recipe.
399 DebugLoc DL;
400
401public:
402 /// An enumeration for keeping track of the concrete subclass of VPRecipeBase
403 /// that is actually instantiated. Values of this enumeration are kept in the
404 /// SubclassID field of the VPRecipeBase objects. They are used for concrete
405 /// type identification.
406 using VPRecipeTy = enum {
407 VPBranchOnMaskSC,
408 VPDerivedIVSC,
409 VPExpandSCEVSC,
410 VPExpressionSC,
411 VPIRInstructionSC,
412 VPInstructionSC,
413 VPInterleaveEVLSC,
414 VPInterleaveSC,
415 VPReductionEVLSC,
416 VPReductionSC,
417 VPReplicateSC,
418 VPScalarIVStepsSC,
419 VPVectorPointerSC,
420 VPVectorEndPointerSC,
421 VPWidenCallSC,
422 VPWidenCanonicalIVSC,
423 VPWidenCastSC,
424 VPWidenGEPSC,
425 VPWidenIntrinsicSC,
426 VPWidenLoadEVLSC,
427 VPWidenLoadSC,
428 VPWidenStoreEVLSC,
429 VPWidenStoreSC,
430 VPWidenSC,
431 VPBlendSC,
432 VPHistogramSC,
433 // START: Phi-like recipes. Need to be kept together.
434 VPWidenPHISC,
435 VPPredInstPHISC,
436 // START: SubclassID for recipes that inherit VPHeaderPHIRecipe.
437 // VPHeaderPHIRecipe need to be kept together.
438 VPCanonicalIVPHISC,
439 VPCurrentIterationPHISC,
440 VPActiveLaneMaskPHISC,
441 VPFirstOrderRecurrencePHISC,
442 VPWidenIntOrFpInductionSC,
443 VPWidenPointerInductionSC,
444 VPReductionPHISC,
445 // END: SubclassID for recipes that inherit VPHeaderPHIRecipe
446 // END: Phi-like recipes
447 VPFirstPHISC = VPWidenPHISC,
448 VPFirstHeaderPHISC = VPCanonicalIVPHISC,
449 VPLastHeaderPHISC = VPReductionPHISC,
450 VPLastPHISC = VPReductionPHISC,
451 };
452
453 VPRecipeBase(const unsigned char SC, ArrayRef<VPValue *> Operands,
455 : VPDef(), VPUser(Operands), SubclassID(SC), DL(DL) {}
456
457 ~VPRecipeBase() override = default;
458
459 /// Clone the current recipe.
460 virtual VPRecipeBase *clone() = 0;
461
462 /// \return the VPBasicBlock which this VPRecipe belongs to.
463 VPBasicBlock *getParent() { return Parent; }
464 const VPBasicBlock *getParent() const { return Parent; }
465
466 /// \return the VPRegionBlock which the recipe belongs to.
467 VPRegionBlock *getRegion();
468 const VPRegionBlock *getRegion() const;
469
470 /// The method which generates the output IR instructions that correspond to
471 /// this VPRecipe, thereby "executing" the VPlan.
472 virtual void execute(VPTransformState &State) = 0;
473
474 /// Return the cost of this recipe, taking into account if the cost
475 /// computation should be skipped and the ForceTargetInstructionCost flag.
476 /// Also takes care of printing the cost for debugging.
478
479 /// Insert an unlinked recipe into a basic block immediately before
480 /// the specified recipe.
481 void insertBefore(VPRecipeBase *InsertPos);
482 /// Insert an unlinked recipe into \p BB immediately before the insertion
483 /// point \p IP;
484 void insertBefore(VPBasicBlock &BB, iplist<VPRecipeBase>::iterator IP);
485
486 /// Insert an unlinked Recipe into a basic block immediately after
487 /// the specified Recipe.
488 void insertAfter(VPRecipeBase *InsertPos);
489
490 /// Unlink this recipe from its current VPBasicBlock and insert it into
491 /// the VPBasicBlock that MovePos lives in, right after MovePos.
492 void moveAfter(VPRecipeBase *MovePos);
493
494 /// Unlink this recipe and insert into BB before I.
495 ///
496 /// \pre I is a valid iterator into BB.
497 void moveBefore(VPBasicBlock &BB, iplist<VPRecipeBase>::iterator I);
498
499 /// This method unlinks 'this' from the containing basic block, but does not
500 /// delete it.
501 void removeFromParent();
502
503 /// This method unlinks 'this' from the containing basic block and deletes it.
504 ///
505 /// \returns an iterator pointing to the element after the erased one
507
508 /// \return an ID for the concrete type of this object.
509 unsigned getVPRecipeID() const { return SubclassID; }
510
511 /// Method to support type inquiry through isa, cast, and dyn_cast.
512 static inline bool classof(const VPDef *D) {
513 // All VPDefs are also VPRecipeBases.
514 return true;
515 }
516
517 static inline bool classof(const VPUser *U) { return true; }
518
519 /// Returns true if the recipe may have side-effects.
520 bool mayHaveSideEffects() const;
521
522 /// Returns true for PHI-like recipes.
523 bool isPhi() const;
524
525 /// Returns true if the recipe may read from memory.
526 bool mayReadFromMemory() const;
527
528 /// Returns true if the recipe may write to memory.
529 bool mayWriteToMemory() const;
530
531 /// Returns true if the recipe may read from or write to memory.
532 bool mayReadOrWriteMemory() const {
534 }
535
536 /// Returns the debug location of the recipe.
537 DebugLoc getDebugLoc() const { return DL; }
538
539 /// Return true if the recipe is a scalar cast.
540 bool isScalarCast() const;
541
542 /// Set the recipe's debug location to \p NewDL.
543 void setDebugLoc(DebugLoc NewDL) { DL = NewDL; }
544
545#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
546 /// Dump the recipe to stderr (for debugging).
547 LLVM_ABI_FOR_TEST void dump() const;
548
549 /// Print the recipe, delegating to printRecipe().
550 void print(raw_ostream &O, const Twine &Indent,
552#endif
553
554protected:
555 /// Compute the cost of this recipe either using a recipe's specialized
556 /// implementation or using the legacy cost model and the underlying
557 /// instructions.
558 virtual InstructionCost computeCost(ElementCount VF,
559 VPCostContext &Ctx) const;
560
561#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
562 /// Each concrete VPRecipe prints itself, without printing common information,
563 /// like debug info or metadata.
564 virtual void printRecipe(raw_ostream &O, const Twine &Indent,
565 VPSlotTracker &SlotTracker) const = 0;
566#endif
567};
568
569// Helper macro to define common classof implementations for recipes.
570#define VP_CLASSOF_IMPL(VPRecipeID) \
571 static inline bool classof(const VPRecipeBase *R) { \
572 return R->getVPRecipeID() == VPRecipeID; \
573 } \
574 static inline bool classof(const VPValue *V) { \
575 auto *R = V->getDefiningRecipe(); \
576 return R && R->getVPRecipeID() == VPRecipeID; \
577 } \
578 static inline bool classof(const VPUser *U) { \
579 auto *R = dyn_cast<VPRecipeBase>(U); \
580 return R && R->getVPRecipeID() == VPRecipeID; \
581 } \
582 static inline bool classof(const VPSingleDefRecipe *R) { \
583 return R->getVPRecipeID() == VPRecipeID; \
584 }
585
586/// VPSingleDef is a base class for recipes for modeling a sequence of one or
587/// more output IR that define a single result VPValue.
588/// Note that VPRecipeBase must be inherited from before VPValue.
590public:
591 VPSingleDefRecipe(const unsigned char SC, ArrayRef<VPValue *> Operands,
593 : VPRecipeBase(SC, Operands, DL), VPRecipeValue(this) {}
594
595 VPSingleDefRecipe(const unsigned char SC, ArrayRef<VPValue *> Operands,
597 : VPRecipeBase(SC, Operands, DL), VPRecipeValue(this, UV) {}
598
599 static inline bool classof(const VPRecipeBase *R) {
600 switch (R->getVPRecipeID()) {
601 case VPRecipeBase::VPDerivedIVSC:
602 case VPRecipeBase::VPExpandSCEVSC:
603 case VPRecipeBase::VPExpressionSC:
604 case VPRecipeBase::VPInstructionSC:
605 case VPRecipeBase::VPReductionEVLSC:
606 case VPRecipeBase::VPReductionSC:
607 case VPRecipeBase::VPReplicateSC:
608 case VPRecipeBase::VPScalarIVStepsSC:
609 case VPRecipeBase::VPVectorPointerSC:
610 case VPRecipeBase::VPVectorEndPointerSC:
611 case VPRecipeBase::VPWidenCallSC:
612 case VPRecipeBase::VPWidenCanonicalIVSC:
613 case VPRecipeBase::VPWidenCastSC:
614 case VPRecipeBase::VPWidenGEPSC:
615 case VPRecipeBase::VPWidenIntrinsicSC:
616 case VPRecipeBase::VPWidenSC:
617 case VPRecipeBase::VPBlendSC:
618 case VPRecipeBase::VPPredInstPHISC:
619 case VPRecipeBase::VPCanonicalIVPHISC:
620 case VPRecipeBase::VPCurrentIterationPHISC:
621 case VPRecipeBase::VPActiveLaneMaskPHISC:
622 case VPRecipeBase::VPFirstOrderRecurrencePHISC:
623 case VPRecipeBase::VPWidenPHISC:
624 case VPRecipeBase::VPWidenIntOrFpInductionSC:
625 case VPRecipeBase::VPWidenPointerInductionSC:
626 case VPRecipeBase::VPReductionPHISC:
627 return true;
628 case VPRecipeBase::VPBranchOnMaskSC:
629 case VPRecipeBase::VPInterleaveEVLSC:
630 case VPRecipeBase::VPInterleaveSC:
631 case VPRecipeBase::VPIRInstructionSC:
632 case VPRecipeBase::VPWidenLoadEVLSC:
633 case VPRecipeBase::VPWidenLoadSC:
634 case VPRecipeBase::VPWidenStoreEVLSC:
635 case VPRecipeBase::VPWidenStoreSC:
636 case VPRecipeBase::VPHistogramSC:
637 // TODO: Widened stores don't define a value, but widened loads do. Split
638 // the recipes to be able to make widened loads VPSingleDefRecipes.
639 return false;
640 }
641 llvm_unreachable("Unhandled VPRecipeID");
642 }
643
644 static inline bool classof(const VPValue *V) {
645 auto *R = V->getDefiningRecipe();
646 return R && classof(R);
647 }
648
649 static inline bool classof(const VPUser *U) {
650 auto *R = dyn_cast<VPRecipeBase>(U);
651 return R && classof(R);
652 }
653
654 VPSingleDefRecipe *clone() override = 0;
655
656 /// Returns the underlying instruction.
663
664#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
665 /// Print this VPSingleDefRecipe to dbgs() (for debugging).
667#endif
668};
669
670/// Class to record and manage LLVM IR flags.
673 enum class OperationType : unsigned char {
674 Cmp,
675 FCmp,
676 OverflowingBinOp,
677 Trunc,
678 DisjointOp,
679 PossiblyExactOp,
680 GEPOp,
681 FPMathOp,
682 NonNegOp,
683 ReductionOp,
684 Other
685 };
686
687public:
688 struct WrapFlagsTy {
689 char HasNUW : 1;
690 char HasNSW : 1;
691
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
859 OpType = Other.OpType;
860 AllFlags[0] = Other.AllFlags[0];
861 AllFlags[1] = Other.AllFlags[1];
862 }
863
864 /// Only keep flags also present in \p Other. \p Other must have the same
865 /// OpType as the current object.
866 void intersectFlags(const VPIRFlags &Other);
867
868 /// Drop all poison-generating flags.
870 // NOTE: This needs to be kept in-sync with
871 // Instruction::dropPoisonGeneratingFlags.
872 switch (OpType) {
873 case OperationType::OverflowingBinOp:
874 WrapFlags.HasNUW = false;
875 WrapFlags.HasNSW = false;
876 break;
877 case OperationType::Trunc:
878 TruncFlags.HasNUW = false;
879 TruncFlags.HasNSW = false;
880 break;
881 case OperationType::DisjointOp:
882 DisjointFlags.IsDisjoint = false;
883 break;
884 case OperationType::PossiblyExactOp:
885 ExactFlags.IsExact = false;
886 break;
887 case OperationType::GEPOp:
888 GEPFlagsStorage = 0;
889 break;
890 case OperationType::FPMathOp:
891 case OperationType::FCmp:
892 case OperationType::ReductionOp:
893 getFMFsRef().NoNaNs = false;
894 getFMFsRef().NoInfs = false;
895 break;
896 case OperationType::NonNegOp:
897 NonNegFlags.NonNeg = false;
898 break;
899 case OperationType::Cmp:
900 case OperationType::Other:
901 break;
902 }
903 }
904
905 /// Apply the IR flags to \p I.
906 void applyFlags(Instruction &I) const {
907 switch (OpType) {
908 case OperationType::OverflowingBinOp:
909 I.setHasNoUnsignedWrap(WrapFlags.HasNUW);
910 I.setHasNoSignedWrap(WrapFlags.HasNSW);
911 break;
912 case OperationType::Trunc:
913 I.setHasNoUnsignedWrap(TruncFlags.HasNUW);
914 I.setHasNoSignedWrap(TruncFlags.HasNSW);
915 break;
916 case OperationType::DisjointOp:
917 cast<PossiblyDisjointInst>(&I)->setIsDisjoint(DisjointFlags.IsDisjoint);
918 break;
919 case OperationType::PossiblyExactOp:
920 I.setIsExact(ExactFlags.IsExact);
921 break;
922 case OperationType::GEPOp:
923 cast<GetElementPtrInst>(&I)->setNoWrapFlags(
925 break;
926 case OperationType::FPMathOp:
927 case OperationType::FCmp: {
928 const FastMathFlagsTy &F = getFMFsRef();
929 I.setHasAllowReassoc(F.AllowReassoc);
930 I.setHasNoNaNs(F.NoNaNs);
931 I.setHasNoInfs(F.NoInfs);
932 I.setHasNoSignedZeros(F.NoSignedZeros);
933 I.setHasAllowReciprocal(F.AllowReciprocal);
934 I.setHasAllowContract(F.AllowContract);
935 I.setHasApproxFunc(F.ApproxFunc);
936 break;
937 }
938 case OperationType::NonNegOp:
939 I.setNonNeg(NonNegFlags.NonNeg);
940 break;
941 case OperationType::ReductionOp:
942 llvm_unreachable("reduction ops should not use applyFlags");
943 case OperationType::Cmp:
944 case OperationType::Other:
945 break;
946 }
947 }
948
950 assert((OpType == OperationType::Cmp || OpType == OperationType::FCmp) &&
951 "recipe doesn't have a compare predicate");
952 uint8_t Storage = OpType == OperationType::FCmp ? FCmpFlags.CmpPredStorage
955 }
956
958 assert((OpType == OperationType::Cmp || OpType == OperationType::FCmp) &&
959 "recipe doesn't have a compare predicate");
960 if (OpType == OperationType::FCmp)
962 else
964 assert(getPredicate() == Pred && "predicate truncated");
965 }
966
970
971 /// Returns true if the recipe has a comparison predicate.
972 bool hasPredicate() const {
973 return OpType == OperationType::Cmp || OpType == OperationType::FCmp;
974 }
975
976 /// Returns true if the recipe has fast-math flags.
977 bool hasFastMathFlags() const {
978 return OpType == OperationType::FPMathOp || OpType == OperationType::FCmp ||
979 OpType == OperationType::ReductionOp;
980 }
981
983
984 /// Returns true if the recipe has non-negative flag.
985 bool hasNonNegFlag() const { return OpType == OperationType::NonNegOp; }
986
987 bool isNonNeg() const {
988 assert(OpType == OperationType::NonNegOp &&
989 "recipe doesn't have a NNEG flag");
990 return NonNegFlags.NonNeg;
991 }
992
993 bool hasNoUnsignedWrap() const {
994 switch (OpType) {
995 case OperationType::OverflowingBinOp:
996 return WrapFlags.HasNUW;
997 case OperationType::Trunc:
998 return TruncFlags.HasNUW;
999 default:
1000 llvm_unreachable("recipe doesn't have a NUW flag");
1001 }
1002 }
1003
1004 bool hasNoSignedWrap() const {
1005 switch (OpType) {
1006 case OperationType::OverflowingBinOp:
1007 return WrapFlags.HasNSW;
1008 case OperationType::Trunc:
1009 return TruncFlags.HasNSW;
1010 default:
1011 llvm_unreachable("recipe doesn't have a NSW flag");
1012 }
1013 }
1014
1015 bool isDisjoint() const {
1016 assert(OpType == OperationType::DisjointOp &&
1017 "recipe cannot have a disjoing flag");
1018 return DisjointFlags.IsDisjoint;
1019 }
1020
1022 assert(OpType == OperationType::ReductionOp &&
1023 "recipe doesn't have reduction flags");
1024 return static_cast<RecurKind>(ReductionFlags.Kind);
1025 }
1026
1027 bool isReductionOrdered() const {
1028 assert(OpType == OperationType::ReductionOp &&
1029 "recipe doesn't have reduction flags");
1030 return ReductionFlags.IsOrdered;
1031 }
1032
1033 bool isReductionInLoop() const {
1034 assert(OpType == OperationType::ReductionOp &&
1035 "recipe doesn't have reduction flags");
1036 return ReductionFlags.IsInLoop;
1037 }
1038
1039private:
1040 /// Get a reference to the fast-math flags for FPMathOp, FCmp or ReductionOp.
1041 FastMathFlagsTy &getFMFsRef() {
1042 if (OpType == OperationType::FCmp)
1043 return FCmpFlags.FMFs;
1044 if (OpType == OperationType::ReductionOp)
1045 return ReductionFlags.FMFs;
1046 return FMFs;
1047 }
1048 const FastMathFlagsTy &getFMFsRef() const {
1049 if (OpType == OperationType::FCmp)
1050 return FCmpFlags.FMFs;
1051 if (OpType == OperationType::ReductionOp)
1052 return ReductionFlags.FMFs;
1053 return FMFs;
1054 }
1055
1056public:
1057 /// Returns default flags for \p Opcode for opcodes that support it, asserts
1058 /// otherwise. Opcodes not supporting default flags include compares and
1059 /// ComputeReductionResult.
1060 static VPIRFlags getDefaultFlags(unsigned Opcode);
1061
1062#if !defined(NDEBUG)
1063 /// Returns true if the set flags are valid for \p Opcode.
1064 LLVM_ABI_FOR_TEST bool flagsValidForOpcode(unsigned Opcode) const;
1065
1066 /// Returns true if \p Opcode has its required flags set.
1067 LLVM_ABI_FOR_TEST bool hasRequiredFlagsForOpcode(unsigned Opcode) 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.
1081 VPRecipeWithIRFlags(const unsigned char SC, ArrayRef<VPValue *> Operands,
1082 const VPIRFlags &Flags,
1084 : VPSingleDefRecipe(SC, Operands, DL), VPIRFlags(Flags) {}
1085
1086 static inline bool classof(const VPRecipeBase *R) {
1087 return R->getVPRecipeID() == VPRecipeBase::VPBlendSC ||
1088 R->getVPRecipeID() == VPRecipeBase::VPInstructionSC ||
1089 R->getVPRecipeID() == VPRecipeBase::VPWidenSC ||
1090 R->getVPRecipeID() == VPRecipeBase::VPWidenGEPSC ||
1091 R->getVPRecipeID() == VPRecipeBase::VPWidenCallSC ||
1092 R->getVPRecipeID() == VPRecipeBase::VPWidenCastSC ||
1093 R->getVPRecipeID() == VPRecipeBase::VPWidenIntrinsicSC ||
1094 R->getVPRecipeID() == VPRecipeBase::VPReductionSC ||
1095 R->getVPRecipeID() == VPRecipeBase::VPReductionEVLSC ||
1096 R->getVPRecipeID() == VPRecipeBase::VPReplicateSC ||
1097 R->getVPRecipeID() == VPRecipeBase::VPVectorEndPointerSC ||
1098 R->getVPRecipeID() == VPRecipeBase::VPVectorPointerSC;
1099 }
1100
1101 static inline bool classof(const VPUser *U) {
1102 auto *R = dyn_cast<VPRecipeBase>(U);
1103 return R && classof(R);
1104 }
1105
1106 static inline bool classof(const VPValue *V) {
1107 auto *R = V->getDefiningRecipe();
1108 return R && classof(R);
1109 }
1110
1112
1113 static inline bool classof(const VPSingleDefRecipe *R) {
1114 return classof(static_cast<const VPRecipeBase *>(R));
1115 }
1116
1117 void execute(VPTransformState &State) override = 0;
1118
1119 /// Compute the cost for this recipe for \p VF, using \p Opcode and \p Ctx.
1121 VPCostContext &Ctx) const;
1122};
1123
1124/// Helper to access the operand that contains the unroll part for this recipe
1125/// after unrolling.
1126template <unsigned PartOpIdx> class LLVM_ABI_FOR_TEST VPUnrollPartAccessor {
1127protected:
1128 /// Return the VPValue operand containing the unroll part or null if there is
1129 /// no such operand.
1130 VPValue *getUnrollPartOperand(const VPUser &U) const;
1131
1132 /// Return the unroll part.
1133 unsigned getUnrollPart(const VPUser &U) const;
1134};
1135
1136/// Helper to manage IR metadata for recipes. It filters out metadata that
1137/// cannot be propagated.
1140
1141public:
1142 VPIRMetadata() = default;
1143
1144 /// Adds metatadata that can be preserved from the original instruction
1145 /// \p I.
1147
1148 /// Copy constructor for cloning.
1150
1152
1153 /// Add all metadata to \p I.
1154 void applyMetadata(Instruction &I) const;
1155
1156 /// Set metadata with kind \p Kind to \p Node. If metadata with \p Kind
1157 /// already exists, it will be replaced. Otherwise, it will be added.
1158 void setMetadata(unsigned Kind, MDNode *Node) {
1159 auto It =
1160 llvm::find_if(Metadata, [Kind](const std::pair<unsigned, MDNode *> &P) {
1161 return P.first == Kind;
1162 });
1163 if (It != Metadata.end())
1164 It->second = Node;
1165 else
1166 Metadata.emplace_back(Kind, Node);
1167 }
1168
1169 /// Intersect this VPIRMetadata object with \p MD, keeping only metadata
1170 /// nodes that are common to both.
1171 void intersect(const VPIRMetadata &MD);
1172
1173 /// Get metadata of kind \p Kind. Returns nullptr if not found.
1174 MDNode *getMetadata(unsigned Kind) const {
1175 auto It =
1176 find_if(Metadata, [Kind](const auto &P) { return P.first == Kind; });
1177 return It != Metadata.end() ? It->second : nullptr;
1178 }
1179
1180#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1181 /// Print metadata with node IDs.
1182 void print(raw_ostream &O, VPSlotTracker &SlotTracker) const;
1183#endif
1184};
1185
1186/// This is a concrete Recipe that models a single VPlan-level instruction.
1187/// While as any Recipe it may generate a sequence of IR instructions when
1188/// executed, these instructions would always form a single-def expression as
1189/// the VPInstruction is also a single def-use vertex. Most VPInstruction
1190/// opcodes can take an optional mask. Masks may be assigned during
1191/// predication.
1193 public VPIRMetadata {
1194 friend class VPlanSlp;
1195
1196public:
1197 /// VPlan opcodes, extending LLVM IR with idiomatics instructions.
1198 enum {
1200 Instruction::OtherOpsEnd + 1, // Combines the incoming and previous
1201 // values of a first-order recurrence.
1205 // Creates a mask where each lane is active (true) whilst the current
1206 // counter (first operand + index) is less than the second operand. i.e.
1207 // mask[i] = icmpt ult (op0 + i), op1
1208 // The size of the mask returned is VF * Multiplier (UF, third op).
1212 // Increment the canonical IV separately for each unrolled part.
1214 // Abstract instruction that compares two values and branches. This is
1215 // lowered to ICmp + BranchOnCond during VPlan to VPlan transformation.
1218 // Branch with 2 boolean condition operands and 3 successors. If condition
1219 // 0 is true, branches to successor 0; if condition 1 is true, branches to
1220 // successor 1; otherwise branches to successor 2. Expanded after region
1221 // dissolution into: (1) an OR of the two conditions branching to
1222 // middle.split or successor 2, and (2) middle.split branching to successor
1223 // 0 or successor 1 based on condition 0.
1226 /// Given operands of (the same) struct type, creates a struct of fixed-
1227 /// width vectors each containing a struct field of all operands. The
1228 /// number of operands matches the element count of every vector.
1230 /// Creates a fixed-width vector containing all operands. The number of
1231 /// operands matches the vector element count.
1233 /// Extracts all lanes from its (non-scalable) vector operand. This is an
1234 /// abstract VPInstruction whose single defined VPValue represents VF
1235 /// scalars extracted from a vector, to be replaced by VF ExtractElement
1236 /// VPInstructions.
1238 /// Compute the final result of a AnyOf reduction with select(cmp(),x,y),
1239 /// where one of (x,y) is loop invariant, and both x and y are integer type.
1242 // Extracts the last part of its operand. Removed during unrolling.
1244 // Extracts the last lane of its vector operand, per part.
1246 // Extracts the second-to-last lane from its operand or the second-to-last
1247 // part if it is scalar. In the latter case, the recipe will be removed
1248 // during unrolling.
1250 LogicalAnd, // Non-poison propagating logical And.
1251 LogicalOr, // Non-poison propagating logical Or.
1252 // Add an offset in bytes (second operand) to a base pointer (first
1253 // operand). Only generates scalar values (either for the first lane only or
1254 // for all lanes, depending on its uses).
1256 // Add a vector offset in bytes (second operand) to a scalar base pointer
1257 // (first operand).
1259 // Returns a scalar boolean value, which is true if any lane of its
1260 // (boolean) vector operands is true. It produces the reduced value across
1261 // all unrolled iterations. Unrolling will add all copies of its original
1262 // operand as additional operands. AnyOf is poison-safe as all operands
1263 // will be frozen.
1265 // Calculates the first active lane index of the vector predicate operands.
1266 // It produces the lane index across all unrolled iterations. Unrolling will
1267 // add all copies of its original operand as additional operands.
1268 // Implemented with @llvm.experimental.cttz.elts, but returns the expected
1269 // result even with operands that are all zeroes.
1271 // Calculates the last active lane index of the vector predicate operands.
1272 // The predicates must be prefix-masks (all 1s before all 0s). Used when
1273 // tail-folding to extract the correct live-out value from the last active
1274 // iteration. It produces the lane index across all unrolled iterations.
1275 // Unrolling will add all copies of its original operand as additional
1276 // operands.
1278 // Returns a reversed vector for the operand.
1280
1281 // The opcodes below are used for VPInstructionWithType.
1282 //
1283 /// Scale the first operand (vector step) by the second operand
1284 /// (scalar-step). Casts both operands to the result type if needed.
1286 /// Start vector for reductions with 3 operands: the original start value,
1287 /// the identity value for the reduction and an integer indicating the
1288 /// scaling factor.
1290 // Creates a step vector starting from 0 to VF with a step of 1.
1292 /// Extracts a single lane (first operand) from a set of vector operands.
1293 /// The lane specifies an index into a vector formed by combining all vector
1294 /// operands (all operands after the first one).
1296 /// Explicit user for the resume phi of the canonical induction in the main
1297 /// VPlan, used by the epilogue vector loop.
1299 /// Extracts the last active lane from a set of vectors. The first operand
1300 /// is the default value if no lanes in the masks are active. Conceptually,
1301 /// this concatenates all data vectors (odd operands), concatenates all
1302 /// masks (even operands -- ignoring the default value), and returns the
1303 /// last active value from the combined data vector using the combined mask.
1305
1306 /// Returns the value for vscale.
1308 /// Compute the exiting value of a wide induction after vectorization, that
1309 /// is the value of the last lane of the induction increment (i.e. its
1310 /// backedge value). Has the wide induction recipe as operand.
1314 };
1315
1316 /// Returns true if this VPInstruction generates scalar values for all lanes.
1317 /// Most VPInstructions generate a single value per part, either vector or
1318 /// scalar. VPReplicateRecipe takes care of generating multiple (scalar)
1319 /// values per all lanes, stemming from an original ingredient. This method
1320 /// identifies the (rare) cases of VPInstructions that do so as well, w/o an
1321 /// underlying ingredient.
1322 bool doesGeneratePerAllLanes() const;
1323
1324 /// Return the number of operands determined by the opcode of the
1325 /// VPInstruction, excluding mask. Returns -1u if the number of operands
1326 /// cannot be determined directly by the opcode.
1327 unsigned getNumOperandsForOpcode() const;
1328
1329private:
1330 typedef unsigned char OpcodeTy;
1331 OpcodeTy Opcode;
1332
1333 /// An optional name that can be used for the generated IR instruction.
1334 std::string Name;
1335
1336 /// Returns true if we can generate a scalar for the first lane only if
1337 /// needed.
1338 bool canGenerateScalarForFirstLane() const;
1339
1340 /// Utility methods serving execute(): generates a single vector instance of
1341 /// the modeled instruction. \returns the generated value. . In some cases an
1342 /// existing value is returned rather than a generated one.
1343 Value *generate(VPTransformState &State);
1344
1345 /// Returns true if the VPInstruction does not need masking.
1346 bool alwaysUnmasked() const {
1347 if (Opcode == VPInstruction::MaskedCond)
1348 return false;
1349
1350 // For now only VPInstructions with underlying values use masks.
1351 // TODO: provide masks to VPInstructions w/o underlying values.
1352 if (!getUnderlyingValue())
1353 return true;
1354
1355 return Opcode == Instruction::PHI || Opcode == Instruction::GetElementPtr;
1356 }
1357
1358public:
1359 VPInstruction(unsigned Opcode, ArrayRef<VPValue *> Operands,
1360 const VPIRFlags &Flags = {}, const VPIRMetadata &MD = {},
1361 DebugLoc DL = DebugLoc::getUnknown(), const Twine &Name = "");
1362
1363 VP_CLASSOF_IMPL(VPRecipeBase::VPInstructionSC)
1364
1365 VPInstruction *clone() override {
1366 auto *New = new VPInstruction(Opcode, operands(), *this, *this,
1367 getDebugLoc(), Name);
1368 if (getUnderlyingValue())
1369 New->setUnderlyingValue(getUnderlyingInstr());
1370 return New;
1371 }
1372
1373 unsigned getOpcode() const { return Opcode; }
1374
1375 /// Generate the instruction.
1376 /// TODO: We currently execute only per-part unless a specific instance is
1377 /// provided.
1378 void execute(VPTransformState &State) override;
1379
1380 /// Return the cost of this VPInstruction.
1381 InstructionCost computeCost(ElementCount VF,
1382 VPCostContext &Ctx) const override;
1383
1384#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1385 /// Print the VPInstruction to dbgs() (for debugging).
1386 LLVM_DUMP_METHOD void dump() const;
1387#endif
1388
1389 bool hasResult() const {
1390 // CallInst may or may not have a result, depending on the called function.
1391 // Conservatively return calls have results for now.
1392 switch (getOpcode()) {
1393 case Instruction::Ret:
1394 case Instruction::Br:
1395 case Instruction::Store:
1396 case Instruction::Switch:
1397 case Instruction::IndirectBr:
1398 case Instruction::Resume:
1399 case Instruction::CatchRet:
1400 case Instruction::Unreachable:
1401 case Instruction::Fence:
1402 case Instruction::AtomicRMW:
1406 return false;
1407 default:
1408 return true;
1409 }
1410 }
1411
1412 /// Returns true if the VPInstruction has a mask operand.
1413 bool isMasked() const {
1414 unsigned NumOpsForOpcode = getNumOperandsForOpcode();
1415 // VPInstructions without a fixed number of operands cannot be masked.
1416 if (NumOpsForOpcode == -1u)
1417 return false;
1418 return NumOpsForOpcode + 1 == getNumOperands();
1419 }
1420
1421 /// Returns the number of operands, excluding the mask if the VPInstruction is
1422 /// masked.
1423 unsigned getNumOperandsWithoutMask() const {
1424 return getNumOperands() - isMasked();
1425 }
1426
1427 /// Add mask \p Mask to an unmasked VPInstruction, if it needs masking.
1428 void addMask(VPValue *Mask) {
1429 assert(!isMasked() && "recipe is already masked");
1430 if (alwaysUnmasked())
1431 return;
1432 addOperand(Mask);
1433 }
1434
1435 /// Returns the mask for the VPInstruction. Returns nullptr for unmasked
1436 /// VPInstructions.
1437 VPValue *getMask() const {
1438 return isMasked() ? getOperand(getNumOperands() - 1) : nullptr;
1439 }
1440
1441 /// Returns an iterator range over the operands excluding the mask operand
1442 /// if present.
1449
1450 /// Returns true if the underlying opcode may read from or write to memory.
1451 bool opcodeMayReadOrWriteFromMemory() const;
1452
1453 /// Returns true if the recipe only uses the first lane of operand \p Op.
1454 bool usesFirstLaneOnly(const VPValue *Op) const override;
1455
1456 /// Returns true if the recipe only uses the first part of operand \p Op.
1457 bool usesFirstPartOnly(const VPValue *Op) const override;
1458
1459 /// Returns true if this VPInstruction produces a scalar value from a vector,
1460 /// e.g. by performing a reduction or extracting a lane.
1461 bool isVectorToScalar() const;
1462
1463 /// Returns true if this VPInstruction's operands are single scalars and the
1464 /// result is also a single scalar.
1465 bool isSingleScalar() const;
1466
1467 /// Returns the symbolic name assigned to the VPInstruction.
1468 StringRef getName() const { return Name; }
1469
1470 /// Set the symbolic name for the VPInstruction.
1471 void setName(StringRef NewName) { Name = NewName.str(); }
1472
1473protected:
1474#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1475 /// Print the VPInstruction to \p O.
1476 void printRecipe(raw_ostream &O, const Twine &Indent,
1477 VPSlotTracker &SlotTracker) const override;
1478#endif
1479};
1480
1481/// A specialization of VPInstruction augmenting it with a dedicated result
1482/// type, to be used when the opcode and operands of the VPInstruction don't
1483/// directly determine the result type. Note that there is no separate recipe ID
1484/// for VPInstructionWithType; it shares the same ID as VPInstruction and is
1485/// distinguished purely by the opcode.
1487 /// Scalar result type produced by the recipe.
1488 Type *ResultTy;
1489
1490public:
1492 Type *ResultTy, const VPIRFlags &Flags = {},
1493 const VPIRMetadata &Metadata = {},
1495 const Twine &Name = "")
1496 : VPInstruction(Opcode, Operands, Flags, Metadata, DL, Name),
1497 ResultTy(ResultTy) {}
1498
1499 static inline bool classof(const VPRecipeBase *R) {
1500 // VPInstructionWithType are VPInstructions with specific opcodes requiring
1501 // type information.
1502 if (R->isScalarCast())
1503 return true;
1504 auto *VPI = dyn_cast<VPInstruction>(R);
1505 if (!VPI)
1506 return false;
1507 switch (VPI->getOpcode()) {
1511 case Instruction::Load:
1512 return true;
1513 default:
1514 return false;
1515 }
1516 }
1517
1518 static inline bool classof(const VPUser *R) {
1520 }
1521
1522 VPInstruction *clone() override {
1523 auto *New =
1525 *this, *this, getDebugLoc(), getName());
1526 New->setUnderlyingValue(getUnderlyingValue());
1527 return New;
1528 }
1529
1530 void execute(VPTransformState &State) override;
1531
1532 /// Return the cost of this VPInstruction.
1534 VPCostContext &Ctx) const override {
1535 // TODO: Compute accurate cost after retiring the legacy cost model.
1536 return 0;
1537 }
1538
1539 Type *getResultType() const { return ResultTy; }
1540
1541protected:
1542#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1543 /// Print the recipe.
1544 void printRecipe(raw_ostream &O, const Twine &Indent,
1545 VPSlotTracker &SlotTracker) const override;
1546#endif
1547};
1548
1549/// Helper type to provide functions to access incoming values and blocks for
1550/// phi-like recipes.
1552protected:
1553 /// Return a VPRecipeBase* to the current object.
1554 virtual const VPRecipeBase *getAsRecipe() const = 0;
1555
1556public:
1557 virtual ~VPPhiAccessors() = default;
1558
1559 /// Returns the incoming VPValue with index \p Idx.
1560 VPValue *getIncomingValue(unsigned Idx) const {
1561 return getAsRecipe()->getOperand(Idx);
1562 }
1563
1564 /// Returns the incoming block with index \p Idx.
1565 const VPBasicBlock *getIncomingBlock(unsigned Idx) const;
1566
1567 /// Returns the incoming value for \p VPBB. \p VPBB must be an incoming block.
1568 VPValue *getIncomingValueForBlock(const VPBasicBlock *VPBB) const;
1569
1570 /// Sets the incoming value for \p VPBB to \p V. \p VPBB must be an incoming
1571 /// block.
1572 void setIncomingValueForBlock(const VPBasicBlock *VPBB, VPValue *V) const;
1573
1574 /// Returns the number of incoming values, also number of incoming blocks.
1575 virtual unsigned getNumIncoming() const {
1576 return getAsRecipe()->getNumOperands();
1577 }
1578
1579 /// Returns an interator range over the incoming values.
1581 return make_range(getAsRecipe()->op_begin(),
1582 getAsRecipe()->op_begin() + getNumIncoming());
1583 }
1584
1586 detail::index_iterator, std::function<const VPBasicBlock *(size_t)>>>;
1587
1588 /// Returns an iterator range over the incoming blocks.
1590 std::function<const VPBasicBlock *(size_t)> GetBlock = [this](size_t Idx) {
1591 return getIncomingBlock(Idx);
1592 };
1593 return map_range(index_range(0, getNumIncoming()), GetBlock);
1594 }
1595
1596 /// Returns an iterator range over pairs of incoming values and corresponding
1597 /// incoming blocks.
1603
1604 /// Removes the incoming value for \p IncomingBlock, which must be a
1605 /// predecessor.
1606 void removeIncomingValueFor(VPBlockBase *IncomingBlock) const;
1607
1608#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1609 /// Print the recipe.
1611#endif
1612};
1613
1616 const Twine &Name = "")
1617 : VPInstruction(Instruction::PHI, Operands, Flags, {}, DL, Name) {}
1618
1619 static inline bool classof(const VPUser *U) {
1620 auto *VPI = dyn_cast<VPInstruction>(U);
1621 return VPI && VPI->getOpcode() == Instruction::PHI;
1622 }
1623
1624 static inline bool classof(const VPValue *V) {
1625 auto *VPI = dyn_cast<VPInstruction>(V);
1626 return VPI && VPI->getOpcode() == Instruction::PHI;
1627 }
1628
1629 static inline bool classof(const VPSingleDefRecipe *SDR) {
1630 auto *VPI = dyn_cast<VPInstruction>(SDR);
1631 return VPI && VPI->getOpcode() == Instruction::PHI;
1632 }
1633
1634 VPPhi *clone() override {
1635 auto *PhiR = new VPPhi(operands(), *this, getDebugLoc(), getName());
1636 PhiR->setUnderlyingValue(getUnderlyingValue());
1637 return PhiR;
1638 }
1639
1640 void execute(VPTransformState &State) override;
1641
1642protected:
1643#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1644 /// Print the recipe.
1645 void printRecipe(raw_ostream &O, const Twine &Indent,
1646 VPSlotTracker &SlotTracker) const override;
1647#endif
1648
1649 const VPRecipeBase *getAsRecipe() const override { return this; }
1650};
1651
1652/// A recipe to wrap on original IR instruction not to be modified during
1653/// execution, except for PHIs. PHIs are modeled via the VPIRPhi subclass.
1654/// Expect PHIs, VPIRInstructions cannot have any operands.
1656 Instruction &I;
1657
1658protected:
1659 /// VPIRInstruction::create() should be used to create VPIRInstructions, as
1660 /// subclasses may need to be created, e.g. VPIRPhi.
1662 : VPRecipeBase(VPRecipeBase::VPIRInstructionSC, {}), I(I) {}
1663
1664public:
1665 ~VPIRInstruction() override = default;
1666
1667 /// Create a new VPIRPhi for \p \I, if it is a PHINode, otherwise create a
1668 /// VPIRInstruction.
1670
1671 VP_CLASSOF_IMPL(VPRecipeBase::VPIRInstructionSC)
1672
1674 auto *R = create(I);
1675 for (auto *Op : operands())
1676 R->addOperand(Op);
1677 return R;
1678 }
1679
1680 void execute(VPTransformState &State) override;
1681
1682 /// Return the cost of this VPIRInstruction.
1684 computeCost(ElementCount VF, VPCostContext &Ctx) const override;
1685
1686 Instruction &getInstruction() const { return I; }
1687
1688 bool usesScalars(const VPValue *Op) const override {
1690 "Op must be an operand of the recipe");
1691 return true;
1692 }
1693
1694 bool usesFirstPartOnly(const VPValue *Op) const override {
1696 "Op must be an operand of the recipe");
1697 return true;
1698 }
1699
1700 bool usesFirstLaneOnly(const VPValue *Op) const override {
1702 "Op must be an operand of the recipe");
1703 return true;
1704 }
1705
1706protected:
1707#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1708 /// Print the recipe.
1709 void printRecipe(raw_ostream &O, const Twine &Indent,
1710 VPSlotTracker &SlotTracker) const override;
1711#endif
1712};
1713
1714/// An overlay for VPIRInstructions wrapping PHI nodes enabling convenient use
1715/// cast/dyn_cast/isa and execute() implementation. A single VPValue operand is
1716/// allowed, and it is used to add a new incoming value for the single
1717/// predecessor VPBB.
1719 public VPPhiAccessors {
1721
1722 static inline bool classof(const VPRecipeBase *U) {
1723 auto *R = dyn_cast<VPIRInstruction>(U);
1724 return R && isa<PHINode>(R->getInstruction());
1725 }
1726
1727 static inline bool classof(const VPUser *U) {
1728 auto *R = dyn_cast<VPRecipeBase>(U);
1729 return R && classof(R);
1730 }
1731
1733
1734 void execute(VPTransformState &State) override;
1735
1736protected:
1737#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1738 /// Print the recipe.
1739 void printRecipe(raw_ostream &O, const Twine &Indent,
1740 VPSlotTracker &SlotTracker) const override;
1741#endif
1742
1743 const VPRecipeBase *getAsRecipe() const override { return this; }
1744};
1745
1746/// VPWidenRecipe is a recipe for producing a widened instruction using the
1747/// opcode and operands of the recipe. This recipe covers most of the
1748/// traditional vectorization cases where each recipe transforms into a
1749/// vectorized version of itself.
1751 public VPIRMetadata {
1752 unsigned Opcode;
1753
1754public:
1756 const VPIRFlags &Flags = {}, const VPIRMetadata &Metadata = {},
1757 DebugLoc DL = {})
1758 : VPRecipeWithIRFlags(VPRecipeBase::VPWidenSC, Operands, Flags, DL),
1759 VPIRMetadata(Metadata), Opcode(I.getOpcode()) {
1760 setUnderlyingValue(&I);
1761 }
1762
1763 VPWidenRecipe(unsigned Opcode, ArrayRef<VPValue *> Operands,
1764 const VPIRFlags &Flags = {}, const VPIRMetadata &Metadata = {},
1765 DebugLoc DL = {})
1766 : VPRecipeWithIRFlags(VPRecipeBase::VPWidenSC, Operands, Flags, DL),
1767 VPIRMetadata(Metadata), Opcode(Opcode) {}
1768
1769 ~VPWidenRecipe() override = default;
1770
1771 VPWidenRecipe *clone() override {
1772 if (auto *UV = getUnderlyingValue())
1773 return new VPWidenRecipe(*cast<Instruction>(UV), operands(), *this, *this,
1774 getDebugLoc());
1775 return new VPWidenRecipe(Opcode, operands(), *this, *this, getDebugLoc());
1776 }
1777
1778 VP_CLASSOF_IMPL(VPRecipeBase::VPWidenSC)
1779
1780 /// Produce a widened instruction using the opcode and operands of the recipe,
1781 /// processing State.VF elements.
1782 void execute(VPTransformState &State) override;
1783
1784 /// Return the cost of this VPWidenRecipe.
1785 InstructionCost computeCost(ElementCount VF,
1786 VPCostContext &Ctx) const override;
1787
1788 unsigned getOpcode() const { return Opcode; }
1789
1790protected:
1791#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1792 /// Print the recipe.
1793 void printRecipe(raw_ostream &O, const Twine &Indent,
1794 VPSlotTracker &SlotTracker) const override;
1795#endif
1796
1797 /// Returns true if the recipe only uses the first lane of operand \p Op.
1798 bool usesFirstLaneOnly(const VPValue *Op) const override {
1800 "Op must be an operand of the recipe");
1801 return Opcode == Instruction::Select && Op == getOperand(0) &&
1802 Op->isDefinedOutsideLoopRegions();
1803 }
1804};
1805
1806/// VPWidenCastRecipe is a recipe to create vector cast instructions.
1808 /// Cast instruction opcode.
1809 Instruction::CastOps Opcode;
1810
1811 /// Result type for the cast.
1812 Type *ResultTy;
1813
1814public:
1816 CastInst *CI = nullptr, const VPIRFlags &Flags = {},
1817 const VPIRMetadata &Metadata = {},
1819 : VPRecipeWithIRFlags(VPRecipeBase::VPWidenCastSC, Op, Flags, DL),
1820 VPIRMetadata(Metadata), Opcode(Opcode), ResultTy(ResultTy) {
1821 assert(flagsValidForOpcode(Opcode) &&
1822 "Set flags not supported for the provided opcode");
1824 "Opcode requires specific flags to be set");
1826 }
1827
1828 ~VPWidenCastRecipe() override = default;
1829
1831 return new VPWidenCastRecipe(Opcode, getOperand(0), ResultTy,
1833 *this, *this, getDebugLoc());
1834 }
1835
1836 VP_CLASSOF_IMPL(VPRecipeBase::VPWidenCastSC)
1837
1838 /// Produce widened copies of the cast.
1839 LLVM_ABI_FOR_TEST void execute(VPTransformState &State) override;
1840
1841 /// Return the cost of this VPWidenCastRecipe.
1843 computeCost(ElementCount VF, VPCostContext &Ctx) const override;
1844
1845 Instruction::CastOps getOpcode() const { return Opcode; }
1846
1847 /// Returns the result type of the cast.
1848 Type *getResultType() const { return ResultTy; }
1849
1850protected:
1851#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1852 /// Print the recipe.
1853 LLVM_ABI_FOR_TEST void printRecipe(raw_ostream &O, const Twine &Indent,
1854 VPSlotTracker &SlotTracker) const override;
1855#endif
1856};
1857
1858/// A recipe for widening vector intrinsics.
1860 /// ID of the vector intrinsic to widen.
1861 Intrinsic::ID VectorIntrinsicID;
1862
1863 /// Scalar return type of the intrinsic.
1864 Type *ResultTy;
1865
1866 /// True if the intrinsic may read from memory.
1867 bool MayReadFromMemory;
1868
1869 /// True if the intrinsic may read write to memory.
1870 bool MayWriteToMemory;
1871
1872 /// True if the intrinsic may have side-effects.
1873 bool MayHaveSideEffects;
1874
1875public:
1877 ArrayRef<VPValue *> CallArguments, Type *Ty,
1878 const VPIRFlags &Flags = {},
1879 const VPIRMetadata &MD = {},
1881 : VPRecipeWithIRFlags(VPRecipeBase::VPWidenIntrinsicSC, CallArguments,
1882 Flags, DL),
1883 VPIRMetadata(MD), VectorIntrinsicID(VectorIntrinsicID), ResultTy(Ty),
1884 MayReadFromMemory(CI.mayReadFromMemory()),
1885 MayWriteToMemory(CI.mayWriteToMemory()),
1886 MayHaveSideEffects(CI.mayHaveSideEffects()) {
1887 setUnderlyingValue(&CI);
1888 }
1889
1891 ArrayRef<VPValue *> CallArguments, Type *Ty,
1892 const VPIRFlags &Flags = {},
1893 const VPIRMetadata &Metadata = {},
1895 : VPRecipeWithIRFlags(VPRecipeBase::VPWidenIntrinsicSC, CallArguments,
1896 Flags, DL),
1897 VPIRMetadata(Metadata), VectorIntrinsicID(VectorIntrinsicID),
1898 ResultTy(Ty) {
1899 LLVMContext &Ctx = Ty->getContext();
1900 AttributeSet Attrs = Intrinsic::getFnAttributes(Ctx, VectorIntrinsicID);
1901 MemoryEffects ME = Attrs.getMemoryEffects();
1902 MayReadFromMemory = !ME.onlyWritesMemory();
1903 MayWriteToMemory = !ME.onlyReadsMemory();
1904 MayHaveSideEffects = MayWriteToMemory ||
1905 !Attrs.hasAttribute(Attribute::NoUnwind) ||
1906 !Attrs.hasAttribute(Attribute::WillReturn);
1907 }
1908
1909 ~VPWidenIntrinsicRecipe() override = default;
1910
1912 if (Value *CI = getUnderlyingValue())
1913 return new VPWidenIntrinsicRecipe(*cast<CallInst>(CI), VectorIntrinsicID,
1914 operands(), ResultTy, *this, *this,
1915 getDebugLoc());
1916 return new VPWidenIntrinsicRecipe(VectorIntrinsicID, operands(), ResultTy,
1917 *this, *this, getDebugLoc());
1918 }
1919
1920 VP_CLASSOF_IMPL(VPRecipeBase::VPWidenIntrinsicSC)
1921
1922 /// Produce a widened version of the vector intrinsic.
1923 LLVM_ABI_FOR_TEST void execute(VPTransformState &State) override;
1924
1925 /// Return the cost of this vector intrinsic.
1927 computeCost(ElementCount VF, VPCostContext &Ctx) const override;
1928
1929 /// Return the ID of the intrinsic.
1930 Intrinsic::ID getVectorIntrinsicID() const { return VectorIntrinsicID; }
1931
1932 /// Return the scalar return type of the intrinsic.
1933 Type *getResultType() const { return ResultTy; }
1934
1935 /// Return to name of the intrinsic as string.
1937
1938 /// Returns true if the intrinsic may read from memory.
1939 bool mayReadFromMemory() const { return MayReadFromMemory; }
1940
1941 /// Returns true if the intrinsic may write to memory.
1942 bool mayWriteToMemory() const { return MayWriteToMemory; }
1943
1944 /// Returns true if the intrinsic may have side-effects.
1945 bool mayHaveSideEffects() const { return MayHaveSideEffects; }
1946
1947 LLVM_ABI_FOR_TEST bool usesFirstLaneOnly(const VPValue *Op) const override;
1948
1949protected:
1950#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1951 /// Print the recipe.
1952 LLVM_ABI_FOR_TEST void printRecipe(raw_ostream &O, const Twine &Indent,
1953 VPSlotTracker &SlotTracker) const override;
1954#endif
1955};
1956
1957/// A recipe for widening Call instructions using library calls.
1959 public VPIRMetadata {
1960 /// Variant stores a pointer to the chosen function. There is a 1:1 mapping
1961 /// between a given VF and the chosen vectorized variant, so there will be a
1962 /// different VPlan for each VF with a valid variant.
1963 Function *Variant;
1964
1965public:
1967 ArrayRef<VPValue *> CallArguments,
1968 const VPIRFlags &Flags = {},
1969 const VPIRMetadata &Metadata = {}, DebugLoc DL = {})
1970 : VPRecipeWithIRFlags(VPRecipeBase::VPWidenCallSC, CallArguments, Flags,
1971 DL),
1972 VPIRMetadata(Metadata), Variant(Variant) {
1973 setUnderlyingValue(UV);
1974 assert(
1975 isa<Function>(getOperand(getNumOperands() - 1)->getLiveInIRValue()) &&
1976 "last operand must be the called function");
1977 }
1978
1979 ~VPWidenCallRecipe() override = default;
1980
1982 return new VPWidenCallRecipe(getUnderlyingValue(), Variant, operands(),
1983 *this, *this, getDebugLoc());
1984 }
1985
1986 VP_CLASSOF_IMPL(VPRecipeBase::VPWidenCallSC)
1987
1988 /// Produce a widened version of the call instruction.
1989 void execute(VPTransformState &State) override;
1990
1991 /// Return the cost of this VPWidenCallRecipe.
1992 InstructionCost computeCost(ElementCount VF,
1993 VPCostContext &Ctx) const override;
1994
1998
2001
2002protected:
2003#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2004 /// Print the recipe.
2005 void printRecipe(raw_ostream &O, const Twine &Indent,
2006 VPSlotTracker &SlotTracker) const override;
2007#endif
2008};
2009
2010/// A recipe representing a sequence of load -> update -> store as part of
2011/// a histogram operation. This means there may be aliasing between vector
2012/// lanes, which is handled by the llvm.experimental.vector.histogram family
2013/// of intrinsics. The only update operations currently supported are
2014/// 'add' and 'sub' where the other term is loop-invariant.
2016 /// Opcode of the update operation, currently either add or sub.
2017 unsigned Opcode;
2018
2019public:
2020 VPHistogramRecipe(unsigned Opcode, ArrayRef<VPValue *> Operands,
2022 : VPRecipeBase(VPRecipeBase::VPHistogramSC, Operands, DL),
2023 Opcode(Opcode) {}
2024
2025 ~VPHistogramRecipe() override = default;
2026
2028 return new VPHistogramRecipe(Opcode, operands(), getDebugLoc());
2029 }
2030
2031 VP_CLASSOF_IMPL(VPRecipeBase::VPHistogramSC);
2032
2033 /// Produce a vectorized histogram operation.
2034 void execute(VPTransformState &State) override;
2035
2036 /// Return the cost of this VPHistogramRecipe.
2038 VPCostContext &Ctx) const override;
2039
2040 unsigned getOpcode() const { return Opcode; }
2041
2042 /// Return the mask operand if one was provided, or a null pointer if all
2043 /// lanes should be executed unconditionally.
2044 VPValue *getMask() const {
2045 return getNumOperands() == 3 ? getOperand(2) : nullptr;
2046 }
2047
2048protected:
2049#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2050 /// Print the recipe
2051 void printRecipe(raw_ostream &O, const Twine &Indent,
2052 VPSlotTracker &SlotTracker) const override;
2053#endif
2054};
2055
2056/// A recipe for handling GEP instructions.
2058 Type *SourceElementTy;
2059
2060 bool isPointerLoopInvariant() const {
2061 return getOperand(0)->isDefinedOutsideLoopRegions();
2062 }
2063
2064 bool isIndexLoopInvariant(unsigned I) const {
2065 return getOperand(I + 1)->isDefinedOutsideLoopRegions();
2066 }
2067
2068public:
2070 const VPIRFlags &Flags = {},
2072 : VPRecipeWithIRFlags(VPRecipeBase::VPWidenGEPSC, Operands, Flags, DL),
2073 SourceElementTy(GEP->getSourceElementType()) {
2074 setUnderlyingValue(GEP);
2076 (void)Metadata;
2078 assert(Metadata.empty() && "unexpected metadata on GEP");
2079 }
2080
2081 ~VPWidenGEPRecipe() override = default;
2082
2085 operands(), *this, getDebugLoc());
2086 }
2087
2088 VP_CLASSOF_IMPL(VPRecipeBase::VPWidenGEPSC)
2089
2090 /// This recipe generates a GEP instruction.
2091 unsigned getOpcode() const { return Instruction::GetElementPtr; }
2092
2093 /// Generate the gep nodes.
2094 void execute(VPTransformState &State) override;
2095
2096 Type *getSourceElementType() const { return SourceElementTy; }
2097
2098 /// Return the cost of this VPWidenGEPRecipe.
2100 VPCostContext &Ctx) const override {
2101 // TODO: Compute accurate cost after retiring the legacy cost model.
2102 return 0;
2103 }
2104
2105 /// Returns true if the recipe only uses the first lane of operand \p Op.
2106 bool usesFirstLaneOnly(const VPValue *Op) const override;
2107
2108protected:
2109#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2110 /// Print the recipe.
2111 void printRecipe(raw_ostream &O, const Twine &Indent,
2112 VPSlotTracker &SlotTracker) const override;
2113#endif
2114};
2115
2116/// A recipe to compute a pointer to the last element of each part of a widened
2117/// memory access for widened memory accesses of SourceElementTy. Used for
2118/// VPWidenMemoryRecipes or VPInterleaveRecipes that are reversed. An extra
2119/// Offset operand is added by convertToConcreteRecipes when UF = 1, and by the
2120/// unroller otherwise.
2122 Type *SourceElementTy;
2123
2124 /// The constant stride of the pointer computed by this recipe, expressed in
2125 /// units of SourceElementTy.
2126 int64_t Stride;
2127
2128public:
2129 VPVectorEndPointerRecipe(VPValue *Ptr, VPValue *VF, Type *SourceElementTy,
2130 int64_t Stride, GEPNoWrapFlags GEPFlags, DebugLoc DL)
2131 : VPRecipeWithIRFlags(VPRecipeBase::VPVectorEndPointerSC, {Ptr, VF},
2132 GEPFlags, DL),
2133 SourceElementTy(SourceElementTy), Stride(Stride) {
2134 assert(Stride < 0 && "Stride must be negative");
2135 }
2136
2137 VP_CLASSOF_IMPL(VPRecipeBase::VPVectorEndPointerSC)
2138
2139 Type *getSourceElementType() const { return SourceElementTy; }
2140 int64_t getStride() const { return Stride; }
2141 VPValue *getPointer() const { return getOperand(0); }
2142 VPValue *getVFValue() const { return getOperand(1); }
2144 return getNumOperands() == 3 ? getOperand(2) : nullptr;
2145 }
2146
2147 /// Adds the offset operand to the recipe.
2148 /// Offset = Stride * (VF - 1) + Part * Stride * VF.
2149 void materializeOffset(unsigned Part = 0);
2150
2151 void execute(VPTransformState &State) override;
2152
2153 bool usesFirstLaneOnly(const VPValue *Op) const override {
2155 "Op must be an operand of the recipe");
2156 return true;
2157 }
2158
2159 /// Return the cost of this VPVectorPointerRecipe.
2161 VPCostContext &Ctx) const override {
2162 // TODO: Compute accurate cost after retiring the legacy cost model.
2163 return 0;
2164 }
2165
2166 /// Returns true if the recipe only uses the first part of operand \p Op.
2167 bool usesFirstPartOnly(const VPValue *Op) const override {
2169 "Op must be an operand of the recipe");
2170 assert(getNumOperands() <= 2 && "must have at most two operands");
2171 return true;
2172 }
2173
2175 auto *VEPR = new VPVectorEndPointerRecipe(
2178 if (auto *Offset = getOffset())
2179 VEPR->addOperand(Offset);
2180 return VEPR;
2181 }
2182
2183protected:
2184#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2185 /// Print the recipe.
2186 void printRecipe(raw_ostream &O, const Twine &Indent,
2187 VPSlotTracker &SlotTracker) const override;
2188#endif
2189};
2190
2191/// A recipe to compute the pointers for widened memory accesses of \p
2192/// SourceElementTy. Unrolling adds an extra offset operand for unrolled parts >
2193/// 0 and it produces `GEP Ptr, Offset`. The offset for unrolled part 0 is 0.
2195 Type *SourceElementTy;
2196
2197public:
2198 VPVectorPointerRecipe(VPValue *Ptr, Type *SourceElementTy,
2199 GEPNoWrapFlags GEPFlags, DebugLoc DL)
2200 : VPRecipeWithIRFlags(VPRecipeBase::VPVectorPointerSC, Ptr, GEPFlags, DL),
2201 SourceElementTy(SourceElementTy) {}
2202
2203 VP_CLASSOF_IMPL(VPRecipeBase::VPVectorPointerSC)
2204
2206 return getNumOperands() == 2 ? getOperand(1) : nullptr;
2207 }
2208
2209 void execute(VPTransformState &State) override;
2210
2211 Type *getSourceElementType() const { return SourceElementTy; }
2212
2213 bool usesFirstLaneOnly(const VPValue *Op) const override {
2215 "Op must be an operand of the recipe");
2216 return true;
2217 }
2218
2219 /// Returns true if the recipe only uses the first part of operand \p Op.
2220 bool usesFirstPartOnly(const VPValue *Op) const override {
2222 "Op must be an operand of the recipe");
2223 assert(getNumOperands() <= 2 && "must have at most two operands");
2224 return true;
2225 }
2226
2228 auto *Clone = new VPVectorPointerRecipe(getOperand(0), SourceElementTy,
2230 if (auto *Off = getOffset())
2231 Clone->addOperand(Off);
2232 return Clone;
2233 }
2234
2235 /// Return the cost of this VPHeaderPHIRecipe.
2237 VPCostContext &Ctx) const override {
2238 // TODO: Compute accurate cost after retiring the legacy cost model.
2239 return 0;
2240 }
2241
2242protected:
2243#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2244 /// Print the recipe.
2245 void printRecipe(raw_ostream &O, const Twine &Indent,
2246 VPSlotTracker &SlotTracker) const override;
2247#endif
2248};
2249
2250/// A pure virtual base class for all recipes modeling header phis, including
2251/// phis for first order recurrences, pointer inductions and reductions. The
2252/// start value is the first operand of the recipe and the incoming value from
2253/// the backedge is the second operand.
2254///
2255/// Inductions are modeled using the following sub-classes:
2256/// * VPCanonicalIVPHIRecipe: Canonical scalar induction of the vector loop,
2257/// starting at a specified value (zero for the main vector loop, the resume
2258/// value for the epilogue vector loop) and stepping by 1. The induction
2259/// controls exiting of the vector loop by comparing against the vector trip
2260/// count. Produces a single scalar PHI for the induction value per
2261/// iteration.
2262/// * VPWidenIntOrFpInductionRecipe: Generates vector values for integer and
2263/// floating point inductions with arbitrary start and step values. Produces
2264/// a vector PHI per-part.
2265/// * VPWidenPointerInductionRecipe: Generate vector and scalar values for a
2266/// pointer induction. Produces either a vector PHI per-part or scalar values
2267/// per-lane based on the canonical induction.
2268/// * VPFirstOrderRecurrencePHIRecipe
2269/// * VPReductionPHIRecipe
2270/// * VPActiveLaneMaskPHIRecipe
2271/// * VPEVLBasedIVPHIRecipe
2273 public VPPhiAccessors {
2274protected:
2275 VPHeaderPHIRecipe(unsigned char VPRecipeID, Instruction *UnderlyingInstr,
2276 VPValue *Start, DebugLoc DL = DebugLoc::getUnknown())
2277 : VPSingleDefRecipe(VPRecipeID, Start, UnderlyingInstr, DL) {}
2278
2279 const VPRecipeBase *getAsRecipe() const override { return this; }
2280
2281public:
2282 ~VPHeaderPHIRecipe() override = default;
2283
2284 /// Method to support type inquiry through isa, cast, and dyn_cast.
2285 static inline bool classof(const VPRecipeBase *R) {
2286 return R->getVPRecipeID() >= VPRecipeBase::VPFirstHeaderPHISC &&
2287 R->getVPRecipeID() <= VPRecipeBase::VPLastHeaderPHISC;
2288 }
2289 static inline bool classof(const VPValue *V) {
2290 return isa<VPHeaderPHIRecipe>(V->getDefiningRecipe());
2291 }
2292 static inline bool classof(const VPSingleDefRecipe *R) {
2293 return isa<VPHeaderPHIRecipe>(static_cast<const VPRecipeBase *>(R));
2294 }
2295
2296 /// Generate the phi nodes.
2297 void execute(VPTransformState &State) override = 0;
2298
2299 /// Return the cost of this header phi recipe.
2301 VPCostContext &Ctx) const override;
2302
2303 /// Returns the start value of the phi, if one is set.
2305 return getNumOperands() == 0 ? nullptr : getOperand(0);
2306 }
2308 return getNumOperands() == 0 ? nullptr : getOperand(0);
2309 }
2310
2311 /// Update the start value of the recipe.
2313
2314 /// Returns the incoming value from the loop backedge.
2316 return getOperand(1);
2317 }
2318
2319 /// Update the incoming value from the loop backedge.
2321
2322 /// Returns the backedge value as a recipe. The backedge value is guaranteed
2323 /// to be a recipe.
2325 return *getBackedgeValue()->getDefiningRecipe();
2326 }
2327
2328protected:
2329#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2330 /// Print the recipe.
2331 void printRecipe(raw_ostream &O, const Twine &Indent,
2332 VPSlotTracker &SlotTracker) const override = 0;
2333#endif
2334};
2335
2336/// Base class for widened induction (VPWidenIntOrFpInductionRecipe and
2337/// VPWidenPointerInductionRecipe), providing shared functionality, including
2338/// retrieving the step value, induction descriptor and original phi node.
2340 const InductionDescriptor &IndDesc;
2341
2342public:
2343 VPWidenInductionRecipe(unsigned char Kind, PHINode *IV, VPValue *Start,
2344 VPValue *Step, const InductionDescriptor &IndDesc,
2345 DebugLoc DL)
2346 : VPHeaderPHIRecipe(Kind, IV, Start, DL), IndDesc(IndDesc) {
2347 addOperand(Step);
2348 }
2349
2350 static inline bool classof(const VPRecipeBase *R) {
2351 return R->getVPRecipeID() == VPRecipeBase::VPWidenIntOrFpInductionSC ||
2352 R->getVPRecipeID() == VPRecipeBase::VPWidenPointerInductionSC;
2353 }
2354
2355 static inline bool classof(const VPValue *V) {
2356 auto *R = V->getDefiningRecipe();
2357 return R && classof(R);
2358 }
2359
2360 static inline bool classof(const VPSingleDefRecipe *R) {
2361 return classof(static_cast<const VPRecipeBase *>(R));
2362 }
2363
2364 void execute(VPTransformState &State) override = 0;
2365
2366 /// Returns the start value of the induction.
2368
2369 /// Returns the step value of the induction.
2371 const VPValue *getStepValue() const { return getOperand(1); }
2372
2373 /// Update the step value of the recipe.
2374 void setStepValue(VPValue *V) { setOperand(1, V); }
2375
2377 const VPValue *getVFValue() const { return getOperand(2); }
2378
2379 /// Returns the number of incoming values, also number of incoming blocks.
2380 /// Note that at the moment, VPWidenPointerInductionRecipe only has a single
2381 /// incoming value, its start value.
2382 unsigned getNumIncoming() const override { return 1; }
2383
2384 /// Returns the underlying PHINode if one exists, or null otherwise.
2388
2389 /// Returns the induction descriptor for the recipe.
2390 const InductionDescriptor &getInductionDescriptor() const { return IndDesc; }
2391
2393 // TODO: All operands of base recipe must exist and be at same index in
2394 // derived recipe.
2396 "VPWidenIntOrFpInductionRecipe generates its own backedge value");
2397 }
2398
2400 // TODO: All operands of base recipe must exist and be at same index in
2401 // derived recipe.
2403 "VPWidenIntOrFpInductionRecipe generates its own backedge value");
2404 }
2405
2406 /// Returns true if the recipe only uses the first lane of operand \p Op.
2407 bool usesFirstLaneOnly(const VPValue *Op) const override {
2409 "Op must be an operand of the recipe");
2410 // The recipe creates its own wide start value, so it only requests the
2411 // first lane of the operand.
2412 // TODO: Remove once creating the start value is modeled separately.
2413 return Op == getStartValue() || Op == getStepValue();
2414 }
2415};
2416
2417/// A recipe for handling phi nodes of integer and floating-point inductions,
2418/// producing their vector values. This is an abstract recipe and must be
2419/// converted to concrete recipes before executing.
2421 public VPIRFlags {
2422 TruncInst *Trunc;
2423
2424 // If this recipe is unrolled it will have 2 additional operands.
2425 bool isUnrolled() const { return getNumOperands() == 5; }
2426
2427public:
2429 VPValue *VF, const InductionDescriptor &IndDesc,
2430 const VPIRFlags &Flags, DebugLoc DL)
2431 : VPWidenInductionRecipe(VPRecipeBase::VPWidenIntOrFpInductionSC, IV,
2432 Start, Step, IndDesc, DL),
2433 VPIRFlags(Flags), Trunc(nullptr) {
2434 addOperand(VF);
2435 }
2436
2438 VPValue *VF, const InductionDescriptor &IndDesc,
2439 TruncInst *Trunc, const VPIRFlags &Flags,
2440 DebugLoc DL)
2441 : VPWidenInductionRecipe(VPRecipeBase::VPWidenIntOrFpInductionSC, IV,
2442 Start, Step, IndDesc, DL),
2443 VPIRFlags(Flags), Trunc(Trunc) {
2444 addOperand(VF);
2446 (void)Metadata;
2447 if (Trunc)
2449 assert(Metadata.empty() && "unexpected metadata on Trunc");
2450 }
2451
2453
2459
2460 VP_CLASSOF_IMPL(VPRecipeBase::VPWidenIntOrFpInductionSC)
2461
2462 void execute(VPTransformState &State) override {
2463 llvm_unreachable("cannot execute this recipe, should be expanded via "
2464 "expandVPWidenIntOrFpInductionRecipe");
2465 }
2466
2467 /// Returns the start value of the induction.
2469
2470 /// If the recipe has been unrolled, return the VPValue for the induction
2471 /// increment, otherwise return null.
2473 return isUnrolled() ? getOperand(getNumOperands() - 2) : nullptr;
2474 }
2475
2476 /// Returns the number of incoming values, also number of incoming blocks.
2477 /// Note that at the moment, VPWidenIntOrFpInductionRecipes only have a single
2478 /// incoming value, its start value.
2479 unsigned getNumIncoming() const override { return 1; }
2480
2481 /// Returns the first defined value as TruncInst, if it is one or nullptr
2482 /// otherwise.
2483 TruncInst *getTruncInst() { return Trunc; }
2484 const TruncInst *getTruncInst() const { return Trunc; }
2485
2486 /// Returns true if the induction is canonical, i.e. starting at 0 and
2487 /// incremented by UF * VF (= the original IV is incremented by 1) and has the
2488 /// same type as the canonical induction.
2489 bool isCanonical() const;
2490
2491 /// Returns the scalar type of the induction.
2493 return Trunc ? Trunc->getType() : getStartValue()->getType();
2494 }
2495
2496 /// Returns the VPValue representing the value of this induction at
2497 /// the last unrolled part, if it exists. Returns itself if unrolling did not
2498 /// take place.
2500 return isUnrolled() ? getOperand(getNumOperands() - 1) : this;
2501 }
2502
2503protected:
2504#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2505 /// Print the recipe.
2506 void printRecipe(raw_ostream &O, const Twine &Indent,
2507 VPSlotTracker &SlotTracker) const override;
2508#endif
2509};
2510
2512public:
2513 /// Create a new VPWidenPointerInductionRecipe for \p Phi with start value \p
2514 /// Start and the number of elements unrolled \p NumUnrolledElems, typically
2515 /// VF*UF.
2517 VPValue *NumUnrolledElems,
2518 const InductionDescriptor &IndDesc, DebugLoc DL)
2519 : VPWidenInductionRecipe(VPRecipeBase::VPWidenPointerInductionSC, Phi,
2520 Start, Step, IndDesc, DL) {
2521 addOperand(NumUnrolledElems);
2522 }
2523
2525
2531
2532 VP_CLASSOF_IMPL(VPRecipeBase::VPWidenPointerInductionSC)
2533
2534 /// Generate vector values for the pointer induction.
2535 void execute(VPTransformState &State) override {
2536 llvm_unreachable("cannot execute this recipe, should be expanded via "
2537 "expandVPWidenPointerInduction");
2538 };
2539
2540 /// Returns true if only scalar values will be generated.
2541 bool onlyScalarsGenerated(bool IsScalable);
2542
2543protected:
2544#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2545 /// Print the recipe.
2546 void printRecipe(raw_ostream &O, const Twine &Indent,
2547 VPSlotTracker &SlotTracker) const override;
2548#endif
2549};
2550
2551/// A recipe for widened phis. Incoming values are operands of the recipe and
2552/// their operand index corresponds to the incoming predecessor block. If the
2553/// recipe is placed in an entry block to a (non-replicate) region, it must have
2554/// exactly 2 incoming values, the first from the predecessor of the region and
2555/// the second from the exiting block of the region.
2557 public VPPhiAccessors {
2558 /// Name to use for the generated IR instruction for the widened phi.
2559 std::string Name;
2560
2561public:
2562 /// Create a new VPWidenPHIRecipe for \p Phi with start value \p Start and
2563 /// debug location \p DL.
2564 VPWidenPHIRecipe(PHINode *Phi, VPValue *Start = nullptr,
2565 DebugLoc DL = DebugLoc::getUnknown(), const Twine &Name = "")
2566 : VPSingleDefRecipe(VPRecipeBase::VPWidenPHISC, {}, Phi, DL),
2567 Name(Name.str()) {
2568 if (Start)
2569 addOperand(Start);
2570 }
2571
2573 auto *C =
2575 getOperand(0), getDebugLoc(), Name);
2577 C->addOperand(Op);
2578 return C;
2579 }
2580
2581 ~VPWidenPHIRecipe() override = default;
2582
2583 VP_CLASSOF_IMPL(VPRecipeBase::VPWidenPHISC)
2584
2585 /// Generate the phi/select nodes.
2586 void execute(VPTransformState &State) override;
2587
2588 /// Return the cost of this VPWidenPHIRecipe.
2590 VPCostContext &Ctx) const override;
2591
2592protected:
2593#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2594 /// Print the recipe.
2595 void printRecipe(raw_ostream &O, const Twine &Indent,
2596 VPSlotTracker &SlotTracker) const override;
2597#endif
2598
2599 const VPRecipeBase *getAsRecipe() const override { return this; }
2600};
2601
2602/// A recipe for handling first-order recurrence phis. The start value is the
2603/// first operand of the recipe and the incoming value from the backedge is the
2604/// second operand.
2607 VPValue &BackedgeValue)
2608 : VPHeaderPHIRecipe(VPRecipeBase::VPFirstOrderRecurrencePHISC, Phi,
2609 &Start) {
2610 addOperand(&BackedgeValue);
2611 }
2612
2613 VP_CLASSOF_IMPL(VPRecipeBase::VPFirstOrderRecurrencePHISC)
2614
2619
2620 void execute(VPTransformState &State) override;
2621
2622 /// Return the cost of this first-order recurrence phi recipe.
2624 VPCostContext &Ctx) const override;
2625
2626 /// Returns true if the recipe only uses the first lane of operand \p Op.
2627 bool usesFirstLaneOnly(const VPValue *Op) const override {
2629 "Op must be an operand of the recipe");
2630 return Op == getStartValue();
2631 }
2632
2633protected:
2634#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2635 /// Print the recipe.
2636 void printRecipe(raw_ostream &O, const Twine &Indent,
2637 VPSlotTracker &SlotTracker) const override;
2638#endif
2639};
2640
2641/// Possible variants of a reduction.
2642
2643/// This reduction is ordered and in-loop.
2644struct RdxOrdered {};
2645/// This reduction is in-loop.
2646struct RdxInLoop {};
2647/// This reduction is unordered with the partial result scaled down by some
2648/// factor.
2651};
2652using ReductionStyle = std::variant<RdxOrdered, RdxInLoop, RdxUnordered>;
2653
2654inline ReductionStyle getReductionStyle(bool InLoop, bool Ordered,
2655 unsigned ScaleFactor) {
2656 assert((!Ordered || InLoop) && "Ordered implies in-loop");
2657 if (Ordered)
2658 return RdxOrdered{};
2659 if (InLoop)
2660 return RdxInLoop{};
2661 return RdxUnordered{/*VFScaleFactor=*/ScaleFactor};
2662}
2663
2664/// A recipe for handling reduction phis. The start value is the first operand
2665/// of the recipe and the incoming value from the backedge is the second
2666/// operand.
2668 /// The recurrence kind of the reduction.
2669 const RecurKind Kind;
2670
2671 ReductionStyle Style;
2672
2673 /// The phi is part of a multi-use reduction (e.g., used in FindIV
2674 /// patterns for argmin/argmax).
2675 /// TODO: Also support cases where the phi itself has a single use, but its
2676 /// compare has multiple uses.
2677 bool HasUsesOutsideReductionChain;
2678
2679public:
2680 /// Create a new VPReductionPHIRecipe for the reduction \p Phi.
2682 VPValue &BackedgeValue, ReductionStyle Style,
2683 const VPIRFlags &Flags,
2684 bool HasUsesOutsideReductionChain = false)
2685 : VPHeaderPHIRecipe(VPRecipeBase::VPReductionPHISC, Phi, &Start),
2686 VPIRFlags(Flags), Kind(Kind), Style(Style),
2687 HasUsesOutsideReductionChain(HasUsesOutsideReductionChain) {
2688 addOperand(&BackedgeValue);
2689 }
2690
2691 ~VPReductionPHIRecipe() override = default;
2692
2694 return new VPReductionPHIRecipe(
2696 *getOperand(0), *getBackedgeValue(), Style, *this,
2697 HasUsesOutsideReductionChain);
2698 }
2699
2700 VP_CLASSOF_IMPL(VPRecipeBase::VPReductionPHISC)
2701
2702 /// Generate the phi/select nodes.
2703 void execute(VPTransformState &State) override;
2704
2705 /// Get the factor that the VF of this recipe's output should be scaled by, or
2706 /// 1 if it isn't scaled.
2707 unsigned getVFScaleFactor() const {
2708 auto *Partial = std::get_if<RdxUnordered>(&Style);
2709 return Partial ? Partial->VFScaleFactor : 1;
2710 }
2711
2712 /// Set the VFScaleFactor for this reduction phi. Can only be set to a factor
2713 /// > 1.
2714 void setVFScaleFactor(unsigned ScaleFactor) {
2715 assert(ScaleFactor > 1 && "must set to scale factor > 1");
2716 Style = RdxUnordered{ScaleFactor};
2717 }
2718
2719 /// Returns the number of incoming values, also number of incoming blocks.
2720 /// Note that at the moment, VPWidenPointerInductionRecipe only has a single
2721 /// incoming value, its start value.
2722 unsigned getNumIncoming() const override { return 2; }
2723
2724 /// Returns the recurrence kind of the reduction.
2725 RecurKind getRecurrenceKind() const { return Kind; }
2726
2727 /// Returns true, if the phi is part of an ordered reduction.
2728 bool isOrdered() const { return std::holds_alternative<RdxOrdered>(Style); }
2729
2730 /// Returns true if the phi is part of an in-loop reduction.
2731 bool isInLoop() const {
2732 return std::holds_alternative<RdxInLoop>(Style) ||
2733 std::holds_alternative<RdxOrdered>(Style);
2734 }
2735
2736 /// Returns true if the reduction outputs a vector with a scaled down VF.
2737 bool isPartialReduction() const { return getVFScaleFactor() > 1; }
2738
2739 /// Returns true, if the phi is part of a multi-use reduction.
2741 return HasUsesOutsideReductionChain;
2742 }
2743
2744 /// Returns true if the recipe only uses the first lane of operand \p Op.
2745 bool usesFirstLaneOnly(const VPValue *Op) const override {
2747 "Op must be an operand of the recipe");
2748 return isOrdered() || isInLoop();
2749 }
2750
2751protected:
2752#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2753 /// Print the recipe.
2754 void printRecipe(raw_ostream &O, const Twine &Indent,
2755 VPSlotTracker &SlotTracker) const override;
2756#endif
2757};
2758
2759/// A recipe for vectorizing a phi-node as a sequence of mask-based select
2760/// instructions.
2762public:
2763 /// The blend operation is a User of the incoming values and of their
2764 /// respective masks, ordered [I0, M0, I1, M1, I2, M2, ...]. Note that M0 can
2765 /// be omitted (implied by passing an odd number of operands) in which case
2766 /// all other incoming values are merged into it.
2768 const VPIRFlags &Flags, DebugLoc DL)
2769 : VPRecipeWithIRFlags(VPRecipeBase::VPBlendSC, Operands, Flags, DL) {
2770 assert(Operands.size() >= 2 && "Expected at least two operands!");
2771 setUnderlyingValue(Phi);
2772 }
2773
2774 VPBlendRecipe *clone() override {
2776 operands(), *this, getDebugLoc());
2777 }
2778
2779 VP_CLASSOF_IMPL(VPRecipeBase::VPBlendSC)
2780
2781 /// A normalized blend is one that has an odd number of operands, whereby the
2782 /// first operand does not have an associated mask.
2783 bool isNormalized() const { return getNumOperands() % 2; }
2784
2785 /// Return the number of incoming values, taking into account when normalized
2786 /// the first incoming value will have no mask.
2787 unsigned getNumIncomingValues() const {
2788 return (getNumOperands() + isNormalized()) / 2;
2789 }
2790
2791 /// Return incoming value number \p Idx.
2792 VPValue *getIncomingValue(unsigned Idx) const {
2793 return Idx == 0 ? getOperand(0) : getOperand(Idx * 2 - isNormalized());
2794 }
2795
2796 /// Return mask number \p Idx.
2797 VPValue *getMask(unsigned Idx) const {
2798 assert((Idx > 0 || !isNormalized()) && "First index has no mask!");
2799 return Idx == 0 ? getOperand(1) : getOperand(Idx * 2 + !isNormalized());
2800 }
2801
2802 /// Set mask number \p Idx to \p V.
2803 void setMask(unsigned Idx, VPValue *V) {
2804 assert((Idx > 0 || !isNormalized()) && "First index has no mask!");
2805 Idx == 0 ? setOperand(1, V) : setOperand(Idx * 2 + !isNormalized(), V);
2806 }
2807
2808 void execute(VPTransformState &State) override {
2809 llvm_unreachable("VPBlendRecipe should be expanded by simplifyBlends");
2810 }
2811
2812 /// Return the cost of this VPWidenMemoryRecipe.
2813 InstructionCost computeCost(ElementCount VF,
2814 VPCostContext &Ctx) const override;
2815
2816 /// Returns true if the recipe only uses the first lane of operand \p Op.
2817 bool usesFirstLaneOnly(const VPValue *Op) const override {
2819 "Op must be an operand of the recipe");
2820 // Recursing through Blend recipes only, must terminate at header phi's the
2821 // latest.
2822 return all_of(users(),
2823 [this](VPUser *U) { return U->usesFirstLaneOnly(this); });
2824 }
2825
2826protected:
2827#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2828 /// Print the recipe.
2829 void printRecipe(raw_ostream &O, const Twine &Indent,
2830 VPSlotTracker &SlotTracker) const override;
2831#endif
2832};
2833
2834/// A common base class for interleaved memory operations.
2835/// An Interleaved memory operation is a memory access method that combines
2836/// multiple strided loads/stores into a single wide load/store with shuffles.
2837/// The first operand is the start address. The optional operands are, in order,
2838/// the stored values and the mask.
2840 public VPIRMetadata {
2842
2843 /// Indicates if the interleave group is in a conditional block and requires a
2844 /// mask.
2845 bool HasMask = false;
2846
2847 /// Indicates if gaps between members of the group need to be masked out or if
2848 /// unusued gaps can be loaded speculatively.
2849 bool NeedsMaskForGaps = false;
2850
2851protected:
2852 VPInterleaveBase(const unsigned char SC,
2854 ArrayRef<VPValue *> Operands,
2855 ArrayRef<VPValue *> StoredValues, VPValue *Mask,
2856 bool NeedsMaskForGaps, const VPIRMetadata &MD, DebugLoc DL)
2857 : VPRecipeBase(SC, Operands, DL), VPIRMetadata(MD), IG(IG),
2858 NeedsMaskForGaps(NeedsMaskForGaps) {
2859 // TODO: extend the masked interleaved-group support to reversed access.
2860 assert((!Mask || !IG->isReverse()) &&
2861 "Reversed masked interleave-group not supported.");
2862 if (StoredValues.empty()) {
2863 for (unsigned I = 0; I < IG->getFactor(); ++I)
2864 if (Instruction *Inst = IG->getMember(I)) {
2865 assert(!Inst->getType()->isVoidTy() && "must have result");
2866 new VPRecipeValue(this, Inst);
2867 }
2868 } else {
2869 for (auto *SV : StoredValues)
2870 addOperand(SV);
2871 }
2872 if (Mask) {
2873 HasMask = true;
2874 addOperand(Mask);
2875 }
2876 }
2877
2878public:
2879 VPInterleaveBase *clone() override = 0;
2880
2881 static inline bool classof(const VPRecipeBase *R) {
2882 return R->getVPRecipeID() == VPRecipeBase::VPInterleaveSC ||
2883 R->getVPRecipeID() == VPRecipeBase::VPInterleaveEVLSC;
2884 }
2885
2886 static inline bool classof(const VPUser *U) {
2887 auto *R = dyn_cast<VPRecipeBase>(U);
2888 return R && classof(R);
2889 }
2890
2891 /// Return the address accessed by this recipe.
2892 VPValue *getAddr() const {
2893 return getOperand(0); // Address is the 1st, mandatory operand.
2894 }
2895
2896 /// Return the mask used by this recipe. Note that a full mask is represented
2897 /// by a nullptr.
2898 VPValue *getMask() const {
2899 // Mask is optional and the last operand.
2900 return HasMask ? getOperand(getNumOperands() - 1) : nullptr;
2901 }
2902
2903 /// Return true if the access needs a mask because of the gaps.
2904 bool needsMaskForGaps() const { return NeedsMaskForGaps; }
2905
2907
2908 Instruction *getInsertPos() const { return IG->getInsertPos(); }
2909
2910 void execute(VPTransformState &State) override {
2911 llvm_unreachable("VPInterleaveBase should not be instantiated.");
2912 }
2913
2914 /// Return the cost of this recipe.
2915 InstructionCost computeCost(ElementCount VF,
2916 VPCostContext &Ctx) const override;
2917
2918 /// Returns true if the recipe only uses the first lane of operand \p Op.
2919 bool usesFirstLaneOnly(const VPValue *Op) const override = 0;
2920
2921 /// Returns the number of stored operands of this interleave group. Returns 0
2922 /// for load interleave groups.
2923 virtual unsigned getNumStoreOperands() const = 0;
2924
2925 /// Return the VPValues stored by this interleave group. If it is a load
2926 /// interleave group, return an empty ArrayRef.
2928 return {op_end() - (getNumStoreOperands() + (HasMask ? 1 : 0)),
2930 }
2931};
2932
2933/// VPInterleaveRecipe is a recipe for transforming an interleave group of load
2934/// or stores into one wide load/store and shuffles. The first operand of a
2935/// VPInterleave recipe is the address, followed by the stored values, followed
2936/// by an optional mask.
2938public:
2940 ArrayRef<VPValue *> StoredValues, VPValue *Mask,
2941 bool NeedsMaskForGaps, const VPIRMetadata &MD, DebugLoc DL)
2942 : VPInterleaveBase(VPRecipeBase::VPInterleaveSC, IG, Addr, StoredValues,
2943 Mask, NeedsMaskForGaps, MD, DL) {}
2944
2945 ~VPInterleaveRecipe() override = default;
2946
2950 needsMaskForGaps(), *this, getDebugLoc());
2951 }
2952
2953 VP_CLASSOF_IMPL(VPRecipeBase::VPInterleaveSC)
2954
2955 /// Generate the wide load or store, and shuffles.
2956 void execute(VPTransformState &State) override;
2957
2958 bool usesFirstLaneOnly(const VPValue *Op) const override {
2960 "Op must be an operand of the recipe");
2961 return Op == getAddr() && !llvm::is_contained(getStoredValues(), Op);
2962 }
2963
2964 unsigned getNumStoreOperands() const override {
2965 return getNumOperands() - (getMask() ? 2 : 1);
2966 }
2967
2968protected:
2969#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2970 /// Print the recipe.
2971 void printRecipe(raw_ostream &O, const Twine &Indent,
2972 VPSlotTracker &SlotTracker) const override;
2973#endif
2974};
2975
2976/// A recipe for interleaved memory operations with vector-predication
2977/// intrinsics. The first operand is the address, the second operand is the
2978/// explicit vector length. Stored values and mask are optional operands.
2980public:
2982 : VPInterleaveBase(VPRecipeBase::VPInterleaveEVLSC,
2983 R.getInterleaveGroup(), {R.getAddr(), &EVL},
2984 R.getStoredValues(), Mask, R.needsMaskForGaps(), R,
2985 R.getDebugLoc()) {
2986 assert(!getInterleaveGroup()->isReverse() &&
2987 "Reversed interleave-group with tail folding is not supported.");
2988 assert(!needsMaskForGaps() && "Interleaved access with gap mask is not "
2989 "supported for scalable vector.");
2990 }
2991
2992 ~VPInterleaveEVLRecipe() override = default;
2993
2995 llvm_unreachable("cloning not implemented yet");
2996 }
2997
2998 VP_CLASSOF_IMPL(VPRecipeBase::VPInterleaveEVLSC)
2999
3000 /// The VPValue of the explicit vector length.
3001 VPValue *getEVL() const { return getOperand(1); }
3002
3003 /// Generate the wide load or store, and shuffles.
3004 void execute(VPTransformState &State) override;
3005
3006 /// The recipe only uses the first lane of the address, and EVL operand.
3007 bool usesFirstLaneOnly(const VPValue *Op) const override {
3009 "Op must be an operand of the recipe");
3010 return (Op == getAddr() && !llvm::is_contained(getStoredValues(), Op)) ||
3011 Op == getEVL();
3012 }
3013
3014 unsigned getNumStoreOperands() const override {
3015 return getNumOperands() - (getMask() ? 3 : 2);
3016 }
3017
3018protected:
3019#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3020 /// Print the recipe.
3021 void printRecipe(raw_ostream &O, const Twine &Indent,
3022 VPSlotTracker &SlotTracker) const override;
3023#endif
3024};
3025
3026/// A recipe to represent inloop, ordered or partial reduction operations. It
3027/// performs a reduction on a vector operand into a scalar (vector in the case
3028/// of a partial reduction) value, and adds the result to a chain. The Operands
3029/// are {ChainOp, VecOp, [Condition]}.
3031
3032 /// The recurrence kind for the reduction in question.
3033 RecurKind RdxKind;
3034 /// Whether the reduction is conditional.
3035 bool IsConditional = false;
3036 ReductionStyle Style;
3037
3038protected:
3039 VPReductionRecipe(const unsigned char SC, RecurKind RdxKind,
3041 ArrayRef<VPValue *> Operands, VPValue *CondOp,
3042 ReductionStyle Style, DebugLoc DL)
3043 : VPRecipeWithIRFlags(SC, Operands, FMFs, DL), RdxKind(RdxKind),
3044 Style(Style) {
3045 if (CondOp) {
3046 IsConditional = true;
3047 addOperand(CondOp);
3048 }
3050 }
3051
3052public:
3054 VPValue *ChainOp, VPValue *VecOp, VPValue *CondOp,
3056 : VPReductionRecipe(VPRecipeBase::VPReductionSC, RdxKind, FMFs, I,
3057 {ChainOp, VecOp}, CondOp, Style, DL) {}
3058
3060 VPValue *ChainOp, VPValue *VecOp, VPValue *CondOp,
3062 : VPReductionRecipe(VPRecipeBase::VPReductionSC, RdxKind, FMFs, nullptr,
3063 {ChainOp, VecOp}, CondOp, Style, DL) {}
3064
3065 ~VPReductionRecipe() override = default;
3066
3068 return new VPReductionRecipe(RdxKind, getFastMathFlags(),
3070 getCondOp(), Style, getDebugLoc());
3071 }
3072
3073 static inline bool classof(const VPRecipeBase *R) {
3074 return R->getVPRecipeID() == VPRecipeBase::VPReductionSC ||
3075 R->getVPRecipeID() == VPRecipeBase::VPReductionEVLSC;
3076 }
3077
3078 static inline bool classof(const VPUser *U) {
3079 auto *R = dyn_cast<VPRecipeBase>(U);
3080 return R && classof(R);
3081 }
3082
3083 static inline bool classof(const VPValue *VPV) {
3084 const VPRecipeBase *R = VPV->getDefiningRecipe();
3085 return R && classof(R);
3086 }
3087
3088 static inline bool classof(const VPSingleDefRecipe *R) {
3089 return classof(static_cast<const VPRecipeBase *>(R));
3090 }
3091
3092 /// Generate the reduction in the loop.
3093 void execute(VPTransformState &State) override;
3094
3095 /// Return the cost of VPReductionRecipe.
3096 InstructionCost computeCost(ElementCount VF,
3097 VPCostContext &Ctx) const override;
3098
3099 /// Return the recurrence kind for the in-loop reduction.
3100 RecurKind getRecurrenceKind() const { return RdxKind; }
3101 /// Return true if the in-loop reduction is ordered.
3102 bool isOrdered() const { return std::holds_alternative<RdxOrdered>(Style); };
3103 /// Return true if the in-loop reduction is conditional.
3104 bool isConditional() const { return IsConditional; };
3105 /// Returns true if the reduction outputs a vector with a scaled down VF.
3106 bool isPartialReduction() const { return getVFScaleFactor() > 1; }
3107 /// Returns true if the reduction is in-loop.
3108 bool isInLoop() const {
3109 return std::holds_alternative<RdxInLoop>(Style) ||
3110 std::holds_alternative<RdxOrdered>(Style);
3111 }
3112 /// The VPValue of the scalar Chain being accumulated.
3113 VPValue *getChainOp() const { return getOperand(0); }
3114 /// The VPValue of the vector value to be reduced.
3115 VPValue *getVecOp() const { return getOperand(1); }
3116 /// The VPValue of the condition for the block.
3118 return isConditional() ? getOperand(getNumOperands() - 1) : nullptr;
3119 }
3120 /// Get the factor that the VF of this recipe's output should be scaled by, or
3121 /// 1 if it isn't scaled.
3122 unsigned getVFScaleFactor() const {
3123 auto *Partial = std::get_if<RdxUnordered>(&Style);
3124 return Partial ? Partial->VFScaleFactor : 1;
3125 }
3126
3127protected:
3128#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3129 /// Print the recipe.
3130 void printRecipe(raw_ostream &O, const Twine &Indent,
3131 VPSlotTracker &SlotTracker) const override;
3132#endif
3133};
3134
3135/// A recipe to represent inloop reduction operations with vector-predication
3136/// intrinsics, performing a reduction on a vector operand with the explicit
3137/// vector length (EVL) into a scalar value, and adding the result to a chain.
3138/// The Operands are {ChainOp, VecOp, EVL, [Condition]}.
3140public:
3143 : VPReductionRecipe(VPRecipeBase::VPReductionEVLSC, R.getRecurrenceKind(),
3144 R.getFastMathFlags(),
3146 {R.getChainOp(), R.getVecOp(), &EVL}, CondOp,
3147 getReductionStyle(/*InLoop=*/true, R.isOrdered(), 1),
3148 DL) {}
3149
3150 ~VPReductionEVLRecipe() override = default;
3151
3153 llvm_unreachable("cloning not implemented yet");
3154 }
3155
3156 VP_CLASSOF_IMPL(VPRecipeBase::VPReductionEVLSC)
3157
3158 /// Generate the reduction in the loop
3159 void execute(VPTransformState &State) override;
3160
3161 /// The VPValue of the explicit vector length.
3162 VPValue *getEVL() const { return getOperand(2); }
3163
3164 /// Returns true if the recipe only uses the first lane of operand \p Op.
3165 bool usesFirstLaneOnly(const VPValue *Op) const override {
3167 "Op must be an operand of the recipe");
3168 return Op == getEVL();
3169 }
3170
3171protected:
3172#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3173 /// Print the recipe.
3174 void printRecipe(raw_ostream &O, const Twine &Indent,
3175 VPSlotTracker &SlotTracker) const override;
3176#endif
3177};
3178
3179/// VPReplicateRecipe replicates a given instruction producing multiple scalar
3180/// copies of the original scalar type, one per lane, instead of producing a
3181/// single copy of widened type for all lanes. If the instruction is known to be
3182/// a single scalar, only one copy, per lane zero, will be generated.
3184 public VPIRMetadata {
3185 /// Indicator if only a single replica per lane is needed.
3186 bool IsSingleScalar;
3187
3188 /// Indicator if the replicas are also predicated.
3189 bool IsPredicated;
3190
3191public:
3193 bool IsSingleScalar, VPValue *Mask = nullptr,
3194 const VPIRFlags &Flags = {}, VPIRMetadata Metadata = {},
3195 DebugLoc DL = DebugLoc::getUnknown())
3196 : VPRecipeWithIRFlags(VPRecipeBase::VPReplicateSC, Operands, Flags, DL),
3197 VPIRMetadata(Metadata), IsSingleScalar(IsSingleScalar),
3198 IsPredicated(Mask) {
3199 setUnderlyingValue(I);
3200 if (Mask)
3201 addOperand(Mask);
3202 }
3203
3204 ~VPReplicateRecipe() override = default;
3205
3207 auto *Copy = new VPReplicateRecipe(
3208 getUnderlyingInstr(), operands(), IsSingleScalar,
3209 isPredicated() ? getMask() : nullptr, *this, *this, getDebugLoc());
3210 Copy->transferFlags(*this);
3211 return Copy;
3212 }
3213
3214 VP_CLASSOF_IMPL(VPRecipeBase::VPReplicateSC)
3215
3216 /// Generate replicas of the desired Ingredient. Replicas will be generated
3217 /// for all parts and lanes unless a specific part and lane are specified in
3218 /// the \p State.
3219 void execute(VPTransformState &State) override;
3220
3221 /// Return the cost of this VPReplicateRecipe.
3222 InstructionCost computeCost(ElementCount VF,
3223 VPCostContext &Ctx) const override;
3224
3225 bool isSingleScalar() const { return IsSingleScalar; }
3226
3227 bool isPredicated() const { return IsPredicated; }
3228
3229 /// Returns true if the recipe only uses the first lane of operand \p Op.
3230 bool usesFirstLaneOnly(const VPValue *Op) const override {
3232 "Op must be an operand of the recipe");
3233 return isSingleScalar();
3234 }
3235
3236 /// Returns true if the recipe uses scalars of operand \p Op.
3237 bool usesScalars(const VPValue *Op) const override {
3239 "Op must be an operand of the recipe");
3240 return true;
3241 }
3242
3243 /// Returns true if the recipe is used by a widened recipe via an intervening
3244 /// VPPredInstPHIRecipe. In this case, the scalar values should also be packed
3245 /// in a vector.
3246 bool shouldPack() const;
3247
3248 /// Return the mask of a predicated VPReplicateRecipe.
3250 assert(isPredicated() && "Trying to get the mask of a unpredicated recipe");
3251 return getOperand(getNumOperands() - 1);
3252 }
3253
3254 unsigned getOpcode() const { return getUnderlyingInstr()->getOpcode(); }
3255
3256protected:
3257#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3258 /// Print the recipe.
3259 void printRecipe(raw_ostream &O, const Twine &Indent,
3260 VPSlotTracker &SlotTracker) const override;
3261#endif
3262};
3263
3264/// A recipe for generating conditional branches on the bits of a mask.
3266public:
3268 : VPRecipeBase(VPRecipeBase::VPBranchOnMaskSC, {BlockInMask}, DL) {}
3269
3272 }
3273
3274 VP_CLASSOF_IMPL(VPRecipeBase::VPBranchOnMaskSC)
3275
3276 /// Generate the extraction of the appropriate bit from the block mask and the
3277 /// conditional branch.
3278 void execute(VPTransformState &State) override;
3279
3280 /// Return the cost of this VPBranchOnMaskRecipe.
3281 InstructionCost computeCost(ElementCount VF,
3282 VPCostContext &Ctx) const override;
3283
3284#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3285 /// Print the recipe.
3286 void printRecipe(raw_ostream &O, const Twine &Indent,
3287 VPSlotTracker &SlotTracker) const override {
3288 O << Indent << "BRANCH-ON-MASK ";
3290 }
3291#endif
3292
3293 /// Returns true if the recipe uses scalars of operand \p Op.
3294 bool usesScalars(const VPValue *Op) const override {
3296 "Op must be an operand of the recipe");
3297 return true;
3298 }
3299};
3300
3301/// A recipe to combine multiple recipes into a single 'expression' recipe,
3302/// which should be considered a single entity for cost-modeling and transforms.
3303/// The recipe needs to be 'decomposed', i.e. replaced by its individual
3304/// expression recipes, before execute. The individual expression recipes are
3305/// completely disconnected from the def-use graph of other recipes not part of
3306/// the expression. Def-use edges between pairs of expression recipes remain
3307/// intact, whereas every edge between an expression recipe and a recipe outside
3308/// the expression is elevated to connect the non-expression recipe with the
3309/// VPExpressionRecipe itself.
3310class VPExpressionRecipe : public VPSingleDefRecipe {
3311 /// Recipes included in this VPExpressionRecipe. This could contain
3312 /// duplicates.
3313 SmallVector<VPSingleDefRecipe *> ExpressionRecipes;
3314
3315 /// Temporary VPValues used for external operands of the expression, i.e.
3316 /// operands not defined by recipes in the expression.
3317 SmallVector<VPValue *> LiveInPlaceholders;
3318
3319 enum class ExpressionTypes {
3320 /// Represents an inloop extended reduction operation, performing a
3321 /// reduction on an extended vector operand into a scalar value, and adding
3322 /// the result to a chain.
3323 ExtendedReduction,
3324 /// Represent an inloop multiply-accumulate reduction, multiplying the
3325 /// extended vector operands, performing a reduction.add on the result, and
3326 /// adding the scalar result to a chain.
3327 ExtMulAccReduction,
3328 /// Represent an inloop multiply-accumulate reduction, multiplying the
3329 /// vector operands, performing a reduction.add on the result, and adding
3330 /// the scalar result to a chain.
3331 MulAccReduction,
3332 /// Represent an inloop multiply-accumulate reduction, multiplying the
3333 /// extended vector operands, negating the multiplication, performing a
3334 /// reduction.add on the result, and adding the scalar result to a chain.
3335 ExtNegatedMulAccReduction,
3336 };
3337
3338 /// Type of the expression.
3339 ExpressionTypes ExpressionType;
3340
3341 /// Construct a new VPExpressionRecipe by internalizing recipes in \p
3342 /// ExpressionRecipes. External operands (i.e. not defined by another recipe
3343 /// in the expression) are replaced by temporary VPValues and the original
3344 /// operands are transferred to the VPExpressionRecipe itself. Clone recipes
3345 /// as needed (excluding last) to ensure they are only used by other recipes
3346 /// in the expression.
3347 VPExpressionRecipe(ExpressionTypes ExpressionType,
3348 ArrayRef<VPSingleDefRecipe *> ExpressionRecipes);
3349
3350public:
3352 : VPExpressionRecipe(ExpressionTypes::ExtendedReduction, {Ext, Red}) {}
3354 : VPExpressionRecipe(ExpressionTypes::MulAccReduction, {Mul, Red}) {}
3357 : VPExpressionRecipe(ExpressionTypes::ExtMulAccReduction,
3358 {Ext0, Ext1, Mul, Red}) {}
3361 VPReductionRecipe *Red)
3362 : VPExpressionRecipe(ExpressionTypes::ExtNegatedMulAccReduction,
3363 {Ext0, Ext1, Mul, Sub, Red}) {
3364 assert(Mul->getOpcode() == Instruction::Mul && "Expected a mul");
3365 assert(Red->getRecurrenceKind() == RecurKind::Add &&
3366 "Expected an add reduction");
3367 assert(getNumOperands() >= 3 && "Expected at least three operands");
3368 [[maybe_unused]] auto *SubConst = dyn_cast<VPConstantInt>(getOperand(2));
3369 assert(SubConst && SubConst->isZero() &&
3370 Sub->getOpcode() == Instruction::Sub && "Expected a negating sub");
3371 }
3372
3374 SmallPtrSet<VPSingleDefRecipe *, 4> ExpressionRecipesSeen;
3375 for (auto *R : reverse(ExpressionRecipes)) {
3376 if (ExpressionRecipesSeen.insert(R).second)
3377 delete R;
3378 }
3379 for (VPValue *T : LiveInPlaceholders)
3380 delete T;
3381 }
3382
3383 VP_CLASSOF_IMPL(VPRecipeBase::VPExpressionSC)
3384
3385 VPExpressionRecipe *clone() override {
3386 assert(!ExpressionRecipes.empty() && "empty expressions should be removed");
3387 SmallVector<VPSingleDefRecipe *> NewExpressiondRecipes;
3388 for (auto *R : ExpressionRecipes)
3389 NewExpressiondRecipes.push_back(R->clone());
3390 for (auto *New : NewExpressiondRecipes) {
3391 for (const auto &[Idx, Old] : enumerate(ExpressionRecipes))
3392 New->replaceUsesOfWith(Old, NewExpressiondRecipes[Idx]);
3393 // Update placeholder operands in the cloned recipe to use the external
3394 // operands, to be internalized when the cloned expression is constructed.
3395 for (const auto &[Placeholder, OutsideOp] :
3396 zip(LiveInPlaceholders, operands()))
3397 New->replaceUsesOfWith(Placeholder, OutsideOp);
3398 }
3399 return new VPExpressionRecipe(ExpressionType, NewExpressiondRecipes);
3400 }
3401
3402 /// Return the VPValue to use to infer the result type of the recipe.
3404 unsigned OpIdx =
3405 cast<VPReductionRecipe>(ExpressionRecipes.back())->isConditional() ? 2
3406 : 1;
3407 return getOperand(getNumOperands() - OpIdx);
3408 }
3409
3410 /// Insert the recipes of the expression back into the VPlan, directly before
3411 /// the current recipe. Leaves the expression recipe empty, which must be
3412 /// removed before codegen.
3413 void decompose();
3414
3415 unsigned getVFScaleFactor() const {
3416 auto *PR = dyn_cast<VPReductionRecipe>(ExpressionRecipes.back());
3417 return PR ? PR->getVFScaleFactor() : 1;
3418 }
3419
3420 /// Method for generating code, must not be called as this recipe is abstract.
3421 void execute(VPTransformState &State) override {
3422 llvm_unreachable("recipe must be removed before execute");
3423 }
3424
3426 VPCostContext &Ctx) const override;
3427
3428 /// Returns true if this expression contains recipes that may read from or
3429 /// write to memory.
3430 bool mayReadOrWriteMemory() const;
3431
3432 /// Returns true if this expression contains recipes that may have side
3433 /// effects.
3434 bool mayHaveSideEffects() const;
3435
3436 /// Returns true if the result of this VPExpressionRecipe is a single-scalar.
3437 bool isSingleScalar() const;
3438
3439protected:
3440#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3441 /// Print the recipe.
3442 void printRecipe(raw_ostream &O, const Twine &Indent,
3443 VPSlotTracker &SlotTracker) const override;
3444#endif
3445};
3446
3447/// VPPredInstPHIRecipe is a recipe for generating the phi nodes needed when
3448/// control converges back from a Branch-on-Mask. The phi nodes are needed in
3449/// order to merge values that are set under such a branch and feed their uses.
3450/// The phi nodes can be scalar or vector depending on the users of the value.
3451/// This recipe works in concert with VPBranchOnMaskRecipe.
3453public:
3454 /// Construct a VPPredInstPHIRecipe given \p PredInst whose value needs a phi
3455 /// nodes after merging back from a Branch-on-Mask.
3457 : VPSingleDefRecipe(VPRecipeBase::VPPredInstPHISC, PredV, DL) {}
3458 ~VPPredInstPHIRecipe() override = default;
3459
3461 return new VPPredInstPHIRecipe(getOperand(0), getDebugLoc());
3462 }
3463
3464 VP_CLASSOF_IMPL(VPRecipeBase::VPPredInstPHISC)
3465
3466 /// Generates phi nodes for live-outs (from a replicate region) as needed to
3467 /// retain SSA form.
3468 void execute(VPTransformState &State) override;
3469
3470 /// Return the cost of this VPPredInstPHIRecipe.
3472 VPCostContext &Ctx) const override {
3473 // TODO: Compute accurate cost after retiring the legacy cost model.
3474 return 0;
3475 }
3476
3477 /// Returns true if the recipe uses scalars of operand \p Op.
3478 bool usesScalars(const VPValue *Op) const override {
3480 "Op must be an operand of the recipe");
3481 return true;
3482 }
3483
3484protected:
3485#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3486 /// Print the recipe.
3487 void printRecipe(raw_ostream &O, const Twine &Indent,
3488 VPSlotTracker &SlotTracker) const override;
3489#endif
3490};
3491
3492/// A common base class for widening memory operations. An optional mask can be
3493/// provided as the last operand.
3495 public VPIRMetadata {
3496protected:
3498
3499 /// Alignment information for this memory access.
3501
3502 /// Whether the accessed addresses are consecutive.
3504
3505 /// Whether the consecutive accessed addresses are in reverse order.
3507
3508 /// Whether the memory access is masked.
3509 bool IsMasked = false;
3510
3511 void setMask(VPValue *Mask) {
3512 assert(!IsMasked && "cannot re-set mask");
3513 if (!Mask)
3514 return;
3515 addOperand(Mask);
3516 IsMasked = true;
3517 }
3518
3519 VPWidenMemoryRecipe(const char unsigned SC, Instruction &I,
3520 std::initializer_list<VPValue *> Operands,
3521 bool Consecutive, bool Reverse,
3522 const VPIRMetadata &Metadata, DebugLoc DL)
3523 : VPRecipeBase(SC, Operands, DL), VPIRMetadata(Metadata), Ingredient(I),
3525 Reverse(Reverse) {
3526 assert((Consecutive || !Reverse) && "Reverse implies consecutive");
3528 "Reversed acccess without VPVectorEndPointerRecipe address?");
3529 }
3530
3531public:
3533 llvm_unreachable("cloning not supported");
3534 }
3535
3536 static inline bool classof(const VPRecipeBase *R) {
3537 return R->getVPRecipeID() == VPRecipeBase::VPWidenLoadSC ||
3538 R->getVPRecipeID() == VPRecipeBase::VPWidenStoreSC ||
3539 R->getVPRecipeID() == VPRecipeBase::VPWidenLoadEVLSC ||
3540 R->getVPRecipeID() == VPRecipeBase::VPWidenStoreEVLSC;
3541 }
3542
3543 static inline bool classof(const VPUser *U) {
3544 auto *R = dyn_cast<VPRecipeBase>(U);
3545 return R && classof(R);
3546 }
3547
3548 /// Return whether the loaded-from / stored-to addresses are consecutive.
3549 bool isConsecutive() const { return Consecutive; }
3550
3551 /// Return whether the consecutive loaded/stored addresses are in reverse
3552 /// order.
3553 bool isReverse() const { return Reverse; }
3554
3555 /// Return the address accessed by this recipe.
3556 VPValue *getAddr() const { return getOperand(0); }
3557
3558 /// Returns true if the recipe is masked.
3559 bool isMasked() const { return IsMasked; }
3560
3561 /// Return the mask used by this recipe. Note that a full mask is represented
3562 /// by a nullptr.
3563 VPValue *getMask() const {
3564 // Mask is optional and therefore the last operand.
3565 return isMasked() ? getOperand(getNumOperands() - 1) : nullptr;
3566 }
3567
3568 /// Returns the alignment of the memory access.
3569 Align getAlign() const { return Alignment; }
3570
3571 /// Generate the wide load/store.
3572 void execute(VPTransformState &State) override {
3573 llvm_unreachable("VPWidenMemoryRecipe should not be instantiated.");
3574 }
3575
3576 /// Return the cost of this VPWidenMemoryRecipe.
3577 InstructionCost computeCost(ElementCount VF,
3578 VPCostContext &Ctx) const override;
3579
3581};
3582
3583/// A recipe for widening load operations, using the address to load from and an
3584/// optional mask.
3586 public VPRecipeValue {
3588 bool Consecutive, bool Reverse,
3589 const VPIRMetadata &Metadata, DebugLoc DL)
3590 : VPWidenMemoryRecipe(VPRecipeBase::VPWidenLoadSC, Load, {Addr},
3591 Consecutive, Reverse, Metadata, DL),
3592 VPRecipeValue(this, &Load) {
3593 setMask(Mask);
3594 }
3595
3598 getMask(), Consecutive, Reverse, *this,
3599 getDebugLoc());
3600 }
3601
3602 VP_CLASSOF_IMPL(VPRecipeBase::VPWidenLoadSC);
3603
3604 /// Generate a wide load or gather.
3605 void execute(VPTransformState &State) override;
3606
3607 /// Returns true if the recipe only uses the first lane of operand \p Op.
3608 bool usesFirstLaneOnly(const VPValue *Op) const override {
3610 "Op must be an operand of the recipe");
3611 // Widened, consecutive loads operations only demand the first lane of
3612 // their address.
3613 return Op == getAddr() && isConsecutive();
3614 }
3615
3616protected:
3617#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3618 /// Print the recipe.
3619 void printRecipe(raw_ostream &O, const Twine &Indent,
3620 VPSlotTracker &SlotTracker) const override;
3621#endif
3622};
3623
3624/// A recipe for widening load operations with vector-predication intrinsics,
3625/// using the address to load from, the explicit vector length and an optional
3626/// mask.
3628 public VPRecipeValue {
3630 VPValue *Mask)
3631 : VPWidenMemoryRecipe(VPRecipeBase::VPWidenLoadEVLSC, L.getIngredient(),
3632 {Addr, &EVL}, L.isConsecutive(), L.isReverse(), L,
3633 L.getDebugLoc()),
3634 VPRecipeValue(this, &getIngredient()) {
3635 setMask(Mask);
3636 }
3637
3638 VP_CLASSOF_IMPL(VPRecipeBase::VPWidenLoadEVLSC)
3639
3640 /// Return the EVL operand.
3641 VPValue *getEVL() const { return getOperand(1); }
3642
3643 /// Generate the wide load or gather.
3644 LLVM_ABI_FOR_TEST void execute(VPTransformState &State) override;
3645
3646 /// Return the cost of this VPWidenLoadEVLRecipe.
3648 computeCost(ElementCount VF, VPCostContext &Ctx) const override;
3649
3650 /// Returns true if the recipe only uses the first lane of operand \p Op.
3651 bool usesFirstLaneOnly(const VPValue *Op) const override {
3653 "Op must be an operand of the recipe");
3654 // Widened loads only demand the first lane of EVL and consecutive loads
3655 // only demand the first lane of their address.
3656 return Op == getEVL() || (Op == getAddr() && isConsecutive());
3657 }
3658
3659protected:
3660#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3661 /// Print the recipe.
3662 LLVM_ABI_FOR_TEST void printRecipe(raw_ostream &O, const Twine &Indent,
3663 VPSlotTracker &SlotTracker) const override;
3664#endif
3665};
3666
3667/// A recipe for widening store operations, using the stored value, the address
3668/// to store to and an optional mask.
3670 VPWidenStoreRecipe(StoreInst &Store, VPValue *Addr, VPValue *StoredVal,
3671 VPValue *Mask, bool Consecutive, bool Reverse,
3672 const VPIRMetadata &Metadata, DebugLoc DL)
3673 : VPWidenMemoryRecipe(VPRecipeBase::VPWidenStoreSC, Store,
3674 {Addr, StoredVal}, Consecutive, Reverse, Metadata,
3675 DL) {
3676 setMask(Mask);
3677 }
3678
3684
3685 VP_CLASSOF_IMPL(VPRecipeBase::VPWidenStoreSC);
3686
3687 /// Return the value stored by this recipe.
3688 VPValue *getStoredValue() const { return getOperand(1); }
3689
3690 /// Generate a wide store or scatter.
3691 void execute(VPTransformState &State) override;
3692
3693 /// Returns true if the recipe only uses the first lane of operand \p Op.
3694 bool usesFirstLaneOnly(const VPValue *Op) const override {
3696 "Op must be an operand of the recipe");
3697 // Widened, consecutive stores only demand the first lane of their address,
3698 // unless the same operand is also stored.
3699 return Op == getAddr() && isConsecutive() && Op != getStoredValue();
3700 }
3701
3702protected:
3703#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3704 /// Print the recipe.
3705 void printRecipe(raw_ostream &O, const Twine &Indent,
3706 VPSlotTracker &SlotTracker) const override;
3707#endif
3708};
3709
3710/// A recipe for widening store operations with vector-predication intrinsics,
3711/// using the value to store, the address to store to, the explicit vector
3712/// length and an optional mask.
3715 VPValue *StoredVal, VPValue &EVL, VPValue *Mask)
3716 : VPWidenMemoryRecipe(VPRecipeBase::VPWidenStoreEVLSC, S.getIngredient(),
3717 {Addr, StoredVal, &EVL}, S.isConsecutive(),
3718 S.isReverse(), S, S.getDebugLoc()) {
3719 setMask(Mask);
3720 }
3721
3722 VP_CLASSOF_IMPL(VPRecipeBase::VPWidenStoreEVLSC)
3723
3724 /// Return the address accessed by this recipe.
3725 VPValue *getStoredValue() const { return getOperand(1); }
3726
3727 /// Return the EVL operand.
3728 VPValue *getEVL() const { return getOperand(2); }
3729
3730 /// Generate the wide store or scatter.
3731 LLVM_ABI_FOR_TEST void execute(VPTransformState &State) override;
3732
3733 /// Return the cost of this VPWidenStoreEVLRecipe.
3735 computeCost(ElementCount VF, VPCostContext &Ctx) const override;
3736
3737 /// Returns true if the recipe only uses the first lane of operand \p Op.
3738 bool usesFirstLaneOnly(const VPValue *Op) const override {
3740 "Op must be an operand of the recipe");
3741 if (Op == getEVL()) {
3742 assert(getStoredValue() != Op && "unexpected store of EVL");
3743 return true;
3744 }
3745 // Widened, consecutive memory operations only demand the first lane of
3746 // their address, unless the same operand is also stored. That latter can
3747 // happen with opaque pointers.
3748 return Op == getAddr() && isConsecutive() && Op != getStoredValue();
3749 }
3750
3751protected:
3752#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3753 /// Print the recipe.
3754 LLVM_ABI_FOR_TEST void printRecipe(raw_ostream &O, const Twine &Indent,
3755 VPSlotTracker &SlotTracker) const override;
3756#endif
3757};
3758
3759/// Recipe to expand a SCEV expression.
3761 const SCEV *Expr;
3762
3763public:
3765 : VPSingleDefRecipe(VPRecipeBase::VPExpandSCEVSC, {}), Expr(Expr) {}
3766
3767 ~VPExpandSCEVRecipe() override = default;
3768
3769 VPExpandSCEVRecipe *clone() override { return new VPExpandSCEVRecipe(Expr); }
3770
3771 VP_CLASSOF_IMPL(VPRecipeBase::VPExpandSCEVSC)
3772
3773 void execute(VPTransformState &State) override {
3774 llvm_unreachable("SCEV expressions must be expanded before final execute");
3775 }
3776
3777 /// Return the cost of this VPExpandSCEVRecipe.
3779 VPCostContext &Ctx) const override {
3780 // TODO: Compute accurate cost after retiring the legacy cost model.
3781 return 0;
3782 }
3783
3784 const SCEV *getSCEV() const { return Expr; }
3785
3786protected:
3787#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3788 /// Print the recipe.
3789 void printRecipe(raw_ostream &O, const Twine &Indent,
3790 VPSlotTracker &SlotTracker) const override;
3791#endif
3792};
3793
3794/// Canonical scalar induction phi of the vector loop. Starting at the specified
3795/// start value (either 0 or the resume value when vectorizing the epilogue
3796/// loop). VPWidenCanonicalIVRecipe represents the vector version of the
3797/// canonical induction variable.
3799public:
3801 : VPHeaderPHIRecipe(VPRecipeBase::VPCanonicalIVPHISC, nullptr, StartV,
3802 DL) {}
3803
3804 ~VPCanonicalIVPHIRecipe() override = default;
3805
3808 R->addOperand(getBackedgeValue());
3809 return R;
3810 }
3811
3812 VP_CLASSOF_IMPL(VPRecipeBase::VPCanonicalIVPHISC)
3813
3814 void execute(VPTransformState &State) override {
3815 llvm_unreachable("cannot execute this recipe, should be replaced by a "
3816 "scalar phi recipe");
3817 }
3818
3819 /// Returns the start value of the canonical induction.
3821
3822 /// Returns the scalar type of the induction.
3823 Type *getScalarType() const { return getStartValue()->getType(); }
3824
3825 /// Returns true if the recipe only uses the first lane of operand \p Op.
3826 bool usesFirstLaneOnly(const VPValue *Op) const override {
3828 "Op must be an operand of the recipe");
3829 return true;
3830 }
3831
3832 /// Returns true if the recipe only uses the first part of operand \p Op.
3833 bool usesFirstPartOnly(const VPValue *Op) const override {
3835 "Op must be an operand of the recipe");
3836 return true;
3837 }
3838
3839 /// Return the cost of this VPCanonicalIVPHIRecipe.
3841 VPCostContext &Ctx) const override {
3842 // For now, match the behavior of the legacy cost model.
3843 return 0;
3844 }
3845
3846protected:
3847#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3848 /// Print the recipe.
3849 LLVM_ABI_FOR_TEST void printRecipe(raw_ostream &O, const Twine &Indent,
3850 VPSlotTracker &SlotTracker) const override;
3851#endif
3852};
3853
3854/// A recipe for generating the active lane mask for the vector loop that is
3855/// used to predicate the vector operations.
3857public:
3859 : VPHeaderPHIRecipe(VPRecipeBase::VPActiveLaneMaskPHISC, nullptr,
3860 StartMask, DL) {}
3861
3862 ~VPActiveLaneMaskPHIRecipe() override = default;
3863
3866 if (getNumOperands() == 2)
3867 R->addOperand(getOperand(1));
3868 return R;
3869 }
3870
3871 VP_CLASSOF_IMPL(VPRecipeBase::VPActiveLaneMaskPHISC)
3872
3873 /// Generate the active lane mask phi of the vector loop.
3874 void execute(VPTransformState &State) override;
3875
3876protected:
3877#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3878 /// Print the recipe.
3879 void printRecipe(raw_ostream &O, const Twine &Indent,
3880 VPSlotTracker &SlotTracker) const override;
3881#endif
3882};
3883
3884/// A recipe for generating the phi node tracking the current scalar iteration
3885/// index. It starts at the start value of the canonical induction and gets
3886/// incremented by the number of scalar iterations processed by the vector loop
3887/// iteration. The increment does not have to be loop invariant.
3889public:
3891 : VPHeaderPHIRecipe(VPRecipeBase::VPCurrentIterationPHISC, nullptr,
3892 StartIV, DL) {}
3893
3894 ~VPCurrentIterationPHIRecipe() override = default;
3895
3897 llvm_unreachable("cloning not implemented yet");
3898 }
3899
3900 VP_CLASSOF_IMPL(VPRecipeBase::VPCurrentIterationPHISC)
3901
3902 void execute(VPTransformState &State) override {
3903 llvm_unreachable("cannot execute this recipe, should be replaced by a "
3904 "scalar phi recipe");
3905 }
3906
3907 /// Return the cost of this VPCurrentIterationPHIRecipe.
3909 VPCostContext &Ctx) const override {
3910 // For now, match the behavior of the legacy cost model.
3911 return 0;
3912 }
3913
3914 /// Returns true if the recipe only uses the first lane of operand \p Op.
3915 bool usesFirstLaneOnly(const VPValue *Op) const override {
3917 "Op must be an operand of the recipe");
3918 return true;
3919 }
3920
3921protected:
3922#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3923 /// Print the recipe.
3924 LLVM_ABI_FOR_TEST void printRecipe(raw_ostream &O, const Twine &Indent,
3925 VPSlotTracker &SlotTracker) const override;
3926#endif
3927};
3928
3929/// A Recipe for widening the canonical induction variable of the vector loop.
3931 public VPUnrollPartAccessor<1> {
3932public:
3934 : VPSingleDefRecipe(VPRecipeBase::VPWidenCanonicalIVSC, {CanonicalIV}) {}
3935
3936 ~VPWidenCanonicalIVRecipe() override = default;
3937
3942
3943 VP_CLASSOF_IMPL(VPRecipeBase::VPWidenCanonicalIVSC)
3944
3945 /// Generate a canonical vector induction variable of the vector loop, with
3946 /// start = {<Part*VF, Part*VF+1, ..., Part*VF+VF-1> for 0 <= Part < UF}, and
3947 /// step = <VF*UF, VF*UF, ..., VF*UF>.
3948 void execute(VPTransformState &State) override;
3949
3950 /// Return the cost of this VPWidenCanonicalIVPHIRecipe.
3952 VPCostContext &Ctx) const override {
3953 // TODO: Compute accurate cost after retiring the legacy cost model.
3954 return 0;
3955 }
3956
3957protected:
3958#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3959 /// Print the recipe.
3960 void printRecipe(raw_ostream &O, const Twine &Indent,
3961 VPSlotTracker &SlotTracker) const override;
3962#endif
3963};
3964
3965/// A recipe for converting the input value \p IV value to the corresponding
3966/// value of an IV with different start and step values, using Start + IV *
3967/// Step.
3969 /// Kind of the induction.
3971 /// If not nullptr, the floating point induction binary operator. Must be set
3972 /// for floating point inductions.
3973 const FPMathOperator *FPBinOp;
3974
3975 /// Name to use for the generated IR instruction for the derived IV.
3976 std::string Name;
3977
3978public:
3980 VPCanonicalIVPHIRecipe *CanonicalIV, VPValue *Step,
3981 const Twine &Name = "")
3983 IndDesc.getKind(),
3984 dyn_cast_or_null<FPMathOperator>(IndDesc.getInductionBinOp()),
3985 Start, CanonicalIV, Step, Name) {}
3986
3988 const FPMathOperator *FPBinOp, VPIRValue *Start,
3989 VPValue *IV, VPValue *Step, const Twine &Name = "")
3990 : VPSingleDefRecipe(VPRecipeBase::VPDerivedIVSC, {Start, IV, Step}),
3991 Kind(Kind), FPBinOp(FPBinOp), Name(Name.str()) {}
3992
3993 ~VPDerivedIVRecipe() override = default;
3994
3996 return new VPDerivedIVRecipe(Kind, FPBinOp, getStartValue(), getOperand(1),
3997 getStepValue());
3998 }
3999
4000 VP_CLASSOF_IMPL(VPRecipeBase::VPDerivedIVSC)
4001
4002 /// Generate the transformed value of the induction at offset StartValue (1.
4003 /// operand) + IV (2. operand) * StepValue (3, operand).
4004 void execute(VPTransformState &State) override;
4005
4006 /// Return the cost of this VPDerivedIVRecipe.
4008 VPCostContext &Ctx) const override {
4009 // TODO: Compute accurate cost after retiring the legacy cost model.
4010 return 0;
4011 }
4012
4013 Type *getScalarType() const { return getStartValue()->getType(); }
4014
4016 VPValue *getStepValue() const { return getOperand(2); }
4017
4018 /// Returns true if the recipe only uses the first lane of operand \p Op.
4019 bool usesFirstLaneOnly(const VPValue *Op) const override {
4021 "Op must be an operand of the recipe");
4022 return true;
4023 }
4024
4025protected:
4026#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4027 /// Print the recipe.
4028 void printRecipe(raw_ostream &O, const Twine &Indent,
4029 VPSlotTracker &SlotTracker) const override;
4030#endif
4031};
4032
4033/// A recipe for handling phi nodes of integer and floating-point inductions,
4034/// producing their scalar values. Before unrolling by UF the recipe represents
4035/// the VF*UF scalar values to be produced, or UF scalar values if only first
4036/// lane is used, and has 3 operands: IV, step and VF. Unrolling adds one extra
4037/// operand StartIndex to all unroll parts except part 0, as the recipe
4038/// represents the VF scalar values (this number of values is taken from
4039/// State.VF rather than from the VF operand) starting at IV + StartIndex.
4041 Instruction::BinaryOps InductionOpcode;
4042
4043public:
4046 DebugLoc DL)
4047 : VPRecipeWithIRFlags(VPRecipeBase::VPScalarIVStepsSC, {IV, Step, VF},
4048 FMFs, DL),
4049 InductionOpcode(Opcode) {}
4050
4052 VPValue *Step, VPValue *VF,
4055 IV, Step, VF, IndDesc.getInductionOpcode(),
4056 dyn_cast_or_null<FPMathOperator>(IndDesc.getInductionBinOp())
4057 ? IndDesc.getInductionBinOp()->getFastMathFlags()
4058 : FastMathFlags(),
4059 DL) {}
4060
4061 ~VPScalarIVStepsRecipe() override = default;
4062
4064 auto *NewR = new VPScalarIVStepsRecipe(getOperand(0), getOperand(1),
4065 getOperand(2), InductionOpcode,
4067 if (VPValue *StartIndex = getStartIndex())
4068 NewR->setStartIndex(StartIndex);
4069 return NewR;
4070 }
4071
4072 VP_CLASSOF_IMPL(VPRecipeBase::VPScalarIVStepsSC)
4073
4074 /// Generate the scalarized versions of the phi node as needed by their users.
4075 void execute(VPTransformState &State) override;
4076
4077 /// Return the cost of this VPScalarIVStepsRecipe.
4079 VPCostContext &Ctx) const override {
4080 // TODO: Compute accurate cost after retiring the legacy cost model.
4081 return 0;
4082 }
4083
4084 VPValue *getStepValue() const { return getOperand(1); }
4085
4086 /// Return the number of scalars to produce per unroll part, used to compute
4087 /// StartIndex during unrolling.
4088 VPValue *getVFValue() const { return getOperand(2); }
4089
4090 /// Return the StartIndex, or null if known to be zero, valid only after
4091 /// unrolling.
4093 return getNumOperands() == 4 ? getOperand(3) : nullptr;
4094 }
4095
4096 /// Set or add the StartIndex operand.
4097 void setStartIndex(VPValue *StartIndex) {
4098 if (getNumOperands() == 4)
4099 setOperand(3, StartIndex);
4100 else
4101 addOperand(StartIndex);
4102 }
4103
4104 /// Returns true if the recipe only uses the first lane of operand \p Op.
4105 bool usesFirstLaneOnly(const VPValue *Op) const override {
4107 "Op must be an operand of the recipe");
4108 return true;
4109 }
4110
4111 Instruction::BinaryOps getInductionOpcode() const { return InductionOpcode; }
4112
4113protected:
4114#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4115 /// Print the recipe.
4116 void printRecipe(raw_ostream &O, const Twine &Indent,
4117 VPSlotTracker &SlotTracker) const override;
4118#endif
4119};
4120
4121/// Casting from VPRecipeBase -> VPPhiAccessors is supported for all recipe
4122/// types implementing VPPhiAccessors. Used by isa<> & co.
4124 static inline bool isPossible(const VPRecipeBase *f) {
4125 // TODO: include VPPredInstPHIRecipe too, once it implements VPPhiAccessors.
4127 }
4128};
4129/// Support casting from VPRecipeBase -> VPPhiAccessors, by down-casting to the
4130/// recipe types implementing VPPhiAccessors. Used by cast<>, dyn_cast<> & co.
4131template <typename SrcTy>
4132struct CastInfoVPPhiAccessors : public CastIsPossible<VPPhiAccessors, SrcTy> {
4133
4135
4136 /// doCast is used by cast<>.
4137 static inline VPPhiAccessors *doCast(SrcTy R) {
4138 return const_cast<VPPhiAccessors *>([R]() -> const VPPhiAccessors * {
4139 switch (R->getVPRecipeID()) {
4140 case VPRecipeBase::VPInstructionSC:
4141 return cast<VPPhi>(R);
4142 case VPRecipeBase::VPIRInstructionSC:
4143 return cast<VPIRPhi>(R);
4144 case VPRecipeBase::VPWidenPHISC:
4145 return cast<VPWidenPHIRecipe>(R);
4146 default:
4147 return cast<VPHeaderPHIRecipe>(R);
4148 }
4149 }());
4150 }
4151
4152 /// doCastIfPossible is used by dyn_cast<>.
4153 static inline VPPhiAccessors *doCastIfPossible(SrcTy f) {
4154 if (!Self::isPossible(f))
4155 return nullptr;
4156 return doCast(f);
4157 }
4158};
4159template <>
4162template <>
4165
4166/// Casting from (const) VPRecipeBase -> (const) VPIRMetadata is supported for
4167/// all recipe types implementing VPIRMetadata. Used by isa<> & co.
4168namespace detail {
4169template <typename DstTy, typename RecipeBasePtrTy>
4170static inline auto castToVPIRMetadata(RecipeBasePtrTy R) -> DstTy {
4171 switch (R->getVPRecipeID()) {
4172 case VPRecipeBase::VPInstructionSC:
4173 return cast<VPInstruction>(R);
4174 case VPRecipeBase::VPWidenSC:
4175 return cast<VPWidenRecipe>(R);
4176 case VPRecipeBase::VPWidenCastSC:
4177 return cast<VPWidenCastRecipe>(R);
4178 case VPRecipeBase::VPWidenIntrinsicSC:
4180 case VPRecipeBase::VPWidenCallSC:
4181 return cast<VPWidenCallRecipe>(R);
4182 case VPRecipeBase::VPReplicateSC:
4183 return cast<VPReplicateRecipe>(R);
4184 case VPRecipeBase::VPInterleaveSC:
4185 case VPRecipeBase::VPInterleaveEVLSC:
4186 return cast<VPInterleaveBase>(R);
4187 case VPRecipeBase::VPWidenLoadSC:
4188 case VPRecipeBase::VPWidenLoadEVLSC:
4189 case VPRecipeBase::VPWidenStoreSC:
4190 case VPRecipeBase::VPWidenStoreEVLSC:
4191 return cast<VPWidenMemoryRecipe>(R);
4192 default:
4193 llvm_unreachable("invalid recipe for VPIRMetadata cast");
4194 }
4195}
4196} // namespace detail
4197
4198/// Support casting from VPRecipeBase -> VPIRMetadata, by down-casting to the
4199/// recipe types implementing VPIRMetadata. Used by cast<>, dyn_cast<> & co.
4200template <typename DstTy, typename SrcTy>
4201struct CastInfoVPIRMetadata : public CastIsPossible<DstTy, SrcTy> {
4202 static inline bool isPossible(SrcTy R) {
4203 // NOTE: Each recipe inheriting from VPIRMetadata must be listed here and
4204 // also handled in castToVPIRMetadata.
4209 R);
4210 }
4211
4212 using RetTy = DstTy *;
4213
4214 /// doCast is used by cast<>.
4215 static inline RetTy doCast(SrcTy R) {
4217 }
4218
4219 /// doCastIfPossible is used by dyn_cast<>.
4220 static inline RetTy doCastIfPossible(SrcTy R) {
4221 if (!isPossible(R))
4222 return nullptr;
4223 return doCast(R);
4224 }
4225};
4226template <>
4229template <>
4232
4233/// VPBasicBlock serves as the leaf of the Hierarchical Control-Flow Graph. It
4234/// holds a sequence of zero or more VPRecipe's each representing a sequence of
4235/// output IR instructions. All PHI-like recipes must come before any non-PHI recipes.
4236class LLVM_ABI_FOR_TEST VPBasicBlock : public VPBlockBase {
4237 friend class VPlan;
4238
4239 /// Use VPlan::createVPBasicBlock to create VPBasicBlocks.
4240 VPBasicBlock(const Twine &Name = "", VPRecipeBase *Recipe = nullptr)
4241 : VPBlockBase(VPBasicBlockSC, Name.str()) {
4242 if (Recipe)
4243 appendRecipe(Recipe);
4244 }
4245
4246public:
4248
4249protected:
4250 /// The VPRecipes held in the order of output instructions to generate.
4252
4253 VPBasicBlock(const unsigned char BlockSC, const Twine &Name = "")
4254 : VPBlockBase(BlockSC, Name.str()) {}
4255
4256public:
4257 ~VPBasicBlock() override {
4258 while (!Recipes.empty())
4259 Recipes.pop_back();
4260 }
4261
4262 /// Instruction iterators...
4267
4268 //===--------------------------------------------------------------------===//
4269 /// Recipe iterator methods
4270 ///
4271 inline iterator begin() { return Recipes.begin(); }
4272 inline const_iterator begin() const { return Recipes.begin(); }
4273 inline iterator end() { return Recipes.end(); }
4274 inline const_iterator end() const { return Recipes.end(); }
4275
4276 inline reverse_iterator rbegin() { return Recipes.rbegin(); }
4277 inline const_reverse_iterator rbegin() const { return Recipes.rbegin(); }
4278 inline reverse_iterator rend() { return Recipes.rend(); }
4279 inline const_reverse_iterator rend() const { return Recipes.rend(); }
4280
4281 inline size_t size() const { return Recipes.size(); }
4282 inline bool empty() const { return Recipes.empty(); }
4283 inline const VPRecipeBase &front() const { return Recipes.front(); }
4284 inline VPRecipeBase &front() { return Recipes.front(); }
4285 inline const VPRecipeBase &back() const { return Recipes.back(); }
4286 inline VPRecipeBase &back() { return Recipes.back(); }
4287
4288 /// Returns a reference to the list of recipes.
4290
4291 /// Returns a pointer to a member of the recipe list.
4292 static RecipeListTy VPBasicBlock::*getSublistAccess(VPRecipeBase *) {
4293 return &VPBasicBlock::Recipes;
4294 }
4295
4296 /// Method to support type inquiry through isa, cast, and dyn_cast.
4297 static inline bool classof(const VPBlockBase *V) {
4298 return V->getVPBlockID() == VPBlockBase::VPBasicBlockSC ||
4299 V->getVPBlockID() == VPBlockBase::VPIRBasicBlockSC;
4300 }
4301
4302 void insert(VPRecipeBase *Recipe, iterator InsertPt) {
4303 assert(Recipe && "No recipe to append.");
4304 assert(!Recipe->Parent && "Recipe already in VPlan");
4305 Recipe->Parent = this;
4306 Recipes.insert(InsertPt, Recipe);
4307 }
4308
4309 /// Augment the existing recipes of a VPBasicBlock with an additional
4310 /// \p Recipe as the last recipe.
4311 void appendRecipe(VPRecipeBase *Recipe) { insert(Recipe, end()); }
4312
4313 /// The method which generates the output IR instructions that correspond to
4314 /// this VPBasicBlock, thereby "executing" the VPlan.
4315 void execute(VPTransformState *State) override;
4316
4317 /// Return the cost of this VPBasicBlock.
4318 InstructionCost cost(ElementCount VF, VPCostContext &Ctx) override;
4319
4320 /// Return the position of the first non-phi node recipe in the block.
4321 iterator getFirstNonPhi();
4322
4323 /// Returns an iterator range over the PHI-like recipes in the block.
4327
4328 /// Split current block at \p SplitAt by inserting a new block between the
4329 /// current block and its successors and moving all recipes starting at
4330 /// SplitAt to the new block. Returns the new block.
4331 VPBasicBlock *splitAt(iterator SplitAt);
4332
4333 VPRegionBlock *getEnclosingLoopRegion();
4334 const VPRegionBlock *getEnclosingLoopRegion() const;
4335
4336#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4337 /// Print this VPBsicBlock to \p O, prefixing all lines with \p Indent. \p
4338 /// SlotTracker is used to print unnamed VPValue's using consequtive numbers.
4339 ///
4340 /// Note that the numbering is applied to the whole VPlan, so printing
4341 /// individual blocks is consistent with the whole VPlan printing.
4342 void print(raw_ostream &O, const Twine &Indent,
4343 VPSlotTracker &SlotTracker) const override;
4344 using VPBlockBase::print; // Get the print(raw_stream &O) version.
4345#endif
4346
4347 /// If the block has multiple successors, return the branch recipe terminating
4348 /// the block. If there are no or only a single successor, return nullptr;
4349 VPRecipeBase *getTerminator();
4350 const VPRecipeBase *getTerminator() const;
4351
4352 /// Returns true if the block is exiting it's parent region.
4353 bool isExiting() const;
4354
4355 /// Clone the current block and it's recipes, without updating the operands of
4356 /// the cloned recipes.
4357 VPBasicBlock *clone() override;
4358
4359 /// Returns the predecessor block at index \p Idx with the predecessors as per
4360 /// the corresponding plain CFG. If the block is an entry block to a region,
4361 /// the first predecessor is the single predecessor of a region, and the
4362 /// second predecessor is the exiting block of the region.
4363 const VPBasicBlock *getCFGPredecessor(unsigned Idx) const;
4364
4365protected:
4366 /// Execute the recipes in the IR basic block \p BB.
4367 void executeRecipes(VPTransformState *State, BasicBlock *BB);
4368
4369 /// Connect the VPBBs predecessors' in the VPlan CFG to the IR basic block
4370 /// generated for this VPBB.
4371 void connectToPredecessors(VPTransformState &State);
4372
4373private:
4374 /// Create an IR BasicBlock to hold the output instructions generated by this
4375 /// VPBasicBlock, and return it. Update the CFGState accordingly.
4376 BasicBlock *createEmptyBasicBlock(VPTransformState &State);
4377};
4378
4379inline const VPBasicBlock *
4381 return getAsRecipe()->getParent()->getCFGPredecessor(Idx);
4382}
4383
4384/// A special type of VPBasicBlock that wraps an existing IR basic block.
4385/// Recipes of the block get added before the first non-phi instruction in the
4386/// wrapped block.
4387/// Note: At the moment, VPIRBasicBlock can only be used to wrap VPlan's
4388/// preheader block.
4389class VPIRBasicBlock : public VPBasicBlock {
4390 friend class VPlan;
4391
4392 BasicBlock *IRBB;
4393
4394 /// Use VPlan::createVPIRBasicBlock to create VPIRBasicBlocks.
4395 VPIRBasicBlock(BasicBlock *IRBB)
4396 : VPBasicBlock(VPIRBasicBlockSC,
4397 (Twine("ir-bb<") + IRBB->getName() + Twine(">")).str()),
4398 IRBB(IRBB) {}
4399
4400public:
4401 ~VPIRBasicBlock() override = default;
4402
4403 static inline bool classof(const VPBlockBase *V) {
4404 return V->getVPBlockID() == VPBlockBase::VPIRBasicBlockSC;
4405 }
4406
4407 /// The method which generates the output IR instructions that correspond to
4408 /// this VPBasicBlock, thereby "executing" the VPlan.
4409 void execute(VPTransformState *State) override;
4410
4411 VPIRBasicBlock *clone() override;
4412
4413 BasicBlock *getIRBasicBlock() const { return IRBB; }
4414};
4415
4416/// VPRegionBlock represents a collection of VPBasicBlocks and VPRegionBlocks
4417/// which form a Single-Entry-Single-Exiting subgraph of the output IR CFG.
4418/// A VPRegionBlock may indicate that its contents are to be replicated several
4419/// times. This is designed to support predicated scalarization, in which a
4420/// scalar if-then code structure needs to be generated VF * UF times. Having
4421/// this replication indicator helps to keep a single model for multiple
4422/// candidate VF's. The actual replication takes place only once the desired VF
4423/// and UF have been determined.
4424class LLVM_ABI_FOR_TEST VPRegionBlock : public VPBlockBase {
4425 friend class VPlan;
4426
4427 /// Hold the Single Entry of the SESE region modelled by the VPRegionBlock.
4428 VPBlockBase *Entry;
4429
4430 /// Hold the Single Exiting block of the SESE region modelled by the
4431 /// VPRegionBlock.
4432 VPBlockBase *Exiting;
4433
4434 /// An indicator whether this region is to generate multiple replicated
4435 /// instances of output IR corresponding to its VPBlockBases.
4436 bool IsReplicator;
4437
4438 /// Use VPlan::createVPRegionBlock to create VPRegionBlocks.
4439 VPRegionBlock(VPBlockBase *Entry, VPBlockBase *Exiting,
4440 const std::string &Name = "", bool IsReplicator = false)
4441 : VPBlockBase(VPRegionBlockSC, Name), Entry(Entry), Exiting(Exiting),
4442 IsReplicator(IsReplicator) {
4443 assert(Entry->getPredecessors().empty() && "Entry block has predecessors.");
4444 assert(Exiting->getSuccessors().empty() && "Exit block has successors.");
4445 Entry->setParent(this);
4446 Exiting->setParent(this);
4447 }
4448 VPRegionBlock(const std::string &Name = "", bool IsReplicator = false)
4449 : VPBlockBase(VPRegionBlockSC, Name), Entry(nullptr), Exiting(nullptr),
4450 IsReplicator(IsReplicator) {}
4451
4452public:
4453 ~VPRegionBlock() override = default;
4454
4455 /// Method to support type inquiry through isa, cast, and dyn_cast.
4456 static inline bool classof(const VPBlockBase *V) {
4457 return V->getVPBlockID() == VPBlockBase::VPRegionBlockSC;
4458 }
4459
4460 const VPBlockBase *getEntry() const { return Entry; }
4461 VPBlockBase *getEntry() { return Entry; }
4462
4463 /// Set \p EntryBlock as the entry VPBlockBase of this VPRegionBlock. \p
4464 /// EntryBlock must have no predecessors.
4465 void setEntry(VPBlockBase *EntryBlock) {
4466 assert(EntryBlock->getPredecessors().empty() &&
4467 "Entry block cannot have predecessors.");
4468 Entry = EntryBlock;
4469 EntryBlock->setParent(this);
4470 }
4471
4472 const VPBlockBase *getExiting() const { return Exiting; }
4473 VPBlockBase *getExiting() { return Exiting; }
4474
4475 /// Set \p ExitingBlock as the exiting VPBlockBase of this VPRegionBlock. \p
4476 /// ExitingBlock must have no successors.
4477 void setExiting(VPBlockBase *ExitingBlock) {
4478 assert(ExitingBlock->getSuccessors().empty() &&
4479 "Exit block cannot have successors.");
4480 Exiting = ExitingBlock;
4481 ExitingBlock->setParent(this);
4482 }
4483
4484 /// Returns the pre-header VPBasicBlock of the loop region.
4486 assert(!isReplicator() && "should only get pre-header of loop regions");
4487 return getSinglePredecessor()->getExitingBasicBlock();
4488 }
4489
4490 /// An indicator whether this region is to generate multiple replicated
4491 /// instances of output IR corresponding to its VPBlockBases.
4492 bool isReplicator() const { return IsReplicator; }
4493
4494 /// The method which generates the output IR instructions that correspond to
4495 /// this VPRegionBlock, thereby "executing" the VPlan.
4496 void execute(VPTransformState *State) override;
4497
4498 // Return the cost of this region.
4499 InstructionCost cost(ElementCount VF, VPCostContext &Ctx) override;
4500
4501#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4502 /// Print this VPRegionBlock to \p O (recursively), prefixing all lines with
4503 /// \p Indent. \p SlotTracker is used to print unnamed VPValue's using
4504 /// consequtive numbers.
4505 ///
4506 /// Note that the numbering is applied to the whole VPlan, so printing
4507 /// individual regions is consistent with the whole VPlan printing.
4508 void print(raw_ostream &O, const Twine &Indent,
4509 VPSlotTracker &SlotTracker) const override;
4510 using VPBlockBase::print; // Get the print(raw_stream &O) version.
4511#endif
4512
4513 /// Clone all blocks in the single-entry single-exit region of the block and
4514 /// their recipes without updating the operands of the cloned recipes.
4515 VPRegionBlock *clone() override;
4516
4517 /// Remove the current region from its VPlan, connecting its predecessor to
4518 /// its entry, and its exiting block to its successor.
4519 void dissolveToCFGLoop();
4520
4521 /// Returns the canonical induction recipe of the region.
4523 VPBasicBlock *EntryVPBB = getEntryBasicBlock();
4524 if (EntryVPBB->empty()) {
4525 // VPlan native path. TODO: Unify both code paths.
4526 EntryVPBB = cast<VPBasicBlock>(EntryVPBB->getSingleSuccessor());
4527 }
4528 return cast<VPCanonicalIVPHIRecipe>(&*EntryVPBB->begin());
4529 }
4531 return const_cast<VPRegionBlock *>(this)->getCanonicalIV();
4532 }
4533
4534 /// Return the type of the canonical IV for loop regions.
4535 Type *getCanonicalIVType() { return getCanonicalIV()->getScalarType(); }
4536 const Type *getCanonicalIVType() const {
4537 return getCanonicalIV()->getScalarType();
4538 }
4539};
4540
4542 return getParent()->getParent();
4543}
4544
4546 return getParent()->getParent();
4547}
4548
4549/// VPlan models a candidate for vectorization, encoding various decisions take
4550/// to produce efficient output IR, including which branches, basic-blocks and
4551/// output IR instructions to generate, and their cost. VPlan holds a
4552/// Hierarchical-CFG of VPBasicBlocks and VPRegionBlocks rooted at an Entry
4553/// VPBasicBlock.
4554class VPlan {
4555 friend class VPlanPrinter;
4556 friend class VPSlotTracker;
4557
4558 /// VPBasicBlock corresponding to the original preheader. Used to place
4559 /// VPExpandSCEV recipes for expressions used during skeleton creation and the
4560 /// rest of VPlan execution.
4561 /// When this VPlan is used for the epilogue vector loop, the entry will be
4562 /// replaced by a new entry block created during skeleton creation.
4563 VPBasicBlock *Entry;
4564
4565 /// VPIRBasicBlock wrapping the header of the original scalar loop.
4566 VPIRBasicBlock *ScalarHeader;
4567
4568 /// Immutable list of VPIRBasicBlocks wrapping the exit blocks of the original
4569 /// scalar loop. Note that some exit blocks may be unreachable at the moment,
4570 /// e.g. if the scalar epilogue always executes.
4572
4573 /// Holds the VFs applicable to this VPlan.
4575
4576 /// Holds the UFs applicable to this VPlan. If empty, the VPlan is valid for
4577 /// any UF.
4579
4580 /// Holds the name of the VPlan, for printing.
4581 std::string Name;
4582
4583 /// Represents the trip count of the original loop, for folding
4584 /// the tail.
4585 VPValue *TripCount = nullptr;
4586
4587 /// Represents the backedge taken count of the original loop, for folding
4588 /// the tail. It equals TripCount - 1.
4589 VPSymbolicValue *BackedgeTakenCount = nullptr;
4590
4591 /// Represents the vector trip count.
4592 VPSymbolicValue VectorTripCount;
4593
4594 /// Represents the vectorization factor of the loop.
4595 VPSymbolicValue VF;
4596
4597 /// Represents the unroll factor of the loop.
4598 VPSymbolicValue UF;
4599
4600 /// Represents the loop-invariant VF * UF of the vector loop region.
4601 VPSymbolicValue VFxUF;
4602
4603 /// Contains all the external definitions created for this VPlan, as a mapping
4604 /// from IR Values to VPIRValues.
4606
4607 /// Blocks allocated and owned by the VPlan. They will be deleted once the
4608 /// VPlan is destroyed.
4609 SmallVector<VPBlockBase *> CreatedBlocks;
4610
4611 /// Construct a VPlan with \p Entry to the plan and with \p ScalarHeader
4612 /// wrapping the original header of the scalar loop.
4613 VPlan(VPBasicBlock *Entry, VPIRBasicBlock *ScalarHeader)
4614 : Entry(Entry), ScalarHeader(ScalarHeader) {
4615 Entry->setPlan(this);
4616 assert(ScalarHeader->getNumSuccessors() == 0 &&
4617 "scalar header must be a leaf node");
4618 }
4619
4620public:
4621 /// Construct a VPlan for \p L. This will create VPIRBasicBlocks wrapping the
4622 /// original preheader and scalar header of \p L, to be used as entry and
4623 /// scalar header blocks of the new VPlan.
4624 VPlan(Loop *L);
4625
4626 /// Construct a VPlan with a new VPBasicBlock as entry, a VPIRBasicBlock
4627 /// wrapping \p ScalarHeaderBB and a trip count of \p TC.
4628 VPlan(BasicBlock *ScalarHeaderBB) {
4629 setEntry(createVPBasicBlock("preheader"));
4630 ScalarHeader = createVPIRBasicBlock(ScalarHeaderBB);
4631 }
4632
4634
4636 Entry = VPBB;
4637 VPBB->setPlan(this);
4638 }
4639
4640 /// Generate the IR code for this VPlan.
4641 void execute(VPTransformState *State);
4642
4643 /// Return the cost of this plan.
4645
4646 VPBasicBlock *getEntry() { return Entry; }
4647 const VPBasicBlock *getEntry() const { return Entry; }
4648
4649 /// Returns the preheader of the vector loop region, if one exists, or null
4650 /// otherwise.
4652 VPRegionBlock *VectorRegion = getVectorLoopRegion();
4653 return VectorRegion
4654 ? cast<VPBasicBlock>(VectorRegion->getSinglePredecessor())
4655 : nullptr;
4656 }
4657
4658 /// Returns the VPRegionBlock of the vector loop.
4661
4662 /// Returns the 'middle' block of the plan, that is the block that selects
4663 /// whether to execute the scalar tail loop or the exit block from the loop
4664 /// latch. If there is an early exit from the vector loop, the middle block
4665 /// conceptully has the early exit block as third successor, split accross 2
4666 /// VPBBs. In that case, the second VPBB selects whether to execute the scalar
4667 /// tail loop or the exit block. If the scalar tail loop or exit block are
4668 /// known to always execute, the middle block may branch directly to that
4669 /// block. This function cannot be called once the vector loop region has been
4670 /// removed.
4672 VPRegionBlock *LoopRegion = getVectorLoopRegion();
4673 assert(
4674 LoopRegion &&
4675 "cannot call the function after vector loop region has been removed");
4676 // The middle block is always the last successor of the region.
4677 return cast<VPBasicBlock>(LoopRegion->getSuccessors().back());
4678 }
4679
4681 return const_cast<VPlan *>(this)->getMiddleBlock();
4682 }
4683
4684 /// Return the VPBasicBlock for the preheader of the scalar loop.
4686 return cast<VPBasicBlock>(getScalarHeader()->getSinglePredecessor());
4687 }
4688
4689 /// Return the VPIRBasicBlock wrapping the header of the scalar loop.
4690 VPIRBasicBlock *getScalarHeader() const { return ScalarHeader; }
4691
4692 /// Return an ArrayRef containing VPIRBasicBlocks wrapping the exit blocks of
4693 /// the original scalar loop.
4694 ArrayRef<VPIRBasicBlock *> getExitBlocks() const { return ExitBlocks; }
4695
4696 /// Return the VPIRBasicBlock corresponding to \p IRBB. \p IRBB must be an
4697 /// exit block.
4699
4700 /// Returns true if \p VPBB is an exit block.
4701 bool isExitBlock(VPBlockBase *VPBB);
4702
4703 /// The trip count of the original loop.
4705 assert(TripCount && "trip count needs to be set before accessing it");
4706 return TripCount;
4707 }
4708
4709 /// Set the trip count assuming it is currently null; if it is not - use
4710 /// resetTripCount().
4711 void setTripCount(VPValue *NewTripCount) {
4712 assert(!TripCount && NewTripCount && "TripCount should not be set yet.");
4713 TripCount = NewTripCount;
4714 }
4715
4716 /// Resets the trip count for the VPlan. The caller must make sure all uses of
4717 /// the original trip count have been replaced.
4718 void resetTripCount(VPValue *NewTripCount) {
4719 assert(TripCount && NewTripCount && TripCount->getNumUsers() == 0 &&
4720 "TripCount must be set when resetting");
4721 TripCount = NewTripCount;
4722 }
4723
4724 /// The backedge taken count of the original loop.
4726 if (!BackedgeTakenCount)
4727 BackedgeTakenCount = new VPSymbolicValue();
4728 return BackedgeTakenCount;
4729 }
4730 VPValue *getBackedgeTakenCount() const { return BackedgeTakenCount; }
4731
4732 /// The vector trip count.
4733 VPSymbolicValue &getVectorTripCount() { return VectorTripCount; }
4734
4735 /// Returns the VF of the vector loop region.
4736 VPValue &getVF() { return VF; };
4737 const VPValue &getVF() const { return VF; };
4738
4739 /// Returns the UF of the vector loop region.
4740 VPValue &getUF() { return UF; };
4741
4742 /// Returns VF * UF of the vector loop region.
4743 VPValue &getVFxUF() { return VFxUF; }
4744
4747 }
4748
4749 void addVF(ElementCount VF) { VFs.insert(VF); }
4750
4752 assert(hasVF(VF) && "Cannot set VF not already in plan");
4753 VFs.clear();
4754 VFs.insert(VF);
4755 }
4756
4757 /// Remove \p VF from the plan.
4759 assert(hasVF(VF) && "tried to remove VF not present in plan");
4760 VFs.remove(VF);
4761 }
4762
4763 bool hasVF(ElementCount VF) const { return VFs.count(VF); }
4764 bool hasScalableVF() const {
4765 return any_of(VFs, [](ElementCount VF) { return VF.isScalable(); });
4766 }
4767
4768 /// Returns an iterator range over all VFs of the plan.
4771 return VFs;
4772 }
4773
4774 bool hasScalarVFOnly() const {
4775 bool HasScalarVFOnly = VFs.size() == 1 && VFs[0].isScalar();
4776 assert(HasScalarVFOnly == hasVF(ElementCount::getFixed(1)) &&
4777 "Plan with scalar VF should only have a single VF");
4778 return HasScalarVFOnly;
4779 }
4780
4781 bool hasUF(unsigned UF) const { return UFs.empty() || UFs.contains(UF); }
4782
4783 /// Returns the concrete UF of the plan, after unrolling.
4784 unsigned getConcreteUF() const {
4785 assert(UFs.size() == 1 && "Expected a single UF");
4786 return UFs[0];
4787 }
4788
4789 void setUF(unsigned UF) {
4790 assert(hasUF(UF) && "Cannot set the UF not already in plan");
4791 UFs.clear();
4792 UFs.insert(UF);
4793 }
4794
4795 /// Returns true if the VPlan already has been unrolled, i.e. it has a single
4796 /// concrete UF.
4797 bool isUnrolled() const { return UFs.size() == 1; }
4798
4799 /// Return a string with the name of the plan and the applicable VFs and UFs.
4800 std::string getName() const;
4801
4802 void setName(const Twine &newName) { Name = newName.str(); }
4803
4804 /// Gets the live-in VPIRValue for \p V or adds a new live-in (if none exists
4805 /// yet) for \p V.
4807 assert(V && "Trying to get or add the VPIRValue of a null Value");
4808 auto [It, Inserted] = LiveIns.try_emplace(V);
4809 if (Inserted) {
4810 if (auto *CI = dyn_cast<ConstantInt>(V))
4811 It->second = new VPConstantInt(CI);
4812 else
4813 It->second = new VPIRValue(V);
4814 }
4815
4816 assert(isa<VPIRValue>(It->second) &&
4817 "Only VPIRValues should be in mapping");
4818 return It->second;
4819 }
4821 assert(V && "Trying to get or add the VPIRValue of a null VPIRValue");
4822 return getOrAddLiveIn(V->getValue());
4823 }
4824
4825 /// Return a VPIRValue wrapping i1 true.
4826 VPIRValue *getTrue() { return getConstantInt(1, 1); }
4827
4828 /// Return a VPIRValue wrapping i1 false.
4829 VPIRValue *getFalse() { return getConstantInt(1, 0); }
4830
4831 /// Return a VPIRValue wrapping the null value of type \p Ty.
4832 VPIRValue *getZero(Type *Ty) { return getConstantInt(Ty, 0); }
4833
4834 /// Return a VPIRValue wrapping the AllOnes value of type \p Ty.
4836 return getConstantInt(APInt::getAllOnes(Ty->getIntegerBitWidth()));
4837 }
4838
4839 /// Return a VPIRValue wrapping a ConstantInt with the given type and value.
4840 VPIRValue *getConstantInt(Type *Ty, uint64_t Val, bool IsSigned = false) {
4841 return getOrAddLiveIn(ConstantInt::get(Ty, Val, IsSigned));
4842 }
4843
4844 /// Return a VPIRValue wrapping a ConstantInt with the given bitwidth and
4845 /// value.
4847 bool IsSigned = false) {
4848 return getConstantInt(APInt(BitWidth, Val, IsSigned));
4849 }
4850
4851 /// Return a VPIRValue wrapping a ConstantInt with the given APInt value.
4853 return getOrAddLiveIn(ConstantInt::get(getContext(), Val));
4854 }
4855
4856 /// Return the live-in VPIRValue for \p V, if there is one or nullptr
4857 /// otherwise.
4858 VPIRValue *getLiveIn(Value *V) const { return LiveIns.lookup(V); }
4859
4860 /// Return the list of live-in VPValues available in the VPlan.
4861 auto getLiveIns() const { return LiveIns.values(); }
4862
4863#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4864 /// Print the live-ins of this VPlan to \p O.
4865 void printLiveIns(raw_ostream &O) const;
4866
4867 /// Print this VPlan to \p O.
4868 LLVM_ABI_FOR_TEST void print(raw_ostream &O) const;
4869
4870 /// Print this VPlan in DOT format to \p O.
4871 LLVM_ABI_FOR_TEST void printDOT(raw_ostream &O) const;
4872
4873 /// Dump the plan to stderr (for debugging).
4874 LLVM_DUMP_METHOD void dump() const;
4875#endif
4876
4877 /// Clone the current VPlan, update all VPValues of the new VPlan and cloned
4878 /// recipes to refer to the clones, and return it.
4880
4881 /// Create a new VPBasicBlock with \p Name and containing \p Recipe if
4882 /// present. The returned block is owned by the VPlan and deleted once the
4883 /// VPlan is destroyed.
4885 VPRecipeBase *Recipe = nullptr) {
4886 auto *VPB = new VPBasicBlock(Name, Recipe);
4887 CreatedBlocks.push_back(VPB);
4888 return VPB;
4889 }
4890
4891 /// Create a new loop region with \p Name and entry and exiting blocks set
4892 /// to \p Entry and \p Exiting respectively, if set. The returned block is
4893 /// owned by the VPlan and deleted once the VPlan is destroyed.
4894 VPRegionBlock *createLoopRegion(const std::string &Name = "",
4895 VPBlockBase *Entry = nullptr,
4896 VPBlockBase *Exiting = nullptr) {
4897 auto *VPB = Entry ? new VPRegionBlock(Entry, Exiting, Name)
4898 : new VPRegionBlock(Name);
4899 CreatedBlocks.push_back(VPB);
4900 return VPB;
4901 }
4902
4903 /// Create a new replicate region with \p Entry, \p Exiting and \p Name. The
4904 /// returned block is owned by the VPlan and deleted once the VPlan is
4905 /// destroyed.
4907 const std::string &Name = "") {
4908 auto *VPB = new VPRegionBlock(Entry, Exiting, Name, true);
4909 CreatedBlocks.push_back(VPB);
4910 return VPB;
4911 }
4912
4913 /// Create a VPIRBasicBlock wrapping \p IRBB, but do not create
4914 /// VPIRInstructions wrapping the instructions in t\p IRBB. The returned
4915 /// block is owned by the VPlan and deleted once the VPlan is destroyed.
4917
4918 /// Create a VPIRBasicBlock from \p IRBB containing VPIRInstructions for all
4919 /// instructions in \p IRBB, except its terminator which is managed by the
4920 /// successors of the block in VPlan. The returned block is owned by the VPlan
4921 /// and deleted once the VPlan is destroyed.
4923
4924 /// Returns true if the VPlan is based on a loop with an early exit. That is
4925 /// the case if the VPlan has either more than one exit block or a single exit
4926 /// block with multiple predecessors (one for the exit via the latch and one
4927 /// via the other early exit).
4928 bool hasEarlyExit() const {
4929 return count_if(ExitBlocks,
4930 [](VPIRBasicBlock *EB) { return EB->hasPredecessors(); }) >
4931 1 ||
4932 (ExitBlocks.size() == 1 && ExitBlocks[0]->getNumPredecessors() > 1);
4933 }
4934
4935 /// Returns true if the scalar tail may execute after the vector loop. Note
4936 /// that this relies on unneeded branches to the scalar tail loop being
4937 /// removed.
4938 bool hasScalarTail() const {
4939 return !(!getScalarPreheader()->hasPredecessors() ||
4941 }
4942};
4943
4944#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4945inline raw_ostream &operator<<(raw_ostream &OS, const VPlan &Plan) {
4946 Plan.print(OS);
4947 return OS;
4948}
4949#endif
4950
4951} // end namespace llvm
4952
4953#endif // LLVM_TRANSFORMS_VECTORIZE_VPLAN_H
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
aarch64 promote const
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 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_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Definition Compiler.h:661
#define LLVM_ABI_FOR_TEST
Definition Compiler.h:218
#define LLVM_PACKED_START
Definition Compiler.h:554
dxil translate DXIL Translate Metadata
Hexagon Common GEP
iv users
Definition IVUsers.cpp:48
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)
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
static DebugLoc getDebugLoc(MachineBasicBlock::instr_iterator FirstMI, MachineBasicBlock::instr_iterator LastMI)
Return the first DebugLoc that has line number information, given a range of instructions.
This file implements a map that provides insertion order iteration.
This file provides utility analysis objects describing memory locations.
#define T
MachineInstr unsigned OpIdx
#define P(N)
static StringRef getName(Value *V)
static bool mayHaveSideEffects(MachineInstr &MI)
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
static const BasicSubtargetSubTypeKV * find(StringRef S, ArrayRef< BasicSubtargetSubTypeKV > A)
Find KV in array using binary search.
static std::optional< unsigned > getOpcode(ArrayRef< VPValue * > Values)
Returns the opcode of Values or ~0 if they do not all agree.
Definition VPlanSLP.cpp:247
This file contains the declarations of the entities induced by Vectorization Plans,...
#define VP_CLASSOF_IMPL(VPRecipeID)
Definition VPlan.h:570
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:235
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
bool empty() const
empty - Check if the array is empty.
Definition ArrayRef.h:137
LLVM Basic Block Representation.
Definition BasicBlock.h:62
LLVM_ABI LLVMContext & getContext() const
Get the context in which this basic block lives.
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:448
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:676
A debug info location.
Definition DebugLoc.h:123
static DebugLoc getUnknown()
Definition DebugLoc.h:161
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:164
static constexpr ElementCount getFixed(ScalarTy MinVal)
Definition TypeSize.h:309
Utility class for floating point operations which can have information about relaxed accuracy require...
Definition Operator.h:200
Convenience struct for specifying and reasoning about fast-math flags.
Definition FMF.h:23
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
Common base class shared among various IRBuilders.
Definition IRBuilder.h:114
A struct for saving information about induction variables.
InductionKind
This enum represents the kinds of inductions that we support.
InnerLoopVectorizer vectorizes loops which contain only one basic block to a specified vectorization ...
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:68
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:1080
Root of the metadata hierarchy.
Definition Metadata.h:64
The RecurrenceDescriptor is used to identify recurrences variables in a loop.
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:339
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.
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
std::string str() const
str - Get the contents as an std::string.
Definition StringRef.h:222
This class represents a truncation of integer types.
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:45
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition Type.h:128
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:3864
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
VPActiveLaneMaskPHIRecipe(VPValue *StartMask, DebugLoc DL)
Definition VPlan.h:3858
~VPActiveLaneMaskPHIRecipe() override=default
VPBasicBlock serves as the leaf of the Hierarchical Control-Flow Graph.
Definition VPlan.h:4236
RecipeListTy::const_iterator const_iterator
Definition VPlan.h:4264
void appendRecipe(VPRecipeBase *Recipe)
Augment the existing recipes of a VPBasicBlock with an additional Recipe as the last recipe.
Definition VPlan.h:4311
RecipeListTy::const_reverse_iterator const_reverse_iterator
Definition VPlan.h:4266
RecipeListTy::iterator iterator
Instruction iterators...
Definition VPlan.h:4263
RecipeListTy & getRecipeList()
Returns a reference to the list of recipes.
Definition VPlan.h:4289
iplist< VPRecipeBase > RecipeListTy
Definition VPlan.h:4247
VPBasicBlock(const unsigned char BlockSC, const Twine &Name="")
Definition VPlan.h:4253
iterator end()
Definition VPlan.h:4273
iterator begin()
Recipe iterator methods.
Definition VPlan.h:4271
RecipeListTy::reverse_iterator reverse_iterator
Definition VPlan.h:4265
iterator_range< iterator > phis()
Returns an iterator range over the PHI-like recipes in the block.
Definition VPlan.h:4324
const VPBasicBlock * getCFGPredecessor(unsigned Idx) const
Returns the predecessor block at index Idx with the predecessors as per the corresponding plain CFG.
Definition VPlan.cpp:791
iterator getFirstNonPhi()
Return the position of the first non-phi node recipe in the block.
Definition VPlan.cpp:232
~VPBasicBlock() override
Definition VPlan.h:4257
const_reverse_iterator rbegin() const
Definition VPlan.h:4277
reverse_iterator rend()
Definition VPlan.h:4278
RecipeListTy Recipes
The VPRecipes held in the order of output instructions to generate.
Definition VPlan.h:4251
VPRecipeBase & back()
Definition VPlan.h:4286
const VPRecipeBase & front() const
Definition VPlan.h:4283
const_iterator begin() const
Definition VPlan.h:4272
VPRecipeBase & front()
Definition VPlan.h:4284
const VPRecipeBase & back() const
Definition VPlan.h:4285
void insert(VPRecipeBase *Recipe, iterator InsertPt)
Definition VPlan.h:4302
bool empty() const
Definition VPlan.h:4282
const_iterator end() const
Definition VPlan.h:4274
static bool classof(const VPBlockBase *V)
Method to support type inquiry through isa, cast, and dyn_cast.
Definition VPlan.h:4297
static RecipeListTy VPBasicBlock::* getSublistAccess(VPRecipeBase *)
Returns a pointer to a member of the recipe list.
Definition VPlan.h:4292
reverse_iterator rbegin()
Definition VPlan.h:4276
friend class VPlan
Definition VPlan.h:4237
size_t size() const
Definition VPlan.h:4281
const_reverse_iterator rend() const
Definition VPlan.h:4279
VPValue * getIncomingValue(unsigned Idx) const
Return incoming value number Idx.
Definition VPlan.h:2792
VPValue * getMask(unsigned Idx) const
Return mask number Idx.
Definition VPlan.h:2797
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:2767
unsigned getNumIncomingValues() const
Return the number of incoming values, taking into account when normalized the first incoming value wi...
Definition VPlan.h:2787
void execute(VPTransformState &State) override
The method which generates the output IR instructions that correspond to this VPRecipe,...
Definition VPlan.h:2808
bool usesFirstLaneOnly(const VPValue *Op) const override
Returns true if the recipe only uses the first lane of operand Op.
Definition VPlan.h:2817
VPBlendRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:2774
void setMask(unsigned Idx, VPValue *V)
Set mask number Idx to V.
Definition VPlan.h:2803
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:2783
VPBlockBase is the building block of the Hierarchical Control-Flow Graph.
Definition VPlan.h:82
void setSuccessors(ArrayRef< VPBlockBase * > NewSuccs)
Set each VPBasicBlock in NewSuccss as successor of this VPBlockBase.
Definition VPlan.h:301
VPRegionBlock * getParent()
Definition VPlan.h:174
VPBlocksTy & getPredecessors()
Definition VPlan.h:206
iterator_range< VPBlockBase ** > predecessors()
Definition VPlan.h:203
LLVM_DUMP_METHOD void dump() const
Dump this VPBlockBase to dbgs().
Definition VPlan.h:371
void setName(const Twine &newName)
Definition VPlan.h:167
size_t getNumSuccessors() const
Definition VPlan.h:220
iterator_range< VPBlockBase ** > successors()
Definition VPlan.h:202
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:224
void swapSuccessors()
Swap successors of the block. The block must have exactly 2 successors.
Definition VPlan.h:323
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:666
SmallVectorImpl< VPBlockBase * > VPBlocksTy
Definition VPlan.h:161
virtual ~VPBlockBase()=default
const VPBlocksTy & getHierarchicalPredecessors()
Definition VPlan.h:259
unsigned getIndexForSuccessor(const VPBlockBase *Succ) const
Returns the index for Succ in the blocks successor list.
Definition VPlan.h:336
size_t getNumPredecessors() const
Definition VPlan.h:221
void setPredecessors(ArrayRef< VPBlockBase * > NewPreds)
Set each VPBasicBlock in NewPreds as predecessor of this VPBlockBase.
Definition VPlan.h:292
VPBlockBase * getEnclosingBlockWithPredecessors()
Definition VPlan.cpp:224
unsigned getIndexForPredecessor(const VPBlockBase *Pred) const
Returns the index for Pred in the blocks predecessors list.
Definition VPlan.h:329
const VPBlocksTy & getPredecessors() const
Definition VPlan.h:205
virtual VPBlockBase * clone()=0
Clone the current block and it's recipes without updating the operands of the cloned recipes,...
enum { VPRegionBlockSC, VPBasicBlockSC, VPIRBasicBlockSC } VPBlockTy
An enumeration for keeping track of the concrete subclass of VPBlockBase that are actually instantiat...
Definition VPlan.h:159
virtual InstructionCost cost(ElementCount VF, VPCostContext &Ctx)=0
Return the cost of the block.
void setPlan(VPlan *ParentPlan)
Sets the pointer of the plan containing the block.
Definition VPlan.cpp:196
const VPRegionBlock * getParent() const
Definition VPlan.h:175
const std::string & getName() const
Definition VPlan.h:165
void clearSuccessors()
Remove all the successors of this block.
Definition VPlan.h:311
VPBlockBase * getSingleHierarchicalSuccessor()
Definition VPlan.h:249
void setTwoSuccessors(VPBlockBase *IfTrue, VPBlockBase *IfFalse)
Set two given VPBlockBases IfTrue and IfFalse to be the two successors of this VPBlockBase.
Definition VPlan.h:283
VPBlockBase * getSinglePredecessor() const
Definition VPlan.h:216
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:243
void clearPredecessors()
Remove all the predecessor of this block.
Definition VPlan.h:308
friend class VPBlockUtils
Definition VPlan.h:83
unsigned getVPBlockID() const
Definition VPlan.h:172
void printAsOperand(raw_ostream &OS, bool PrintType=false) const
Definition VPlan.h:350
void swapPredecessors()
Swap predecessors of the block.
Definition VPlan.h:315
VPBlockBase(const unsigned char SC, const std::string &N)
Definition VPlan.h:151
VPBlocksTy & getSuccessors()
Definition VPlan.h:200
VPBlockBase * getEnclosingBlockWithSuccessors()
An Enclosing Block of a block B is any block containing B, including B itself.
Definition VPlan.cpp:216
const VPBasicBlock * getEntryBasicBlock() const
Definition VPlan.cpp:182
void setOneSuccessor(VPBlockBase *Successor)
Set a given VPBlockBase Successor as the single successor of this VPBlockBase.
Definition VPlan.h:272
void setParent(VPRegionBlock *P)
Definition VPlan.h:185
VPBlockBase * getSingleHierarchicalPredecessor()
Definition VPlan.h:265
VPBlockBase * getSingleSuccessor() const
Definition VPlan.h:210
const VPBlocksTy & getSuccessors() const
Definition VPlan.h:199
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
Definition VPlan.h:3286
VPBranchOnMaskRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:3270
bool usesScalars(const VPValue *Op) const override
Returns true if the recipe uses scalars of operand Op.
Definition VPlan.h:3294
VPBranchOnMaskRecipe(VPValue *BlockInMask, DebugLoc DL)
Definition VPlan.h:3267
VPlan-based builder utility analogous to IRBuilder.
Canonical scalar induction phi of the vector loop.
Definition VPlan.h:3798
~VPCanonicalIVPHIRecipe() override=default
VPCanonicalIVPHIRecipe(VPIRValue *StartV, DebugLoc DL)
Definition VPlan.h:3800
bool usesFirstLaneOnly(const VPValue *Op) const override
Returns true if the recipe only uses the first lane of operand Op.
Definition VPlan.h:3826
VPCanonicalIVPHIRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:3806
LLVM_ABI_FOR_TEST void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
bool usesFirstPartOnly(const VPValue *Op) const override
Returns true if the recipe only uses the first part of operand Op.
Definition VPlan.h:3833
VPIRValue * getStartValue() const
Returns the start value of the canonical induction.
Definition VPlan.h:3820
Type * getScalarType() const
Returns the scalar type of the induction.
Definition VPlan.h:3823
void execute(VPTransformState &State) override
Generate the phi nodes.
Definition VPlan.h:3814
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPCanonicalIVPHIRecipe.
Definition VPlan.h:3840
VPCurrentIterationPHIRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:3896
VPCurrentIterationPHIRecipe(VPValue *StartIV, DebugLoc DL)
Definition VPlan.h:3890
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPCurrentIterationPHIRecipe.
Definition VPlan.h:3908
LLVM_ABI_FOR_TEST void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
void execute(VPTransformState &State) override
Generate the phi nodes.
Definition VPlan.h:3902
bool usesFirstLaneOnly(const VPValue *Op) const override
Returns true if the recipe only uses the first lane of operand Op.
Definition VPlan.h:3915
~VPCurrentIterationPHIRecipe() override=default
void execute(VPTransformState &State) override
Generate the transformed value of the induction at offset StartValue (1.
VPIRValue * getStartValue() const
Definition VPlan.h:4015
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPDerivedIVRecipe.
Definition VPlan.h:4007
VPValue * getStepValue() const
Definition VPlan.h:4016
VPDerivedIVRecipe(const InductionDescriptor &IndDesc, VPIRValue *Start, VPCanonicalIVPHIRecipe *CanonicalIV, VPValue *Step, const Twine &Name="")
Definition VPlan.h:3979
Type * getScalarType() const
Definition VPlan.h:4013
VPDerivedIVRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:3995
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
~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:4019
VPDerivedIVRecipe(InductionDescriptor::InductionKind Kind, const FPMathOperator *FPBinOp, VPIRValue *Start, VPValue *IV, VPValue *Step, const Twine &Name="")
Definition VPlan.h:3987
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:3773
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:3778
VPExpandSCEVRecipe(const SCEV *Expr)
Definition VPlan.h:3764
const SCEV * getSCEV() const
Definition VPlan.h:3784
VPExpandSCEVRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:3769
~VPExpandSCEVRecipe() override=default
void execute(VPTransformState &State) override
Method for generating code, must not be called as this recipe is abstract.
Definition VPlan.h:3421
VPValue * getOperandOfResultType() const
Return the VPValue to use to infer the result type of the recipe.
Definition VPlan.h:3403
VPExpressionRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:3385
void decompose()
Insert the recipes of the expression back into the VPlan, directly before the current recipe.
~VPExpressionRecipe() override
Definition VPlan.h:3373
bool isSingleScalar() const
Returns true if the result of this VPExpressionRecipe is a single-scalar.
VPExpressionRecipe(VPWidenCastRecipe *Ext0, VPWidenCastRecipe *Ext1, VPWidenRecipe *Mul, VPWidenRecipe *Sub, VPReductionRecipe *Red)
Definition VPlan.h:3359
VPExpressionRecipe(VPWidenCastRecipe *Ext, VPReductionRecipe *Red)
Definition VPlan.h:3351
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:3355
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
unsigned getVFScaleFactor() const
Definition VPlan.h:3415
VPExpressionRecipe(VPWidenRecipe *Mul, VPReductionRecipe *Red)
Definition VPlan.h:3353
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this header phi recipe.
VPHeaderPHIRecipe(unsigned char VPRecipeID, Instruction *UnderlyingInstr, VPValue *Start, DebugLoc DL=DebugLoc::getUnknown())
Definition VPlan.h:2275
const VPRecipeBase * getAsRecipe() const override
Return a VPRecipeBase* to the current object.
Definition VPlan.h:2279
static bool classof(const VPSingleDefRecipe *R)
Definition VPlan.h:2292
static bool classof(const VPValue *V)
Definition VPlan.h:2289
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override=0
Print the recipe.
virtual VPValue * getBackedgeValue()
Returns the incoming value from the loop backedge.
Definition VPlan.h:2315
void setBackedgeValue(VPValue *V)
Update the incoming value from the loop backedge.
Definition VPlan.h:2320
VPValue * getStartValue()
Returns the start value of the phi, if one is set.
Definition VPlan.h:2304
void setStartValue(VPValue *V)
Update the start value of the recipe.
Definition VPlan.h:2312
static bool classof(const VPRecipeBase *R)
Method to support type inquiry through isa, cast, and dyn_cast.
Definition VPlan.h:2285
VPValue * getStartValue() const
Definition VPlan.h:2307
void execute(VPTransformState &State) override=0
Generate the phi nodes.
virtual VPRecipeBase & getBackedgeRecipe()
Returns the backedge value as a recipe.
Definition VPlan.h:2324
~VPHeaderPHIRecipe() override=default
void execute(VPTransformState &State) override
Produce a vectorized histogram operation.
VPHistogramRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:2027
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:2044
unsigned getOpcode() const
Definition VPlan.h:2040
VPHistogramRecipe(unsigned Opcode, ArrayRef< VPValue * > Operands, DebugLoc DL=DebugLoc::getUnknown())
Definition VPlan.h:2020
VP_CLASSOF_IMPL(VPRecipeBase::VPHistogramSC)
~VPHistogramRecipe() override=default
A special type of VPBasicBlock that wraps an existing IR basic block.
Definition VPlan.h:4389
void execute(VPTransformState *State) override
The method which generates the output IR instructions that correspond to this VPBasicBlock,...
Definition VPlan.cpp:461
BasicBlock * getIRBasicBlock() const
Definition VPlan.h:4413
static bool classof(const VPBlockBase *V)
Definition VPlan.h:4403
~VPIRBasicBlock() override=default
friend class VPlan
Definition VPlan.h:4390
VPIRBasicBlock * clone() override
Clone the current block and it's recipes, without updating the operands of the cloned recipes.
Definition VPlan.cpp:486
Class to record and manage LLVM IR flags.
Definition VPlan.h:672
FastMathFlagsTy FMFs
Definition VPlan.h:760
ReductionFlagsTy ReductionFlags
Definition VPlan.h:762
LLVM_ABI_FOR_TEST bool hasRequiredFlagsForOpcode(unsigned Opcode) const
Returns true if Opcode has its required flags set.
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.
static VPIRFlags getDefaultFlags(unsigned Opcode)
Returns default flags for Opcode for opcodes that support it, asserts otherwise.
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:977
LLVM_ABI_FOR_TEST FastMathFlags getFastMathFlags() const
bool isReductionOrdered() const
Definition VPlan.h:1027
TruncFlagsTy TruncFlags
Definition VPlan.h:755
CmpInst::Predicate getPredicate() const
Definition VPlan.h:949
uint8_t AllFlags[2]
Definition VPlan.h:763
bool hasNonNegFlag() const
Returns true if the recipe has non-negative flag.
Definition VPlan.h:985
void transferFlags(VPIRFlags &Other)
Definition VPlan.h:858
ExactFlagsTy ExactFlags
Definition VPlan.h:757
bool hasNoSignedWrap() const
Definition VPlan.h:1004
void intersectFlags(const VPIRFlags &Other)
Only keep flags also present in Other.
bool isDisjoint() const
Definition VPlan.h:1015
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
bool isNonNeg() const
Definition VPlan.h:987
GEPNoWrapFlags getGEPNoWrapFlags() const
Definition VPlan.h:967
bool hasPredicate() const
Returns true if the recipe has a comparison predicate.
Definition VPlan.h:972
DisjointFlagsTy DisjointFlags
Definition VPlan.h:756
void setPredicate(CmpInst::Predicate Pred)
Definition VPlan.h:957
bool hasNoUnsignedWrap() const
Definition VPlan.h:993
FCmpFlagsTy FCmpFlags
Definition VPlan.h:761
NonNegFlagsTy NonNegFlags
Definition VPlan.h:759
bool isReductionInLoop() const
Definition VPlan.h:1033
void dropPoisonGeneratingFlags()
Drop all poison-generating flags.
Definition VPlan.h:869
void applyFlags(Instruction &I) const
Apply the IR flags to I.
Definition VPlan.h:906
VPIRFlags(GEPNoWrapFlags GEPFlags)
Definition VPlan.h:848
uint8_t CmpPredStorage
Definition VPlan.h:753
RecurKind getRecurKind() const
Definition VPlan.h:1021
VPIRFlags(Instruction &I)
Definition VPlan.h:769
Instruction & getInstruction() const
Definition VPlan.h:1686
bool usesFirstPartOnly(const VPValue *Op) const override
Returns true if the VPUser only uses the first part of operand Op.
Definition VPlan.h:1694
~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:1673
bool usesFirstLaneOnly(const VPValue *Op) const override
Returns true if the VPUser only uses the first lane of operand Op.
Definition VPlan.h:1700
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:1688
VPIRInstruction(Instruction &I)
VPIRInstruction::create() should be used to create VPIRInstructions, as subclasses may need to be cre...
Definition VPlan.h:1661
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:1138
VPIRMetadata & operator=(const VPIRMetadata &Other)=default
MDNode * getMetadata(unsigned Kind) const
Get metadata of kind Kind. Returns nullptr if not found.
Definition VPlan.h:1174
VPIRMetadata(Instruction &I)
Adds metatadata that can be preserved from the original instruction I.
Definition VPlan.h:1146
VPIRMetadata(const VPIRMetadata &Other)=default
Copy constructor for cloning.
void intersect(const VPIRMetadata &MD)
Intersect this VPIRMetadata object with MD, keeping only metadata nodes that are common to both.
VPIRMetadata()=default
void print(raw_ostream &O, VPSlotTracker &SlotTracker) const
Print metadata with node IDs.
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:1158
VPInstructionWithType(unsigned Opcode, ArrayRef< VPValue * > Operands, Type *ResultTy, const VPIRFlags &Flags={}, const VPIRMetadata &Metadata={}, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="")
Definition VPlan.h:1491
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPInstruction.
Definition VPlan.h:1533
static bool classof(const VPUser *R)
Definition VPlan.h:1518
static bool classof(const VPRecipeBase *R)
Definition VPlan.h:1499
Type * getResultType() const
Definition VPlan.h:1539
VPInstruction * clone() override
Clone the current recipe.
Definition VPlan.h:1522
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
void execute(VPTransformState &State) override
Generate the instruction.
This is a concrete Recipe that models a single VPlan-level instruction.
Definition VPlan.h:1193
unsigned getNumOperandsWithoutMask() const
Returns the number of operands, excluding the mask if the VPInstruction is masked.
Definition VPlan.h:1423
iterator_range< operand_iterator > operandsWithoutMask()
Returns an iterator range over the operands excluding the mask operand if present.
Definition VPlan.h:1443
VPInstruction * clone() override
Clone the current recipe.
Definition VPlan.h:1365
@ ExtractLastActive
Extracts the last active lane from a set of vectors.
Definition VPlan.h:1304
@ ExtractLane
Extracts a single lane (first operand) from a set of vector operands.
Definition VPlan.h:1295
@ ExitingIVValue
Compute the exiting value of a wide induction after vectorization, that is the value of the last lane...
Definition VPlan.h:1311
@ ComputeAnyOfResult
Compute the final result of a AnyOf reduction with select(cmp(),x,y), where one of (x,...
Definition VPlan.h:1240
@ WideIVStep
Scale the first operand (vector step) by the second operand (scalar-step).
Definition VPlan.h:1285
@ ResumeForEpilogue
Explicit user for the resume phi of the canonical induction in the main VPlan, used by the epilogue v...
Definition VPlan.h:1298
@ Unpack
Extracts all lanes from its (non-scalable) vector operand.
Definition VPlan.h:1237
@ ReductionStartVector
Start vector for reductions with 3 operands: the original start value, the identity value for the red...
Definition VPlan.h:1289
@ BuildVector
Creates a fixed-width vector containing all operands.
Definition VPlan.h:1232
@ BuildStructVector
Given operands of (the same) struct type, creates a struct of fixed- width vectors each containing a ...
Definition VPlan.h:1229
@ VScale
Returns the value for vscale.
Definition VPlan.h:1307
@ CanonicalIVIncrementForPart
Definition VPlan.h:1213
bool hasResult() const
Definition VPlan.h:1389
iterator_range< const_operand_iterator > operandsWithoutMask() const
Definition VPlan.h:1446
void addMask(VPValue *Mask)
Add mask Mask to an unmasked VPInstruction, if it needs masking.
Definition VPlan.h:1428
StringRef getName() const
Returns the symbolic name assigned to the VPInstruction.
Definition VPlan.h:1468
unsigned getOpcode() const
Definition VPlan.h:1373
VPInstruction(unsigned Opcode, ArrayRef< VPValue * > Operands, const VPIRFlags &Flags={}, const VPIRMetadata &MD={}, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="")
void setName(StringRef NewName)
Set the symbolic name for the VPInstruction.
Definition VPlan.h:1471
friend class VPlanSlp
Definition VPlan.h:1194
VPValue * getMask() const
Returns the mask for the VPInstruction.
Definition VPlan.h:1437
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:1413
virtual unsigned getNumStoreOperands() const =0
Returns the number of stored operands of this interleave group.
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:2904
void execute(VPTransformState &State) override
The method which generates the output IR instructions that correspond to this VPRecipe,...
Definition VPlan.h:2910
static bool classof(const VPUser *U)
Definition VPlan.h:2886
VPInterleaveBase(const unsigned char SC, const InterleaveGroup< Instruction > *IG, ArrayRef< VPValue * > Operands, ArrayRef< VPValue * > StoredValues, VPValue *Mask, bool NeedsMaskForGaps, const VPIRMetadata &MD, DebugLoc DL)
Definition VPlan.h:2852
Instruction * getInsertPos() const
Definition VPlan.h:2908
static bool classof(const VPRecipeBase *R)
Definition VPlan.h:2881
const InterleaveGroup< Instruction > * getInterleaveGroup() const
Definition VPlan.h:2906
VPValue * getMask() const
Return the mask used by this recipe.
Definition VPlan.h:2898
ArrayRef< VPValue * > getStoredValues() const
Return the VPValues stored by this interleave group.
Definition VPlan.h:2927
VPInterleaveBase * clone() override=0
Clone the current recipe.
VPValue * getAddr() const
Return the address accessed by this recipe.
Definition VPlan.h:2892
A recipe for interleaved memory operations with vector-predication intrinsics.
Definition VPlan.h:2979
bool usesFirstLaneOnly(const VPValue *Op) const override
The recipe only uses the first lane of the address, and EVL operand.
Definition VPlan.h:3007
VPValue * getEVL() const
The VPValue of the explicit vector length.
Definition VPlan.h:3001
~VPInterleaveEVLRecipe() override=default
unsigned getNumStoreOperands() const override
Returns the number of stored operands of this interleave group.
Definition VPlan.h:3014
VPInterleaveEVLRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:2994
VPInterleaveEVLRecipe(VPInterleaveRecipe &R, VPValue &EVL, VPValue *Mask)
Definition VPlan.h:2981
VPInterleaveRecipe is a recipe for transforming an interleave group of load or stores into one wide l...
Definition VPlan.h:2937
unsigned getNumStoreOperands() const override
Returns the number of stored operands of this interleave group.
Definition VPlan.h:2964
~VPInterleaveRecipe() override=default
VPInterleaveRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:2947
bool usesFirstLaneOnly(const VPValue *Op) const override
Returns true if the recipe only uses the first lane of operand Op.
Definition VPlan.h:2958
VPInterleaveRecipe(const InterleaveGroup< Instruction > *IG, VPValue *Addr, ArrayRef< VPValue * > StoredValues, VPValue *Mask, bool NeedsMaskForGaps, const VPIRMetadata &MD, DebugLoc DL)
Definition VPlan.h:2939
In what follows, the term "input IR" refers to code that is fed into the vectorizer whereas the term ...
Helper type to provide functions to access incoming values and blocks for phi-like recipes.
Definition VPlan.h:1551
virtual const VPRecipeBase * getAsRecipe() const =0
Return a VPRecipeBase* to the current object.
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:1580
virtual unsigned getNumIncoming() const
Returns the number of incoming values, also number of incoming blocks.
Definition VPlan.h:1575
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:4380
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:1600
VPValue * getIncomingValue(unsigned Idx) const
Returns the incoming VPValue with index Idx.
Definition VPlan.h:1560
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:1585
const_incoming_blocks_range incoming_blocks() const
Returns an iterator range over the incoming blocks.
Definition VPlan.h:1589
~VPPredInstPHIRecipe() override=default
bool usesScalars(const VPValue *Op) const override
Returns true if the recipe uses scalars of operand Op.
Definition VPlan.h:3478
VPPredInstPHIRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:3460
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPPredInstPHIRecipe.
Definition VPlan.h:3471
VPPredInstPHIRecipe(VPValue *PredV, DebugLoc DL)
Construct a VPPredInstPHIRecipe given PredInst whose value needs a phi nodes after merging back from ...
Definition VPlan.h:3456
VPRecipeBase is a base class modeling a sequence of one or more output IR instructions.
Definition VPlan.h:388
bool mayReadFromMemory() const
Returns true if the recipe may read from memory.
bool mayReadOrWriteMemory() const
Returns true if the recipe may read from or write to memory.
Definition VPlan.h:532
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:4541
void setDebugLoc(DebugLoc NewDL)
Set the recipe's debug location to NewDL.
Definition VPlan.h:543
bool mayWriteToMemory() const
Returns true if the recipe may write to memory.
~VPRecipeBase() override=default
VPBasicBlock * getParent()
Definition VPlan.h:463
DebugLoc getDebugLoc() const
Returns the debug location of the recipe.
Definition VPlan.h:537
virtual void execute(VPTransformState &State)=0
The method which generates the output IR instructions that correspond to this VPRecipe,...
void moveBefore(VPBasicBlock &BB, iplist< VPRecipeBase >::iterator I)
Unlink this recipe and insert into BB before I.
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:512
iplist< VPRecipeBase >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
virtual VPRecipeBase * clone()=0
Clone the current recipe.
friend class VPBlockUtils
Definition VPlan.h:390
const VPBasicBlock * getParent() const
Definition VPlan.h:464
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:517
void removeFromParent()
This method unlinks 'this' from the containing basic block, but does not delete it.
unsigned getVPRecipeID() const
Definition VPlan.h:509
void moveAfter(VPRecipeBase *MovePos)
Unlink this recipe from its current VPBasicBlock and insert it into the VPBasicBlock that MovePos liv...
enum { VPBranchOnMaskSC, VPDerivedIVSC, VPExpandSCEVSC, VPExpressionSC, VPIRInstructionSC, VPInstructionSC, VPInterleaveEVLSC, VPInterleaveSC, VPReductionEVLSC, VPReductionSC, VPReplicateSC, VPScalarIVStepsSC, VPVectorPointerSC, VPVectorEndPointerSC, VPWidenCallSC, VPWidenCanonicalIVSC, VPWidenCastSC, VPWidenGEPSC, VPWidenIntrinsicSC, VPWidenLoadEVLSC, VPWidenLoadSC, VPWidenStoreEVLSC, VPWidenStoreSC, VPWidenSC, VPBlendSC, VPHistogramSC, VPWidenPHISC, VPPredInstPHISC, VPCanonicalIVPHISC, VPCurrentIterationPHISC, VPActiveLaneMaskPHISC, VPFirstOrderRecurrencePHISC, VPWidenIntOrFpInductionSC, VPWidenPointerInductionSC, VPReductionPHISC, VPFirstPHISC=VPWidenPHISC, VPFirstHeaderPHISC=VPCanonicalIVPHISC, VPLastHeaderPHISC=VPReductionPHISC, VPLastPHISC=VPReductionPHISC, } VPRecipeTy
An enumeration for keeping track of the concrete subclass of VPRecipeBase that is actually instantiat...
Definition VPlan.h:406
VPRecipeBase(const unsigned char SC, ArrayRef< VPValue * > Operands, DebugLoc DL=DebugLoc::getUnknown())
Definition VPlan.h:453
A VPValue defined by a recipe that produces one or more values.
Definition VPlanValue.h:232
LLVM_ABI_FOR_TEST VPRecipeValue(VPRecipeBase *Def, Value *UV=nullptr)
Definition VPlan.cpp:143
friend class VPValue
Definition VPlanValue.h:233
VPValue * getEVL() const
The VPValue of the explicit vector length.
Definition VPlan.h:3162
VPReductionEVLRecipe(VPReductionRecipe &R, VPValue &EVL, VPValue *CondOp, DebugLoc DL=DebugLoc::getUnknown())
Definition VPlan.h:3141
bool usesFirstLaneOnly(const VPValue *Op) const override
Returns true if the recipe only uses the first lane of operand Op.
Definition VPlan.h:3165
VPReductionEVLRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:3152
~VPReductionEVLRecipe() override=default
bool isOrdered() const
Returns true, if the phi is part of an ordered reduction.
Definition VPlan.h:2728
void setVFScaleFactor(unsigned ScaleFactor)
Set the VFScaleFactor for this reduction phi.
Definition VPlan.h:2714
VPReductionPHIRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:2693
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:2707
~VPReductionPHIRecipe() override=default
bool hasUsesOutsideReductionChain() const
Returns true, if the phi is part of a multi-use reduction.
Definition VPlan.h:2740
unsigned getNumIncoming() const override
Returns the number of incoming values, also number of incoming blocks.
Definition VPlan.h:2722
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:2681
bool isInLoop() const
Returns true if the phi is part of an in-loop reduction.
Definition VPlan.h:2731
bool usesFirstLaneOnly(const VPValue *Op) const override
Returns true if the recipe only uses the first lane of operand Op.
Definition VPlan.h:2745
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.
bool isPartialReduction() const
Returns true if the reduction outputs a vector with a scaled down VF.
Definition VPlan.h:2737
RecurKind getRecurrenceKind() const
Returns the recurrence kind of the reduction.
Definition VPlan.h:2725
A recipe to represent inloop, ordered or partial reduction operations.
Definition VPlan.h:3030
VPReductionRecipe(const unsigned char SC, RecurKind RdxKind, FastMathFlags FMFs, Instruction *I, ArrayRef< VPValue * > Operands, VPValue *CondOp, ReductionStyle Style, DebugLoc DL)
Definition VPlan.h:3039
bool isConditional() const
Return true if the in-loop reduction is conditional.
Definition VPlan.h:3104
static bool classof(const VPRecipeBase *R)
Definition VPlan.h:3073
static bool classof(const VPSingleDefRecipe *R)
Definition VPlan.h:3088
VPValue * getVecOp() const
The VPValue of the vector value to be reduced.
Definition VPlan.h:3115
VPValue * getCondOp() const
The VPValue of the condition for the block.
Definition VPlan.h:3117
RecurKind getRecurrenceKind() const
Return the recurrence kind for the in-loop reduction.
Definition VPlan.h:3100
VPReductionRecipe(RecurKind RdxKind, FastMathFlags FMFs, Instruction *I, VPValue *ChainOp, VPValue *VecOp, VPValue *CondOp, ReductionStyle Style, DebugLoc DL=DebugLoc::getUnknown())
Definition VPlan.h:3053
bool isOrdered() const
Return true if the in-loop reduction is ordered.
Definition VPlan.h:3102
VPReductionRecipe(const RecurKind RdxKind, FastMathFlags FMFs, VPValue *ChainOp, VPValue *VecOp, VPValue *CondOp, ReductionStyle Style, DebugLoc DL=DebugLoc::getUnknown())
Definition VPlan.h:3059
bool isPartialReduction() const
Returns true if the reduction outputs a vector with a scaled down VF.
Definition VPlan.h:3106
~VPReductionRecipe() override=default
VPValue * getChainOp() const
The VPValue of the scalar Chain being accumulated.
Definition VPlan.h:3113
bool isInLoop() const
Returns true if the reduction is in-loop.
Definition VPlan.h:3108
VPReductionRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:3067
static bool classof(const VPUser *U)
Definition VPlan.h:3078
static bool classof(const VPValue *VPV)
Definition VPlan.h:3083
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:3122
VPRegionBlock represents a collection of VPBasicBlocks and VPRegionBlocks which form a Single-Entry-S...
Definition VPlan.h:4424
const VPBlockBase * getEntry() const
Definition VPlan.h:4460
Type * getCanonicalIVType()
Return the type of the canonical IV for loop regions.
Definition VPlan.h:4535
bool isReplicator() const
An indicator whether this region is to generate multiple replicated instances of output IR correspond...
Definition VPlan.h:4492
~VPRegionBlock() override=default
void setExiting(VPBlockBase *ExitingBlock)
Set ExitingBlock as the exiting VPBlockBase of this VPRegionBlock.
Definition VPlan.h:4477
VPBlockBase * getExiting()
Definition VPlan.h:4473
VPCanonicalIVPHIRecipe * getCanonicalIV()
Returns the canonical induction recipe of the region.
Definition VPlan.h:4522
void setEntry(VPBlockBase *EntryBlock)
Set EntryBlock as the entry VPBlockBase of this VPRegionBlock.
Definition VPlan.h:4465
const Type * getCanonicalIVType() const
Definition VPlan.h:4536
const VPBlockBase * getExiting() const
Definition VPlan.h:4472
VPBlockBase * getEntry()
Definition VPlan.h:4461
const VPCanonicalIVPHIRecipe * getCanonicalIV() const
Definition VPlan.h:4530
VPBasicBlock * getPreheaderVPBB()
Returns the pre-header VPBasicBlock of the loop region.
Definition VPlan.h:4485
friend class VPlan
Definition VPlan.h:4425
static bool classof(const VPBlockBase *V)
Method to support type inquiry through isa, cast, and dyn_cast.
Definition VPlan.h:4456
VPReplicateRecipe replicates a given instruction producing multiple scalar copies of the original sca...
Definition VPlan.h:3184
bool isSingleScalar() const
Definition VPlan.h:3225
VPReplicateRecipe(Instruction *I, ArrayRef< VPValue * > Operands, bool IsSingleScalar, VPValue *Mask=nullptr, const VPIRFlags &Flags={}, VPIRMetadata Metadata={}, DebugLoc DL=DebugLoc::getUnknown())
Definition VPlan.h:3192
~VPReplicateRecipe() override=default
bool usesScalars(const VPValue *Op) const override
Returns true if the recipe uses scalars of operand Op.
Definition VPlan.h:3237
bool isPredicated() const
Definition VPlan.h:3227
VPReplicateRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:3206
bool usesFirstLaneOnly(const VPValue *Op) const override
Returns true if the recipe only uses the first lane of operand Op.
Definition VPlan.h:3230
unsigned getOpcode() const
Definition VPlan.h:3254
VPValue * getMask()
Return the mask of a predicated VPReplicateRecipe.
Definition VPlan.h:3249
Instruction::BinaryOps getInductionOpcode() const
Definition VPlan.h:4111
VPValue * getStepValue() const
Definition VPlan.h:4084
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPScalarIVStepsRecipe.
Definition VPlan.h:4078
VPScalarIVStepsRecipe(const InductionDescriptor &IndDesc, VPValue *IV, VPValue *Step, VPValue *VF, DebugLoc DL=DebugLoc::getUnknown())
Definition VPlan.h:4051
void setStartIndex(VPValue *StartIndex)
Set or add the StartIndex operand.
Definition VPlan.h:4097
VPScalarIVStepsRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:4063
VPValue * getStartIndex() const
Return the StartIndex, or null if known to be zero, valid only after unrolling.
Definition VPlan.h:4092
VPValue * getVFValue() const
Return the number of scalars to produce per unroll part, used to compute StartIndex during unrolling.
Definition VPlan.h:4088
VPScalarIVStepsRecipe(VPValue *IV, VPValue *Step, VPValue *VF, Instruction::BinaryOps Opcode, FastMathFlags FMFs, DebugLoc DL)
Definition VPlan.h:4044
~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:4105
VPSingleDef is a base class for recipes for modeling a sequence of one or more output IR that define ...
Definition VPlan.h:589
VPSingleDefRecipe(const unsigned char SC, ArrayRef< VPValue * > Operands, Value *UV, DebugLoc DL=DebugLoc::getUnknown())
Definition VPlan.h:595
static bool classof(const VPValue *V)
Definition VPlan.h:644
Instruction * getUnderlyingInstr()
Returns the underlying instruction.
Definition VPlan.h:657
static bool classof(const VPRecipeBase *R)
Definition VPlan.h:599
const Instruction * getUnderlyingInstr() const
Definition VPlan.h:660
static bool classof(const VPUser *U)
Definition VPlan.h:649
LLVM_ABI_FOR_TEST LLVM_DUMP_METHOD void dump() const
Print this VPSingleDefRecipe to dbgs() (for debugging).
VPSingleDefRecipe * clone() override=0
Clone the current recipe.
VPSingleDefRecipe(const unsigned char SC, ArrayRef< VPValue * > Operands, DebugLoc DL=DebugLoc::getUnknown())
Definition VPlan.h:591
This class can be used to assign names to VPValues.
Helper to access the operand that contains the unroll part for this recipe after unrolling.
Definition VPlan.h:1126
VPValue * getUnrollPartOperand(const VPUser &U) const
Return the VPValue operand containing the unroll part or null if there is no such operand.
unsigned getUnrollPart(const VPUser &U) const
Return the unroll part.
This class augments VPValue with operands which provide the inverse def-use edges from VPValue's user...
Definition VPlanValue.h:258
void printOperands(raw_ostream &O, VPSlotTracker &SlotTracker) const
Print the operands to O.
Definition VPlan.cpp:1451
operand_range operands()
Definition VPlanValue.h:326
void setOperand(unsigned I, VPValue *New)
Definition VPlanValue.h:302
unsigned getNumOperands() const
Definition VPlanValue.h:296
operand_iterator op_end()
Definition VPlanValue.h:324
operand_iterator op_begin()
Definition VPlanValue.h:322
VPValue * getOperand(unsigned N) const
Definition VPlanValue.h:297
VPUser(ArrayRef< VPValue * > Operands)
Definition VPlanValue.h:277
iterator_range< const_operand_iterator > const_operand_range
Definition VPlanValue.h:320
iterator_range< operand_iterator > operand_range
Definition VPlanValue.h:319
This is the base class of the VPlan Def/Use graph, used for modeling the data flow into,...
Definition VPlanValue.h:46
Value * getLiveInIRValue() const
Return the underlying IR value for a VPIRValue.
Definition VPlan.cpp:137
VPRecipeBase * getDefiningRecipe()
Returns the recipe defining this VPValue or nullptr if it is not defined by a recipe,...
Definition VPlan.cpp:127
friend class VPRecipeValue
Definition VPlanValue.h:50
Value * getUnderlyingValue() const
Return the underlying Value attached to this VPValue.
Definition VPlanValue.h:71
void setUnderlyingValue(Value *Val)
Definition VPlanValue.h:172
unsigned getNumUsers() const
Definition VPlanValue.h:104
bool usesFirstLaneOnly(const VPValue *Op) const override
Returns true if the VPUser only uses the first lane of operand Op.
Definition VPlan.h:2153
VPValue * getVFValue() const
Definition VPlan.h:2142
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:2139
int64_t getStride() const
Definition VPlan.h:2140
VPVectorEndPointerRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:2174
VPValue * getOffset() const
Definition VPlan.h:2143
bool usesFirstPartOnly(const VPValue *Op) const override
Returns true if the recipe only uses the first part of operand Op.
Definition VPlan.h:2167
VPVectorEndPointerRecipe(VPValue *Ptr, VPValue *VF, Type *SourceElementTy, int64_t Stride, GEPNoWrapFlags GEPFlags, DebugLoc DL)
Definition VPlan.h:2129
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPVectorPointerRecipe.
Definition VPlan.h:2160
VPValue * getPointer() const
Definition VPlan.h:2141
void materializeOffset(unsigned Part=0)
Adds the offset operand to the recipe.
Type * getSourceElementType() const
Definition VPlan.h:2211
bool usesFirstLaneOnly(const VPValue *Op) const override
Returns true if the VPUser only uses the first lane of operand Op.
Definition VPlan.h:2213
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,...
bool usesFirstPartOnly(const VPValue *Op) const override
Returns true if the recipe only uses the first part of operand Op.
Definition VPlan.h:2220
VPVectorPointerRecipe(VPValue *Ptr, Type *SourceElementTy, GEPNoWrapFlags GEPFlags, DebugLoc DL)
Definition VPlan.h:2198
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPHeaderPHIRecipe.
Definition VPlan.h:2236
VPVectorPointerRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:2227
A recipe for widening Call instructions using library calls.
Definition VPlan.h:1959
VPWidenCallRecipe(Value *UV, Function *Variant, ArrayRef< VPValue * > CallArguments, const VPIRFlags &Flags={}, const VPIRMetadata &Metadata={}, DebugLoc DL={})
Definition VPlan.h:1966
const_operand_range args() const
Definition VPlan.h:2000
VPWidenCallRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:1981
operand_range args()
Definition VPlan.h:1999
Function * getCalledScalarFunction() const
Definition VPlan.h:1995
~VPWidenCallRecipe() override=default
void execute(VPTransformState &State) override
Generate a canonical vector induction variable of the vector loop, with start = {<Part*VF,...
~VPWidenCanonicalIVRecipe() override=default
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:3951
VPWidenCanonicalIVRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:3938
VPWidenCanonicalIVRecipe(VPCanonicalIVPHIRecipe *CanonicalIV)
Definition VPlan.h:3933
VPWidenCastRecipe is a recipe to create vector cast instructions.
Definition VPlan.h:1807
Instruction::CastOps getOpcode() const
Definition VPlan.h:1845
LLVM_ABI_FOR_TEST void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
Type * getResultType() const
Returns the result type of the cast.
Definition VPlan.h:1848
LLVM_ABI_FOR_TEST void execute(VPTransformState &State) override
Produce widened copies of the cast.
~VPWidenCastRecipe() override=default
LLVM_ABI_FOR_TEST InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPWidenCastRecipe.
VPWidenCastRecipe(Instruction::CastOps Opcode, VPValue *Op, Type *ResultTy, CastInst *CI=nullptr, const VPIRFlags &Flags={}, const VPIRMetadata &Metadata={}, DebugLoc DL=DebugLoc::getUnknown())
Definition VPlan.h:1815
VPWidenCastRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:1830
unsigned getOpcode() const
This recipe generates a GEP instruction.
Definition VPlan.h:2091
Type * getSourceElementType() const
Definition VPlan.h:2096
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPWidenGEPRecipe.
Definition VPlan.h:2099
VPWidenGEPRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:2083
~VPWidenGEPRecipe() override=default
VPWidenGEPRecipe(GetElementPtrInst *GEP, ArrayRef< VPValue * > Operands, const VPIRFlags &Flags={}, DebugLoc DL=DebugLoc::getUnknown())
Definition VPlan.h:2069
void execute(VPTransformState &State) override=0
Generate the phi nodes.
bool usesFirstLaneOnly(const VPValue *Op) const override
Returns true if the recipe only uses the first lane of operand Op.
Definition VPlan.h:2407
static bool classof(const VPValue *V)
Definition VPlan.h:2355
void setStepValue(VPValue *V)
Update the step value of the recipe.
Definition VPlan.h:2374
VPValue * getBackedgeValue() override
Returns the incoming value from the loop backedge.
Definition VPlan.h:2392
VPIRValue * getStartValue() const
Returns the start value of the induction.
Definition VPlan.h:2367
unsigned getNumIncoming() const override
Returns the number of incoming values, also number of incoming blocks.
Definition VPlan.h:2382
PHINode * getPHINode() const
Returns the underlying PHINode if one exists, or null otherwise.
Definition VPlan.h:2385
VPWidenInductionRecipe(unsigned char Kind, PHINode *IV, VPValue *Start, VPValue *Step, const InductionDescriptor &IndDesc, DebugLoc DL)
Definition VPlan.h:2343
VPValue * getStepValue()
Returns the step value of the induction.
Definition VPlan.h:2370
const InductionDescriptor & getInductionDescriptor() const
Returns the induction descriptor for the recipe.
Definition VPlan.h:2390
VPRecipeBase & getBackedgeRecipe() override
Returns the backedge value as a recipe.
Definition VPlan.h:2399
static bool classof(const VPRecipeBase *R)
Definition VPlan.h:2350
const VPValue * getVFValue() const
Definition VPlan.h:2377
static bool classof(const VPSingleDefRecipe *R)
Definition VPlan.h:2360
const VPValue * getStepValue() const
Definition VPlan.h:2371
VPIRValue * getStartValue() const
Returns the start value of the induction.
Definition VPlan.h:2468
const TruncInst * getTruncInst() const
Definition VPlan.h:2484
void execute(VPTransformState &State) override
Generate the phi nodes.
Definition VPlan.h:2462
~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:2472
VPWidenIntOrFpInductionRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:2454
VPWidenIntOrFpInductionRecipe(PHINode *IV, VPIRValue *Start, VPValue *Step, VPValue *VF, const InductionDescriptor &IndDesc, const VPIRFlags &Flags, DebugLoc DL)
Definition VPlan.h:2428
TruncInst * getTruncInst()
Returns the first defined value as TruncInst, if it is one or nullptr otherwise.
Definition VPlan.h:2483
VPWidenIntOrFpInductionRecipe(PHINode *IV, VPIRValue *Start, VPValue *Step, VPValue *VF, const InductionDescriptor &IndDesc, TruncInst *Trunc, const VPIRFlags &Flags, DebugLoc DL)
Definition VPlan.h:2437
VPValue * getLastUnrolledPartOperand()
Returns the VPValue representing the value of this induction at the last unrolled part,...
Definition VPlan.h:2499
unsigned getNumIncoming() const override
Returns the number of incoming values, also number of incoming blocks.
Definition VPlan.h:2479
Type * getScalarType() const
Returns the scalar type of the induction.
Definition VPlan.h:2492
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:1859
VPWidenIntrinsicRecipe(Intrinsic::ID VectorIntrinsicID, ArrayRef< VPValue * > CallArguments, Type *Ty, const VPIRFlags &Flags={}, const VPIRMetadata &Metadata={}, DebugLoc DL=DebugLoc::getUnknown())
Definition VPlan.h:1890
Intrinsic::ID getVectorIntrinsicID() const
Return the ID of the intrinsic.
Definition VPlan.h:1930
LLVM_ABI_FOR_TEST void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
bool mayReadFromMemory() const
Returns true if the intrinsic may read from memory.
Definition VPlan.h:1939
StringRef getIntrinsicName() const
Return to name of the intrinsic as string.
VPWidenIntrinsicRecipe(CallInst &CI, Intrinsic::ID VectorIntrinsicID, ArrayRef< VPValue * > CallArguments, Type *Ty, const VPIRFlags &Flags={}, const VPIRMetadata &MD={}, DebugLoc DL=DebugLoc::getUnknown())
Definition VPlan.h:1876
bool mayHaveSideEffects() const
Returns true if the intrinsic may have side-effects.
Definition VPlan.h:1945
VPWidenIntrinsicRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:1911
bool mayWriteToMemory() const
Returns true if the intrinsic may write to memory.
Definition VPlan.h:1942
~VPWidenIntrinsicRecipe() override=default
LLVM_ABI_FOR_TEST bool usesFirstLaneOnly(const VPValue *Op) const override
Returns true if the VPUser only uses the first lane of operand Op.
Type * getResultType() const
Return the scalar return type of the intrinsic.
Definition VPlan.h:1933
LLVM_ABI_FOR_TEST void execute(VPTransformState &State) override
Produce a widened version of the vector intrinsic.
LLVM_ABI_FOR_TEST InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this vector intrinsic.
bool IsMasked
Whether the memory access is masked.
Definition VPlan.h:3509
bool Reverse
Whether the consecutive accessed addresses are in reverse order.
Definition VPlan.h:3506
bool isConsecutive() const
Return whether the loaded-from / stored-to addresses are consecutive.
Definition VPlan.h:3549
static bool classof(const VPUser *U)
Definition VPlan.h:3543
void execute(VPTransformState &State) override
Generate the wide load/store.
Definition VPlan.h:3572
Instruction & Ingredient
Definition VPlan.h:3497
VPWidenMemoryRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:3532
Instruction & getIngredient() const
Definition VPlan.h:3580
bool Consecutive
Whether the accessed addresses are consecutive.
Definition VPlan.h:3503
static bool classof(const VPRecipeBase *R)
Definition VPlan.h:3536
VPValue * getMask() const
Return the mask used by this recipe.
Definition VPlan.h:3563
Align Alignment
Alignment information for this memory access.
Definition VPlan.h:3500
bool isMasked() const
Returns true if the recipe is masked.
Definition VPlan.h:3559
VPWidenMemoryRecipe(const char unsigned SC, Instruction &I, std::initializer_list< VPValue * > Operands, bool Consecutive, bool Reverse, const VPIRMetadata &Metadata, DebugLoc DL)
Definition VPlan.h:3519
void setMask(VPValue *Mask)
Definition VPlan.h:3511
Align getAlign() const
Returns the alignment of the memory access.
Definition VPlan.h:3569
VPValue * getAddr() const
Return the address accessed by this recipe.
Definition VPlan.h:3556
bool isReverse() const
Return whether the consecutive loaded/stored addresses are in reverse order.
Definition VPlan.h:3553
const VPRecipeBase * getAsRecipe() const override
Return a VPRecipeBase* to the current object.
Definition VPlan.h:2599
VPWidenPHIRecipe(PHINode *Phi, VPValue *Start=nullptr, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="")
Create a new VPWidenPHIRecipe for Phi with start value Start and debug location DL.
Definition VPlan.h:2564
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPWidenPHIRecipe.
VPWidenPHIRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:2572
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
~VPWidenPHIRecipe() override=default
void execute(VPTransformState &State) override
Generate the phi/select nodes.
VPWidenPointerInductionRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:2526
~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:2535
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:2516
VPWidenRecipe is a recipe for producing a widened instruction using the opcode and operands of the re...
Definition VPlan.h:1751
VPWidenRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:1771
bool usesFirstLaneOnly(const VPValue *Op) const override
Returns true if the recipe only uses the first lane of operand Op.
Definition VPlan.h:1798
VPWidenRecipe(Instruction &I, ArrayRef< VPValue * > Operands, const VPIRFlags &Flags={}, const VPIRMetadata &Metadata={}, DebugLoc DL={})
Definition VPlan.h:1755
VPWidenRecipe(unsigned Opcode, ArrayRef< VPValue * > Operands, const VPIRFlags &Flags={}, const VPIRMetadata &Metadata={}, DebugLoc DL={})
Definition VPlan.h:1763
~VPWidenRecipe() override=default
unsigned getOpcode() const
Definition VPlan.h:1788
Class that maps (parts of) an existing VPlan to trees of combined VPInstructions.
Definition VPlanSLP.h:74
VPlan models a candidate for vectorization, encoding various decisions take to produce efficient outp...
Definition VPlan.h:4554
VPIRValue * getLiveIn(Value *V) const
Return the live-in VPIRValue for V, if there is one or nullptr otherwise.
Definition VPlan.h:4858
LLVM_ABI_FOR_TEST void printDOT(raw_ostream &O) const
Print this VPlan in DOT format to O.
Definition VPlan.cpp:1139
friend class VPSlotTracker
Definition VPlan.h:4556
std::string getName() const
Return a string with the name of the plan and the applicable VFs and UFs.
Definition VPlan.cpp:1115
bool hasVF(ElementCount VF) const
Definition VPlan.h:4763
LLVMContext & getContext() const
Definition VPlan.h:4745
VPBasicBlock * getEntry()
Definition VPlan.h:4646
void setName(const Twine &newName)
Definition VPlan.h:4802
bool hasScalableVF() const
Definition VPlan.h:4764
VPValue & getVFxUF()
Returns VF * UF of the vector loop region.
Definition VPlan.h:4743
VPValue & getVF()
Returns the VF of the vector loop region.
Definition VPlan.h:4736
VPValue * getTripCount() const
The trip count of the original loop.
Definition VPlan.h:4704
VPValue * getOrCreateBackedgeTakenCount()
The backedge taken count of the original loop.
Definition VPlan.h:4725
iterator_range< SmallSetVector< ElementCount, 2 >::iterator > vectorFactors() const
Returns an iterator range over all VFs of the plan.
Definition VPlan.h:4770
VPIRBasicBlock * getExitBlock(BasicBlock *IRBB) const
Return the VPIRBasicBlock corresponding to IRBB.
Definition VPlan.cpp:910
LLVM_ABI_FOR_TEST ~VPlan()
Definition VPlan.cpp:888
VPIRValue * getOrAddLiveIn(VPIRValue *V)
Definition VPlan.h:4820
const VPValue & getVF() const
Definition VPlan.h:4737
VPValue & getUF()
Returns the UF of the vector loop region.
Definition VPlan.h:4740
bool isExitBlock(VPBlockBase *VPBB)
Returns true if VPBB is an exit block.
Definition VPlan.cpp:918
const VPBasicBlock * getEntry() const
Definition VPlan.h:4647
friend class VPlanPrinter
Definition VPlan.h:4555
VPIRValue * getFalse()
Return a VPIRValue wrapping i1 false.
Definition VPlan.h:4829
VPIRValue * getConstantInt(const APInt &Val)
Return a VPIRValue wrapping a ConstantInt with the given APInt value.
Definition VPlan.h:4852
VPIRValue * getAllOnesValue(Type *Ty)
Return a VPIRValue wrapping the AllOnes value of type Ty.
Definition VPlan.h:4835
VPRegionBlock * createReplicateRegion(VPBlockBase *Entry, VPBlockBase *Exiting, const std::string &Name="")
Create a new replicate region with Entry, Exiting and Name.
Definition VPlan.h:4906
VPIRBasicBlock * createEmptyVPIRBasicBlock(BasicBlock *IRBB)
Create a VPIRBasicBlock wrapping IRBB, but do not create VPIRInstructions wrapping the instructions i...
Definition VPlan.cpp:1251
auto getLiveIns() const
Return the list of live-in VPValues available in the VPlan.
Definition VPlan.h:4861
bool hasUF(unsigned UF) const
Definition VPlan.h:4781
ArrayRef< VPIRBasicBlock * > getExitBlocks() const
Return an ArrayRef containing VPIRBasicBlocks wrapping the exit blocks of the original scalar loop.
Definition VPlan.h:4694
VPSymbolicValue & getVectorTripCount()
The vector trip count.
Definition VPlan.h:4733
VPValue * getBackedgeTakenCount() const
Definition VPlan.h:4730
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:4806
VPIRValue * getZero(Type *Ty)
Return a VPIRValue wrapping the null value of type Ty.
Definition VPlan.h:4832
void setVF(ElementCount VF)
Definition VPlan.h:4751
bool isUnrolled() const
Returns true if the VPlan already has been unrolled, i.e.
Definition VPlan.h:4797
LLVM_ABI_FOR_TEST VPRegionBlock * getVectorLoopRegion()
Returns the VPRegionBlock of the vector loop.
Definition VPlan.cpp:1038
bool hasEarlyExit() const
Returns true if the VPlan is based on a loop with an early exit.
Definition VPlan.h:4928
InstructionCost cost(ElementCount VF, VPCostContext &Ctx)
Return the cost of this plan.
Definition VPlan.cpp:1020
unsigned getConcreteUF() const
Returns the concrete UF of the plan, after unrolling.
Definition VPlan.h:4784
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:4846
const VPBasicBlock * getMiddleBlock() const
Definition VPlan.h:4680
void setTripCount(VPValue *NewTripCount)
Set the trip count assuming it is currently null; if it is not - use resetTripCount().
Definition VPlan.h:4711
void resetTripCount(VPValue *NewTripCount)
Resets the trip count for the VPlan.
Definition VPlan.h:4718
VPBasicBlock * getMiddleBlock()
Returns the 'middle' block of the plan, that is the block that selects whether to execute the scalar ...
Definition VPlan.h:4671
void setEntry(VPBasicBlock *VPBB)
Definition VPlan.h:4635
VPBasicBlock * createVPBasicBlock(const Twine &Name, VPRecipeBase *Recipe=nullptr)
Create a new VPBasicBlock with Name and containing Recipe if present.
Definition VPlan.h:4884
LLVM_ABI_FOR_TEST VPIRBasicBlock * createVPIRBasicBlock(BasicBlock *IRBB)
Create a VPIRBasicBlock from IRBB containing VPIRInstructions for all instructions in IRBB,...
Definition VPlan.cpp:1257
void removeVF(ElementCount VF)
Remove VF from the plan.
Definition VPlan.h:4758
VPIRValue * getTrue()
Return a VPIRValue wrapping i1 true.
Definition VPlan.h:4826
VPRegionBlock * createLoopRegion(const std::string &Name="", VPBlockBase *Entry=nullptr, VPBlockBase *Exiting=nullptr)
Create a new loop region with Name and entry and exiting blocks set to Entry and Exiting respectively...
Definition VPlan.h:4894
LLVM_DUMP_METHOD void dump() const
Dump the plan to stderr (for debugging).
Definition VPlan.cpp:1145
bool hasScalarVFOnly() const
Definition VPlan.h:4774
VPBasicBlock * getScalarPreheader() const
Return the VPBasicBlock for the preheader of the scalar loop.
Definition VPlan.h:4685
void execute(VPTransformState *State)
Generate the IR code for this VPlan.
Definition VPlan.cpp:928
LLVM_ABI_FOR_TEST void print(raw_ostream &O) const
Print this VPlan to O.
Definition VPlan.cpp:1098
void addVF(ElementCount VF)
Definition VPlan.h:4749
VPIRBasicBlock * getScalarHeader() const
Return the VPIRBasicBlock wrapping the header of the scalar loop.
Definition VPlan.h:4690
void printLiveIns(raw_ostream &O) const
Print the live-ins of this VPlan to O.
Definition VPlan.cpp:1054
VPBasicBlock * getVectorPreheader()
Returns the preheader of the vector loop region, if one exists, or null otherwise.
Definition VPlan.h:4651
void setUF(unsigned UF)
Definition VPlan.h:4789
bool hasScalarTail() const
Returns true if the scalar tail may execute after the vector loop.
Definition VPlan.h:4938
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:1186
VPlan(BasicBlock *ScalarHeaderBB)
Construct a VPlan with a new VPBasicBlock as entry, a VPIRBasicBlock wrapping ScalarHeaderBB and a tr...
Definition VPlan.h:4628
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:4840
LLVM Value Representation.
Definition Value.h:75
Increasing range of size_t indices.
Definition STLExtras.h:2507
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::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
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.
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
This namespace contains an enum with a value for every intrinsic/builtin function known by LLVM.
LLVM_ABI AttributeSet getFnAttributes(LLVMContext &C, ID id)
Return the function attributes for an intrinsic.
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
static auto castToVPIRMetadata(RecipeBasePtrTy R) -> DstTy
Definition VPlan.h:4170
This is an optimization pass for GlobalISel generic memory operations.
Definition Types.h:26
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:316
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
@ Offset
Definition DWP.cpp:532
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:831
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:1765
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:1739
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:841
ReductionStyle getReductionStyle(bool InLoop, bool Ordered, unsigned ScaleFactor)
Definition VPlan.h:2654
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:2554
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
LLVM_ABI void getMetadataToPropagate(Instruction *Inst, SmallVectorImpl< std::pair< unsigned, MDNode * > > &Metadata)
Add metadata from Inst to Metadata, if it can be preserved after vectorization.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
auto cast_or_null(const Y &Val)
Definition Casting.h:714
Align getLoadStoreAlignment(const Value *I)
A helper function that returns the alignment of load or store instruction.
MemoryEffectsBase< IRMemLocation > MemoryEffects
Summary of how a function affects memory in the program.
Definition ModRef.h:336
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:1746
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:207
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.
@ Sub
Subtraction of integers.
@ Add
Sum of integers.
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:2012
DWARFExpression::Operation Op
raw_ostream & operator<<(raw_ostream &OS, const APFixedPoint &FX)
constexpr unsigned BitWidth
auto count_if(R &&Range, UnaryPredicate P)
Wrapper function around std::count_if to count the number of times an element satisfying a given pred...
Definition STLExtras.h:2019
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:1772
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1947
std::variant< RdxOrdered, RdxInLoop, RdxUnordered > ReductionStyle
Definition VPlan.h:2652
std::unique_ptr< VPlan > VPlanPtr
Definition VPlan.h:78
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:872
#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
Support casting from VPRecipeBase -> VPIRMetadata, by down-casting to the recipe types implementing V...
Definition VPlan.h:4201
static RetTy doCast(SrcTy R)
doCast is used by cast<>.
Definition VPlan.h:4215
static RetTy doCastIfPossible(SrcTy R)
doCastIfPossible is used by dyn_cast<>.
Definition VPlan.h:4220
static bool isPossible(SrcTy R)
Definition VPlan.h:4202
Support casting from VPRecipeBase -> VPPhiAccessors, by down-casting to the recipe types implementing...
Definition VPlan.h:4132
static VPPhiAccessors * doCastIfPossible(SrcTy f)
doCastIfPossible is used by dyn_cast<>.
Definition VPlan.h:4153
CastInfo< VPPhiAccessors, SrcTy > Self
Definition VPlan.h:4134
static VPPhiAccessors * doCast(SrcTy R)
doCast is used by cast<>.
Definition VPlan.h:4137
This struct provides a method for customizing the way a cast is performed.
Definition Casting.h:476
static bool isPossible(const VPRecipeBase *f)
Definition VPlan.h:4124
This struct provides a way to check if a given cast is possible.
Definition Casting.h:253
static bool isPossible(const SrcTy &f)
Definition Casting.h:254
This reduction is in-loop.
Definition VPlan.h:2646
Possible variants of a reduction.
Definition VPlan.h:2644
This reduction is unordered with the partial result scaled down by some factor.
Definition VPlan.h:2649
unsigned VFScaleFactor
Definition VPlan.h:2650
A MapVector that performs no allocations if smaller than a certain size.
Definition MapVector.h:276
An overlay on VPIRValue for VPValues that wrap a ConstantInt.
Definition VPlanValue.h:201
Struct to hold various analysis needed for cost computations.
void execute(VPTransformState &State) override
Generate the phi nodes.
VPFirstOrderRecurrencePHIRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:2615
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:2627
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:2606
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:692
PHINode & getIRPhi()
Definition VPlan.h:1732
VPIRPhi(PHINode &PN)
Definition VPlan.h:1720
static bool classof(const VPRecipeBase *U)
Definition VPlan.h:1722
static bool classof(const VPUser *U)
Definition VPlan.h:1727
const VPRecipeBase * getAsRecipe() const override
Return a VPRecipeBase* to the current object.
Definition VPlan.h:1743
A VPValue representing a live-in from the input IR or a constant.
Definition VPlanValue.h:183
Type * getType() const
Returns the type of the underlying IR value.
Definition VPlan.cpp:141
static bool classof(const VPUser *U)
Definition VPlan.h:1619
VPPhi(ArrayRef< VPValue * > Operands, const VPIRFlags &Flags, DebugLoc DL, const Twine &Name="")
Definition VPlan.h:1615
VPPhi * clone() override
Clone the current recipe.
Definition VPlan.h:1634
const VPRecipeBase * getAsRecipe() const override
Return a VPRecipeBase* to the current object.
Definition VPlan.h:1649
static bool classof(const VPSingleDefRecipe *SDR)
Definition VPlan.h:1629
static bool classof(const VPValue *V)
Definition VPlan.h:1624
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:1113
static bool classof(const VPRecipeBase *R)
Definition VPlan.h:1086
InstructionCost getCostForRecipeWithOpcode(unsigned Opcode, ElementCount VF, VPCostContext &Ctx) const
Compute the cost for this recipe for VF, using Opcode and Ctx.
VPRecipeWithIRFlags(const unsigned char SC, ArrayRef< VPValue * > Operands, const VPIRFlags &Flags, DebugLoc DL=DebugLoc::getUnknown())
Definition VPlan.h:1081
static bool classof(const VPValue *V)
Definition VPlan.h:1106
void execute(VPTransformState &State) override=0
The method which generates the output IR instructions that correspond to this VPRecipe,...
VPRecipeWithIRFlags * clone() override=0
Clone the current recipe.
static bool classof(const VPUser *U)
Definition VPlan.h:1101
A symbolic live-in VPValue, used for values like vector trip count, VF, and VFxUF.
Definition VPlanValue.h:223
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:3628
LLVM_ABI_FOR_TEST void execute(VPTransformState &State) override
Generate the wide load or gather.
LLVM_ABI_FOR_TEST void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
LLVM_ABI_FOR_TEST InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPWidenLoadEVLRecipe.
VPValue * getEVL() const
Return the EVL operand.
Definition VPlan.h:3641
VPWidenLoadEVLRecipe(VPWidenLoadRecipe &L, VPValue *Addr, VPValue &EVL, VPValue *Mask)
Definition VPlan.h:3629
bool usesFirstLaneOnly(const VPValue *Op) const override
Returns true if the recipe only uses the first lane of operand Op.
Definition VPlan.h:3651
A recipe for widening load operations, using the address to load from and an optional mask.
Definition VPlan.h:3586
bool usesFirstLaneOnly(const VPValue *Op) const override
Returns true if the recipe only uses the first lane of operand Op.
Definition VPlan.h:3608
void execute(VPTransformState &State) override
Generate a wide load or gather.
VPWidenLoadRecipe(LoadInst &Load, VPValue *Addr, VPValue *Mask, bool Consecutive, bool Reverse, const VPIRMetadata &Metadata, DebugLoc DL)
Definition VPlan.h:3587
VPWidenLoadRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:3596
VP_CLASSOF_IMPL(VPRecipeBase::VPWidenLoadSC)
A recipe for widening store operations with vector-predication intrinsics, using the value to store,...
Definition VPlan.h:3713
VPValue * getStoredValue() const
Return the address accessed by this recipe.
Definition VPlan.h:3725
LLVM_ABI_FOR_TEST void execute(VPTransformState &State) override
Generate the wide store or scatter.
VPWidenStoreEVLRecipe(VPWidenStoreRecipe &S, VPValue *Addr, VPValue *StoredVal, VPValue &EVL, VPValue *Mask)
Definition VPlan.h:3714
bool usesFirstLaneOnly(const VPValue *Op) const override
Returns true if the recipe only uses the first lane of operand Op.
Definition VPlan.h:3738
LLVM_ABI_FOR_TEST void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
LLVM_ABI_FOR_TEST InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPWidenStoreEVLRecipe.
VPValue * getEVL() const
Return the EVL operand.
Definition VPlan.h:3728
A recipe for widening store operations, using the stored value, the address to store to and an option...
Definition VPlan.h:3669
VP_CLASSOF_IMPL(VPRecipeBase::VPWidenStoreSC)
VPValue * getStoredValue() const
Return the value stored by this recipe.
Definition VPlan.h:3688
VPWidenStoreRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:3679
bool usesFirstLaneOnly(const VPValue *Op) const override
Returns true if the recipe only uses the first lane of operand Op.
Definition VPlan.h:3694
VPWidenStoreRecipe(StoreInst &Store, VPValue *Addr, VPValue *StoredVal, VPValue *Mask, bool Consecutive, bool Reverse, const VPIRMetadata &Metadata, DebugLoc DL)
Definition VPlan.h:3670