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