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"
43#include <cassert>
44#include <cstddef>
45#include <functional>
46#include <string>
47#include <utility>
48#include <variant>
49
50namespace llvm {
51
52class BasicBlock;
53class DominatorTree;
55class IRBuilderBase;
56struct VPTransformState;
57class raw_ostream;
59class SCEV;
60class SCEVPredicate;
61class Type;
62class VPBasicBlock;
63class VPBuilder;
64class VPDominatorTree;
65class VPRegionBlock;
66class VPlan;
67class VPLane;
69class Value;
71
72struct VPCostContext;
73
74using VPlanPtr = std::unique_ptr<VPlan>;
75
76/// \enum UncountableExitStyle
77/// Different methods of handling early exits.
78///
81 /// No side effects to worry about, so we can process any uncountable exits
82 /// in the loop and branch either to the middle block if the trip count was
83 /// reached, or an early exitblock to determine which exit was taken.
85 /// All memory operations other than the load(s) required to determine whether
86 /// an uncountable exit occurre will be masked based on that condition. If an
87 /// uncountable exit is taken, then all lanes before the exiting lane will
88 /// complete, leaving just the final lane to execute in the scalar tail.
90};
91
92/// VPBlockBase is the building block of the Hierarchical Control-Flow Graph.
93/// A VPBlockBase can be either a VPBasicBlock or a VPRegionBlock.
95 friend class VPBlockUtils;
96
97protected:
98 /// An enumeration for keeping track of the concrete subclass of VPBlockBase
99 /// that are actually instantiated. Values of this enumeration are kept in the
100 /// SubclassID field of the VPBlockBase objects. They are used for concrete
101 /// type identification.
102 using VPBlockTy = enum : unsigned char {
103 VPRegionBlockSC,
104 VPBasicBlockSC,
105 VPIRBasicBlockSC
106 };
107
108private:
109 /// An optional name for the block.
110 std::string Name;
111
112 /// The immediate VPRegionBlock which this VPBlockBase belongs to, or null if
113 /// it is a topmost VPBlockBase.
114 VPRegionBlock *Parent = nullptr;
115
116 /// List of predecessor blocks.
118
119 /// List of successor blocks.
121
122 /// VPlan containing the block. Can only be set on the entry block of the
123 /// plan.
124 VPlan *Plan = nullptr;
125
126 /// Subclass identifier (for isa/dyn_cast).
127 const VPBlockTy SubclassID;
128
129 /// Unique number, used as node number in the dominator tree.
130 unsigned Number;
131
132 /// Add \p Successor as the last successor to this block.
133 void appendSuccessor(VPBlockBase *Successor) {
134 assert(Successor && "Cannot add nullptr successor!");
135 Successors.push_back(Successor);
136 }
137
138 /// Add \p Predecessor as the last predecessor to this block.
139 void appendPredecessor(VPBlockBase *Predecessor) {
140 assert(Predecessor && "Cannot add nullptr predecessor!");
141 Predecessors.push_back(Predecessor);
142 }
143
144 /// Remove \p Predecessor from the predecessors of this block.
145 void removePredecessor(VPBlockBase *Predecessor) {
146 auto Pos = find(Predecessors, Predecessor);
147 assert(Pos && "Predecessor does not exist");
148 Predecessors.erase(Pos);
149 }
150
151 /// Remove \p Successor from the successors of this block.
152 void removeSuccessor(VPBlockBase *Successor) {
153 auto Pos = find(Successors, Successor);
154 assert(Pos && "Successor does not exist");
155 Successors.erase(Pos);
156 }
157
158 /// This function replaces one predecessor with another, useful when
159 /// trying to replace an old block in the CFG with a new one.
160 void replacePredecessor(VPBlockBase *Old, VPBlockBase *New) {
161 auto I = find(Predecessors, Old);
162 assert(I != Predecessors.end());
163 assert(Old->getParent() == New->getParent() &&
164 "replaced predecessor must have the same parent");
165 *I = New;
166 }
167
168 /// This function replaces one successor with another, useful when
169 /// trying to replace an old block in the CFG with a new one.
170 void replaceSuccessor(VPBlockBase *Old, VPBlockBase *New) {
171 auto I = find(Successors, Old);
172 assert(I != Successors.end());
173 assert(Old->getParent() == New->getParent() &&
174 "replaced successor must have the same parent");
175 *I = New;
176 }
177
178public:
180
181 virtual ~VPBlockBase() = default;
182
183 const std::string &getName() const { return Name; }
184
185 void setName(const Twine &newName) { Name = newName.str(); }
186
187 /// \return an ID for the concrete type of this object.
188 /// This is used to implement the classof checks. This should not be used
189 /// for any other purpose, as the values may change as LLVM evolves.
190 unsigned getVPBlockID() const { return SubclassID; }
191
192 VPRegionBlock *getParent() { return Parent; }
193 const VPRegionBlock *getParent() const { return Parent; }
194
195 /// \return A pointer to the plan containing the current block.
196 VPlan *getPlan();
197 const VPlan *getPlan() const;
198
199 /// Sets the pointer of the plan containing the block. The block must be the
200 /// entry block into the VPlan.
201 void setPlan(VPlan *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 LLVM_ABI_FOR_TEST 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,
613 ArrayRef<VPValue *> Operands);
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).
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 has its required flags set.
1111 LLVM_ABI_FOR_TEST bool hasRequiredFlagsForOpcode(unsigned Opcode) const;
1112#endif
1113
1114#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1115 void printFlags(raw_ostream &O) const;
1116#endif
1117};
1119
1120static_assert(sizeof(VPIRFlags) <= 3, "VPIRFlags should not grow");
1121
1122/// A pure-virtual common base class for recipes defining a single VPValue and
1123/// using IR flags.
1126 const VPIRFlags &Flags,
1128 : VPSingleDefRecipe(SC, Operands, DL), VPIRFlags(Flags) {}
1129
1131 Type *ResultTy, const VPIRFlags &Flags,
1133 : VPSingleDefRecipe(SC, Operands, ResultTy, /*UV=*/nullptr, DL),
1134 VPIRFlags(Flags) {}
1135
1136 static inline bool classof(const VPRecipeBase *R) {
1137 return R->getVPRecipeID() == VPRecipeBase::VPBlendSC ||
1138 R->getVPRecipeID() == VPRecipeBase::VPInstructionSC ||
1139 R->getVPRecipeID() == VPRecipeBase::VPWidenSC ||
1140 R->getVPRecipeID() == VPRecipeBase::VPWidenGEPSC ||
1141 R->getVPRecipeID() == VPRecipeBase::VPWidenCallSC ||
1142 R->getVPRecipeID() == VPRecipeBase::VPWidenCastSC ||
1143 R->getVPRecipeID() == VPRecipeBase::VPWidenIntrinsicSC ||
1144 R->getVPRecipeID() == VPRecipeBase::VPWidenMemIntrinsicSC ||
1145 R->getVPRecipeID() == VPRecipeBase::VPReductionSC ||
1146 R->getVPRecipeID() == VPRecipeBase::VPReductionEVLSC ||
1147 R->getVPRecipeID() == VPRecipeBase::VPReplicateSC ||
1148 R->getVPRecipeID() == VPRecipeBase::VPVectorEndPointerSC ||
1149 R->getVPRecipeID() == VPRecipeBase::VPVectorPointerSC ||
1150 R->getVPRecipeID() == VPRecipeBase::VPWidenCanonicalIVSC ||
1151 R->getVPRecipeID() == VPRecipeBase::VPDerivedIVSC;
1152 }
1153
1154 static inline bool classof(const VPUser *U) {
1155 auto *R = dyn_cast<VPRecipeBase>(U);
1156 return R && classof(R);
1157 }
1158
1159 static inline bool classof(const VPValue *V) {
1160 auto *R = V->getDefiningRecipe();
1161 return R && classof(R);
1162 }
1163
1165
1166 static inline bool classof(const VPSingleDefRecipe *R) {
1167 return classof(static_cast<const VPRecipeBase *>(R));
1168 }
1169
1170 void execute(VPTransformState &State) override = 0;
1171
1172 /// Compute the cost for this recipe for \p VF, using \p Opcode and \p Ctx.
1174 VPCostContext &Ctx) const;
1175};
1176
1177/// Helper to manage IR metadata for recipes. It filters out metadata that
1178/// cannot be propagated.
1181
1182public:
1183 VPIRMetadata() = default;
1184
1185 /// Adds metatadata that can be preserved from the original instruction
1186 /// \p I.
1188
1189 /// Copy constructor for cloning.
1191
1193
1194 /// Add all metadata to \p I.
1195 void applyMetadata(Instruction &I) const;
1196
1197 /// Set metadata with kind \p Kind to \p Node. If metadata with \p Kind
1198 /// already exists, it will be replaced. Otherwise, it will be added.
1199 void setMetadata(unsigned Kind, MDNode *Node) {
1200 auto It =
1201 llvm::find_if(Metadata, [Kind](const std::pair<unsigned, MDNode *> &P) {
1202 return P.first == Kind;
1203 });
1204 if (It != Metadata.end())
1205 It->second = Node;
1206 else
1207 Metadata.emplace_back(Kind, Node);
1208 }
1209
1210 /// Intersect this VPIRMetadata object with \p MD, keeping only metadata
1211 /// nodes that are common to both.
1212 void intersect(const VPIRMetadata &MD);
1213
1214 /// Get metadata of kind \p Kind. Returns nullptr if not found.
1215 MDNode *getMetadata(unsigned Kind) const {
1216 auto It =
1217 find_if(Metadata, [Kind](const auto &P) { return P.first == Kind; });
1218 return It != Metadata.end() ? It->second : nullptr;
1219 }
1220
1221#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1222 /// Print metadata with node IDs.
1223 void print(raw_ostream &O, VPSlotTracker &SlotTracker) const;
1224#endif
1225};
1226
1227/// This is a concrete Recipe that models a single VPlan-level instruction.
1228/// While as any Recipe it may generate a sequence of IR instructions when
1229/// executed, these instructions would always form a single-def expression as
1230/// the VPInstruction is also a single def-use vertex. Most VPInstruction
1231/// opcodes can take an optional mask. Masks may be assigned during
1232/// predication.
1234 public VPIRMetadata {
1235public:
1236 /// VPlan opcodes, extending LLVM IR with idiomatics instructions.
1237 enum {
1239 Instruction::OtherOpsEnd + 1, // Combines the incoming and previous
1240 // values of a first-order recurrence.
1242 // Creates a mask where each lane is active (true) whilst the current
1243 // counter (first operand + index) is less than the second operand. i.e.
1244 // mask[i] = icmpt ult (op0 + i), op1
1245 // The size of the mask returned is VF * Multiplier (UF, third op).
1248 // Represents the incoming loop-invariant alias-mask. All memory accesses
1249 // in the loop must stay within the active lanes.
1252 // Increment the canonical IV separately for each unrolled part.
1254 // Abstract instruction that compares two values and branches. This is
1255 // lowered to ICmp + BranchOnCond during VPlan to VPlan transformation.
1258 // Branch with 2 boolean condition operands and 3 successors. If condition
1259 // 0 is true, branches to successor 0; if condition 1 is true, branches to
1260 // successor 1; otherwise branches to successor 2. Expanded after region
1261 // dissolution into: (1) an OR of the two conditions branching to
1262 // middle.split or successor 2, and (2) middle.split branching to successor
1263 // 0 or successor 1 based on condition 0.
1266 /// Given operands of (the same) struct type, creates a struct of fixed-
1267 /// width vectors each containing a struct field of all operands. The
1268 /// number of operands matches the element count of every vector.
1270 /// Creates a fixed-width vector containing all operands. The number of
1271 /// operands matches the vector element count.
1273 /// Extracts all lanes from its (non-scalable) vector operand. This is an
1274 /// abstract VPInstruction whose single defined VPValue represents VF
1275 /// scalars extracted from a vector, to be replaced by VF ExtractElement
1276 /// VPInstructions.
1278 /// Reduce the operands to the final reduction result using the operation
1279 /// specified via the operation's VPIRFlags.
1281 // Extracts the last part of its operand. Removed during unrolling.
1283 // Extracts the last lane of its vector operand, per part.
1285 // Extracts the second-to-last lane from its operand or the second-to-last
1286 // part if it is scalar. In the latter case, the recipe will be removed
1287 // during unrolling.
1289 LogicalAnd, // Non-poison propagating logical And.
1290 LogicalOr, // Non-poison propagating logical Or.
1291 NumActiveLanes, // Counts the number of active lanes in a mask.
1292 // Add an offset in bytes (second operand) to a base pointer (first
1293 // operand). Only generates scalar values (either for the first lane only or
1294 // for all lanes, depending on its uses).
1296 // Add a vector offset in bytes (second operand) to a scalar base pointer
1297 // (first operand).
1299 // Returns a scalar boolean value, which is true if any lane of its
1300 // (boolean) vector operands is true. It produces the reduced value across
1301 // all unrolled iterations. Unrolling will add all copies of its original
1302 // operand as additional operands. AnyOf is poison-safe as all operands
1303 // will be frozen.
1305 // Calculates the first active lane index of the vector predicate operands.
1306 // It produces the lane index across all unrolled iterations. Unrolling will
1307 // add all copies of its original operand as additional operands.
1308 // Implemented with @llvm.experimental.cttz.elts, but returns the expected
1309 // result even with operands that are all zeroes.
1311 // Calculates the last active lane index of the vector predicate operands.
1312 // The predicates must be prefix-masks (all 1s before all 0s). Used when
1313 // tail-folding to extract the correct live-out value from the last active
1314 // iteration. It produces the lane index across all unrolled iterations.
1315 // Unrolling will add all copies of its original operand as additional
1316 // operands.
1318 // Returns a reversed vector for the operand.
1320 /// Start vector for reductions with 3 operands: the original start value,
1321 /// the identity value for the reduction and an integer indicating the
1322 /// scaling factor.
1324 /// Extracts a single lane (first operand) from a set of vector operands.
1325 /// The lane specifies an index into a vector formed by combining all vector
1326 /// operands (all operands after the first one).
1328 /// Explicit user for the resume phi of the canonical induction in the main
1329 /// VPlan, used by the epilogue vector loop.
1331 /// Extracts the last active lane from a set of vectors. The first operand
1332 /// is the default value if no lanes in the masks are active. Conceptually,
1333 /// this concatenates all data vectors (odd operands), concatenates all
1334 /// masks (even operands -- ignoring the default value), and returns the
1335 /// last active value from the combined data vector using the combined mask.
1337 /// Compute the exiting value of a wide induction after vectorization, that
1338 /// is the value of the last lane of the induction increment (i.e. its
1339 /// backedge value). Has the wide induction recipe as operand.
1342
1343 // The opcodes below are used for VPInstructionWithType.
1344 // NOTE: VPInstructionWithType classes are also used for:
1345 // 1. All CastInst variants - see createVPInstructionsForVPBB, and other
1346 // cases where createScalarCast, createScalarZExtOrTrunc and
1347 // createScalarSExtOrTrunc are invoked.
1348 // 2. Scalar load instructions - see createVPInstructionsForVPBB.
1349
1350 /// Scale the first operand (vector step) by the second operand
1351 /// (scalar-step). Casts both operands to the result type if needed.
1353 // Creates a step vector starting from 0 to VF with a step of 1.
1355 /// Calls a scalar intrinsic. The intrinsic ID is the last operand.
1357
1359 };
1360
1361 /// Returns true if this recipe produces scalar values for all VF lanes.
1362 bool doesGeneratePerAllLanes() const;
1363
1364 /// Return the number of operands determined by the opcode of the
1365 /// VPInstruction, excluding mask. Returns -1u if the number of operands
1366 /// cannot be determined directly by the opcode.
1367 unsigned getNumOperandsForOpcode() const;
1368
1369private:
1370 typedef unsigned char OpcodeTy;
1371 OpcodeTy Opcode;
1372
1373 /// An optional name that can be used for the generated IR instruction.
1374 std::string Name;
1375
1376 /// Returns true if we can generate a scalar for the first lane only if
1377 /// needed.
1378 bool canGenerateScalarForFirstLane() const;
1379
1380 /// Utility methods serving execute(): generates a single vector instance of
1381 /// the modeled instruction. \returns the generated value. . In some cases an
1382 /// existing value is returned rather than a generated one.
1383 Value *generate(VPTransformState &State);
1384
1385 /// Returns true if the VPInstruction does not need masking.
1386 bool alwaysUnmasked() const {
1387 if (Opcode == VPInstruction::MaskedCond)
1388 return false;
1389
1390 // For now only VPInstructions with underlying values use masks.
1391 // TODO: provide masks to VPInstructions w/o underlying values.
1392 if (!getUnderlyingValue())
1393 return true;
1394
1395 return Instruction::isCast(Opcode) || Opcode == Instruction::PHI ||
1396 Opcode == Instruction::GetElementPtr;
1397 }
1398
1399public:
1400 VPInstruction(unsigned Opcode, ArrayRef<VPValue *> Operands,
1401 const VPIRFlags &Flags = {}, const VPIRMetadata &MD = {},
1402 DebugLoc DL = DebugLoc::getUnknown(), const Twine &Name = "",
1403 Type *ResultTy = nullptr);
1404
1405 VP_CLASSOF_IMPL(VPRecipeBase::VPInstructionSC)
1406
1407 VPInstruction *clone() override {
1409 }
1410
1412 Type *ResultTy = nullptr) {
1413 auto *New = new VPInstruction(Opcode, NewOperands, *this, *this,
1414 getDebugLoc(), Name, ResultTy);
1415 if (getUnderlyingValue())
1416 New->setUnderlyingValue(getUnderlyingInstr());
1417 return New;
1418 }
1419
1420 unsigned getOpcode() const { return Opcode; }
1421
1422 /// Add \p Op as operand of this VPInstruction. Only supported for AnyOf,
1423 /// ComputeReductionResult, BuildVector, BuildStructVector, ExtractLane,
1424 /// ExtractLastActive, FirstActiveLane, LastActiveLane.
1425 void addOperand(VPValue *Op);
1426
1427 /// Generate the instruction.
1428 /// TODO: We currently execute only per-part unless a specific instance is
1429 /// provided.
1430 void execute(VPTransformState &State) override;
1431
1432 /// Return the cost of this VPInstruction.
1433 InstructionCost computeCost(ElementCount VF,
1434 VPCostContext &Ctx) const override;
1435
1436#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1437 /// Print the VPInstruction to dbgs() (for debugging).
1438 LLVM_DUMP_METHOD void dump() const;
1439#endif
1440
1441 bool hasResult() const {
1442 // CallInst may or may not have a result, depending on the called function.
1443 // Conservatively return calls have results for now.
1444 switch (getOpcode()) {
1445 case Instruction::Ret:
1446 case Instruction::UncondBr:
1447 case Instruction::CondBr:
1448 case Instruction::Store:
1449 case Instruction::Switch:
1450 case Instruction::IndirectBr:
1451 case Instruction::Resume:
1452 case Instruction::CatchRet:
1453 case Instruction::Unreachable:
1454 case Instruction::Fence:
1455 case Instruction::AtomicRMW:
1459 return false;
1460 default:
1461 return true;
1462 }
1463 }
1464
1465 /// Returns true if the VPInstruction has a mask operand.
1466 bool isMasked() const {
1467 unsigned NumOpsForOpcode = getNumOperandsForOpcode();
1468 // VPInstructions without a fixed number of operands cannot be masked.
1469 if (NumOpsForOpcode == -1u)
1470 return false;
1471 return NumOpsForOpcode + 1 == getNumOperands();
1472 }
1473
1474 /// Returns the number of operands, excluding the mask if the VPInstruction is
1475 /// masked.
1476 unsigned getNumOperandsWithoutMask() const {
1477 return getNumOperands() - isMasked();
1478 }
1479
1480 /// Add mask \p Mask to an unmasked VPInstruction, if it needs masking.
1481 void addMask(VPValue *Mask) {
1482 assert(!isMasked() && "recipe is already masked");
1483 if (alwaysUnmasked())
1484 return;
1485 assert(Mask->getScalarType()->isIntegerTy(1) &&
1486 "Mask must be an i1 (vector)");
1487 VPUser::addOperand(Mask);
1488 }
1489
1490 /// Returns the mask for the VPInstruction. Returns nullptr for unmasked
1491 /// VPInstructions.
1492 VPValue *getMask() const {
1493 return isMasked() ? getOperand(getNumOperands() - 1) : nullptr;
1494 }
1495
1496 /// Returns an iterator range over the operands excluding the mask operand
1497 /// if present.
1504
1505 /// Returns true if the underlying opcode may read from or write to memory.
1506 bool opcodeMayReadOrWriteFromMemory() const;
1507
1508 /// Returns true if the recipe only uses the first lane of operand \p Op.
1509 bool usesFirstLaneOnly(const VPValue *Op) const override;
1510
1511 /// Returns true if the recipe only uses the first part of operand \p Op.
1512 bool usesFirstPartOnly(const VPValue *Op) const override;
1513
1514 /// Returns true if this VPInstruction produces a scalar value from a vector,
1515 /// e.g. by performing a reduction or extracting a lane.
1516 bool isVectorToScalar() const;
1517
1518 /// Returns true if the recipe produces a single scalar value.
1519 bool isSingleScalar() const;
1520
1521 /// Returns the symbolic name assigned to the VPInstruction.
1522 StringRef getName() const { return Name; }
1523
1524 /// Set the symbolic name for the VPInstruction.
1525 void setName(StringRef NewName) { Name = NewName.str(); }
1526
1527protected:
1528#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1529 /// Print the VPInstruction to \p O.
1530 void printRecipe(raw_ostream &O, const Twine &Indent,
1531 VPSlotTracker &SlotTracker) const override;
1532#endif
1533};
1534
1535/// A specialization of VPInstruction augmenting it with a dedicated result
1536/// type, to be used when the opcode and operands of the VPInstruction don't
1537/// directly determine the result type. Note that there is no separate recipe ID
1538/// for VPInstructionWithType; it shares the same ID as VPInstruction and is
1539/// distinguished purely by the opcode.
1540/// TODO: Merge with VPInstruction, now that VPRecipeValue provides the type.
1542public:
1544 Type *ResultTy, const VPIRFlags &Flags = {},
1545 const VPIRMetadata &Metadata = {},
1547 const Twine &Name = "", Value *UV = nullptr)
1548 : VPInstruction(Opcode, Operands, Flags, Metadata, DL, Name, ResultTy) {
1550 }
1551
1552 static inline bool classof(const VPRecipeBase *R) {
1553 // VPInstructionWithType are VPInstructions with specific opcodes requiring
1554 // type information.
1555 auto *VPI = dyn_cast<VPInstruction>(R);
1556 if (!VPI)
1557 return false;
1558 unsigned Opc = VPI->getOpcode();
1560 return true;
1561 switch (Opc) {
1565 case Instruction::Load:
1566 return true;
1567 default:
1568 return false;
1569 }
1570 }
1571
1572 static inline bool classof(const VPUser *R) {
1574 }
1575
1576 VPInstruction *clone() override {
1577 auto *New =
1579 *this, *this, getDebugLoc(), getName());
1580 New->setUnderlyingValue(getUnderlyingValue());
1581 return New;
1582 }
1583
1584 void execute(VPTransformState &State) override;
1585
1586 /// Return the cost of this VPInstruction.
1588 VPCostContext &Ctx) const override;
1589
1590 Type *getResultType() const { return getScalarType(); }
1591
1592 /// Cast recipes always use scalars of their operand.
1593 bool usesScalars(const VPValue *Op) const override {
1595 return true;
1597 }
1598
1599protected:
1600#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1601 /// Print the recipe.
1602 void printRecipe(raw_ostream &O, const Twine &Indent,
1603 VPSlotTracker &SlotTracker) const override;
1604#endif
1605};
1606
1607/// Helper type to provide functions to access incoming values and blocks for
1608/// phi-like recipes.
1610protected:
1611 /// Return a VPRecipeBase* to the current object.
1612 virtual const VPRecipeBase *getAsRecipe() const = 0;
1613
1614public:
1615 virtual ~VPPhiAccessors() = default;
1616
1617 /// Returns the incoming VPValue with index \p Idx.
1618 VPValue *getIncomingValue(unsigned Idx) const {
1619 return getAsRecipe()->getOperand(Idx);
1620 }
1621
1622 /// Returns the incoming block with index \p Idx.
1623 const VPBasicBlock *getIncomingBlock(unsigned Idx) const;
1624
1625 /// Returns the incoming value for \p VPBB. \p VPBB must be an incoming block.
1626 VPValue *getIncomingValueForBlock(const VPBasicBlock *VPBB) const;
1627
1628 /// Sets the incoming value for \p VPBB to \p V. \p VPBB must be an incoming
1629 /// block.
1630 void setIncomingValueForBlock(const VPBasicBlock *VPBB, VPValue *V) const;
1631
1632 /// Returns the number of incoming values, also number of incoming blocks.
1633 virtual unsigned getNumIncoming() const {
1634 return getAsRecipe()->getNumOperands();
1635 }
1636
1637 /// Returns an interator range over the incoming values.
1639 return make_range(getAsRecipe()->op_begin(),
1640 getAsRecipe()->op_begin() + getNumIncoming());
1641 }
1642
1644 detail::index_iterator, std::function<const VPBasicBlock *(size_t)>>>;
1645
1646 /// Returns an iterator range over the incoming blocks.
1648 std::function<const VPBasicBlock *(size_t)> GetBlock = [this](size_t Idx) {
1649 return getIncomingBlock(Idx);
1650 };
1651 return map_range(index_range(0, getNumIncoming()), GetBlock);
1652 }
1653
1654 /// Returns an iterator range over pairs of incoming values and corresponding
1655 /// incoming blocks.
1661
1662 /// Removes the incoming value for \p IncomingBlock, which must be a
1663 /// predecessor.
1664 void removeIncomingValueFor(VPBlockBase *IncomingBlock) const;
1665
1666 /// Append \p IncomingV as an incoming value to the phi-like recipe.
1667 void addIncoming(VPValue *IncomingV) {
1668 auto *R = const_cast<VPRecipeBase *>(getAsRecipe());
1669 assert((R->getNumOperands() == 0 ||
1670 IncomingV->getScalarType() == R->getOperand(0)->getScalarType()) &&
1671 "all incoming values must have the same type");
1672 R->addOperand(IncomingV);
1673 }
1674
1675#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1676 /// Print the recipe.
1678#endif
1679};
1680
1683 const Twine &Name = "", Type *ResultTy = nullptr)
1684 : VPInstruction(Instruction::PHI, Operands, Flags, {}, DL, Name,
1685 ResultTy) {}
1686
1687 static inline bool classof(const VPUser *U) {
1688 auto *VPI = dyn_cast<VPInstruction>(U);
1689 return VPI && VPI->getOpcode() == Instruction::PHI;
1690 }
1691
1692 static inline bool classof(const VPValue *V) {
1693 auto *VPI = dyn_cast<VPInstruction>(V);
1694 return VPI && VPI->getOpcode() == Instruction::PHI;
1695 }
1696
1697 static inline bool classof(const VPSingleDefRecipe *SDR) {
1698 auto *VPI = dyn_cast<VPInstruction>(SDR);
1699 return VPI && VPI->getOpcode() == Instruction::PHI;
1700 }
1701
1702 VPPhi *clone() override {
1703 auto *PhiR = new VPPhi(operands(), *this, getDebugLoc(), getName());
1704 PhiR->setUnderlyingValue(getUnderlyingValue());
1705 return PhiR;
1706 }
1707
1708 void execute(VPTransformState &State) override;
1709
1710protected:
1711#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1712 /// Print the recipe.
1713 void printRecipe(raw_ostream &O, const Twine &Indent,
1714 VPSlotTracker &SlotTracker) const override;
1715#endif
1716
1717 const VPRecipeBase *getAsRecipe() const override { return this; }
1718};
1719
1720/// A recipe to wrap on original IR instruction not to be modified during
1721/// execution, except for PHIs. PHIs are modeled via the VPIRPhi subclass.
1722/// Expect PHIs, VPIRInstructions cannot have any operands.
1724 Instruction &I;
1725
1726protected:
1727 /// VPIRInstruction::create() should be used to create VPIRInstructions, as
1728 /// subclasses may need to be created, e.g. VPIRPhi.
1730 : VPRecipeBase(VPRecipeBase::VPIRInstructionSC, {}), I(I) {}
1731
1732public:
1733 ~VPIRInstruction() override = default;
1734
1735 /// Create a new VPIRPhi for \p \I, if it is a PHINode, otherwise create a
1736 /// VPIRInstruction.
1738
1739 VP_CLASSOF_IMPL(VPRecipeBase::VPIRInstructionSC)
1740
1742 auto *R = create(I);
1743 for (auto *Op : operands())
1744 R->addOperand(Op);
1745 return R;
1746 }
1747
1748 void execute(VPTransformState &State) override;
1749
1750 /// Return the cost of this VPIRInstruction.
1752 computeCost(ElementCount VF, VPCostContext &Ctx) const override;
1753
1754 Instruction &getInstruction() const { return I; }
1755
1756 bool usesScalars(const VPValue *Op) const override {
1758 "Op must be an operand of the recipe");
1759 return true;
1760 }
1761
1762 bool usesFirstPartOnly(const VPValue *Op) const override {
1764 "Op must be an operand of the recipe");
1765 return true;
1766 }
1767
1768 bool usesFirstLaneOnly(const VPValue *Op) const override {
1770 "Op must be an operand of the recipe");
1771 return true;
1772 }
1773
1774protected:
1775#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1776 /// Print the recipe.
1777 void printRecipe(raw_ostream &O, const Twine &Indent,
1778 VPSlotTracker &SlotTracker) const override;
1779#endif
1780};
1781
1782/// An overlay for VPIRInstructions wrapping PHI nodes enabling convenient use
1783/// cast/dyn_cast/isa and execute() implementation. A single VPValue operand is
1784/// allowed, and it is used to add a new incoming value for the single
1785/// predecessor VPBB.
1787 public VPPhiAccessors {
1789
1790 static inline bool classof(const VPRecipeBase *U) {
1791 auto *R = dyn_cast<VPIRInstruction>(U);
1792 return R && isa<PHINode>(R->getInstruction());
1793 }
1794
1795 static inline bool classof(const VPUser *U) {
1796 auto *R = dyn_cast<VPRecipeBase>(U);
1797 return R && classof(R);
1798 }
1799
1801
1802 void execute(VPTransformState &State) override;
1803
1804protected:
1805#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1806 /// Print the recipe.
1807 void printRecipe(raw_ostream &O, const Twine &Indent,
1808 VPSlotTracker &SlotTracker) const override;
1809#endif
1810
1811 const VPRecipeBase *getAsRecipe() const override { return this; }
1812};
1813
1814/// VPWidenRecipe is a recipe for producing a widened instruction using the
1815/// opcode and operands of the recipe. This recipe covers most of the
1816/// traditional vectorization cases where each recipe transforms into a
1817/// vectorized version of itself.
1819 public VPIRMetadata {
1820 unsigned Opcode;
1821
1822public:
1824 const VPIRFlags &Flags = {}, const VPIRMetadata &Metadata = {},
1825 DebugLoc DL = {})
1826 : VPWidenRecipe(I.getOpcode(), Operands, Flags, Metadata, DL) {
1827 setUnderlyingValue(&I);
1828 }
1829
1830 VPWidenRecipe(unsigned Opcode, ArrayRef<VPValue *> Operands,
1831 const VPIRFlags &Flags = {}, const VPIRMetadata &Metadata = {},
1832 DebugLoc DL = {})
1833 : VPRecipeWithIRFlags(VPRecipeBase::VPWidenSC, Operands,
1834 computeScalarTypeForInstruction(Opcode, Operands),
1835 Flags, DL),
1836 VPIRMetadata(Metadata), Opcode(Opcode) {}
1837
1838 ~VPWidenRecipe() override = default;
1839
1841
1843 if (auto *UV = getUnderlyingValue())
1844 return new VPWidenRecipe(*cast<Instruction>(UV), NewOperands, *this,
1845 *this, getDebugLoc());
1846 return new VPWidenRecipe(Opcode, NewOperands, *this, *this, getDebugLoc());
1847 }
1848
1849 VP_CLASSOF_IMPL(VPRecipeBase::VPWidenSC)
1850
1851 /// Produce a widened instruction using the opcode and operands of the recipe,
1852 /// processing State.VF elements.
1853 void execute(VPTransformState &State) override;
1854
1855 /// Return the cost of this VPWidenRecipe.
1856 InstructionCost computeCost(ElementCount VF,
1857 VPCostContext &Ctx) const override;
1858
1859 unsigned getOpcode() const { return Opcode; }
1860
1861protected:
1862#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1863 /// Print the recipe.
1864 void printRecipe(raw_ostream &O, const Twine &Indent,
1865 VPSlotTracker &SlotTracker) const override;
1866#endif
1867
1868 /// Returns true if the recipe only uses the first lane of operand \p Op.
1869 bool usesFirstLaneOnly(const VPValue *Op) const override {
1871 "Op must be an operand of the recipe");
1872 return Opcode == Instruction::Select && Op == getOperand(0) &&
1874 }
1875};
1876
1877/// VPWidenCastRecipe is a recipe to create vector cast instructions.
1878/// TODO: Merge with VPWidenRecipe now that type is associated to every
1879/// VPRecipeValue.
1881 /// Cast instruction opcode.
1882 Instruction::CastOps Opcode;
1883
1884public:
1886 CastInst *CI = nullptr, const VPIRFlags &Flags = {},
1887 const VPIRMetadata &Metadata = {},
1889 : VPRecipeWithIRFlags(VPRecipeBase::VPWidenCastSC, Op, ResultTy, Flags,
1890 DL),
1891 VPIRMetadata(Metadata), Opcode(Opcode) {
1892 assert(flagsValidForOpcode(Opcode) &&
1893 "Set flags not supported for the provided opcode");
1895 "Opcode requires specific flags to be set");
1897 }
1898
1899 ~VPWidenCastRecipe() override = default;
1900
1902 return new VPWidenCastRecipe(Opcode, getOperand(0), getScalarType(),
1904 *this, *this, getDebugLoc());
1905 }
1906
1907 VP_CLASSOF_IMPL(VPRecipeBase::VPWidenCastSC)
1908
1909 /// Produce widened copies of the cast.
1910 LLVM_ABI_FOR_TEST void execute(VPTransformState &State) override;
1911
1912 /// Return the cost of this VPWidenCastRecipe.
1914 computeCost(ElementCount VF, VPCostContext &Ctx) const override;
1915
1916 Instruction::CastOps getOpcode() const { return Opcode; }
1917
1918protected:
1919#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1920 /// Print the recipe.
1921 LLVM_ABI_FOR_TEST void printRecipe(raw_ostream &O, const Twine &Indent,
1922 VPSlotTracker &SlotTracker) const override;
1923#endif
1924};
1925
1926/// A recipe for widening vector intrinsics.
1928 /// ID of the vector intrinsic to widen.
1929 Intrinsic::ID VectorIntrinsicID;
1930
1931 /// True if the intrinsic may read from memory.
1932 bool MayReadFromMemory;
1933
1934 /// True if the intrinsic may read write to memory.
1935 bool MayWriteToMemory;
1936
1937 /// True if the intrinsic may have side-effects.
1938 bool MayHaveSideEffects;
1939
1940protected:
1942 ArrayRef<VPValue *> CallArguments, Type *Ty,
1943 const VPIRFlags &Flags = {},
1944 const VPIRMetadata &MD = {},
1946 : VPRecipeWithIRFlags(SC, CallArguments, Ty, Flags, DL), VPIRMetadata(MD),
1947 VectorIntrinsicID(VectorIntrinsicID) {
1948 LLVMContext &Ctx = Ty->getContext();
1949 AttributeSet Attrs = Intrinsic::getFnAttributes(Ctx, VectorIntrinsicID);
1950 MemoryEffects ME = Attrs.getMemoryEffects();
1951 MayReadFromMemory = !ME.onlyWritesMemory();
1952 MayWriteToMemory = !ME.onlyReadsMemory();
1953 MayHaveSideEffects = MayWriteToMemory ||
1954 !Attrs.hasAttribute(Attribute::NoUnwind) ||
1955 !Attrs.hasAttribute(Attribute::WillReturn);
1956 }
1957
1958 /// Helper function to produce the widened intrinsic call.
1959 CallInst *createVectorCall(VPTransformState &State);
1960
1961public:
1963 ArrayRef<VPValue *> CallArguments, Type *Ty,
1964 const VPIRFlags &Flags = {},
1965 const VPIRMetadata &MD = {},
1967 : VPRecipeWithIRFlags(VPRecipeBase::VPWidenIntrinsicSC, CallArguments, Ty,
1968 Flags, DL),
1969 VPIRMetadata(MD), VectorIntrinsicID(VectorIntrinsicID),
1970 MayReadFromMemory(CI.mayReadFromMemory()),
1971 MayWriteToMemory(CI.mayWriteToMemory()),
1972 MayHaveSideEffects(CI.mayHaveSideEffects()) {
1973 setUnderlyingValue(&CI);
1974 }
1975
1977 ArrayRef<VPValue *> CallArguments, Type *Ty,
1978 const VPIRFlags &Flags = {},
1979 const VPIRMetadata &Metadata = {},
1981 : VPWidenIntrinsicRecipe(VPRecipeBase::VPWidenIntrinsicSC,
1982 VectorIntrinsicID, CallArguments, Ty, Flags,
1983 Metadata, DL) {}
1984
1985 ~VPWidenIntrinsicRecipe() override = default;
1986
1988 if (Value *CI = getUnderlyingValue())
1989 return new VPWidenIntrinsicRecipe(*cast<CallInst>(CI), VectorIntrinsicID,
1990 operands(), getScalarType(), *this,
1991 *this, getDebugLoc());
1992 return new VPWidenIntrinsicRecipe(VectorIntrinsicID, operands(),
1993 getScalarType(), *this, *this,
1994 getDebugLoc());
1995 }
1996
1997 static inline bool classof(const VPRecipeBase *R) {
1998 return R->getVPRecipeID() == VPRecipeBase::VPWidenIntrinsicSC ||
1999 R->getVPRecipeID() == VPRecipeBase::VPWidenMemIntrinsicSC;
2000 }
2001
2002 static inline bool classof(const VPUser *U) {
2003 auto *R = dyn_cast<VPRecipeBase>(U);
2004 return R && classof(R);
2005 }
2006
2007 static inline bool classof(const VPValue *V) {
2008 auto *R = V->getDefiningRecipe();
2009 return R && classof(R);
2010 }
2011
2012 static inline bool classof(const VPSingleDefRecipe *R) {
2013 return classof(static_cast<const VPRecipeBase *>(R));
2014 }
2015
2016 /// Produce a widened version of the vector intrinsic.
2017 LLVM_ABI_FOR_TEST void execute(VPTransformState &State) override;
2018
2019 /// Compute the cost of a vector intrinsic with \p ID and \p Operands.
2022 const VPRecipeWithIRFlags &R,
2023 ElementCount VF, VPCostContext &Ctx);
2024
2025 /// Return the cost of this vector intrinsic.
2027 computeCost(ElementCount VF, VPCostContext &Ctx) const override;
2028
2029 /// Return the ID of the intrinsic.
2030 Intrinsic::ID getVectorIntrinsicID() const { return VectorIntrinsicID; }
2031
2032 /// Return to name of the intrinsic as string.
2034
2035 /// Returns true if the intrinsic may read from memory.
2036 bool mayReadFromMemory() const { return MayReadFromMemory; }
2037
2038 /// Returns true if the intrinsic may write to memory.
2039 bool mayWriteToMemory() const { return MayWriteToMemory; }
2040
2041 /// Returns true if the intrinsic may have side-effects.
2042 bool mayHaveSideEffects() const { return MayHaveSideEffects; }
2043
2044 LLVM_ABI_FOR_TEST bool usesFirstLaneOnly(const VPValue *Op) const override;
2045
2046protected:
2047#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2048 /// Print the recipe.
2049 LLVM_ABI_FOR_TEST void printRecipe(raw_ostream &O, const Twine &Indent,
2050 VPSlotTracker &SlotTracker) const override;
2051#endif
2052};
2053
2054/// A recipe for widening vector memory intrinsics.
2056 /// Alignment information for this memory access.
2057 Align Alignment;
2058
2059public:
2060 // TODO: support StoreInst for strided store
2062 ArrayRef<VPValue *> CallArguments, Type *Ty,
2063 Align Alignment, const VPIRMetadata &MD = {},
2065 : VPWidenIntrinsicRecipe(VPRecipeBase::VPWidenMemIntrinsicSC,
2066 VectorIntrinsicID, CallArguments, Ty, {}, MD,
2067 DL),
2068 Alignment(Alignment) {
2069 assert(VectorIntrinsicID == Intrinsic::experimental_vp_strided_load &&
2070 "Unexpected intrinsic");
2071 }
2072
2073 ~VPWidenMemIntrinsicRecipe() override = default;
2074
2077 getScalarType(), Alignment, *this,
2078 getDebugLoc());
2079 }
2080
2081 VP_CLASSOF_IMPL(VPRecipeBase::VPWidenMemIntrinsicSC)
2082
2083 /// Produce a widened version of the vector memory intrinsic.
2084 void execute(VPTransformState &State) override;
2085
2086 /// Helper function for computing the cost of vector memory intrinsic.
2088 bool IsMasked, Align Alignment,
2089 VPCostContext &Ctx);
2090
2091 /// Return the cost of this vector memory intrinsic.
2093 VPCostContext &Ctx) const override;
2094};
2095
2096/// A recipe for widening Call instructions using library calls.
2098 public VPIRMetadata {
2099 /// Variant stores a pointer to the chosen function. There is a 1:1 mapping
2100 /// between a given VF and the chosen vectorized variant, so there will be a
2101 /// different VPlan for each VF with a valid variant.
2102 Function *Variant;
2103
2104public:
2106 ArrayRef<VPValue *> CallArguments,
2107 const VPIRFlags &Flags = {},
2108 const VPIRMetadata &Metadata = {}, DebugLoc DL = {})
2109 : VPRecipeWithIRFlags(VPRecipeBase::VPWidenCallSC, CallArguments,
2110 toScalarizedTy(Variant->getReturnType()), Flags,
2111 DL),
2112 VPIRMetadata(Metadata), Variant(Variant) {
2113 setUnderlyingValue(UV);
2114 assert(
2115 isa<Function>(getOperand(getNumOperands() - 1)->getLiveInIRValue()) &&
2116 "last operand must be the called function");
2117 assert(cast<Function>(CallArguments.back()->getLiveInIRValue())
2118 ->getReturnType() == getScalarType() &&
2119 "Scalar type must match return type of called scalar function");
2120 }
2121
2122 ~VPWidenCallRecipe() override = default;
2123
2125 return new VPWidenCallRecipe(getUnderlyingValue(), Variant, operands(),
2126 *this, *this, getDebugLoc());
2127 }
2128
2129 VP_CLASSOF_IMPL(VPRecipeBase::VPWidenCallSC)
2130
2131 /// Produce a widened version of the call instruction.
2132 void execute(VPTransformState &State) override;
2133
2134 /// Return the cost of this VPWidenCallRecipe.
2135 InstructionCost computeCost(ElementCount VF,
2136 VPCostContext &Ctx) const override;
2137
2138 /// Return the cost of widening a call using the vector function \p Variant.
2139 static InstructionCost computeCallCost(Function *Variant, VPCostContext &Ctx);
2140
2144
2147
2148 /// Returns true if the recipe only uses the first lane of operand \p Op.
2149 bool usesFirstLaneOnly(const VPValue *Op) const override;
2150
2151protected:
2152#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2153 /// Print the recipe.
2154 void printRecipe(raw_ostream &O, const Twine &Indent,
2155 VPSlotTracker &SlotTracker) const override;
2156#endif
2157};
2158
2159/// A recipe representing a sequence of load -> update -> store as part of
2160/// a histogram operation. This means there may be aliasing between vector
2161/// lanes, which is handled by the llvm.experimental.vector.histogram family
2162/// of intrinsics. The only update operations currently supported are
2163/// 'add' and 'sub' where the other term is loop-invariant.
2165 /// Opcode of the update operation, currently either add or sub.
2166 unsigned Opcode;
2167
2168public:
2169 VPHistogramRecipe(unsigned Opcode, ArrayRef<VPValue *> Operands,
2170 const VPIRMetadata &Metadata = {},
2172 : VPRecipeBase(VPRecipeBase::VPHistogramSC, Operands, DL),
2173 VPIRMetadata(Metadata), Opcode(Opcode) {}
2174
2175 ~VPHistogramRecipe() override = default;
2176
2178 return new VPHistogramRecipe(Opcode, operands(), *this, getDebugLoc());
2179 }
2180
2181 VP_CLASSOF_IMPL(VPRecipeBase::VPHistogramSC);
2182
2183 /// Produce a vectorized histogram operation.
2184 void execute(VPTransformState &State) override;
2185
2186 /// Return the cost of this VPHistogramRecipe.
2188 VPCostContext &Ctx) const override;
2189
2190 unsigned getOpcode() const { return Opcode; }
2191
2192 /// Return the mask operand if one was provided, or a null pointer if all
2193 /// lanes should be executed unconditionally.
2194 VPValue *getMask() const {
2195 return getNumOperands() == 3 ? getOperand(2) : nullptr;
2196 }
2197
2198protected:
2199#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2200 /// Print the recipe
2201 void printRecipe(raw_ostream &O, const Twine &Indent,
2202 VPSlotTracker &SlotTracker) const override;
2203#endif
2204};
2205
2206/// A recipe for handling GEP instructions.
2208 Type *SourceElementTy;
2209
2210public:
2211 VPWidenGEPRecipe(Type *SourceElementTy, ArrayRef<VPValue *> Operands,
2212 const VPIRFlags &Flags = {},
2214 GetElementPtrInst *UV = nullptr)
2215 : VPRecipeWithIRFlags(VPRecipeBase::VPWidenGEPSC, Operands,
2216 Operands[0]->getScalarType(), Flags, DL),
2217 SourceElementTy(SourceElementTy) {
2218 if (UV) {
2219 setUnderlyingValue(UV);
2222 assert(Metadata.empty() && "unexpected metadata on GEP");
2223 }
2224 }
2225
2226 ~VPWidenGEPRecipe() override = default;
2227
2233
2234 VP_CLASSOF_IMPL(VPRecipeBase::VPWidenGEPSC)
2235
2236 /// This recipe generates a GEP instruction.
2237 unsigned getOpcode() const { return Instruction::GetElementPtr; }
2238
2239 /// Generate the gep nodes.
2240 void execute(VPTransformState &State) override;
2241
2242 Type *getSourceElementType() const { return SourceElementTy; }
2243
2244 /// Return the cost of this VPWidenGEPRecipe.
2246 VPCostContext &Ctx) const override {
2247 // TODO: Compute accurate cost after retiring the legacy cost model.
2248 return 0;
2249 }
2250
2251 /// Returns true if the recipe only uses the first lane of operand \p Op.
2252 bool usesFirstLaneOnly(const VPValue *Op) const override;
2253
2254protected:
2255#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2256 /// Print the recipe.
2257 void printRecipe(raw_ostream &O, const Twine &Indent,
2258 VPSlotTracker &SlotTracker) const override;
2259#endif
2260};
2261
2262/// A recipe to compute a pointer to the last element of each part of a widened
2263/// memory access for widened memory accesses of SourceElementTy. Used for
2264/// VPWidenMemoryRecipes or VPInterleaveRecipes that are reversed. An extra
2265/// Offset operand is added by convertToConcreteRecipes when UF = 1, and by the
2266/// unroller otherwise.
2268 Type *SourceElementTy;
2269
2270 /// The constant stride of the pointer computed by this recipe, expressed in
2271 /// units of SourceElementTy.
2272 int64_t Stride;
2273
2274public:
2275 VPVectorEndPointerRecipe(VPValue *Ptr, VPValue *VF, Type *SourceElementTy,
2276 int64_t Stride, GEPNoWrapFlags GEPFlags, DebugLoc DL)
2277 : VPRecipeWithIRFlags(VPRecipeBase::VPVectorEndPointerSC, {Ptr, VF},
2278 Ptr->getScalarType(), GEPFlags, DL),
2279 SourceElementTy(SourceElementTy), Stride(Stride) {
2280 assert(Stride < 0 && "Stride must be negative");
2281 }
2282
2283 VP_CLASSOF_IMPL(VPRecipeBase::VPVectorEndPointerSC)
2284
2285 Type *getSourceElementType() const { return SourceElementTy; }
2286 int64_t getStride() const { return Stride; }
2287 VPValue *getPointer() const { return getOperand(0); }
2288 VPValue *getVFValue() const { return getOperand(1); }
2290 return getNumOperands() == 3 ? getOperand(2) : nullptr;
2291 }
2292
2293 /// Adds the offset operand to the recipe.
2294 /// Offset = Stride * (VF - 1) + Part * Stride * VF.
2295 void materializeOffset(unsigned Part = 0);
2296
2297 /// Append \p Offset as the offset operand. The offset is an integer index
2298 /// expressed in units of SourceElementTy.
2300 assert(Offset->getScalarType()->isIntegerTy() &&
2301 "offset must be an integer index");
2303 }
2304
2305 void execute(VPTransformState &State) override;
2306
2307 bool usesFirstLaneOnly(const VPValue *Op) const override {
2309 "Op must be an operand of the recipe");
2310 return true;
2311 }
2312
2313 /// Return the cost of this VPVectorPointerRecipe.
2315 VPCostContext &Ctx) const override {
2316 // TODO: Compute accurate cost after retiring the legacy cost model.
2317 return 0;
2318 }
2319
2320 /// Returns true if the recipe only uses the first part of operand \p Op.
2321 bool usesFirstPartOnly(const VPValue *Op) const override {
2323 "Op must be an operand of the recipe");
2324 assert(getNumOperands() <= 2 && "must have at most two operands");
2325 return true;
2326 }
2327
2329 auto *VEPR = new VPVectorEndPointerRecipe(
2332 if (auto *Offset = getOffset())
2333 VEPR->addOffset(Offset);
2334 return VEPR;
2335 }
2336
2337protected:
2338#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2339 /// Print the recipe.
2340 void printRecipe(raw_ostream &O, const Twine &Indent,
2341 VPSlotTracker &SlotTracker) const override;
2342#endif
2343};
2344
2345/// A recipe to compute the pointers for widened memory accesses of \p
2346/// SourceElementTy, with the \p Stride expressed in units of \p
2347/// SourceElementTy. Unrolling adds an extra \p VFxPart operand for unrolled
2348/// parts > 0 and it produces `GEP SourceElementTy Ptr, VFxPart * Stride`.
2350 Type *SourceElementTy;
2351
2352public:
2353 VPVectorPointerRecipe(VPValue *Ptr, Type *SourceElementTy, VPValue *Stride,
2354 GEPNoWrapFlags GEPFlags, DebugLoc DL)
2355 : VPRecipeWithIRFlags(VPRecipeBase::VPVectorPointerSC,
2356 ArrayRef<VPValue *>({Ptr, Stride}),
2357 Ptr->getScalarType(), GEPFlags, DL),
2358 SourceElementTy(SourceElementTy) {}
2359
2360 VP_CLASSOF_IMPL(VPRecipeBase::VPVectorPointerSC)
2361
2362 VPValue *getStride() const { return getOperand(1); }
2363
2365 return getNumOperands() > 2 ? getOperand(2) : nullptr;
2366 }
2367
2368 /// Add the per-part offset (VFxPart) used for unrolled parts > 0.
2369 void addPerPartOffset(VPValue *VFxPart) {
2370 assert(VFxPart->getScalarType()->isIntegerTy() &&
2371 "per-part offset must be an integer index");
2372 VPUser::addOperand(VFxPart);
2373 }
2374
2375 void execute(VPTransformState &State) override;
2376
2377 Type *getSourceElementType() const { return SourceElementTy; }
2378
2379 bool usesFirstLaneOnly(const VPValue *Op) const override {
2381 "Op must be an operand of the recipe");
2382 return true;
2383 }
2384
2385 /// Returns true if the recipe only uses the first part of operand \p Op.
2386 bool usesFirstPartOnly(const VPValue *Op) const override {
2388 "Op must be an operand of the recipe");
2389 assert(getNumOperands() <= 2 && "must have at most two operands");
2390 return true;
2391 }
2392
2394 auto *Clone =
2395 new VPVectorPointerRecipe(getOperand(0), SourceElementTy, getStride(),
2397 if (auto *VFxPart = getVFxPart())
2398 Clone->addPerPartOffset(VFxPart);
2399 return Clone;
2400 }
2401
2402 /// Return the cost of this VPHeaderPHIRecipe.
2404 VPCostContext &Ctx) const override {
2405 // TODO: Compute accurate cost after retiring the legacy cost model.
2406 return 0;
2407 }
2408
2409protected:
2410#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2411 /// Print the recipe.
2412 void printRecipe(raw_ostream &O, const Twine &Indent,
2413 VPSlotTracker &SlotTracker) const override;
2414#endif
2415};
2416
2417/// A pure virtual base class for all recipes modeling header phis, including
2418/// phis for first order recurrences, pointer inductions and reductions. The
2419/// start value is the first operand of the recipe and the incoming value from
2420/// the backedge is the second operand.
2421///
2422/// Inductions are modeled using the following sub-classes:
2423/// * VPWidenIntOrFpInductionRecipe: Generates vector values for integer and
2424/// floating point inductions with arbitrary start and step values. Produces
2425/// a vector PHI per-part.
2426/// * VPWidenPointerInductionRecipe: Generate vector and scalar values for a
2427/// pointer induction. Produces either a vector PHI per-part or scalar values
2428/// per-lane based on the canonical induction.
2429/// * VPFirstOrderRecurrencePHIRecipe
2430/// * VPReductionPHIRecipe
2431/// * VPActiveLaneMaskPHIRecipe
2432/// * VPEVLBasedIVPHIRecipe
2433///
2434/// Note that the canonical IV is modeled as a VPRegionValue associated with
2435/// its loop region.
2437 public VPPhiAccessors {
2438protected:
2439 VPHeaderPHIRecipe(VPRecipeTy VPRecipeID, Instruction *UnderlyingInstr,
2440 VPValue *Start, DebugLoc DL = DebugLoc::getUnknown())
2441 : VPHeaderPHIRecipe(VPRecipeID, UnderlyingInstr, Start,
2442 Start->getScalarType(), DL) {}
2443
2444 VPHeaderPHIRecipe(VPRecipeTy VPRecipeID, Instruction *UnderlyingInstr,
2445 VPValue *Start, Type *ResultTy, DebugLoc DL)
2446 : VPSingleDefRecipe(VPRecipeID, Start, ResultTy, UnderlyingInstr, DL) {}
2447
2448 const VPRecipeBase *getAsRecipe() const override { return this; }
2449
2450public:
2451 ~VPHeaderPHIRecipe() override = default;
2452
2453 /// Method to support type inquiry through isa, cast, and dyn_cast.
2454 static inline bool classof(const VPRecipeBase *R) {
2455 return R->getVPRecipeID() >= VPRecipeBase::VPFirstHeaderPHISC &&
2456 R->getVPRecipeID() <= VPRecipeBase::VPLastHeaderPHISC;
2457 }
2458 static inline bool classof(const VPValue *V) {
2459 return isa<VPHeaderPHIRecipe>(V->getDefiningRecipe());
2460 }
2461 static inline bool classof(const VPSingleDefRecipe *R) {
2462 return isa<VPHeaderPHIRecipe>(static_cast<const VPRecipeBase *>(R));
2463 }
2464
2465 /// Generate the phi nodes.
2466 void execute(VPTransformState &State) override = 0;
2467
2468 /// Return the cost of this header phi recipe.
2470 VPCostContext &Ctx) const override;
2471
2472 /// Returns the start value of the phi, if one is set.
2474 return getNumOperands() == 0 ? nullptr : getOperand(0);
2475 }
2477 return getNumOperands() == 0 ? nullptr : getOperand(0);
2478 }
2479
2480 /// Update the start value of the recipe.
2482
2483 /// Returns the incoming value from the loop backedge.
2485 return getOperand(1);
2486 }
2487
2488 /// Update the incoming value from the loop backedge.
2490
2491 /// Add \p V as the incoming value from the loop backedge.
2493 assert(getNumOperands() == 1 &&
2494 "backedge value must be appended right after construction");
2495 assert(V->getScalarType() == getScalarType() &&
2496 "backedge value must have the same type as the start value");
2498 }
2499
2500protected:
2501#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2502 /// Print the recipe.
2503 void printRecipe(raw_ostream &O, const Twine &Indent,
2504 VPSlotTracker &SlotTracker) const override = 0;
2505#endif
2506};
2507
2508/// Base class for widened induction (VPWidenIntOrFpInductionRecipe and
2509/// VPWidenPointerInductionRecipe), providing shared functionality, including
2510/// retrieving the step value, induction descriptor and original phi node.
2512 InductionDescriptor IndDesc;
2513
2514public:
2516 VPValue *Step, const InductionDescriptor &IndDesc,
2517 DebugLoc DL)
2518 : VPWidenInductionRecipe(Kind, IV, Start, Step, IndDesc,
2519 Start->getScalarType(), DL) {}
2520
2522 VPValue *Step, const InductionDescriptor &IndDesc,
2523 Type *ResultTy, DebugLoc DL)
2524 : VPHeaderPHIRecipe(Kind, IV, Start, ResultTy, DL), IndDesc(IndDesc) {
2525 addOperand(Step);
2526 }
2527
2528 /// After unrolling, append the splat-VF step (`VF * step`) and the value of
2529 /// the induction at the last unrolled part.
2530 void addUnrolledPartOperands(VPValue *SplatVFStep, VPValue *LastPart) {
2531 assert(LastPart->getScalarType() == getScalarType() &&
2532 "last-part value must match the induction recipe's scalar type");
2534 ? SplatVFStep->getScalarType()->isIntegerTy()
2535 : SplatVFStep->getScalarType() == getScalarType()) &&
2536 "splat-step must match the induction type for non-pointer "
2537 "inductions, or be an integer index for pointer inductions");
2538 VPUser::addOperand(SplatVFStep);
2539 VPUser::addOperand(LastPart);
2540 }
2541
2542 static inline bool classof(const VPRecipeBase *R) {
2543 return R->getVPRecipeID() == VPRecipeBase::VPWidenIntOrFpInductionSC ||
2544 R->getVPRecipeID() == VPRecipeBase::VPWidenPointerInductionSC;
2545 }
2546
2547 static inline bool classof(const VPValue *V) {
2548 auto *R = V->getDefiningRecipe();
2549 return R && classof(R);
2550 }
2551
2552 static inline bool classof(const VPSingleDefRecipe *R) {
2553 return classof(static_cast<const VPRecipeBase *>(R));
2554 }
2555
2556 void execute(VPTransformState &State) override = 0;
2557
2558 /// Returns the start value of the induction.
2560
2561 /// Returns the step value of the induction.
2563 const VPValue *getStepValue() const { return getOperand(1); }
2564
2565 /// Update the step value of the recipe.
2566 void setStepValue(VPValue *V) { setOperand(1, V); }
2567
2569 const VPValue *getVFValue() const { return getOperand(2); }
2570
2571 /// Returns the number of incoming values, also number of incoming blocks.
2572 /// Note that at the moment, VPWidenPointerInductionRecipe only has a single
2573 /// incoming value, its start value.
2574 unsigned getNumIncoming() const override { return 1; }
2575
2576 /// Returns the underlying PHINode if one exists, or null otherwise.
2580
2581 /// Returns the induction descriptor for the recipe.
2582 const InductionDescriptor &getInductionDescriptor() const { return IndDesc; }
2583
2584 /// Returns the SCEV predicates associated with this induction.
2586 return IndDesc.getNoWrapPredicates();
2587 }
2588
2590 // TODO: All operands of base recipe must exist and be at same index in
2591 // derived recipe.
2593 "VPWidenIntOrFpInductionRecipe generates its own backedge value");
2594 }
2595
2596 /// Returns true if the recipe only uses the first lane of operand \p Op.
2597 bool usesFirstLaneOnly(const VPValue *Op) const override {
2599 "Op must be an operand of the recipe");
2600 // The recipe creates its own wide start value, so it only requests the
2601 // first lane of the operand.
2602 // TODO: Remove once creating the start value is modeled separately.
2603 return Op == getStartValue() || Op == getStepValue();
2604 }
2605};
2606
2607/// A recipe for handling phi nodes of integer and floating-point inductions,
2608/// producing their vector values. This is an abstract recipe and must be
2609/// converted to concrete recipes before executing.
2611 public VPIRFlags {
2612 TruncInst *Trunc;
2613
2614 // If this recipe is unrolled it will have 2 additional operands.
2615 bool isUnrolled() const { return getNumOperands() == 5; }
2616
2617public:
2619 VPValue *VF, const InductionDescriptor &IndDesc,
2620 const VPIRFlags &Flags, DebugLoc DL)
2621 : VPWidenInductionRecipe(VPRecipeBase::VPWidenIntOrFpInductionSC, IV,
2622 Start, Step, IndDesc, DL),
2623 VPIRFlags(Flags), Trunc(nullptr) {
2624 addOperand(VF);
2625 }
2626
2628 VPValue *VF, const InductionDescriptor &IndDesc,
2629 TruncInst *Trunc, const VPIRFlags &Flags,
2630 DebugLoc DL)
2631 : VPWidenInductionRecipe(VPRecipeBase::VPWidenIntOrFpInductionSC, IV,
2632 Start, Step, IndDesc,
2633 Trunc ? Trunc->getType() : Start->getType(), DL),
2634 VPIRFlags(Flags), Trunc(Trunc) {
2635 addOperand(VF);
2637 if (Trunc)
2639 assert(Metadata.empty() && "unexpected metadata on Trunc");
2640 }
2641
2643
2649
2650 VP_CLASSOF_IMPL(VPRecipeBase::VPWidenIntOrFpInductionSC)
2651
2652 void execute(VPTransformState &State) override {
2653 llvm_unreachable("cannot execute this recipe, should be expanded via "
2654 "expandVPWidenIntOrFpInductionRecipe");
2655 }
2656
2657 /// If the recipe has been unrolled, return the VPValue for the induction
2658 /// increment, otherwise return null.
2660 return isUnrolled() ? getOperand(getNumOperands() - 2) : nullptr;
2661 }
2662
2663 /// Returns the number of incoming values, also number of incoming blocks.
2664 /// Note that at the moment, VPWidenIntOrFpInductionRecipes only have a single
2665 /// incoming value, its start value.
2666 unsigned getNumIncoming() const override { return 1; }
2667
2668 /// Returns the first defined value as TruncInst, if it is one or nullptr
2669 /// otherwise.
2670 TruncInst *getTruncInst() { return Trunc; }
2671 const TruncInst *getTruncInst() const { return Trunc; }
2672
2673 /// Return the cost of this VPWidenIntOrFpInductionRecipe.
2675 VPCostContext &Ctx) const override;
2676
2677 /// Returns true if the induction is canonical, i.e. starting at 0 and
2678 /// incremented by UF * VF (= the original IV is incremented by 1) and has the
2679 /// same type as the canonical induction.
2680 bool isCanonical() const;
2681
2682 /// Returns the VPValue representing the value of this induction at
2683 /// the last unrolled part, if it exists. Returns itself if unrolling did not
2684 /// take place.
2686 return isUnrolled() ? getOperand(getNumOperands() - 1) : this;
2687 }
2688
2689protected:
2690#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2691 /// Print the recipe.
2692 void printRecipe(raw_ostream &O, const Twine &Indent,
2693 VPSlotTracker &SlotTracker) const override;
2694#endif
2695};
2696
2698public:
2699 /// Create a new VPWidenPointerInductionRecipe for \p Phi with start value \p
2700 /// Start and the number of elements unrolled \p NumUnrolledElems, typically
2701 /// VF*UF.
2703 VPValue *NumUnrolledElems,
2704 const InductionDescriptor &IndDesc, DebugLoc DL)
2705 : VPWidenInductionRecipe(VPRecipeBase::VPWidenPointerInductionSC, Phi,
2706 Start, Step, IndDesc, DL) {
2707 addOperand(NumUnrolledElems);
2708 }
2709
2711
2717
2718 VP_CLASSOF_IMPL(VPRecipeBase::VPWidenPointerInductionSC)
2719
2720 /// Generate vector values for the pointer induction.
2721 void execute(VPTransformState &State) override {
2722 llvm_unreachable("cannot execute this recipe, should be expanded via "
2723 "expandVPWidenPointerInduction");
2724 };
2725
2726 /// Returns true if only scalar values will be generated.
2727 bool onlyScalarsGenerated(bool IsScalable);
2728
2729protected:
2730#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2731 /// Print the recipe.
2732 void printRecipe(raw_ostream &O, const Twine &Indent,
2733 VPSlotTracker &SlotTracker) const override;
2734#endif
2735};
2736
2737/// A recipe for widened phis. Incoming values are operands of the recipe and
2738/// their operand index corresponds to the incoming predecessor block. If the
2739/// recipe is placed in an entry block to a (non-replicate) region, it must have
2740/// exactly 2 incoming values, the first from the predecessor of the region and
2741/// the second from the exiting block of the region.
2743 public VPPhiAccessors {
2744 /// Name to use for the generated IR instruction for the widened phi.
2745 std::string Name;
2746
2747public:
2748 /// Create a new VPWidenPHIRecipe with incoming values \p IncomingValues,
2749 /// debug location \p DL and \p Name.
2751 DebugLoc DL = DebugLoc::getUnknown(), const Twine &Name = "")
2752 : VPSingleDefRecipe(VPRecipeBase::VPWidenPHISC, IncomingValues,
2753 IncomingValues[0]->getScalarType(),
2754 /*UV=*/nullptr, DL),
2755 Name(Name.str()) {
2756 assert(all_of(IncomingValues,
2757 [this](VPValue *VPV) {
2758 return VPV->getScalarType() == getScalarType();
2759 }) &&
2760 "all incoming values must have the same type");
2761 }
2762
2764 return new VPWidenPHIRecipe(operands(), getDebugLoc(), Name);
2765 }
2766
2767 ~VPWidenPHIRecipe() override = default;
2768
2769 /// This recipe generates a PHI.
2770 unsigned getOpcode() const { return Instruction::PHI; }
2771
2772 VP_CLASSOF_IMPL(VPRecipeBase::VPWidenPHISC)
2773
2774 /// Generate the phi/select nodes.
2775 void execute(VPTransformState &State) override;
2776
2777 /// Return the cost of this VPWidenPHIRecipe.
2778 InstructionCost computeCost(ElementCount VF,
2779 VPCostContext &Ctx) const override;
2780
2781protected:
2782#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2783 /// Print the recipe.
2784 void printRecipe(raw_ostream &O, const Twine &Indent,
2785 VPSlotTracker &SlotTracker) const override;
2786#endif
2787
2788 const VPRecipeBase *getAsRecipe() const override { return this; }
2789};
2790
2791/// A recipe for handling first-order recurrence phis. The start value is the
2792/// first operand of the recipe and the incoming value from the backedge is the
2793/// second operand.
2796 VPValue &BackedgeValue)
2797 : VPHeaderPHIRecipe(VPRecipeBase::VPFirstOrderRecurrencePHISC, Phi,
2798 &Start) {
2799 addOperand(&BackedgeValue);
2800 }
2801
2802 VP_CLASSOF_IMPL(VPRecipeBase::VPFirstOrderRecurrencePHISC)
2803
2808
2809 void execute(VPTransformState &State) override;
2810
2811 /// Return the cost of this first-order recurrence phi recipe.
2813 VPCostContext &Ctx) const override;
2814
2815 /// Returns true if the recipe only uses the first lane of operand \p Op.
2816 bool usesFirstLaneOnly(const VPValue *Op) const override {
2818 "Op must be an operand of the recipe");
2819 return Op == getStartValue();
2820 }
2821
2822protected:
2823#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2824 /// Print the recipe.
2825 void printRecipe(raw_ostream &O, const Twine &Indent,
2826 VPSlotTracker &SlotTracker) const override;
2827#endif
2828};
2829
2830/// Possible variants of a reduction.
2831
2832/// This reduction is ordered and in-loop.
2833struct RdxOrdered {};
2834/// This reduction is in-loop.
2835struct RdxInLoop {};
2836/// This reduction is unordered with the partial result scaled down by some
2837/// factor.
2840};
2841using ReductionStyle = std::variant<RdxOrdered, RdxInLoop, RdxUnordered>;
2842
2843inline ReductionStyle getReductionStyle(bool InLoop, bool Ordered,
2844 unsigned ScaleFactor) {
2845 assert((!Ordered || InLoop) && "Ordered implies in-loop");
2846 if (Ordered)
2847 return RdxOrdered{};
2848 if (InLoop)
2849 return RdxInLoop{};
2850 return RdxUnordered{/*VFScaleFactor=*/ScaleFactor};
2851}
2852
2853/// A recipe for handling reduction phis. The start value is the first operand
2854/// of the recipe and the incoming value from the backedge is the second
2855/// operand.
2857 /// The recurrence kind of the reduction.
2858 const RecurKind Kind;
2859
2860 ReductionStyle Style;
2861
2862 /// The phi is part of a multi-use reduction (e.g., used in FindIV
2863 /// patterns for argmin/argmax).
2864 /// TODO: Also support cases where the phi itself has a single use, but its
2865 /// compare has multiple uses.
2866 bool HasUsesOutsideReductionChain;
2867
2868public:
2869 /// Create a new VPReductionPHIRecipe for the reduction \p Phi.
2871 VPValue &BackedgeValue, ReductionStyle Style,
2872 const VPIRFlags &Flags,
2873 bool HasUsesOutsideReductionChain = false)
2874 : VPHeaderPHIRecipe(VPRecipeBase::VPReductionPHISC, Phi, &Start),
2875 VPIRFlags(Flags), Kind(Kind), Style(Style),
2876 HasUsesOutsideReductionChain(HasUsesOutsideReductionChain) {
2877 addOperand(&BackedgeValue);
2878 }
2879
2880 ~VPReductionPHIRecipe() override = default;
2881
2883 VPValue *BackedgeValue) {
2884 return new VPReductionPHIRecipe(
2886 *Start, *BackedgeValue, Style, *this, HasUsesOutsideReductionChain);
2887 }
2888
2892
2893 VP_CLASSOF_IMPL(VPRecipeBase::VPReductionPHISC)
2894
2895 /// Generate the phi/select nodes.
2896 void execute(VPTransformState &State) override;
2897
2898 /// Get the factor that the VF of this recipe's output should be scaled by, or
2899 /// 1 if it isn't scaled.
2900 unsigned getVFScaleFactor() const {
2901 auto *Partial = std::get_if<RdxUnordered>(&Style);
2902 return Partial ? Partial->VFScaleFactor : 1;
2903 }
2904
2905 /// Set the VFScaleFactor for this reduction phi. Can only be set to a factor
2906 /// > 1.
2907 void setVFScaleFactor(unsigned ScaleFactor) {
2908 assert(ScaleFactor > 1 && "must set to scale factor > 1");
2909 Style = RdxUnordered{ScaleFactor};
2910 }
2911
2912 /// Returns the recurrence kind of the reduction.
2913 RecurKind getRecurrenceKind() const { return Kind; }
2914
2915 /// Returns true, if the phi is part of an ordered reduction.
2916 bool isOrdered() const { return std::holds_alternative<RdxOrdered>(Style); }
2917
2918 /// Returns true if the phi is part of an in-loop reduction.
2919 bool isInLoop() const {
2920 return std::holds_alternative<RdxInLoop>(Style) ||
2921 std::holds_alternative<RdxOrdered>(Style);
2922 }
2923
2924 /// Returns true if the reduction outputs a vector with a scaled down VF.
2925 bool isPartialReduction() const { return getVFScaleFactor() > 1; }
2926
2927 /// Returns true, if the phi is part of a multi-use reduction.
2929 return HasUsesOutsideReductionChain;
2930 }
2931
2932 /// Returns true if the recipe only uses the first lane of operand \p Op.
2933 bool usesFirstLaneOnly(const VPValue *Op) const override {
2935 "Op must be an operand of the recipe");
2936 return isOrdered() || isInLoop();
2937 }
2938
2939protected:
2940#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2941 /// Print the recipe.
2942 void printRecipe(raw_ostream &O, const Twine &Indent,
2943 VPSlotTracker &SlotTracker) const override;
2944#endif
2945};
2946
2947/// A recipe for vectorizing a phi-node as a sequence of mask-based select
2948/// instructions.
2950public:
2951 /// The blend operation is a User of the incoming values and of their
2952 /// respective masks, ordered [I0, M0, I1, M1, I2, M2, ...]. Note that M0 can
2953 /// be omitted (implied by passing an odd number of operands) in which case
2954 /// all other incoming values are merged into it.
2956 const VPIRFlags &Flags, DebugLoc DL)
2957 : VPRecipeWithIRFlags(VPRecipeBase::VPBlendSC, Operands,
2958 Operands[0]->getScalarType(), Flags, DL) {
2959 assert(Operands.size() >= 2 && "Expected at least two operands!");
2961 [this](unsigned I) {
2962 return getIncomingValue(I)->getScalarType() ==
2963 getScalarType();
2964 }) &&
2965 "all incoming values must have the same type");
2967 [this](unsigned I) {
2968 return getMask(I)->getScalarType()->isIntegerTy(1);
2969 }) &&
2970 "masks must be a bool");
2971 setUnderlyingValue(Phi);
2972 }
2973
2975
2978 NewOperands, *this, getDebugLoc());
2979 }
2980
2981 VP_CLASSOF_IMPL(VPRecipeBase::VPBlendSC)
2982
2983 /// A normalized blend is one that has an odd number of operands, whereby the
2984 /// first operand does not have an associated mask.
2985 bool isNormalized() const { return getNumOperands() % 2; }
2986
2987 /// Return the number of incoming values, taking into account when normalized
2988 /// the first incoming value will have no mask.
2989 unsigned getNumIncomingValues() const {
2990 return (getNumOperands() + isNormalized()) / 2;
2991 }
2992
2993 /// Return incoming value number \p Idx.
2994 VPValue *getIncomingValue(unsigned Idx) const {
2995 return Idx == 0 ? getOperand(0) : getOperand(Idx * 2 - isNormalized());
2996 }
2997
2998 /// Return mask number \p Idx.
2999 VPValue *getMask(unsigned Idx) const {
3000 assert((Idx > 0 || !isNormalized()) && "First index has no mask!");
3001 return Idx == 0 ? getOperand(1) : getOperand(Idx * 2 + !isNormalized());
3002 }
3003
3004 /// Set mask number \p Idx to \p V.
3005 void setMask(unsigned Idx, VPValue *V) {
3006 assert((Idx > 0 || !isNormalized()) && "First index has no mask!");
3007 assert(V->getScalarType()->isIntegerTy(1) && "Mask must be an i1 (vector)");
3008 Idx == 0 ? setOperand(1, V) : setOperand(Idx * 2 + !isNormalized(), V);
3009 }
3010
3011 void execute(VPTransformState &State) override {
3012 llvm_unreachable("VPBlendRecipe should be expanded by simplifyBlends");
3013 }
3014
3015 /// Return the cost of this VPWidenMemoryRecipe.
3016 InstructionCost computeCost(ElementCount VF,
3017 VPCostContext &Ctx) const override;
3018
3019 /// Returns true if the recipe only uses the first lane of operand \p Op.
3020 bool usesFirstLaneOnly(const VPValue *Op) const override;
3021
3022protected:
3023#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3024 /// Print the recipe.
3025 void printRecipe(raw_ostream &O, const Twine &Indent,
3026 VPSlotTracker &SlotTracker) const override;
3027#endif
3028};
3029
3030/// A common base class for interleaved memory operations.
3031/// An Interleaved memory operation is a memory access method that combines
3032/// multiple strided loads/stores into a single wide load/store with shuffles.
3033/// The first operand is the start address. The optional operands are, in order,
3034/// the stored values and the mask.
3036 public VPIRMetadata {
3038
3039 /// Indicates if the interleave group is in a conditional block and requires a
3040 /// mask.
3041 bool HasMask = false;
3042
3043 /// Indicates if gaps between members of the group need to be masked out or if
3044 /// unusued gaps can be loaded speculatively.
3045 bool NeedsMaskForGaps = false;
3046
3047protected:
3049 ArrayRef<VPValue *> Operands,
3050 ArrayRef<VPValue *> StoredValues, VPValue *Mask,
3051 bool NeedsMaskForGaps, const VPIRMetadata &MD, DebugLoc DL)
3052 : VPRecipeBase(SC, Operands, DL), VPIRMetadata(MD), IG(IG),
3053 NeedsMaskForGaps(NeedsMaskForGaps) {
3054 // TODO: extend the masked interleaved-group support to reversed access.
3055 assert((!Mask || !IG->isReverse()) &&
3056 "Reversed masked interleave-group not supported.");
3057 if (StoredValues.empty()) {
3058 for (Instruction *Inst : IG->members()) {
3059 assert(!Inst->getType()->isVoidTy() && "must have result");
3060 new VPMultiDefValue(this, Inst, Inst->getType());
3061 }
3062 } else {
3063 for (auto *SV : StoredValues)
3064 addOperand(SV);
3065 }
3066 if (Mask) {
3067 HasMask = true;
3068 addOperand(Mask);
3069 }
3070 }
3071
3072public:
3073 VPInterleaveBase *clone() override = 0;
3074
3075 static inline bool classof(const VPRecipeBase *R) {
3076 return R->getVPRecipeID() == VPRecipeBase::VPInterleaveSC ||
3077 R->getVPRecipeID() == VPRecipeBase::VPInterleaveEVLSC;
3078 }
3079
3080 static inline bool classof(const VPUser *U) {
3081 auto *R = dyn_cast<VPRecipeBase>(U);
3082 return R && classof(R);
3083 }
3084
3085 /// Return the address accessed by this recipe.
3086 VPValue *getAddr() const {
3087 return getOperand(0); // Address is the 1st, mandatory operand.
3088 }
3089
3090 /// Return the mask used by this recipe. Note that a full mask is represented
3091 /// by a nullptr.
3092 VPValue *getMask() const {
3093 // Mask is optional and the last operand.
3094 return HasMask ? getOperand(getNumOperands() - 1) : nullptr;
3095 }
3096
3097 /// Return true if the access needs a mask because of the gaps.
3098 bool needsMaskForGaps() const { return NeedsMaskForGaps; }
3099
3101
3102 Instruction *getInsertPos() const { return IG->getInsertPos(); }
3103
3104 void execute(VPTransformState &State) override {
3105 llvm_unreachable("VPInterleaveBase should not be instantiated.");
3106 }
3107
3108 /// Return the cost of this recipe.
3109 InstructionCost computeCost(ElementCount VF,
3110 VPCostContext &Ctx) const override;
3111
3112 /// Returns true if the recipe only uses the first lane of operand \p Op.
3113 bool usesFirstLaneOnly(const VPValue *Op) const override = 0;
3114
3115 /// Returns the number of stored operands of this interleave group. Returns 0
3116 /// for load interleave groups.
3117 virtual unsigned getNumStoreOperands() const = 0;
3118
3119 /// Return the VPValues stored by this interleave group. If it is a load
3120 /// interleave group, return an empty ArrayRef.
3122 return {op_end() - (getNumStoreOperands() + (HasMask ? 1 : 0)),
3124 }
3125};
3126
3127/// VPInterleaveRecipe is a recipe for transforming an interleave group of load
3128/// or stores into one wide load/store and shuffles. The first operand of a
3129/// VPInterleave recipe is the address, followed by the stored values, followed
3130/// by an optional mask.
3132public:
3134 ArrayRef<VPValue *> StoredValues, VPValue *Mask,
3135 bool NeedsMaskForGaps, const VPIRMetadata &MD, DebugLoc DL)
3136 : VPInterleaveBase(VPRecipeBase::VPInterleaveSC, IG, Addr, StoredValues,
3137 Mask, NeedsMaskForGaps, MD, DL) {}
3138
3139 ~VPInterleaveRecipe() override = default;
3140
3144 needsMaskForGaps(), *this, getDebugLoc());
3145 }
3146
3147 VP_CLASSOF_IMPL(VPRecipeBase::VPInterleaveSC)
3148
3149 /// Generate the wide load or store, and shuffles.
3150 void execute(VPTransformState &State) override;
3151
3152 bool usesFirstLaneOnly(const VPValue *Op) const override {
3154 "Op must be an operand of the recipe");
3155 return Op == getAddr() && !llvm::is_contained(getStoredValues(), Op);
3156 }
3157
3158 unsigned getNumStoreOperands() const override {
3159 return getNumOperands() - (getMask() ? 2 : 1);
3160 }
3161
3162protected:
3163#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3164 /// Print the recipe.
3165 void printRecipe(raw_ostream &O, const Twine &Indent,
3166 VPSlotTracker &SlotTracker) const override;
3167#endif
3168};
3169
3170/// A recipe for interleaved memory operations with vector-predication
3171/// intrinsics. The first operand is the address, the second operand is the
3172/// explicit vector length. Stored values and mask are optional operands.
3174public:
3176 : VPInterleaveBase(VPRecipeBase::VPInterleaveEVLSC,
3177 R.getInterleaveGroup(), {R.getAddr(), &EVL},
3178 R.getStoredValues(), Mask, R.needsMaskForGaps(), R,
3179 R.getDebugLoc()) {
3180 assert(!getInterleaveGroup()->isReverse() &&
3181 "Reversed interleave-group with tail folding is not supported.");
3182 assert(!needsMaskForGaps() && "Interleaved access with gap mask is not "
3183 "supported for scalable vector.");
3184 }
3185
3186 ~VPInterleaveEVLRecipe() override = default;
3187
3189 llvm_unreachable("cloning not implemented yet");
3190 }
3191
3192 VP_CLASSOF_IMPL(VPRecipeBase::VPInterleaveEVLSC)
3193
3194 /// The VPValue of the explicit vector length.
3195 VPValue *getEVL() const { return getOperand(1); }
3196
3197 /// Generate the wide load or store, and shuffles.
3198 void execute(VPTransformState &State) override;
3199
3200 /// The recipe only uses the first lane of the address, and EVL operand.
3201 bool usesFirstLaneOnly(const VPValue *Op) const override {
3203 "Op must be an operand of the recipe");
3204 return (Op == getAddr() && !llvm::is_contained(getStoredValues(), Op)) ||
3205 Op == getEVL();
3206 }
3207
3208 unsigned getNumStoreOperands() const override {
3209 return getNumOperands() - (getMask() ? 3 : 2);
3210 }
3211
3212protected:
3213#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3214 /// Print the recipe.
3215 void printRecipe(raw_ostream &O, const Twine &Indent,
3216 VPSlotTracker &SlotTracker) const override;
3217#endif
3218};
3219
3220/// A recipe to represent inloop, ordered or partial reduction operations. It
3221/// performs a reduction on a vector operand into a scalar (vector in the case
3222/// of a partial reduction) value, and adds the result to a chain. The Operands
3223/// are {ChainOp, VecOp, [Condition]}.
3225
3226 /// The recurrence kind for the reduction in question.
3227 RecurKind RdxKind;
3228 /// Whether the reduction is conditional.
3229 bool IsConditional = false;
3230 ReductionStyle Style;
3231
3232protected:
3235 VPValue *CondOp, ReductionStyle Style, DebugLoc DL)
3236 : VPRecipeWithIRFlags(SC, Operands, Operands[0]->getScalarType(), FMFs,
3237 DL),
3238 RdxKind(RdxKind), Style(Style) {
3239 assert(all_of(Operands,
3240 [this](VPValue *VPV) {
3241 return VPV->getScalarType() == getScalarType() ||
3242 (isa<VPInstruction>(VPV) &&
3243 cast<VPInstruction>(VPV)->getOpcode() ==
3245 }) &&
3246 "all incoming values must have the same type");
3247 if (CondOp) {
3248 assert(CondOp->getScalarType()->isIntegerTy(1) &&
3249 "CondOp must be a bool");
3250 IsConditional = true;
3251 addOperand(CondOp);
3252 }
3254 }
3255
3256public:
3258 VPValue *ChainOp, VPValue *VecOp, VPValue *CondOp,
3260 : VPReductionRecipe(VPRecipeBase::VPReductionSC, RdxKind, FMFs, I,
3261 {ChainOp, VecOp}, CondOp, Style, DL) {}
3262
3264 VPValue *ChainOp, VPValue *VecOp, VPValue *CondOp,
3266 : VPReductionRecipe(VPRecipeBase::VPReductionSC, RdxKind, FMFs, nullptr,
3267 {ChainOp, VecOp}, CondOp, Style, DL) {}
3268
3269 ~VPReductionRecipe() override = default;
3270
3272 return new VPReductionRecipe(RdxKind, getFastMathFlagsOrNone(),
3274 getCondOp(), Style, getDebugLoc());
3275 }
3276
3277 static inline bool classof(const VPRecipeBase *R) {
3278 return R->getVPRecipeID() == VPRecipeBase::VPReductionSC ||
3279 R->getVPRecipeID() == VPRecipeBase::VPReductionEVLSC;
3280 }
3281
3282 static inline bool classof(const VPUser *U) {
3283 auto *R = dyn_cast<VPRecipeBase>(U);
3284 return R && classof(R);
3285 }
3286
3287 static inline bool classof(const VPValue *VPV) {
3288 const VPRecipeBase *R = VPV->getDefiningRecipe();
3289 return R && classof(R);
3290 }
3291
3292 static inline bool classof(const VPSingleDefRecipe *R) {
3293 return classof(static_cast<const VPRecipeBase *>(R));
3294 }
3295
3296 /// Generate the reduction in the loop.
3297 void execute(VPTransformState &State) override;
3298
3299 /// Return the cost of VPReductionRecipe.
3300 InstructionCost computeCost(ElementCount VF,
3301 VPCostContext &Ctx) const override;
3302
3303 /// Return the recurrence kind for the in-loop reduction.
3304 RecurKind getRecurrenceKind() const { return RdxKind; }
3305 /// Return true if the in-loop reduction is ordered.
3306 bool isOrdered() const { return std::holds_alternative<RdxOrdered>(Style); };
3307 /// Return true if the in-loop reduction is conditional.
3308 bool isConditional() const { return IsConditional; };
3309 /// Returns true if the reduction outputs a vector with a scaled down VF.
3310 bool isPartialReduction() const { return getVFScaleFactor() > 1; }
3311 /// Returns true if the reduction is in-loop.
3312 bool isInLoop() const {
3313 return std::holds_alternative<RdxInLoop>(Style) ||
3314 std::holds_alternative<RdxOrdered>(Style);
3315 }
3316 /// The VPValue of the scalar Chain being accumulated.
3317 VPValue *getChainOp() const { return getOperand(0); }
3318 /// The VPValue of the vector value to be reduced.
3319 VPValue *getVecOp() const { return getOperand(1); }
3320 /// The VPValue of the condition for the block.
3322 return isConditional() ? getOperand(getNumOperands() - 1) : nullptr;
3323 }
3324 /// Get the factor that the VF of this recipe's output should be scaled by, or
3325 /// 1 if it isn't scaled.
3326 unsigned getVFScaleFactor() const {
3327 auto *Partial = std::get_if<RdxUnordered>(&Style);
3328 return Partial ? Partial->VFScaleFactor : 1;
3329 }
3330
3331protected:
3332#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3333 /// Print the recipe.
3334 void printRecipe(raw_ostream &O, const Twine &Indent,
3335 VPSlotTracker &SlotTracker) const override;
3336#endif
3337};
3338
3339/// A recipe to represent inloop reduction operations with vector-predication
3340/// intrinsics, performing a reduction on a vector operand with the explicit
3341/// vector length (EVL) into a scalar value, and adding the result to a chain.
3342/// The Operands are {ChainOp, VecOp, EVL, [Condition]}.
3344public:
3347 : VPReductionRecipe(VPRecipeBase::VPReductionEVLSC, R.getRecurrenceKind(),
3350 {R.getChainOp(), R.getVecOp(), &EVL}, CondOp,
3351 getReductionStyle(/*InLoop=*/true, R.isOrdered(), 1),
3352 DL) {}
3353
3354 ~VPReductionEVLRecipe() override = default;
3355
3357 llvm_unreachable("cloning not implemented yet");
3358 }
3359
3360 VP_CLASSOF_IMPL(VPRecipeBase::VPReductionEVLSC)
3361
3362 /// Generate the reduction in the loop
3363 void execute(VPTransformState &State) override;
3364
3365 /// The VPValue of the explicit vector length.
3366 VPValue *getEVL() const { return getOperand(2); }
3367
3368 /// Returns true if the recipe only uses the first lane of operand \p Op.
3369 bool usesFirstLaneOnly(const VPValue *Op) const override {
3371 "Op must be an operand of the recipe");
3372 return Op == getEVL();
3373 }
3374
3375protected:
3376#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3377 /// Print the recipe.
3378 void printRecipe(raw_ostream &O, const Twine &Indent,
3379 VPSlotTracker &SlotTracker) const override;
3380#endif
3381};
3382
3383/// VPReplicateRecipe replicates a given instruction producing multiple scalar
3384/// copies of the original scalar type, one per lane, instead of producing a
3385/// single copy of widened type for all lanes. If the instruction is known to be
3386/// a single scalar, only one copy will be generated.
3388 public VPIRMetadata {
3389 /// Indicator if only a single replica per lane is needed.
3390 bool IsSingleScalar;
3391
3392 /// Indicator if the replicas are also predicated.
3393 bool IsPredicated;
3394
3395public:
3397 bool IsSingleScalar, VPValue *Mask = nullptr,
3398 const VPIRFlags &Flags = {}, VPIRMetadata Metadata = {},
3399 DebugLoc DL = DebugLoc::getUnknown())
3400 : VPRecipeWithIRFlags(VPRecipeBase::VPReplicateSC, Operands,
3401 computeScalarType(I, Operands), Flags, DL),
3402 VPIRMetadata(Metadata), IsSingleScalar(IsSingleScalar),
3403 IsPredicated(Mask) {
3404 assert((!IsSingleScalar || !I->isCast()) &&
3405 "single-scalar casts should use VPInstructionWithType");
3406 setUnderlyingValue(I);
3407 if (Mask)
3408 addOperand(Mask);
3409 }
3410
3411 ~VPReplicateRecipe() override = default;
3412
3413 /// Compute the scalar result type for a VPReplicateRecipe wrapping \p I with
3414 /// \p Operands (excluding any predicate mask).
3415 static Type *computeScalarType(const Instruction *I,
3416 ArrayRef<VPValue *> Operands);
3417
3419
3421 auto *Copy = new VPReplicateRecipe(
3422 getUnderlyingInstr(), NewOperands, IsSingleScalar,
3423 isPredicated() ? getMask() : nullptr, *this, *this, getDebugLoc());
3424 Copy->transferFlags(*this);
3425 return Copy;
3426 }
3427
3428 VP_CLASSOF_IMPL(VPRecipeBase::VPReplicateSC)
3429
3430 /// Generate replicas of the desired Ingredient. Replicas will be generated
3431 /// for all parts and lanes unless a specific part and lane are specified in
3432 /// the \p State.
3433 void execute(VPTransformState &State) override;
3434
3435 /// Return the cost of this VPReplicateRecipe.
3436 InstructionCost computeCost(ElementCount VF,
3437 VPCostContext &Ctx) const override;
3438
3439 /// Return the cost of scalarizing a call to \p CalledFn with argument
3440 /// operands \p ArgOps for a given \p VF.
3441 static InstructionCost computeCallCost(Function *CalledFn, Type *ResultTy,
3443 bool IsSingleScalar, ElementCount VF,
3444 VPCostContext &Ctx);
3445
3446 /// Returns true if the recipe produces a single scalar value.
3447 bool isSingleScalar() const { return IsSingleScalar; }
3448
3449 /// Returns true if the recipe produces scalar values for all VF lanes.
3450 bool doesGeneratePerAllLanes() const { return !IsSingleScalar; }
3451
3452 bool isPredicated() const { return IsPredicated; }
3453
3454 /// Returns true if the recipe only uses the first lane of operand \p Op.
3455 bool usesFirstLaneOnly(const VPValue *Op) const override {
3457 "Op must be an operand of the recipe");
3458 return isSingleScalar();
3459 }
3460
3461 /// Returns true if the recipe uses scalars of operand \p Op.
3462 bool usesScalars(const VPValue *Op) const override {
3464 "Op must be an operand of the recipe");
3465 return true;
3466 }
3467
3468 /// Return the mask of a predicated VPReplicateRecipe.
3470 assert(isPredicated() && "Trying to get the mask of a unpredicated recipe");
3471 return getOperand(getNumOperands() - 1);
3472 }
3473
3474 /// Return the recipe's operands, excluding the mask of a predicated recipe.
3478
3479 /// Returns the number of operands, excluding the mask if the recipe is
3480 /// predicated.
3481 unsigned getNumOperandsWithoutMask() const {
3482 return getNumOperands() - isPredicated();
3483 }
3484
3485 unsigned getOpcode() const { return getUnderlyingInstr()->getOpcode(); }
3486
3487protected:
3488#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3489 /// Print the recipe.
3490 void printRecipe(raw_ostream &O, const Twine &Indent,
3491 VPSlotTracker &SlotTracker) const override;
3492#endif
3493};
3494
3495/// A recipe for generating conditional branches on the bits of a mask.
3497public:
3499 : VPRecipeBase(VPRecipeBase::VPBranchOnMaskSC, {BlockInMask}, DL) {}
3500
3503 }
3504
3505 VP_CLASSOF_IMPL(VPRecipeBase::VPBranchOnMaskSC)
3506
3507 /// Generate the extraction of the appropriate bit from the block mask and the
3508 /// conditional branch.
3509 void execute(VPTransformState &State) override;
3510
3511 /// Return the cost of this VPBranchOnMaskRecipe.
3512 InstructionCost computeCost(ElementCount VF,
3513 VPCostContext &Ctx) const override;
3514
3515#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3516 /// Print the recipe.
3517 void printRecipe(raw_ostream &O, const Twine &Indent,
3518 VPSlotTracker &SlotTracker) const override {
3519 O << Indent << "BRANCH-ON-MASK ";
3521 }
3522#endif
3523
3524 /// Returns true if the recipe uses scalars of operand \p Op.
3525 bool usesScalars(const VPValue *Op) const override {
3527 "Op must be an operand of the recipe");
3528 return true;
3529 }
3530};
3531
3532/// A recipe to combine multiple recipes into a single 'expression' recipe,
3533/// which should be considered a single entity for cost-modeling and transforms.
3534/// The recipe needs to be 'decomposed', i.e. replaced by its individual
3535/// expression recipes, before execute. The individual expression recipes are
3536/// completely disconnected from the def-use graph of other recipes not part of
3537/// the expression. Def-use edges between pairs of expression recipes remain
3538/// intact, whereas every edge between an expression recipe and a recipe outside
3539/// the expression is elevated to connect the non-expression recipe with the
3540/// VPExpressionRecipe itself.
3541class VPExpressionRecipe : public VPSingleDefRecipe {
3542 /// Recipes included in this VPExpressionRecipe. This could contain
3543 /// duplicates.
3544 SmallVector<VPSingleDefRecipe *> ExpressionRecipes;
3545
3546 /// Temporary VPValues used for external operands of the expression, i.e.
3547 /// operands not defined by recipes in the expression.
3548 SmallVector<VPValue *> LiveInPlaceholders;
3549
3550 enum class ExpressionTypes {
3551 /// Represents an inloop extended reduction operation, performing a
3552 /// reduction on an extended vector operand into a scalar value, and adding
3553 /// the result to a chain.
3554 ExtendedReduction,
3555 /// Represents an inloop extended reduction operation, which is negated,
3556 /// then reduced before adding the result to a chain.
3557 NegatedExtendedReduction,
3558 /// Represent an inloop multiply-accumulate reduction, multiplying the
3559 /// extended vector operands, performing a reduction.add on the result, and
3560 /// adding the scalar result to a chain.
3561 ExtMulAccReduction,
3562 /// Represent an inloop multiply-accumulate reduction, multiplying the
3563 /// vector operands, performing a reduction.add on the result, and adding
3564 /// the scalar result to a chain.
3565 MulAccReduction,
3566 /// Represent an inloop multiply-accumulate reduction, multiplying the
3567 /// extended vector operands, negating the multiplication, performing a
3568 /// reduction.add on the result, and adding the scalar result to a chain.
3569 ExtNegatedMulAccReduction,
3570 };
3571
3572 /// Type of the expression.
3573 ExpressionTypes ExpressionType;
3574
3575 /// Construct a new VPExpressionRecipe by internalizing recipes in \p
3576 /// ExpressionRecipes. External operands (i.e. not defined by another recipe
3577 /// in the expression) are replaced by temporary VPValues and the original
3578 /// operands are transferred to the VPExpressionRecipe itself. Clone recipes
3579 /// as needed (excluding last) to ensure they are only used by other recipes
3580 /// in the expression.
3581 VPExpressionRecipe(ExpressionTypes ExpressionType,
3582 ArrayRef<VPSingleDefRecipe *> ExpressionRecipes);
3583
3584public:
3586 : VPExpressionRecipe(ExpressionTypes::ExtendedReduction, {Ext, Red}) {}
3588 VPReductionRecipe *Red)
3589 : VPExpressionRecipe(ExpressionTypes::NegatedExtendedReduction,
3590 {Ext, Neg, Red}) {
3591 assert((Red->getRecurrenceKind() == RecurKind::Add ||
3592 Red->getRecurrenceKind() == RecurKind::FAdd ||
3593 Red->getRecurrenceKind() == RecurKind::AddChainWithSubs) &&
3594 "Expected an add or add-chain-with-subs reduction");
3595 if (Neg->getOpcode() == Instruction::Sub) {
3596 [[maybe_unused]] auto *SubConst = dyn_cast<VPConstantInt>(getOperand(1));
3597 assert(SubConst && SubConst->isZero() && "Expected a negating sub");
3598 } else
3599 assert(Neg->getOpcode() == Instruction::FNeg && "Unexpected opcode");
3600 }
3602 : VPExpressionRecipe(ExpressionTypes::MulAccReduction, {Mul, Red}) {}
3605 : VPExpressionRecipe(ExpressionTypes::ExtMulAccReduction,
3606 {Ext0, Ext1, Mul, Red}) {}
3609 VPReductionRecipe *Red)
3610 : VPExpressionRecipe(ExpressionTypes::ExtNegatedMulAccReduction,
3611 {Ext0, Ext1, Mul, Neg, Red}) {
3612 assert((Mul->getOpcode() == Instruction::Mul ||
3613 Mul->getOpcode() == Instruction::FMul) &&
3614 "Expected a mul");
3615 assert((Red->getRecurrenceKind() == RecurKind::Add ||
3616 Red->getRecurrenceKind() == RecurKind::FAdd ||
3617 Red->getRecurrenceKind() == RecurKind::AddChainWithSubs) &&
3618 "Expected an add or add-chain-with-subs reduction");
3619 assert(getNumOperands() >= 3 && "Expected at least three operands");
3620 if (Neg->getOpcode() == Instruction::Sub) {
3621 [[maybe_unused]] auto *SubConst = dyn_cast<VPConstantInt>(getOperand(2));
3622 assert(SubConst && SubConst->isZero() &&
3623 Neg->getOpcode() == Instruction::Sub && "Expected a negating sub");
3624 } else
3625 assert(Neg->getOpcode() == Instruction::FNeg && "Unexpected opcode");
3626 }
3627
3629 SmallPtrSet<VPSingleDefRecipe *, 4> ExpressionRecipesSeen;
3630 for (auto *R : reverse(ExpressionRecipes)) {
3631 if (ExpressionRecipesSeen.insert(R).second)
3632 delete R;
3633 }
3634 for (VPValue *T : LiveInPlaceholders)
3635 delete T;
3636 }
3637
3638 VP_CLASSOF_IMPL(VPRecipeBase::VPExpressionSC)
3639
3640 VPExpressionRecipe *clone() override {
3641 assert(!ExpressionRecipes.empty() && "empty expressions should be removed");
3642 SmallVector<VPSingleDefRecipe *> NewExpressiondRecipes;
3643 for (auto *R : ExpressionRecipes)
3644 NewExpressiondRecipes.push_back(R->clone());
3645 for (auto *New : NewExpressiondRecipes) {
3646 for (const auto &[Idx, Old] : enumerate(ExpressionRecipes))
3647 New->replaceUsesOfWith(Old, NewExpressiondRecipes[Idx]);
3648 // Update placeholder operands in the cloned recipe to use the external
3649 // operands, to be internalized when the cloned expression is constructed.
3650 for (const auto &[Placeholder, OutsideOp] :
3651 zip(LiveInPlaceholders, operands()))
3652 New->replaceUsesOfWith(Placeholder, OutsideOp);
3653 }
3654 return new VPExpressionRecipe(ExpressionType, NewExpressiondRecipes);
3655 }
3656
3657 /// Insert the recipes of the expression back into the VPlan, directly before
3658 /// the current recipe. Leaves the expression recipe empty, which must be
3659 /// removed before codegen.
3660 void decompose();
3661
3662 unsigned getVFScaleFactor() const {
3663 auto *PR = dyn_cast<VPReductionRecipe>(ExpressionRecipes.back());
3664 return PR ? PR->getVFScaleFactor() : 1;
3665 }
3666
3667 /// Method for generating code, must not be called as this recipe is abstract.
3668 void execute(VPTransformState &State) override {
3669 llvm_unreachable("recipe must be removed before execute");
3670 }
3671
3673 VPCostContext &Ctx) const override;
3674
3675 /// Returns true if this expression contains recipes that may read from or
3676 /// write to memory.
3677 bool mayReadOrWriteMemory() const;
3678
3679 /// Returns true if this expression contains recipes that may have side
3680 /// effects.
3681 bool mayHaveSideEffects() const;
3682
3683 /// Returns true if this VPExpressionRecipe produces a single scalar.
3684 bool isVectorToScalar() const;
3685
3686protected:
3687#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3688 /// Print the recipe.
3689 void printRecipe(raw_ostream &O, const Twine &Indent,
3690 VPSlotTracker &SlotTracker) const override;
3691#endif
3692};
3693
3694/// VPPredInstPHIRecipe is a recipe for generating the phi nodes needed when
3695/// control converges back from a Branch-on-Mask. The phi nodes are needed in
3696/// order to merge values that are set under such a branch and feed their uses.
3697/// The phi nodes can be scalar or vector depending on the users of the value.
3698/// This recipe works in concert with VPBranchOnMaskRecipe.
3700public:
3701 /// Construct a VPPredInstPHIRecipe given \p PredInst whose value needs a phi
3702 /// nodes after merging back from a Branch-on-Mask.
3704 : VPSingleDefRecipe(VPRecipeBase::VPPredInstPHISC, PredV,
3705 PredV->getScalarType(), /*UV=*/nullptr, DL) {}
3706 ~VPPredInstPHIRecipe() override = default;
3707
3709 return new VPPredInstPHIRecipe(getOperand(0), getDebugLoc());
3710 }
3711
3712 VP_CLASSOF_IMPL(VPRecipeBase::VPPredInstPHISC)
3713
3714 /// Generates phi nodes for live-outs (from a replicate region) as needed to
3715 /// retain SSA form.
3716 void execute(VPTransformState &State) override;
3717
3718 /// Return the cost of this VPPredInstPHIRecipe.
3720 VPCostContext &Ctx) const override {
3721 // TODO: Compute accurate cost after retiring the legacy cost model.
3722 return 0;
3723 }
3724
3725protected:
3726#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3727 /// Print the recipe.
3728 void printRecipe(raw_ostream &O, const Twine &Indent,
3729 VPSlotTracker &SlotTracker) const override;
3730#endif
3731};
3732
3733/// A common mixin class for widening memory operations. An optional mask can be
3734/// provided as the last operand.
3736protected:
3738
3739 /// Alignment information for this memory access.
3741
3742 /// Whether the accessed addresses are consecutive.
3744
3745 /// Whether the memory access is masked.
3746 bool IsMasked = false;
3747
3748 void setMask(VPValue *Mask) {
3749 assert(!IsMasked && "cannot re-set mask");
3750 if (!Mask)
3751 return;
3752 assert(Mask->getScalarType()->isIntegerTy(1) &&
3753 "Mask must be an i1 (vector)");
3754 getAsRecipe()->addOperand(Mask);
3755 IsMasked = true;
3756 }
3757
3762
3763public:
3764 virtual ~VPWidenMemoryRecipe() = default;
3765
3766 /// Return a VPRecipeBase* to the current object.
3768 virtual const VPRecipeBase *getAsRecipe() const = 0;
3769
3770 /// Return whether the loaded-from / stored-to addresses are consecutive.
3771 bool isConsecutive() const { return Consecutive; }
3772
3773 /// Return the address accessed by this recipe.
3774 VPValue *getAddr() const { return getAsRecipe()->getOperand(0); }
3775
3776 /// Returns true if the recipe is masked.
3777 bool isMasked() const { return IsMasked; }
3778
3779 /// Return the mask used by this recipe. Note that a full mask is represented
3780 /// by a nullptr.
3781 VPValue *getMask() const {
3782 // Mask is optional and therefore the last operand.
3783 const VPRecipeBase *R = getAsRecipe();
3784 return isMasked() ? R->getOperand(R->getNumOperands() - 1) : nullptr;
3785 }
3786
3787 /// Returns the alignment of the memory access.
3788 Align getAlign() const { return Alignment; }
3789
3790 /// Return the cost of this VPWidenMemoryRecipe.
3791 InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const;
3792
3794};
3795
3796/// A recipe for widening load operations, using the address to load from and an
3797/// optional mask.
3799 public VPWidenMemoryRecipe {
3801 bool Consecutive, const VPIRMetadata &Metadata, DebugLoc DL)
3802 : VPSingleDefRecipe(VPRecipeBase::VPWidenLoadSC, {Addr}, Load.getType(),
3803 &Load, DL),
3804 VPWidenMemoryRecipe(Load, Consecutive, Metadata) {
3805 setMask(Mask);
3806 }
3807
3810 getMask(), Consecutive, *this, getDebugLoc());
3811 }
3812
3813 VP_CLASSOF_IMPL(VPRecipeBase::VPWidenLoadSC);
3814
3815 /// Generate a wide load or gather.
3816 void execute(VPTransformState &State) override;
3817
3818 /// Return the cost of this VPWidenLoadRecipe.
3820 VPCostContext &Ctx) const override {
3821 return VPWidenMemoryRecipe::computeCost(VF, Ctx);
3822 }
3823
3824 /// Returns true if the recipe only uses the first lane of operand \p Op.
3825 bool usesFirstLaneOnly(const VPValue *Op) const override {
3827 "Op must be an operand of the recipe");
3828 // Widened, consecutive loads operations only demand the first lane of
3829 // their address.
3830 return Op == getAddr() && isConsecutive();
3831 }
3832
3833protected:
3834 VPRecipeBase *getAsRecipe() override;
3835 const VPRecipeBase *getAsRecipe() const override;
3836
3837#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3838 /// Print the recipe.
3839 void printRecipe(raw_ostream &O, const Twine &Indent,
3840 VPSlotTracker &SlotTracker) const override;
3841#endif
3842};
3843
3844/// A recipe for widening load operations with vector-predication intrinsics,
3845/// using the address to load from, the explicit vector length and an optional
3846/// mask.
3848 : public VPSingleDefRecipe,
3849 public VPWidenMemoryRecipe {
3851 VPValue *Mask)
3852 : VPSingleDefRecipe(VPRecipeBase::VPWidenLoadEVLSC, {Addr, &EVL},
3853 L.getIngredient().getType(), &L.getIngredient(),
3854 L.getDebugLoc()),
3855 VPWidenMemoryRecipe(L.getIngredient(), L.isConsecutive(), L) {
3856 setMask(Mask);
3857 }
3858
3860 llvm_unreachable("cloning not supported");
3861 }
3862
3863 VP_CLASSOF_IMPL(VPRecipeBase::VPWidenLoadEVLSC)
3864
3865 /// Return the EVL operand.
3866 VPValue *getEVL() const { return getOperand(1); }
3867
3868 /// Generate the wide load or gather.
3869 void execute(VPTransformState &State) override;
3870
3871 /// Return the cost of this VPWidenLoadEVLRecipe.
3872 InstructionCost computeCost(ElementCount VF,
3873 VPCostContext &Ctx) const override;
3874
3875 /// Returns true if the recipe only uses the first lane of operand \p Op.
3876 bool usesFirstLaneOnly(const VPValue *Op) const override {
3878 "Op must be an operand of the recipe");
3879 // Widened loads only demand the first lane of EVL and consecutive loads
3880 // only demand the first lane of their address.
3881 return Op == getEVL() || (Op == getAddr() && isConsecutive());
3882 }
3883
3884protected:
3885 VPRecipeBase *getAsRecipe() override;
3886 const VPRecipeBase *getAsRecipe() const override;
3887
3888#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3889 /// Print the recipe.
3890 void printRecipe(raw_ostream &O, const Twine &Indent,
3891 VPSlotTracker &SlotTracker) const override;
3892#endif
3893};
3894
3895/// A recipe for widening store operations, using the stored value, the address
3896/// to store to and an optional mask.
3898 public VPWidenMemoryRecipe {
3900 VPValue *Mask, bool Consecutive,
3901 const VPIRMetadata &Metadata, DebugLoc DL)
3902 : VPRecipeBase(VPRecipeBase::VPWidenStoreSC, {Addr, StoredVal}, DL),
3903 VPWidenMemoryRecipe(Store, Consecutive, Metadata) {
3904 setMask(Mask);
3905 }
3906
3910 *this, getDebugLoc());
3911 }
3912
3913 VP_CLASSOF_IMPL(VPRecipeBase::VPWidenStoreSC);
3914
3915 /// Return the value stored by this recipe.
3916 VPValue *getStoredValue() const { return getOperand(1); }
3917
3918 /// Generate a wide store or scatter.
3919 void execute(VPTransformState &State) override;
3920
3921 /// Return the cost of this VPWidenStoreRecipe.
3923 VPCostContext &Ctx) const override {
3924 return VPWidenMemoryRecipe::computeCost(VF, Ctx);
3925 }
3926
3927 /// Returns true if the recipe only uses the first lane of operand \p Op.
3928 bool usesFirstLaneOnly(const VPValue *Op) const override {
3930 "Op must be an operand of the recipe");
3931 // Widened, consecutive stores only demand the first lane of their address,
3932 // unless the same operand is also stored.
3933 return Op == getAddr() && isConsecutive() && Op != getStoredValue();
3934 }
3935
3936protected:
3937 VPRecipeBase *getAsRecipe() override;
3938 const VPRecipeBase *getAsRecipe() const override;
3939
3940#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3941 /// Print the recipe.
3942 void printRecipe(raw_ostream &O, const Twine &Indent,
3943 VPSlotTracker &SlotTracker) const override;
3944#endif
3945};
3946
3947/// A recipe for widening store operations with vector-predication intrinsics,
3948/// using the value to store, the address to store to, the explicit vector
3949/// length and an optional mask.
3951 : public VPRecipeBase,
3952 public VPWidenMemoryRecipe {
3954 VPValue *StoredVal, VPValue &EVL, VPValue *Mask)
3955 : VPRecipeBase(VPRecipeBase::VPWidenStoreEVLSC, {Addr, StoredVal, &EVL},
3956 S.getDebugLoc()),
3957 VPWidenMemoryRecipe(S.getIngredient(), S.isConsecutive(), S) {
3958 setMask(Mask);
3959 }
3960
3962 llvm_unreachable("cloning not supported");
3963 }
3964
3965 VP_CLASSOF_IMPL(VPRecipeBase::VPWidenStoreEVLSC)
3966
3967 /// Return the address accessed by this recipe.
3968 VPValue *getStoredValue() const { return getOperand(1); }
3969
3970 /// Return the EVL operand.
3971 VPValue *getEVL() const { return getOperand(2); }
3972
3973 /// Generate the wide store or scatter.
3974 void execute(VPTransformState &State) override;
3975
3976 /// Return the cost of this VPWidenStoreEVLRecipe.
3977 InstructionCost computeCost(ElementCount VF,
3978 VPCostContext &Ctx) const override;
3979
3980 /// Returns true if the recipe only uses the first lane of operand \p Op.
3981 bool usesFirstLaneOnly(const VPValue *Op) const override {
3983 "Op must be an operand of the recipe");
3984 if (Op == getEVL()) {
3985 assert(getStoredValue() != Op && "unexpected store of EVL");
3986 return true;
3987 }
3988 // Widened, consecutive memory operations only demand the first lane of
3989 // their address, unless the same operand is also stored. That latter can
3990 // happen with opaque pointers.
3991 return Op == getAddr() && isConsecutive() && Op != getStoredValue();
3992 }
3993
3994protected:
3995 VPRecipeBase *getAsRecipe() override;
3996 const VPRecipeBase *getAsRecipe() const override;
3997
3998#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3999 /// Print the recipe.
4000 void printRecipe(raw_ostream &O, const Twine &Indent,
4001 VPSlotTracker &SlotTracker) const override;
4002#endif
4003};
4004
4005/// Recipe to expand a SCEV expression.
4007 const SCEV *Expr;
4008
4009public:
4010 VPExpandSCEVRecipe(const SCEV *Expr);
4011
4012 ~VPExpandSCEVRecipe() override = default;
4013
4014 VPExpandSCEVRecipe *clone() override { return new VPExpandSCEVRecipe(Expr); }
4015
4016 VP_CLASSOF_IMPL(VPRecipeBase::VPExpandSCEVSC)
4017
4018 void execute(VPTransformState &State) override {
4019 llvm_unreachable("SCEV expressions must be expanded before final execute");
4020 }
4021
4022 /// Return the cost of this VPExpandSCEVRecipe.
4024 VPCostContext &Ctx) const override {
4025 // TODO: Compute accurate cost after retiring the legacy cost model.
4026 return 0;
4027 }
4028
4029 const SCEV *getSCEV() const { return Expr; }
4030
4031protected:
4032#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4033 /// Print the recipe.
4034 void printRecipe(raw_ostream &O, const Twine &Indent,
4035 VPSlotTracker &SlotTracker) const override;
4036#endif
4037};
4038
4039/// A recipe for generating the active lane mask for the vector loop that is
4040/// used to predicate the vector operations.
4042public:
4044 : VPHeaderPHIRecipe(VPRecipeBase::VPActiveLaneMaskPHISC, nullptr,
4045 StartMask, DL) {}
4046
4047 ~VPActiveLaneMaskPHIRecipe() override = default;
4048
4051 if (getNumOperands() == 2)
4052 R->addBackedgeValue(getOperand(1));
4053 return R;
4054 }
4055
4056 VP_CLASSOF_IMPL(VPRecipeBase::VPActiveLaneMaskPHISC)
4057
4058 /// Generate the active lane mask phi of the vector loop.
4059 void execute(VPTransformState &State) override;
4060
4061protected:
4062#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4063 /// Print the recipe.
4064 void printRecipe(raw_ostream &O, const Twine &Indent,
4065 VPSlotTracker &SlotTracker) const override;
4066#endif
4067};
4068
4069/// A recipe for generating the phi node tracking the current scalar iteration
4070/// index. It starts at the start value of the canonical induction and gets
4071/// incremented by the number of scalar iterations processed by the vector loop
4072/// iteration. The increment does not have to be loop invariant.
4074public:
4076 : VPHeaderPHIRecipe(VPRecipeBase::VPCurrentIterationPHISC, nullptr,
4077 StartIV, DL) {}
4078
4079 ~VPCurrentIterationPHIRecipe() override = default;
4080
4082 llvm_unreachable("cloning not implemented yet");
4083 }
4084
4085 VP_CLASSOF_IMPL(VPRecipeBase::VPCurrentIterationPHISC)
4086
4087 void execute(VPTransformState &State) override {
4088 llvm_unreachable("cannot execute this recipe, should be replaced by a "
4089 "scalar phi recipe");
4090 }
4091
4092 /// Return the cost of this VPCurrentIterationPHIRecipe.
4094 VPCostContext &Ctx) const override {
4095 // For now, match the behavior of the legacy cost model.
4096 return 0;
4097 }
4098
4099 /// Returns true if the recipe only uses the first lane of operand \p Op.
4100 bool usesFirstLaneOnly(const VPValue *Op) const override {
4102 "Op must be an operand of the recipe");
4103 return true;
4104 }
4105
4106protected:
4107#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4108 /// Print the recipe.
4109 LLVM_ABI_FOR_TEST void printRecipe(raw_ostream &O, const Twine &Indent,
4110 VPSlotTracker &SlotTracker) const override;
4111#endif
4112};
4113
4114/// A Recipe for widening the canonical induction variable of the vector loop.
4115/// First operand is the canonical IV recipe, a second step operand (VF * Part)
4116/// is added during unrolling.
4118public:
4120 const VPIRFlags::WrapFlagsTy &Flags = {})
4121 : VPRecipeWithIRFlags(VPRecipeBase::VPWidenCanonicalIVSC, CanonicalIV,
4122 CanonicalIV->getType(), Flags) {}
4123
4124 ~VPWidenCanonicalIVRecipe() override = default;
4125
4127 auto *WideCanIV =
4129 if (VPValue *Step = getStepValue())
4130 WideCanIV->addPerPartStep(Step);
4131 return WideCanIV;
4132 }
4133
4134 VP_CLASSOF_IMPL(VPRecipeBase::VPWidenCanonicalIVSC)
4135
4136 void execute(VPTransformState &State) override {
4137 llvm_unreachable("Expected prior expansion of WidenCanonicalIV recipes");
4138 }
4139
4140 /// Return the cost of this VPWidenCanonicalIVPHIRecipe.
4142 VPCostContext &Ctx) const override {
4143 // TODO: Compute accurate cost after retiring the legacy cost model.
4144 return 0;
4145 }
4146
4147 /// Return the canonical IV being widened.
4151
4153 return getNumOperands() == 2 ? getOperand(1) : nullptr;
4154 }
4155
4156 /// Add the per-part step (VF * Part) used for unrolled parts.
4158 assert(Step->getScalarType() == getScalarType() &&
4159 "per-part step must have the same type as the canonical IV");
4160 VPUser::addOperand(Step);
4161 }
4162
4163protected:
4164#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4165 /// Print the recipe.
4166 void printRecipe(raw_ostream &O, const Twine &Indent,
4167 VPSlotTracker &SlotTracker) const override;
4168#endif
4169};
4170
4171/// A recipe for converting \p Current into \p Start + \p Current * \p Step.
4172/// FastMathFlags are derived from the \p FPBinOp in the case of FP inductions,
4173/// and the passed NoWrap \p Flags apply in the case of Ptr and Int inductions.
4175 /// Kind of the induction.
4177 /// If not nullptr, the floating point induction binary operator. Must be set
4178 /// for floating point inductions.
4179 const FPMathOperator *FPBinOp;
4180
4181public:
4183 const FPMathOperator *FPBinOp, VPValue *Start,
4184 VPValue *Current, VPValue *Step,
4185 const VPIRFlags::WrapFlagsTy &Flags = {})
4186 : VPRecipeWithIRFlags(VPRecipeBase::VPDerivedIVSC, {Start, Current, Step},
4187 Start->getScalarType(), Flags),
4188 Kind(Kind), FPBinOp(FPBinOp) {}
4189
4190 ~VPDerivedIVRecipe() override = default;
4191
4193 return new VPDerivedIVRecipe(Kind, FPBinOp, getStartValue(), getOperand(1),
4195 }
4196
4197 VP_CLASSOF_IMPL(VPRecipeBase::VPDerivedIVSC)
4198
4199 void execute(VPTransformState &State) override {
4200 llvm_unreachable("Expected prior expansion of this recipe");
4201 }
4202
4203 /// Return the cost of this VPDerivedIVRecipe.
4205 VPCostContext &Ctx) const override;
4206
4207 VPValue *getStartValue() const { return getOperand(0); }
4208 VPValue *getIndex() const { return getOperand(1); }
4209 VPValue *getStepValue() const { return getOperand(2); }
4210 const FPMathOperator *getFPBinOp() const { return FPBinOp; }
4212
4213 /// Returns true if the recipe only uses the first lane of operand \p Op.
4214 bool usesFirstLaneOnly(const VPValue *Op) const override {
4216 "Op must be an operand of the recipe");
4217 return true;
4218 }
4219
4220protected:
4221#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4222 /// Print the recipe.
4223 void printRecipe(raw_ostream &O, const Twine &Indent,
4224 VPSlotTracker &SlotTracker) const override;
4225#endif
4226};
4227
4228/// A recipe for handling phi nodes of integer and floating-point inductions,
4229/// producing their scalar values. Before unrolling by UF the recipe represents
4230/// the VF*UF scalar values to be produced, or UF scalar values if only first
4231/// lane is used, and has 3 operands: IV, step and VF. Unrolling adds one extra
4232/// operand StartIndex to all unroll parts except part 0, as the recipe
4233/// represents the VF scalar values (this number of values is taken from
4234/// State.VF rather than from the VF operand) starting at IV + StartIndex.
4236 Instruction::BinaryOps InductionOpcode;
4237
4238public:
4242 : VPRecipeWithIRFlags(VPRecipeBase::VPScalarIVStepsSC, {IV, Step, VF},
4243 IV->getScalarType(), FMFs, DL),
4244 InductionOpcode(Opcode) {}
4245
4246 ~VPScalarIVStepsRecipe() override = default;
4247
4249 auto *NewR = new VPScalarIVStepsRecipe(
4250 getOperand(0), getOperand(1), getOperand(2), InductionOpcode,
4252 if (VPValue *StartIndex = getStartIndex())
4253 NewR->setStartIndex(StartIndex);
4254 return NewR;
4255 }
4256
4257 VP_CLASSOF_IMPL(VPRecipeBase::VPScalarIVStepsSC)
4258
4259 /// Generate the scalarized versions of the phi node as needed by their users.
4260 void execute(VPTransformState &State) override;
4261
4262 /// Return the cost of this VPScalarIVStepsRecipe.
4263 InstructionCost computeCost(ElementCount VF,
4264 VPCostContext &Ctx) const override;
4265
4266 VPValue *getStepValue() const { return getOperand(1); }
4267
4268 /// Return the number of scalars to produce per unroll part, used to compute
4269 /// StartIndex during unrolling.
4270 VPValue *getVFValue() const { return getOperand(2); }
4271
4272 /// Return the StartIndex, or null if known to be zero, valid only after
4273 /// unrolling.
4275 return getNumOperands() == 4 ? getOperand(3) : nullptr;
4276 }
4277
4278 /// Set or add the StartIndex operand.
4279 void setStartIndex(VPValue *StartIndex) {
4280 if (getNumOperands() == 4)
4281 setOperand(3, StartIndex);
4282 else
4283 addOperand(StartIndex);
4284 }
4285
4286 /// Returns true if this recipe produces scalar values for all VF lanes.
4287 bool doesGeneratePerAllLanes() const;
4288
4289 /// Returns true if the recipe only uses the first lane of operand \p Op.
4290 bool usesFirstLaneOnly(const VPValue *Op) const override {
4292 "Op must be an operand of the recipe");
4293 return true;
4294 }
4295
4296 Instruction::BinaryOps getInductionOpcode() const { return InductionOpcode; }
4297
4298protected:
4299#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4300 /// Print the recipe.
4301 void printRecipe(raw_ostream &O, const Twine &Indent,
4302 VPSlotTracker &SlotTracker) const override;
4303#endif
4304};
4305
4306/// CastInfo helper for casting from VPRecipeBase to a mixin class that is not
4307/// part of the VPRecipeBase class hierarchy (e.g. VPPhiAccessors,
4308/// VPIRMetadata).
4309namespace vpdetail {
4310template <typename VPMixin, typename... RecipeTys>
4312 : public DefaultDoCastIfPossible<VPMixin *, VPRecipeBase *,
4313 CastInfoMixinImpl<VPMixin, RecipeTys...>> {
4314 static_assert((std::is_base_of_v<VPMixin, RecipeTys> && ...),
4315 "Each type in RecipeTys must derive from VPMixin");
4316
4317 /// Used by isa.
4318 static bool isPossible(VPRecipeBase *R) { return isa<RecipeTys...>(R); }
4319
4320 /// Used by cast.
4321 static VPMixin *doCast(VPRecipeBase *R) {
4322 VPMixin *Out = nullptr;
4323 ((Out = dyn_cast<RecipeTys>(R)) || ...);
4324 assert(Out && "Illegal recipe for cast");
4325 return Out;
4326 }
4327 static VPMixin *castFailed() { return nullptr; }
4328};
4329} // namespace vpdetail
4330
4331/// Support casting from VPRecipeBase -> VPPhiAccessors.
4332template <>
4336
4337template <>
4342template <>
4344 : public ForwardToPointerCast<VPPhiAccessors, VPRecipeBase *,
4345 CastInfo<VPPhiAccessors, VPRecipeBase *>> {};
4346
4347/// Support casting from VPRecipeBase / VPUser -> VPWidenMemoryRecipe.
4348template <>
4353template <>
4358
4359/// Support casting from VPRecipeBase -> VPIRMetadata.
4360template <>
4366
4367template <>
4372template <>
4374 : public ForwardToPointerCast<VPIRMetadata, VPRecipeBase *,
4375 CastInfo<VPIRMetadata, VPRecipeBase *>> {};
4376
4377/// VPBasicBlock serves as the leaf of the Hierarchical Control-Flow Graph. It
4378/// holds a sequence of zero or more VPRecipe's each representing a sequence of
4379/// output IR instructions. All PHI-like recipes must come before any non-PHI recipes.
4380class LLVM_ABI_FOR_TEST VPBasicBlock : public VPBlockBase {
4381 friend class VPlan;
4382
4383 /// Use VPlan::createVPBasicBlock to create VPBasicBlocks.
4384 VPBasicBlock(const Twine &Name = "", VPRecipeBase *Recipe = nullptr)
4385 : VPBlockBase(VPBasicBlockSC, Name.str()) {
4386 if (Recipe)
4387 appendRecipe(Recipe);
4388 }
4389
4390public:
4392
4393protected:
4394 /// The VPRecipes held in the order of output instructions to generate.
4396
4397 VPBasicBlock(VPBlockTy BlockSC, const Twine &Name = "")
4398 : VPBlockBase(BlockSC, Name.str()) {}
4399
4400public:
4401 ~VPBasicBlock() override {
4402 while (!Recipes.empty())
4403 Recipes.pop_back();
4404 }
4405
4406 /// Instruction iterators...
4411
4412 //===--------------------------------------------------------------------===//
4413 /// Recipe iterator methods
4414 ///
4415 inline iterator begin() { return Recipes.begin(); }
4416 inline const_iterator begin() const { return Recipes.begin(); }
4417 inline iterator end() { return Recipes.end(); }
4418 inline const_iterator end() const { return Recipes.end(); }
4419
4420 inline reverse_iterator rbegin() { return Recipes.rbegin(); }
4421 inline const_reverse_iterator rbegin() const { return Recipes.rbegin(); }
4422 inline reverse_iterator rend() { return Recipes.rend(); }
4423 inline const_reverse_iterator rend() const { return Recipes.rend(); }
4424
4425 inline size_t size() const { return Recipes.size(); }
4426 inline bool empty() const { return Recipes.empty(); }
4427 inline const VPRecipeBase &front() const { return Recipes.front(); }
4428 inline VPRecipeBase &front() { return Recipes.front(); }
4429 inline const VPRecipeBase &back() const { return Recipes.back(); }
4430 inline VPRecipeBase &back() { return Recipes.back(); }
4431
4432 /// Returns a reference to the list of recipes.
4434
4435 /// Returns a pointer to a member of the recipe list.
4436 static RecipeListTy VPBasicBlock::*getSublistAccess(VPRecipeBase *) {
4437 return &VPBasicBlock::Recipes;
4438 }
4439
4440 /// Method to support type inquiry through isa, cast, and dyn_cast.
4441 static inline bool classof(const VPBlockBase *V) {
4442 return V->getVPBlockID() == VPBlockBase::VPBasicBlockSC ||
4443 V->getVPBlockID() == VPBlockBase::VPIRBasicBlockSC;
4444 }
4445
4446 void insert(VPRecipeBase *Recipe, iterator InsertPt) {
4447 assert(Recipe && "No recipe to append.");
4448 assert(!Recipe->Parent && "Recipe already in VPlan");
4449 Recipe->Parent = this;
4450 Recipes.insert(InsertPt, Recipe);
4451 }
4452
4453 /// Augment the existing recipes of a VPBasicBlock with an additional
4454 /// \p Recipe as the last recipe.
4455 void appendRecipe(VPRecipeBase *Recipe) { insert(Recipe, end()); }
4456
4457 /// The method which generates the output IR instructions that correspond to
4458 /// this VPBasicBlock, thereby "executing" the VPlan.
4459 void execute(VPTransformState *State) override;
4460
4461 /// Return the cost of this VPBasicBlock.
4462 InstructionCost cost(ElementCount VF, VPCostContext &Ctx) override;
4463
4464 /// Return the position of the first non-phi node recipe in the block.
4465 iterator getFirstNonPhi();
4466
4467 /// Returns an iterator range over the PHI-like recipes in the block.
4471
4472 /// Split current block at \p SplitAt by inserting a new block between the
4473 /// current block and its successors and moving all recipes starting at
4474 /// SplitAt to the new block. Returns the new block.
4475 VPBasicBlock *splitAt(iterator SplitAt);
4476
4477 VPRegionBlock *getEnclosingLoopRegion();
4478 const VPRegionBlock *getEnclosingLoopRegion() const;
4479
4480#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4481 /// Print this VPBsicBlock to \p O, prefixing all lines with \p Indent. \p
4482 /// SlotTracker is used to print unnamed VPValue's using consequtive numbers.
4483 ///
4484 /// Note that the numbering is applied to the whole VPlan, so printing
4485 /// individual blocks is consistent with the whole VPlan printing.
4486 void print(raw_ostream &O, const Twine &Indent,
4487 VPSlotTracker &SlotTracker) const override;
4488 using VPBlockBase::print; // Get the print(raw_stream &O) version.
4489#endif
4490
4491 /// If the block has multiple successors, return the branch recipe terminating
4492 /// the block. If there are no or only a single successor, return nullptr;
4493 VPRecipeBase *getTerminator();
4494 const VPRecipeBase *getTerminator() const;
4495
4496 /// Returns true if the block is exiting it's parent region.
4497 bool isExiting() const;
4498
4499 /// Clone the current block and it's recipes, without updating the operands of
4500 /// the cloned recipes.
4501 VPBasicBlock *clone() override;
4502
4503 /// Returns the predecessor block at index \p Idx with the predecessors as per
4504 /// the corresponding plain CFG. If the block is an entry block to a region,
4505 /// the first predecessor is the single predecessor of a region, and the
4506 /// second predecessor is the exiting block of the region.
4507 const VPBasicBlock *getCFGPredecessor(unsigned Idx) const;
4508
4509protected:
4510 /// Execute the recipes in the IR basic block \p BB.
4511 void executeRecipes(VPTransformState *State, BasicBlock *BB);
4512
4513 /// Connect the VPBBs predecessors' in the VPlan CFG to the IR basic block
4514 /// generated for this VPBB.
4515 void connectToPredecessors(VPTransformState &State);
4516
4517private:
4518 /// Create an IR BasicBlock to hold the output instructions generated by this
4519 /// VPBasicBlock, and return it. Update the CFGState accordingly.
4520 BasicBlock *createEmptyBasicBlock(VPTransformState &State);
4521};
4522
4523inline const VPBasicBlock *
4525 return getAsRecipe()->getParent()->getCFGPredecessor(Idx);
4526}
4527
4528/// A special type of VPBasicBlock that wraps an existing IR basic block.
4529/// Recipes of the block get added before the first non-phi instruction in the
4530/// wrapped block.
4531/// Note: At the moment, VPIRBasicBlock can only be used to wrap VPlan's
4532/// preheader block.
4533class VPIRBasicBlock : public VPBasicBlock {
4534 friend class VPlan;
4535
4536 BasicBlock *IRBB;
4537
4538 /// Use VPlan::createVPIRBasicBlock to create VPIRBasicBlocks.
4539 VPIRBasicBlock(BasicBlock *IRBB)
4540 : VPBasicBlock(VPIRBasicBlockSC,
4541 (Twine("ir-bb<") + IRBB->getName() + Twine(">")).str()),
4542 IRBB(IRBB) {}
4543
4544public:
4545 ~VPIRBasicBlock() override = default;
4546
4547 static inline bool classof(const VPBlockBase *V) {
4548 return V->getVPBlockID() == VPBlockBase::VPIRBasicBlockSC;
4549 }
4550
4551 /// The method which generates the output IR instructions that correspond to
4552 /// this VPBasicBlock, thereby "executing" the VPlan.
4553 void execute(VPTransformState *State) override;
4554
4555 VPIRBasicBlock *clone() override;
4556
4557 BasicBlock *getIRBasicBlock() const { return IRBB; }
4558};
4559
4560/// Track information about the canonical IV and header mask of a loop region.
4561/// TODO: Have it also track the canonical IV increment, subject of NUW flag.
4563 /// VPRegionValue for the canonical IV, whose allocation is managed by
4564 /// VPCanonicalIVInfo.
4565 std::unique_ptr<VPRegionValue> CanIV;
4566
4567 /// Optional VPRegionValue for the header mask, set when tail folding.
4568 std::unique_ptr<VPRegionValue> HeaderMask;
4569
4570 /// Whether the increment of the canonical IV may unsigned wrap or not.
4571 bool HasNUW = true;
4572
4573public:
4575 : CanIV(std::make_unique<VPRegionValue>(Ty, DL, Region)) {}
4576
4577 VPRegionValue *getRegionValue() { return CanIV.get(); }
4578 const VPRegionValue *getRegionValue() const { return CanIV.get(); }
4579
4580 VPRegionValue *getHeaderMask() const { return HeaderMask.get(); }
4581
4582 /// Create the header mask for the region and return it. Must only be called
4583 /// when no header mask exists yet.
4585 assert(!HeaderMask && "Header mask already created");
4586 HeaderMask = std::make_unique<VPRegionValue>(
4587 Type::getInt1Ty(CanIV->getType()->getContext()), DebugLoc::getUnknown(),
4588 CanIV->getDefiningRegion());
4589 return HeaderMask.get();
4590 }
4591
4592 bool hasNUW() const { return HasNUW; }
4593
4594 void clearNUW() { HasNUW = false; }
4595};
4596
4597/// VPRegionBlock represents a collection of VPBasicBlocks and VPRegionBlocks
4598/// which form a Single-Entry-Single-Exiting subgraph of the output IR CFG.
4599/// A VPRegionBlock may indicate that its contents are to be replicated several
4600/// times. This is designed to support predicated scalarization, in which a
4601/// scalar if-then code structure needs to be generated VF * UF times. Having
4602/// this replication indicator helps to keep a single model for multiple
4603/// candidate VF's. The actual replication takes place only once the desired VF
4604/// and UF have been determined.
4605class LLVM_ABI_FOR_TEST VPRegionBlock : public VPBlockBase {
4606 friend class VPlan;
4607
4608 /// Hold the Single Entry of the SESE region modelled by the VPRegionBlock.
4609 VPBlockBase *Entry;
4610
4611 /// Hold the Single Exiting block of the SESE region modelled by the
4612 /// VPRegionBlock.
4613 VPBlockBase *Exiting;
4614
4615 /// Holds the Canonical IV of the loop region along with additional
4616 /// information. If CanIVInfo is nullptr, the region is a replicating region.
4617 /// Loop regions retain their canonical IVs until they are dissolved, even if
4618 /// the canonical IV has no users.
4619 std::unique_ptr<VPCanonicalIVInfo> CanIVInfo;
4620
4621 /// Use VPlan::createLoopRegion() and VPlan::createReplicateRegion() to create
4622 /// VPRegionBlocks.
4623 VPRegionBlock(VPBlockBase *Entry, VPBlockBase *Exiting,
4624 const std::string &Name = "")
4625 : VPBlockBase(VPRegionBlockSC, Name), Entry(Entry), Exiting(Exiting) {
4626 if (Entry) {
4627 assert(!Entry->hasPredecessors() && "Entry block has predecessors.");
4628 assert(Exiting && "Must also pass Exiting if Entry is passed.");
4629 assert(!Exiting->hasSuccessors() && "Exit block has successors.");
4630 Entry->setParent(this);
4631 Exiting->setParent(this);
4632 }
4633 }
4634
4635 VPRegionBlock(Type *CanIVTy, DebugLoc DL, VPBlockBase *Entry,
4636 VPBlockBase *Exiting, const std::string &Name = "")
4637 : VPRegionBlock(Entry, Exiting, Name) {
4638 CanIVInfo = std::make_unique<VPCanonicalIVInfo>(CanIVTy, DL, this);
4639 }
4640
4641public:
4642 ~VPRegionBlock() override = default;
4643
4644 /// Method to support type inquiry through isa, cast, and dyn_cast.
4645 static inline bool classof(const VPBlockBase *V) {
4646 return V->getVPBlockID() == VPBlockBase::VPRegionBlockSC;
4647 }
4648
4649 const VPBlockBase *getEntry() const { return Entry; }
4650 VPBlockBase *getEntry() { return Entry; }
4651
4652 /// Set \p EntryBlock as the entry VPBlockBase of this VPRegionBlock. \p
4653 /// EntryBlock must have no predecessors.
4654 void setEntry(VPBlockBase *EntryBlock) {
4655 assert(!EntryBlock->hasPredecessors() &&
4656 "Entry block cannot have predecessors.");
4657 Entry = EntryBlock;
4658 EntryBlock->setParent(this);
4659 }
4660
4661 const VPBlockBase *getExiting() const { return Exiting; }
4662 VPBlockBase *getExiting() { return Exiting; }
4663
4664 /// Set \p ExitingBlock as the exiting VPBlockBase of this VPRegionBlock. \p
4665 /// ExitingBlock must have no successors.
4666 void setExiting(VPBlockBase *ExitingBlock) {
4667 assert(!ExitingBlock->hasSuccessors() &&
4668 "Exit block cannot have successors.");
4669 Exiting = ExitingBlock;
4670 ExitingBlock->setParent(this);
4671 }
4672
4673 /// Returns the pre-header VPBasicBlock of the loop region.
4675 assert(!isReplicator() && "should only get pre-header of loop regions");
4676 return getSinglePredecessor()->getExitingBasicBlock();
4677 }
4678
4679 /// An indicator whether this region is to generate multiple replicated
4680 /// instances of output IR corresponding to its VPBlockBases.
4681 bool isReplicator() const { return !CanIVInfo; }
4682
4683 /// Return the VPBranchOnMaskRecipe from the entry block of this replicating
4684 /// region.
4685 const VPBranchOnMaskRecipe *getEntryBranchOnMask() const;
4687 return const_cast<VPBranchOnMaskRecipe *>(
4688 static_cast<const VPRegionBlock *>(this)->getEntryBranchOnMask());
4689 }
4690
4691 /// The method which generates the output IR instructions that correspond to
4692 /// this VPRegionBlock, thereby "executing" the VPlan.
4693 void execute(VPTransformState *State) override;
4694
4695 // Return the cost of this region.
4696 InstructionCost cost(ElementCount VF, VPCostContext &Ctx) override;
4697
4698#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4699 /// Print this VPRegionBlock to \p O (recursively), prefixing all lines with
4700 /// \p Indent. \p SlotTracker is used to print unnamed VPValue's using
4701 /// consequtive numbers.
4702 ///
4703 /// Note that the numbering is applied to the whole VPlan, so printing
4704 /// individual regions is consistent with the whole VPlan printing.
4705 void print(raw_ostream &O, const Twine &Indent,
4706 VPSlotTracker &SlotTracker) const override;
4707 using VPBlockBase::print; // Get the print(raw_stream &O) version.
4708#endif
4709
4710 /// Clone all blocks in the single-entry single-exit region of the block and
4711 /// their recipes without updating the operands of the cloned recipes.
4712 VPRegionBlock *clone() override;
4713
4714 /// Remove the current region from its VPlan, connecting its predecessor to
4715 /// its entry, and its exiting block to its successor.
4716 void dissolveToCFGLoop();
4717
4718 /// Get the canonical IV increment instruction if it exists. Otherwise, create
4719 /// a new increment before the terminator and return it. The canonical IV
4720 /// increment is subject to DCE if unused, unlike the canonical IV itself.
4721 VPInstruction *getOrCreateCanonicalIVIncrement();
4722
4723 /// Return the canonical induction variable of the region, null for
4724 /// replicating regions.
4726 return CanIVInfo ? CanIVInfo->getRegionValue() : nullptr;
4727 }
4729 return CanIVInfo ? CanIVInfo->getRegionValue() : nullptr;
4730 }
4731
4732 /// Return the type of the canonical IV for loop regions.
4734 return CanIVInfo->getRegionValue()->getType();
4735 }
4736
4737 /// Return the header mask of the region, or null if not set.
4739 return CanIVInfo ? CanIVInfo->getHeaderMask() : nullptr;
4740 }
4741
4742 /// Return the header mask if it exists and is used, or null otherwise. The
4743 /// mask is materialized into concrete recipes only after costing, so cost and
4744 /// codegen accounting sites use this to skip an unused mask.
4746 VPRegionValue *HeaderMask = getHeaderMask();
4747 return HeaderMask && HeaderMask->getNumUsers() > 0 ? HeaderMask : nullptr;
4748 }
4749
4750 /// Create the header mask for the region and return it. Must only be called
4751 /// on loop regions that don't already have a header mask.
4753 assert(CanIVInfo && "Can only create header mask for loop regions");
4754 return CanIVInfo->createHeaderMask();
4755 }
4756
4757 /// Return the region values of the loop region (canonical IV, header mask)
4758 /// or an empty vector for replicate regions.
4760 if (!CanIVInfo)
4761 return {};
4762 SmallVector<VPRegionValue *, 2> R = {CanIVInfo->getRegionValue()};
4763 if (auto *HM = CanIVInfo->getHeaderMask())
4764 R.push_back(HM);
4765 return R;
4766 }
4767
4768 /// Indicates if NUW is set for the canonical IV increment, for loop regions.
4769 bool hasCanonicalIVNUW() const { return CanIVInfo->hasNUW(); }
4770
4771 /// Unsets NUW for the canonical IV increment \p Increment, for loop regions.
4773 assert(Increment && "Must provide increment to clear");
4774 Increment->dropPoisonGeneratingFlags();
4775 CanIVInfo->clearNUW();
4776 }
4777};
4778
4780 return getParent()->getParent();
4781}
4782
4784 return getParent()->getParent();
4785}
4786
4787/// VPlan models a candidate for vectorization, encoding various decisions take
4788/// to produce efficient output IR, including which branches, basic-blocks and
4789/// output IR instructions to generate, and their cost. VPlan holds a
4790/// Hierarchical-CFG of VPBasicBlocks and VPRegionBlocks rooted at an Entry
4791/// VPBasicBlock.
4792class VPlan {
4793 friend class VPlanPrinter;
4794 friend class VPSlotTracker;
4795
4796 /// VPBasicBlock corresponding to the original preheader. Used to place
4797 /// VPExpandSCEV recipes for expressions used during skeleton creation and the
4798 /// rest of VPlan execution.
4799 /// When this VPlan is used for the epilogue vector loop, the entry will be
4800 /// replaced by a new entry block created during skeleton creation.
4801 VPBasicBlock *Entry;
4802
4803 /// VPIRBasicBlock wrapping the header of the original scalar loop.
4804 VPIRBasicBlock *ScalarHeader;
4805
4806 /// Immutable list of VPIRBasicBlocks wrapping the exit blocks of the original
4807 /// scalar loop. Note that some exit blocks may be unreachable at the moment,
4808 /// e.g. if the scalar epilogue always executes.
4810
4811 /// Holds the VFs applicable to this VPlan.
4813
4814 /// Holds the UFs applicable to this VPlan. If empty, the VPlan is valid for
4815 /// any UF.
4817
4818 /// Holds the name of the VPlan, for printing.
4819 std::string Name;
4820
4821 /// Represents the trip count of the original loop, for folding
4822 /// the tail.
4823 VPValue *TripCount = nullptr;
4824
4825 /// Represents the backedge taken count of the original loop, for folding
4826 /// the tail. It equals TripCount - 1.
4827 VPSymbolicValue *BackedgeTakenCount = nullptr;
4828
4829 /// Represents the vector trip count.
4830 VPSymbolicValue VectorTripCount;
4831
4832 /// Represents the vectorization factor of the loop.
4833 VPSymbolicValue VF;
4834
4835 /// Represents the unroll factor of the loop.
4836 VPSymbolicValue UF;
4837
4838 /// Represents the loop-invariant VF * UF of the vector loop region.
4839 VPSymbolicValue VFxUF;
4840
4841 /// Contains all the external definitions created for this VPlan, as a mapping
4842 /// from IR Values to VPIRValues.
4844
4845 /// Blocks allocated and owned by the VPlan. They will be deleted once the
4846 /// VPlan is destroyed.
4847 SmallVector<VPBlockBase *> CreatedBlocks;
4848
4849 /// Construct a VPlan with \p Entry to the plan and with \p ScalarHeader
4850 /// wrapping the original header of the scalar loop. The vector loop will have
4851 /// index type \p IdxTy.
4852 VPlan(VPBasicBlock *Entry, VPIRBasicBlock *ScalarHeader, Type *IdxTy)
4853 : Entry(Entry), ScalarHeader(ScalarHeader), VectorTripCount(IdxTy),
4854 VF(IdxTy), UF(IdxTy), VFxUF(IdxTy) {
4855 Entry->setPlan(this);
4856 assert(ScalarHeader->getNumSuccessors() == 0 &&
4857 "scalar header must be a leaf node");
4858 }
4859
4860public:
4861 /// Construct a VPlan for \p L. This will create VPIRBasicBlocks wrapping the
4862 /// original preheader and scalar header of \p L, to be used as entry and
4863 /// scalar header blocks of the new VPlan. The vector loop will have index
4864 /// type \p IdxTy.
4865 VPlan(Loop *L, Type *IdxTy);
4866
4867 /// Construct a VPlan with a new VPBasicBlock as entry, a VPIRBasicBlock
4868 /// wrapping \p ScalarHeaderBB and vector loop index of type \p IdxTy.
4869 VPlan(BasicBlock *ScalarHeaderBB, Type *IdxTy)
4870 : VectorTripCount(IdxTy), VF(IdxTy), UF(IdxTy), VFxUF(IdxTy) {
4871 setEntry(createVPBasicBlock("preheader"));
4872 ScalarHeader = createVPIRBasicBlock(ScalarHeaderBB);
4873 }
4874
4876
4878 Entry = VPBB;
4879 VPBB->setPlan(this);
4880 }
4881
4882 /// Generate the IR code for this VPlan.
4883 void execute(VPTransformState *State);
4884
4885 /// Return the cost of this plan.
4887
4888 VPBasicBlock *getEntry() { return Entry; }
4889 const VPBasicBlock *getEntry() const { return Entry; }
4890
4891 /// Returns the preheader of the vector loop region, if one exists, or null
4892 /// otherwise.
4894 const VPRegionBlock *VectorRegion = getVectorLoopRegion();
4895 return VectorRegion
4896 ? cast<VPBasicBlock>(VectorRegion->getSinglePredecessor())
4897 : nullptr;
4898 }
4899
4900 /// Returns the VPRegionBlock of the vector loop.
4903
4904 /// Returns true if this VPlan is for an outer loop, i.e., its vector
4905 /// loop region contains a nested loop region.
4906 LLVM_ABI_FOR_TEST bool isOuterLoop() const;
4907
4908 /// Returns true if the vector loop region is tail-folded.
4909 bool hasTailFolded() const {
4910 const VPRegionBlock *LoopRegion = getVectorLoopRegion();
4911 return LoopRegion && LoopRegion->getHeaderMask();
4912 }
4913
4914 /// Returns the 'middle' block of the plan, that is the block that selects
4915 /// whether to execute the scalar tail loop or the exit block from the loop
4916 /// latch. If there is an early exit from the vector loop, the middle block
4917 /// conceptully has the early exit block as third successor, split accross 2
4918 /// VPBBs. In that case, the second VPBB selects whether to execute the scalar
4919 /// tail loop or the exit block. If the scalar tail loop or exit block are
4920 /// known to always execute, the middle block may branch directly to that
4921 /// block. This function cannot be called once the vector loop region has been
4922 /// removed.
4924 VPRegionBlock *LoopRegion = getVectorLoopRegion();
4925 assert(
4926 LoopRegion &&
4927 "cannot call the function after vector loop region has been removed");
4928 // The middle block is always the last successor of the region.
4929 return cast<VPBasicBlock>(LoopRegion->getSuccessors().back());
4930 }
4931
4933 return const_cast<VPlan *>(this)->getMiddleBlock();
4934 }
4935
4936 /// Return the VPBasicBlock for the preheader of the scalar loop.
4939 getScalarHeader()->getSinglePredecessor());
4940 }
4941
4942 /// Return the VPIRBasicBlock wrapping the header of the scalar loop.
4943 VPIRBasicBlock *getScalarHeader() const { return ScalarHeader; }
4944
4945 /// Return an ArrayRef containing VPIRBasicBlocks wrapping the exit blocks of
4946 /// the original scalar loop.
4947 ArrayRef<VPIRBasicBlock *> getExitBlocks() const { return ExitBlocks; }
4948
4949 /// Returns true if \p VPBB is an exit block.
4950 bool isExitBlock(VPBlockBase *VPBB);
4951
4952 /// The trip count of the original loop.
4954 assert(TripCount && "trip count needs to be set before accessing it");
4955 return TripCount;
4956 }
4957
4958 /// Set the trip count assuming it is currently null; if it is not - use
4959 /// resetTripCount().
4960 void setTripCount(VPValue *NewTripCount) {
4961 assert(!TripCount && NewTripCount && "TripCount should not be set yet.");
4962 TripCount = NewTripCount;
4963 }
4964
4965 /// Resets the trip count for the VPlan. The caller must make sure all uses of
4966 /// the original trip count have been replaced.
4967 void resetTripCount(VPValue *NewTripCount) {
4968 assert(TripCount && NewTripCount && TripCount->user_empty() &&
4969 "TripCount must be set when resetting");
4970 TripCount = NewTripCount;
4971 }
4972
4973 /// The backedge taken count of the original loop.
4975 // BTC shares the canonical IV type with VectorTripCount.
4976 if (!BackedgeTakenCount)
4977 BackedgeTakenCount = new VPSymbolicValue(VectorTripCount.getType());
4978 return BackedgeTakenCount;
4979 }
4980 VPValue *getBackedgeTakenCount() const { return BackedgeTakenCount; }
4981
4982 /// The vector trip count.
4983 VPSymbolicValue &getVectorTripCount() { return VectorTripCount; }
4984
4985 /// Returns the VF of the vector loop region.
4986 VPSymbolicValue &getVF() { return VF; };
4987 const VPSymbolicValue &getVF() const { return VF; };
4988
4989 /// Returns the UF of the vector loop region.
4990 VPSymbolicValue &getUF() { return UF; };
4991
4992 /// Returns VF * UF of the vector loop region.
4993 VPSymbolicValue &getVFxUF() { return VFxUF; }
4994
4997 }
4998
4999 const DataLayout &getDataLayout() const {
5001 }
5002
5003 void addVF(ElementCount VF) { VFs.insert(VF); }
5004
5006 assert(hasVF(VF) && "Cannot set VF not already in plan");
5007 VFs.clear();
5008 VFs.insert(VF);
5009 }
5010
5011 /// Remove \p VF from the plan.
5013 assert(hasVF(VF) && "tried to remove VF not present in plan");
5014 VFs.remove(VF);
5015 }
5016
5017 bool hasVF(ElementCount VF) const { return VFs.count(VF); }
5018 bool hasScalableVF() const {
5019 return any_of(VFs, [](ElementCount VF) { return VF.isScalable(); });
5020 }
5021
5022 /// Returns an iterator range over all VFs of the plan.
5025 return VFs;
5026 }
5027
5028 /// Returns the single VF of the plan, asserting that the plan has exactly
5029 /// one VF.
5031 assert(VFs.size() == 1 && "expected plan with single VF");
5032 return VFs[0];
5033 }
5034
5035 bool hasScalarVFOnly() const {
5036 bool HasScalarVFOnly = VFs.size() == 1 && VFs[0].isScalar();
5037 assert(HasScalarVFOnly == hasVF(ElementCount::getFixed(1)) &&
5038 "Plan with scalar VF should only have a single VF");
5039 return HasScalarVFOnly;
5040 }
5041
5042 bool hasUF(unsigned UF) const { return UFs.empty() || UFs.contains(UF); }
5043
5044 /// Returns the concrete UF of the plan, after unrolling.
5045 unsigned getConcreteUF() const {
5046 assert(UFs.size() == 1 && "Expected a single UF");
5047 return UFs[0];
5048 }
5049
5050 void setUF(unsigned UF) {
5051 assert(hasUF(UF) && "Cannot set the UF not already in plan");
5052 UFs.clear();
5053 UFs.insert(UF);
5054 }
5055
5056 /// Returns true if the VPlan already has been unrolled, i.e. it has a single
5057 /// concrete UF.
5058 bool isUnrolled() const { return UFs.size() == 1; }
5059
5060 /// Return a string with the name of the plan and the applicable VFs and UFs.
5061 std::string getName() const;
5062
5063 void setName(const Twine &newName) { Name = newName.str(); }
5064
5065 /// Gets the live-in VPIRValue for \p V or adds a new live-in (if none exists
5066 /// yet) for \p V.
5068 assert(V && "Trying to get or add the VPIRValue of a null Value");
5069 auto [It, Inserted] = LiveIns.try_emplace(V);
5070 if (Inserted) {
5071 if (auto *CI = dyn_cast<ConstantInt>(V))
5072 It->second = new VPConstantInt(CI);
5073 else
5074 It->second = new VPIRValue(V);
5075 }
5076
5077 assert(isa<VPIRValue>(It->second) &&
5078 "Only VPIRValues should be in mapping");
5079 return It->second;
5080 }
5082 assert(V && "Trying to get or add the VPIRValue of a null VPIRValue");
5083 return getOrAddLiveIn(V->getValue());
5084 }
5085
5086 /// Return a VPIRValue wrapping i1 true.
5087 VPIRValue *getTrue() { return getConstantInt(1, 1); }
5088
5089 /// Return a VPIRValue wrapping i1 false.
5090 VPIRValue *getFalse() { return getConstantInt(1, 0); }
5091
5092 /// Return a VPIRValue wrapping the null value of type \p Ty.
5093 VPIRValue *getZero(Type *Ty) { return getConstantInt(Ty, 0); }
5094
5095 /// Return a VPIRValue wrapping the AllOnes value of type \p Ty.
5097 return getConstantInt(APInt::getAllOnes(Ty->getIntegerBitWidth()));
5098 }
5099
5100 /// Return a VPIRValue wrapping a ConstantInt with the given type and value.
5101 VPIRValue *getConstantInt(Type *Ty, uint64_t Val, bool IsSigned = false) {
5102 return getOrAddLiveIn(ConstantInt::get(Ty, Val, IsSigned));
5103 }
5104
5105 /// Return a VPIRValue wrapping a ConstantInt with the given bitwidth and
5106 /// value.
5108 bool IsSigned = false) {
5109 return getConstantInt(APInt(BitWidth, Val, IsSigned));
5110 }
5111
5112 /// Return a VPIRValue wrapping a ConstantInt with the given APInt value.
5114 return getOrAddLiveIn(ConstantInt::get(getContext(), Val));
5115 }
5116
5117 /// Return a VPIRValue wrapping a poison value of type \p Ty.
5119 return getOrAddLiveIn(PoisonValue::get(Ty));
5120 }
5121
5122 /// Return the live-in VPIRValue for \p V, if there is one or nullptr
5123 /// otherwise.
5124 VPIRValue *getLiveIn(Value *V) const { return LiveIns.lookup(V); }
5125
5126 /// Return the list of live-in VPValues available in the VPlan.
5127 auto getLiveIns() const { return LiveIns.values(); }
5128
5129#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
5130 /// Print the live-ins of this VPlan to \p O.
5131 void printLiveIns(raw_ostream &O) const;
5132
5133 /// Print this VPlan to \p O.
5134 LLVM_ABI_FOR_TEST void print(raw_ostream &O) const;
5135
5136 /// Print this VPlan in DOT format to \p O.
5137 LLVM_ABI_FOR_TEST void printDOT(raw_ostream &O) const;
5138
5139 /// Dump the plan to stderr (for debugging).
5140 LLVM_DUMP_METHOD void dump() const;
5141#endif
5142
5143 /// Clone the current VPlan, update all VPValues of the new VPlan and cloned
5144 /// recipes to refer to the clones, and return it.
5146
5147 /// Create a new VPBasicBlock with \p Name and containing \p Recipe if
5148 /// present. The returned block is owned by the VPlan and deleted once the
5149 /// VPlan is destroyed.
5151 VPRecipeBase *Recipe = nullptr) {
5152 auto *VPB = new VPBasicBlock(Name, Recipe);
5153 VPB->setNumber(CreatedBlocks.size());
5154 CreatedBlocks.push_back(VPB);
5155 return VPB;
5156 }
5157
5158 /// Create a new loop region with a canonical IV using \p CanIVTy and
5159 /// \p DL. Use \p Name as the region's name and set entry and exiting blocks
5160 /// to \p Entry and \p Exiting respectively, if provided. The returned block
5161 /// is owned by the VPlan and deleted once the VPlan is destroyed.
5163 const std::string &Name = "",
5164 VPBlockBase *Entry = nullptr,
5165 VPBlockBase *Exiting = nullptr) {
5166 auto *VPB = new VPRegionBlock(CanIVTy, DL, Entry, Exiting, Name);
5167 VPB->setNumber(CreatedBlocks.size());
5168 CreatedBlocks.push_back(VPB);
5169 return VPB;
5170 }
5171
5172 /// Create a new replicate region with \p Entry, \p Exiting and \p Name. The
5173 /// returned block is owned by the VPlan and deleted once the VPlan is
5174 /// destroyed.
5176 const std::string &Name = "") {
5177 auto *VPB = new VPRegionBlock(Entry, Exiting, Name);
5178 VPB->setNumber(CreatedBlocks.size());
5179 CreatedBlocks.push_back(VPB);
5180 return VPB;
5181 }
5182
5183 /// Create a VPIRBasicBlock wrapping \p IRBB, but do not create
5184 /// VPIRInstructions wrapping the instructions in t\p IRBB. The returned
5185 /// block is owned by the VPlan and deleted once the VPlan is destroyed.
5187
5188 /// Create a VPIRBasicBlock from \p IRBB containing VPIRInstructions for all
5189 /// instructions in \p IRBB, except its terminator which is managed by the
5190 /// successors of the block in VPlan. The returned block is owned by the VPlan
5191 /// and deleted once the VPlan is destroyed.
5193
5194 unsigned getMaxBlockNumber() const { return CreatedBlocks.size(); }
5195
5196 /// Returns true if the VPlan is based on a loop with an early exit.
5197 bool hasEarlyExit() const {
5198 unsigned NumExitPredecessors =
5199 sum_of(map_range(ExitBlocks, [](VPIRBasicBlock *EB) {
5200 return EB->getNumPredecessors();
5201 }));
5202
5203 // If the scalar preheader executes unconditionally, there's no branch from
5204 // middle block to any exit. If there is any edge to an exit block
5205 // remaining, it must be an early exit.
5206 VPBasicBlock *ScalarPH = getScalarPreheader();
5207 VPBlockBase *ScalarPHPred =
5208 ScalarPH ? ScalarPH->getSinglePredecessor() : nullptr;
5209 if (ScalarPHPred && ScalarPHPred->getNumSuccessors() == 1)
5210 return NumExitPredecessors >= 1;
5211
5212 // Otherwise there must be at least 2 edges to exit blocks (from the middle
5213 // block and the early exiting edge).
5214 return NumExitPredecessors > 1;
5215 }
5216
5217 /// Returns true if the scalar tail may execute after the vector loop, i.e.
5218 /// if the middle block is a predecessor of the scalar preheader. Note that
5219 /// this relies on unneeded branches to the scalar tail loop being removed.
5220 bool hasScalarTail() const {
5221 auto *ScalarPH = getScalarPreheader();
5222 return ScalarPH &&
5223 is_contained(ScalarPH->getPredecessors(), getMiddleBlock());
5224 }
5225
5226 /// The type of the canonical induction variable of the vector loop.
5227 Type *getIndexType() const { return VF.getType(); }
5228};
5229
5230#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
5231inline raw_ostream &operator<<(raw_ostream &OS, const VPlan &Plan) {
5232 Plan.print(OS);
5233 return OS;
5234}
5235#endif
5236
5237} // end namespace llvm
5238
5239#endif // LLVM_TRANSFORMS_VECTORIZE_VPLAN_H
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
aarch64 promote const
static MCDisassembler::DecodeStatus addOperand(MCInst &Inst, const MCOperand &Opnd)
Rewrite undef for PHI
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static void print(raw_ostream &Out, object::Archive::Kind Kind, T Val)
This file implements methods to test, set and extract typed bits from packed unsigned integers.
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
#define LLVM_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)
Func MI getDebugLoc()))
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
static SymbolRef::Type getType(const Symbol *Sym)
Definition TapiFile.cpp:39
static const BasicSubtargetSubTypeKV * find(StringRef S, ArrayRef< BasicSubtargetSubTypeKV > A)
Find KV in array using binary search.
This file contains the declarations of the entities induced by Vectorization Plans,...
#define VP_CLASSOF_IMPL(VPRecipeID)
Definition VPlan.h: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:235
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:309
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:1069
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.
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:306
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:257
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:4049
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
VPActiveLaneMaskPHIRecipe(VPValue *StartMask, DebugLoc DL)
Definition VPlan.h:4043
~VPActiveLaneMaskPHIRecipe() override=default
VPBasicBlock serves as the leaf of the Hierarchical Control-Flow Graph.
Definition VPlan.h:4380
RecipeListTy::const_iterator const_iterator
Definition VPlan.h:4408
void appendRecipe(VPRecipeBase *Recipe)
Augment the existing recipes of a VPBasicBlock with an additional Recipe as the last recipe.
Definition VPlan.h:4455
RecipeListTy::const_reverse_iterator const_reverse_iterator
Definition VPlan.h:4410
RecipeListTy::iterator iterator
Instruction iterators...
Definition VPlan.h:4407
RecipeListTy & getRecipeList()
Returns a reference to the list of recipes.
Definition VPlan.h:4433
iplist< VPRecipeBase > RecipeListTy
Definition VPlan.h:4391
iterator end()
Definition VPlan.h:4417
iterator begin()
Recipe iterator methods.
Definition VPlan.h:4415
RecipeListTy::reverse_iterator reverse_iterator
Definition VPlan.h:4409
iterator_range< iterator > phis()
Returns an iterator range over the PHI-like recipes in the block.
Definition VPlan.h:4468
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:797
iterator getFirstNonPhi()
Return the position of the first non-phi node recipe in the block.
Definition VPlan.cpp:266
~VPBasicBlock() override
Definition VPlan.h:4401
const_reverse_iterator rbegin() const
Definition VPlan.h:4421
reverse_iterator rend()
Definition VPlan.h:4422
RecipeListTy Recipes
The VPRecipes held in the order of output instructions to generate.
Definition VPlan.h:4395
VPRecipeBase & back()
Definition VPlan.h:4430
const VPRecipeBase & front() const
Definition VPlan.h:4427
const_iterator begin() const
Definition VPlan.h:4416
VPRecipeBase & front()
Definition VPlan.h:4428
const VPRecipeBase & back() const
Definition VPlan.h:4429
void insert(VPRecipeBase *Recipe, iterator InsertPt)
Definition VPlan.h:4446
bool empty() const
Definition VPlan.h:4426
const_iterator end() const
Definition VPlan.h:4418
static bool classof(const VPBlockBase *V)
Method to support type inquiry through isa, cast, and dyn_cast.
Definition VPlan.h:4441
static RecipeListTy VPBasicBlock::* getSublistAccess(VPRecipeBase *)
Returns a pointer to a member of the recipe list.
Definition VPlan.h:4436
reverse_iterator rbegin()
Definition VPlan.h:4420
friend class VPlan
Definition VPlan.h:4381
size_t size() const
Definition VPlan.h:4425
const_reverse_iterator rend() const
Definition VPlan.h:4423
VPBasicBlock(VPBlockTy BlockSC, const Twine &Name="")
Definition VPlan.h:4397
VPValue * getIncomingValue(unsigned Idx) const
Return incoming value number Idx.
Definition VPlan.h:2994
VPValue * getMask(unsigned Idx) const
Return mask number Idx.
Definition VPlan.h:2999
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:2955
unsigned getNumIncomingValues() const
Return the number of incoming values, taking into account when normalized the first incoming value wi...
Definition VPlan.h:2989
void execute(VPTransformState &State) override
The method which generates the output IR instructions that correspond to this VPRecipe,...
Definition VPlan.h:3011
VPBlendRecipe * cloneWithOperands(ArrayRef< VPValue * > NewOperands)
Definition VPlan.h:2976
VPBlendRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:2974
void setMask(unsigned Idx, VPValue *V)
Set mask number Idx to V.
Definition VPlan.h:3005
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:2985
VPBlockBase is the building block of the Hierarchical Control-Flow Graph.
Definition VPlan.h:94
void setSuccessors(ArrayRef< VPBlockBase * > NewSuccs)
Set each VPBasicBlock in NewSuccss as successor of this VPBlockBase.
Definition VPlan.h:315
VPRegionBlock * getParent()
Definition VPlan.h:192
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:185
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:685
SmallVectorImpl< VPBlockBase * > VPBlocksTy
Definition VPlan.h:179
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:258
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:102
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.
void setPlan(VPlan *ParentPlan)
Sets the pointer of the plan containing the block.
Definition VPlan.cpp:230
const VPRegionBlock * getParent() const
Definition VPlan.h:193
const std::string & getName() const
Definition VPlan.h:183
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:95
unsigned getVPBlockID() const
Definition VPlan.h:190
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:250
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:3496
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
Definition VPlan.h:3517
VPBranchOnMaskRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:3501
bool usesScalars(const VPValue *Op) const override
Returns true if the recipe uses scalars of operand Op.
Definition VPlan.h:3525
VPBranchOnMaskRecipe(VPValue *BlockInMask, DebugLoc DL)
Definition VPlan.h:3498
VPlan-based builder utility analogous to IRBuilder.
VPRegionValue * createHeaderMask()
Create the header mask for the region and return it.
Definition VPlan.h:4584
VPRegionValue * getHeaderMask() const
Definition VPlan.h:4580
VPRegionValue * getRegionValue()
Definition VPlan.h:4577
VPCanonicalIVInfo(Type *Ty, DebugLoc DL, VPRegionBlock *Region)
Definition VPlan.h:4574
const VPRegionValue * getRegionValue() const
Definition VPlan.h:4578
bool hasNUW() const
Definition VPlan.h:4592
VPCurrentIterationPHIRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:4081
VPCurrentIterationPHIRecipe(VPValue *StartIV, DebugLoc DL)
Definition VPlan.h:4075
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPCurrentIterationPHIRecipe.
Definition VPlan.h:4093
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:4087
bool usesFirstLaneOnly(const VPValue *Op) const override
Returns true if the recipe only uses the first lane of operand Op.
Definition VPlan.h:4100
~VPCurrentIterationPHIRecipe() override=default
InductionDescriptor::InductionKind getInductionKind() const
Definition VPlan.h:4211
VPValue * getIndex() const
Definition VPlan.h:4208
const FPMathOperator * getFPBinOp() const
Definition VPlan.h:4210
VPDerivedIVRecipe(InductionDescriptor::InductionKind Kind, const FPMathOperator *FPBinOp, VPValue *Start, VPValue *Current, VPValue *Step, const VPIRFlags::WrapFlagsTy &Flags={})
Definition VPlan.h:4182
VPValue * getStepValue() const
Definition VPlan.h:4209
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:4199
VPDerivedIVRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:4192
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:4214
VPValue * getStartValue() const
Definition VPlan.h:4207
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:4018
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:4023
VPExpandSCEVRecipe(const SCEV *Expr)
const SCEV * getSCEV() const
Definition VPlan.h:4029
VPExpandSCEVRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:4014
~VPExpandSCEVRecipe() override=default
void execute(VPTransformState &State) override
Method for generating code, must not be called as this recipe is abstract.
Definition VPlan.h:3668
bool isVectorToScalar() const
Returns true if this VPExpressionRecipe produces a single scalar.
VPExpressionRecipe(VPWidenCastRecipe *Ext, VPWidenRecipe *Neg, VPReductionRecipe *Red)
Definition VPlan.h:3587
VPExpressionRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:3640
void decompose()
Insert the recipes of the expression back into the VPlan, directly before the current recipe.
~VPExpressionRecipe() override
Definition VPlan.h:3628
VPExpressionRecipe(VPWidenCastRecipe *Ext, VPReductionRecipe *Red)
Definition VPlan.h:3585
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:3603
VPExpressionRecipe(VPWidenCastRecipe *Ext0, VPWidenCastRecipe *Ext1, VPWidenRecipe *Mul, VPWidenRecipe *Neg, VPReductionRecipe *Red)
Definition VPlan.h:3607
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
unsigned getVFScaleFactor() const
Definition VPlan.h:3662
VPExpressionRecipe(VPWidenRecipe *Mul, VPReductionRecipe *Red)
Definition VPlan.h:3601
A pure virtual base class for all recipes modeling header phis, including phis for first order recurr...
Definition VPlan.h:2437
VPHeaderPHIRecipe(VPRecipeTy VPRecipeID, Instruction *UnderlyingInstr, VPValue *Start, Type *ResultTy, DebugLoc DL)
Definition VPlan.h:2444
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:2439
const VPRecipeBase * getAsRecipe() const override
Return a VPRecipeBase* to the current object.
Definition VPlan.h:2448
void addBackedgeValue(VPValue *V)
Add V as the incoming value from the loop backedge.
Definition VPlan.h:2492
static bool classof(const VPSingleDefRecipe *R)
Definition VPlan.h:2461
static bool classof(const VPValue *V)
Definition VPlan.h:2458
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:2484
void setBackedgeValue(VPValue *V)
Update the incoming value from the loop backedge.
Definition VPlan.h:2489
VPValue * getStartValue()
Returns the start value of the phi, if one is set.
Definition VPlan.h:2473
void setStartValue(VPValue *V)
Update the start value of the recipe.
Definition VPlan.h:2481
static bool classof(const VPRecipeBase *R)
Method to support type inquiry through isa, cast, and dyn_cast.
Definition VPlan.h:2454
VPValue * getStartValue() const
Definition VPlan.h:2476
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:2164
void execute(VPTransformState &State) override
Produce a vectorized histogram operation.
VPHistogramRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:2177
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:2194
unsigned getOpcode() const
Definition VPlan.h:2190
VP_CLASSOF_IMPL(VPRecipeBase::VPHistogramSC)
~VPHistogramRecipe() override=default
VPHistogramRecipe(unsigned Opcode, ArrayRef< VPValue * > Operands, const VPIRMetadata &Metadata={}, DebugLoc DL=DebugLoc::getUnknown())
Definition VPlan.h:2169
A special type of VPBasicBlock that wraps an existing IR basic block.
Definition VPlan.h:4533
void execute(VPTransformState *State) override
The method which generates the output IR instructions that correspond to this VPBasicBlock,...
Definition VPlan.cpp:497
BasicBlock * getIRBasicBlock() const
Definition VPlan.h:4557
static bool classof(const VPBlockBase *V)
Definition VPlan.h:4547
~VPIRBasicBlock() override=default
friend class VPlan
Definition VPlan.h:4534
VPIRBasicBlock * clone() override
Clone the current block and it's recipes, without updating the operands of the cloned recipes.
Definition VPlan.cpp:522
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
LLVM_ABI_FOR_TEST bool hasRequiredFlagsForOpcode(unsigned Opcode) const
Returns true if Opcode has its required flags set.
VPIRFlags(RecurKind Kind, bool IsOrdered, bool IsInLoop, FastMathFlags FMFs)
Definition VPlan.h: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
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:1754
bool usesFirstPartOnly(const VPValue *Op) const override
Returns true if the VPUser only uses the first part of operand Op.
Definition VPlan.h:1762
~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:1741
bool usesFirstLaneOnly(const VPValue *Op) const override
Returns true if the VPUser only uses the first lane of operand Op.
Definition VPlan.h:1768
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:1756
VPIRInstruction(Instruction &I)
VPIRInstruction::create() should be used to create VPIRInstructions, as subclasses may need to be cre...
Definition VPlan.h:1729
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:1179
VPIRMetadata & operator=(const VPIRMetadata &Other)=default
MDNode * getMetadata(unsigned Kind) const
Get metadata of kind Kind. Returns nullptr if not found.
Definition VPlan.h:1215
VPIRMetadata(Instruction &I)
Adds metatadata that can be preserved from the original instruction I.
Definition VPlan.h:1187
VPIRMetadata(const VPIRMetadata &Other)=default
Copy constructor for cloning.
VPIRMetadata()=default
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:1199
static bool classof(const VPUser *R)
Definition VPlan.h:1572
static bool classof(const VPRecipeBase *R)
Definition VPlan.h:1552
Type * getResultType() const
Definition VPlan.h:1590
VPInstruction * clone() override
Clone the current recipe.
Definition VPlan.h:1576
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
VPInstructionWithType(unsigned Opcode, ArrayRef< VPValue * > Operands, Type *ResultTy, const VPIRFlags &Flags={}, const VPIRMetadata &Metadata={}, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="", Value *UV=nullptr)
Definition VPlan.h:1543
void execute(VPTransformState &State) override
Generate the instruction.
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPInstruction.
bool usesScalars(const VPValue *Op) const override
Cast recipes always use scalars of their operand.
Definition VPlan.h:1593
This is a concrete Recipe that models a single VPlan-level instruction.
Definition VPlan.h:1234
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:1476
iterator_range< operand_iterator > operandsWithoutMask()
Returns an iterator range over the operands excluding the mask operand if present.
Definition VPlan.h:1498
VPInstruction * clone() override
Clone the current recipe.
Definition VPlan.h:1407
@ ExtractLastActive
Extracts the last active lane from a set of vectors.
Definition VPlan.h:1336
@ Intrinsic
Calls a scalar intrinsic. The intrinsic ID is the last operand.
Definition VPlan.h:1356
@ ExtractLane
Extracts a single lane (first operand) from a set of vector operands.
Definition VPlan.h:1327
@ ExitingIVValue
Compute the exiting value of a wide induction after vectorization, that is the value of the last lane...
Definition VPlan.h:1340
@ WideIVStep
Scale the first operand (vector step) by the second operand (scalar-step).
Definition VPlan.h:1352
@ ResumeForEpilogue
Explicit user for the resume phi of the canonical induction in the main VPlan, used by the epilogue v...
Definition VPlan.h:1330
@ Unpack
Extracts all lanes from its (non-scalable) vector operand.
Definition VPlan.h:1277
@ ReductionStartVector
Start vector for reductions with 3 operands: the original start value, the identity value for the red...
Definition VPlan.h:1323
@ BuildVector
Creates a fixed-width vector containing all operands.
Definition VPlan.h:1272
@ BuildStructVector
Given operands of (the same) struct type, creates a struct of fixed- width vectors each containing a ...
Definition VPlan.h:1269
@ CanonicalIVIncrementForPart
Definition VPlan.h:1253
@ ComputeReductionResult
Reduce the operands to the final reduction result using the operation specified via the operation's V...
Definition VPlan.h:1280
bool hasResult() const
Definition VPlan.h:1441
iterator_range< const_operand_iterator > operandsWithoutMask() const
Definition VPlan.h:1501
void addMask(VPValue *Mask)
Add mask Mask to an unmasked VPInstruction, if it needs masking.
Definition VPlan.h:1481
StringRef getName() const
Returns the symbolic name assigned to the VPInstruction.
Definition VPlan.h:1522
unsigned getOpcode() const
Definition VPlan.h:1420
void setName(StringRef NewName)
Set the symbolic name for the VPInstruction.
Definition VPlan.h:1525
VPValue * getMask() const
Returns the mask for the VPInstruction.
Definition VPlan.h:1492
VPInstruction * cloneWithOperands(ArrayRef< VPValue * > NewOperands, Type *ResultTy=nullptr)
Definition VPlan.h:1411
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:1466
A common base class for interleaved memory operations.
Definition VPlan.h:3036
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:3048
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:3098
void execute(VPTransformState &State) override
The method which generates the output IR instructions that correspond to this VPRecipe,...
Definition VPlan.h:3104
static bool classof(const VPUser *U)
Definition VPlan.h:3080
Instruction * getInsertPos() const
Definition VPlan.h:3102
static bool classof(const VPRecipeBase *R)
Definition VPlan.h:3075
const InterleaveGroup< Instruction > * getInterleaveGroup() const
Definition VPlan.h:3100
VPValue * getMask() const
Return the mask used by this recipe.
Definition VPlan.h:3092
ArrayRef< VPValue * > getStoredValues() const
Return the VPValues stored by this interleave group.
Definition VPlan.h:3121
VPInterleaveBase * clone() override=0
Clone the current recipe.
VPValue * getAddr() const
Return the address accessed by this recipe.
Definition VPlan.h:3086
bool usesFirstLaneOnly(const VPValue *Op) const override
The recipe only uses the first lane of the address, and EVL operand.
Definition VPlan.h:3201
VPValue * getEVL() const
The VPValue of the explicit vector length.
Definition VPlan.h:3195
~VPInterleaveEVLRecipe() override=default
unsigned getNumStoreOperands() const override
Returns the number of stored operands of this interleave group.
Definition VPlan.h:3208
VPInterleaveEVLRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:3188
VPInterleaveEVLRecipe(VPInterleaveRecipe &R, VPValue &EVL, VPValue *Mask)
Definition VPlan.h:3175
VPInterleaveRecipe is a recipe for transforming an interleave group of load or stores into one wide l...
Definition VPlan.h:3131
unsigned getNumStoreOperands() const override
Returns the number of stored operands of this interleave group.
Definition VPlan.h:3158
~VPInterleaveRecipe() override=default
VPInterleaveRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:3141
bool usesFirstLaneOnly(const VPValue *Op) const override
Returns true if the recipe only uses the first lane of operand Op.
Definition VPlan.h:3152
VPInterleaveRecipe(const InterleaveGroup< Instruction > *IG, VPValue *Addr, ArrayRef< VPValue * > StoredValues, VPValue *Mask, bool NeedsMaskForGaps, const VPIRMetadata &MD, DebugLoc DL)
Definition VPlan.h:3133
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:1609
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:1638
void addIncoming(VPValue *IncomingV)
Append IncomingV as an incoming value to the phi-like recipe.
Definition VPlan.h:1667
virtual unsigned getNumIncoming() const
Returns the number of incoming values, also number of incoming blocks.
Definition VPlan.h:1633
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:4524
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:1658
VPValue * getIncomingValue(unsigned Idx) const
Returns the incoming VPValue with index Idx.
Definition VPlan.h:1618
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:1643
const_incoming_blocks_range incoming_blocks() const
Returns an iterator range over the incoming blocks.
Definition VPlan.h:1647
~VPPredInstPHIRecipe() override=default
VPPredInstPHIRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:3708
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPPredInstPHIRecipe.
Definition VPlan.h:3719
VPPredInstPHIRecipe(VPValue *PredV, DebugLoc DL)
Construct a VPPredInstPHIRecipe given PredInst whose value needs a phi nodes after merging back from ...
Definition VPlan.h:3703
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:4779
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:3366
VPReductionEVLRecipe(VPReductionRecipe &R, VPValue &EVL, VPValue *CondOp, DebugLoc DL=DebugLoc::getUnknown())
Definition VPlan.h:3345
bool usesFirstLaneOnly(const VPValue *Op) const override
Returns true if the recipe only uses the first lane of operand Op.
Definition VPlan.h:3369
VPReductionEVLRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:3356
~VPReductionEVLRecipe() override=default
bool isOrdered() const
Returns true, if the phi is part of an ordered reduction.
Definition VPlan.h:2916
void setVFScaleFactor(unsigned ScaleFactor)
Set the VFScaleFactor for this reduction phi.
Definition VPlan.h:2907
VPReductionPHIRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:2889
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:2900
~VPReductionPHIRecipe() override=default
bool hasUsesOutsideReductionChain() const
Returns true, if the phi is part of a multi-use reduction.
Definition VPlan.h:2928
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:2870
bool isInLoop() const
Returns true if the phi is part of an in-loop reduction.
Definition VPlan.h:2919
bool usesFirstLaneOnly(const VPValue *Op) const override
Returns true if the recipe only uses the first lane of operand Op.
Definition VPlan.h:2933
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:2882
bool isPartialReduction() const
Returns true if the reduction outputs a vector with a scaled down VF.
Definition VPlan.h:2925
RecurKind getRecurrenceKind() const
Returns the recurrence kind of the reduction.
Definition VPlan.h:2913
A recipe to represent inloop, ordered or partial reduction operations.
Definition VPlan.h:3224
bool isConditional() const
Return true if the in-loop reduction is conditional.
Definition VPlan.h:3308
static bool classof(const VPRecipeBase *R)
Definition VPlan.h:3277
static bool classof(const VPSingleDefRecipe *R)
Definition VPlan.h:3292
VPValue * getVecOp() const
The VPValue of the vector value to be reduced.
Definition VPlan.h:3319
VPValue * getCondOp() const
The VPValue of the condition for the block.
Definition VPlan.h:3321
RecurKind getRecurrenceKind() const
Return the recurrence kind for the in-loop reduction.
Definition VPlan.h:3304
VPReductionRecipe(RecurKind RdxKind, FastMathFlags FMFs, Instruction *I, VPValue *ChainOp, VPValue *VecOp, VPValue *CondOp, ReductionStyle Style, DebugLoc DL=DebugLoc::getUnknown())
Definition VPlan.h:3257
bool isOrdered() const
Return true if the in-loop reduction is ordered.
Definition VPlan.h:3306
VPReductionRecipe(const RecurKind RdxKind, FastMathFlags FMFs, VPValue *ChainOp, VPValue *VecOp, VPValue *CondOp, ReductionStyle Style, DebugLoc DL=DebugLoc::getUnknown())
Definition VPlan.h:3263
VPReductionRecipe(VPRecipeTy SC, RecurKind RdxKind, FastMathFlags FMFs, Instruction *I, ArrayRef< VPValue * > Operands, VPValue *CondOp, ReductionStyle Style, DebugLoc DL)
Definition VPlan.h:3233
bool isPartialReduction() const
Returns true if the reduction outputs a vector with a scaled down VF.
Definition VPlan.h:3310
~VPReductionRecipe() override=default
VPValue * getChainOp() const
The VPValue of the scalar Chain being accumulated.
Definition VPlan.h:3317
bool isInLoop() const
Returns true if the reduction is in-loop.
Definition VPlan.h:3312
VPReductionRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:3271
static bool classof(const VPUser *U)
Definition VPlan.h:3282
static bool classof(const VPValue *VPV)
Definition VPlan.h:3287
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:3326
VPRegionBlock represents a collection of VPBasicBlocks and VPRegionBlocks which form a Single-Entry-S...
Definition VPlan.h:4605
const VPBlockBase * getEntry() const
Definition VPlan.h:4649
bool isReplicator() const
An indicator whether this region is to generate multiple replicated instances of output IR correspond...
Definition VPlan.h:4681
~VPRegionBlock() override=default
VPRegionValue * createHeaderMask()
Create the header mask for the region and return it.
Definition VPlan.h:4752
VPRegionValue * getUsedHeaderMask() const
Return the header mask if it exists and is used, or null otherwise.
Definition VPlan.h:4745
void setExiting(VPBlockBase *ExitingBlock)
Set ExitingBlock as the exiting VPBlockBase of this VPRegionBlock.
Definition VPlan.h:4666
VPBlockBase * getExiting()
Definition VPlan.h:4662
VPBranchOnMaskRecipe * getEntryBranchOnMask()
Definition VPlan.h:4686
const VPRegionValue * getCanonicalIV() const
Definition VPlan.h:4728
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:4759
void setEntry(VPBlockBase *EntryBlock)
Set EntryBlock as the entry VPBlockBase of this VPRegionBlock.
Definition VPlan.h:4654
Type * getCanonicalIVType() const
Return the type of the canonical IV for loop regions.
Definition VPlan.h:4733
bool hasCanonicalIVNUW() const
Indicates if NUW is set for the canonical IV increment, for loop regions.
Definition VPlan.h:4769
void clearCanonicalIVNUW(VPInstruction *Increment)
Unsets NUW for the canonical IV increment Increment, for loop regions.
Definition VPlan.h:4772
VPRegionValue * getCanonicalIV()
Return the canonical induction variable of the region, null for replicating regions.
Definition VPlan.h:4725
const VPBlockBase * getExiting() const
Definition VPlan.h:4661
VPBlockBase * getEntry()
Definition VPlan.h:4650
VPBasicBlock * getPreheaderVPBB()
Returns the pre-header VPBasicBlock of the loop region.
Definition VPlan.h:4674
VPRegionValue * getHeaderMask() const
Return the header mask of the region, or null if not set.
Definition VPlan.h:4738
friend class VPlan
Definition VPlan.h:4606
static bool classof(const VPBlockBase *V)
Method to support type inquiry through isa, cast, and dyn_cast.
Definition VPlan.h:4645
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:3388
bool isSingleScalar() const
Returns true if the recipe produces a single scalar value.
Definition VPlan.h:3447
unsigned getNumOperandsWithoutMask() const
Returns the number of operands, excluding the mask if the recipe is predicated.
Definition VPlan.h:3481
VPReplicateRecipe(Instruction *I, ArrayRef< VPValue * > Operands, bool IsSingleScalar, VPValue *Mask=nullptr, const VPIRFlags &Flags={}, VPIRMetadata Metadata={}, DebugLoc DL=DebugLoc::getUnknown())
Definition VPlan.h:3396
~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:3420
bool usesScalars(const VPValue *Op) const override
Returns true if the recipe uses scalars of operand Op.
Definition VPlan.h:3462
operand_range operandsWithoutMask()
Return the recipe's operands, excluding the mask of a predicated recipe.
Definition VPlan.h:3475
bool isPredicated() const
Definition VPlan.h:3452
VPReplicateRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:3418
bool doesGeneratePerAllLanes() const
Returns true if the recipe produces scalar values for all VF lanes.
Definition VPlan.h:3450
bool usesFirstLaneOnly(const VPValue *Op) const override
Returns true if the recipe only uses the first lane of operand Op.
Definition VPlan.h:3455
unsigned getOpcode() const
Definition VPlan.h:3485
VPValue * getMask()
Return the mask of a predicated VPReplicateRecipe.
Definition VPlan.h:3469
Instruction::BinaryOps getInductionOpcode() const
Definition VPlan.h:4296
VPValue * getStepValue() const
Definition VPlan.h:4266
void setStartIndex(VPValue *StartIndex)
Set or add the StartIndex operand.
Definition VPlan.h:4279
VPScalarIVStepsRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:4248
VPValue * getStartIndex() const
Return the StartIndex, or null if known to be zero, valid only after unrolling.
Definition VPlan.h:4274
VPValue * getVFValue() const
Return the number of scalars to produce per unroll part, used to compute StartIndex during unrolling.
Definition VPlan.h:4270
VPScalarIVStepsRecipe(VPValue *IV, VPValue *Step, VPValue *VF, Instruction::BinaryOps Opcode, FastMathFlags FMFs={}, DebugLoc DL=DebugLoc::getUnknown())
Definition VPlan.h:4239
~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:4290
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:169
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:1534
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
virtual bool usesScalars(const VPValue *Op) const
Returns true if the VPUser uses scalars of operand Op.
Definition VPlanValue.h:481
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:149
Value * getLiveInIRValue() const
Return the underlying IR value for a VPIRValue.
Definition VPlan.cpp:143
VPRecipeBase * getDefiningRecipe()
Returns the recipe defining this VPValue or nullptr if it is not defined by a recipe,...
Definition VPlan.cpp:130
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:2307
VPValue * getVFValue() const
Definition VPlan.h:2288
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:2285
int64_t getStride() const
Definition VPlan.h:2286
VPVectorEndPointerRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:2328
VPValue * getOffset() const
Definition VPlan.h:2289
bool usesFirstPartOnly(const VPValue *Op) const override
Returns true if the recipe only uses the first part of operand Op.
Definition VPlan.h:2321
void addOffset(VPValue *Offset)
Append Offset as the offset operand.
Definition VPlan.h:2299
VPVectorEndPointerRecipe(VPValue *Ptr, VPValue *VF, Type *SourceElementTy, int64_t Stride, GEPNoWrapFlags GEPFlags, DebugLoc DL)
Definition VPlan.h:2275
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPVectorPointerRecipe.
Definition VPlan.h:2314
VPValue * getPointer() const
Definition VPlan.h:2287
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:2369
VPValue * getStride() const
Definition VPlan.h:2362
Type * getSourceElementType() const
Definition VPlan.h:2377
bool usesFirstLaneOnly(const VPValue *Op) const override
Returns true if the VPUser only uses the first lane of operand Op.
Definition VPlan.h:2379
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:2386
VPVectorPointerRecipe(VPValue *Ptr, Type *SourceElementTy, VPValue *Stride, GEPNoWrapFlags GEPFlags, DebugLoc DL)
Definition VPlan.h:2353
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPHeaderPHIRecipe.
Definition VPlan.h:2403
VPVectorPointerRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:2393
VPValue * getVFxPart() const
Definition VPlan.h:2364
A recipe for widening Call instructions using library calls.
Definition VPlan.h:2098
VPWidenCallRecipe(Value *UV, Function *Variant, ArrayRef< VPValue * > CallArguments, const VPIRFlags &Flags={}, const VPIRMetadata &Metadata={}, DebugLoc DL={})
Definition VPlan.h:2105
const_operand_range args() const
Definition VPlan.h:2146
VPWidenCallRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:2124
operand_range args()
Definition VPlan.h:2145
Function * getCalledScalarFunction() const
Definition VPlan.h:2141
~VPWidenCallRecipe() override=default
~VPWidenCanonicalIVRecipe() override=default
VPValue * getStepValue() const
Definition VPlan.h:4152
void addPerPartStep(VPValue *Step)
Add the per-part step (VF * Part) used for unrolled parts.
Definition VPlan.h:4157
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:4141
VPRegionValue * getCanonicalIV() const
Return the canonical IV being widened.
Definition VPlan.h:4148
VPWidenCanonicalIVRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:4126
VPWidenCanonicalIVRecipe(VPRegionValue *CanonicalIV, const VPIRFlags::WrapFlagsTy &Flags={})
Definition VPlan.h:4119
void execute(VPTransformState &State) override
The method which generates the output IR instructions that correspond to this VPRecipe,...
Definition VPlan.h:4136
VPWidenCastRecipe is a recipe to create vector cast instructions.
Definition VPlan.h:1880
Instruction::CastOps getOpcode() const
Definition VPlan.h:1916
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:1885
VPWidenCastRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:1901
unsigned getOpcode() const
This recipe generates a GEP instruction.
Definition VPlan.h:2237
Type * getSourceElementType() const
Definition VPlan.h:2242
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPWidenGEPRecipe.
Definition VPlan.h:2245
VPWidenGEPRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:2228
~VPWidenGEPRecipe() override=default
VPWidenGEPRecipe(Type *SourceElementTy, ArrayRef< VPValue * > Operands, const VPIRFlags &Flags={}, DebugLoc DL=DebugLoc::getUnknown(), GetElementPtrInst *UV=nullptr)
Definition VPlan.h:2211
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:2585
bool usesFirstLaneOnly(const VPValue *Op) const override
Returns true if the recipe only uses the first lane of operand Op.
Definition VPlan.h:2597
static bool classof(const VPValue *V)
Definition VPlan.h:2547
void setStepValue(VPValue *V)
Update the step value of the recipe.
Definition VPlan.h:2566
VPValue * getBackedgeValue() override
Returns the incoming value from the loop backedge.
Definition VPlan.h:2589
VPIRValue * getStartValue() const
Returns the start value of the induction.
Definition VPlan.h:2559
unsigned getNumIncoming() const override
Returns the number of incoming values, also number of incoming blocks.
Definition VPlan.h:2574
PHINode * getPHINode() const
Returns the underlying PHINode if one exists, or null otherwise.
Definition VPlan.h:2577
VPValue * getStepValue()
Returns the step value of the induction.
Definition VPlan.h:2562
const InductionDescriptor & getInductionDescriptor() const
Returns the induction descriptor for the recipe.
Definition VPlan.h:2582
static bool classof(const VPRecipeBase *R)
Definition VPlan.h:2542
VPWidenInductionRecipe(VPRecipeTy Kind, PHINode *IV, VPValue *Start, VPValue *Step, const InductionDescriptor &IndDesc, Type *ResultTy, DebugLoc DL)
Definition VPlan.h:2521
const VPValue * getVFValue() const
Definition VPlan.h:2569
static bool classof(const VPSingleDefRecipe *R)
Definition VPlan.h:2552
const VPValue * getStepValue() const
Definition VPlan.h:2563
VPWidenInductionRecipe(VPRecipeTy Kind, PHINode *IV, VPValue *Start, VPValue *Step, const InductionDescriptor &IndDesc, DebugLoc DL)
Definition VPlan.h:2515
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:2530
const TruncInst * getTruncInst() const
Definition VPlan.h:2671
void execute(VPTransformState &State) override
Generate the phi nodes.
Definition VPlan.h:2652
~VPWidenIntOrFpInductionRecipe() override=default
VPValue * getSplatVFValue() const
If the recipe has been unrolled, return the VPValue for the induction increment, otherwise return nul...
Definition VPlan.h:2659
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPWidenIntOrFpInductionRecipe.
VPWidenIntOrFpInductionRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:2644
VPWidenIntOrFpInductionRecipe(PHINode *IV, VPIRValue *Start, VPValue *Step, VPValue *VF, const InductionDescriptor &IndDesc, const VPIRFlags &Flags, DebugLoc DL)
Definition VPlan.h:2618
TruncInst * getTruncInst()
Returns the first defined value as TruncInst, if it is one or nullptr otherwise.
Definition VPlan.h:2670
VPWidenIntOrFpInductionRecipe(PHINode *IV, VPIRValue *Start, VPValue *Step, VPValue *VF, const InductionDescriptor &IndDesc, TruncInst *Trunc, const VPIRFlags &Flags, DebugLoc DL)
Definition VPlan.h:2627
VPValue * getLastUnrolledPartOperand()
Returns the VPValue representing the value of this induction at the last unrolled part,...
Definition VPlan.h:2685
unsigned getNumIncoming() const override
Returns the number of incoming values, also number of incoming blocks.
Definition VPlan.h:2666
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:1927
VPWidenIntrinsicRecipe(VPRecipeTy SC, Intrinsic::ID VectorIntrinsicID, ArrayRef< VPValue * > CallArguments, Type *Ty, const VPIRFlags &Flags={}, const VPIRMetadata &MD={}, DebugLoc DL=DebugLoc::getUnknown())
Definition VPlan.h:1941
VPWidenIntrinsicRecipe(Intrinsic::ID VectorIntrinsicID, ArrayRef< VPValue * > CallArguments, Type *Ty, const VPIRFlags &Flags={}, const VPIRMetadata &Metadata={}, DebugLoc DL=DebugLoc::getUnknown())
Definition VPlan.h:1976
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:2030
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:2036
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:1962
bool mayHaveSideEffects() const
Returns true if the intrinsic may have side-effects.
Definition VPlan.h:2042
static bool classof(const VPSingleDefRecipe *R)
Definition VPlan.h:2012
static bool classof(const VPValue *V)
Definition VPlan.h:2007
VPWidenIntrinsicRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:1987
bool mayWriteToMemory() const
Returns true if the intrinsic may write to memory.
Definition VPlan.h:2039
~VPWidenIntrinsicRecipe() override=default
static bool classof(const VPRecipeBase *R)
Definition VPlan.h:1997
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:2002
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:2075
VPWidenMemIntrinsicRecipe(Intrinsic::ID VectorIntrinsicID, ArrayRef< VPValue * > CallArguments, Type *Ty, Align Alignment, const VPIRMetadata &MD={}, DebugLoc DL=DebugLoc::getUnknown())
Definition VPlan.h:2061
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:3735
bool IsMasked
Whether the memory access is masked.
Definition VPlan.h:3746
bool isConsecutive() const
Return whether the loaded-from / stored-to addresses are consecutive.
Definition VPlan.h:3771
virtual ~VPWidenMemoryRecipe()=default
Instruction & Ingredient
Definition VPlan.h:3737
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const
Return the cost of this VPWidenMemoryRecipe.
Instruction & getIngredient() const
Definition VPlan.h:3793
bool Consecutive
Whether the accessed addresses are consecutive.
Definition VPlan.h:3743
virtual const VPRecipeBase * getAsRecipe() const =0
VPValue * getMask() const
Return the mask used by this recipe.
Definition VPlan.h:3781
Align Alignment
Alignment information for this memory access.
Definition VPlan.h:3740
VPWidenMemoryRecipe(Instruction &I, bool Consecutive, const VPIRMetadata &Metadata)
Definition VPlan.h:3758
virtual VPRecipeBase * getAsRecipe()=0
Return a VPRecipeBase* to the current object.
bool isMasked() const
Returns true if the recipe is masked.
Definition VPlan.h:3777
void setMask(VPValue *Mask)
Definition VPlan.h:3748
Align getAlign() const
Returns the alignment of the memory access.
Definition VPlan.h:3788
VPValue * getAddr() const
Return the address accessed by this recipe.
Definition VPlan.h:3774
A recipe for widened phis.
Definition VPlan.h:2743
const VPRecipeBase * getAsRecipe() const override
Return a VPRecipeBase* to the current object.
Definition VPlan.h:2788
unsigned getOpcode() const
This recipe generates a PHI.
Definition VPlan.h:2770
VPWidenPHIRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:2763
~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:2750
VPWidenPointerInductionRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:2712
~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:2721
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:2702
VPWidenRecipe is a recipe for producing a widened instruction using the opcode and operands of the re...
Definition VPlan.h:1819
VPWidenRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:1840
bool usesFirstLaneOnly(const VPValue *Op) const override
Returns true if the recipe only uses the first lane of operand Op.
Definition VPlan.h:1869
VPWidenRecipe(Instruction &I, ArrayRef< VPValue * > Operands, const VPIRFlags &Flags={}, const VPIRMetadata &Metadata={}, DebugLoc DL={})
Definition VPlan.h:1823
VPWidenRecipe(unsigned Opcode, ArrayRef< VPValue * > Operands, const VPIRFlags &Flags={}, const VPIRMetadata &Metadata={}, DebugLoc DL={})
Definition VPlan.h:1830
~VPWidenRecipe() override=default
VPWidenRecipe * cloneWithOperands(ArrayRef< VPValue * > NewOperands)
Definition VPlan.h:1842
unsigned getOpcode() const
Definition VPlan.h:1859
VPlan models a candidate for vectorization, encoding various decisions take to produce efficient outp...
Definition VPlan.h:4792
VPIRValue * getLiveIn(Value *V) const
Return the live-in VPIRValue for V, if there is one or nullptr otherwise.
Definition VPlan.h:5124
LLVM_ABI_FOR_TEST void printDOT(raw_ostream &O) const
Print this VPlan in DOT format to O.
Definition VPlan.cpp:1186
friend class VPSlotTracker
Definition VPlan.h:4794
std::string getName() const
Return a string with the name of the plan and the applicable VFs and UFs.
Definition VPlan.cpp:1162
bool hasVF(ElementCount VF) const
Definition VPlan.h:5017
ElementCount getSingleVF() const
Returns the single VF of the plan, asserting that the plan has exactly one VF.
Definition VPlan.h:5030
const DataLayout & getDataLayout() const
Definition VPlan.h:4999
LLVMContext & getContext() const
Definition VPlan.h:4995
VPBasicBlock * getEntry()
Definition VPlan.h:4888
Type * getIndexType() const
The type of the canonical induction variable of the vector loop.
Definition VPlan.h:5227
void setName(const Twine &newName)
Definition VPlan.h:5063
bool hasScalableVF() const
Definition VPlan.h:5018
VPValue * getTripCount() const
The trip count of the original loop.
Definition VPlan.h:4953
VPValue * getOrCreateBackedgeTakenCount()
The backedge taken count of the original loop.
Definition VPlan.h:4974
iterator_range< SmallSetVector< ElementCount, 2 >::iterator > vectorFactors() const
Returns an iterator range over all VFs of the plan.
Definition VPlan.h:5024
LLVM_ABI_FOR_TEST ~VPlan()
Definition VPlan.cpp:923
VPIRValue * getOrAddLiveIn(VPIRValue *V)
Definition VPlan.h:5081
bool isExitBlock(VPBlockBase *VPBB)
Returns true if VPBB is an exit block.
Definition VPlan.cpp:942
const VPBasicBlock * getEntry() const
Definition VPlan.h:4889
friend class VPlanPrinter
Definition VPlan.h:4793
VPIRValue * getFalse()
Return a VPIRValue wrapping i1 false.
Definition VPlan.h:5090
VPIRValue * getConstantInt(const APInt &Val)
Return a VPIRValue wrapping a ConstantInt with the given APInt value.
Definition VPlan.h:5113
VPSymbolicValue & getVFxUF()
Returns VF * UF of the vector loop region.
Definition VPlan.h:4993
VPIRValue * getAllOnesValue(Type *Ty)
Return a VPIRValue wrapping the AllOnes value of type Ty.
Definition VPlan.h:5096
VPRegionBlock * createReplicateRegion(VPBlockBase *Entry, VPBlockBase *Exiting, const std::string &Name="")
Create a new replicate region with Entry, Exiting and Name.
Definition VPlan.h:5175
VPIRBasicBlock * createEmptyVPIRBasicBlock(BasicBlock *IRBB)
Create a VPIRBasicBlock wrapping IRBB, but do not create VPIRInstructions wrapping the instructions i...
Definition VPlan.cpp:1325
auto getLiveIns() const
Return the list of live-in VPValues available in the VPlan.
Definition VPlan.h:5127
bool hasUF(unsigned UF) const
Definition VPlan.h:5042
VPIRValue * getPoison(Type *Ty)
Return a VPIRValue wrapping a poison value of type Ty.
Definition VPlan.h:5118
ArrayRef< VPIRBasicBlock * > getExitBlocks() const
Return an ArrayRef containing VPIRBasicBlocks wrapping the exit blocks of the original scalar loop.
Definition VPlan.h:4947
VPlan(BasicBlock *ScalarHeaderBB, Type *IdxTy)
Construct a VPlan with a new VPBasicBlock as entry, a VPIRBasicBlock wrapping ScalarHeaderBB and vect...
Definition VPlan.h:4869
VPSymbolicValue & getVectorTripCount()
The vector trip count.
Definition VPlan.h:4983
VPValue * getBackedgeTakenCount() const
Definition VPlan.h:4980
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:5067
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:5162
VPIRValue * getZero(Type *Ty)
Return a VPIRValue wrapping the null value of type Ty.
Definition VPlan.h:5093
void setVF(ElementCount VF)
Definition VPlan.h:5005
unsigned getMaxBlockNumber() const
Definition VPlan.h:5194
bool isUnrolled() const
Returns true if the VPlan already has been unrolled, i.e.
Definition VPlan.h:5058
LLVM_ABI_FOR_TEST VPRegionBlock * getVectorLoopRegion()
Returns the VPRegionBlock of the vector loop.
Definition VPlan.cpp:1077
bool hasEarlyExit() const
Returns true if the VPlan is based on a loop with an early exit.
Definition VPlan.h:5197
InstructionCost cost(ElementCount VF, VPCostContext &Ctx)
Return the cost of this plan.
Definition VPlan.cpp:1059
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:1092
unsigned getConcreteUF() const
Returns the concrete UF of the plan, after unrolling.
Definition VPlan.h:5045
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:5107
const VPBasicBlock * getMiddleBlock() const
Definition VPlan.h:4932
void setTripCount(VPValue *NewTripCount)
Set the trip count assuming it is currently null; if it is not - use resetTripCount().
Definition VPlan.h:4960
void resetTripCount(VPValue *NewTripCount)
Resets the trip count for the VPlan.
Definition VPlan.h:4967
VPBasicBlock * getMiddleBlock()
Returns the 'middle' block of the plan, that is the block that selects whether to execute the scalar ...
Definition VPlan.h:4923
void setEntry(VPBasicBlock *VPBB)
Definition VPlan.h:4877
VPBasicBlock * createVPBasicBlock(const Twine &Name, VPRecipeBase *Recipe=nullptr)
Create a new VPBasicBlock with Name and containing Recipe if present.
Definition VPlan.h:5150
LLVM_ABI_FOR_TEST VPIRBasicBlock * createVPIRBasicBlock(BasicBlock *IRBB)
Create a VPIRBasicBlock from IRBB containing VPIRInstructions for all instructions in IRBB,...
Definition VPlan.cpp:1332
void removeVF(ElementCount VF)
Remove VF from the plan.
Definition VPlan.h:5012
VPIRValue * getTrue()
Return a VPIRValue wrapping i1 true.
Definition VPlan.h:5087
VPBasicBlock * getVectorPreheader() const
Returns the preheader of the vector loop region, if one exists, or null otherwise.
Definition VPlan.h:4893
LLVM_DUMP_METHOD void dump() const
Dump the plan to stderr (for debugging).
Definition VPlan.cpp:1192
VPSymbolicValue & getUF()
Returns the UF of the vector loop region.
Definition VPlan.h:4990
bool hasScalarVFOnly() const
Definition VPlan.h:5035
VPBasicBlock * getScalarPreheader() const
Return the VPBasicBlock for the preheader of the scalar loop.
Definition VPlan.h:4937
void execute(VPTransformState *State)
Generate the IR code for this VPlan.
Definition VPlan.cpp:952
LLVM_ABI_FOR_TEST void print(raw_ostream &O) const
Print this VPlan to O.
Definition VPlan.cpp:1145
bool hasTailFolded() const
Returns true if the vector loop region is tail-folded.
Definition VPlan.h:4909
void addVF(ElementCount VF)
Definition VPlan.h:5003
VPIRBasicBlock * getScalarHeader() const
Return the VPIRBasicBlock wrapping the header of the scalar loop.
Definition VPlan.h:4943
void printLiveIns(raw_ostream &O) const
Print the live-ins of this VPlan to O.
Definition VPlan.cpp:1101
VPSymbolicValue & getVF()
Returns the VF of the vector loop region.
Definition VPlan.h:4986
void setUF(unsigned UF)
Definition VPlan.h:5050
const VPSymbolicValue & getVF() const
Definition VPlan.h:4987
bool hasScalarTail() const
Returns true if the scalar tail may execute after the vector loop, i.e.
Definition VPlan.h:5220
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:1233
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:5101
LLVM Value Representation.
Definition Value.h:75
Increasing range of size_t indices.
Definition STLExtras.h:2507
typename base_list_type::const_reverse_iterator const_reverse_iterator
Definition ilist.h:124
typename base_list_type::reverse_iterator reverse_iterator
Definition ilist.h:123
typename base_list_type::const_iterator const_iterator
Definition ilist.h:122
An intrusive list with ownership and callbacks specified/controlled by ilist_traits,...
Definition ilist.h:328
A range adaptor for a pair of iterators.
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
This file defines classes to implement an intrusive doubly linked list class (i.e.
This file defines the ilist_node class template, which is a convenient base class for creating classe...
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
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:4309
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:578
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:830
LLVM_PACKED_END
Definition VPlan.h:1120
auto cast_if_present(const Y &Val)
cast_if_present<X> - Functionally identical to cast, except that a null value is accepted.
Definition Casting.h:683
auto find(R &&Range, const T &Val)
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1765
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1739
detail::zippy< detail::zip_first, T, U, Args... > zip_equal(T &&t, U &&u, Args &&...args)
zip iterator that assumes that all iteratees have the same length.
Definition STLExtras.h:840
ReductionStyle getReductionStyle(bool InLoop, bool Ordered, unsigned ScaleFactor)
Definition VPlan.h:2843
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition STLExtras.h:2554
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:365
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1746
auto reverse(ContainerTy &&C)
Definition STLExtras.h:407
UncountableExitStyle
Different methods of handling early exits.
Definition VPlan.h:79
@ MaskedHandleExitInScalarLoop
All memory operations other than the load(s) required to determine whether an uncountable exit occurr...
Definition VPlan.h:89
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:378
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:322
@ 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:2012
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:1717
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1772
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:1947
std::variant< RdxOrdered, RdxInLoop, RdxUnordered > ReductionStyle
Definition VPlan.h:2841
@ Increment
Incrementally increasing token ID.
Definition AllocToken.h:26
std::unique_ptr< VPlan > VPlanPtr
Definition VPlan.h:74
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:2835
Possible variants of a reduction.
Definition VPlan.h:2833
This reduction is unordered with the partial result scaled down by some factor.
Definition VPlan.h:2838
unsigned VFScaleFactor
Definition VPlan.h:2839
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.
void execute(VPTransformState &State) override
Generate the phi nodes.
VPFirstOrderRecurrencePHIRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:2804
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:2816
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:2795
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:1787
PHINode & getIRPhi()
Definition VPlan.h:1800
VPIRPhi(PHINode &PN)
Definition VPlan.h:1788
static bool classof(const VPRecipeBase *U)
Definition VPlan.h:1790
static bool classof(const VPUser *U)
Definition VPlan.h:1795
const VPRecipeBase * getAsRecipe() const override
Return a VPRecipeBase* to the current object.
Definition VPlan.h:1811
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:1687
VPPhi * clone() override
Clone the current recipe.
Definition VPlan.h:1702
const VPRecipeBase * getAsRecipe() const override
Return a VPRecipeBase* to the current object.
Definition VPlan.h:1717
static bool classof(const VPSingleDefRecipe *SDR)
Definition VPlan.h:1697
static bool classof(const VPValue *V)
Definition VPlan.h:1692
VPPhi(ArrayRef< VPValue * > Operands, const VPIRFlags &Flags, DebugLoc DL, const Twine &Name="", Type *ResultTy=nullptr)
Definition VPlan.h:1682
A pure-virtual common base class for recipes defining a single VPValue and using IR flags.
Definition VPlan.h:1124
VPRecipeWithIRFlags(VPRecipeTy SC, ArrayRef< VPValue * > Operands, const VPIRFlags &Flags, DebugLoc DL=DebugLoc::getUnknown())
Definition VPlan.h:1125
static bool classof(const VPSingleDefRecipe *R)
Definition VPlan.h:1166
static bool classof(const VPRecipeBase *R)
Definition VPlan.h:1136
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:1159
VPRecipeWithIRFlags(VPRecipeTy SC, ArrayRef< VPValue * > Operands, Type *ResultTy, const VPIRFlags &Flags, DebugLoc DL=DebugLoc::getUnknown())
Definition VPlan.h:1130
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:1154
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:3849
VPWidenLoadEVLRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:3859
VPValue * getEVL() const
Return the EVL operand.
Definition VPlan.h:3866
VPWidenLoadEVLRecipe(VPWidenLoadRecipe &L, VPValue *Addr, VPValue &EVL, VPValue *Mask)
Definition VPlan.h:3850
bool usesFirstLaneOnly(const VPValue *Op) const override
Returns true if the recipe only uses the first lane of operand Op.
Definition VPlan.h:3876
A recipe for widening load operations, using the address to load from and an optional mask.
Definition VPlan.h:3799
VPWidenLoadRecipe(LoadInst &Load, VPValue *Addr, VPValue *Mask, bool Consecutive, const VPIRMetadata &Metadata, DebugLoc DL)
Definition VPlan.h:3800
bool usesFirstLaneOnly(const VPValue *Op) const override
Returns true if the recipe only uses the first lane of operand Op.
Definition VPlan.h:3825
void execute(VPTransformState &State) override
Generate a wide load or gather.
VPWidenLoadRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:3808
VP_CLASSOF_IMPL(VPRecipeBase::VPWidenLoadSC)
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPWidenLoadRecipe.
Definition VPlan.h:3819
A recipe for widening store operations with vector-predication intrinsics, using the value to store,...
Definition VPlan.h:3952
VPValue * getStoredValue() const
Return the address accessed by this recipe.
Definition VPlan.h:3968
VPWidenStoreEVLRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:3961
VPWidenStoreEVLRecipe(VPWidenStoreRecipe &S, VPValue *Addr, VPValue *StoredVal, VPValue &EVL, VPValue *Mask)
Definition VPlan.h:3953
bool usesFirstLaneOnly(const VPValue *Op) const override
Returns true if the recipe only uses the first lane of operand Op.
Definition VPlan.h:3981
VPValue * getEVL() const
Return the EVL operand.
Definition VPlan.h:3971
A recipe for widening store operations, using the stored value, the address to store to and an option...
Definition VPlan.h:3898
VPWidenStoreRecipe(StoreInst &Store, VPValue *Addr, VPValue *StoredVal, VPValue *Mask, bool Consecutive, const VPIRMetadata &Metadata, DebugLoc DL)
Definition VPlan.h:3899
VP_CLASSOF_IMPL(VPRecipeBase::VPWidenStoreSC)
VPValue * getStoredValue() const
Return the value stored by this recipe.
Definition VPlan.h:3916
VPWidenStoreRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:3907
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPWidenStoreRecipe.
Definition VPlan.h:3922
bool usesFirstLaneOnly(const VPValue *Op) const override
Returns true if the recipe only uses the first lane of operand Op.
Definition VPlan.h:3928
static VPMixin * castFailed()
Definition VPlan.h:4327
static bool isPossible(VPRecipeBase *R)
Used by isa.
Definition VPlan.h:4318
static VPMixin * doCast(VPRecipeBase *R)
Used by cast.
Definition VPlan.h:4321