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 "VPlanLoopInfo.h" 29 #include "VPlanValue.h" 30 #include "llvm/ADT/DenseMap.h" 31 #include "llvm/ADT/DepthFirstIterator.h" 32 #include "llvm/ADT/GraphTraits.h" 33 #include "llvm/ADT/Optional.h" 34 #include "llvm/ADT/SmallBitVector.h" 35 #include "llvm/ADT/SmallPtrSet.h" 36 #include "llvm/ADT/SmallSet.h" 37 #include "llvm/ADT/SmallVector.h" 38 #include "llvm/ADT/Twine.h" 39 #include "llvm/ADT/ilist.h" 40 #include "llvm/ADT/ilist_node.h" 41 #include "llvm/Analysis/VectorUtils.h" 42 #include "llvm/IR/IRBuilder.h" 43 #include "llvm/Support/InstructionCost.h" 44 #include <algorithm> 45 #include <cassert> 46 #include <cstddef> 47 #include <map> 48 #include <string> 49 50 namespace llvm { 51 52 class BasicBlock; 53 class DominatorTree; 54 class InnerLoopVectorizer; 55 class LoopInfo; 56 class raw_ostream; 57 class RecurrenceDescriptor; 58 class Value; 59 class VPBasicBlock; 60 class VPRegionBlock; 61 class VPlan; 62 class VPlanSlp; 63 64 /// Returns a calculation for the total number of elements for a given \p VF. 65 /// For fixed width vectors this value is a constant, whereas for scalable 66 /// vectors it is an expression determined at runtime. 67 Value *getRuntimeVF(IRBuilder<> &B, Type *Ty, ElementCount VF); 68 69 /// A range of powers-of-2 vectorization factors with fixed start and 70 /// adjustable end. The range includes start and excludes end, e.g.,: 71 /// [1, 9) = {1, 2, 4, 8} 72 struct VFRange { 73 // A power of 2. 74 const ElementCount Start; 75 76 // Need not be a power of 2. If End <= Start range is empty. 77 ElementCount End; 78 79 bool isEmpty() const { 80 return End.getKnownMinValue() <= Start.getKnownMinValue(); 81 } 82 83 VFRange(const ElementCount &Start, const ElementCount &End) 84 : Start(Start), End(End) { 85 assert(Start.isScalable() == End.isScalable() && 86 "Both Start and End should have the same scalable flag"); 87 assert(isPowerOf2_32(Start.getKnownMinValue()) && 88 "Expected Start to be a power of 2"); 89 } 90 }; 91 92 using VPlanPtr = std::unique_ptr<VPlan>; 93 94 /// In what follows, the term "input IR" refers to code that is fed into the 95 /// vectorizer whereas the term "output IR" refers to code that is generated by 96 /// the vectorizer. 97 98 /// VPLane provides a way to access lanes in both fixed width and scalable 99 /// vectors, where for the latter the lane index sometimes needs calculating 100 /// as a runtime expression. 101 class VPLane { 102 public: 103 /// Kind describes how to interpret Lane. 104 enum class Kind : uint8_t { 105 /// For First, Lane is the index into the first N elements of a 106 /// fixed-vector <N x <ElTy>> or a scalable vector <vscale x N x <ElTy>>. 107 First, 108 /// For ScalableLast, Lane is the offset from the start of the last 109 /// N-element subvector in a scalable vector <vscale x N x <ElTy>>. For 110 /// example, a Lane of 0 corresponds to lane `(vscale - 1) * N`, a Lane of 111 /// 1 corresponds to `((vscale - 1) * N) + 1`, etc. 112 ScalableLast 113 }; 114 115 private: 116 /// in [0..VF) 117 unsigned Lane; 118 119 /// Indicates how the Lane should be interpreted, as described above. 120 Kind LaneKind; 121 122 public: 123 VPLane(unsigned Lane, Kind LaneKind) : Lane(Lane), LaneKind(LaneKind) {} 124 125 static VPLane getFirstLane() { return VPLane(0, VPLane::Kind::First); } 126 127 static VPLane getLastLaneForVF(const ElementCount &VF) { 128 unsigned LaneOffset = VF.getKnownMinValue() - 1; 129 Kind LaneKind; 130 if (VF.isScalable()) 131 // In this case 'LaneOffset' refers to the offset from the start of the 132 // last subvector with VF.getKnownMinValue() elements. 133 LaneKind = VPLane::Kind::ScalableLast; 134 else 135 LaneKind = VPLane::Kind::First; 136 return VPLane(LaneOffset, LaneKind); 137 } 138 139 /// Returns a compile-time known value for the lane index and asserts if the 140 /// lane can only be calculated at runtime. 141 unsigned getKnownLane() const { 142 assert(LaneKind == Kind::First); 143 return Lane; 144 } 145 146 /// Returns an expression describing the lane index that can be used at 147 /// runtime. 148 Value *getAsRuntimeExpr(IRBuilder<> &Builder, const ElementCount &VF) const; 149 150 /// Returns the Kind of lane offset. 151 Kind getKind() const { return LaneKind; } 152 153 /// Returns true if this is the first lane of the whole vector. 154 bool isFirstLane() const { return Lane == 0 && LaneKind == Kind::First; } 155 156 /// Maps the lane to a cache index based on \p VF. 157 unsigned mapToCacheIndex(const ElementCount &VF) const { 158 switch (LaneKind) { 159 case VPLane::Kind::ScalableLast: 160 assert(VF.isScalable() && Lane < VF.getKnownMinValue()); 161 return VF.getKnownMinValue() + Lane; 162 default: 163 assert(Lane < VF.getKnownMinValue()); 164 return Lane; 165 } 166 } 167 168 /// Returns the maxmimum number of lanes that we are able to consider 169 /// caching for \p VF. 170 static unsigned getNumCachedLanes(const ElementCount &VF) { 171 return VF.getKnownMinValue() * (VF.isScalable() ? 2 : 1); 172 } 173 }; 174 175 /// VPIteration represents a single point in the iteration space of the output 176 /// (vectorized and/or unrolled) IR loop. 177 struct VPIteration { 178 /// in [0..UF) 179 unsigned Part; 180 181 VPLane Lane; 182 183 VPIteration(unsigned Part, unsigned Lane, 184 VPLane::Kind Kind = VPLane::Kind::First) 185 : Part(Part), Lane(Lane, Kind) {} 186 187 VPIteration(unsigned Part, const VPLane &Lane) : Part(Part), Lane(Lane) {} 188 189 bool isFirstIteration() const { return Part == 0 && Lane.isFirstLane(); } 190 }; 191 192 /// VPTransformState holds information passed down when "executing" a VPlan, 193 /// needed for generating the output IR. 194 struct VPTransformState { 195 VPTransformState(ElementCount VF, unsigned UF, LoopInfo *LI, 196 DominatorTree *DT, IRBuilder<> &Builder, 197 InnerLoopVectorizer *ILV, VPlan *Plan) 198 : VF(VF), UF(UF), Instance(), LI(LI), DT(DT), Builder(Builder), ILV(ILV), 199 Plan(Plan) {} 200 201 /// The chosen Vectorization and Unroll Factors of the loop being vectorized. 202 ElementCount VF; 203 unsigned UF; 204 205 /// Hold the indices to generate specific scalar instructions. Null indicates 206 /// that all instances are to be generated, using either scalar or vector 207 /// instructions. 208 Optional<VPIteration> Instance; 209 210 struct DataState { 211 /// A type for vectorized values in the new loop. Each value from the 212 /// original loop, when vectorized, is represented by UF vector values in 213 /// the new unrolled loop, where UF is the unroll factor. 214 typedef SmallVector<Value *, 2> PerPartValuesTy; 215 216 DenseMap<VPValue *, PerPartValuesTy> PerPartOutput; 217 218 using ScalarsPerPartValuesTy = SmallVector<SmallVector<Value *, 4>, 2>; 219 DenseMap<VPValue *, ScalarsPerPartValuesTy> PerPartScalars; 220 } Data; 221 222 /// Get the generated Value for a given VPValue and a given Part. Note that 223 /// as some Defs are still created by ILV and managed in its ValueMap, this 224 /// method will delegate the call to ILV in such cases in order to provide 225 /// callers a consistent API. 226 /// \see set. 227 Value *get(VPValue *Def, unsigned Part); 228 229 /// Get the generated Value for a given VPValue and given Part and Lane. 230 Value *get(VPValue *Def, const VPIteration &Instance); 231 232 bool hasVectorValue(VPValue *Def, unsigned Part) { 233 auto I = Data.PerPartOutput.find(Def); 234 return I != Data.PerPartOutput.end() && Part < I->second.size() && 235 I->second[Part]; 236 } 237 238 bool hasAnyVectorValue(VPValue *Def) const { 239 return Data.PerPartOutput.find(Def) != Data.PerPartOutput.end(); 240 } 241 242 bool hasScalarValue(VPValue *Def, VPIteration Instance) { 243 auto I = Data.PerPartScalars.find(Def); 244 if (I == Data.PerPartScalars.end()) 245 return false; 246 unsigned CacheIdx = Instance.Lane.mapToCacheIndex(VF); 247 return Instance.Part < I->second.size() && 248 CacheIdx < I->second[Instance.Part].size() && 249 I->second[Instance.Part][CacheIdx]; 250 } 251 252 /// Set the generated Value for a given VPValue and a given Part. 253 void set(VPValue *Def, Value *V, unsigned Part) { 254 if (!Data.PerPartOutput.count(Def)) { 255 DataState::PerPartValuesTy Entry(UF); 256 Data.PerPartOutput[Def] = Entry; 257 } 258 Data.PerPartOutput[Def][Part] = V; 259 } 260 /// Reset an existing vector value for \p Def and a given \p Part. 261 void reset(VPValue *Def, Value *V, unsigned Part) { 262 auto Iter = Data.PerPartOutput.find(Def); 263 assert(Iter != Data.PerPartOutput.end() && 264 "need to overwrite existing value"); 265 Iter->second[Part] = V; 266 } 267 268 /// Set the generated scalar \p V for \p Def and the given \p Instance. 269 void set(VPValue *Def, Value *V, const VPIteration &Instance) { 270 auto Iter = Data.PerPartScalars.insert({Def, {}}); 271 auto &PerPartVec = Iter.first->second; 272 while (PerPartVec.size() <= Instance.Part) 273 PerPartVec.emplace_back(); 274 auto &Scalars = PerPartVec[Instance.Part]; 275 unsigned CacheIdx = Instance.Lane.mapToCacheIndex(VF); 276 while (Scalars.size() <= CacheIdx) 277 Scalars.push_back(nullptr); 278 assert(!Scalars[CacheIdx] && "should overwrite existing value"); 279 Scalars[CacheIdx] = V; 280 } 281 282 /// Reset an existing scalar value for \p Def and a given \p Instance. 283 void reset(VPValue *Def, Value *V, const VPIteration &Instance) { 284 auto Iter = Data.PerPartScalars.find(Def); 285 assert(Iter != Data.PerPartScalars.end() && 286 "need to overwrite existing value"); 287 assert(Instance.Part < Iter->second.size() && 288 "need to overwrite existing value"); 289 unsigned CacheIdx = Instance.Lane.mapToCacheIndex(VF); 290 assert(CacheIdx < Iter->second[Instance.Part].size() && 291 "need to overwrite existing value"); 292 Iter->second[Instance.Part][CacheIdx] = V; 293 } 294 295 /// Hold state information used when constructing the CFG of the output IR, 296 /// traversing the VPBasicBlocks and generating corresponding IR BasicBlocks. 297 struct CFGState { 298 /// The previous VPBasicBlock visited. Initially set to null. 299 VPBasicBlock *PrevVPBB = nullptr; 300 301 /// The previous IR BasicBlock created or used. Initially set to the new 302 /// header BasicBlock. 303 BasicBlock *PrevBB = nullptr; 304 305 /// The last IR BasicBlock in the output IR. Set to the new latch 306 /// BasicBlock, used for placing the newly created BasicBlocks. 307 BasicBlock *LastBB = nullptr; 308 309 /// A mapping of each VPBasicBlock to the corresponding BasicBlock. In case 310 /// of replication, maps the BasicBlock of the last replica created. 311 SmallDenseMap<VPBasicBlock *, BasicBlock *> VPBB2IRBB; 312 313 /// Vector of VPBasicBlocks whose terminator instruction needs to be fixed 314 /// up at the end of vector code generation. 315 SmallVector<VPBasicBlock *, 8> VPBBsToFix; 316 317 CFGState() = default; 318 } CFG; 319 320 /// Hold a pointer to LoopInfo to register new basic blocks in the loop. 321 LoopInfo *LI; 322 323 /// Hold a pointer to Dominator Tree to register new basic blocks in the loop. 324 DominatorTree *DT; 325 326 /// Hold a reference to the IRBuilder used to generate output IR code. 327 IRBuilder<> &Builder; 328 329 VPValue2ValueTy VPValue2Value; 330 331 /// Hold the canonical scalar IV of the vector loop (start=0, step=VF*UF). 332 Value *CanonicalIV = nullptr; 333 334 /// Hold the trip count of the scalar loop. 335 Value *TripCount = nullptr; 336 337 /// Hold a pointer to InnerLoopVectorizer to reuse its IR generation methods. 338 InnerLoopVectorizer *ILV; 339 340 /// Pointer to the VPlan code is generated for. 341 VPlan *Plan; 342 }; 343 344 /// VPBlockBase is the building block of the Hierarchical Control-Flow Graph. 345 /// A VPBlockBase can be either a VPBasicBlock or a VPRegionBlock. 346 class VPBlockBase { 347 friend class VPBlockUtils; 348 349 const unsigned char SubclassID; ///< Subclass identifier (for isa/dyn_cast). 350 351 /// An optional name for the block. 352 std::string Name; 353 354 /// The immediate VPRegionBlock which this VPBlockBase belongs to, or null if 355 /// it is a topmost VPBlockBase. 356 VPRegionBlock *Parent = nullptr; 357 358 /// List of predecessor blocks. 359 SmallVector<VPBlockBase *, 1> Predecessors; 360 361 /// List of successor blocks. 362 SmallVector<VPBlockBase *, 1> Successors; 363 364 /// Successor selector managed by a VPUser. For blocks with zero or one 365 /// successors, there is no operand. Otherwise there is exactly one operand 366 /// which is the branch condition. 367 VPUser CondBitUser; 368 369 /// If the block is predicated, its predicate is stored as an operand of this 370 /// VPUser to maintain the def-use relations. Otherwise there is no operand 371 /// here. 372 VPUser PredicateUser; 373 374 /// VPlan containing the block. Can only be set on the entry block of the 375 /// plan. 376 VPlan *Plan = nullptr; 377 378 /// Add \p Successor as the last successor to this block. 379 void appendSuccessor(VPBlockBase *Successor) { 380 assert(Successor && "Cannot add nullptr successor!"); 381 Successors.push_back(Successor); 382 } 383 384 /// Add \p Predecessor as the last predecessor to this block. 385 void appendPredecessor(VPBlockBase *Predecessor) { 386 assert(Predecessor && "Cannot add nullptr predecessor!"); 387 Predecessors.push_back(Predecessor); 388 } 389 390 /// Remove \p Predecessor from the predecessors of this block. 391 void removePredecessor(VPBlockBase *Predecessor) { 392 auto Pos = find(Predecessors, Predecessor); 393 assert(Pos && "Predecessor does not exist"); 394 Predecessors.erase(Pos); 395 } 396 397 /// Remove \p Successor from the successors of this block. 398 void removeSuccessor(VPBlockBase *Successor) { 399 auto Pos = find(Successors, Successor); 400 assert(Pos && "Successor does not exist"); 401 Successors.erase(Pos); 402 } 403 404 protected: 405 VPBlockBase(const unsigned char SC, const std::string &N) 406 : SubclassID(SC), Name(N) {} 407 408 public: 409 /// An enumeration for keeping track of the concrete subclass of VPBlockBase 410 /// that are actually instantiated. Values of this enumeration are kept in the 411 /// SubclassID field of the VPBlockBase objects. They are used for concrete 412 /// type identification. 413 using VPBlockTy = enum { VPBasicBlockSC, VPRegionBlockSC }; 414 415 using VPBlocksTy = SmallVectorImpl<VPBlockBase *>; 416 417 virtual ~VPBlockBase() = default; 418 419 const std::string &getName() const { return Name; } 420 421 void setName(const Twine &newName) { Name = newName.str(); } 422 423 /// \return an ID for the concrete type of this object. 424 /// This is used to implement the classof checks. This should not be used 425 /// for any other purpose, as the values may change as LLVM evolves. 426 unsigned getVPBlockID() const { return SubclassID; } 427 428 VPRegionBlock *getParent() { return Parent; } 429 const VPRegionBlock *getParent() const { return Parent; } 430 431 /// \return A pointer to the plan containing the current block. 432 VPlan *getPlan(); 433 const VPlan *getPlan() const; 434 435 /// Sets the pointer of the plan containing the block. The block must be the 436 /// entry block into the VPlan. 437 void setPlan(VPlan *ParentPlan); 438 439 void setParent(VPRegionBlock *P) { Parent = P; } 440 441 /// \return the VPBasicBlock that is the entry of this VPBlockBase, 442 /// recursively, if the latter is a VPRegionBlock. Otherwise, if this 443 /// VPBlockBase is a VPBasicBlock, it is returned. 444 const VPBasicBlock *getEntryBasicBlock() const; 445 VPBasicBlock *getEntryBasicBlock(); 446 447 /// \return the VPBasicBlock that is the exit of this VPBlockBase, 448 /// recursively, if the latter is a VPRegionBlock. Otherwise, if this 449 /// VPBlockBase is a VPBasicBlock, it is returned. 450 const VPBasicBlock *getExitBasicBlock() const; 451 VPBasicBlock *getExitBasicBlock(); 452 453 const VPBlocksTy &getSuccessors() const { return Successors; } 454 VPBlocksTy &getSuccessors() { return Successors; } 455 456 const VPBlocksTy &getPredecessors() const { return Predecessors; } 457 VPBlocksTy &getPredecessors() { return Predecessors; } 458 459 /// \return the successor of this VPBlockBase if it has a single successor. 460 /// Otherwise return a null pointer. 461 VPBlockBase *getSingleSuccessor() const { 462 return (Successors.size() == 1 ? *Successors.begin() : nullptr); 463 } 464 465 /// \return the predecessor of this VPBlockBase if it has a single 466 /// predecessor. Otherwise return a null pointer. 467 VPBlockBase *getSinglePredecessor() const { 468 return (Predecessors.size() == 1 ? *Predecessors.begin() : nullptr); 469 } 470 471 size_t getNumSuccessors() const { return Successors.size(); } 472 size_t getNumPredecessors() const { return Predecessors.size(); } 473 474 /// An Enclosing Block of a block B is any block containing B, including B 475 /// itself. \return the closest enclosing block starting from "this", which 476 /// has successors. \return the root enclosing block if all enclosing blocks 477 /// have no successors. 478 VPBlockBase *getEnclosingBlockWithSuccessors(); 479 480 /// \return the closest enclosing block starting from "this", which has 481 /// predecessors. \return the root enclosing block if all enclosing blocks 482 /// have no predecessors. 483 VPBlockBase *getEnclosingBlockWithPredecessors(); 484 485 /// \return the successors either attached directly to this VPBlockBase or, if 486 /// this VPBlockBase is the exit block of a VPRegionBlock and has no 487 /// successors of its own, search recursively for the first enclosing 488 /// VPRegionBlock that has successors and return them. If no such 489 /// VPRegionBlock exists, return the (empty) successors of the topmost 490 /// VPBlockBase reached. 491 const VPBlocksTy &getHierarchicalSuccessors() { 492 return getEnclosingBlockWithSuccessors()->getSuccessors(); 493 } 494 495 /// \return the hierarchical successor of this VPBlockBase if it has a single 496 /// hierarchical successor. Otherwise return a null pointer. 497 VPBlockBase *getSingleHierarchicalSuccessor() { 498 return getEnclosingBlockWithSuccessors()->getSingleSuccessor(); 499 } 500 501 /// \return the predecessors either attached directly to this VPBlockBase or, 502 /// if this VPBlockBase is the entry block of a VPRegionBlock and has no 503 /// predecessors of its own, search recursively for the first enclosing 504 /// VPRegionBlock that has predecessors and return them. If no such 505 /// VPRegionBlock exists, return the (empty) predecessors of the topmost 506 /// VPBlockBase reached. 507 const VPBlocksTy &getHierarchicalPredecessors() { 508 return getEnclosingBlockWithPredecessors()->getPredecessors(); 509 } 510 511 /// \return the hierarchical predecessor of this VPBlockBase if it has a 512 /// single hierarchical predecessor. Otherwise return a null pointer. 513 VPBlockBase *getSingleHierarchicalPredecessor() { 514 return getEnclosingBlockWithPredecessors()->getSinglePredecessor(); 515 } 516 517 /// \return the condition bit selecting the successor. 518 VPValue *getCondBit(); 519 /// \return the condition bit selecting the successor. 520 const VPValue *getCondBit() const; 521 /// Set the condition bit selecting the successor. 522 void setCondBit(VPValue *CV); 523 524 /// \return the block's predicate. 525 VPValue *getPredicate(); 526 /// \return the block's predicate. 527 const VPValue *getPredicate() const; 528 /// Set the block's predicate. 529 void setPredicate(VPValue *Pred); 530 531 /// Set a given VPBlockBase \p Successor as the single successor of this 532 /// VPBlockBase. This VPBlockBase is not added as predecessor of \p Successor. 533 /// This VPBlockBase must have no successors. 534 void setOneSuccessor(VPBlockBase *Successor) { 535 assert(Successors.empty() && "Setting one successor when others exist."); 536 appendSuccessor(Successor); 537 } 538 539 /// Set two given VPBlockBases \p IfTrue and \p IfFalse to be the two 540 /// successors of this VPBlockBase. \p Condition is set as the successor 541 /// selector. This VPBlockBase is not added as predecessor of \p IfTrue or \p 542 /// IfFalse. This VPBlockBase must have no successors. 543 void setTwoSuccessors(VPBlockBase *IfTrue, VPBlockBase *IfFalse, 544 VPValue *Condition) { 545 assert(Successors.empty() && "Setting two successors when others exist."); 546 assert(Condition && "Setting two successors without condition!"); 547 setCondBit(Condition); 548 appendSuccessor(IfTrue); 549 appendSuccessor(IfFalse); 550 } 551 552 /// Set each VPBasicBlock in \p NewPreds as predecessor of this VPBlockBase. 553 /// This VPBlockBase must have no predecessors. This VPBlockBase is not added 554 /// as successor of any VPBasicBlock in \p NewPreds. 555 void setPredecessors(ArrayRef<VPBlockBase *> NewPreds) { 556 assert(Predecessors.empty() && "Block predecessors already set."); 557 for (auto *Pred : NewPreds) 558 appendPredecessor(Pred); 559 } 560 561 /// Remove all the predecessor of this block. 562 void clearPredecessors() { Predecessors.clear(); } 563 564 /// Remove all the successors of this block and set to null its condition bit 565 void clearSuccessors() { 566 Successors.clear(); 567 setCondBit(nullptr); 568 } 569 570 /// The method which generates the output IR that correspond to this 571 /// VPBlockBase, thereby "executing" the VPlan. 572 virtual void execute(struct VPTransformState *State) = 0; 573 574 /// Delete all blocks reachable from a given VPBlockBase, inclusive. 575 static void deleteCFG(VPBlockBase *Entry); 576 577 /// Return true if it is legal to hoist instructions into this block. 578 bool isLegalToHoistInto() { 579 // There are currently no constraints that prevent an instruction to be 580 // hoisted into a VPBlockBase. 581 return true; 582 } 583 584 /// Replace all operands of VPUsers in the block with \p NewValue and also 585 /// replaces all uses of VPValues defined in the block with NewValue. 586 virtual void dropAllReferences(VPValue *NewValue) = 0; 587 588 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 589 void printAsOperand(raw_ostream &OS, bool PrintType) const { 590 OS << getName(); 591 } 592 593 /// Print plain-text dump of this VPBlockBase to \p O, prefixing all lines 594 /// with \p Indent. \p SlotTracker is used to print unnamed VPValue's using 595 /// consequtive numbers. 596 /// 597 /// Note that the numbering is applied to the whole VPlan, so printing 598 /// individual blocks is consistent with the whole VPlan printing. 599 virtual void print(raw_ostream &O, const Twine &Indent, 600 VPSlotTracker &SlotTracker) const = 0; 601 602 /// Print plain-text dump of this VPlan to \p O. 603 void print(raw_ostream &O) const { 604 VPSlotTracker SlotTracker(getPlan()); 605 print(O, "", SlotTracker); 606 } 607 608 /// Dump this VPBlockBase to dbgs(). 609 LLVM_DUMP_METHOD void dump() const { print(dbgs()); } 610 #endif 611 }; 612 613 /// VPRecipeBase is a base class modeling a sequence of one or more output IR 614 /// instructions. VPRecipeBase owns the the VPValues it defines through VPDef 615 /// and is responsible for deleting its defined values. Single-value 616 /// VPRecipeBases that also inherit from VPValue must make sure to inherit from 617 /// VPRecipeBase before VPValue. 618 class VPRecipeBase : public ilist_node_with_parent<VPRecipeBase, VPBasicBlock>, 619 public VPDef, 620 public VPUser { 621 friend VPBasicBlock; 622 friend class VPBlockUtils; 623 624 625 /// Each VPRecipe belongs to a single VPBasicBlock. 626 VPBasicBlock *Parent = nullptr; 627 628 public: 629 VPRecipeBase(const unsigned char SC, ArrayRef<VPValue *> Operands) 630 : VPDef(SC), VPUser(Operands) {} 631 632 template <typename IterT> 633 VPRecipeBase(const unsigned char SC, iterator_range<IterT> Operands) 634 : VPDef(SC), VPUser(Operands) {} 635 virtual ~VPRecipeBase() = default; 636 637 /// \return the VPBasicBlock which this VPRecipe belongs to. 638 VPBasicBlock *getParent() { return Parent; } 639 const VPBasicBlock *getParent() const { return Parent; } 640 641 /// The method which generates the output IR instructions that correspond to 642 /// this VPRecipe, thereby "executing" the VPlan. 643 virtual void execute(struct VPTransformState &State) = 0; 644 645 /// Insert an unlinked recipe into a basic block immediately before 646 /// the specified recipe. 647 void insertBefore(VPRecipeBase *InsertPos); 648 649 /// Insert an unlinked Recipe into a basic block immediately after 650 /// the specified Recipe. 651 void insertAfter(VPRecipeBase *InsertPos); 652 653 /// Unlink this recipe from its current VPBasicBlock and insert it into 654 /// the VPBasicBlock that MovePos lives in, right after MovePos. 655 void moveAfter(VPRecipeBase *MovePos); 656 657 /// Unlink this recipe and insert into BB before I. 658 /// 659 /// \pre I is a valid iterator into BB. 660 void moveBefore(VPBasicBlock &BB, iplist<VPRecipeBase>::iterator I); 661 662 /// This method unlinks 'this' from the containing basic block, but does not 663 /// delete it. 664 void removeFromParent(); 665 666 /// This method unlinks 'this' from the containing basic block and deletes it. 667 /// 668 /// \returns an iterator pointing to the element after the erased one 669 iplist<VPRecipeBase>::iterator eraseFromParent(); 670 671 /// Returns the underlying instruction, if the recipe is a VPValue or nullptr 672 /// otherwise. 673 Instruction *getUnderlyingInstr() { 674 return cast<Instruction>(getVPSingleValue()->getUnderlyingValue()); 675 } 676 const Instruction *getUnderlyingInstr() const { 677 return cast<Instruction>(getVPSingleValue()->getUnderlyingValue()); 678 } 679 680 /// Method to support type inquiry through isa, cast, and dyn_cast. 681 static inline bool classof(const VPDef *D) { 682 // All VPDefs are also VPRecipeBases. 683 return true; 684 } 685 686 /// Returns true if the recipe may have side-effects. 687 bool mayHaveSideEffects() const; 688 689 /// Returns true for PHI-like recipes. 690 bool isPhi() const { 691 return getVPDefID() == VPWidenIntOrFpInductionSC || getVPDefID() == VPWidenPHISC || 692 getVPDefID() == VPPredInstPHISC || getVPDefID() == VPWidenCanonicalIVSC; 693 } 694 }; 695 696 inline bool VPUser::classof(const VPDef *Def) { 697 return Def->getVPDefID() == VPRecipeBase::VPInstructionSC || 698 Def->getVPDefID() == VPRecipeBase::VPWidenSC || 699 Def->getVPDefID() == VPRecipeBase::VPWidenCallSC || 700 Def->getVPDefID() == VPRecipeBase::VPWidenSelectSC || 701 Def->getVPDefID() == VPRecipeBase::VPWidenGEPSC || 702 Def->getVPDefID() == VPRecipeBase::VPBlendSC || 703 Def->getVPDefID() == VPRecipeBase::VPInterleaveSC || 704 Def->getVPDefID() == VPRecipeBase::VPReplicateSC || 705 Def->getVPDefID() == VPRecipeBase::VPReductionSC || 706 Def->getVPDefID() == VPRecipeBase::VPBranchOnMaskSC || 707 Def->getVPDefID() == VPRecipeBase::VPWidenMemoryInstructionSC; 708 } 709 710 /// This is a concrete Recipe that models a single VPlan-level instruction. 711 /// While as any Recipe it may generate a sequence of IR instructions when 712 /// executed, these instructions would always form a single-def expression as 713 /// the VPInstruction is also a single def-use vertex. 714 class VPInstruction : public VPRecipeBase, public VPValue { 715 friend class VPlanSlp; 716 717 public: 718 /// VPlan opcodes, extending LLVM IR with idiomatics instructions. 719 enum { 720 Not = Instruction::OtherOpsEnd + 1, 721 ICmpULE, 722 SLPLoad, 723 SLPStore, 724 ActiveLaneMask, 725 }; 726 727 private: 728 typedef unsigned char OpcodeTy; 729 OpcodeTy Opcode; 730 731 /// Utility method serving execute(): generates a single instance of the 732 /// modeled instruction. 733 void generateInstruction(VPTransformState &State, unsigned Part); 734 735 protected: 736 void setUnderlyingInstr(Instruction *I) { setUnderlyingValue(I); } 737 738 public: 739 VPInstruction(unsigned Opcode, ArrayRef<VPValue *> Operands) 740 : VPRecipeBase(VPRecipeBase::VPInstructionSC, Operands), 741 VPValue(VPValue::VPVInstructionSC, nullptr, this), Opcode(Opcode) {} 742 743 VPInstruction(unsigned Opcode, ArrayRef<VPInstruction *> Operands) 744 : VPRecipeBase(VPRecipeBase::VPInstructionSC, {}), 745 VPValue(VPValue::VPVInstructionSC, nullptr, this), Opcode(Opcode) { 746 for (auto *I : Operands) 747 addOperand(I->getVPSingleValue()); 748 } 749 750 VPInstruction(unsigned Opcode, std::initializer_list<VPValue *> Operands) 751 : VPInstruction(Opcode, ArrayRef<VPValue *>(Operands)) {} 752 753 /// Method to support type inquiry through isa, cast, and dyn_cast. 754 static inline bool classof(const VPValue *V) { 755 return V->getVPValueID() == VPValue::VPVInstructionSC; 756 } 757 758 VPInstruction *clone() const { 759 SmallVector<VPValue *, 2> Operands(operands()); 760 return new VPInstruction(Opcode, Operands); 761 } 762 763 /// Method to support type inquiry through isa, cast, and dyn_cast. 764 static inline bool classof(const VPDef *R) { 765 return R->getVPDefID() == VPRecipeBase::VPInstructionSC; 766 } 767 768 unsigned getOpcode() const { return Opcode; } 769 770 /// Generate the instruction. 771 /// TODO: We currently execute only per-part unless a specific instance is 772 /// provided. 773 void execute(VPTransformState &State) override; 774 775 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 776 /// Print the VPInstruction to \p O. 777 void print(raw_ostream &O, const Twine &Indent, 778 VPSlotTracker &SlotTracker) const override; 779 780 /// Print the VPInstruction to dbgs() (for debugging). 781 LLVM_DUMP_METHOD void dump() const; 782 #endif 783 784 /// Return true if this instruction may modify memory. 785 bool mayWriteToMemory() const { 786 // TODO: we can use attributes of the called function to rule out memory 787 // modifications. 788 return Opcode == Instruction::Store || Opcode == Instruction::Call || 789 Opcode == Instruction::Invoke || Opcode == SLPStore; 790 } 791 792 bool hasResult() const { 793 // CallInst may or may not have a result, depending on the called function. 794 // Conservatively return calls have results for now. 795 switch (getOpcode()) { 796 case Instruction::Ret: 797 case Instruction::Br: 798 case Instruction::Store: 799 case Instruction::Switch: 800 case Instruction::IndirectBr: 801 case Instruction::Resume: 802 case Instruction::CatchRet: 803 case Instruction::Unreachable: 804 case Instruction::Fence: 805 case Instruction::AtomicRMW: 806 return false; 807 default: 808 return true; 809 } 810 } 811 }; 812 813 /// VPWidenRecipe is a recipe for producing a copy of vector type its 814 /// ingredient. This recipe covers most of the traditional vectorization cases 815 /// where each ingredient transforms into a vectorized version of itself. 816 class VPWidenRecipe : public VPRecipeBase, public VPValue { 817 public: 818 template <typename IterT> 819 VPWidenRecipe(Instruction &I, iterator_range<IterT> Operands) 820 : VPRecipeBase(VPRecipeBase::VPWidenSC, Operands), 821 VPValue(VPValue::VPVWidenSC, &I, this) {} 822 823 ~VPWidenRecipe() override = default; 824 825 /// Method to support type inquiry through isa, cast, and dyn_cast. 826 static inline bool classof(const VPDef *D) { 827 return D->getVPDefID() == VPRecipeBase::VPWidenSC; 828 } 829 static inline bool classof(const VPValue *V) { 830 return V->getVPValueID() == VPValue::VPVWidenSC; 831 } 832 833 /// Produce widened copies of all Ingredients. 834 void execute(VPTransformState &State) override; 835 836 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 837 /// Print the recipe. 838 void print(raw_ostream &O, const Twine &Indent, 839 VPSlotTracker &SlotTracker) const override; 840 #endif 841 }; 842 843 /// A recipe for widening Call instructions. 844 class VPWidenCallRecipe : public VPRecipeBase, public VPValue { 845 846 public: 847 template <typename IterT> 848 VPWidenCallRecipe(CallInst &I, iterator_range<IterT> CallArguments) 849 : VPRecipeBase(VPRecipeBase::VPWidenCallSC, CallArguments), 850 VPValue(VPValue::VPVWidenCallSC, &I, this) {} 851 852 ~VPWidenCallRecipe() override = default; 853 854 /// Method to support type inquiry through isa, cast, and dyn_cast. 855 static inline bool classof(const VPDef *D) { 856 return D->getVPDefID() == VPRecipeBase::VPWidenCallSC; 857 } 858 859 /// Produce a widened version of the call instruction. 860 void execute(VPTransformState &State) override; 861 862 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 863 /// Print the recipe. 864 void print(raw_ostream &O, const Twine &Indent, 865 VPSlotTracker &SlotTracker) const override; 866 #endif 867 }; 868 869 /// A recipe for widening select instructions. 870 class VPWidenSelectRecipe : public VPRecipeBase, public VPValue { 871 872 /// Is the condition of the select loop invariant? 873 bool InvariantCond; 874 875 public: 876 template <typename IterT> 877 VPWidenSelectRecipe(SelectInst &I, iterator_range<IterT> Operands, 878 bool InvariantCond) 879 : VPRecipeBase(VPRecipeBase::VPWidenSelectSC, Operands), 880 VPValue(VPValue::VPVWidenSelectSC, &I, this), 881 InvariantCond(InvariantCond) {} 882 883 ~VPWidenSelectRecipe() override = default; 884 885 /// Method to support type inquiry through isa, cast, and dyn_cast. 886 static inline bool classof(const VPDef *D) { 887 return D->getVPDefID() == VPRecipeBase::VPWidenSelectSC; 888 } 889 890 /// Produce a widened version of the select instruction. 891 void execute(VPTransformState &State) override; 892 893 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 894 /// Print the recipe. 895 void print(raw_ostream &O, const Twine &Indent, 896 VPSlotTracker &SlotTracker) const override; 897 #endif 898 }; 899 900 /// A recipe for handling GEP instructions. 901 class VPWidenGEPRecipe : public VPRecipeBase, public VPValue { 902 bool IsPtrLoopInvariant; 903 SmallBitVector IsIndexLoopInvariant; 904 905 public: 906 template <typename IterT> 907 VPWidenGEPRecipe(GetElementPtrInst *GEP, iterator_range<IterT> Operands) 908 : VPRecipeBase(VPRecipeBase::VPWidenGEPSC, Operands), 909 VPValue(VPWidenGEPSC, GEP, this), 910 IsIndexLoopInvariant(GEP->getNumIndices(), false) {} 911 912 template <typename IterT> 913 VPWidenGEPRecipe(GetElementPtrInst *GEP, iterator_range<IterT> Operands, 914 Loop *OrigLoop) 915 : VPRecipeBase(VPRecipeBase::VPWidenGEPSC, Operands), 916 VPValue(VPValue::VPVWidenGEPSC, GEP, this), 917 IsIndexLoopInvariant(GEP->getNumIndices(), false) { 918 IsPtrLoopInvariant = OrigLoop->isLoopInvariant(GEP->getPointerOperand()); 919 for (auto Index : enumerate(GEP->indices())) 920 IsIndexLoopInvariant[Index.index()] = 921 OrigLoop->isLoopInvariant(Index.value().get()); 922 } 923 ~VPWidenGEPRecipe() override = default; 924 925 /// Method to support type inquiry through isa, cast, and dyn_cast. 926 static inline bool classof(const VPDef *D) { 927 return D->getVPDefID() == VPRecipeBase::VPWidenGEPSC; 928 } 929 930 /// Generate the gep nodes. 931 void execute(VPTransformState &State) override; 932 933 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 934 /// Print the recipe. 935 void print(raw_ostream &O, const Twine &Indent, 936 VPSlotTracker &SlotTracker) const override; 937 #endif 938 }; 939 940 /// A recipe for handling phi nodes of integer and floating-point inductions, 941 /// producing their vector and scalar values. 942 class VPWidenIntOrFpInductionRecipe : public VPRecipeBase { 943 PHINode *IV; 944 945 public: 946 VPWidenIntOrFpInductionRecipe(PHINode *IV, VPValue *Start, Instruction *Cast, 947 TruncInst *Trunc = nullptr) 948 : VPRecipeBase(VPWidenIntOrFpInductionSC, {Start}), IV(IV) { 949 if (Trunc) 950 new VPValue(Trunc, this); 951 else 952 new VPValue(IV, this); 953 954 if (Cast) 955 new VPValue(Cast, this); 956 } 957 ~VPWidenIntOrFpInductionRecipe() override = default; 958 959 /// Method to support type inquiry through isa, cast, and dyn_cast. 960 static inline bool classof(const VPDef *D) { 961 return D->getVPDefID() == VPRecipeBase::VPWidenIntOrFpInductionSC; 962 } 963 964 /// Generate the vectorized and scalarized versions of the phi node as 965 /// needed by their users. 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 /// Returns the start value of the induction. 975 VPValue *getStartValue() { return getOperand(0); } 976 977 /// Returns the cast VPValue, if one is attached, or nullptr otherwise. 978 VPValue *getCastValue() { 979 if (getNumDefinedValues() != 2) 980 return nullptr; 981 return getVPValue(1); 982 } 983 984 /// Returns the first defined value as TruncInst, if it is one or nullptr 985 /// otherwise. 986 TruncInst *getTruncInst() { 987 return dyn_cast_or_null<TruncInst>(getVPValue(0)->getUnderlyingValue()); 988 } 989 const TruncInst *getTruncInst() const { 990 return dyn_cast_or_null<TruncInst>(getVPValue(0)->getUnderlyingValue()); 991 } 992 }; 993 994 /// A recipe for handling all phi nodes except for integer and FP inductions. 995 /// For reduction PHIs, RdxDesc must point to the corresponding recurrence 996 /// descriptor, the start value is the first operand of the recipe and the 997 /// incoming value from the backedge is the second operand. In the VPlan native 998 /// path, all incoming VPValues & VPBasicBlock pairs are managed in the recipe 999 /// directly. 1000 class VPWidenPHIRecipe : public VPRecipeBase, public VPValue { 1001 /// Descriptor for a reduction PHI. 1002 RecurrenceDescriptor *RdxDesc = nullptr; 1003 1004 /// List of incoming blocks. Only used in the VPlan native path. 1005 SmallVector<VPBasicBlock *, 2> IncomingBlocks; 1006 1007 public: 1008 /// Create a new VPWidenPHIRecipe for the reduction \p Phi described by \p 1009 /// RdxDesc. 1010 VPWidenPHIRecipe(PHINode *Phi, RecurrenceDescriptor &RdxDesc, VPValue &Start) 1011 : VPWidenPHIRecipe(Phi) { 1012 this->RdxDesc = &RdxDesc; 1013 addOperand(&Start); 1014 } 1015 1016 /// Create a VPWidenPHIRecipe for \p Phi 1017 VPWidenPHIRecipe(PHINode *Phi) 1018 : VPRecipeBase(VPWidenPHISC, {}), 1019 VPValue(VPValue::VPVWidenPHISC, Phi, this) {} 1020 ~VPWidenPHIRecipe() override = default; 1021 1022 /// Method to support type inquiry through isa, cast, and dyn_cast. 1023 static inline bool classof(const VPDef *D) { 1024 return D->getVPDefID() == VPRecipeBase::VPWidenPHISC; 1025 } 1026 static inline bool classof(const VPValue *V) { 1027 return V->getVPValueID() == VPValue::VPVWidenPHISC; 1028 } 1029 1030 /// Generate the phi/select nodes. 1031 void execute(VPTransformState &State) override; 1032 1033 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1034 /// Print the recipe. 1035 void print(raw_ostream &O, const Twine &Indent, 1036 VPSlotTracker &SlotTracker) const override; 1037 #endif 1038 1039 /// Returns the start value of the phi, if it is a reduction. 1040 VPValue *getStartValue() { 1041 return getNumOperands() == 0 ? nullptr : getOperand(0); 1042 } 1043 1044 /// Returns the incoming value from the loop backedge, if it is a reduction. 1045 VPValue *getBackedgeValue() { 1046 assert(RdxDesc && "second incoming value is only guaranteed to be backedge " 1047 "value for reductions"); 1048 return getOperand(1); 1049 } 1050 1051 /// Adds a pair (\p IncomingV, \p IncomingBlock) to the phi. 1052 void addIncoming(VPValue *IncomingV, VPBasicBlock *IncomingBlock) { 1053 addOperand(IncomingV); 1054 IncomingBlocks.push_back(IncomingBlock); 1055 } 1056 1057 /// Returns the \p I th incoming VPValue. 1058 VPValue *getIncomingValue(unsigned I) { return getOperand(I); } 1059 1060 /// Returns the \p I th incoming VPBasicBlock. 1061 VPBasicBlock *getIncomingBlock(unsigned I) { return IncomingBlocks[I]; } 1062 1063 RecurrenceDescriptor *getRecurrenceDescriptor() { return RdxDesc; } 1064 }; 1065 1066 /// A recipe for vectorizing a phi-node as a sequence of mask-based select 1067 /// instructions. 1068 class VPBlendRecipe : public VPRecipeBase, public VPValue { 1069 PHINode *Phi; 1070 1071 public: 1072 /// The blend operation is a User of the incoming values and of their 1073 /// respective masks, ordered [I0, M0, I1, M1, ...]. Note that a single value 1074 /// might be incoming with a full mask for which there is no VPValue. 1075 VPBlendRecipe(PHINode *Phi, ArrayRef<VPValue *> Operands) 1076 : VPRecipeBase(VPBlendSC, Operands), 1077 VPValue(VPValue::VPVBlendSC, Phi, this), Phi(Phi) { 1078 assert(Operands.size() > 0 && 1079 ((Operands.size() == 1) || (Operands.size() % 2 == 0)) && 1080 "Expected either a single incoming value or a positive even number " 1081 "of operands"); 1082 } 1083 1084 /// Method to support type inquiry through isa, cast, and dyn_cast. 1085 static inline bool classof(const VPDef *D) { 1086 return D->getVPDefID() == VPRecipeBase::VPBlendSC; 1087 } 1088 1089 /// Return the number of incoming values, taking into account that a single 1090 /// incoming value has no mask. 1091 unsigned getNumIncomingValues() const { return (getNumOperands() + 1) / 2; } 1092 1093 /// Return incoming value number \p Idx. 1094 VPValue *getIncomingValue(unsigned Idx) const { return getOperand(Idx * 2); } 1095 1096 /// Return mask number \p Idx. 1097 VPValue *getMask(unsigned Idx) const { return getOperand(Idx * 2 + 1); } 1098 1099 /// Generate the phi/select nodes. 1100 void execute(VPTransformState &State) override; 1101 1102 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1103 /// Print the recipe. 1104 void print(raw_ostream &O, const Twine &Indent, 1105 VPSlotTracker &SlotTracker) const override; 1106 #endif 1107 }; 1108 1109 /// VPInterleaveRecipe is a recipe for transforming an interleave group of load 1110 /// or stores into one wide load/store and shuffles. The first operand of a 1111 /// VPInterleave recipe is the address, followed by the stored values, followed 1112 /// by an optional mask. 1113 class VPInterleaveRecipe : public VPRecipeBase { 1114 const InterleaveGroup<Instruction> *IG; 1115 1116 bool HasMask = false; 1117 1118 public: 1119 VPInterleaveRecipe(const InterleaveGroup<Instruction> *IG, VPValue *Addr, 1120 ArrayRef<VPValue *> StoredValues, VPValue *Mask) 1121 : VPRecipeBase(VPInterleaveSC, {Addr}), IG(IG) { 1122 for (unsigned i = 0; i < IG->getFactor(); ++i) 1123 if (Instruction *I = IG->getMember(i)) { 1124 if (I->getType()->isVoidTy()) 1125 continue; 1126 new VPValue(I, this); 1127 } 1128 1129 for (auto *SV : StoredValues) 1130 addOperand(SV); 1131 if (Mask) { 1132 HasMask = true; 1133 addOperand(Mask); 1134 } 1135 } 1136 ~VPInterleaveRecipe() override = default; 1137 1138 /// Method to support type inquiry through isa, cast, and dyn_cast. 1139 static inline bool classof(const VPDef *D) { 1140 return D->getVPDefID() == VPRecipeBase::VPInterleaveSC; 1141 } 1142 1143 /// Return the address accessed by this recipe. 1144 VPValue *getAddr() const { 1145 return getOperand(0); // Address is the 1st, mandatory operand. 1146 } 1147 1148 /// Return the mask used by this recipe. Note that a full mask is represented 1149 /// by a nullptr. 1150 VPValue *getMask() const { 1151 // Mask is optional and therefore the last, currently 2nd operand. 1152 return HasMask ? getOperand(getNumOperands() - 1) : nullptr; 1153 } 1154 1155 /// Return the VPValues stored by this interleave group. If it is a load 1156 /// interleave group, return an empty ArrayRef. 1157 ArrayRef<VPValue *> getStoredValues() const { 1158 // The first operand is the address, followed by the stored values, followed 1159 // by an optional mask. 1160 return ArrayRef<VPValue *>(op_begin(), getNumOperands()) 1161 .slice(1, getNumOperands() - (HasMask ? 2 : 1)); 1162 } 1163 1164 /// Generate the wide load or store, and shuffles. 1165 void execute(VPTransformState &State) override; 1166 1167 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1168 /// Print the recipe. 1169 void print(raw_ostream &O, const Twine &Indent, 1170 VPSlotTracker &SlotTracker) const override; 1171 #endif 1172 1173 const InterleaveGroup<Instruction> *getInterleaveGroup() { return IG; } 1174 }; 1175 1176 /// A recipe to represent inloop reduction operations, performing a reduction on 1177 /// a vector operand into a scalar value, and adding the result to a chain. 1178 /// The Operands are {ChainOp, VecOp, [Condition]}. 1179 class VPReductionRecipe : public VPRecipeBase, public VPValue { 1180 /// The recurrence decriptor for the reduction in question. 1181 RecurrenceDescriptor *RdxDesc; 1182 /// Pointer to the TTI, needed to create the target reduction 1183 const TargetTransformInfo *TTI; 1184 1185 public: 1186 VPReductionRecipe(RecurrenceDescriptor *R, Instruction *I, VPValue *ChainOp, 1187 VPValue *VecOp, VPValue *CondOp, 1188 const TargetTransformInfo *TTI) 1189 : VPRecipeBase(VPRecipeBase::VPReductionSC, {ChainOp, VecOp}), 1190 VPValue(VPValue::VPVReductionSC, I, this), RdxDesc(R), TTI(TTI) { 1191 if (CondOp) 1192 addOperand(CondOp); 1193 } 1194 1195 ~VPReductionRecipe() override = default; 1196 1197 /// Method to support type inquiry through isa, cast, and dyn_cast. 1198 static inline bool classof(const VPValue *V) { 1199 return V->getVPValueID() == VPValue::VPVReductionSC; 1200 } 1201 1202 static inline bool classof(const VPDef *D) { 1203 return D->getVPDefID() == VPRecipeBase::VPReductionSC; 1204 } 1205 1206 /// Generate the reduction in the loop 1207 void execute(VPTransformState &State) override; 1208 1209 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1210 /// Print the recipe. 1211 void print(raw_ostream &O, const Twine &Indent, 1212 VPSlotTracker &SlotTracker) const override; 1213 #endif 1214 1215 /// The VPValue of the scalar Chain being accumulated. 1216 VPValue *getChainOp() const { return getOperand(0); } 1217 /// The VPValue of the vector value to be reduced. 1218 VPValue *getVecOp() const { return getOperand(1); } 1219 /// The VPValue of the condition for the block. 1220 VPValue *getCondOp() const { 1221 return getNumOperands() > 2 ? getOperand(2) : nullptr; 1222 } 1223 }; 1224 1225 /// VPReplicateRecipe replicates a given instruction producing multiple scalar 1226 /// copies of the original scalar type, one per lane, instead of producing a 1227 /// single copy of widened type for all lanes. If the instruction is known to be 1228 /// uniform only one copy, per lane zero, will be generated. 1229 class VPReplicateRecipe : public VPRecipeBase, public VPValue { 1230 /// Indicator if only a single replica per lane is needed. 1231 bool IsUniform; 1232 1233 /// Indicator if the replicas are also predicated. 1234 bool IsPredicated; 1235 1236 /// Indicator if the scalar values should also be packed into a vector. 1237 bool AlsoPack; 1238 1239 public: 1240 template <typename IterT> 1241 VPReplicateRecipe(Instruction *I, iterator_range<IterT> Operands, 1242 bool IsUniform, bool IsPredicated = false) 1243 : VPRecipeBase(VPReplicateSC, Operands), VPValue(VPVReplicateSC, I, this), 1244 IsUniform(IsUniform), IsPredicated(IsPredicated) { 1245 // Retain the previous behavior of predicateInstructions(), where an 1246 // insert-element of a predicated instruction got hoisted into the 1247 // predicated basic block iff it was its only user. This is achieved by 1248 // having predicated instructions also pack their values into a vector by 1249 // default unless they have a replicated user which uses their scalar value. 1250 AlsoPack = IsPredicated && !I->use_empty(); 1251 } 1252 1253 ~VPReplicateRecipe() override = default; 1254 1255 /// Method to support type inquiry through isa, cast, and dyn_cast. 1256 static inline bool classof(const VPDef *D) { 1257 return D->getVPDefID() == VPRecipeBase::VPReplicateSC; 1258 } 1259 1260 static inline bool classof(const VPValue *V) { 1261 return V->getVPValueID() == VPValue::VPVReplicateSC; 1262 } 1263 1264 /// Generate replicas of the desired Ingredient. Replicas will be generated 1265 /// for all parts and lanes unless a specific part and lane are specified in 1266 /// the \p State. 1267 void execute(VPTransformState &State) override; 1268 1269 void setAlsoPack(bool Pack) { AlsoPack = Pack; } 1270 1271 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1272 /// Print the recipe. 1273 void print(raw_ostream &O, const Twine &Indent, 1274 VPSlotTracker &SlotTracker) const override; 1275 #endif 1276 1277 bool isUniform() const { return IsUniform; } 1278 1279 bool isPacked() const { return AlsoPack; } 1280 1281 bool isPredicated() const { return IsPredicated; } 1282 }; 1283 1284 /// A recipe for generating conditional branches on the bits of a mask. 1285 class VPBranchOnMaskRecipe : public VPRecipeBase { 1286 public: 1287 VPBranchOnMaskRecipe(VPValue *BlockInMask) 1288 : VPRecipeBase(VPBranchOnMaskSC, {}) { 1289 if (BlockInMask) // nullptr means all-one mask. 1290 addOperand(BlockInMask); 1291 } 1292 1293 /// Method to support type inquiry through isa, cast, and dyn_cast. 1294 static inline bool classof(const VPDef *D) { 1295 return D->getVPDefID() == VPRecipeBase::VPBranchOnMaskSC; 1296 } 1297 1298 /// Generate the extraction of the appropriate bit from the block mask and the 1299 /// conditional branch. 1300 void execute(VPTransformState &State) override; 1301 1302 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1303 /// Print the recipe. 1304 void print(raw_ostream &O, const Twine &Indent, 1305 VPSlotTracker &SlotTracker) const override { 1306 O << Indent << "BRANCH-ON-MASK "; 1307 if (VPValue *Mask = getMask()) 1308 Mask->printAsOperand(O, SlotTracker); 1309 else 1310 O << " All-One"; 1311 } 1312 #endif 1313 1314 /// Return the mask used by this recipe. Note that a full mask is represented 1315 /// by a nullptr. 1316 VPValue *getMask() const { 1317 assert(getNumOperands() <= 1 && "should have either 0 or 1 operands"); 1318 // Mask is optional. 1319 return getNumOperands() == 1 ? getOperand(0) : nullptr; 1320 } 1321 }; 1322 1323 /// VPPredInstPHIRecipe is a recipe for generating the phi nodes needed when 1324 /// control converges back from a Branch-on-Mask. The phi nodes are needed in 1325 /// order to merge values that are set under such a branch and feed their uses. 1326 /// The phi nodes can be scalar or vector depending on the users of the value. 1327 /// This recipe works in concert with VPBranchOnMaskRecipe. 1328 class VPPredInstPHIRecipe : public VPRecipeBase, public VPValue { 1329 public: 1330 /// Construct a VPPredInstPHIRecipe given \p PredInst whose value needs a phi 1331 /// nodes after merging back from a Branch-on-Mask. 1332 VPPredInstPHIRecipe(VPValue *PredV) 1333 : VPRecipeBase(VPPredInstPHISC, PredV), 1334 VPValue(VPValue::VPVPredInstPHI, nullptr, this) {} 1335 ~VPPredInstPHIRecipe() override = default; 1336 1337 /// Method to support type inquiry through isa, cast, and dyn_cast. 1338 static inline bool classof(const VPDef *D) { 1339 return D->getVPDefID() == VPRecipeBase::VPPredInstPHISC; 1340 } 1341 1342 /// Generates phi nodes for live-outs as needed to retain SSA form. 1343 void execute(VPTransformState &State) override; 1344 1345 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1346 /// Print the recipe. 1347 void print(raw_ostream &O, const Twine &Indent, 1348 VPSlotTracker &SlotTracker) const override; 1349 #endif 1350 }; 1351 1352 /// A Recipe for widening load/store operations. 1353 /// The recipe uses the following VPValues: 1354 /// - For load: Address, optional mask 1355 /// - For store: Address, stored value, optional mask 1356 /// TODO: We currently execute only per-part unless a specific instance is 1357 /// provided. 1358 class VPWidenMemoryInstructionRecipe : public VPRecipeBase { 1359 Instruction &Ingredient; 1360 1361 void setMask(VPValue *Mask) { 1362 if (!Mask) 1363 return; 1364 addOperand(Mask); 1365 } 1366 1367 bool isMasked() const { 1368 return isStore() ? getNumOperands() == 3 : getNumOperands() == 2; 1369 } 1370 1371 public: 1372 VPWidenMemoryInstructionRecipe(LoadInst &Load, VPValue *Addr, VPValue *Mask) 1373 : VPRecipeBase(VPWidenMemoryInstructionSC, {Addr}), Ingredient(Load) { 1374 new VPValue(VPValue::VPVMemoryInstructionSC, &Load, this); 1375 setMask(Mask); 1376 } 1377 1378 VPWidenMemoryInstructionRecipe(StoreInst &Store, VPValue *Addr, 1379 VPValue *StoredValue, VPValue *Mask) 1380 : VPRecipeBase(VPWidenMemoryInstructionSC, {Addr, StoredValue}), 1381 Ingredient(Store) { 1382 setMask(Mask); 1383 } 1384 1385 /// Method to support type inquiry through isa, cast, and dyn_cast. 1386 static inline bool classof(const VPDef *D) { 1387 return D->getVPDefID() == VPRecipeBase::VPWidenMemoryInstructionSC; 1388 } 1389 1390 /// Return the address accessed by this recipe. 1391 VPValue *getAddr() const { 1392 return getOperand(0); // Address is the 1st, mandatory operand. 1393 } 1394 1395 /// Return the mask used by this recipe. Note that a full mask is represented 1396 /// by a nullptr. 1397 VPValue *getMask() const { 1398 // Mask is optional and therefore the last operand. 1399 return isMasked() ? getOperand(getNumOperands() - 1) : nullptr; 1400 } 1401 1402 /// Returns true if this recipe is a store. 1403 bool isStore() const { return isa<StoreInst>(Ingredient); } 1404 1405 /// Return the address accessed by this recipe. 1406 VPValue *getStoredValue() const { 1407 assert(isStore() && "Stored value only available for store instructions"); 1408 return getOperand(1); // Stored value is the 2nd, mandatory operand. 1409 } 1410 1411 /// Generate the wide load/store. 1412 void execute(VPTransformState &State) override; 1413 1414 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1415 /// Print the recipe. 1416 void print(raw_ostream &O, const Twine &Indent, 1417 VPSlotTracker &SlotTracker) const override; 1418 #endif 1419 }; 1420 1421 /// A Recipe for widening the canonical induction variable of the vector loop. 1422 class VPWidenCanonicalIVRecipe : public VPRecipeBase { 1423 public: 1424 VPWidenCanonicalIVRecipe() : VPRecipeBase(VPWidenCanonicalIVSC, {}) { 1425 new VPValue(nullptr, this); 1426 } 1427 1428 ~VPWidenCanonicalIVRecipe() override = default; 1429 1430 /// Method to support type inquiry through isa, cast, and dyn_cast. 1431 static inline bool classof(const VPDef *D) { 1432 return D->getVPDefID() == VPRecipeBase::VPWidenCanonicalIVSC; 1433 } 1434 1435 /// Generate a canonical vector induction variable of the vector loop, with 1436 /// start = {<Part*VF, Part*VF+1, ..., Part*VF+VF-1> for 0 <= Part < UF}, and 1437 /// step = <VF*UF, VF*UF, ..., VF*UF>. 1438 void execute(VPTransformState &State) override; 1439 1440 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1441 /// Print the recipe. 1442 void print(raw_ostream &O, const Twine &Indent, 1443 VPSlotTracker &SlotTracker) const override; 1444 #endif 1445 }; 1446 1447 /// VPBasicBlock serves as the leaf of the Hierarchical Control-Flow Graph. It 1448 /// holds a sequence of zero or more VPRecipe's each representing a sequence of 1449 /// output IR instructions. All PHI-like recipes must come before any non-PHI recipes. 1450 class VPBasicBlock : public VPBlockBase { 1451 public: 1452 using RecipeListTy = iplist<VPRecipeBase>; 1453 1454 private: 1455 /// The VPRecipes held in the order of output instructions to generate. 1456 RecipeListTy Recipes; 1457 1458 public: 1459 VPBasicBlock(const Twine &Name = "", VPRecipeBase *Recipe = nullptr) 1460 : VPBlockBase(VPBasicBlockSC, Name.str()) { 1461 if (Recipe) 1462 appendRecipe(Recipe); 1463 } 1464 1465 ~VPBasicBlock() override { 1466 while (!Recipes.empty()) 1467 Recipes.pop_back(); 1468 } 1469 1470 /// Instruction iterators... 1471 using iterator = RecipeListTy::iterator; 1472 using const_iterator = RecipeListTy::const_iterator; 1473 using reverse_iterator = RecipeListTy::reverse_iterator; 1474 using const_reverse_iterator = RecipeListTy::const_reverse_iterator; 1475 1476 //===--------------------------------------------------------------------===// 1477 /// Recipe iterator methods 1478 /// 1479 inline iterator begin() { return Recipes.begin(); } 1480 inline const_iterator begin() const { return Recipes.begin(); } 1481 inline iterator end() { return Recipes.end(); } 1482 inline const_iterator end() const { return Recipes.end(); } 1483 1484 inline reverse_iterator rbegin() { return Recipes.rbegin(); } 1485 inline const_reverse_iterator rbegin() const { return Recipes.rbegin(); } 1486 inline reverse_iterator rend() { return Recipes.rend(); } 1487 inline const_reverse_iterator rend() const { return Recipes.rend(); } 1488 1489 inline size_t size() const { return Recipes.size(); } 1490 inline bool empty() const { return Recipes.empty(); } 1491 inline const VPRecipeBase &front() const { return Recipes.front(); } 1492 inline VPRecipeBase &front() { return Recipes.front(); } 1493 inline const VPRecipeBase &back() const { return Recipes.back(); } 1494 inline VPRecipeBase &back() { return Recipes.back(); } 1495 1496 /// Returns a reference to the list of recipes. 1497 RecipeListTy &getRecipeList() { return Recipes; } 1498 1499 /// Returns a pointer to a member of the recipe list. 1500 static RecipeListTy VPBasicBlock::*getSublistAccess(VPRecipeBase *) { 1501 return &VPBasicBlock::Recipes; 1502 } 1503 1504 /// Method to support type inquiry through isa, cast, and dyn_cast. 1505 static inline bool classof(const VPBlockBase *V) { 1506 return V->getVPBlockID() == VPBlockBase::VPBasicBlockSC; 1507 } 1508 1509 void insert(VPRecipeBase *Recipe, iterator InsertPt) { 1510 assert(Recipe && "No recipe to append."); 1511 assert(!Recipe->Parent && "Recipe already in VPlan"); 1512 Recipe->Parent = this; 1513 Recipes.insert(InsertPt, Recipe); 1514 } 1515 1516 /// Augment the existing recipes of a VPBasicBlock with an additional 1517 /// \p Recipe as the last recipe. 1518 void appendRecipe(VPRecipeBase *Recipe) { insert(Recipe, end()); } 1519 1520 /// The method which generates the output IR instructions that correspond to 1521 /// this VPBasicBlock, thereby "executing" the VPlan. 1522 void execute(struct VPTransformState *State) override; 1523 1524 /// Return the position of the first non-phi node recipe in the block. 1525 iterator getFirstNonPhi(); 1526 1527 /// Returns an iterator range over the PHI-like recipes in the block. 1528 iterator_range<iterator> phis() { 1529 return make_range(begin(), getFirstNonPhi()); 1530 } 1531 1532 void dropAllReferences(VPValue *NewValue) override; 1533 1534 /// Split current block at \p SplitAt by inserting a new block between the 1535 /// current block and its successors and moving all recipes starting at 1536 /// SplitAt to the new block. Returns the new block. 1537 VPBasicBlock *splitAt(iterator SplitAt); 1538 1539 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1540 /// Print this VPBsicBlock to \p O, prefixing all lines with \p Indent. \p 1541 /// SlotTracker is used to print unnamed VPValue's using consequtive numbers. 1542 /// 1543 /// Note that the numbering is applied to the whole VPlan, so printing 1544 /// individual blocks is consistent with the whole VPlan printing. 1545 void print(raw_ostream &O, const Twine &Indent, 1546 VPSlotTracker &SlotTracker) const override; 1547 using VPBlockBase::print; // Get the print(raw_stream &O) version. 1548 #endif 1549 1550 private: 1551 /// Create an IR BasicBlock to hold the output instructions generated by this 1552 /// VPBasicBlock, and return it. Update the CFGState accordingly. 1553 BasicBlock *createEmptyBasicBlock(VPTransformState::CFGState &CFG); 1554 }; 1555 1556 /// VPRegionBlock represents a collection of VPBasicBlocks and VPRegionBlocks 1557 /// which form a Single-Entry-Single-Exit subgraph of the output IR CFG. 1558 /// A VPRegionBlock may indicate that its contents are to be replicated several 1559 /// times. This is designed to support predicated scalarization, in which a 1560 /// scalar if-then code structure needs to be generated VF * UF times. Having 1561 /// this replication indicator helps to keep a single model for multiple 1562 /// candidate VF's. The actual replication takes place only once the desired VF 1563 /// and UF have been determined. 1564 class VPRegionBlock : public VPBlockBase { 1565 /// Hold the Single Entry of the SESE region modelled by the VPRegionBlock. 1566 VPBlockBase *Entry; 1567 1568 /// Hold the Single Exit of the SESE region modelled by the VPRegionBlock. 1569 VPBlockBase *Exit; 1570 1571 /// An indicator whether this region is to generate multiple replicated 1572 /// instances of output IR corresponding to its VPBlockBases. 1573 bool IsReplicator; 1574 1575 public: 1576 VPRegionBlock(VPBlockBase *Entry, VPBlockBase *Exit, 1577 const std::string &Name = "", bool IsReplicator = false) 1578 : VPBlockBase(VPRegionBlockSC, Name), Entry(Entry), Exit(Exit), 1579 IsReplicator(IsReplicator) { 1580 assert(Entry->getPredecessors().empty() && "Entry block has predecessors."); 1581 assert(Exit->getSuccessors().empty() && "Exit block has successors."); 1582 Entry->setParent(this); 1583 Exit->setParent(this); 1584 } 1585 VPRegionBlock(const std::string &Name = "", bool IsReplicator = false) 1586 : VPBlockBase(VPRegionBlockSC, Name), Entry(nullptr), Exit(nullptr), 1587 IsReplicator(IsReplicator) {} 1588 1589 ~VPRegionBlock() override { 1590 if (Entry) { 1591 VPValue DummyValue; 1592 Entry->dropAllReferences(&DummyValue); 1593 deleteCFG(Entry); 1594 } 1595 } 1596 1597 /// Method to support type inquiry through isa, cast, and dyn_cast. 1598 static inline bool classof(const VPBlockBase *V) { 1599 return V->getVPBlockID() == VPBlockBase::VPRegionBlockSC; 1600 } 1601 1602 const VPBlockBase *getEntry() const { return Entry; } 1603 VPBlockBase *getEntry() { return Entry; } 1604 1605 /// Set \p EntryBlock as the entry VPBlockBase of this VPRegionBlock. \p 1606 /// EntryBlock must have no predecessors. 1607 void setEntry(VPBlockBase *EntryBlock) { 1608 assert(EntryBlock->getPredecessors().empty() && 1609 "Entry block cannot have predecessors."); 1610 Entry = EntryBlock; 1611 EntryBlock->setParent(this); 1612 } 1613 1614 // FIXME: DominatorTreeBase is doing 'A->getParent()->front()'. 'front' is a 1615 // specific interface of llvm::Function, instead of using 1616 // GraphTraints::getEntryNode. We should add a new template parameter to 1617 // DominatorTreeBase representing the Graph type. 1618 VPBlockBase &front() const { return *Entry; } 1619 1620 const VPBlockBase *getExit() const { return Exit; } 1621 VPBlockBase *getExit() { return Exit; } 1622 1623 /// Set \p ExitBlock as the exit VPBlockBase of this VPRegionBlock. \p 1624 /// ExitBlock must have no successors. 1625 void setExit(VPBlockBase *ExitBlock) { 1626 assert(ExitBlock->getSuccessors().empty() && 1627 "Exit block cannot have successors."); 1628 Exit = ExitBlock; 1629 ExitBlock->setParent(this); 1630 } 1631 1632 /// An indicator whether this region is to generate multiple replicated 1633 /// instances of output IR corresponding to its VPBlockBases. 1634 bool isReplicator() const { return IsReplicator; } 1635 1636 /// The method which generates the output IR instructions that correspond to 1637 /// this VPRegionBlock, thereby "executing" the VPlan. 1638 void execute(struct VPTransformState *State) override; 1639 1640 void dropAllReferences(VPValue *NewValue) override; 1641 1642 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1643 /// Print this VPRegionBlock to \p O (recursively), prefixing all lines with 1644 /// \p Indent. \p SlotTracker is used to print unnamed VPValue's using 1645 /// consequtive numbers. 1646 /// 1647 /// Note that the numbering is applied to the whole VPlan, so printing 1648 /// individual regions is consistent with the whole VPlan printing. 1649 void print(raw_ostream &O, const Twine &Indent, 1650 VPSlotTracker &SlotTracker) const override; 1651 using VPBlockBase::print; // Get the print(raw_stream &O) version. 1652 #endif 1653 }; 1654 1655 //===----------------------------------------------------------------------===// 1656 // GraphTraits specializations for VPlan Hierarchical Control-Flow Graphs // 1657 //===----------------------------------------------------------------------===// 1658 1659 // The following set of template specializations implement GraphTraits to treat 1660 // any VPBlockBase as a node in a graph of VPBlockBases. It's important to note 1661 // that VPBlockBase traits don't recurse into VPRegioBlocks, i.e., if the 1662 // VPBlockBase is a VPRegionBlock, this specialization provides access to its 1663 // successors/predecessors but not to the blocks inside the region. 1664 1665 template <> struct GraphTraits<VPBlockBase *> { 1666 using NodeRef = VPBlockBase *; 1667 using ChildIteratorType = SmallVectorImpl<VPBlockBase *>::iterator; 1668 1669 static NodeRef getEntryNode(NodeRef N) { return N; } 1670 1671 static inline ChildIteratorType child_begin(NodeRef N) { 1672 return N->getSuccessors().begin(); 1673 } 1674 1675 static inline ChildIteratorType child_end(NodeRef N) { 1676 return N->getSuccessors().end(); 1677 } 1678 }; 1679 1680 template <> struct GraphTraits<const VPBlockBase *> { 1681 using NodeRef = const VPBlockBase *; 1682 using ChildIteratorType = SmallVectorImpl<VPBlockBase *>::const_iterator; 1683 1684 static NodeRef getEntryNode(NodeRef N) { return N; } 1685 1686 static inline ChildIteratorType child_begin(NodeRef N) { 1687 return N->getSuccessors().begin(); 1688 } 1689 1690 static inline ChildIteratorType child_end(NodeRef N) { 1691 return N->getSuccessors().end(); 1692 } 1693 }; 1694 1695 // Inverse order specialization for VPBasicBlocks. Predecessors are used instead 1696 // of successors for the inverse traversal. 1697 template <> struct GraphTraits<Inverse<VPBlockBase *>> { 1698 using NodeRef = VPBlockBase *; 1699 using ChildIteratorType = SmallVectorImpl<VPBlockBase *>::iterator; 1700 1701 static NodeRef getEntryNode(Inverse<NodeRef> B) { return B.Graph; } 1702 1703 static inline ChildIteratorType child_begin(NodeRef N) { 1704 return N->getPredecessors().begin(); 1705 } 1706 1707 static inline ChildIteratorType child_end(NodeRef N) { 1708 return N->getPredecessors().end(); 1709 } 1710 }; 1711 1712 // The following set of template specializations implement GraphTraits to 1713 // treat VPRegionBlock as a graph and recurse inside its nodes. It's important 1714 // to note that the blocks inside the VPRegionBlock are treated as VPBlockBases 1715 // (i.e., no dyn_cast is performed, VPBlockBases specialization is used), so 1716 // there won't be automatic recursion into other VPBlockBases that turn to be 1717 // VPRegionBlocks. 1718 1719 template <> 1720 struct GraphTraits<VPRegionBlock *> : public GraphTraits<VPBlockBase *> { 1721 using GraphRef = VPRegionBlock *; 1722 using nodes_iterator = df_iterator<NodeRef>; 1723 1724 static NodeRef getEntryNode(GraphRef N) { return N->getEntry(); } 1725 1726 static nodes_iterator nodes_begin(GraphRef N) { 1727 return nodes_iterator::begin(N->getEntry()); 1728 } 1729 1730 static nodes_iterator nodes_end(GraphRef N) { 1731 // df_iterator::end() returns an empty iterator so the node used doesn't 1732 // matter. 1733 return nodes_iterator::end(N); 1734 } 1735 }; 1736 1737 template <> 1738 struct GraphTraits<const VPRegionBlock *> 1739 : public GraphTraits<const VPBlockBase *> { 1740 using GraphRef = const VPRegionBlock *; 1741 using nodes_iterator = df_iterator<NodeRef>; 1742 1743 static NodeRef getEntryNode(GraphRef N) { return N->getEntry(); } 1744 1745 static nodes_iterator nodes_begin(GraphRef N) { 1746 return nodes_iterator::begin(N->getEntry()); 1747 } 1748 1749 static nodes_iterator nodes_end(GraphRef N) { 1750 // df_iterator::end() returns an empty iterator so the node used doesn't 1751 // matter. 1752 return nodes_iterator::end(N); 1753 } 1754 }; 1755 1756 template <> 1757 struct GraphTraits<Inverse<VPRegionBlock *>> 1758 : public GraphTraits<Inverse<VPBlockBase *>> { 1759 using GraphRef = VPRegionBlock *; 1760 using nodes_iterator = df_iterator<NodeRef>; 1761 1762 static NodeRef getEntryNode(Inverse<GraphRef> N) { 1763 return N.Graph->getExit(); 1764 } 1765 1766 static nodes_iterator nodes_begin(GraphRef N) { 1767 return nodes_iterator::begin(N->getExit()); 1768 } 1769 1770 static nodes_iterator nodes_end(GraphRef N) { 1771 // df_iterator::end() returns an empty iterator so the node used doesn't 1772 // matter. 1773 return nodes_iterator::end(N); 1774 } 1775 }; 1776 1777 /// Iterator to traverse all successors of a VPBlockBase node. This includes the 1778 /// entry node of VPRegionBlocks. Exit blocks of a region implicitly have their 1779 /// parent region's successors. This ensures all blocks in a region are visited 1780 /// before any blocks in a successor region when doing a reverse post-order 1781 // traversal of the graph. 1782 template <typename BlockPtrTy> 1783 class VPAllSuccessorsIterator 1784 : public iterator_facade_base<VPAllSuccessorsIterator<BlockPtrTy>, 1785 std::forward_iterator_tag, VPBlockBase> { 1786 BlockPtrTy Block; 1787 /// Index of the current successor. For VPBasicBlock nodes, this simply is the 1788 /// index for the successor array. For VPRegionBlock, SuccessorIdx == 0 is 1789 /// used for the region's entry block, and SuccessorIdx - 1 are the indices 1790 /// for the successor array. 1791 size_t SuccessorIdx; 1792 1793 static BlockPtrTy getBlockWithSuccs(BlockPtrTy Current) { 1794 while (Current && Current->getNumSuccessors() == 0) 1795 Current = Current->getParent(); 1796 return Current; 1797 } 1798 1799 /// Templated helper to dereference successor \p SuccIdx of \p Block. Used by 1800 /// both the const and non-const operator* implementations. 1801 template <typename T1> static T1 deref(T1 Block, unsigned SuccIdx) { 1802 if (auto *R = dyn_cast<VPRegionBlock>(Block)) { 1803 if (SuccIdx == 0) 1804 return R->getEntry(); 1805 SuccIdx--; 1806 } 1807 1808 // For exit blocks, use the next parent region with successors. 1809 return getBlockWithSuccs(Block)->getSuccessors()[SuccIdx]; 1810 } 1811 1812 public: 1813 VPAllSuccessorsIterator(BlockPtrTy Block, size_t Idx = 0) 1814 : Block(Block), SuccessorIdx(Idx) {} 1815 VPAllSuccessorsIterator(const VPAllSuccessorsIterator &Other) 1816 : Block(Other.Block), SuccessorIdx(Other.SuccessorIdx) {} 1817 1818 VPAllSuccessorsIterator &operator=(const VPAllSuccessorsIterator &R) { 1819 Block = R.Block; 1820 SuccessorIdx = R.SuccessorIdx; 1821 return *this; 1822 } 1823 1824 static VPAllSuccessorsIterator end(BlockPtrTy Block) { 1825 BlockPtrTy ParentWithSuccs = getBlockWithSuccs(Block); 1826 unsigned NumSuccessors = ParentWithSuccs 1827 ? ParentWithSuccs->getNumSuccessors() 1828 : Block->getNumSuccessors(); 1829 1830 if (auto *R = dyn_cast<VPRegionBlock>(Block)) 1831 return {R, NumSuccessors + 1}; 1832 return {Block, NumSuccessors}; 1833 } 1834 1835 bool operator==(const VPAllSuccessorsIterator &R) const { 1836 return Block == R.Block && SuccessorIdx == R.SuccessorIdx; 1837 } 1838 1839 const VPBlockBase *operator*() const { return deref(Block, SuccessorIdx); } 1840 1841 BlockPtrTy operator*() { return deref(Block, SuccessorIdx); } 1842 1843 VPAllSuccessorsIterator &operator++() { 1844 SuccessorIdx++; 1845 return *this; 1846 } 1847 1848 VPAllSuccessorsIterator operator++(int X) { 1849 VPAllSuccessorsIterator Orig = *this; 1850 SuccessorIdx++; 1851 return Orig; 1852 } 1853 }; 1854 1855 /// Helper for GraphTraits specialization that traverses through VPRegionBlocks. 1856 template <typename BlockTy> class VPBlockRecursiveTraversalWrapper { 1857 BlockTy Entry; 1858 1859 public: 1860 VPBlockRecursiveTraversalWrapper(BlockTy Entry) : Entry(Entry) {} 1861 BlockTy getEntry() { return Entry; } 1862 }; 1863 1864 /// GraphTraits specialization to recursively traverse VPBlockBase nodes, 1865 /// including traversing through VPRegionBlocks. Exit blocks of a region 1866 /// implicitly have their parent region's successors. This ensures all blocks in 1867 /// a region are visited before any blocks in a successor region when doing a 1868 /// reverse post-order traversal of the graph. 1869 template <> 1870 struct GraphTraits<VPBlockRecursiveTraversalWrapper<VPBlockBase *>> { 1871 using NodeRef = VPBlockBase *; 1872 using ChildIteratorType = VPAllSuccessorsIterator<VPBlockBase *>; 1873 1874 static NodeRef 1875 getEntryNode(VPBlockRecursiveTraversalWrapper<VPBlockBase *> N) { 1876 return N.getEntry(); 1877 } 1878 1879 static inline ChildIteratorType child_begin(NodeRef N) { 1880 return ChildIteratorType(N); 1881 } 1882 1883 static inline ChildIteratorType child_end(NodeRef N) { 1884 return ChildIteratorType::end(N); 1885 } 1886 }; 1887 1888 template <> 1889 struct GraphTraits<VPBlockRecursiveTraversalWrapper<const VPBlockBase *>> { 1890 using NodeRef = const VPBlockBase *; 1891 using ChildIteratorType = VPAllSuccessorsIterator<const VPBlockBase *>; 1892 1893 static NodeRef 1894 getEntryNode(VPBlockRecursiveTraversalWrapper<const VPBlockBase *> N) { 1895 return N.getEntry(); 1896 } 1897 1898 static inline ChildIteratorType child_begin(NodeRef N) { 1899 return ChildIteratorType(N); 1900 } 1901 1902 static inline ChildIteratorType child_end(NodeRef N) { 1903 return ChildIteratorType::end(N); 1904 } 1905 }; 1906 1907 /// VPlan models a candidate for vectorization, encoding various decisions take 1908 /// to produce efficient output IR, including which branches, basic-blocks and 1909 /// output IR instructions to generate, and their cost. VPlan holds a 1910 /// Hierarchical-CFG of VPBasicBlocks and VPRegionBlocks rooted at an Entry 1911 /// VPBlock. 1912 class VPlan { 1913 friend class VPlanPrinter; 1914 friend class VPSlotTracker; 1915 1916 /// Hold the single entry to the Hierarchical CFG of the VPlan. 1917 VPBlockBase *Entry; 1918 1919 /// Holds the VFs applicable to this VPlan. 1920 SmallSetVector<ElementCount, 2> VFs; 1921 1922 /// Holds the name of the VPlan, for printing. 1923 std::string Name; 1924 1925 /// Holds all the external definitions created for this VPlan. 1926 // TODO: Introduce a specific representation for external definitions in 1927 // VPlan. External definitions must be immutable and hold a pointer to its 1928 // underlying IR that will be used to implement its structural comparison 1929 // (operators '==' and '<'). 1930 SetVector<VPValue *> VPExternalDefs; 1931 1932 /// Represents the backedge taken count of the original loop, for folding 1933 /// the tail. 1934 VPValue *BackedgeTakenCount = nullptr; 1935 1936 /// Holds a mapping between Values and their corresponding VPValue inside 1937 /// VPlan. 1938 Value2VPValueTy Value2VPValue; 1939 1940 /// Contains all VPValues that been allocated by addVPValue directly and need 1941 /// to be free when the plan's destructor is called. 1942 SmallVector<VPValue *, 16> VPValuesToFree; 1943 1944 /// Holds the VPLoopInfo analysis for this VPlan. 1945 VPLoopInfo VPLInfo; 1946 1947 public: 1948 VPlan(VPBlockBase *Entry = nullptr) : Entry(Entry) { 1949 if (Entry) 1950 Entry->setPlan(this); 1951 } 1952 1953 ~VPlan() { 1954 if (Entry) { 1955 VPValue DummyValue; 1956 for (VPBlockBase *Block : depth_first(Entry)) 1957 Block->dropAllReferences(&DummyValue); 1958 1959 VPBlockBase::deleteCFG(Entry); 1960 } 1961 for (VPValue *VPV : VPValuesToFree) 1962 delete VPV; 1963 if (BackedgeTakenCount) 1964 delete BackedgeTakenCount; 1965 for (VPValue *Def : VPExternalDefs) 1966 delete Def; 1967 } 1968 1969 /// Generate the IR code for this VPlan. 1970 void execute(struct VPTransformState *State); 1971 1972 VPBlockBase *getEntry() { return Entry; } 1973 const VPBlockBase *getEntry() const { return Entry; } 1974 1975 VPBlockBase *setEntry(VPBlockBase *Block) { 1976 Entry = Block; 1977 Block->setPlan(this); 1978 return Entry; 1979 } 1980 1981 /// The backedge taken count of the original loop. 1982 VPValue *getOrCreateBackedgeTakenCount() { 1983 if (!BackedgeTakenCount) 1984 BackedgeTakenCount = new VPValue(); 1985 return BackedgeTakenCount; 1986 } 1987 1988 void addVF(ElementCount VF) { VFs.insert(VF); } 1989 1990 bool hasVF(ElementCount VF) { return VFs.count(VF); } 1991 1992 const std::string &getName() const { return Name; } 1993 1994 void setName(const Twine &newName) { Name = newName.str(); } 1995 1996 /// Add \p VPVal to the pool of external definitions if it's not already 1997 /// in the pool. 1998 void addExternalDef(VPValue *VPVal) { VPExternalDefs.insert(VPVal); } 1999 2000 void addVPValue(Value *V) { 2001 assert(V && "Trying to add a null Value to VPlan"); 2002 assert(!Value2VPValue.count(V) && "Value already exists in VPlan"); 2003 VPValue *VPV = new VPValue(V); 2004 Value2VPValue[V] = VPV; 2005 VPValuesToFree.push_back(VPV); 2006 } 2007 2008 void addVPValue(Value *V, VPValue *VPV) { 2009 assert(V && "Trying to add a null Value to VPlan"); 2010 assert(!Value2VPValue.count(V) && "Value already exists in VPlan"); 2011 Value2VPValue[V] = VPV; 2012 } 2013 2014 VPValue *getVPValue(Value *V) { 2015 assert(V && "Trying to get the VPValue of a null Value"); 2016 assert(Value2VPValue.count(V) && "Value does not exist in VPlan"); 2017 return Value2VPValue[V]; 2018 } 2019 2020 VPValue *getOrAddVPValue(Value *V) { 2021 assert(V && "Trying to get or add the VPValue of a null Value"); 2022 if (!Value2VPValue.count(V)) 2023 addVPValue(V); 2024 return getVPValue(V); 2025 } 2026 2027 void removeVPValueFor(Value *V) { Value2VPValue.erase(V); } 2028 2029 /// Return the VPLoopInfo analysis for this VPlan. 2030 VPLoopInfo &getVPLoopInfo() { return VPLInfo; } 2031 const VPLoopInfo &getVPLoopInfo() const { return VPLInfo; } 2032 2033 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 2034 /// Print this VPlan to \p O. 2035 void print(raw_ostream &O) const; 2036 2037 /// Print this VPlan in DOT format to \p O. 2038 void printDOT(raw_ostream &O) const; 2039 2040 /// Dump the plan to stderr (for debugging). 2041 LLVM_DUMP_METHOD void dump() const; 2042 #endif 2043 2044 /// Returns a range mapping the values the range \p Operands to their 2045 /// corresponding VPValues. 2046 iterator_range<mapped_iterator<Use *, std::function<VPValue *(Value *)>>> 2047 mapToVPValues(User::op_range Operands) { 2048 std::function<VPValue *(Value *)> Fn = [this](Value *Op) { 2049 return getOrAddVPValue(Op); 2050 }; 2051 return map_range(Operands, Fn); 2052 } 2053 2054 private: 2055 /// Add to the given dominator tree the header block and every new basic block 2056 /// that was created between it and the latch block, inclusive. 2057 static void updateDominatorTree(DominatorTree *DT, BasicBlock *LoopLatchBB, 2058 BasicBlock *LoopPreHeaderBB, 2059 BasicBlock *LoopExitBB); 2060 }; 2061 2062 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 2063 /// VPlanPrinter prints a given VPlan to a given output stream. The printing is 2064 /// indented and follows the dot format. 2065 class VPlanPrinter { 2066 raw_ostream &OS; 2067 const VPlan &Plan; 2068 unsigned Depth = 0; 2069 unsigned TabWidth = 2; 2070 std::string Indent; 2071 unsigned BID = 0; 2072 SmallDenseMap<const VPBlockBase *, unsigned> BlockID; 2073 2074 VPSlotTracker SlotTracker; 2075 2076 /// Handle indentation. 2077 void bumpIndent(int b) { Indent = std::string((Depth += b) * TabWidth, ' '); } 2078 2079 /// Print a given \p Block of the Plan. 2080 void dumpBlock(const VPBlockBase *Block); 2081 2082 /// Print the information related to the CFG edges going out of a given 2083 /// \p Block, followed by printing the successor blocks themselves. 2084 void dumpEdges(const VPBlockBase *Block); 2085 2086 /// Print a given \p BasicBlock, including its VPRecipes, followed by printing 2087 /// its successor blocks. 2088 void dumpBasicBlock(const VPBasicBlock *BasicBlock); 2089 2090 /// Print a given \p Region of the Plan. 2091 void dumpRegion(const VPRegionBlock *Region); 2092 2093 unsigned getOrCreateBID(const VPBlockBase *Block) { 2094 return BlockID.count(Block) ? BlockID[Block] : BlockID[Block] = BID++; 2095 } 2096 2097 const Twine getOrCreateName(const VPBlockBase *Block); 2098 2099 const Twine getUID(const VPBlockBase *Block); 2100 2101 /// Print the information related to a CFG edge between two VPBlockBases. 2102 void drawEdge(const VPBlockBase *From, const VPBlockBase *To, bool Hidden, 2103 const Twine &Label); 2104 2105 public: 2106 VPlanPrinter(raw_ostream &O, const VPlan &P) 2107 : OS(O), Plan(P), SlotTracker(&P) {} 2108 2109 LLVM_DUMP_METHOD void dump(); 2110 }; 2111 2112 struct VPlanIngredient { 2113 const Value *V; 2114 2115 VPlanIngredient(const Value *V) : V(V) {} 2116 2117 void print(raw_ostream &O) const; 2118 }; 2119 2120 inline raw_ostream &operator<<(raw_ostream &OS, const VPlanIngredient &I) { 2121 I.print(OS); 2122 return OS; 2123 } 2124 2125 inline raw_ostream &operator<<(raw_ostream &OS, const VPlan &Plan) { 2126 Plan.print(OS); 2127 return OS; 2128 } 2129 #endif 2130 2131 //===----------------------------------------------------------------------===// 2132 // VPlan Utilities 2133 //===----------------------------------------------------------------------===// 2134 2135 /// Class that provides utilities for VPBlockBases in VPlan. 2136 class VPBlockUtils { 2137 public: 2138 VPBlockUtils() = delete; 2139 2140 /// Insert disconnected VPBlockBase \p NewBlock after \p BlockPtr. Add \p 2141 /// NewBlock as successor of \p BlockPtr and \p BlockPtr as predecessor of \p 2142 /// NewBlock, and propagate \p BlockPtr parent to \p NewBlock. If \p BlockPtr 2143 /// has more than one successor, its conditional bit is propagated to \p 2144 /// NewBlock. \p NewBlock must have neither successors nor predecessors. 2145 static void insertBlockAfter(VPBlockBase *NewBlock, VPBlockBase *BlockPtr) { 2146 assert(NewBlock->getSuccessors().empty() && 2147 "Can't insert new block with successors."); 2148 // TODO: move successors from BlockPtr to NewBlock when this functionality 2149 // is necessary. For now, setBlockSingleSuccessor will assert if BlockPtr 2150 // already has successors. 2151 BlockPtr->setOneSuccessor(NewBlock); 2152 NewBlock->setPredecessors({BlockPtr}); 2153 NewBlock->setParent(BlockPtr->getParent()); 2154 } 2155 2156 /// Insert disconnected VPBlockBases \p IfTrue and \p IfFalse after \p 2157 /// BlockPtr. Add \p IfTrue and \p IfFalse as succesors of \p BlockPtr and \p 2158 /// BlockPtr as predecessor of \p IfTrue and \p IfFalse. Propagate \p BlockPtr 2159 /// parent to \p IfTrue and \p IfFalse. \p Condition is set as the successor 2160 /// selector. \p BlockPtr must have no successors and \p IfTrue and \p IfFalse 2161 /// must have neither successors nor predecessors. 2162 static void insertTwoBlocksAfter(VPBlockBase *IfTrue, VPBlockBase *IfFalse, 2163 VPValue *Condition, VPBlockBase *BlockPtr) { 2164 assert(IfTrue->getSuccessors().empty() && 2165 "Can't insert IfTrue with successors."); 2166 assert(IfFalse->getSuccessors().empty() && 2167 "Can't insert IfFalse with successors."); 2168 BlockPtr->setTwoSuccessors(IfTrue, IfFalse, Condition); 2169 IfTrue->setPredecessors({BlockPtr}); 2170 IfFalse->setPredecessors({BlockPtr}); 2171 IfTrue->setParent(BlockPtr->getParent()); 2172 IfFalse->setParent(BlockPtr->getParent()); 2173 } 2174 2175 /// Connect VPBlockBases \p From and \p To bi-directionally. Append \p To to 2176 /// the successors of \p From and \p From to the predecessors of \p To. Both 2177 /// VPBlockBases must have the same parent, which can be null. Both 2178 /// VPBlockBases can be already connected to other VPBlockBases. 2179 static void connectBlocks(VPBlockBase *From, VPBlockBase *To) { 2180 assert((From->getParent() == To->getParent()) && 2181 "Can't connect two block with different parents"); 2182 assert(From->getNumSuccessors() < 2 && 2183 "Blocks can't have more than two successors."); 2184 From->appendSuccessor(To); 2185 To->appendPredecessor(From); 2186 } 2187 2188 /// Disconnect VPBlockBases \p From and \p To bi-directionally. Remove \p To 2189 /// from the successors of \p From and \p From from the predecessors of \p To. 2190 static void disconnectBlocks(VPBlockBase *From, VPBlockBase *To) { 2191 assert(To && "Successor to disconnect is null."); 2192 From->removeSuccessor(To); 2193 To->removePredecessor(From); 2194 } 2195 2196 /// Returns true if the edge \p FromBlock -> \p ToBlock is a back-edge. 2197 static bool isBackEdge(const VPBlockBase *FromBlock, 2198 const VPBlockBase *ToBlock, const VPLoopInfo *VPLI) { 2199 assert(FromBlock->getParent() == ToBlock->getParent() && 2200 FromBlock->getParent() && "Must be in same region"); 2201 const VPLoop *FromLoop = VPLI->getLoopFor(FromBlock); 2202 const VPLoop *ToLoop = VPLI->getLoopFor(ToBlock); 2203 if (!FromLoop || !ToLoop || FromLoop != ToLoop) 2204 return false; 2205 2206 // A back-edge is a branch from the loop latch to its header. 2207 return ToLoop->isLoopLatch(FromBlock) && ToBlock == ToLoop->getHeader(); 2208 } 2209 2210 /// Returns true if \p Block is a loop latch 2211 static bool blockIsLoopLatch(const VPBlockBase *Block, 2212 const VPLoopInfo *VPLInfo) { 2213 if (const VPLoop *ParentVPL = VPLInfo->getLoopFor(Block)) 2214 return ParentVPL->isLoopLatch(Block); 2215 2216 return false; 2217 } 2218 2219 /// Count and return the number of succesors of \p PredBlock excluding any 2220 /// backedges. 2221 static unsigned countSuccessorsNoBE(VPBlockBase *PredBlock, 2222 VPLoopInfo *VPLI) { 2223 unsigned Count = 0; 2224 for (VPBlockBase *SuccBlock : PredBlock->getSuccessors()) { 2225 if (!VPBlockUtils::isBackEdge(PredBlock, SuccBlock, VPLI)) 2226 Count++; 2227 } 2228 return Count; 2229 } 2230 2231 /// Return an iterator range over \p Range which only includes \p BlockTy 2232 /// blocks. The accesses are casted to \p BlockTy. 2233 template <typename BlockTy, typename T> 2234 static auto blocksOnly(const T &Range) { 2235 // Create BaseTy with correct const-ness based on BlockTy. 2236 using BaseTy = 2237 typename std::conditional<std::is_const<BlockTy>::value, 2238 const VPBlockBase, VPBlockBase>::type; 2239 2240 // We need to first create an iterator range over (const) BlocktTy & instead 2241 // of (const) BlockTy * for filter_range to work properly. 2242 auto Mapped = 2243 map_range(Range, [](BaseTy *Block) -> BaseTy & { return *Block; }); 2244 auto Filter = make_filter_range( 2245 Mapped, [](BaseTy &Block) { return isa<BlockTy>(&Block); }); 2246 return map_range(Filter, [](BaseTy &Block) -> BlockTy * { 2247 return cast<BlockTy>(&Block); 2248 }); 2249 } 2250 }; 2251 2252 class VPInterleavedAccessInfo { 2253 DenseMap<VPInstruction *, InterleaveGroup<VPInstruction> *> 2254 InterleaveGroupMap; 2255 2256 /// Type for mapping of instruction based interleave groups to VPInstruction 2257 /// interleave groups 2258 using Old2NewTy = DenseMap<InterleaveGroup<Instruction> *, 2259 InterleaveGroup<VPInstruction> *>; 2260 2261 /// Recursively \p Region and populate VPlan based interleave groups based on 2262 /// \p IAI. 2263 void visitRegion(VPRegionBlock *Region, Old2NewTy &Old2New, 2264 InterleavedAccessInfo &IAI); 2265 /// Recursively traverse \p Block and populate VPlan based interleave groups 2266 /// based on \p IAI. 2267 void visitBlock(VPBlockBase *Block, Old2NewTy &Old2New, 2268 InterleavedAccessInfo &IAI); 2269 2270 public: 2271 VPInterleavedAccessInfo(VPlan &Plan, InterleavedAccessInfo &IAI); 2272 2273 ~VPInterleavedAccessInfo() { 2274 SmallPtrSet<InterleaveGroup<VPInstruction> *, 4> DelSet; 2275 // Avoid releasing a pointer twice. 2276 for (auto &I : InterleaveGroupMap) 2277 DelSet.insert(I.second); 2278 for (auto *Ptr : DelSet) 2279 delete Ptr; 2280 } 2281 2282 /// Get the interleave group that \p Instr belongs to. 2283 /// 2284 /// \returns nullptr if doesn't have such group. 2285 InterleaveGroup<VPInstruction> * 2286 getInterleaveGroup(VPInstruction *Instr) const { 2287 return InterleaveGroupMap.lookup(Instr); 2288 } 2289 }; 2290 2291 /// Class that maps (parts of) an existing VPlan to trees of combined 2292 /// VPInstructions. 2293 class VPlanSlp { 2294 enum class OpMode { Failed, Load, Opcode }; 2295 2296 /// A DenseMapInfo implementation for using SmallVector<VPValue *, 4> as 2297 /// DenseMap keys. 2298 struct BundleDenseMapInfo { 2299 static SmallVector<VPValue *, 4> getEmptyKey() { 2300 return {reinterpret_cast<VPValue *>(-1)}; 2301 } 2302 2303 static SmallVector<VPValue *, 4> getTombstoneKey() { 2304 return {reinterpret_cast<VPValue *>(-2)}; 2305 } 2306 2307 static unsigned getHashValue(const SmallVector<VPValue *, 4> &V) { 2308 return static_cast<unsigned>(hash_combine_range(V.begin(), V.end())); 2309 } 2310 2311 static bool isEqual(const SmallVector<VPValue *, 4> &LHS, 2312 const SmallVector<VPValue *, 4> &RHS) { 2313 return LHS == RHS; 2314 } 2315 }; 2316 2317 /// Mapping of values in the original VPlan to a combined VPInstruction. 2318 DenseMap<SmallVector<VPValue *, 4>, VPInstruction *, BundleDenseMapInfo> 2319 BundleToCombined; 2320 2321 VPInterleavedAccessInfo &IAI; 2322 2323 /// Basic block to operate on. For now, only instructions in a single BB are 2324 /// considered. 2325 const VPBasicBlock &BB; 2326 2327 /// Indicates whether we managed to combine all visited instructions or not. 2328 bool CompletelySLP = true; 2329 2330 /// Width of the widest combined bundle in bits. 2331 unsigned WidestBundleBits = 0; 2332 2333 using MultiNodeOpTy = 2334 typename std::pair<VPInstruction *, SmallVector<VPValue *, 4>>; 2335 2336 // Input operand bundles for the current multi node. Each multi node operand 2337 // bundle contains values not matching the multi node's opcode. They will 2338 // be reordered in reorderMultiNodeOps, once we completed building a 2339 // multi node. 2340 SmallVector<MultiNodeOpTy, 4> MultiNodeOps; 2341 2342 /// Indicates whether we are building a multi node currently. 2343 bool MultiNodeActive = false; 2344 2345 /// Check if we can vectorize Operands together. 2346 bool areVectorizable(ArrayRef<VPValue *> Operands) const; 2347 2348 /// Add combined instruction \p New for the bundle \p Operands. 2349 void addCombined(ArrayRef<VPValue *> Operands, VPInstruction *New); 2350 2351 /// Indicate we hit a bundle we failed to combine. Returns nullptr for now. 2352 VPInstruction *markFailed(); 2353 2354 /// Reorder operands in the multi node to maximize sequential memory access 2355 /// and commutative operations. 2356 SmallVector<MultiNodeOpTy, 4> reorderMultiNodeOps(); 2357 2358 /// Choose the best candidate to use for the lane after \p Last. The set of 2359 /// candidates to choose from are values with an opcode matching \p Last's 2360 /// or loads consecutive to \p Last. 2361 std::pair<OpMode, VPValue *> getBest(OpMode Mode, VPValue *Last, 2362 SmallPtrSetImpl<VPValue *> &Candidates, 2363 VPInterleavedAccessInfo &IAI); 2364 2365 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 2366 /// Print bundle \p Values to dbgs(). 2367 void dumpBundle(ArrayRef<VPValue *> Values); 2368 #endif 2369 2370 public: 2371 VPlanSlp(VPInterleavedAccessInfo &IAI, VPBasicBlock &BB) : IAI(IAI), BB(BB) {} 2372 2373 ~VPlanSlp() = default; 2374 2375 /// Tries to build an SLP tree rooted at \p Operands and returns a 2376 /// VPInstruction combining \p Operands, if they can be combined. 2377 VPInstruction *buildGraph(ArrayRef<VPValue *> Operands); 2378 2379 /// Return the width of the widest combined bundle in bits. 2380 unsigned getWidestBundleBits() const { return WidestBundleBits; } 2381 2382 /// Return true if all visited instruction can be combined. 2383 bool isCompletelySLP() const { return CompletelySLP; } 2384 }; 2385 } // end namespace llvm 2386 2387 #endif // LLVM_TRANSFORMS_VECTORIZE_VPLAN_H 2388