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