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