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. Specializations of GraphTraits that allow VPBlockBase graphs to be 14 /// treated as proper graphs for generic algorithms; 15 /// 3. Pure virtual VPRecipeBase serving as the base class for recipes contained 16 /// within VPBasicBlocks; 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 /// 6. The VPlanPrinter class providing a way to print a plan in dot format; 21 /// These are documented in docs/VectorizationPlan.rst. 22 // 23 //===----------------------------------------------------------------------===// 24 25 #ifndef LLVM_TRANSFORMS_VECTORIZE_VPLAN_H 26 #define LLVM_TRANSFORMS_VECTORIZE_VPLAN_H 27 28 #include "VPlanValue.h" 29 #include "llvm/ADT/DenseMap.h" 30 #include "llvm/ADT/DepthFirstIterator.h" 31 #include "llvm/ADT/GraphTraits.h" 32 #include "llvm/ADT/MapVector.h" 33 #include "llvm/ADT/Optional.h" 34 #include "llvm/ADT/SmallBitVector.h" 35 #include "llvm/ADT/SmallPtrSet.h" 36 #include "llvm/ADT/SmallVector.h" 37 #include "llvm/ADT/Twine.h" 38 #include "llvm/ADT/ilist.h" 39 #include "llvm/ADT/ilist_node.h" 40 #include "llvm/Analysis/LoopInfo.h" 41 #include "llvm/Analysis/VectorUtils.h" 42 #include "llvm/IR/DebugLoc.h" 43 #include "llvm/IR/FMF.h" 44 #include <algorithm> 45 #include <cassert> 46 #include <cstddef> 47 #include <string> 48 49 namespace llvm { 50 51 class BasicBlock; 52 class DominatorTree; 53 class InductionDescriptor; 54 class InnerLoopVectorizer; 55 class IRBuilderBase; 56 class LoopInfo; 57 class raw_ostream; 58 class RecurrenceDescriptor; 59 class Value; 60 class VPBasicBlock; 61 class VPRegionBlock; 62 class VPlan; 63 class VPReplicateRecipe; 64 class VPlanSlp; 65 66 /// Returns a calculation for the total number of elements for a given \p VF. 67 /// For fixed width vectors this value is a constant, whereas for scalable 68 /// vectors it is an expression determined at runtime. 69 Value *getRuntimeVF(IRBuilderBase &B, Type *Ty, ElementCount VF); 70 71 /// Return a value for Step multiplied by VF. 72 Value *createStepForVF(IRBuilderBase &B, Type *Ty, ElementCount VF, 73 int64_t Step); 74 75 /// A range of powers-of-2 vectorization factors with fixed start and 76 /// adjustable end. The range includes start and excludes end, e.g.,: 77 /// [1, 9) = {1, 2, 4, 8} 78 struct VFRange { 79 // A power of 2. 80 const ElementCount Start; 81 82 // Need not be a power of 2. If End <= Start range is empty. 83 ElementCount End; 84 85 bool isEmpty() const { 86 return End.getKnownMinValue() <= Start.getKnownMinValue(); 87 } 88 89 VFRange(const ElementCount &Start, const ElementCount &End) 90 : Start(Start), End(End) { 91 assert(Start.isScalable() == End.isScalable() && 92 "Both Start and End should have the same scalable flag"); 93 assert(isPowerOf2_32(Start.getKnownMinValue()) && 94 "Expected Start to be a power of 2"); 95 } 96 }; 97 98 using VPlanPtr = std::unique_ptr<VPlan>; 99 100 /// In what follows, the term "input IR" refers to code that is fed into the 101 /// vectorizer whereas the term "output IR" refers to code that is generated by 102 /// the vectorizer. 103 104 /// VPLane provides a way to access lanes in both fixed width and scalable 105 /// vectors, where for the latter the lane index sometimes needs calculating 106 /// as a runtime expression. 107 class VPLane { 108 public: 109 /// Kind describes how to interpret Lane. 110 enum class Kind : uint8_t { 111 /// For First, Lane is the index into the first N elements of a 112 /// fixed-vector <N x <ElTy>> or a scalable vector <vscale x N x <ElTy>>. 113 First, 114 /// For ScalableLast, Lane is the offset from the start of the last 115 /// N-element subvector in a scalable vector <vscale x N x <ElTy>>. For 116 /// example, a Lane of 0 corresponds to lane `(vscale - 1) * N`, a Lane of 117 /// 1 corresponds to `((vscale - 1) * N) + 1`, etc. 118 ScalableLast 119 }; 120 121 private: 122 /// in [0..VF) 123 unsigned Lane; 124 125 /// Indicates how the Lane should be interpreted, as described above. 126 Kind LaneKind; 127 128 public: 129 VPLane(unsigned Lane, Kind LaneKind) : Lane(Lane), LaneKind(LaneKind) {} 130 131 static VPLane getFirstLane() { return VPLane(0, VPLane::Kind::First); } 132 133 static VPLane getLastLaneForVF(const ElementCount &VF) { 134 unsigned LaneOffset = VF.getKnownMinValue() - 1; 135 Kind LaneKind; 136 if (VF.isScalable()) 137 // In this case 'LaneOffset' refers to the offset from the start of the 138 // last subvector with VF.getKnownMinValue() elements. 139 LaneKind = VPLane::Kind::ScalableLast; 140 else 141 LaneKind = VPLane::Kind::First; 142 return VPLane(LaneOffset, LaneKind); 143 } 144 145 /// Returns a compile-time known value for the lane index and asserts if the 146 /// lane can only be calculated at runtime. 147 unsigned getKnownLane() const { 148 assert(LaneKind == Kind::First); 149 return Lane; 150 } 151 152 /// Returns an expression describing the lane index that can be used at 153 /// runtime. 154 Value *getAsRuntimeExpr(IRBuilderBase &Builder, const ElementCount &VF) const; 155 156 /// Returns the Kind of lane offset. 157 Kind getKind() const { return LaneKind; } 158 159 /// Returns true if this is the first lane of the whole vector. 160 bool isFirstLane() const { return Lane == 0 && LaneKind == Kind::First; } 161 162 /// Maps the lane to a cache index based on \p VF. 163 unsigned mapToCacheIndex(const ElementCount &VF) const { 164 switch (LaneKind) { 165 case VPLane::Kind::ScalableLast: 166 assert(VF.isScalable() && Lane < VF.getKnownMinValue()); 167 return VF.getKnownMinValue() + Lane; 168 default: 169 assert(Lane < VF.getKnownMinValue()); 170 return Lane; 171 } 172 } 173 174 /// Returns the maxmimum number of lanes that we are able to consider 175 /// caching for \p VF. 176 static unsigned getNumCachedLanes(const ElementCount &VF) { 177 return VF.getKnownMinValue() * (VF.isScalable() ? 2 : 1); 178 } 179 }; 180 181 /// VPIteration represents a single point in the iteration space of the output 182 /// (vectorized and/or unrolled) IR loop. 183 struct VPIteration { 184 /// in [0..UF) 185 unsigned Part; 186 187 VPLane Lane; 188 189 VPIteration(unsigned Part, unsigned Lane, 190 VPLane::Kind Kind = VPLane::Kind::First) 191 : Part(Part), Lane(Lane, Kind) {} 192 193 VPIteration(unsigned Part, const VPLane &Lane) : Part(Part), Lane(Lane) {} 194 195 bool isFirstIteration() const { return Part == 0 && Lane.isFirstLane(); } 196 }; 197 198 /// VPTransformState holds information passed down when "executing" a VPlan, 199 /// needed for generating the output IR. 200 struct VPTransformState { 201 VPTransformState(ElementCount VF, unsigned UF, LoopInfo *LI, 202 DominatorTree *DT, IRBuilderBase &Builder, 203 InnerLoopVectorizer *ILV, VPlan *Plan) 204 : VF(VF), UF(UF), LI(LI), DT(DT), Builder(Builder), ILV(ILV), Plan(Plan) { 205 } 206 207 /// The chosen Vectorization and Unroll Factors of the loop being vectorized. 208 ElementCount VF; 209 unsigned UF; 210 211 /// Hold the indices to generate specific scalar instructions. Null indicates 212 /// that all instances are to be generated, using either scalar or vector 213 /// instructions. 214 Optional<VPIteration> Instance; 215 216 struct DataState { 217 /// A type for vectorized values in the new loop. Each value from the 218 /// original loop, when vectorized, is represented by UF vector values in 219 /// the new unrolled loop, where UF is the unroll factor. 220 typedef SmallVector<Value *, 2> PerPartValuesTy; 221 222 DenseMap<VPValue *, PerPartValuesTy> PerPartOutput; 223 224 using ScalarsPerPartValuesTy = SmallVector<SmallVector<Value *, 4>, 2>; 225 DenseMap<VPValue *, ScalarsPerPartValuesTy> PerPartScalars; 226 } Data; 227 228 /// Get the generated Value for a given VPValue and a given Part. Note that 229 /// as some Defs are still created by ILV and managed in its ValueMap, this 230 /// method will delegate the call to ILV in such cases in order to provide 231 /// callers a consistent API. 232 /// \see set. 233 Value *get(VPValue *Def, unsigned Part); 234 235 /// Get the generated Value for a given VPValue and given Part and Lane. 236 Value *get(VPValue *Def, const VPIteration &Instance); 237 238 bool hasVectorValue(VPValue *Def, unsigned Part) { 239 auto I = Data.PerPartOutput.find(Def); 240 return I != Data.PerPartOutput.end() && Part < I->second.size() && 241 I->second[Part]; 242 } 243 244 bool hasAnyVectorValue(VPValue *Def) const { 245 return Data.PerPartOutput.find(Def) != Data.PerPartOutput.end(); 246 } 247 248 bool hasScalarValue(VPValue *Def, VPIteration Instance) { 249 auto I = Data.PerPartScalars.find(Def); 250 if (I == Data.PerPartScalars.end()) 251 return false; 252 unsigned CacheIdx = Instance.Lane.mapToCacheIndex(VF); 253 return Instance.Part < I->second.size() && 254 CacheIdx < I->second[Instance.Part].size() && 255 I->second[Instance.Part][CacheIdx]; 256 } 257 258 /// Set the generated Value for a given VPValue and a given Part. 259 void set(VPValue *Def, Value *V, unsigned Part) { 260 if (!Data.PerPartOutput.count(Def)) { 261 DataState::PerPartValuesTy Entry(UF); 262 Data.PerPartOutput[Def] = Entry; 263 } 264 Data.PerPartOutput[Def][Part] = V; 265 } 266 /// Reset an existing vector value for \p Def and a given \p Part. 267 void reset(VPValue *Def, Value *V, unsigned Part) { 268 auto Iter = Data.PerPartOutput.find(Def); 269 assert(Iter != Data.PerPartOutput.end() && 270 "need to overwrite existing value"); 271 Iter->second[Part] = V; 272 } 273 274 /// Set the generated scalar \p V for \p Def and the given \p Instance. 275 void set(VPValue *Def, Value *V, const VPIteration &Instance) { 276 auto Iter = Data.PerPartScalars.insert({Def, {}}); 277 auto &PerPartVec = Iter.first->second; 278 while (PerPartVec.size() <= Instance.Part) 279 PerPartVec.emplace_back(); 280 auto &Scalars = PerPartVec[Instance.Part]; 281 unsigned CacheIdx = Instance.Lane.mapToCacheIndex(VF); 282 while (Scalars.size() <= CacheIdx) 283 Scalars.push_back(nullptr); 284 assert(!Scalars[CacheIdx] && "should overwrite existing value"); 285 Scalars[CacheIdx] = V; 286 } 287 288 /// Reset an existing scalar value for \p Def and a given \p Instance. 289 void reset(VPValue *Def, Value *V, const VPIteration &Instance) { 290 auto Iter = Data.PerPartScalars.find(Def); 291 assert(Iter != Data.PerPartScalars.end() && 292 "need to overwrite existing value"); 293 assert(Instance.Part < Iter->second.size() && 294 "need to overwrite existing value"); 295 unsigned CacheIdx = Instance.Lane.mapToCacheIndex(VF); 296 assert(CacheIdx < Iter->second[Instance.Part].size() && 297 "need to overwrite existing value"); 298 Iter->second[Instance.Part][CacheIdx] = V; 299 } 300 301 /// Hold state information used when constructing the CFG of the output IR, 302 /// traversing the VPBasicBlocks and generating corresponding IR BasicBlocks. 303 struct CFGState { 304 /// The previous VPBasicBlock visited. Initially set to null. 305 VPBasicBlock *PrevVPBB = nullptr; 306 307 /// The previous IR BasicBlock created or used. Initially set to the new 308 /// header BasicBlock. 309 BasicBlock *PrevBB = nullptr; 310 311 /// The last IR BasicBlock in the output IR. Set to the exit block of the 312 /// vector loop. 313 BasicBlock *ExitBB = nullptr; 314 315 /// A mapping of each VPBasicBlock to the corresponding BasicBlock. In case 316 /// of replication, maps the BasicBlock of the last replica created. 317 SmallDenseMap<VPBasicBlock *, BasicBlock *> VPBB2IRBB; 318 319 /// Vector of VPBasicBlocks whose terminator instruction needs to be fixed 320 /// up at the end of vector code generation. 321 SmallVector<VPBasicBlock *, 8> VPBBsToFix; 322 323 CFGState() = default; 324 325 /// Returns the BasicBlock* mapped to the pre-header of the loop region 326 /// containing \p R. 327 BasicBlock *getPreheaderBBFor(VPRecipeBase *R); 328 } CFG; 329 330 /// Hold a pointer to LoopInfo to register new basic blocks in the loop. 331 LoopInfo *LI; 332 333 /// Hold a pointer to Dominator Tree to register new basic blocks in the loop. 334 DominatorTree *DT; 335 336 /// Hold a reference to the IRBuilder used to generate output IR code. 337 IRBuilderBase &Builder; 338 339 VPValue2ValueTy VPValue2Value; 340 341 /// Hold the canonical scalar IV of the vector loop (start=0, step=VF*UF). 342 Value *CanonicalIV = nullptr; 343 344 /// Hold a pointer to InnerLoopVectorizer to reuse its IR generation methods. 345 InnerLoopVectorizer *ILV; 346 347 /// Pointer to the VPlan code is generated for. 348 VPlan *Plan; 349 350 /// Holds recipes that may generate a poison value that is used after 351 /// vectorization, even when their operands are not poison. 352 SmallPtrSet<VPRecipeBase *, 16> MayGeneratePoisonRecipes; 353 354 /// The loop object for the current parent region, or nullptr. 355 Loop *CurrentVectorLoop = nullptr; 356 }; 357 358 /// VPUsers instance used by VPBlockBase to manage CondBit and the block 359 /// predicate. Currently VPBlockUsers are used in VPBlockBase for historical 360 /// reasons, but in the future the only VPUsers should either be recipes or 361 /// live-outs.VPBlockBase uses. 362 struct VPBlockUser : public VPUser { 363 VPBlockUser() : VPUser({}, VPUserID::Block) {} 364 365 VPValue *getSingleOperandOrNull() { 366 if (getNumOperands() == 1) 367 return getOperand(0); 368 369 return nullptr; 370 } 371 const VPValue *getSingleOperandOrNull() const { 372 if (getNumOperands() == 1) 373 return getOperand(0); 374 375 return nullptr; 376 } 377 378 void resetSingleOpUser(VPValue *NewVal) { 379 assert(getNumOperands() <= 1 && "Didn't expect more than one operand!"); 380 if (!NewVal) { 381 if (getNumOperands() == 1) 382 removeLastOperand(); 383 return; 384 } 385 386 if (getNumOperands() == 1) 387 setOperand(0, NewVal); 388 else 389 addOperand(NewVal); 390 } 391 }; 392 393 /// VPBlockBase is the building block of the Hierarchical Control-Flow Graph. 394 /// A VPBlockBase can be either a VPBasicBlock or a VPRegionBlock. 395 class VPBlockBase { 396 friend class VPBlockUtils; 397 398 const unsigned char SubclassID; ///< Subclass identifier (for isa/dyn_cast). 399 400 /// An optional name for the block. 401 std::string Name; 402 403 /// The immediate VPRegionBlock which this VPBlockBase belongs to, or null if 404 /// it is a topmost VPBlockBase. 405 VPRegionBlock *Parent = nullptr; 406 407 /// List of predecessor blocks. 408 SmallVector<VPBlockBase *, 1> Predecessors; 409 410 /// List of successor blocks. 411 SmallVector<VPBlockBase *, 1> Successors; 412 413 /// Successor selector managed by a VPUser. For blocks with zero or one 414 /// successors, there is no operand. Otherwise there is exactly one operand 415 /// which is the branch condition. 416 VPBlockUser CondBitUser; 417 418 /// If the block is predicated, its predicate is stored as an operand of this 419 /// VPUser to maintain the def-use relations. Otherwise there is no operand 420 /// here. 421 VPBlockUser PredicateUser; 422 423 /// VPlan containing the block. Can only be set on the entry block of the 424 /// plan. 425 VPlan *Plan = nullptr; 426 427 /// Add \p Successor as the last successor to this block. 428 void appendSuccessor(VPBlockBase *Successor) { 429 assert(Successor && "Cannot add nullptr successor!"); 430 Successors.push_back(Successor); 431 } 432 433 /// Add \p Predecessor as the last predecessor to this block. 434 void appendPredecessor(VPBlockBase *Predecessor) { 435 assert(Predecessor && "Cannot add nullptr predecessor!"); 436 Predecessors.push_back(Predecessor); 437 } 438 439 /// Remove \p Predecessor from the predecessors of this block. 440 void removePredecessor(VPBlockBase *Predecessor) { 441 auto Pos = find(Predecessors, Predecessor); 442 assert(Pos && "Predecessor does not exist"); 443 Predecessors.erase(Pos); 444 } 445 446 /// Remove \p Successor from the successors of this block. 447 void removeSuccessor(VPBlockBase *Successor) { 448 auto Pos = find(Successors, Successor); 449 assert(Pos && "Successor does not exist"); 450 Successors.erase(Pos); 451 } 452 453 protected: 454 VPBlockBase(const unsigned char SC, const std::string &N) 455 : SubclassID(SC), Name(N) {} 456 457 public: 458 /// An enumeration for keeping track of the concrete subclass of VPBlockBase 459 /// that are actually instantiated. Values of this enumeration are kept in the 460 /// SubclassID field of the VPBlockBase objects. They are used for concrete 461 /// type identification. 462 using VPBlockTy = enum { VPBasicBlockSC, VPRegionBlockSC }; 463 464 using VPBlocksTy = SmallVectorImpl<VPBlockBase *>; 465 466 virtual ~VPBlockBase() = default; 467 468 const std::string &getName() const { return Name; } 469 470 void setName(const Twine &newName) { Name = newName.str(); } 471 472 /// \return an ID for the concrete type of this object. 473 /// This is used to implement the classof checks. This should not be used 474 /// for any other purpose, as the values may change as LLVM evolves. 475 unsigned getVPBlockID() const { return SubclassID; } 476 477 VPRegionBlock *getParent() { return Parent; } 478 const VPRegionBlock *getParent() const { return Parent; } 479 480 /// \return A pointer to the plan containing the current block. 481 VPlan *getPlan(); 482 const VPlan *getPlan() const; 483 484 /// Sets the pointer of the plan containing the block. The block must be the 485 /// entry block into the VPlan. 486 void setPlan(VPlan *ParentPlan); 487 488 void setParent(VPRegionBlock *P) { Parent = P; } 489 490 /// \return the VPBasicBlock that is the entry of this VPBlockBase, 491 /// recursively, if the latter is a VPRegionBlock. Otherwise, if this 492 /// VPBlockBase is a VPBasicBlock, it is returned. 493 const VPBasicBlock *getEntryBasicBlock() const; 494 VPBasicBlock *getEntryBasicBlock(); 495 496 /// \return the VPBasicBlock that is the exiting this VPBlockBase, 497 /// recursively, if the latter is a VPRegionBlock. Otherwise, if this 498 /// VPBlockBase is a VPBasicBlock, it is returned. 499 const VPBasicBlock *getExitingBasicBlock() const; 500 VPBasicBlock *getExitingBasicBlock(); 501 502 const VPBlocksTy &getSuccessors() const { return Successors; } 503 VPBlocksTy &getSuccessors() { return Successors; } 504 505 iterator_range<VPBlockBase **> successors() { return Successors; } 506 507 const VPBlocksTy &getPredecessors() const { return Predecessors; } 508 VPBlocksTy &getPredecessors() { return Predecessors; } 509 510 /// \return the successor of this VPBlockBase if it has a single successor. 511 /// Otherwise return a null pointer. 512 VPBlockBase *getSingleSuccessor() const { 513 return (Successors.size() == 1 ? *Successors.begin() : nullptr); 514 } 515 516 /// \return the predecessor of this VPBlockBase if it has a single 517 /// predecessor. Otherwise return a null pointer. 518 VPBlockBase *getSinglePredecessor() const { 519 return (Predecessors.size() == 1 ? *Predecessors.begin() : nullptr); 520 } 521 522 size_t getNumSuccessors() const { return Successors.size(); } 523 size_t getNumPredecessors() const { return Predecessors.size(); } 524 525 /// An Enclosing Block of a block B is any block containing B, including B 526 /// itself. \return the closest enclosing block starting from "this", which 527 /// has successors. \return the root enclosing block if all enclosing blocks 528 /// have no successors. 529 VPBlockBase *getEnclosingBlockWithSuccessors(); 530 531 /// \return the closest enclosing block starting from "this", which has 532 /// predecessors. \return the root enclosing block if all enclosing blocks 533 /// have no predecessors. 534 VPBlockBase *getEnclosingBlockWithPredecessors(); 535 536 /// \return the successors either attached directly to this VPBlockBase or, if 537 /// this VPBlockBase is the exit block of a VPRegionBlock and has no 538 /// successors of its own, search recursively for the first enclosing 539 /// VPRegionBlock that has successors and return them. If no such 540 /// VPRegionBlock exists, return the (empty) successors of the topmost 541 /// VPBlockBase reached. 542 const VPBlocksTy &getHierarchicalSuccessors() { 543 return getEnclosingBlockWithSuccessors()->getSuccessors(); 544 } 545 546 /// \return the hierarchical successor of this VPBlockBase if it has a single 547 /// hierarchical successor. Otherwise return a null pointer. 548 VPBlockBase *getSingleHierarchicalSuccessor() { 549 return getEnclosingBlockWithSuccessors()->getSingleSuccessor(); 550 } 551 552 /// \return the predecessors either attached directly to this VPBlockBase or, 553 /// if this VPBlockBase is the entry block of a VPRegionBlock and has no 554 /// predecessors of its own, search recursively for the first enclosing 555 /// VPRegionBlock that has predecessors and return them. If no such 556 /// VPRegionBlock exists, return the (empty) predecessors of the topmost 557 /// VPBlockBase reached. 558 const VPBlocksTy &getHierarchicalPredecessors() { 559 return getEnclosingBlockWithPredecessors()->getPredecessors(); 560 } 561 562 /// \return the hierarchical predecessor of this VPBlockBase if it has a 563 /// single hierarchical predecessor. Otherwise return a null pointer. 564 VPBlockBase *getSingleHierarchicalPredecessor() { 565 return getEnclosingBlockWithPredecessors()->getSinglePredecessor(); 566 } 567 568 /// \return the condition bit selecting the successor. 569 VPValue *getCondBit(); 570 /// \return the condition bit selecting the successor. 571 const VPValue *getCondBit() const; 572 /// Set the condition bit selecting the successor. 573 void setCondBit(VPValue *CV); 574 575 /// \return the block's predicate. 576 VPValue *getPredicate(); 577 /// \return the block's predicate. 578 const VPValue *getPredicate() const; 579 /// Set the block's predicate. 580 void setPredicate(VPValue *Pred); 581 582 /// Set a given VPBlockBase \p Successor as the single successor of this 583 /// VPBlockBase. This VPBlockBase is not added as predecessor of \p Successor. 584 /// This VPBlockBase must have no successors. 585 void setOneSuccessor(VPBlockBase *Successor) { 586 assert(Successors.empty() && "Setting one successor when others exist."); 587 appendSuccessor(Successor); 588 } 589 590 /// Set two given VPBlockBases \p IfTrue and \p IfFalse to be the two 591 /// successors of this VPBlockBase. \p Condition is set as the successor 592 /// selector. This VPBlockBase is not added as predecessor of \p IfTrue or \p 593 /// IfFalse. This VPBlockBase must have no successors. 594 void setTwoSuccessors(VPBlockBase *IfTrue, VPBlockBase *IfFalse, 595 VPValue *Condition) { 596 assert(Successors.empty() && "Setting two successors when others exist."); 597 assert(Condition && "Setting two successors without condition!"); 598 setCondBit(Condition); 599 appendSuccessor(IfTrue); 600 appendSuccessor(IfFalse); 601 } 602 603 /// Set each VPBasicBlock in \p NewPreds as predecessor of this VPBlockBase. 604 /// This VPBlockBase must have no predecessors. This VPBlockBase is not added 605 /// as successor of any VPBasicBlock in \p NewPreds. 606 void setPredecessors(ArrayRef<VPBlockBase *> NewPreds) { 607 assert(Predecessors.empty() && "Block predecessors already set."); 608 for (auto *Pred : NewPreds) 609 appendPredecessor(Pred); 610 } 611 612 /// Remove all the predecessor of this block. 613 void clearPredecessors() { Predecessors.clear(); } 614 615 /// Remove all the successors of this block and set to null its condition bit 616 void clearSuccessors() { 617 Successors.clear(); 618 setCondBit(nullptr); 619 } 620 621 /// The method which generates the output IR that correspond to this 622 /// VPBlockBase, thereby "executing" the VPlan. 623 virtual void execute(struct VPTransformState *State) = 0; 624 625 /// Delete all blocks reachable from a given VPBlockBase, inclusive. 626 static void deleteCFG(VPBlockBase *Entry); 627 628 /// Return true if it is legal to hoist instructions into this block. 629 bool isLegalToHoistInto() { 630 // There are currently no constraints that prevent an instruction to be 631 // hoisted into a VPBlockBase. 632 return true; 633 } 634 635 /// Replace all operands of VPUsers in the block with \p NewValue and also 636 /// replaces all uses of VPValues defined in the block with NewValue. 637 virtual void dropAllReferences(VPValue *NewValue) = 0; 638 639 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 640 void printAsOperand(raw_ostream &OS, bool PrintType) const { 641 OS << getName(); 642 } 643 644 /// Print plain-text dump of this VPBlockBase to \p O, prefixing all lines 645 /// with \p Indent. \p SlotTracker is used to print unnamed VPValue's using 646 /// consequtive numbers. 647 /// 648 /// Note that the numbering is applied to the whole VPlan, so printing 649 /// individual blocks is consistent with the whole VPlan printing. 650 virtual void print(raw_ostream &O, const Twine &Indent, 651 VPSlotTracker &SlotTracker) const = 0; 652 653 /// Print plain-text dump of this VPlan to \p O. 654 void print(raw_ostream &O) const { 655 VPSlotTracker SlotTracker(getPlan()); 656 print(O, "", SlotTracker); 657 } 658 659 /// Print the successors of this block to \p O, prefixing all lines with \p 660 /// Indent. 661 void printSuccessors(raw_ostream &O, const Twine &Indent) const; 662 663 /// Dump this VPBlockBase to dbgs(). 664 LLVM_DUMP_METHOD void dump() const { print(dbgs()); } 665 #endif 666 }; 667 668 /// A value that is used outside the VPlan. The operand of the user needs to be 669 /// added to the associated LCSSA phi node. 670 class VPLiveOut : public VPUser { 671 PHINode *Phi; 672 673 public: 674 VPLiveOut(PHINode *Phi, VPValue *Op) 675 : VPUser({Op}, VPUser::VPUserID::LiveOut), Phi(Phi) {} 676 677 /// Fixup the wrapped LCSSA phi node in the unique exit block. This simply 678 /// means we need to add the appropriate incoming value from the middle 679 /// block as exiting edges from the scalar epilogue loop (if present) are 680 /// already in place, and we exit the vector loop exclusively to the middle 681 /// block. 682 void fixPhi(VPlan &Plan, VPTransformState &State); 683 684 /// Returns true if the VPLiveOut uses scalars of operand \p Op. 685 bool usesScalars(const VPValue *Op) const override { 686 assert(is_contained(operands(), Op) && 687 "Op must be an operand of the recipe"); 688 return true; 689 } 690 691 PHINode *getPhi() const { return Phi; } 692 }; 693 694 /// VPRecipeBase is a base class modeling a sequence of one or more output IR 695 /// instructions. VPRecipeBase owns the the VPValues it defines through VPDef 696 /// and is responsible for deleting its defined values. Single-value 697 /// VPRecipeBases that also inherit from VPValue must make sure to inherit from 698 /// VPRecipeBase before VPValue. 699 class VPRecipeBase : public ilist_node_with_parent<VPRecipeBase, VPBasicBlock>, 700 public VPDef, 701 public VPUser { 702 friend VPBasicBlock; 703 friend class VPBlockUtils; 704 705 /// Each VPRecipe belongs to a single VPBasicBlock. 706 VPBasicBlock *Parent = nullptr; 707 708 public: 709 VPRecipeBase(const unsigned char SC, ArrayRef<VPValue *> Operands) 710 : VPDef(SC), VPUser(Operands, VPUser::VPUserID::Recipe) {} 711 712 template <typename IterT> 713 VPRecipeBase(const unsigned char SC, iterator_range<IterT> Operands) 714 : VPDef(SC), VPUser(Operands, VPUser::VPUserID::Recipe) {} 715 virtual ~VPRecipeBase() = default; 716 717 /// \return the VPBasicBlock which this VPRecipe belongs to. 718 VPBasicBlock *getParent() { return Parent; } 719 const VPBasicBlock *getParent() const { return Parent; } 720 721 /// The method which generates the output IR instructions that correspond to 722 /// this VPRecipe, thereby "executing" the VPlan. 723 virtual void execute(struct VPTransformState &State) = 0; 724 725 /// Insert an unlinked recipe into a basic block immediately before 726 /// the specified recipe. 727 void insertBefore(VPRecipeBase *InsertPos); 728 /// Insert an unlinked recipe into \p BB immediately before the insertion 729 /// point \p IP; 730 void insertBefore(VPBasicBlock &BB, iplist<VPRecipeBase>::iterator IP); 731 732 /// Insert an unlinked Recipe into a basic block immediately after 733 /// the specified Recipe. 734 void insertAfter(VPRecipeBase *InsertPos); 735 736 /// Unlink this recipe from its current VPBasicBlock and insert it into 737 /// the VPBasicBlock that MovePos lives in, right after MovePos. 738 void moveAfter(VPRecipeBase *MovePos); 739 740 /// Unlink this recipe and insert into BB before I. 741 /// 742 /// \pre I is a valid iterator into BB. 743 void moveBefore(VPBasicBlock &BB, iplist<VPRecipeBase>::iterator I); 744 745 /// This method unlinks 'this' from the containing basic block, but does not 746 /// delete it. 747 void removeFromParent(); 748 749 /// This method unlinks 'this' from the containing basic block and deletes it. 750 /// 751 /// \returns an iterator pointing to the element after the erased one 752 iplist<VPRecipeBase>::iterator eraseFromParent(); 753 754 /// Returns the underlying instruction, if the recipe is a VPValue or nullptr 755 /// otherwise. 756 Instruction *getUnderlyingInstr() { 757 return cast<Instruction>(getVPSingleValue()->getUnderlyingValue()); 758 } 759 const Instruction *getUnderlyingInstr() const { 760 return cast<Instruction>(getVPSingleValue()->getUnderlyingValue()); 761 } 762 763 /// Method to support type inquiry through isa, cast, and dyn_cast. 764 static inline bool classof(const VPDef *D) { 765 // All VPDefs are also VPRecipeBases. 766 return true; 767 } 768 769 static inline bool classof(const VPUser *U) { 770 return U->getVPUserID() == VPUser::VPUserID::Recipe; 771 } 772 773 /// Returns true if the recipe may have side-effects. 774 bool mayHaveSideEffects() const; 775 776 /// Returns true for PHI-like recipes. 777 bool isPhi() const { 778 return getVPDefID() >= VPFirstPHISC && getVPDefID() <= VPLastPHISC; 779 } 780 781 /// Returns true if the recipe may read from memory. 782 bool mayReadFromMemory() const; 783 784 /// Returns true if the recipe may write to memory. 785 bool mayWriteToMemory() const; 786 787 /// Returns true if the recipe may read from or write to memory. 788 bool mayReadOrWriteMemory() const { 789 return mayReadFromMemory() || mayWriteToMemory(); 790 } 791 }; 792 793 inline bool VPUser::classof(const VPDef *Def) { 794 return Def->getVPDefID() == VPRecipeBase::VPInstructionSC || 795 Def->getVPDefID() == VPRecipeBase::VPWidenSC || 796 Def->getVPDefID() == VPRecipeBase::VPWidenCallSC || 797 Def->getVPDefID() == VPRecipeBase::VPWidenSelectSC || 798 Def->getVPDefID() == VPRecipeBase::VPWidenGEPSC || 799 Def->getVPDefID() == VPRecipeBase::VPBlendSC || 800 Def->getVPDefID() == VPRecipeBase::VPInterleaveSC || 801 Def->getVPDefID() == VPRecipeBase::VPReplicateSC || 802 Def->getVPDefID() == VPRecipeBase::VPReductionSC || 803 Def->getVPDefID() == VPRecipeBase::VPBranchOnMaskSC || 804 Def->getVPDefID() == VPRecipeBase::VPWidenMemoryInstructionSC; 805 } 806 807 /// This is a concrete Recipe that models a single VPlan-level instruction. 808 /// While as any Recipe it may generate a sequence of IR instructions when 809 /// executed, these instructions would always form a single-def expression as 810 /// the VPInstruction is also a single def-use vertex. 811 class VPInstruction : public VPRecipeBase, public VPValue { 812 friend class VPlanSlp; 813 814 public: 815 /// VPlan opcodes, extending LLVM IR with idiomatics instructions. 816 enum { 817 FirstOrderRecurrenceSplice = 818 Instruction::OtherOpsEnd + 1, // Combines the incoming and previous 819 // values of a first-order recurrence. 820 Not, 821 ICmpULE, 822 SLPLoad, 823 SLPStore, 824 ActiveLaneMask, 825 CanonicalIVIncrement, 826 CanonicalIVIncrementNUW, 827 BranchOnCount, 828 }; 829 830 private: 831 typedef unsigned char OpcodeTy; 832 OpcodeTy Opcode; 833 FastMathFlags FMF; 834 DebugLoc DL; 835 836 /// Utility method serving execute(): generates a single instance of the 837 /// modeled instruction. 838 void generateInstruction(VPTransformState &State, unsigned Part); 839 840 protected: 841 void setUnderlyingInstr(Instruction *I) { setUnderlyingValue(I); } 842 843 public: 844 VPInstruction(unsigned Opcode, ArrayRef<VPValue *> Operands, DebugLoc DL) 845 : VPRecipeBase(VPRecipeBase::VPInstructionSC, Operands), 846 VPValue(VPValue::VPVInstructionSC, nullptr, this), Opcode(Opcode), 847 DL(DL) {} 848 849 VPInstruction(unsigned Opcode, std::initializer_list<VPValue *> Operands, 850 DebugLoc DL = {}) 851 : VPInstruction(Opcode, ArrayRef<VPValue *>(Operands), DL) {} 852 853 /// Method to support type inquiry through isa, cast, and dyn_cast. 854 static inline bool classof(const VPValue *V) { 855 return V->getVPValueID() == VPValue::VPVInstructionSC; 856 } 857 858 VPInstruction *clone() const { 859 SmallVector<VPValue *, 2> Operands(operands()); 860 return new VPInstruction(Opcode, Operands, DL); 861 } 862 863 /// Method to support type inquiry through isa, cast, and dyn_cast. 864 static inline bool classof(const VPDef *R) { 865 return R->getVPDefID() == VPRecipeBase::VPInstructionSC; 866 } 867 868 /// Extra classof implementations to allow directly casting from VPUser -> 869 /// VPInstruction. 870 static inline bool classof(const VPUser *U) { 871 auto *R = dyn_cast<VPRecipeBase>(U); 872 return R && R->getVPDefID() == VPRecipeBase::VPInstructionSC; 873 } 874 static inline bool classof(const VPRecipeBase *R) { 875 return R->getVPDefID() == VPRecipeBase::VPInstructionSC; 876 } 877 878 unsigned getOpcode() const { return Opcode; } 879 880 /// Generate the instruction. 881 /// TODO: We currently execute only per-part unless a specific instance is 882 /// provided. 883 void execute(VPTransformState &State) override; 884 885 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 886 /// Print the VPInstruction to \p O. 887 void print(raw_ostream &O, const Twine &Indent, 888 VPSlotTracker &SlotTracker) const override; 889 890 /// Print the VPInstruction to dbgs() (for debugging). 891 LLVM_DUMP_METHOD void dump() const; 892 #endif 893 894 /// Return true if this instruction may modify memory. 895 bool mayWriteToMemory() const { 896 // TODO: we can use attributes of the called function to rule out memory 897 // modifications. 898 return Opcode == Instruction::Store || Opcode == Instruction::Call || 899 Opcode == Instruction::Invoke || Opcode == SLPStore; 900 } 901 902 bool hasResult() const { 903 // CallInst may or may not have a result, depending on the called function. 904 // Conservatively return calls have results for now. 905 switch (getOpcode()) { 906 case Instruction::Ret: 907 case Instruction::Br: 908 case Instruction::Store: 909 case Instruction::Switch: 910 case Instruction::IndirectBr: 911 case Instruction::Resume: 912 case Instruction::CatchRet: 913 case Instruction::Unreachable: 914 case Instruction::Fence: 915 case Instruction::AtomicRMW: 916 case VPInstruction::BranchOnCount: 917 return false; 918 default: 919 return true; 920 } 921 } 922 923 /// Set the fast-math flags. 924 void setFastMathFlags(FastMathFlags FMFNew); 925 926 /// Returns true if the recipe only uses the first lane of operand \p Op. 927 bool onlyFirstLaneUsed(const VPValue *Op) const override { 928 assert(is_contained(operands(), Op) && 929 "Op must be an operand of the recipe"); 930 if (getOperand(0) != Op) 931 return false; 932 switch (getOpcode()) { 933 default: 934 return false; 935 case VPInstruction::ActiveLaneMask: 936 case VPInstruction::CanonicalIVIncrement: 937 case VPInstruction::CanonicalIVIncrementNUW: 938 case VPInstruction::BranchOnCount: 939 return true; 940 }; 941 llvm_unreachable("switch should return"); 942 } 943 }; 944 945 /// VPWidenRecipe is a recipe for producing a copy of vector type its 946 /// ingredient. This recipe covers most of the traditional vectorization cases 947 /// where each ingredient transforms into a vectorized version of itself. 948 class VPWidenRecipe : public VPRecipeBase, public VPValue { 949 public: 950 template <typename IterT> 951 VPWidenRecipe(Instruction &I, iterator_range<IterT> Operands) 952 : VPRecipeBase(VPRecipeBase::VPWidenSC, Operands), 953 VPValue(VPValue::VPVWidenSC, &I, this) {} 954 955 ~VPWidenRecipe() override = default; 956 957 /// Method to support type inquiry through isa, cast, and dyn_cast. 958 static inline bool classof(const VPDef *D) { 959 return D->getVPDefID() == VPRecipeBase::VPWidenSC; 960 } 961 static inline bool classof(const VPValue *V) { 962 return V->getVPValueID() == VPValue::VPVWidenSC; 963 } 964 965 /// Produce widened copies of all Ingredients. 966 void execute(VPTransformState &State) override; 967 968 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 969 /// Print the recipe. 970 void print(raw_ostream &O, const Twine &Indent, 971 VPSlotTracker &SlotTracker) const override; 972 #endif 973 }; 974 975 /// A recipe for widening Call instructions. 976 class VPWidenCallRecipe : public VPRecipeBase, public VPValue { 977 978 public: 979 template <typename IterT> 980 VPWidenCallRecipe(CallInst &I, iterator_range<IterT> CallArguments) 981 : VPRecipeBase(VPRecipeBase::VPWidenCallSC, CallArguments), 982 VPValue(VPValue::VPVWidenCallSC, &I, this) {} 983 984 ~VPWidenCallRecipe() override = default; 985 986 /// Method to support type inquiry through isa, cast, and dyn_cast. 987 static inline bool classof(const VPDef *D) { 988 return D->getVPDefID() == VPRecipeBase::VPWidenCallSC; 989 } 990 991 /// Produce a widened version of the call instruction. 992 void execute(VPTransformState &State) override; 993 994 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 995 /// Print the recipe. 996 void print(raw_ostream &O, const Twine &Indent, 997 VPSlotTracker &SlotTracker) const override; 998 #endif 999 }; 1000 1001 /// A recipe for widening select instructions. 1002 class VPWidenSelectRecipe : public VPRecipeBase, public VPValue { 1003 1004 /// Is the condition of the select loop invariant? 1005 bool InvariantCond; 1006 1007 public: 1008 template <typename IterT> 1009 VPWidenSelectRecipe(SelectInst &I, iterator_range<IterT> Operands, 1010 bool InvariantCond) 1011 : VPRecipeBase(VPRecipeBase::VPWidenSelectSC, Operands), 1012 VPValue(VPValue::VPVWidenSelectSC, &I, this), 1013 InvariantCond(InvariantCond) {} 1014 1015 ~VPWidenSelectRecipe() override = default; 1016 1017 /// Method to support type inquiry through isa, cast, and dyn_cast. 1018 static inline bool classof(const VPDef *D) { 1019 return D->getVPDefID() == VPRecipeBase::VPWidenSelectSC; 1020 } 1021 1022 /// Produce a widened version of the select instruction. 1023 void execute(VPTransformState &State) override; 1024 1025 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1026 /// Print the recipe. 1027 void print(raw_ostream &O, const Twine &Indent, 1028 VPSlotTracker &SlotTracker) const override; 1029 #endif 1030 }; 1031 1032 /// A recipe for handling GEP instructions. 1033 class VPWidenGEPRecipe : public VPRecipeBase, public VPValue { 1034 bool IsPtrLoopInvariant; 1035 SmallBitVector IsIndexLoopInvariant; 1036 1037 public: 1038 template <typename IterT> 1039 VPWidenGEPRecipe(GetElementPtrInst *GEP, iterator_range<IterT> Operands) 1040 : VPRecipeBase(VPRecipeBase::VPWidenGEPSC, Operands), 1041 VPValue(VPWidenGEPSC, GEP, this), 1042 IsIndexLoopInvariant(GEP->getNumIndices(), false) {} 1043 1044 template <typename IterT> 1045 VPWidenGEPRecipe(GetElementPtrInst *GEP, iterator_range<IterT> Operands, 1046 Loop *OrigLoop) 1047 : VPRecipeBase(VPRecipeBase::VPWidenGEPSC, Operands), 1048 VPValue(VPValue::VPVWidenGEPSC, GEP, this), 1049 IsIndexLoopInvariant(GEP->getNumIndices(), false) { 1050 IsPtrLoopInvariant = OrigLoop->isLoopInvariant(GEP->getPointerOperand()); 1051 for (auto Index : enumerate(GEP->indices())) 1052 IsIndexLoopInvariant[Index.index()] = 1053 OrigLoop->isLoopInvariant(Index.value().get()); 1054 } 1055 ~VPWidenGEPRecipe() override = default; 1056 1057 /// Method to support type inquiry through isa, cast, and dyn_cast. 1058 static inline bool classof(const VPDef *D) { 1059 return D->getVPDefID() == VPRecipeBase::VPWidenGEPSC; 1060 } 1061 1062 /// Generate the gep nodes. 1063 void execute(VPTransformState &State) override; 1064 1065 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1066 /// Print the recipe. 1067 void print(raw_ostream &O, const Twine &Indent, 1068 VPSlotTracker &SlotTracker) const override; 1069 #endif 1070 }; 1071 1072 /// A recipe for handling phi nodes of integer and floating-point inductions, 1073 /// producing their vector values. 1074 class VPWidenIntOrFpInductionRecipe : public VPRecipeBase, public VPValue { 1075 PHINode *IV; 1076 const InductionDescriptor &IndDesc; 1077 bool NeedsScalarIV; 1078 bool NeedsVectorIV; 1079 1080 public: 1081 VPWidenIntOrFpInductionRecipe(PHINode *IV, VPValue *Start, VPValue *Step, 1082 const InductionDescriptor &IndDesc, 1083 bool NeedsScalarIV, bool NeedsVectorIV) 1084 : VPRecipeBase(VPWidenIntOrFpInductionSC, {Start, Step}), 1085 VPValue(IV, this), IV(IV), IndDesc(IndDesc), 1086 NeedsScalarIV(NeedsScalarIV), NeedsVectorIV(NeedsVectorIV) {} 1087 1088 VPWidenIntOrFpInductionRecipe(PHINode *IV, VPValue *Start, VPValue *Step, 1089 const InductionDescriptor &IndDesc, 1090 TruncInst *Trunc, bool NeedsScalarIV, 1091 bool NeedsVectorIV) 1092 : VPRecipeBase(VPWidenIntOrFpInductionSC, {Start, Step}), 1093 VPValue(Trunc, this), IV(IV), IndDesc(IndDesc), 1094 NeedsScalarIV(NeedsScalarIV), NeedsVectorIV(NeedsVectorIV) {} 1095 1096 ~VPWidenIntOrFpInductionRecipe() override = default; 1097 1098 /// Method to support type inquiry through isa, cast, and dyn_cast. 1099 static inline bool classof(const VPDef *D) { 1100 return D->getVPDefID() == VPRecipeBase::VPWidenIntOrFpInductionSC; 1101 } 1102 1103 /// Generate the vectorized and scalarized versions of the phi node as 1104 /// needed by their users. 1105 void execute(VPTransformState &State) override; 1106 1107 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1108 /// Print the recipe. 1109 void print(raw_ostream &O, const Twine &Indent, 1110 VPSlotTracker &SlotTracker) const override; 1111 #endif 1112 1113 /// Returns the start value of the induction. 1114 VPValue *getStartValue() { return getOperand(0); } 1115 const VPValue *getStartValue() const { return getOperand(0); } 1116 1117 /// Returns the step value of the induction. 1118 VPValue *getStepValue() { return getOperand(1); } 1119 const VPValue *getStepValue() const { return getOperand(1); } 1120 1121 /// Returns the first defined value as TruncInst, if it is one or nullptr 1122 /// otherwise. 1123 TruncInst *getTruncInst() { 1124 return dyn_cast_or_null<TruncInst>(getVPValue(0)->getUnderlyingValue()); 1125 } 1126 const TruncInst *getTruncInst() const { 1127 return dyn_cast_or_null<TruncInst>(getVPValue(0)->getUnderlyingValue()); 1128 } 1129 1130 PHINode *getPHINode() { return IV; } 1131 1132 /// Returns the induction descriptor for the recipe. 1133 const InductionDescriptor &getInductionDescriptor() const { return IndDesc; } 1134 1135 /// Returns true if the induction is canonical, i.e. starting at 0 and 1136 /// incremented by UF * VF (= the original IV is incremented by 1). 1137 bool isCanonical() const; 1138 1139 /// Returns the scalar type of the induction. 1140 const Type *getScalarType() const { 1141 const TruncInst *TruncI = getTruncInst(); 1142 return TruncI ? TruncI->getType() : IV->getType(); 1143 } 1144 1145 /// Returns true if a scalar phi needs to be created for the induction. 1146 bool needsScalarIV() const { return NeedsScalarIV; } 1147 1148 /// Returns true if a vector phi needs to be created for the induction. 1149 bool needsVectorIV() const { return NeedsVectorIV; } 1150 }; 1151 1152 /// A pure virtual base class for all recipes modeling header phis, including 1153 /// phis for first order recurrences, pointer inductions and reductions. The 1154 /// start value is the first operand of the recipe and the incoming value from 1155 /// the backedge is the second operand. 1156 class VPHeaderPHIRecipe : public VPRecipeBase, public VPValue { 1157 protected: 1158 VPHeaderPHIRecipe(unsigned char VPVID, unsigned char VPDefID, PHINode *Phi, 1159 VPValue *Start = nullptr) 1160 : VPRecipeBase(VPDefID, {}), VPValue(VPVID, Phi, this) { 1161 if (Start) 1162 addOperand(Start); 1163 } 1164 1165 public: 1166 ~VPHeaderPHIRecipe() override = default; 1167 1168 /// Method to support type inquiry through isa, cast, and dyn_cast. 1169 static inline bool classof(const VPRecipeBase *B) { 1170 return B->getVPDefID() == VPRecipeBase::VPCanonicalIVPHISC || 1171 B->getVPDefID() == VPRecipeBase::VPFirstOrderRecurrencePHISC || 1172 B->getVPDefID() == VPRecipeBase::VPReductionPHISC || 1173 B->getVPDefID() == VPRecipeBase::VPWidenIntOrFpInductionSC || 1174 B->getVPDefID() == VPRecipeBase::VPWidenPHISC; 1175 } 1176 static inline bool classof(const VPValue *V) { 1177 return V->getVPValueID() == VPValue::VPVCanonicalIVPHISC || 1178 V->getVPValueID() == VPValue::VPVFirstOrderRecurrencePHISC || 1179 V->getVPValueID() == VPValue::VPVReductionPHISC || 1180 V->getVPValueID() == VPValue::VPVWidenIntOrFpInductionSC || 1181 V->getVPValueID() == VPValue::VPVWidenPHISC; 1182 } 1183 1184 /// Generate the phi nodes. 1185 void execute(VPTransformState &State) override = 0; 1186 1187 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1188 /// Print the recipe. 1189 void print(raw_ostream &O, const Twine &Indent, 1190 VPSlotTracker &SlotTracker) const override = 0; 1191 #endif 1192 1193 /// Returns the start value of the phi, if one is set. 1194 VPValue *getStartValue() { 1195 return getNumOperands() == 0 ? nullptr : getOperand(0); 1196 } 1197 VPValue *getStartValue() const { 1198 return getNumOperands() == 0 ? nullptr : getOperand(0); 1199 } 1200 1201 /// Returns the incoming value from the loop backedge. 1202 VPValue *getBackedgeValue() { 1203 return getOperand(1); 1204 } 1205 1206 /// Returns the backedge value as a recipe. The backedge value is guaranteed 1207 /// to be a recipe. 1208 VPRecipeBase *getBackedgeRecipe() { 1209 return cast<VPRecipeBase>(getBackedgeValue()->getDef()); 1210 } 1211 }; 1212 1213 class VPWidenPointerInductionRecipe : public VPHeaderPHIRecipe { 1214 const InductionDescriptor &IndDesc; 1215 1216 /// SCEV used to expand step. 1217 /// FIXME: move expansion of step to the pre-header, once it is modeled 1218 /// explicitly. 1219 ScalarEvolution &SE; 1220 1221 public: 1222 /// Create a new VPWidenPointerInductionRecipe for \p Phi with start value \p 1223 /// Start. 1224 VPWidenPointerInductionRecipe(PHINode *Phi, VPValue *Start, 1225 const InductionDescriptor &IndDesc, 1226 ScalarEvolution &SE) 1227 : VPHeaderPHIRecipe(VPVWidenPointerInductionSC, VPWidenPointerInductionSC, 1228 Phi), 1229 IndDesc(IndDesc), SE(SE) { 1230 addOperand(Start); 1231 } 1232 1233 ~VPWidenPointerInductionRecipe() override = default; 1234 1235 /// Method to support type inquiry through isa, cast, and dyn_cast. 1236 static inline bool classof(const VPRecipeBase *B) { 1237 return B->getVPDefID() == VPRecipeBase::VPWidenPointerInductionSC; 1238 } 1239 static inline bool classof(const VPHeaderPHIRecipe *R) { 1240 return R->getVPDefID() == VPRecipeBase::VPWidenPointerInductionSC; 1241 } 1242 static inline bool classof(const VPValue *V) { 1243 return V->getVPValueID() == VPValue::VPVWidenPointerInductionSC; 1244 } 1245 1246 /// Generate vector values for the pointer induction. 1247 void execute(VPTransformState &State) override; 1248 1249 /// Returns true if only scalar values will be generated. 1250 bool onlyScalarsGenerated(ElementCount VF); 1251 1252 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1253 /// Print the recipe. 1254 void print(raw_ostream &O, const Twine &Indent, 1255 VPSlotTracker &SlotTracker) const override; 1256 #endif 1257 }; 1258 1259 /// A recipe for handling header phis that are widened in the vector loop. 1260 /// In the VPlan native path, all incoming VPValues & VPBasicBlock pairs are 1261 /// managed in the recipe directly. 1262 class VPWidenPHIRecipe : public VPHeaderPHIRecipe { 1263 /// List of incoming blocks. Only used in the VPlan native path. 1264 SmallVector<VPBasicBlock *, 2> IncomingBlocks; 1265 1266 public: 1267 /// Create a new VPWidenPHIRecipe for \p Phi with start value \p Start. 1268 VPWidenPHIRecipe(PHINode *Phi, VPValue *Start = nullptr) 1269 : VPHeaderPHIRecipe(VPVWidenPHISC, VPWidenPHISC, Phi) { 1270 if (Start) 1271 addOperand(Start); 1272 } 1273 1274 ~VPWidenPHIRecipe() override = default; 1275 1276 /// Method to support type inquiry through isa, cast, and dyn_cast. 1277 static inline bool classof(const VPRecipeBase *B) { 1278 return B->getVPDefID() == VPRecipeBase::VPWidenPHISC; 1279 } 1280 static inline bool classof(const VPHeaderPHIRecipe *R) { 1281 return R->getVPDefID() == VPRecipeBase::VPWidenPHISC; 1282 } 1283 static inline bool classof(const VPValue *V) { 1284 return V->getVPValueID() == VPValue::VPVWidenPHISC; 1285 } 1286 1287 /// Generate the phi/select nodes. 1288 void execute(VPTransformState &State) override; 1289 1290 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1291 /// Print the recipe. 1292 void print(raw_ostream &O, const Twine &Indent, 1293 VPSlotTracker &SlotTracker) const override; 1294 #endif 1295 1296 /// Adds a pair (\p IncomingV, \p IncomingBlock) to the phi. 1297 void addIncoming(VPValue *IncomingV, VPBasicBlock *IncomingBlock) { 1298 addOperand(IncomingV); 1299 IncomingBlocks.push_back(IncomingBlock); 1300 } 1301 1302 /// Returns the \p I th incoming VPBasicBlock. 1303 VPBasicBlock *getIncomingBlock(unsigned I) { return IncomingBlocks[I]; } 1304 1305 /// Returns the \p I th incoming VPValue. 1306 VPValue *getIncomingValue(unsigned I) { return getOperand(I); } 1307 }; 1308 1309 /// A recipe for handling first-order recurrence phis. The start value is the 1310 /// first operand of the recipe and the incoming value from the backedge is the 1311 /// second operand. 1312 struct VPFirstOrderRecurrencePHIRecipe : public VPHeaderPHIRecipe { 1313 VPFirstOrderRecurrencePHIRecipe(PHINode *Phi, VPValue &Start) 1314 : VPHeaderPHIRecipe(VPVFirstOrderRecurrencePHISC, 1315 VPFirstOrderRecurrencePHISC, Phi, &Start) {} 1316 1317 /// Method to support type inquiry through isa, cast, and dyn_cast. 1318 static inline bool classof(const VPRecipeBase *R) { 1319 return R->getVPDefID() == VPRecipeBase::VPFirstOrderRecurrencePHISC; 1320 } 1321 static inline bool classof(const VPHeaderPHIRecipe *R) { 1322 return R->getVPDefID() == VPRecipeBase::VPFirstOrderRecurrencePHISC; 1323 } 1324 static inline bool classof(const VPValue *V) { 1325 return V->getVPValueID() == VPValue::VPVFirstOrderRecurrencePHISC; 1326 } 1327 1328 void execute(VPTransformState &State) override; 1329 1330 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1331 /// Print the recipe. 1332 void print(raw_ostream &O, const Twine &Indent, 1333 VPSlotTracker &SlotTracker) const override; 1334 #endif 1335 }; 1336 1337 /// A recipe for handling reduction phis. The start value is the first operand 1338 /// of the recipe and the incoming value from the backedge is the second 1339 /// operand. 1340 class VPReductionPHIRecipe : public VPHeaderPHIRecipe { 1341 /// Descriptor for the reduction. 1342 const RecurrenceDescriptor &RdxDesc; 1343 1344 /// The phi is part of an in-loop reduction. 1345 bool IsInLoop; 1346 1347 /// The phi is part of an ordered reduction. Requires IsInLoop to be true. 1348 bool IsOrdered; 1349 1350 public: 1351 /// Create a new VPReductionPHIRecipe for the reduction \p Phi described by \p 1352 /// RdxDesc. 1353 VPReductionPHIRecipe(PHINode *Phi, const RecurrenceDescriptor &RdxDesc, 1354 VPValue &Start, bool IsInLoop = false, 1355 bool IsOrdered = false) 1356 : VPHeaderPHIRecipe(VPVReductionPHISC, VPReductionPHISC, Phi, &Start), 1357 RdxDesc(RdxDesc), IsInLoop(IsInLoop), IsOrdered(IsOrdered) { 1358 assert((!IsOrdered || IsInLoop) && "IsOrdered requires IsInLoop"); 1359 } 1360 1361 ~VPReductionPHIRecipe() override = default; 1362 1363 /// Method to support type inquiry through isa, cast, and dyn_cast. 1364 static inline bool classof(const VPRecipeBase *R) { 1365 return R->getVPDefID() == VPRecipeBase::VPReductionPHISC; 1366 } 1367 static inline bool classof(const VPHeaderPHIRecipe *R) { 1368 return R->getVPDefID() == VPRecipeBase::VPReductionPHISC; 1369 } 1370 static inline bool classof(const VPValue *V) { 1371 return V->getVPValueID() == VPValue::VPVReductionPHISC; 1372 } 1373 1374 /// Generate the phi/select nodes. 1375 void execute(VPTransformState &State) override; 1376 1377 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1378 /// Print the recipe. 1379 void print(raw_ostream &O, const Twine &Indent, 1380 VPSlotTracker &SlotTracker) const override; 1381 #endif 1382 1383 const RecurrenceDescriptor &getRecurrenceDescriptor() const { 1384 return RdxDesc; 1385 } 1386 1387 /// Returns true, if the phi is part of an ordered reduction. 1388 bool isOrdered() const { return IsOrdered; } 1389 1390 /// Returns true, if the phi is part of an in-loop reduction. 1391 bool isInLoop() const { return IsInLoop; } 1392 }; 1393 1394 /// A recipe for vectorizing a phi-node as a sequence of mask-based select 1395 /// instructions. 1396 class VPBlendRecipe : public VPRecipeBase, public VPValue { 1397 PHINode *Phi; 1398 1399 public: 1400 /// The blend operation is a User of the incoming values and of their 1401 /// respective masks, ordered [I0, M0, I1, M1, ...]. Note that a single value 1402 /// might be incoming with a full mask for which there is no VPValue. 1403 VPBlendRecipe(PHINode *Phi, ArrayRef<VPValue *> Operands) 1404 : VPRecipeBase(VPBlendSC, Operands), 1405 VPValue(VPValue::VPVBlendSC, Phi, this), Phi(Phi) { 1406 assert(Operands.size() > 0 && 1407 ((Operands.size() == 1) || (Operands.size() % 2 == 0)) && 1408 "Expected either a single incoming value or a positive even number " 1409 "of operands"); 1410 } 1411 1412 /// Method to support type inquiry through isa, cast, and dyn_cast. 1413 static inline bool classof(const VPDef *D) { 1414 return D->getVPDefID() == VPRecipeBase::VPBlendSC; 1415 } 1416 1417 /// Return the number of incoming values, taking into account that a single 1418 /// incoming value has no mask. 1419 unsigned getNumIncomingValues() const { return (getNumOperands() + 1) / 2; } 1420 1421 /// Return incoming value number \p Idx. 1422 VPValue *getIncomingValue(unsigned Idx) const { return getOperand(Idx * 2); } 1423 1424 /// Return mask number \p Idx. 1425 VPValue *getMask(unsigned Idx) const { return getOperand(Idx * 2 + 1); } 1426 1427 /// Generate the phi/select nodes. 1428 void execute(VPTransformState &State) override; 1429 1430 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1431 /// Print the recipe. 1432 void print(raw_ostream &O, const Twine &Indent, 1433 VPSlotTracker &SlotTracker) const override; 1434 #endif 1435 1436 /// Returns true if the recipe only uses the first lane of operand \p Op. 1437 bool onlyFirstLaneUsed(const VPValue *Op) const override { 1438 assert(is_contained(operands(), Op) && 1439 "Op must be an operand of the recipe"); 1440 // Recursing through Blend recipes only, must terminate at header phi's the 1441 // latest. 1442 return all_of(users(), 1443 [this](VPUser *U) { return U->onlyFirstLaneUsed(this); }); 1444 } 1445 }; 1446 1447 /// VPInterleaveRecipe is a recipe for transforming an interleave group of load 1448 /// or stores into one wide load/store and shuffles. The first operand of a 1449 /// VPInterleave recipe is the address, followed by the stored values, followed 1450 /// by an optional mask. 1451 class VPInterleaveRecipe : public VPRecipeBase { 1452 const InterleaveGroup<Instruction> *IG; 1453 1454 bool HasMask = false; 1455 1456 public: 1457 VPInterleaveRecipe(const InterleaveGroup<Instruction> *IG, VPValue *Addr, 1458 ArrayRef<VPValue *> StoredValues, VPValue *Mask) 1459 : VPRecipeBase(VPInterleaveSC, {Addr}), IG(IG) { 1460 for (unsigned i = 0; i < IG->getFactor(); ++i) 1461 if (Instruction *I = IG->getMember(i)) { 1462 if (I->getType()->isVoidTy()) 1463 continue; 1464 new VPValue(I, this); 1465 } 1466 1467 for (auto *SV : StoredValues) 1468 addOperand(SV); 1469 if (Mask) { 1470 HasMask = true; 1471 addOperand(Mask); 1472 } 1473 } 1474 ~VPInterleaveRecipe() override = default; 1475 1476 /// Method to support type inquiry through isa, cast, and dyn_cast. 1477 static inline bool classof(const VPDef *D) { 1478 return D->getVPDefID() == VPRecipeBase::VPInterleaveSC; 1479 } 1480 1481 /// Return the address accessed by this recipe. 1482 VPValue *getAddr() const { 1483 return getOperand(0); // Address is the 1st, mandatory operand. 1484 } 1485 1486 /// Return the mask used by this recipe. Note that a full mask is represented 1487 /// by a nullptr. 1488 VPValue *getMask() const { 1489 // Mask is optional and therefore the last, currently 2nd operand. 1490 return HasMask ? getOperand(getNumOperands() - 1) : nullptr; 1491 } 1492 1493 /// Return the VPValues stored by this interleave group. If it is a load 1494 /// interleave group, return an empty ArrayRef. 1495 ArrayRef<VPValue *> getStoredValues() const { 1496 // The first operand is the address, followed by the stored values, followed 1497 // by an optional mask. 1498 return ArrayRef<VPValue *>(op_begin(), getNumOperands()) 1499 .slice(1, getNumStoreOperands()); 1500 } 1501 1502 /// Generate the wide load or store, and shuffles. 1503 void execute(VPTransformState &State) override; 1504 1505 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1506 /// Print the recipe. 1507 void print(raw_ostream &O, const Twine &Indent, 1508 VPSlotTracker &SlotTracker) const override; 1509 #endif 1510 1511 const InterleaveGroup<Instruction> *getInterleaveGroup() { return IG; } 1512 1513 /// Returns the number of stored operands of this interleave group. Returns 0 1514 /// for load interleave groups. 1515 unsigned getNumStoreOperands() const { 1516 return getNumOperands() - (HasMask ? 2 : 1); 1517 } 1518 1519 /// The recipe only uses the first lane of the address. 1520 bool onlyFirstLaneUsed(const VPValue *Op) const override { 1521 assert(is_contained(operands(), Op) && 1522 "Op must be an operand of the recipe"); 1523 return Op == getAddr() && all_of(getStoredValues(), [Op](VPValue *StoredV) { 1524 return Op != StoredV; 1525 }); 1526 } 1527 }; 1528 1529 /// A recipe to represent inloop reduction operations, performing a reduction on 1530 /// a vector operand into a scalar value, and adding the result to a chain. 1531 /// The Operands are {ChainOp, VecOp, [Condition]}. 1532 class VPReductionRecipe : public VPRecipeBase, public VPValue { 1533 /// The recurrence decriptor for the reduction in question. 1534 const RecurrenceDescriptor *RdxDesc; 1535 /// Pointer to the TTI, needed to create the target reduction 1536 const TargetTransformInfo *TTI; 1537 1538 public: 1539 VPReductionRecipe(const RecurrenceDescriptor *R, Instruction *I, 1540 VPValue *ChainOp, VPValue *VecOp, VPValue *CondOp, 1541 const TargetTransformInfo *TTI) 1542 : VPRecipeBase(VPRecipeBase::VPReductionSC, {ChainOp, VecOp}), 1543 VPValue(VPValue::VPVReductionSC, I, this), RdxDesc(R), TTI(TTI) { 1544 if (CondOp) 1545 addOperand(CondOp); 1546 } 1547 1548 ~VPReductionRecipe() override = default; 1549 1550 /// Method to support type inquiry through isa, cast, and dyn_cast. 1551 static inline bool classof(const VPValue *V) { 1552 return V->getVPValueID() == VPValue::VPVReductionSC; 1553 } 1554 1555 /// Generate the reduction in the loop 1556 void execute(VPTransformState &State) override; 1557 1558 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1559 /// Print the recipe. 1560 void print(raw_ostream &O, const Twine &Indent, 1561 VPSlotTracker &SlotTracker) const override; 1562 #endif 1563 1564 /// The VPValue of the scalar Chain being accumulated. 1565 VPValue *getChainOp() const { return getOperand(0); } 1566 /// The VPValue of the vector value to be reduced. 1567 VPValue *getVecOp() const { return getOperand(1); } 1568 /// The VPValue of the condition for the block. 1569 VPValue *getCondOp() const { 1570 return getNumOperands() > 2 ? getOperand(2) : nullptr; 1571 } 1572 }; 1573 1574 /// VPReplicateRecipe replicates a given instruction producing multiple scalar 1575 /// copies of the original scalar type, one per lane, instead of producing a 1576 /// single copy of widened type for all lanes. If the instruction is known to be 1577 /// uniform only one copy, per lane zero, will be generated. 1578 class VPReplicateRecipe : public VPRecipeBase, public VPValue { 1579 /// Indicator if only a single replica per lane is needed. 1580 bool IsUniform; 1581 1582 /// Indicator if the replicas are also predicated. 1583 bool IsPredicated; 1584 1585 /// Indicator if the scalar values should also be packed into a vector. 1586 bool AlsoPack; 1587 1588 public: 1589 template <typename IterT> 1590 VPReplicateRecipe(Instruction *I, iterator_range<IterT> Operands, 1591 bool IsUniform, bool IsPredicated = false) 1592 : VPRecipeBase(VPReplicateSC, Operands), VPValue(VPVReplicateSC, I, this), 1593 IsUniform(IsUniform), IsPredicated(IsPredicated) { 1594 // Retain the previous behavior of predicateInstructions(), where an 1595 // insert-element of a predicated instruction got hoisted into the 1596 // predicated basic block iff it was its only user. This is achieved by 1597 // having predicated instructions also pack their values into a vector by 1598 // default unless they have a replicated user which uses their scalar value. 1599 AlsoPack = IsPredicated && !I->use_empty(); 1600 } 1601 1602 ~VPReplicateRecipe() override = default; 1603 1604 /// Method to support type inquiry through isa, cast, and dyn_cast. 1605 static inline bool classof(const VPDef *D) { 1606 return D->getVPDefID() == VPRecipeBase::VPReplicateSC; 1607 } 1608 1609 static inline bool classof(const VPValue *V) { 1610 return V->getVPValueID() == VPValue::VPVReplicateSC; 1611 } 1612 1613 /// Generate replicas of the desired Ingredient. Replicas will be generated 1614 /// for all parts and lanes unless a specific part and lane are specified in 1615 /// the \p State. 1616 void execute(VPTransformState &State) override; 1617 1618 void setAlsoPack(bool Pack) { AlsoPack = Pack; } 1619 1620 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1621 /// Print the recipe. 1622 void print(raw_ostream &O, const Twine &Indent, 1623 VPSlotTracker &SlotTracker) const override; 1624 #endif 1625 1626 bool isUniform() const { return IsUniform; } 1627 1628 bool isPacked() const { return AlsoPack; } 1629 1630 bool isPredicated() const { return IsPredicated; } 1631 1632 /// Returns true if the recipe only uses the first lane of operand \p Op. 1633 bool onlyFirstLaneUsed(const VPValue *Op) const override { 1634 assert(is_contained(operands(), Op) && 1635 "Op must be an operand of the recipe"); 1636 return isUniform(); 1637 } 1638 1639 /// Returns true if the recipe uses scalars of operand \p Op. 1640 bool usesScalars(const VPValue *Op) const override { 1641 assert(is_contained(operands(), Op) && 1642 "Op must be an operand of the recipe"); 1643 return true; 1644 } 1645 }; 1646 1647 /// A recipe for generating conditional branches on the bits of a mask. 1648 class VPBranchOnMaskRecipe : public VPRecipeBase { 1649 public: 1650 VPBranchOnMaskRecipe(VPValue *BlockInMask) 1651 : VPRecipeBase(VPBranchOnMaskSC, {}) { 1652 if (BlockInMask) // nullptr means all-one mask. 1653 addOperand(BlockInMask); 1654 } 1655 1656 /// Method to support type inquiry through isa, cast, and dyn_cast. 1657 static inline bool classof(const VPDef *D) { 1658 return D->getVPDefID() == VPRecipeBase::VPBranchOnMaskSC; 1659 } 1660 1661 /// Generate the extraction of the appropriate bit from the block mask and the 1662 /// conditional branch. 1663 void execute(VPTransformState &State) override; 1664 1665 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1666 /// Print the recipe. 1667 void print(raw_ostream &O, const Twine &Indent, 1668 VPSlotTracker &SlotTracker) const override { 1669 O << Indent << "BRANCH-ON-MASK "; 1670 if (VPValue *Mask = getMask()) 1671 Mask->printAsOperand(O, SlotTracker); 1672 else 1673 O << " All-One"; 1674 } 1675 #endif 1676 1677 /// Return the mask used by this recipe. Note that a full mask is represented 1678 /// by a nullptr. 1679 VPValue *getMask() const { 1680 assert(getNumOperands() <= 1 && "should have either 0 or 1 operands"); 1681 // Mask is optional. 1682 return getNumOperands() == 1 ? getOperand(0) : nullptr; 1683 } 1684 }; 1685 1686 /// VPPredInstPHIRecipe is a recipe for generating the phi nodes needed when 1687 /// control converges back from a Branch-on-Mask. The phi nodes are needed in 1688 /// order to merge values that are set under such a branch and feed their uses. 1689 /// The phi nodes can be scalar or vector depending on the users of the value. 1690 /// This recipe works in concert with VPBranchOnMaskRecipe. 1691 class VPPredInstPHIRecipe : public VPRecipeBase, public VPValue { 1692 public: 1693 /// Construct a VPPredInstPHIRecipe given \p PredInst whose value needs a phi 1694 /// nodes after merging back from a Branch-on-Mask. 1695 VPPredInstPHIRecipe(VPValue *PredV) 1696 : VPRecipeBase(VPPredInstPHISC, PredV), 1697 VPValue(VPValue::VPVPredInstPHI, nullptr, this) {} 1698 ~VPPredInstPHIRecipe() override = default; 1699 1700 /// Method to support type inquiry through isa, cast, and dyn_cast. 1701 static inline bool classof(const VPDef *D) { 1702 return D->getVPDefID() == VPRecipeBase::VPPredInstPHISC; 1703 } 1704 1705 /// Generates phi nodes for live-outs as needed to retain SSA form. 1706 void execute(VPTransformState &State) override; 1707 1708 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1709 /// Print the recipe. 1710 void print(raw_ostream &O, const Twine &Indent, 1711 VPSlotTracker &SlotTracker) const override; 1712 #endif 1713 1714 /// Returns true if the recipe uses scalars of operand \p Op. 1715 bool usesScalars(const VPValue *Op) const override { 1716 assert(is_contained(operands(), Op) && 1717 "Op must be an operand of the recipe"); 1718 return true; 1719 } 1720 }; 1721 1722 /// A Recipe for widening load/store operations. 1723 /// The recipe uses the following VPValues: 1724 /// - For load: Address, optional mask 1725 /// - For store: Address, stored value, optional mask 1726 /// TODO: We currently execute only per-part unless a specific instance is 1727 /// provided. 1728 class VPWidenMemoryInstructionRecipe : public VPRecipeBase { 1729 Instruction &Ingredient; 1730 1731 // Whether the loaded-from / stored-to addresses are consecutive. 1732 bool Consecutive; 1733 1734 // Whether the consecutive loaded/stored addresses are in reverse order. 1735 bool Reverse; 1736 1737 void setMask(VPValue *Mask) { 1738 if (!Mask) 1739 return; 1740 addOperand(Mask); 1741 } 1742 1743 bool isMasked() const { 1744 return isStore() ? getNumOperands() == 3 : getNumOperands() == 2; 1745 } 1746 1747 public: 1748 VPWidenMemoryInstructionRecipe(LoadInst &Load, VPValue *Addr, VPValue *Mask, 1749 bool Consecutive, bool Reverse) 1750 : VPRecipeBase(VPWidenMemoryInstructionSC, {Addr}), Ingredient(Load), 1751 Consecutive(Consecutive), Reverse(Reverse) { 1752 assert((Consecutive || !Reverse) && "Reverse implies consecutive"); 1753 new VPValue(VPValue::VPVMemoryInstructionSC, &Load, this); 1754 setMask(Mask); 1755 } 1756 1757 VPWidenMemoryInstructionRecipe(StoreInst &Store, VPValue *Addr, 1758 VPValue *StoredValue, VPValue *Mask, 1759 bool Consecutive, bool Reverse) 1760 : VPRecipeBase(VPWidenMemoryInstructionSC, {Addr, StoredValue}), 1761 Ingredient(Store), Consecutive(Consecutive), Reverse(Reverse) { 1762 assert((Consecutive || !Reverse) && "Reverse implies consecutive"); 1763 setMask(Mask); 1764 } 1765 1766 /// Method to support type inquiry through isa, cast, and dyn_cast. 1767 static inline bool classof(const VPDef *D) { 1768 return D->getVPDefID() == VPRecipeBase::VPWidenMemoryInstructionSC; 1769 } 1770 1771 /// Return the address accessed by this recipe. 1772 VPValue *getAddr() const { 1773 return getOperand(0); // Address is the 1st, mandatory operand. 1774 } 1775 1776 /// Return the mask used by this recipe. Note that a full mask is represented 1777 /// by a nullptr. 1778 VPValue *getMask() const { 1779 // Mask is optional and therefore the last operand. 1780 return isMasked() ? getOperand(getNumOperands() - 1) : nullptr; 1781 } 1782 1783 /// Returns true if this recipe is a store. 1784 bool isStore() const { return isa<StoreInst>(Ingredient); } 1785 1786 /// Return the address accessed by this recipe. 1787 VPValue *getStoredValue() const { 1788 assert(isStore() && "Stored value only available for store instructions"); 1789 return getOperand(1); // Stored value is the 2nd, mandatory operand. 1790 } 1791 1792 // Return whether the loaded-from / stored-to addresses are consecutive. 1793 bool isConsecutive() const { return Consecutive; } 1794 1795 // Return whether the consecutive loaded/stored addresses are in reverse 1796 // order. 1797 bool isReverse() const { return Reverse; } 1798 1799 /// Generate the wide load/store. 1800 void execute(VPTransformState &State) override; 1801 1802 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1803 /// Print the recipe. 1804 void print(raw_ostream &O, const Twine &Indent, 1805 VPSlotTracker &SlotTracker) const override; 1806 #endif 1807 1808 /// Returns true if the recipe only uses the first lane of operand \p Op. 1809 bool onlyFirstLaneUsed(const VPValue *Op) const override { 1810 assert(is_contained(operands(), Op) && 1811 "Op must be an operand of the recipe"); 1812 1813 // Widened, consecutive memory operations only demand the first lane of 1814 // their address, unless the same operand is also stored. That latter can 1815 // happen with opaque pointers. 1816 return Op == getAddr() && isConsecutive() && 1817 (!isStore() || Op != getStoredValue()); 1818 } 1819 1820 Instruction &getIngredient() const { return Ingredient; } 1821 }; 1822 1823 /// Recipe to expand a SCEV expression. 1824 class VPExpandSCEVRecipe : public VPRecipeBase, public VPValue { 1825 const SCEV *Expr; 1826 ScalarEvolution &SE; 1827 1828 public: 1829 VPExpandSCEVRecipe(const SCEV *Expr, ScalarEvolution &SE) 1830 : VPRecipeBase(VPExpandSCEVSC, {}), VPValue(nullptr, this), Expr(Expr), 1831 SE(SE) {} 1832 1833 ~VPExpandSCEVRecipe() override = default; 1834 1835 /// Method to support type inquiry through isa, cast, and dyn_cast. 1836 static inline bool classof(const VPDef *D) { 1837 return D->getVPDefID() == VPExpandSCEVSC; 1838 } 1839 1840 /// Generate a canonical vector induction variable of the vector loop, with 1841 void execute(VPTransformState &State) override; 1842 1843 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1844 /// Print the recipe. 1845 void print(raw_ostream &O, const Twine &Indent, 1846 VPSlotTracker &SlotTracker) const override; 1847 #endif 1848 1849 const SCEV *getSCEV() const { return Expr; } 1850 }; 1851 1852 /// Canonical scalar induction phi of the vector loop. Starting at the specified 1853 /// start value (either 0 or the resume value when vectorizing the epilogue 1854 /// loop). VPWidenCanonicalIVRecipe represents the vector version of the 1855 /// canonical induction variable. 1856 class VPCanonicalIVPHIRecipe : public VPHeaderPHIRecipe { 1857 DebugLoc DL; 1858 1859 public: 1860 VPCanonicalIVPHIRecipe(VPValue *StartV, DebugLoc DL) 1861 : VPHeaderPHIRecipe(VPValue::VPVCanonicalIVPHISC, VPCanonicalIVPHISC, 1862 nullptr, StartV), 1863 DL(DL) {} 1864 1865 ~VPCanonicalIVPHIRecipe() override = default; 1866 1867 /// Method to support type inquiry through isa, cast, and dyn_cast. 1868 static inline bool classof(const VPDef *D) { 1869 return D->getVPDefID() == VPCanonicalIVPHISC; 1870 } 1871 static inline bool classof(const VPHeaderPHIRecipe *D) { 1872 return D->getVPDefID() == VPCanonicalIVPHISC; 1873 } 1874 static inline bool classof(const VPValue *V) { 1875 return V->getVPValueID() == VPValue::VPVCanonicalIVPHISC; 1876 } 1877 1878 /// Generate the canonical scalar induction phi of the vector loop. 1879 void execute(VPTransformState &State) override; 1880 1881 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1882 /// Print the recipe. 1883 void print(raw_ostream &O, const Twine &Indent, 1884 VPSlotTracker &SlotTracker) const override; 1885 #endif 1886 1887 /// Returns the scalar type of the induction. 1888 const Type *getScalarType() const { 1889 return getOperand(0)->getLiveInIRValue()->getType(); 1890 } 1891 1892 /// Returns true if the recipe only uses the first lane of operand \p Op. 1893 bool onlyFirstLaneUsed(const VPValue *Op) const override { 1894 assert(is_contained(operands(), Op) && 1895 "Op must be an operand of the recipe"); 1896 return true; 1897 } 1898 }; 1899 1900 /// A Recipe for widening the canonical induction variable of the vector loop. 1901 class VPWidenCanonicalIVRecipe : public VPRecipeBase, public VPValue { 1902 public: 1903 VPWidenCanonicalIVRecipe(VPCanonicalIVPHIRecipe *CanonicalIV) 1904 : VPRecipeBase(VPWidenCanonicalIVSC, {CanonicalIV}), 1905 VPValue(VPValue::VPVWidenCanonicalIVSC, nullptr, this) {} 1906 1907 ~VPWidenCanonicalIVRecipe() override = default; 1908 1909 /// Method to support type inquiry through isa, cast, and dyn_cast. 1910 static inline bool classof(const VPDef *D) { 1911 return D->getVPDefID() == VPRecipeBase::VPWidenCanonicalIVSC; 1912 } 1913 1914 /// Extra classof implementations to allow directly casting from VPUser -> 1915 /// VPWidenCanonicalIVRecipe. 1916 static inline bool classof(const VPUser *U) { 1917 auto *R = dyn_cast<VPRecipeBase>(U); 1918 return R && R->getVPDefID() == VPRecipeBase::VPWidenCanonicalIVSC; 1919 } 1920 static inline bool classof(const VPRecipeBase *R) { 1921 return R->getVPDefID() == VPRecipeBase::VPWidenCanonicalIVSC; 1922 } 1923 1924 /// Generate a canonical vector induction variable of the vector loop, with 1925 /// start = {<Part*VF, Part*VF+1, ..., Part*VF+VF-1> for 0 <= Part < UF}, and 1926 /// step = <VF*UF, VF*UF, ..., VF*UF>. 1927 void execute(VPTransformState &State) override; 1928 1929 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1930 /// Print the recipe. 1931 void print(raw_ostream &O, const Twine &Indent, 1932 VPSlotTracker &SlotTracker) const override; 1933 #endif 1934 1935 /// Returns the scalar type of the induction. 1936 const Type *getScalarType() const { 1937 return cast<VPCanonicalIVPHIRecipe>(getOperand(0)->getDef()) 1938 ->getScalarType(); 1939 } 1940 }; 1941 1942 /// A recipe for handling phi nodes of integer and floating-point inductions, 1943 /// producing their scalar values. 1944 class VPScalarIVStepsRecipe : public VPRecipeBase, public VPValue { 1945 /// Scalar type to use for the generated values. 1946 Type *Ty; 1947 /// If not nullptr, truncate the generated values to TruncToTy. 1948 Type *TruncToTy; 1949 const InductionDescriptor &IndDesc; 1950 1951 public: 1952 VPScalarIVStepsRecipe(Type *Ty, const InductionDescriptor &IndDesc, 1953 VPValue *CanonicalIV, VPValue *Start, VPValue *Step, 1954 Type *TruncToTy) 1955 : VPRecipeBase(VPScalarIVStepsSC, {CanonicalIV, Start, Step}), 1956 VPValue(nullptr, this), Ty(Ty), TruncToTy(TruncToTy), IndDesc(IndDesc) { 1957 } 1958 1959 ~VPScalarIVStepsRecipe() override = default; 1960 1961 /// Method to support type inquiry through isa, cast, and dyn_cast. 1962 static inline bool classof(const VPDef *D) { 1963 return D->getVPDefID() == VPRecipeBase::VPScalarIVStepsSC; 1964 } 1965 /// Extra classof implementations to allow directly casting from VPUser -> 1966 /// VPScalarIVStepsRecipe. 1967 static inline bool classof(const VPUser *U) { 1968 auto *R = dyn_cast<VPRecipeBase>(U); 1969 return R && R->getVPDefID() == VPRecipeBase::VPScalarIVStepsSC; 1970 } 1971 static inline bool classof(const VPRecipeBase *R) { 1972 return R->getVPDefID() == VPRecipeBase::VPScalarIVStepsSC; 1973 } 1974 1975 /// Generate the scalarized versions of the phi node as needed by their users. 1976 void execute(VPTransformState &State) override; 1977 1978 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1979 /// Print the recipe. 1980 void print(raw_ostream &O, const Twine &Indent, 1981 VPSlotTracker &SlotTracker) const override; 1982 #endif 1983 1984 /// Returns true if the induction is canonical, i.e. starting at 0 and 1985 /// incremented by UF * VF (= the original IV is incremented by 1). 1986 bool isCanonical() const; 1987 1988 VPCanonicalIVPHIRecipe *getCanonicalIV() const; 1989 VPValue *getStartValue() const { return getOperand(1); } 1990 VPValue *getStepValue() const { return getOperand(2); } 1991 1992 /// Returns true if the recipe only uses the first lane of operand \p Op. 1993 bool onlyFirstLaneUsed(const VPValue *Op) const override { 1994 assert(is_contained(operands(), Op) && 1995 "Op must be an operand of the recipe"); 1996 return true; 1997 } 1998 }; 1999 2000 /// VPBasicBlock serves as the leaf of the Hierarchical Control-Flow Graph. It 2001 /// holds a sequence of zero or more VPRecipe's each representing a sequence of 2002 /// output IR instructions. All PHI-like recipes must come before any non-PHI recipes. 2003 class VPBasicBlock : public VPBlockBase { 2004 public: 2005 using RecipeListTy = iplist<VPRecipeBase>; 2006 2007 private: 2008 /// The VPRecipes held in the order of output instructions to generate. 2009 RecipeListTy Recipes; 2010 2011 public: 2012 VPBasicBlock(const Twine &Name = "", VPRecipeBase *Recipe = nullptr) 2013 : VPBlockBase(VPBasicBlockSC, Name.str()) { 2014 if (Recipe) 2015 appendRecipe(Recipe); 2016 } 2017 2018 ~VPBasicBlock() override { 2019 while (!Recipes.empty()) 2020 Recipes.pop_back(); 2021 } 2022 2023 /// Instruction iterators... 2024 using iterator = RecipeListTy::iterator; 2025 using const_iterator = RecipeListTy::const_iterator; 2026 using reverse_iterator = RecipeListTy::reverse_iterator; 2027 using const_reverse_iterator = RecipeListTy::const_reverse_iterator; 2028 2029 //===--------------------------------------------------------------------===// 2030 /// Recipe iterator methods 2031 /// 2032 inline iterator begin() { return Recipes.begin(); } 2033 inline const_iterator begin() const { return Recipes.begin(); } 2034 inline iterator end() { return Recipes.end(); } 2035 inline const_iterator end() const { return Recipes.end(); } 2036 2037 inline reverse_iterator rbegin() { return Recipes.rbegin(); } 2038 inline const_reverse_iterator rbegin() const { return Recipes.rbegin(); } 2039 inline reverse_iterator rend() { return Recipes.rend(); } 2040 inline const_reverse_iterator rend() const { return Recipes.rend(); } 2041 2042 inline size_t size() const { return Recipes.size(); } 2043 inline bool empty() const { return Recipes.empty(); } 2044 inline const VPRecipeBase &front() const { return Recipes.front(); } 2045 inline VPRecipeBase &front() { return Recipes.front(); } 2046 inline const VPRecipeBase &back() const { return Recipes.back(); } 2047 inline VPRecipeBase &back() { return Recipes.back(); } 2048 2049 /// Returns a reference to the list of recipes. 2050 RecipeListTy &getRecipeList() { return Recipes; } 2051 2052 /// Returns a pointer to a member of the recipe list. 2053 static RecipeListTy VPBasicBlock::*getSublistAccess(VPRecipeBase *) { 2054 return &VPBasicBlock::Recipes; 2055 } 2056 2057 /// Method to support type inquiry through isa, cast, and dyn_cast. 2058 static inline bool classof(const VPBlockBase *V) { 2059 return V->getVPBlockID() == VPBlockBase::VPBasicBlockSC; 2060 } 2061 2062 void insert(VPRecipeBase *Recipe, iterator InsertPt) { 2063 assert(Recipe && "No recipe to append."); 2064 assert(!Recipe->Parent && "Recipe already in VPlan"); 2065 Recipe->Parent = this; 2066 Recipes.insert(InsertPt, Recipe); 2067 } 2068 2069 /// Augment the existing recipes of a VPBasicBlock with an additional 2070 /// \p Recipe as the last recipe. 2071 void appendRecipe(VPRecipeBase *Recipe) { insert(Recipe, end()); } 2072 2073 /// The method which generates the output IR instructions that correspond to 2074 /// this VPBasicBlock, thereby "executing" the VPlan. 2075 void execute(struct VPTransformState *State) override; 2076 2077 /// Return the position of the first non-phi node recipe in the block. 2078 iterator getFirstNonPhi(); 2079 2080 /// Returns an iterator range over the PHI-like recipes in the block. 2081 iterator_range<iterator> phis() { 2082 return make_range(begin(), getFirstNonPhi()); 2083 } 2084 2085 void dropAllReferences(VPValue *NewValue) override; 2086 2087 /// Split current block at \p SplitAt by inserting a new block between the 2088 /// current block and its successors and moving all recipes starting at 2089 /// SplitAt to the new block. Returns the new block. 2090 VPBasicBlock *splitAt(iterator SplitAt); 2091 2092 VPRegionBlock *getEnclosingLoopRegion(); 2093 2094 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 2095 /// Print this VPBsicBlock to \p O, prefixing all lines with \p Indent. \p 2096 /// SlotTracker is used to print unnamed VPValue's using consequtive numbers. 2097 /// 2098 /// Note that the numbering is applied to the whole VPlan, so printing 2099 /// individual blocks is consistent with the whole VPlan printing. 2100 void print(raw_ostream &O, const Twine &Indent, 2101 VPSlotTracker &SlotTracker) const override; 2102 using VPBlockBase::print; // Get the print(raw_stream &O) version. 2103 #endif 2104 2105 private: 2106 /// Create an IR BasicBlock to hold the output instructions generated by this 2107 /// VPBasicBlock, and return it. Update the CFGState accordingly. 2108 BasicBlock *createEmptyBasicBlock(VPTransformState::CFGState &CFG); 2109 }; 2110 2111 /// VPRegionBlock represents a collection of VPBasicBlocks and VPRegionBlocks 2112 /// which form a Single-Entry-Single-Exiting subgraph of the output IR CFG. 2113 /// A VPRegionBlock may indicate that its contents are to be replicated several 2114 /// times. This is designed to support predicated scalarization, in which a 2115 /// scalar if-then code structure needs to be generated VF * UF times. Having 2116 /// this replication indicator helps to keep a single model for multiple 2117 /// candidate VF's. The actual replication takes place only once the desired VF 2118 /// and UF have been determined. 2119 class VPRegionBlock : public VPBlockBase { 2120 /// Hold the Single Entry of the SESE region modelled by the VPRegionBlock. 2121 VPBlockBase *Entry; 2122 2123 /// Hold the Single Exiting block of the SESE region modelled by the 2124 /// VPRegionBlock. 2125 VPBlockBase *Exiting; 2126 2127 /// An indicator whether this region is to generate multiple replicated 2128 /// instances of output IR corresponding to its VPBlockBases. 2129 bool IsReplicator; 2130 2131 public: 2132 VPRegionBlock(VPBlockBase *Entry, VPBlockBase *Exiting, 2133 const std::string &Name = "", bool IsReplicator = false) 2134 : VPBlockBase(VPRegionBlockSC, Name), Entry(Entry), Exiting(Exiting), 2135 IsReplicator(IsReplicator) { 2136 assert(Entry->getPredecessors().empty() && "Entry block has predecessors."); 2137 assert(Exiting->getSuccessors().empty() && "Exit block has successors."); 2138 Entry->setParent(this); 2139 Exiting->setParent(this); 2140 } 2141 VPRegionBlock(const std::string &Name = "", bool IsReplicator = false) 2142 : VPBlockBase(VPRegionBlockSC, Name), Entry(nullptr), Exiting(nullptr), 2143 IsReplicator(IsReplicator) {} 2144 2145 ~VPRegionBlock() override { 2146 if (Entry) { 2147 VPValue DummyValue; 2148 Entry->dropAllReferences(&DummyValue); 2149 deleteCFG(Entry); 2150 } 2151 } 2152 2153 /// Method to support type inquiry through isa, cast, and dyn_cast. 2154 static inline bool classof(const VPBlockBase *V) { 2155 return V->getVPBlockID() == VPBlockBase::VPRegionBlockSC; 2156 } 2157 2158 const VPBlockBase *getEntry() const { return Entry; } 2159 VPBlockBase *getEntry() { return Entry; } 2160 2161 /// Set \p EntryBlock as the entry VPBlockBase of this VPRegionBlock. \p 2162 /// EntryBlock must have no predecessors. 2163 void setEntry(VPBlockBase *EntryBlock) { 2164 assert(EntryBlock->getPredecessors().empty() && 2165 "Entry block cannot have predecessors."); 2166 Entry = EntryBlock; 2167 EntryBlock->setParent(this); 2168 } 2169 2170 // FIXME: DominatorTreeBase is doing 'A->getParent()->front()'. 'front' is a 2171 // specific interface of llvm::Function, instead of using 2172 // GraphTraints::getEntryNode. We should add a new template parameter to 2173 // DominatorTreeBase representing the Graph type. 2174 VPBlockBase &front() const { return *Entry; } 2175 2176 const VPBlockBase *getExiting() const { return Exiting; } 2177 VPBlockBase *getExiting() { return Exiting; } 2178 2179 /// Set \p ExitingBlock as the exiting VPBlockBase of this VPRegionBlock. \p 2180 /// ExitingBlock must have no successors. 2181 void setExiting(VPBlockBase *ExitingBlock) { 2182 assert(ExitingBlock->getSuccessors().empty() && 2183 "Exit block cannot have successors."); 2184 Exiting = ExitingBlock; 2185 ExitingBlock->setParent(this); 2186 } 2187 2188 /// Returns the pre-header VPBasicBlock of the loop region. 2189 VPBasicBlock *getPreheaderVPBB() { 2190 assert(!isReplicator() && "should only get pre-header of loop regions"); 2191 return getSinglePredecessor()->getExitingBasicBlock(); 2192 } 2193 2194 /// An indicator whether this region is to generate multiple replicated 2195 /// instances of output IR corresponding to its VPBlockBases. 2196 bool isReplicator() const { return IsReplicator; } 2197 2198 /// The method which generates the output IR instructions that correspond to 2199 /// this VPRegionBlock, thereby "executing" the VPlan. 2200 void execute(struct VPTransformState *State) override; 2201 2202 void dropAllReferences(VPValue *NewValue) override; 2203 2204 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 2205 /// Print this VPRegionBlock to \p O (recursively), prefixing all lines with 2206 /// \p Indent. \p SlotTracker is used to print unnamed VPValue's using 2207 /// consequtive numbers. 2208 /// 2209 /// Note that the numbering is applied to the whole VPlan, so printing 2210 /// individual regions is consistent with the whole VPlan printing. 2211 void print(raw_ostream &O, const Twine &Indent, 2212 VPSlotTracker &SlotTracker) const override; 2213 using VPBlockBase::print; // Get the print(raw_stream &O) version. 2214 #endif 2215 }; 2216 2217 //===----------------------------------------------------------------------===// 2218 // GraphTraits specializations for VPlan Hierarchical Control-Flow Graphs // 2219 //===----------------------------------------------------------------------===// 2220 2221 // The following set of template specializations implement GraphTraits to treat 2222 // any VPBlockBase as a node in a graph of VPBlockBases. It's important to note 2223 // that VPBlockBase traits don't recurse into VPRegioBlocks, i.e., if the 2224 // VPBlockBase is a VPRegionBlock, this specialization provides access to its 2225 // successors/predecessors but not to the blocks inside the region. 2226 2227 template <> struct GraphTraits<VPBlockBase *> { 2228 using NodeRef = VPBlockBase *; 2229 using ChildIteratorType = SmallVectorImpl<VPBlockBase *>::iterator; 2230 2231 static NodeRef getEntryNode(NodeRef N) { return N; } 2232 2233 static inline ChildIteratorType child_begin(NodeRef N) { 2234 return N->getSuccessors().begin(); 2235 } 2236 2237 static inline ChildIteratorType child_end(NodeRef N) { 2238 return N->getSuccessors().end(); 2239 } 2240 }; 2241 2242 template <> struct GraphTraits<const VPBlockBase *> { 2243 using NodeRef = const VPBlockBase *; 2244 using ChildIteratorType = SmallVectorImpl<VPBlockBase *>::const_iterator; 2245 2246 static NodeRef getEntryNode(NodeRef N) { return N; } 2247 2248 static inline ChildIteratorType child_begin(NodeRef N) { 2249 return N->getSuccessors().begin(); 2250 } 2251 2252 static inline ChildIteratorType child_end(NodeRef N) { 2253 return N->getSuccessors().end(); 2254 } 2255 }; 2256 2257 // Inverse order specialization for VPBasicBlocks. Predecessors are used instead 2258 // of successors for the inverse traversal. 2259 template <> struct GraphTraits<Inverse<VPBlockBase *>> { 2260 using NodeRef = VPBlockBase *; 2261 using ChildIteratorType = SmallVectorImpl<VPBlockBase *>::iterator; 2262 2263 static NodeRef getEntryNode(Inverse<NodeRef> B) { return B.Graph; } 2264 2265 static inline ChildIteratorType child_begin(NodeRef N) { 2266 return N->getPredecessors().begin(); 2267 } 2268 2269 static inline ChildIteratorType child_end(NodeRef N) { 2270 return N->getPredecessors().end(); 2271 } 2272 }; 2273 2274 // The following set of template specializations implement GraphTraits to 2275 // treat VPRegionBlock as a graph and recurse inside its nodes. It's important 2276 // to note that the blocks inside the VPRegionBlock are treated as VPBlockBases 2277 // (i.e., no dyn_cast is performed, VPBlockBases specialization is used), so 2278 // there won't be automatic recursion into other VPBlockBases that turn to be 2279 // VPRegionBlocks. 2280 2281 template <> 2282 struct GraphTraits<VPRegionBlock *> : public GraphTraits<VPBlockBase *> { 2283 using GraphRef = VPRegionBlock *; 2284 using nodes_iterator = df_iterator<NodeRef>; 2285 2286 static NodeRef getEntryNode(GraphRef N) { return N->getEntry(); } 2287 2288 static nodes_iterator nodes_begin(GraphRef N) { 2289 return nodes_iterator::begin(N->getEntry()); 2290 } 2291 2292 static nodes_iterator nodes_end(GraphRef N) { 2293 // df_iterator::end() returns an empty iterator so the node used doesn't 2294 // matter. 2295 return nodes_iterator::end(N); 2296 } 2297 }; 2298 2299 template <> 2300 struct GraphTraits<const VPRegionBlock *> 2301 : public GraphTraits<const VPBlockBase *> { 2302 using GraphRef = const VPRegionBlock *; 2303 using nodes_iterator = df_iterator<NodeRef>; 2304 2305 static NodeRef getEntryNode(GraphRef N) { return N->getEntry(); } 2306 2307 static nodes_iterator nodes_begin(GraphRef N) { 2308 return nodes_iterator::begin(N->getEntry()); 2309 } 2310 2311 static nodes_iterator nodes_end(GraphRef N) { 2312 // df_iterator::end() returns an empty iterator so the node used doesn't 2313 // matter. 2314 return nodes_iterator::end(N); 2315 } 2316 }; 2317 2318 template <> 2319 struct GraphTraits<Inverse<VPRegionBlock *>> 2320 : public GraphTraits<Inverse<VPBlockBase *>> { 2321 using GraphRef = VPRegionBlock *; 2322 using nodes_iterator = df_iterator<NodeRef>; 2323 2324 static NodeRef getEntryNode(Inverse<GraphRef> N) { 2325 return N.Graph->getExiting(); 2326 } 2327 2328 static nodes_iterator nodes_begin(GraphRef N) { 2329 return nodes_iterator::begin(N->getExiting()); 2330 } 2331 2332 static nodes_iterator nodes_end(GraphRef N) { 2333 // df_iterator::end() returns an empty iterator so the node used doesn't 2334 // matter. 2335 return nodes_iterator::end(N); 2336 } 2337 }; 2338 2339 /// Iterator to traverse all successors of a VPBlockBase node. This includes the 2340 /// entry node of VPRegionBlocks. Exit blocks of a region implicitly have their 2341 /// parent region's successors. This ensures all blocks in a region are visited 2342 /// before any blocks in a successor region when doing a reverse post-order 2343 // traversal of the graph. 2344 template <typename BlockPtrTy> 2345 class VPAllSuccessorsIterator 2346 : public iterator_facade_base<VPAllSuccessorsIterator<BlockPtrTy>, 2347 std::forward_iterator_tag, VPBlockBase> { 2348 BlockPtrTy Block; 2349 /// Index of the current successor. For VPBasicBlock nodes, this simply is the 2350 /// index for the successor array. For VPRegionBlock, SuccessorIdx == 0 is 2351 /// used for the region's entry block, and SuccessorIdx - 1 are the indices 2352 /// for the successor array. 2353 size_t SuccessorIdx; 2354 2355 static BlockPtrTy getBlockWithSuccs(BlockPtrTy Current) { 2356 while (Current && Current->getNumSuccessors() == 0) 2357 Current = Current->getParent(); 2358 return Current; 2359 } 2360 2361 /// Templated helper to dereference successor \p SuccIdx of \p Block. Used by 2362 /// both the const and non-const operator* implementations. 2363 template <typename T1> static T1 deref(T1 Block, unsigned SuccIdx) { 2364 if (auto *R = dyn_cast<VPRegionBlock>(Block)) { 2365 if (SuccIdx == 0) 2366 return R->getEntry(); 2367 SuccIdx--; 2368 } 2369 2370 // For exit blocks, use the next parent region with successors. 2371 return getBlockWithSuccs(Block)->getSuccessors()[SuccIdx]; 2372 } 2373 2374 public: 2375 VPAllSuccessorsIterator(BlockPtrTy Block, size_t Idx = 0) 2376 : Block(Block), SuccessorIdx(Idx) {} 2377 VPAllSuccessorsIterator(const VPAllSuccessorsIterator &Other) 2378 : Block(Other.Block), SuccessorIdx(Other.SuccessorIdx) {} 2379 2380 VPAllSuccessorsIterator &operator=(const VPAllSuccessorsIterator &R) { 2381 Block = R.Block; 2382 SuccessorIdx = R.SuccessorIdx; 2383 return *this; 2384 } 2385 2386 static VPAllSuccessorsIterator end(BlockPtrTy Block) { 2387 BlockPtrTy ParentWithSuccs = getBlockWithSuccs(Block); 2388 unsigned NumSuccessors = ParentWithSuccs 2389 ? ParentWithSuccs->getNumSuccessors() 2390 : Block->getNumSuccessors(); 2391 2392 if (auto *R = dyn_cast<VPRegionBlock>(Block)) 2393 return {R, NumSuccessors + 1}; 2394 return {Block, NumSuccessors}; 2395 } 2396 2397 bool operator==(const VPAllSuccessorsIterator &R) const { 2398 return Block == R.Block && SuccessorIdx == R.SuccessorIdx; 2399 } 2400 2401 const VPBlockBase *operator*() const { return deref(Block, SuccessorIdx); } 2402 2403 BlockPtrTy operator*() { return deref(Block, SuccessorIdx); } 2404 2405 VPAllSuccessorsIterator &operator++() { 2406 SuccessorIdx++; 2407 return *this; 2408 } 2409 2410 VPAllSuccessorsIterator operator++(int X) { 2411 VPAllSuccessorsIterator Orig = *this; 2412 SuccessorIdx++; 2413 return Orig; 2414 } 2415 }; 2416 2417 /// Helper for GraphTraits specialization that traverses through VPRegionBlocks. 2418 template <typename BlockTy> class VPBlockRecursiveTraversalWrapper { 2419 BlockTy Entry; 2420 2421 public: 2422 VPBlockRecursiveTraversalWrapper(BlockTy Entry) : Entry(Entry) {} 2423 BlockTy getEntry() { return Entry; } 2424 }; 2425 2426 /// GraphTraits specialization to recursively traverse VPBlockBase nodes, 2427 /// including traversing through VPRegionBlocks. Exit blocks of a region 2428 /// implicitly have their parent region's successors. This ensures all blocks in 2429 /// a region are visited before any blocks in a successor region when doing a 2430 /// reverse post-order traversal of the graph. 2431 template <> 2432 struct GraphTraits<VPBlockRecursiveTraversalWrapper<VPBlockBase *>> { 2433 using NodeRef = VPBlockBase *; 2434 using ChildIteratorType = VPAllSuccessorsIterator<VPBlockBase *>; 2435 2436 static NodeRef 2437 getEntryNode(VPBlockRecursiveTraversalWrapper<VPBlockBase *> N) { 2438 return N.getEntry(); 2439 } 2440 2441 static inline ChildIteratorType child_begin(NodeRef N) { 2442 return ChildIteratorType(N); 2443 } 2444 2445 static inline ChildIteratorType child_end(NodeRef N) { 2446 return ChildIteratorType::end(N); 2447 } 2448 }; 2449 2450 template <> 2451 struct GraphTraits<VPBlockRecursiveTraversalWrapper<const VPBlockBase *>> { 2452 using NodeRef = const VPBlockBase *; 2453 using ChildIteratorType = VPAllSuccessorsIterator<const VPBlockBase *>; 2454 2455 static NodeRef 2456 getEntryNode(VPBlockRecursiveTraversalWrapper<const VPBlockBase *> N) { 2457 return N.getEntry(); 2458 } 2459 2460 static inline ChildIteratorType child_begin(NodeRef N) { 2461 return ChildIteratorType(N); 2462 } 2463 2464 static inline ChildIteratorType child_end(NodeRef N) { 2465 return ChildIteratorType::end(N); 2466 } 2467 }; 2468 2469 /// VPlan models a candidate for vectorization, encoding various decisions take 2470 /// to produce efficient output IR, including which branches, basic-blocks and 2471 /// output IR instructions to generate, and their cost. VPlan holds a 2472 /// Hierarchical-CFG of VPBasicBlocks and VPRegionBlocks rooted at an Entry 2473 /// VPBlock. 2474 class VPlan { 2475 friend class VPlanPrinter; 2476 friend class VPSlotTracker; 2477 2478 /// Hold the single entry to the Hierarchical CFG of the VPlan. 2479 VPBlockBase *Entry; 2480 2481 /// Holds the VFs applicable to this VPlan. 2482 SmallSetVector<ElementCount, 2> VFs; 2483 2484 /// Holds the name of the VPlan, for printing. 2485 std::string Name; 2486 2487 /// Holds all the external definitions created for this VPlan. External 2488 /// definitions must be immutable and hold a pointer to their underlying IR. 2489 DenseMap<Value *, VPValue *> VPExternalDefs; 2490 2491 /// Represents the trip count of the original loop, for folding 2492 /// the tail. 2493 VPValue *TripCount = nullptr; 2494 2495 /// Represents the backedge taken count of the original loop, for folding 2496 /// the tail. It equals TripCount - 1. 2497 VPValue *BackedgeTakenCount = nullptr; 2498 2499 /// Represents the vector trip count. 2500 VPValue VectorTripCount; 2501 2502 /// Holds a mapping between Values and their corresponding VPValue inside 2503 /// VPlan. 2504 Value2VPValueTy Value2VPValue; 2505 2506 /// Contains all VPValues that been allocated by addVPValue directly and need 2507 /// to be free when the plan's destructor is called. 2508 SmallVector<VPValue *, 16> VPValuesToFree; 2509 2510 /// Indicates whether it is safe use the Value2VPValue mapping or if the 2511 /// mapping cannot be used any longer, because it is stale. 2512 bool Value2VPValueEnabled = true; 2513 2514 /// Values used outside the plan. 2515 MapVector<PHINode *, VPLiveOut *> LiveOuts; 2516 2517 public: 2518 VPlan(VPBlockBase *Entry = nullptr) : Entry(Entry) { 2519 if (Entry) 2520 Entry->setPlan(this); 2521 } 2522 2523 ~VPlan() { 2524 clearLiveOuts(); 2525 2526 if (Entry) { 2527 VPValue DummyValue; 2528 for (VPBlockBase *Block : depth_first(Entry)) 2529 Block->dropAllReferences(&DummyValue); 2530 2531 VPBlockBase::deleteCFG(Entry); 2532 } 2533 for (VPValue *VPV : VPValuesToFree) 2534 delete VPV; 2535 if (TripCount) 2536 delete TripCount; 2537 if (BackedgeTakenCount) 2538 delete BackedgeTakenCount; 2539 for (auto &P : VPExternalDefs) 2540 delete P.second; 2541 } 2542 2543 /// Prepare the plan for execution, setting up the required live-in values. 2544 void prepareToExecute(Value *TripCount, Value *VectorTripCount, 2545 Value *CanonicalIVStartValue, VPTransformState &State); 2546 2547 /// Generate the IR code for this VPlan. 2548 void execute(struct VPTransformState *State); 2549 2550 VPBlockBase *getEntry() { return Entry; } 2551 const VPBlockBase *getEntry() const { return Entry; } 2552 2553 VPBlockBase *setEntry(VPBlockBase *Block) { 2554 Entry = Block; 2555 Block->setPlan(this); 2556 return Entry; 2557 } 2558 2559 /// The trip count of the original loop. 2560 VPValue *getOrCreateTripCount() { 2561 if (!TripCount) 2562 TripCount = new VPValue(); 2563 return TripCount; 2564 } 2565 2566 /// The backedge taken count of the original loop. 2567 VPValue *getOrCreateBackedgeTakenCount() { 2568 if (!BackedgeTakenCount) 2569 BackedgeTakenCount = new VPValue(); 2570 return BackedgeTakenCount; 2571 } 2572 2573 /// The vector trip count. 2574 VPValue &getVectorTripCount() { return VectorTripCount; } 2575 2576 /// Mark the plan to indicate that using Value2VPValue is not safe any 2577 /// longer, because it may be stale. 2578 void disableValue2VPValue() { Value2VPValueEnabled = false; } 2579 2580 void addVF(ElementCount VF) { VFs.insert(VF); } 2581 2582 bool hasVF(ElementCount VF) { return VFs.count(VF); } 2583 2584 const std::string &getName() const { return Name; } 2585 2586 void setName(const Twine &newName) { Name = newName.str(); } 2587 2588 /// Get the existing or add a new external definition for \p V. 2589 VPValue *getOrAddExternalDef(Value *V) { 2590 auto I = VPExternalDefs.insert({V, nullptr}); 2591 if (I.second) 2592 I.first->second = new VPValue(V); 2593 return I.first->second; 2594 } 2595 2596 void addVPValue(Value *V) { 2597 assert(Value2VPValueEnabled && 2598 "IR value to VPValue mapping may be out of date!"); 2599 assert(V && "Trying to add a null Value to VPlan"); 2600 assert(!Value2VPValue.count(V) && "Value already exists in VPlan"); 2601 VPValue *VPV = new VPValue(V); 2602 Value2VPValue[V] = VPV; 2603 VPValuesToFree.push_back(VPV); 2604 } 2605 2606 void addVPValue(Value *V, VPValue *VPV) { 2607 assert(Value2VPValueEnabled && "Value2VPValue mapping may be out of date!"); 2608 assert(V && "Trying to add a null Value to VPlan"); 2609 assert(!Value2VPValue.count(V) && "Value already exists in VPlan"); 2610 Value2VPValue[V] = VPV; 2611 } 2612 2613 /// Returns the VPValue for \p V. \p OverrideAllowed can be used to disable 2614 /// checking whether it is safe to query VPValues using IR Values. 2615 VPValue *getVPValue(Value *V, bool OverrideAllowed = false) { 2616 assert((OverrideAllowed || isa<Constant>(V) || Value2VPValueEnabled) && 2617 "Value2VPValue mapping may be out of date!"); 2618 assert(V && "Trying to get the VPValue of a null Value"); 2619 assert(Value2VPValue.count(V) && "Value does not exist in VPlan"); 2620 return Value2VPValue[V]; 2621 } 2622 2623 /// Gets the VPValue or adds a new one (if none exists yet) for \p V. \p 2624 /// OverrideAllowed can be used to disable checking whether it is safe to 2625 /// query VPValues using IR Values. 2626 VPValue *getOrAddVPValue(Value *V, bool OverrideAllowed = false) { 2627 assert((OverrideAllowed || isa<Constant>(V) || Value2VPValueEnabled) && 2628 "Value2VPValue mapping may be out of date!"); 2629 assert(V && "Trying to get or add the VPValue of a null Value"); 2630 if (!Value2VPValue.count(V)) 2631 addVPValue(V); 2632 return getVPValue(V); 2633 } 2634 2635 void removeVPValueFor(Value *V) { 2636 assert(Value2VPValueEnabled && 2637 "IR value to VPValue mapping may be out of date!"); 2638 Value2VPValue.erase(V); 2639 } 2640 2641 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 2642 /// Print this VPlan to \p O. 2643 void print(raw_ostream &O) const; 2644 2645 /// Print this VPlan in DOT format to \p O. 2646 void printDOT(raw_ostream &O) const; 2647 2648 /// Dump the plan to stderr (for debugging). 2649 LLVM_DUMP_METHOD void dump() const; 2650 #endif 2651 2652 /// Returns a range mapping the values the range \p Operands to their 2653 /// corresponding VPValues. 2654 iterator_range<mapped_iterator<Use *, std::function<VPValue *(Value *)>>> 2655 mapToVPValues(User::op_range Operands) { 2656 std::function<VPValue *(Value *)> Fn = [this](Value *Op) { 2657 return getOrAddVPValue(Op); 2658 }; 2659 return map_range(Operands, Fn); 2660 } 2661 2662 /// Returns true if \p VPV is uniform after vectorization. 2663 bool isUniformAfterVectorization(VPValue *VPV) const { 2664 auto RepR = dyn_cast_or_null<VPReplicateRecipe>(VPV->getDef()); 2665 return !VPV->getDef() || (RepR && RepR->isUniform()); 2666 } 2667 2668 /// Returns the VPRegionBlock of the vector loop. 2669 VPRegionBlock *getVectorLoopRegion() { 2670 if (auto *R = dyn_cast<VPRegionBlock>(getEntry())) 2671 return R; 2672 return cast<VPRegionBlock>(getEntry()->getSingleSuccessor()); 2673 } 2674 const VPRegionBlock *getVectorLoopRegion() const { 2675 if (auto *R = dyn_cast<VPRegionBlock>(getEntry())) 2676 return R; 2677 return cast<VPRegionBlock>(getEntry()->getSingleSuccessor()); 2678 } 2679 2680 /// Returns the canonical induction recipe of the vector loop. 2681 VPCanonicalIVPHIRecipe *getCanonicalIV() { 2682 VPBasicBlock *EntryVPBB = getVectorLoopRegion()->getEntryBasicBlock(); 2683 if (EntryVPBB->empty()) { 2684 // VPlan native path. 2685 EntryVPBB = cast<VPBasicBlock>(EntryVPBB->getSingleSuccessor()); 2686 } 2687 return cast<VPCanonicalIVPHIRecipe>(&*EntryVPBB->begin()); 2688 } 2689 2690 void addLiveOut(PHINode *PN, VPValue *V); 2691 2692 void clearLiveOuts() { 2693 for (auto &KV : LiveOuts) 2694 delete KV.second; 2695 LiveOuts.clear(); 2696 } 2697 2698 void removeLiveOut(PHINode *PN) { 2699 delete LiveOuts[PN]; 2700 LiveOuts.erase(PN); 2701 } 2702 2703 const MapVector<PHINode *, VPLiveOut *> &getLiveOuts() const { 2704 return LiveOuts; 2705 } 2706 2707 private: 2708 /// Add to the given dominator tree the header block and every new basic block 2709 /// that was created between it and the latch block, inclusive. 2710 static void updateDominatorTree(DominatorTree *DT, BasicBlock *LoopLatchBB, 2711 BasicBlock *LoopPreHeaderBB, 2712 BasicBlock *LoopExitBB); 2713 }; 2714 2715 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 2716 /// VPlanPrinter prints a given VPlan to a given output stream. The printing is 2717 /// indented and follows the dot format. 2718 class VPlanPrinter { 2719 raw_ostream &OS; 2720 const VPlan &Plan; 2721 unsigned Depth = 0; 2722 unsigned TabWidth = 2; 2723 std::string Indent; 2724 unsigned BID = 0; 2725 SmallDenseMap<const VPBlockBase *, unsigned> BlockID; 2726 2727 VPSlotTracker SlotTracker; 2728 2729 /// Handle indentation. 2730 void bumpIndent(int b) { Indent = std::string((Depth += b) * TabWidth, ' '); } 2731 2732 /// Print a given \p Block of the Plan. 2733 void dumpBlock(const VPBlockBase *Block); 2734 2735 /// Print the information related to the CFG edges going out of a given 2736 /// \p Block, followed by printing the successor blocks themselves. 2737 void dumpEdges(const VPBlockBase *Block); 2738 2739 /// Print a given \p BasicBlock, including its VPRecipes, followed by printing 2740 /// its successor blocks. 2741 void dumpBasicBlock(const VPBasicBlock *BasicBlock); 2742 2743 /// Print a given \p Region of the Plan. 2744 void dumpRegion(const VPRegionBlock *Region); 2745 2746 unsigned getOrCreateBID(const VPBlockBase *Block) { 2747 return BlockID.count(Block) ? BlockID[Block] : BlockID[Block] = BID++; 2748 } 2749 2750 Twine getOrCreateName(const VPBlockBase *Block); 2751 2752 Twine getUID(const VPBlockBase *Block); 2753 2754 /// Print the information related to a CFG edge between two VPBlockBases. 2755 void drawEdge(const VPBlockBase *From, const VPBlockBase *To, bool Hidden, 2756 const Twine &Label); 2757 2758 public: 2759 VPlanPrinter(raw_ostream &O, const VPlan &P) 2760 : OS(O), Plan(P), SlotTracker(&P) {} 2761 2762 LLVM_DUMP_METHOD void dump(); 2763 }; 2764 2765 struct VPlanIngredient { 2766 const Value *V; 2767 2768 VPlanIngredient(const Value *V) : V(V) {} 2769 2770 void print(raw_ostream &O) const; 2771 }; 2772 2773 inline raw_ostream &operator<<(raw_ostream &OS, const VPlanIngredient &I) { 2774 I.print(OS); 2775 return OS; 2776 } 2777 2778 inline raw_ostream &operator<<(raw_ostream &OS, const VPlan &Plan) { 2779 Plan.print(OS); 2780 return OS; 2781 } 2782 #endif 2783 2784 //===----------------------------------------------------------------------===// 2785 // VPlan Utilities 2786 //===----------------------------------------------------------------------===// 2787 2788 /// Class that provides utilities for VPBlockBases in VPlan. 2789 class VPBlockUtils { 2790 public: 2791 VPBlockUtils() = delete; 2792 2793 /// Insert disconnected VPBlockBase \p NewBlock after \p BlockPtr. Add \p 2794 /// NewBlock as successor of \p BlockPtr and \p BlockPtr as predecessor of \p 2795 /// NewBlock, and propagate \p BlockPtr parent to \p NewBlock. \p BlockPtr's 2796 /// successors are moved from \p BlockPtr to \p NewBlock and \p BlockPtr's 2797 /// conditional bit is propagated to \p NewBlock. \p NewBlock must have 2798 /// neither successors nor predecessors. 2799 static void insertBlockAfter(VPBlockBase *NewBlock, VPBlockBase *BlockPtr) { 2800 assert(NewBlock->getSuccessors().empty() && 2801 NewBlock->getPredecessors().empty() && 2802 "Can't insert new block with predecessors or successors."); 2803 NewBlock->setParent(BlockPtr->getParent()); 2804 SmallVector<VPBlockBase *> Succs(BlockPtr->successors()); 2805 for (VPBlockBase *Succ : Succs) { 2806 disconnectBlocks(BlockPtr, Succ); 2807 connectBlocks(NewBlock, Succ); 2808 } 2809 NewBlock->setCondBit(BlockPtr->getCondBit()); 2810 BlockPtr->setCondBit(nullptr); 2811 connectBlocks(BlockPtr, NewBlock); 2812 } 2813 2814 /// Insert disconnected VPBlockBases \p IfTrue and \p IfFalse after \p 2815 /// BlockPtr. Add \p IfTrue and \p IfFalse as succesors of \p BlockPtr and \p 2816 /// BlockPtr as predecessor of \p IfTrue and \p IfFalse. Propagate \p BlockPtr 2817 /// parent to \p IfTrue and \p IfFalse. \p Condition is set as the successor 2818 /// selector. \p BlockPtr must have no successors and \p IfTrue and \p IfFalse 2819 /// must have neither successors nor predecessors. 2820 static void insertTwoBlocksAfter(VPBlockBase *IfTrue, VPBlockBase *IfFalse, 2821 VPValue *Condition, VPBlockBase *BlockPtr) { 2822 assert(IfTrue->getSuccessors().empty() && 2823 "Can't insert IfTrue with successors."); 2824 assert(IfFalse->getSuccessors().empty() && 2825 "Can't insert IfFalse with successors."); 2826 BlockPtr->setTwoSuccessors(IfTrue, IfFalse, Condition); 2827 IfTrue->setPredecessors({BlockPtr}); 2828 IfFalse->setPredecessors({BlockPtr}); 2829 IfTrue->setParent(BlockPtr->getParent()); 2830 IfFalse->setParent(BlockPtr->getParent()); 2831 } 2832 2833 /// Connect VPBlockBases \p From and \p To bi-directionally. Append \p To to 2834 /// the successors of \p From and \p From to the predecessors of \p To. Both 2835 /// VPBlockBases must have the same parent, which can be null. Both 2836 /// VPBlockBases can be already connected to other VPBlockBases. 2837 static void connectBlocks(VPBlockBase *From, VPBlockBase *To) { 2838 assert((From->getParent() == To->getParent()) && 2839 "Can't connect two block with different parents"); 2840 assert(From->getNumSuccessors() < 2 && 2841 "Blocks can't have more than two successors."); 2842 From->appendSuccessor(To); 2843 To->appendPredecessor(From); 2844 } 2845 2846 /// Disconnect VPBlockBases \p From and \p To bi-directionally. Remove \p To 2847 /// from the successors of \p From and \p From from the predecessors of \p To. 2848 static void disconnectBlocks(VPBlockBase *From, VPBlockBase *To) { 2849 assert(To && "Successor to disconnect is null."); 2850 From->removeSuccessor(To); 2851 To->removePredecessor(From); 2852 } 2853 2854 /// Try to merge \p Block into its single predecessor, if \p Block is a 2855 /// VPBasicBlock and its predecessor has a single successor. Returns a pointer 2856 /// to the predecessor \p Block was merged into or nullptr otherwise. 2857 static VPBasicBlock *tryToMergeBlockIntoPredecessor(VPBlockBase *Block) { 2858 auto *VPBB = dyn_cast<VPBasicBlock>(Block); 2859 auto *PredVPBB = 2860 dyn_cast_or_null<VPBasicBlock>(Block->getSinglePredecessor()); 2861 if (!VPBB || !PredVPBB || PredVPBB->getNumSuccessors() != 1) 2862 return nullptr; 2863 2864 for (VPRecipeBase &R : make_early_inc_range(*VPBB)) 2865 R.moveBefore(*PredVPBB, PredVPBB->end()); 2866 VPBlockUtils::disconnectBlocks(PredVPBB, VPBB); 2867 auto *ParentRegion = cast<VPRegionBlock>(Block->getParent()); 2868 if (ParentRegion->getExiting() == Block) 2869 ParentRegion->setExiting(PredVPBB); 2870 SmallVector<VPBlockBase *> Successors(Block->successors()); 2871 for (auto *Succ : Successors) { 2872 VPBlockUtils::disconnectBlocks(Block, Succ); 2873 VPBlockUtils::connectBlocks(PredVPBB, Succ); 2874 } 2875 delete Block; 2876 return PredVPBB; 2877 } 2878 2879 /// Return an iterator range over \p Range which only includes \p BlockTy 2880 /// blocks. The accesses are casted to \p BlockTy. 2881 template <typename BlockTy, typename T> 2882 static auto blocksOnly(const T &Range) { 2883 // Create BaseTy with correct const-ness based on BlockTy. 2884 using BaseTy = 2885 typename std::conditional<std::is_const<BlockTy>::value, 2886 const VPBlockBase, VPBlockBase>::type; 2887 2888 // We need to first create an iterator range over (const) BlocktTy & instead 2889 // of (const) BlockTy * for filter_range to work properly. 2890 auto Mapped = 2891 map_range(Range, [](BaseTy *Block) -> BaseTy & { return *Block; }); 2892 auto Filter = make_filter_range( 2893 Mapped, [](BaseTy &Block) { return isa<BlockTy>(&Block); }); 2894 return map_range(Filter, [](BaseTy &Block) -> BlockTy * { 2895 return cast<BlockTy>(&Block); 2896 }); 2897 } 2898 }; 2899 2900 class VPInterleavedAccessInfo { 2901 DenseMap<VPInstruction *, InterleaveGroup<VPInstruction> *> 2902 InterleaveGroupMap; 2903 2904 /// Type for mapping of instruction based interleave groups to VPInstruction 2905 /// interleave groups 2906 using Old2NewTy = DenseMap<InterleaveGroup<Instruction> *, 2907 InterleaveGroup<VPInstruction> *>; 2908 2909 /// Recursively \p Region and populate VPlan based interleave groups based on 2910 /// \p IAI. 2911 void visitRegion(VPRegionBlock *Region, Old2NewTy &Old2New, 2912 InterleavedAccessInfo &IAI); 2913 /// Recursively traverse \p Block and populate VPlan based interleave groups 2914 /// based on \p IAI. 2915 void visitBlock(VPBlockBase *Block, Old2NewTy &Old2New, 2916 InterleavedAccessInfo &IAI); 2917 2918 public: 2919 VPInterleavedAccessInfo(VPlan &Plan, InterleavedAccessInfo &IAI); 2920 2921 ~VPInterleavedAccessInfo() { 2922 SmallPtrSet<InterleaveGroup<VPInstruction> *, 4> DelSet; 2923 // Avoid releasing a pointer twice. 2924 for (auto &I : InterleaveGroupMap) 2925 DelSet.insert(I.second); 2926 for (auto *Ptr : DelSet) 2927 delete Ptr; 2928 } 2929 2930 /// Get the interleave group that \p Instr belongs to. 2931 /// 2932 /// \returns nullptr if doesn't have such group. 2933 InterleaveGroup<VPInstruction> * 2934 getInterleaveGroup(VPInstruction *Instr) const { 2935 return InterleaveGroupMap.lookup(Instr); 2936 } 2937 }; 2938 2939 /// Class that maps (parts of) an existing VPlan to trees of combined 2940 /// VPInstructions. 2941 class VPlanSlp { 2942 enum class OpMode { Failed, Load, Opcode }; 2943 2944 /// A DenseMapInfo implementation for using SmallVector<VPValue *, 4> as 2945 /// DenseMap keys. 2946 struct BundleDenseMapInfo { 2947 static SmallVector<VPValue *, 4> getEmptyKey() { 2948 return {reinterpret_cast<VPValue *>(-1)}; 2949 } 2950 2951 static SmallVector<VPValue *, 4> getTombstoneKey() { 2952 return {reinterpret_cast<VPValue *>(-2)}; 2953 } 2954 2955 static unsigned getHashValue(const SmallVector<VPValue *, 4> &V) { 2956 return static_cast<unsigned>(hash_combine_range(V.begin(), V.end())); 2957 } 2958 2959 static bool isEqual(const SmallVector<VPValue *, 4> &LHS, 2960 const SmallVector<VPValue *, 4> &RHS) { 2961 return LHS == RHS; 2962 } 2963 }; 2964 2965 /// Mapping of values in the original VPlan to a combined VPInstruction. 2966 DenseMap<SmallVector<VPValue *, 4>, VPInstruction *, BundleDenseMapInfo> 2967 BundleToCombined; 2968 2969 VPInterleavedAccessInfo &IAI; 2970 2971 /// Basic block to operate on. For now, only instructions in a single BB are 2972 /// considered. 2973 const VPBasicBlock &BB; 2974 2975 /// Indicates whether we managed to combine all visited instructions or not. 2976 bool CompletelySLP = true; 2977 2978 /// Width of the widest combined bundle in bits. 2979 unsigned WidestBundleBits = 0; 2980 2981 using MultiNodeOpTy = 2982 typename std::pair<VPInstruction *, SmallVector<VPValue *, 4>>; 2983 2984 // Input operand bundles for the current multi node. Each multi node operand 2985 // bundle contains values not matching the multi node's opcode. They will 2986 // be reordered in reorderMultiNodeOps, once we completed building a 2987 // multi node. 2988 SmallVector<MultiNodeOpTy, 4> MultiNodeOps; 2989 2990 /// Indicates whether we are building a multi node currently. 2991 bool MultiNodeActive = false; 2992 2993 /// Check if we can vectorize Operands together. 2994 bool areVectorizable(ArrayRef<VPValue *> Operands) const; 2995 2996 /// Add combined instruction \p New for the bundle \p Operands. 2997 void addCombined(ArrayRef<VPValue *> Operands, VPInstruction *New); 2998 2999 /// Indicate we hit a bundle we failed to combine. Returns nullptr for now. 3000 VPInstruction *markFailed(); 3001 3002 /// Reorder operands in the multi node to maximize sequential memory access 3003 /// and commutative operations. 3004 SmallVector<MultiNodeOpTy, 4> reorderMultiNodeOps(); 3005 3006 /// Choose the best candidate to use for the lane after \p Last. The set of 3007 /// candidates to choose from are values with an opcode matching \p Last's 3008 /// or loads consecutive to \p Last. 3009 std::pair<OpMode, VPValue *> getBest(OpMode Mode, VPValue *Last, 3010 SmallPtrSetImpl<VPValue *> &Candidates, 3011 VPInterleavedAccessInfo &IAI); 3012 3013 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 3014 /// Print bundle \p Values to dbgs(). 3015 void dumpBundle(ArrayRef<VPValue *> Values); 3016 #endif 3017 3018 public: 3019 VPlanSlp(VPInterleavedAccessInfo &IAI, VPBasicBlock &BB) : IAI(IAI), BB(BB) {} 3020 3021 ~VPlanSlp() = default; 3022 3023 /// Tries to build an SLP tree rooted at \p Operands and returns a 3024 /// VPInstruction combining \p Operands, if they can be combined. 3025 VPInstruction *buildGraph(ArrayRef<VPValue *> Operands); 3026 3027 /// Return the width of the widest combined bundle in bits. 3028 unsigned getWidestBundleBits() const { return WidestBundleBits; } 3029 3030 /// Return true if all visited instruction can be combined. 3031 bool isCompletelySLP() const { return CompletelySLP; } 3032 }; 3033 3034 namespace vputils { 3035 3036 /// Returns true if only the first lane of \p Def is used. 3037 bool onlyFirstLaneUsed(VPValue *Def); 3038 3039 /// Get or create a VPValue that corresponds to the expansion of \p Expr. If \p 3040 /// Expr is a SCEVConstant or SCEVUnknown, return a VPValue wrapping the live-in 3041 /// value. Otherwise return a VPExpandSCEVRecipe to expand \p Expr. If \p Plan's 3042 /// pre-header already contains a recipe expanding \p Expr, return it. If not, 3043 /// create a new one. 3044 VPValue *getOrCreateVPValueForSCEVExpr(VPlan &Plan, const SCEV *Expr, 3045 ScalarEvolution &SE); 3046 3047 } // end namespace vputils 3048 3049 } // end namespace llvm 3050 3051 #endif // LLVM_TRANSFORMS_VECTORIZE_VPLAN_H 3052