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