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 <algorithm> 44 #include <cassert> 45 #include <cstddef> 46 #include <map> 47 #include <string> 48 49 namespace llvm { 50 51 class LoopVectorizationLegality; 52 class LoopVectorizationCostModel; 53 class BasicBlock; 54 class DominatorTree; 55 class InnerLoopVectorizer; 56 template <class T> class InterleaveGroup; 57 class LoopInfo; 58 class raw_ostream; 59 class Value; 60 class VPBasicBlock; 61 class VPRegionBlock; 62 class VPlan; 63 class VPlanSlp; 64 65 /// A range of powers-of-2 vectorization factors with fixed start and 66 /// adjustable end. The range includes start and excludes end, e.g.,: 67 /// [1, 9) = {1, 2, 4, 8} 68 struct VFRange { 69 // A power of 2. 70 const unsigned Start; 71 72 // Need not be a power of 2. If End <= Start range is empty. 73 unsigned End; 74 }; 75 76 using VPlanPtr = std::unique_ptr<VPlan>; 77 78 /// In what follows, the term "input IR" refers to code that is fed into the 79 /// vectorizer whereas the term "output IR" refers to code that is generated by 80 /// the vectorizer. 81 82 /// VPIteration represents a single point in the iteration space of the output 83 /// (vectorized and/or unrolled) IR loop. 84 struct VPIteration { 85 /// in [0..UF) 86 unsigned Part; 87 88 /// in [0..VF) 89 unsigned Lane; 90 }; 91 92 /// This is a helper struct for maintaining vectorization state. It's used for 93 /// mapping values from the original loop to their corresponding values in 94 /// the new loop. Two mappings are maintained: one for vectorized values and 95 /// one for scalarized values. Vectorized values are represented with UF 96 /// vector values in the new loop, and scalarized values are represented with 97 /// UF x VF scalar values in the new loop. UF and VF are the unroll and 98 /// vectorization factors, respectively. 99 /// 100 /// Entries can be added to either map with setVectorValue and setScalarValue, 101 /// which assert that an entry was not already added before. If an entry is to 102 /// replace an existing one, call resetVectorValue and resetScalarValue. This is 103 /// currently needed to modify the mapped values during "fix-up" operations that 104 /// occur once the first phase of widening is complete. These operations include 105 /// type truncation and the second phase of recurrence widening. 106 /// 107 /// Entries from either map can be retrieved using the getVectorValue and 108 /// getScalarValue functions, which assert that the desired value exists. 109 struct VectorizerValueMap { 110 friend struct VPTransformState; 111 112 private: 113 /// The unroll factor. Each entry in the vector map contains UF vector values. 114 unsigned UF; 115 116 /// The vectorization factor. Each entry in the scalar map contains UF x VF 117 /// scalar values. 118 unsigned VF; 119 120 /// The vector and scalar map storage. We use std::map and not DenseMap 121 /// because insertions to DenseMap invalidate its iterators. 122 using VectorParts = SmallVector<Value *, 2>; 123 using ScalarParts = SmallVector<SmallVector<Value *, 4>, 2>; 124 std::map<Value *, VectorParts> VectorMapStorage; 125 std::map<Value *, ScalarParts> ScalarMapStorage; 126 127 public: 128 /// Construct an empty map with the given unroll and vectorization factors. 129 VectorizerValueMap(unsigned UF, unsigned VF) : UF(UF), VF(VF) {} 130 131 /// \return True if the map has any vector entry for \p Key. 132 bool hasAnyVectorValue(Value *Key) const { 133 return VectorMapStorage.count(Key); 134 } 135 136 /// \return True if the map has a vector entry for \p Key and \p Part. 137 bool hasVectorValue(Value *Key, unsigned Part) const { 138 assert(Part < UF && "Queried Vector Part is too large."); 139 if (!hasAnyVectorValue(Key)) 140 return false; 141 const VectorParts &Entry = VectorMapStorage.find(Key)->second; 142 assert(Entry.size() == UF && "VectorParts has wrong dimensions."); 143 return Entry[Part] != nullptr; 144 } 145 146 /// \return True if the map has any scalar entry for \p Key. 147 bool hasAnyScalarValue(Value *Key) const { 148 return ScalarMapStorage.count(Key); 149 } 150 151 /// \return True if the map has a scalar entry for \p Key and \p Instance. 152 bool hasScalarValue(Value *Key, const VPIteration &Instance) const { 153 assert(Instance.Part < UF && "Queried Scalar Part is too large."); 154 assert(Instance.Lane < VF && "Queried Scalar Lane is too large."); 155 if (!hasAnyScalarValue(Key)) 156 return false; 157 const ScalarParts &Entry = ScalarMapStorage.find(Key)->second; 158 assert(Entry.size() == UF && "ScalarParts has wrong dimensions."); 159 assert(Entry[Instance.Part].size() == VF && 160 "ScalarParts has wrong dimensions."); 161 return Entry[Instance.Part][Instance.Lane] != nullptr; 162 } 163 164 /// Retrieve the existing vector value that corresponds to \p Key and 165 /// \p Part. 166 Value *getVectorValue(Value *Key, unsigned Part) { 167 assert(hasVectorValue(Key, Part) && "Getting non-existent value."); 168 return VectorMapStorage[Key][Part]; 169 } 170 171 /// Retrieve the existing scalar value that corresponds to \p Key and 172 /// \p Instance. 173 Value *getScalarValue(Value *Key, const VPIteration &Instance) { 174 assert(hasScalarValue(Key, Instance) && "Getting non-existent value."); 175 return ScalarMapStorage[Key][Instance.Part][Instance.Lane]; 176 } 177 178 /// Set a vector value associated with \p Key and \p Part. Assumes such a 179 /// value is not already set. If it is, use resetVectorValue() instead. 180 void setVectorValue(Value *Key, unsigned Part, Value *Vector) { 181 assert(!hasVectorValue(Key, Part) && "Vector value already set for part"); 182 if (!VectorMapStorage.count(Key)) { 183 VectorParts Entry(UF); 184 VectorMapStorage[Key] = Entry; 185 } 186 VectorMapStorage[Key][Part] = Vector; 187 } 188 189 /// Set a scalar value associated with \p Key and \p Instance. Assumes such a 190 /// value is not already set. 191 void setScalarValue(Value *Key, const VPIteration &Instance, Value *Scalar) { 192 assert(!hasScalarValue(Key, Instance) && "Scalar value already set"); 193 if (!ScalarMapStorage.count(Key)) { 194 ScalarParts Entry(UF); 195 // TODO: Consider storing uniform values only per-part, as they occupy 196 // lane 0 only, keeping the other VF-1 redundant entries null. 197 for (unsigned Part = 0; Part < UF; ++Part) 198 Entry[Part].resize(VF, nullptr); 199 ScalarMapStorage[Key] = Entry; 200 } 201 ScalarMapStorage[Key][Instance.Part][Instance.Lane] = Scalar; 202 } 203 204 /// Reset the vector value associated with \p Key for the given \p Part. 205 /// This function can be used to update values that have already been 206 /// vectorized. This is the case for "fix-up" operations including type 207 /// truncation and the second phase of recurrence vectorization. 208 void resetVectorValue(Value *Key, unsigned Part, Value *Vector) { 209 assert(hasVectorValue(Key, Part) && "Vector value not set for part"); 210 VectorMapStorage[Key][Part] = Vector; 211 } 212 213 /// Reset the scalar value associated with \p Key for \p Part and \p Lane. 214 /// This function can be used to update values that have already been 215 /// scalarized. This is the case for "fix-up" operations including scalar phi 216 /// nodes for scalarized and predicated instructions. 217 void resetScalarValue(Value *Key, const VPIteration &Instance, 218 Value *Scalar) { 219 assert(hasScalarValue(Key, Instance) && 220 "Scalar value not set for part and lane"); 221 ScalarMapStorage[Key][Instance.Part][Instance.Lane] = Scalar; 222 } 223 }; 224 225 /// This class is used to enable the VPlan to invoke a method of ILV. This is 226 /// needed until the method is refactored out of ILV and becomes reusable. 227 struct VPCallback { 228 virtual ~VPCallback() {} 229 virtual Value *getOrCreateVectorValues(Value *V, unsigned Part) = 0; 230 virtual Value *getOrCreateScalarValue(Value *V, 231 const VPIteration &Instance) = 0; 232 }; 233 234 /// VPTransformState holds information passed down when "executing" a VPlan, 235 /// needed for generating the output IR. 236 struct VPTransformState { 237 VPTransformState(unsigned VF, unsigned UF, LoopInfo *LI, DominatorTree *DT, 238 IRBuilder<> &Builder, VectorizerValueMap &ValueMap, 239 InnerLoopVectorizer *ILV, VPCallback &Callback) 240 : VF(VF), UF(UF), Instance(), LI(LI), DT(DT), Builder(Builder), 241 ValueMap(ValueMap), ILV(ILV), Callback(Callback) {} 242 243 /// The chosen Vectorization and Unroll Factors of the loop being vectorized. 244 unsigned VF; 245 unsigned UF; 246 247 /// Hold the indices to generate specific scalar instructions. Null indicates 248 /// that all instances are to be generated, using either scalar or vector 249 /// instructions. 250 Optional<VPIteration> Instance; 251 252 struct DataState { 253 /// A type for vectorized values in the new loop. Each value from the 254 /// original loop, when vectorized, is represented by UF vector values in 255 /// the new unrolled loop, where UF is the unroll factor. 256 typedef SmallVector<Value *, 2> PerPartValuesTy; 257 258 DenseMap<VPValue *, PerPartValuesTy> PerPartOutput; 259 } Data; 260 261 /// Get the generated Value for a given VPValue and a given Part. Note that 262 /// as some Defs are still created by ILV and managed in its ValueMap, this 263 /// method will delegate the call to ILV in such cases in order to provide 264 /// callers a consistent API. 265 /// \see set. 266 Value *get(VPValue *Def, unsigned Part) { 267 // If Values have been set for this Def return the one relevant for \p Part. 268 if (Data.PerPartOutput.count(Def)) 269 return Data.PerPartOutput[Def][Part]; 270 // Def is managed by ILV: bring the Values from ValueMap. 271 return Callback.getOrCreateVectorValues(VPValue2Value[Def], Part); 272 } 273 274 /// Get the generated Value for a given VPValue and given Part and Lane. Note 275 /// that as per-lane Defs are still created by ILV and managed in its ValueMap 276 /// this method currently just delegates the call to ILV. 277 Value *get(VPValue *Def, const VPIteration &Instance) { 278 return Callback.getOrCreateScalarValue(VPValue2Value[Def], Instance); 279 } 280 281 /// Set the generated Value for a given VPValue and a given Part. 282 void set(VPValue *Def, Value *V, unsigned Part) { 283 if (!Data.PerPartOutput.count(Def)) { 284 DataState::PerPartValuesTy Entry(UF); 285 Data.PerPartOutput[Def] = Entry; 286 } 287 Data.PerPartOutput[Def][Part] = V; 288 } 289 290 /// Hold state information used when constructing the CFG of the output IR, 291 /// traversing the VPBasicBlocks and generating corresponding IR BasicBlocks. 292 struct CFGState { 293 /// The previous VPBasicBlock visited. Initially set to null. 294 VPBasicBlock *PrevVPBB = nullptr; 295 296 /// The previous IR BasicBlock created or used. Initially set to the new 297 /// header BasicBlock. 298 BasicBlock *PrevBB = nullptr; 299 300 /// The last IR BasicBlock in the output IR. Set to the new latch 301 /// BasicBlock, used for placing the newly created BasicBlocks. 302 BasicBlock *LastBB = nullptr; 303 304 /// A mapping of each VPBasicBlock to the corresponding BasicBlock. In case 305 /// of replication, maps the BasicBlock of the last replica created. 306 SmallDenseMap<VPBasicBlock *, BasicBlock *> VPBB2IRBB; 307 308 /// Vector of VPBasicBlocks whose terminator instruction needs to be fixed 309 /// up at the end of vector code generation. 310 SmallVector<VPBasicBlock *, 8> VPBBsToFix; 311 312 CFGState() = default; 313 } CFG; 314 315 /// Hold a pointer to LoopInfo to register new basic blocks in the loop. 316 LoopInfo *LI; 317 318 /// Hold a pointer to Dominator Tree to register new basic blocks in the loop. 319 DominatorTree *DT; 320 321 /// Hold a reference to the IRBuilder used to generate output IR code. 322 IRBuilder<> &Builder; 323 324 /// Hold a reference to the Value state information used when generating the 325 /// Values of the output IR. 326 VectorizerValueMap &ValueMap; 327 328 /// Hold a reference to a mapping between VPValues in VPlan and original 329 /// Values they correspond to. 330 VPValue2ValueTy VPValue2Value; 331 332 /// Hold the trip count of the scalar loop. 333 Value *TripCount = nullptr; 334 335 /// Hold a pointer to InnerLoopVectorizer to reuse its IR generation methods. 336 InnerLoopVectorizer *ILV; 337 338 VPCallback &Callback; 339 }; 340 341 /// VPBlockBase is the building block of the Hierarchical Control-Flow Graph. 342 /// A VPBlockBase can be either a VPBasicBlock or a VPRegionBlock. 343 class VPBlockBase { 344 friend class VPBlockUtils; 345 346 private: 347 const unsigned char SubclassID; ///< Subclass identifier (for isa/dyn_cast). 348 349 /// An optional name for the block. 350 std::string Name; 351 352 /// The immediate VPRegionBlock which this VPBlockBase belongs to, or null if 353 /// it is a topmost VPBlockBase. 354 VPRegionBlock *Parent = nullptr; 355 356 /// List of predecessor blocks. 357 SmallVector<VPBlockBase *, 1> Predecessors; 358 359 /// List of successor blocks. 360 SmallVector<VPBlockBase *, 1> Successors; 361 362 /// Successor selector, null for zero or single successor blocks. 363 VPValue *CondBit = nullptr; 364 365 /// Current block predicate - null if the block does not need a predicate. 366 VPValue *Predicate = nullptr; 367 368 /// VPlan containing the block. Can only be set on the entry block of the 369 /// plan. 370 VPlan *Plan = nullptr; 371 372 /// Add \p Successor as the last successor to this block. 373 void appendSuccessor(VPBlockBase *Successor) { 374 assert(Successor && "Cannot add nullptr successor!"); 375 Successors.push_back(Successor); 376 } 377 378 /// Add \p Predecessor as the last predecessor to this block. 379 void appendPredecessor(VPBlockBase *Predecessor) { 380 assert(Predecessor && "Cannot add nullptr predecessor!"); 381 Predecessors.push_back(Predecessor); 382 } 383 384 /// Remove \p Predecessor from the predecessors of this block. 385 void removePredecessor(VPBlockBase *Predecessor) { 386 auto Pos = std::find(Predecessors.begin(), Predecessors.end(), Predecessor); 387 assert(Pos && "Predecessor does not exist"); 388 Predecessors.erase(Pos); 389 } 390 391 /// Remove \p Successor from the successors of this block. 392 void removeSuccessor(VPBlockBase *Successor) { 393 auto Pos = std::find(Successors.begin(), Successors.end(), Successor); 394 assert(Pos && "Successor does not exist"); 395 Successors.erase(Pos); 396 } 397 398 protected: 399 VPBlockBase(const unsigned char SC, const std::string &N) 400 : SubclassID(SC), Name(N) {} 401 402 public: 403 /// An enumeration for keeping track of the concrete subclass of VPBlockBase 404 /// that are actually instantiated. Values of this enumeration are kept in the 405 /// SubclassID field of the VPBlockBase objects. They are used for concrete 406 /// type identification. 407 using VPBlockTy = enum { VPBasicBlockSC, VPRegionBlockSC }; 408 409 using VPBlocksTy = SmallVectorImpl<VPBlockBase *>; 410 411 virtual ~VPBlockBase() = default; 412 413 const std::string &getName() const { return Name; } 414 415 void setName(const Twine &newName) { Name = newName.str(); } 416 417 /// \return an ID for the concrete type of this object. 418 /// This is used to implement the classof checks. This should not be used 419 /// for any other purpose, as the values may change as LLVM evolves. 420 unsigned getVPBlockID() const { return SubclassID; } 421 422 VPRegionBlock *getParent() { return Parent; } 423 const VPRegionBlock *getParent() const { return Parent; } 424 425 /// \return A pointer to the plan containing the current block. 426 VPlan *getPlan(); 427 const VPlan *getPlan() const; 428 429 /// Sets the pointer of the plan containing the block. The block must be the 430 /// entry block into the VPlan. 431 void setPlan(VPlan *ParentPlan); 432 433 void setParent(VPRegionBlock *P) { Parent = P; } 434 435 /// \return the VPBasicBlock that is the entry of this VPBlockBase, 436 /// recursively, if the latter is a VPRegionBlock. Otherwise, if this 437 /// VPBlockBase is a VPBasicBlock, it is returned. 438 const VPBasicBlock *getEntryBasicBlock() const; 439 VPBasicBlock *getEntryBasicBlock(); 440 441 /// \return the VPBasicBlock that is the exit 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 *getExitBasicBlock() const; 445 VPBasicBlock *getExitBasicBlock(); 446 447 const VPBlocksTy &getSuccessors() const { return Successors; } 448 VPBlocksTy &getSuccessors() { return Successors; } 449 450 const VPBlocksTy &getPredecessors() const { return Predecessors; } 451 VPBlocksTy &getPredecessors() { return Predecessors; } 452 453 /// \return the successor of this VPBlockBase if it has a single successor. 454 /// Otherwise return a null pointer. 455 VPBlockBase *getSingleSuccessor() const { 456 return (Successors.size() == 1 ? *Successors.begin() : nullptr); 457 } 458 459 /// \return the predecessor of this VPBlockBase if it has a single 460 /// predecessor. Otherwise return a null pointer. 461 VPBlockBase *getSinglePredecessor() const { 462 return (Predecessors.size() == 1 ? *Predecessors.begin() : nullptr); 463 } 464 465 size_t getNumSuccessors() const { return Successors.size(); } 466 size_t getNumPredecessors() const { return Predecessors.size(); } 467 468 /// An Enclosing Block of a block B is any block containing B, including B 469 /// itself. \return the closest enclosing block starting from "this", which 470 /// has successors. \return the root enclosing block if all enclosing blocks 471 /// have no successors. 472 VPBlockBase *getEnclosingBlockWithSuccessors(); 473 474 /// \return the closest enclosing block starting from "this", which has 475 /// predecessors. \return the root enclosing block if all enclosing blocks 476 /// have no predecessors. 477 VPBlockBase *getEnclosingBlockWithPredecessors(); 478 479 /// \return the successors either attached directly to this VPBlockBase or, if 480 /// this VPBlockBase is the exit block of a VPRegionBlock and has no 481 /// successors of its own, search recursively for the first enclosing 482 /// VPRegionBlock that has successors and return them. If no such 483 /// VPRegionBlock exists, return the (empty) successors of the topmost 484 /// VPBlockBase reached. 485 const VPBlocksTy &getHierarchicalSuccessors() { 486 return getEnclosingBlockWithSuccessors()->getSuccessors(); 487 } 488 489 /// \return the hierarchical successor of this VPBlockBase if it has a single 490 /// hierarchical successor. Otherwise return a null pointer. 491 VPBlockBase *getSingleHierarchicalSuccessor() { 492 return getEnclosingBlockWithSuccessors()->getSingleSuccessor(); 493 } 494 495 /// \return the predecessors either attached directly to this VPBlockBase or, 496 /// if this VPBlockBase is the entry block of a VPRegionBlock and has no 497 /// predecessors of its own, search recursively for the first enclosing 498 /// VPRegionBlock that has predecessors and return them. If no such 499 /// VPRegionBlock exists, return the (empty) predecessors of the topmost 500 /// VPBlockBase reached. 501 const VPBlocksTy &getHierarchicalPredecessors() { 502 return getEnclosingBlockWithPredecessors()->getPredecessors(); 503 } 504 505 /// \return the hierarchical predecessor of this VPBlockBase if it has a 506 /// single hierarchical predecessor. Otherwise return a null pointer. 507 VPBlockBase *getSingleHierarchicalPredecessor() { 508 return getEnclosingBlockWithPredecessors()->getSinglePredecessor(); 509 } 510 511 /// \return the condition bit selecting the successor. 512 VPValue *getCondBit() { return CondBit; } 513 514 const VPValue *getCondBit() const { return CondBit; } 515 516 void setCondBit(VPValue *CV) { CondBit = CV; } 517 518 VPValue *getPredicate() { return Predicate; } 519 520 const VPValue *getPredicate() const { return Predicate; } 521 522 void setPredicate(VPValue *Pred) { Predicate = Pred; } 523 524 /// Set a given VPBlockBase \p Successor as the single successor of this 525 /// VPBlockBase. This VPBlockBase is not added as predecessor of \p Successor. 526 /// This VPBlockBase must have no successors. 527 void setOneSuccessor(VPBlockBase *Successor) { 528 assert(Successors.empty() && "Setting one successor when others exist."); 529 appendSuccessor(Successor); 530 } 531 532 /// Set two given VPBlockBases \p IfTrue and \p IfFalse to be the two 533 /// successors of this VPBlockBase. \p Condition is set as the successor 534 /// selector. This VPBlockBase is not added as predecessor of \p IfTrue or \p 535 /// IfFalse. This VPBlockBase must have no successors. 536 void setTwoSuccessors(VPBlockBase *IfTrue, VPBlockBase *IfFalse, 537 VPValue *Condition) { 538 assert(Successors.empty() && "Setting two successors when others exist."); 539 assert(Condition && "Setting two successors without condition!"); 540 CondBit = Condition; 541 appendSuccessor(IfTrue); 542 appendSuccessor(IfFalse); 543 } 544 545 /// Set each VPBasicBlock in \p NewPreds as predecessor of this VPBlockBase. 546 /// This VPBlockBase must have no predecessors. This VPBlockBase is not added 547 /// as successor of any VPBasicBlock in \p NewPreds. 548 void setPredecessors(ArrayRef<VPBlockBase *> NewPreds) { 549 assert(Predecessors.empty() && "Block predecessors already set."); 550 for (auto *Pred : NewPreds) 551 appendPredecessor(Pred); 552 } 553 554 /// Remove all the predecessor of this block. 555 void clearPredecessors() { Predecessors.clear(); } 556 557 /// Remove all the successors of this block and set to null its condition bit 558 void clearSuccessors() { 559 Successors.clear(); 560 CondBit = nullptr; 561 } 562 563 /// The method which generates the output IR that correspond to this 564 /// VPBlockBase, thereby "executing" the VPlan. 565 virtual void execute(struct VPTransformState *State) = 0; 566 567 /// Delete all blocks reachable from a given VPBlockBase, inclusive. 568 static void deleteCFG(VPBlockBase *Entry); 569 570 void printAsOperand(raw_ostream &OS, bool PrintType) const { 571 OS << getName(); 572 } 573 574 void print(raw_ostream &OS) const { 575 // TODO: Only printing VPBB name for now since we only have dot printing 576 // support for VPInstructions/Recipes. 577 printAsOperand(OS, false); 578 } 579 580 /// Return true if it is legal to hoist instructions into this block. 581 bool isLegalToHoistInto() { 582 // There are currently no constraints that prevent an instruction to be 583 // hoisted into a VPBlockBase. 584 return true; 585 } 586 }; 587 588 /// VPRecipeBase is a base class modeling a sequence of one or more output IR 589 /// instructions. 590 class VPRecipeBase : public ilist_node_with_parent<VPRecipeBase, VPBasicBlock> { 591 friend VPBasicBlock; 592 friend class VPBlockUtils; 593 594 private: 595 const unsigned char SubclassID; ///< Subclass identifier (for isa/dyn_cast). 596 597 /// Each VPRecipe belongs to a single VPBasicBlock. 598 VPBasicBlock *Parent = nullptr; 599 600 public: 601 /// An enumeration for keeping track of the concrete subclass of VPRecipeBase 602 /// that is actually instantiated. Values of this enumeration are kept in the 603 /// SubclassID field of the VPRecipeBase objects. They are used for concrete 604 /// type identification. 605 using VPRecipeTy = enum { 606 VPBlendSC, 607 VPBranchOnMaskSC, 608 VPInstructionSC, 609 VPInterleaveSC, 610 VPPredInstPHISC, 611 VPReplicateSC, 612 VPWidenGEPSC, 613 VPWidenIntOrFpInductionSC, 614 VPWidenMemoryInstructionSC, 615 VPWidenPHISC, 616 VPWidenSC, 617 }; 618 619 VPRecipeBase(const unsigned char SC) : SubclassID(SC) {} 620 virtual ~VPRecipeBase() = default; 621 622 /// \return an ID for the concrete type of this object. 623 /// This is used to implement the classof checks. This should not be used 624 /// for any other purpose, as the values may change as LLVM evolves. 625 unsigned getVPRecipeID() const { return SubclassID; } 626 627 /// \return the VPBasicBlock which this VPRecipe belongs to. 628 VPBasicBlock *getParent() { return Parent; } 629 const VPBasicBlock *getParent() const { return Parent; } 630 631 /// The method which generates the output IR instructions that correspond to 632 /// this VPRecipe, thereby "executing" the VPlan. 633 virtual void execute(struct VPTransformState &State) = 0; 634 635 /// Each recipe prints itself. 636 void print(raw_ostream &O, const Twine &Indent); 637 virtual void print(raw_ostream &O, const Twine &Indent, 638 VPSlotTracker &SlotTracker) const = 0; 639 640 /// Insert an unlinked recipe into a basic block immediately before 641 /// the specified recipe. 642 void insertBefore(VPRecipeBase *InsertPos); 643 644 /// Insert an unlinked Recipe into a basic block immediately after 645 /// the specified Recipe. 646 void insertAfter(VPRecipeBase *InsertPos); 647 648 /// Unlink this recipe from its current VPBasicBlock and insert it into 649 /// the VPBasicBlock that MovePos lives in, right after MovePos. 650 void moveAfter(VPRecipeBase *MovePos); 651 652 /// This method unlinks 'this' from the containing basic block, but does not 653 /// delete it. 654 void removeFromParent(); 655 656 /// This method unlinks 'this' from the containing basic block and deletes it. 657 /// 658 /// \returns an iterator pointing to the element after the erased one 659 iplist<VPRecipeBase>::iterator eraseFromParent(); 660 }; 661 662 /// This is a concrete Recipe that models a single VPlan-level instruction. 663 /// While as any Recipe it may generate a sequence of IR instructions when 664 /// executed, these instructions would always form a single-def expression as 665 /// the VPInstruction is also a single def-use vertex. 666 class VPInstruction : public VPUser, public VPRecipeBase { 667 friend class VPlanSlp; 668 669 public: 670 /// VPlan opcodes, extending LLVM IR with idiomatics instructions. 671 enum { 672 Not = Instruction::OtherOpsEnd + 1, 673 ICmpULE, 674 SLPLoad, 675 SLPStore, 676 }; 677 678 private: 679 typedef unsigned char OpcodeTy; 680 OpcodeTy Opcode; 681 682 /// Utility method serving execute(): generates a single instance of the 683 /// modeled instruction. 684 void generateInstruction(VPTransformState &State, unsigned Part); 685 686 protected: 687 Instruction *getUnderlyingInstr() { 688 return cast_or_null<Instruction>(getUnderlyingValue()); 689 } 690 691 void setUnderlyingInstr(Instruction *I) { setUnderlyingValue(I); } 692 693 public: 694 VPInstruction(unsigned Opcode, ArrayRef<VPValue *> Operands) 695 : VPUser(VPValue::VPInstructionSC, Operands), 696 VPRecipeBase(VPRecipeBase::VPInstructionSC), Opcode(Opcode) {} 697 698 VPInstruction(unsigned Opcode, std::initializer_list<VPValue *> Operands) 699 : VPInstruction(Opcode, ArrayRef<VPValue *>(Operands)) {} 700 701 /// Method to support type inquiry through isa, cast, and dyn_cast. 702 static inline bool classof(const VPValue *V) { 703 return V->getVPValueID() == VPValue::VPInstructionSC; 704 } 705 706 VPInstruction *clone() const { 707 SmallVector<VPValue *, 2> Operands(operands()); 708 return new VPInstruction(Opcode, Operands); 709 } 710 711 /// Method to support type inquiry through isa, cast, and dyn_cast. 712 static inline bool classof(const VPRecipeBase *R) { 713 return R->getVPRecipeID() == VPRecipeBase::VPInstructionSC; 714 } 715 716 unsigned getOpcode() const { return Opcode; } 717 718 /// Generate the instruction. 719 /// TODO: We currently execute only per-part unless a specific instance is 720 /// provided. 721 void execute(VPTransformState &State) override; 722 723 /// Print the Recipe. 724 void print(raw_ostream &O, const Twine &Indent, 725 VPSlotTracker &SlotTracker) const override; 726 727 /// Print the VPInstruction. 728 void print(raw_ostream &O) const; 729 void print(raw_ostream &O, VPSlotTracker &SlotTracker) const; 730 731 /// Return true if this instruction may modify memory. 732 bool mayWriteToMemory() const { 733 // TODO: we can use attributes of the called function to rule out memory 734 // modifications. 735 return Opcode == Instruction::Store || Opcode == Instruction::Call || 736 Opcode == Instruction::Invoke || Opcode == SLPStore; 737 } 738 739 bool hasResult() const { 740 // CallInst may or may not have a result, depending on the called function. 741 // Conservatively return calls have results for now. 742 switch (getOpcode()) { 743 case Instruction::Ret: 744 case Instruction::Br: 745 case Instruction::Store: 746 case Instruction::Switch: 747 case Instruction::IndirectBr: 748 case Instruction::Resume: 749 case Instruction::CatchRet: 750 case Instruction::Unreachable: 751 case Instruction::Fence: 752 case Instruction::AtomicRMW: 753 return false; 754 default: 755 return true; 756 } 757 } 758 }; 759 760 /// VPWidenRecipe is a recipe for producing a copy of vector type its 761 /// ingredient. This recipe covers most of the traditional vectorization cases 762 /// where each ingredient transforms into a vectorized version of itself. 763 class VPWidenRecipe : public VPRecipeBase { 764 private: 765 /// Hold the instruction to be widened. 766 Instruction &Ingredient; 767 768 public: 769 VPWidenRecipe(Instruction &I) : VPRecipeBase(VPWidenSC), Ingredient(I) {} 770 771 ~VPWidenRecipe() override = default; 772 773 /// Method to support type inquiry through isa, cast, and dyn_cast. 774 static inline bool classof(const VPRecipeBase *V) { 775 return V->getVPRecipeID() == VPRecipeBase::VPWidenSC; 776 } 777 778 /// Produce widened copies of all Ingredients. 779 void execute(VPTransformState &State) override; 780 781 /// Print the recipe. 782 void print(raw_ostream &O, const Twine &Indent, 783 VPSlotTracker &SlotTracker) const override; 784 }; 785 786 /// A recipe for handling GEP instructions. 787 class VPWidenGEPRecipe : public VPRecipeBase { 788 private: 789 GetElementPtrInst *GEP; 790 bool IsPtrLoopInvariant; 791 SmallBitVector IsIndexLoopInvariant; 792 793 public: 794 VPWidenGEPRecipe(GetElementPtrInst *GEP, Loop *OrigLoop) 795 : VPRecipeBase(VPWidenGEPSC), GEP(GEP), 796 IsIndexLoopInvariant(GEP->getNumIndices(), false) { 797 IsPtrLoopInvariant = OrigLoop->isLoopInvariant(GEP->getPointerOperand()); 798 for (auto Index : enumerate(GEP->indices())) 799 IsIndexLoopInvariant[Index.index()] = 800 OrigLoop->isLoopInvariant(Index.value().get()); 801 } 802 ~VPWidenGEPRecipe() override = default; 803 804 /// Method to support type inquiry through isa, cast, and dyn_cast. 805 static inline bool classof(const VPRecipeBase *V) { 806 return V->getVPRecipeID() == VPRecipeBase::VPWidenGEPSC; 807 } 808 809 /// Generate the gep nodes. 810 void execute(VPTransformState &State) override; 811 812 /// Print the recipe. 813 void print(raw_ostream &O, const Twine &Indent, 814 VPSlotTracker &SlotTracker) const override; 815 }; 816 817 /// A recipe for handling phi nodes of integer and floating-point inductions, 818 /// producing their vector and scalar values. 819 class VPWidenIntOrFpInductionRecipe : public VPRecipeBase { 820 private: 821 PHINode *IV; 822 TruncInst *Trunc; 823 824 public: 825 VPWidenIntOrFpInductionRecipe(PHINode *IV, TruncInst *Trunc = nullptr) 826 : VPRecipeBase(VPWidenIntOrFpInductionSC), IV(IV), Trunc(Trunc) {} 827 ~VPWidenIntOrFpInductionRecipe() override = default; 828 829 /// Method to support type inquiry through isa, cast, and dyn_cast. 830 static inline bool classof(const VPRecipeBase *V) { 831 return V->getVPRecipeID() == VPRecipeBase::VPWidenIntOrFpInductionSC; 832 } 833 834 /// Generate the vectorized and scalarized versions of the phi node as 835 /// needed by their users. 836 void execute(VPTransformState &State) override; 837 838 /// Print the recipe. 839 void print(raw_ostream &O, const Twine &Indent, 840 VPSlotTracker &SlotTracker) const override; 841 }; 842 843 /// A recipe for handling all phi nodes except for integer and FP inductions. 844 class VPWidenPHIRecipe : public VPRecipeBase { 845 private: 846 PHINode *Phi; 847 848 public: 849 VPWidenPHIRecipe(PHINode *Phi) : VPRecipeBase(VPWidenPHISC), Phi(Phi) {} 850 ~VPWidenPHIRecipe() override = default; 851 852 /// Method to support type inquiry through isa, cast, and dyn_cast. 853 static inline bool classof(const VPRecipeBase *V) { 854 return V->getVPRecipeID() == VPRecipeBase::VPWidenPHISC; 855 } 856 857 /// Generate the phi/select nodes. 858 void execute(VPTransformState &State) override; 859 860 /// Print the recipe. 861 void print(raw_ostream &O, const Twine &Indent, 862 VPSlotTracker &SlotTracker) const override; 863 }; 864 865 /// A recipe for vectorizing a phi-node as a sequence of mask-based select 866 /// instructions. 867 class VPBlendRecipe : public VPRecipeBase { 868 private: 869 PHINode *Phi; 870 871 /// The blend operation is a User of a mask, if not null. 872 std::unique_ptr<VPUser> User; 873 874 public: 875 VPBlendRecipe(PHINode *Phi, ArrayRef<VPValue *> Masks) 876 : VPRecipeBase(VPBlendSC), Phi(Phi) { 877 assert((Phi->getNumIncomingValues() == 1 || 878 Phi->getNumIncomingValues() == Masks.size()) && 879 "Expected the same number of incoming values and masks"); 880 if (!Masks.empty()) 881 User.reset(new VPUser(Masks)); 882 } 883 884 /// Method to support type inquiry through isa, cast, and dyn_cast. 885 static inline bool classof(const VPRecipeBase *V) { 886 return V->getVPRecipeID() == VPRecipeBase::VPBlendSC; 887 } 888 889 /// Generate the phi/select nodes. 890 void execute(VPTransformState &State) override; 891 892 /// Print the recipe. 893 void print(raw_ostream &O, const Twine &Indent, 894 VPSlotTracker &SlotTracker) const override; 895 }; 896 897 /// VPInterleaveRecipe is a recipe for transforming an interleave group of load 898 /// or stores into one wide load/store and shuffles. 899 class VPInterleaveRecipe : public VPRecipeBase { 900 private: 901 const InterleaveGroup<Instruction> *IG; 902 VPUser User; 903 904 public: 905 VPInterleaveRecipe(const InterleaveGroup<Instruction> *IG, VPValue *Addr, 906 VPValue *Mask) 907 : VPRecipeBase(VPInterleaveSC), IG(IG), User({Addr}) { 908 if (Mask) 909 User.addOperand(Mask); 910 } 911 ~VPInterleaveRecipe() override = default; 912 913 /// Method to support type inquiry through isa, cast, and dyn_cast. 914 static inline bool classof(const VPRecipeBase *V) { 915 return V->getVPRecipeID() == VPRecipeBase::VPInterleaveSC; 916 } 917 918 /// Return the address accessed by this recipe. 919 VPValue *getAddr() const { 920 return User.getOperand(0); // Address is the 1st, mandatory operand. 921 } 922 923 /// Return the mask used by this recipe. Note that a full mask is represented 924 /// by a nullptr. 925 VPValue *getMask() const { 926 // Mask is optional and therefore the last, currently 2nd operand. 927 return User.getNumOperands() == 2 ? User.getOperand(1) : nullptr; 928 } 929 930 /// Generate the wide load or store, and shuffles. 931 void execute(VPTransformState &State) override; 932 933 /// Print the recipe. 934 void print(raw_ostream &O, const Twine &Indent, 935 VPSlotTracker &SlotTracker) const override; 936 937 const InterleaveGroup<Instruction> *getInterleaveGroup() { return IG; } 938 }; 939 940 /// VPReplicateRecipe replicates a given instruction producing multiple scalar 941 /// copies of the original scalar type, one per lane, instead of producing a 942 /// single copy of widened type for all lanes. If the instruction is known to be 943 /// uniform only one copy, per lane zero, will be generated. 944 class VPReplicateRecipe : public VPRecipeBase { 945 private: 946 /// The instruction being replicated. 947 Instruction *Ingredient; 948 949 /// Indicator if only a single replica per lane is needed. 950 bool IsUniform; 951 952 /// Indicator if the replicas are also predicated. 953 bool IsPredicated; 954 955 /// Indicator if the scalar values should also be packed into a vector. 956 bool AlsoPack; 957 958 public: 959 VPReplicateRecipe(Instruction *I, bool IsUniform, bool IsPredicated = false) 960 : VPRecipeBase(VPReplicateSC), Ingredient(I), IsUniform(IsUniform), 961 IsPredicated(IsPredicated) { 962 // Retain the previous behavior of predicateInstructions(), where an 963 // insert-element of a predicated instruction got hoisted into the 964 // predicated basic block iff it was its only user. This is achieved by 965 // having predicated instructions also pack their values into a vector by 966 // default unless they have a replicated user which uses their scalar value. 967 AlsoPack = IsPredicated && !I->use_empty(); 968 } 969 970 ~VPReplicateRecipe() override = default; 971 972 /// Method to support type inquiry through isa, cast, and dyn_cast. 973 static inline bool classof(const VPRecipeBase *V) { 974 return V->getVPRecipeID() == VPRecipeBase::VPReplicateSC; 975 } 976 977 /// Generate replicas of the desired Ingredient. Replicas will be generated 978 /// for all parts and lanes unless a specific part and lane are specified in 979 /// the \p State. 980 void execute(VPTransformState &State) override; 981 982 void setAlsoPack(bool Pack) { AlsoPack = Pack; } 983 984 /// Print the recipe. 985 void print(raw_ostream &O, const Twine &Indent, 986 VPSlotTracker &SlotTracker) const override; 987 }; 988 989 /// A recipe for generating conditional branches on the bits of a mask. 990 class VPBranchOnMaskRecipe : public VPRecipeBase { 991 private: 992 std::unique_ptr<VPUser> User; 993 994 public: 995 VPBranchOnMaskRecipe(VPValue *BlockInMask) : VPRecipeBase(VPBranchOnMaskSC) { 996 if (BlockInMask) // nullptr means all-one mask. 997 User.reset(new VPUser({BlockInMask})); 998 } 999 1000 /// Method to support type inquiry through isa, cast, and dyn_cast. 1001 static inline bool classof(const VPRecipeBase *V) { 1002 return V->getVPRecipeID() == VPRecipeBase::VPBranchOnMaskSC; 1003 } 1004 1005 /// Generate the extraction of the appropriate bit from the block mask and the 1006 /// conditional branch. 1007 void execute(VPTransformState &State) override; 1008 1009 /// Print the recipe. 1010 void print(raw_ostream &O, const Twine &Indent, 1011 VPSlotTracker &SlotTracker) const override { 1012 O << " +\n" << Indent << "\"BRANCH-ON-MASK "; 1013 if (User) 1014 User->getOperand(0)->print(O, SlotTracker); 1015 else 1016 O << " All-One"; 1017 O << "\\l\""; 1018 } 1019 }; 1020 1021 /// VPPredInstPHIRecipe is a recipe for generating the phi nodes needed when 1022 /// control converges back from a Branch-on-Mask. The phi nodes are needed in 1023 /// order to merge values that are set under such a branch and feed their uses. 1024 /// The phi nodes can be scalar or vector depending on the users of the value. 1025 /// This recipe works in concert with VPBranchOnMaskRecipe. 1026 class VPPredInstPHIRecipe : public VPRecipeBase { 1027 private: 1028 Instruction *PredInst; 1029 1030 public: 1031 /// Construct a VPPredInstPHIRecipe given \p PredInst whose value needs a phi 1032 /// nodes after merging back from a Branch-on-Mask. 1033 VPPredInstPHIRecipe(Instruction *PredInst) 1034 : VPRecipeBase(VPPredInstPHISC), PredInst(PredInst) {} 1035 ~VPPredInstPHIRecipe() override = default; 1036 1037 /// Method to support type inquiry through isa, cast, and dyn_cast. 1038 static inline bool classof(const VPRecipeBase *V) { 1039 return V->getVPRecipeID() == VPRecipeBase::VPPredInstPHISC; 1040 } 1041 1042 /// Generates phi nodes for live-outs as needed to retain SSA form. 1043 void execute(VPTransformState &State) override; 1044 1045 /// Print the recipe. 1046 void print(raw_ostream &O, const Twine &Indent, 1047 VPSlotTracker &SlotTracker) const override; 1048 }; 1049 1050 /// A Recipe for widening load/store operations. 1051 /// The recipe uses the following VPValues: 1052 /// - For load: Address, optional mask 1053 /// - For store: Address, stored value, optional mask 1054 /// TODO: We currently execute only per-part unless a specific instance is 1055 /// provided. 1056 class VPWidenMemoryInstructionRecipe : public VPRecipeBase { 1057 private: 1058 Instruction &Instr; 1059 VPUser User; 1060 1061 void setMask(VPValue *Mask) { 1062 if (!Mask) 1063 return; 1064 User.addOperand(Mask); 1065 } 1066 1067 bool isMasked() const { 1068 return (isa<LoadInst>(Instr) && User.getNumOperands() == 2) || 1069 (isa<StoreInst>(Instr) && User.getNumOperands() == 3); 1070 } 1071 1072 public: 1073 VPWidenMemoryInstructionRecipe(LoadInst &Load, VPValue *Addr, VPValue *Mask) 1074 : VPRecipeBase(VPWidenMemoryInstructionSC), Instr(Load), User({Addr}) { 1075 setMask(Mask); 1076 } 1077 1078 VPWidenMemoryInstructionRecipe(StoreInst &Store, VPValue *Addr, 1079 VPValue *StoredValue, VPValue *Mask) 1080 : VPRecipeBase(VPWidenMemoryInstructionSC), Instr(Store), 1081 User({Addr, StoredValue}) { 1082 setMask(Mask); 1083 } 1084 1085 /// Method to support type inquiry through isa, cast, and dyn_cast. 1086 static inline bool classof(const VPRecipeBase *V) { 1087 return V->getVPRecipeID() == VPRecipeBase::VPWidenMemoryInstructionSC; 1088 } 1089 1090 /// Return the address accessed by this recipe. 1091 VPValue *getAddr() const { 1092 return User.getOperand(0); // Address is the 1st, mandatory operand. 1093 } 1094 1095 /// Return the mask used by this recipe. Note that a full mask is represented 1096 /// by a nullptr. 1097 VPValue *getMask() const { 1098 // Mask is optional and therefore the last operand. 1099 return isMasked() ? User.getOperand(User.getNumOperands() - 1) : nullptr; 1100 } 1101 1102 /// Return the address accessed by this recipe. 1103 VPValue *getStoredValue() const { 1104 assert(isa<StoreInst>(Instr) && 1105 "Stored value only available for store instructions"); 1106 return User.getOperand(1); // Stored value is the 2nd, mandatory operand. 1107 } 1108 1109 /// Generate the wide load/store. 1110 void execute(VPTransformState &State) override; 1111 1112 /// Print the recipe. 1113 void print(raw_ostream &O, const Twine &Indent, 1114 VPSlotTracker &SlotTracker) const override; 1115 }; 1116 1117 /// VPBasicBlock serves as the leaf of the Hierarchical Control-Flow Graph. It 1118 /// holds a sequence of zero or more VPRecipe's each representing a sequence of 1119 /// output IR instructions. 1120 class VPBasicBlock : public VPBlockBase { 1121 public: 1122 using RecipeListTy = iplist<VPRecipeBase>; 1123 1124 private: 1125 /// The VPRecipes held in the order of output instructions to generate. 1126 RecipeListTy Recipes; 1127 1128 public: 1129 VPBasicBlock(const Twine &Name = "", VPRecipeBase *Recipe = nullptr) 1130 : VPBlockBase(VPBasicBlockSC, Name.str()) { 1131 if (Recipe) 1132 appendRecipe(Recipe); 1133 } 1134 1135 ~VPBasicBlock() override { Recipes.clear(); } 1136 1137 /// Instruction iterators... 1138 using iterator = RecipeListTy::iterator; 1139 using const_iterator = RecipeListTy::const_iterator; 1140 using reverse_iterator = RecipeListTy::reverse_iterator; 1141 using const_reverse_iterator = RecipeListTy::const_reverse_iterator; 1142 1143 //===--------------------------------------------------------------------===// 1144 /// Recipe iterator methods 1145 /// 1146 inline iterator begin() { return Recipes.begin(); } 1147 inline const_iterator begin() const { return Recipes.begin(); } 1148 inline iterator end() { return Recipes.end(); } 1149 inline const_iterator end() const { return Recipes.end(); } 1150 1151 inline reverse_iterator rbegin() { return Recipes.rbegin(); } 1152 inline const_reverse_iterator rbegin() const { return Recipes.rbegin(); } 1153 inline reverse_iterator rend() { return Recipes.rend(); } 1154 inline const_reverse_iterator rend() const { return Recipes.rend(); } 1155 1156 inline size_t size() const { return Recipes.size(); } 1157 inline bool empty() const { return Recipes.empty(); } 1158 inline const VPRecipeBase &front() const { return Recipes.front(); } 1159 inline VPRecipeBase &front() { return Recipes.front(); } 1160 inline const VPRecipeBase &back() const { return Recipes.back(); } 1161 inline VPRecipeBase &back() { return Recipes.back(); } 1162 1163 /// Returns a reference to the list of recipes. 1164 RecipeListTy &getRecipeList() { return Recipes; } 1165 1166 /// Returns a pointer to a member of the recipe list. 1167 static RecipeListTy VPBasicBlock::*getSublistAccess(VPRecipeBase *) { 1168 return &VPBasicBlock::Recipes; 1169 } 1170 1171 /// Method to support type inquiry through isa, cast, and dyn_cast. 1172 static inline bool classof(const VPBlockBase *V) { 1173 return V->getVPBlockID() == VPBlockBase::VPBasicBlockSC; 1174 } 1175 1176 void insert(VPRecipeBase *Recipe, iterator InsertPt) { 1177 assert(Recipe && "No recipe to append."); 1178 assert(!Recipe->Parent && "Recipe already in VPlan"); 1179 Recipe->Parent = this; 1180 Recipes.insert(InsertPt, Recipe); 1181 } 1182 1183 /// Augment the existing recipes of a VPBasicBlock with an additional 1184 /// \p Recipe as the last recipe. 1185 void appendRecipe(VPRecipeBase *Recipe) { insert(Recipe, end()); } 1186 1187 /// The method which generates the output IR instructions that correspond to 1188 /// this VPBasicBlock, thereby "executing" the VPlan. 1189 void execute(struct VPTransformState *State) override; 1190 1191 private: 1192 /// Create an IR BasicBlock to hold the output instructions generated by this 1193 /// VPBasicBlock, and return it. Update the CFGState accordingly. 1194 BasicBlock *createEmptyBasicBlock(VPTransformState::CFGState &CFG); 1195 }; 1196 1197 /// VPRegionBlock represents a collection of VPBasicBlocks and VPRegionBlocks 1198 /// which form a Single-Entry-Single-Exit subgraph of the output IR CFG. 1199 /// A VPRegionBlock may indicate that its contents are to be replicated several 1200 /// times. This is designed to support predicated scalarization, in which a 1201 /// scalar if-then code structure needs to be generated VF * UF times. Having 1202 /// this replication indicator helps to keep a single model for multiple 1203 /// candidate VF's. The actual replication takes place only once the desired VF 1204 /// and UF have been determined. 1205 class VPRegionBlock : public VPBlockBase { 1206 private: 1207 /// Hold the Single Entry of the SESE region modelled by the VPRegionBlock. 1208 VPBlockBase *Entry; 1209 1210 /// Hold the Single Exit of the SESE region modelled by the VPRegionBlock. 1211 VPBlockBase *Exit; 1212 1213 /// An indicator whether this region is to generate multiple replicated 1214 /// instances of output IR corresponding to its VPBlockBases. 1215 bool IsReplicator; 1216 1217 public: 1218 VPRegionBlock(VPBlockBase *Entry, VPBlockBase *Exit, 1219 const std::string &Name = "", bool IsReplicator = false) 1220 : VPBlockBase(VPRegionBlockSC, Name), Entry(Entry), Exit(Exit), 1221 IsReplicator(IsReplicator) { 1222 assert(Entry->getPredecessors().empty() && "Entry block has predecessors."); 1223 assert(Exit->getSuccessors().empty() && "Exit block has successors."); 1224 Entry->setParent(this); 1225 Exit->setParent(this); 1226 } 1227 VPRegionBlock(const std::string &Name = "", bool IsReplicator = false) 1228 : VPBlockBase(VPRegionBlockSC, Name), Entry(nullptr), Exit(nullptr), 1229 IsReplicator(IsReplicator) {} 1230 1231 ~VPRegionBlock() override { 1232 if (Entry) 1233 deleteCFG(Entry); 1234 } 1235 1236 /// Method to support type inquiry through isa, cast, and dyn_cast. 1237 static inline bool classof(const VPBlockBase *V) { 1238 return V->getVPBlockID() == VPBlockBase::VPRegionBlockSC; 1239 } 1240 1241 const VPBlockBase *getEntry() const { return Entry; } 1242 VPBlockBase *getEntry() { return Entry; } 1243 1244 /// Set \p EntryBlock as the entry VPBlockBase of this VPRegionBlock. \p 1245 /// EntryBlock must have no predecessors. 1246 void setEntry(VPBlockBase *EntryBlock) { 1247 assert(EntryBlock->getPredecessors().empty() && 1248 "Entry block cannot have predecessors."); 1249 Entry = EntryBlock; 1250 EntryBlock->setParent(this); 1251 } 1252 1253 // FIXME: DominatorTreeBase is doing 'A->getParent()->front()'. 'front' is a 1254 // specific interface of llvm::Function, instead of using 1255 // GraphTraints::getEntryNode. We should add a new template parameter to 1256 // DominatorTreeBase representing the Graph type. 1257 VPBlockBase &front() const { return *Entry; } 1258 1259 const VPBlockBase *getExit() const { return Exit; } 1260 VPBlockBase *getExit() { return Exit; } 1261 1262 /// Set \p ExitBlock as the exit VPBlockBase of this VPRegionBlock. \p 1263 /// ExitBlock must have no successors. 1264 void setExit(VPBlockBase *ExitBlock) { 1265 assert(ExitBlock->getSuccessors().empty() && 1266 "Exit block cannot have successors."); 1267 Exit = ExitBlock; 1268 ExitBlock->setParent(this); 1269 } 1270 1271 /// An indicator whether this region is to generate multiple replicated 1272 /// instances of output IR corresponding to its VPBlockBases. 1273 bool isReplicator() const { return IsReplicator; } 1274 1275 /// The method which generates the output IR instructions that correspond to 1276 /// this VPRegionBlock, thereby "executing" the VPlan. 1277 void execute(struct VPTransformState *State) override; 1278 }; 1279 1280 //===----------------------------------------------------------------------===// 1281 // GraphTraits specializations for VPlan Hierarchical Control-Flow Graphs // 1282 //===----------------------------------------------------------------------===// 1283 1284 // The following set of template specializations implement GraphTraits to treat 1285 // any VPBlockBase as a node in a graph of VPBlockBases. It's important to note 1286 // that VPBlockBase traits don't recurse into VPRegioBlocks, i.e., if the 1287 // VPBlockBase is a VPRegionBlock, this specialization provides access to its 1288 // successors/predecessors but not to the blocks inside the region. 1289 1290 template <> struct GraphTraits<VPBlockBase *> { 1291 using NodeRef = VPBlockBase *; 1292 using ChildIteratorType = SmallVectorImpl<VPBlockBase *>::iterator; 1293 1294 static NodeRef getEntryNode(NodeRef N) { return N; } 1295 1296 static inline ChildIteratorType child_begin(NodeRef N) { 1297 return N->getSuccessors().begin(); 1298 } 1299 1300 static inline ChildIteratorType child_end(NodeRef N) { 1301 return N->getSuccessors().end(); 1302 } 1303 }; 1304 1305 template <> struct GraphTraits<const VPBlockBase *> { 1306 using NodeRef = const VPBlockBase *; 1307 using ChildIteratorType = SmallVectorImpl<VPBlockBase *>::const_iterator; 1308 1309 static NodeRef getEntryNode(NodeRef N) { return N; } 1310 1311 static inline ChildIteratorType child_begin(NodeRef N) { 1312 return N->getSuccessors().begin(); 1313 } 1314 1315 static inline ChildIteratorType child_end(NodeRef N) { 1316 return N->getSuccessors().end(); 1317 } 1318 }; 1319 1320 // Inverse order specialization for VPBasicBlocks. Predecessors are used instead 1321 // of successors for the inverse traversal. 1322 template <> struct GraphTraits<Inverse<VPBlockBase *>> { 1323 using NodeRef = VPBlockBase *; 1324 using ChildIteratorType = SmallVectorImpl<VPBlockBase *>::iterator; 1325 1326 static NodeRef getEntryNode(Inverse<NodeRef> B) { return B.Graph; } 1327 1328 static inline ChildIteratorType child_begin(NodeRef N) { 1329 return N->getPredecessors().begin(); 1330 } 1331 1332 static inline ChildIteratorType child_end(NodeRef N) { 1333 return N->getPredecessors().end(); 1334 } 1335 }; 1336 1337 // The following set of template specializations implement GraphTraits to 1338 // treat VPRegionBlock as a graph and recurse inside its nodes. It's important 1339 // to note that the blocks inside the VPRegionBlock are treated as VPBlockBases 1340 // (i.e., no dyn_cast is performed, VPBlockBases specialization is used), so 1341 // there won't be automatic recursion into other VPBlockBases that turn to be 1342 // VPRegionBlocks. 1343 1344 template <> 1345 struct GraphTraits<VPRegionBlock *> : public GraphTraits<VPBlockBase *> { 1346 using GraphRef = VPRegionBlock *; 1347 using nodes_iterator = df_iterator<NodeRef>; 1348 1349 static NodeRef getEntryNode(GraphRef N) { return N->getEntry(); } 1350 1351 static nodes_iterator nodes_begin(GraphRef N) { 1352 return nodes_iterator::begin(N->getEntry()); 1353 } 1354 1355 static nodes_iterator nodes_end(GraphRef N) { 1356 // df_iterator::end() returns an empty iterator so the node used doesn't 1357 // matter. 1358 return nodes_iterator::end(N); 1359 } 1360 }; 1361 1362 template <> 1363 struct GraphTraits<const VPRegionBlock *> 1364 : public GraphTraits<const VPBlockBase *> { 1365 using GraphRef = const VPRegionBlock *; 1366 using nodes_iterator = df_iterator<NodeRef>; 1367 1368 static NodeRef getEntryNode(GraphRef N) { return N->getEntry(); } 1369 1370 static nodes_iterator nodes_begin(GraphRef N) { 1371 return nodes_iterator::begin(N->getEntry()); 1372 } 1373 1374 static nodes_iterator nodes_end(GraphRef N) { 1375 // df_iterator::end() returns an empty iterator so the node used doesn't 1376 // matter. 1377 return nodes_iterator::end(N); 1378 } 1379 }; 1380 1381 template <> 1382 struct GraphTraits<Inverse<VPRegionBlock *>> 1383 : public GraphTraits<Inverse<VPBlockBase *>> { 1384 using GraphRef = VPRegionBlock *; 1385 using nodes_iterator = df_iterator<NodeRef>; 1386 1387 static NodeRef getEntryNode(Inverse<GraphRef> N) { 1388 return N.Graph->getExit(); 1389 } 1390 1391 static nodes_iterator nodes_begin(GraphRef N) { 1392 return nodes_iterator::begin(N->getExit()); 1393 } 1394 1395 static nodes_iterator nodes_end(GraphRef N) { 1396 // df_iterator::end() returns an empty iterator so the node used doesn't 1397 // matter. 1398 return nodes_iterator::end(N); 1399 } 1400 }; 1401 1402 class VPSlotTracker; 1403 /// VPlan models a candidate for vectorization, encoding various decisions take 1404 /// to produce efficient output IR, including which branches, basic-blocks and 1405 /// output IR instructions to generate, and their cost. VPlan holds a 1406 /// Hierarchical-CFG of VPBasicBlocks and VPRegionBlocks rooted at an Entry 1407 /// VPBlock. 1408 class VPlan { 1409 friend class VPlanPrinter; 1410 friend class VPSlotTracker; 1411 1412 private: 1413 /// Hold the single entry to the Hierarchical CFG of the VPlan. 1414 VPBlockBase *Entry; 1415 1416 /// Holds the VFs applicable to this VPlan. 1417 SmallSet<unsigned, 2> VFs; 1418 1419 /// Holds the name of the VPlan, for printing. 1420 std::string Name; 1421 1422 /// Holds all the external definitions created for this VPlan. 1423 // TODO: Introduce a specific representation for external definitions in 1424 // VPlan. External definitions must be immutable and hold a pointer to its 1425 // underlying IR that will be used to implement its structural comparison 1426 // (operators '==' and '<'). 1427 SmallPtrSet<VPValue *, 16> VPExternalDefs; 1428 1429 /// Represents the backedge taken count of the original loop, for folding 1430 /// the tail. 1431 VPValue *BackedgeTakenCount = nullptr; 1432 1433 /// Holds a mapping between Values and their corresponding VPValue inside 1434 /// VPlan. 1435 Value2VPValueTy Value2VPValue; 1436 1437 /// Holds the VPLoopInfo analysis for this VPlan. 1438 VPLoopInfo VPLInfo; 1439 1440 /// Holds the condition bit values built during VPInstruction to VPRecipe transformation. 1441 SmallVector<VPValue *, 4> VPCBVs; 1442 1443 public: 1444 VPlan(VPBlockBase *Entry = nullptr) : Entry(Entry) { 1445 if (Entry) 1446 Entry->setPlan(this); 1447 } 1448 1449 ~VPlan() { 1450 if (Entry) 1451 VPBlockBase::deleteCFG(Entry); 1452 for (auto &MapEntry : Value2VPValue) 1453 if (MapEntry.second != BackedgeTakenCount) 1454 delete MapEntry.second; 1455 if (BackedgeTakenCount) 1456 delete BackedgeTakenCount; // Delete once, if in Value2VPValue or not. 1457 for (VPValue *Def : VPExternalDefs) 1458 delete Def; 1459 for (VPValue *CBV : VPCBVs) 1460 delete CBV; 1461 } 1462 1463 /// Generate the IR code for this VPlan. 1464 void execute(struct VPTransformState *State); 1465 1466 VPBlockBase *getEntry() { return Entry; } 1467 const VPBlockBase *getEntry() const { return Entry; } 1468 1469 VPBlockBase *setEntry(VPBlockBase *Block) { 1470 Entry = Block; 1471 Block->setPlan(this); 1472 return Entry; 1473 } 1474 1475 /// The backedge taken count of the original loop. 1476 VPValue *getOrCreateBackedgeTakenCount() { 1477 if (!BackedgeTakenCount) 1478 BackedgeTakenCount = new VPValue(); 1479 return BackedgeTakenCount; 1480 } 1481 1482 void addVF(unsigned VF) { VFs.insert(VF); } 1483 1484 bool hasVF(unsigned VF) { return VFs.count(VF); } 1485 1486 const std::string &getName() const { return Name; } 1487 1488 void setName(const Twine &newName) { Name = newName.str(); } 1489 1490 /// Add \p VPVal to the pool of external definitions if it's not already 1491 /// in the pool. 1492 void addExternalDef(VPValue *VPVal) { 1493 VPExternalDefs.insert(VPVal); 1494 } 1495 1496 /// Add \p CBV to the vector of condition bit values. 1497 void addCBV(VPValue *CBV) { 1498 VPCBVs.push_back(CBV); 1499 } 1500 1501 void addVPValue(Value *V) { 1502 assert(V && "Trying to add a null Value to VPlan"); 1503 assert(!Value2VPValue.count(V) && "Value already exists in VPlan"); 1504 Value2VPValue[V] = new VPValue(V); 1505 } 1506 1507 VPValue *getVPValue(Value *V) { 1508 assert(V && "Trying to get the VPValue of a null Value"); 1509 assert(Value2VPValue.count(V) && "Value does not exist in VPlan"); 1510 return Value2VPValue[V]; 1511 } 1512 1513 VPValue *getOrAddVPValue(Value *V) { 1514 assert(V && "Trying to get or add the VPValue of a null Value"); 1515 if (!Value2VPValue.count(V)) 1516 addVPValue(V); 1517 return getVPValue(V); 1518 } 1519 1520 /// Return the VPLoopInfo analysis for this VPlan. 1521 VPLoopInfo &getVPLoopInfo() { return VPLInfo; } 1522 const VPLoopInfo &getVPLoopInfo() const { return VPLInfo; } 1523 1524 /// Dump the plan to stderr (for debugging). 1525 void dump() const; 1526 1527 private: 1528 /// Add to the given dominator tree the header block and every new basic block 1529 /// that was created between it and the latch block, inclusive. 1530 static void updateDominatorTree(DominatorTree *DT, BasicBlock *LoopLatchBB, 1531 BasicBlock *LoopPreHeaderBB, 1532 BasicBlock *LoopExitBB); 1533 }; 1534 1535 /// VPlanPrinter prints a given VPlan to a given output stream. The printing is 1536 /// indented and follows the dot format. 1537 class VPlanPrinter { 1538 friend inline raw_ostream &operator<<(raw_ostream &OS, const VPlan &Plan); 1539 friend inline raw_ostream &operator<<(raw_ostream &OS, 1540 const struct VPlanIngredient &I); 1541 1542 private: 1543 raw_ostream &OS; 1544 const VPlan &Plan; 1545 unsigned Depth = 0; 1546 unsigned TabWidth = 2; 1547 std::string Indent; 1548 unsigned BID = 0; 1549 SmallDenseMap<const VPBlockBase *, unsigned> BlockID; 1550 1551 VPSlotTracker SlotTracker; 1552 1553 VPlanPrinter(raw_ostream &O, const VPlan &P) 1554 : OS(O), Plan(P), SlotTracker(&P) {} 1555 1556 /// Handle indentation. 1557 void bumpIndent(int b) { Indent = std::string((Depth += b) * TabWidth, ' '); } 1558 1559 /// Print a given \p Block of the Plan. 1560 void dumpBlock(const VPBlockBase *Block); 1561 1562 /// Print the information related to the CFG edges going out of a given 1563 /// \p Block, followed by printing the successor blocks themselves. 1564 void dumpEdges(const VPBlockBase *Block); 1565 1566 /// Print a given \p BasicBlock, including its VPRecipes, followed by printing 1567 /// its successor blocks. 1568 void dumpBasicBlock(const VPBasicBlock *BasicBlock); 1569 1570 /// Print a given \p Region of the Plan. 1571 void dumpRegion(const VPRegionBlock *Region); 1572 1573 unsigned getOrCreateBID(const VPBlockBase *Block) { 1574 return BlockID.count(Block) ? BlockID[Block] : BlockID[Block] = BID++; 1575 } 1576 1577 const Twine getOrCreateName(const VPBlockBase *Block); 1578 1579 const Twine getUID(const VPBlockBase *Block); 1580 1581 /// Print the information related to a CFG edge between two VPBlockBases. 1582 void drawEdge(const VPBlockBase *From, const VPBlockBase *To, bool Hidden, 1583 const Twine &Label); 1584 1585 void dump(); 1586 1587 static void printAsIngredient(raw_ostream &O, Value *V); 1588 }; 1589 1590 struct VPlanIngredient { 1591 Value *V; 1592 1593 VPlanIngredient(Value *V) : V(V) {} 1594 }; 1595 1596 inline raw_ostream &operator<<(raw_ostream &OS, const VPlanIngredient &I) { 1597 VPlanPrinter::printAsIngredient(OS, I.V); 1598 return OS; 1599 } 1600 1601 inline raw_ostream &operator<<(raw_ostream &OS, const VPlan &Plan) { 1602 VPlanPrinter Printer(OS, Plan); 1603 Printer.dump(); 1604 return OS; 1605 } 1606 1607 //===----------------------------------------------------------------------===// 1608 // VPlan Utilities 1609 //===----------------------------------------------------------------------===// 1610 1611 /// Class that provides utilities for VPBlockBases in VPlan. 1612 class VPBlockUtils { 1613 public: 1614 VPBlockUtils() = delete; 1615 1616 /// Insert disconnected VPBlockBase \p NewBlock after \p BlockPtr. Add \p 1617 /// NewBlock as successor of \p BlockPtr and \p BlockPtr as predecessor of \p 1618 /// NewBlock, and propagate \p BlockPtr parent to \p NewBlock. If \p BlockPtr 1619 /// has more than one successor, its conditional bit is propagated to \p 1620 /// NewBlock. \p NewBlock must have neither successors nor predecessors. 1621 static void insertBlockAfter(VPBlockBase *NewBlock, VPBlockBase *BlockPtr) { 1622 assert(NewBlock->getSuccessors().empty() && 1623 "Can't insert new block with successors."); 1624 // TODO: move successors from BlockPtr to NewBlock when this functionality 1625 // is necessary. For now, setBlockSingleSuccessor will assert if BlockPtr 1626 // already has successors. 1627 BlockPtr->setOneSuccessor(NewBlock); 1628 NewBlock->setPredecessors({BlockPtr}); 1629 NewBlock->setParent(BlockPtr->getParent()); 1630 } 1631 1632 /// Insert disconnected VPBlockBases \p IfTrue and \p IfFalse after \p 1633 /// BlockPtr. Add \p IfTrue and \p IfFalse as succesors of \p BlockPtr and \p 1634 /// BlockPtr as predecessor of \p IfTrue and \p IfFalse. Propagate \p BlockPtr 1635 /// parent to \p IfTrue and \p IfFalse. \p Condition is set as the successor 1636 /// selector. \p BlockPtr must have no successors and \p IfTrue and \p IfFalse 1637 /// must have neither successors nor predecessors. 1638 static void insertTwoBlocksAfter(VPBlockBase *IfTrue, VPBlockBase *IfFalse, 1639 VPValue *Condition, VPBlockBase *BlockPtr) { 1640 assert(IfTrue->getSuccessors().empty() && 1641 "Can't insert IfTrue with successors."); 1642 assert(IfFalse->getSuccessors().empty() && 1643 "Can't insert IfFalse with successors."); 1644 BlockPtr->setTwoSuccessors(IfTrue, IfFalse, Condition); 1645 IfTrue->setPredecessors({BlockPtr}); 1646 IfFalse->setPredecessors({BlockPtr}); 1647 IfTrue->setParent(BlockPtr->getParent()); 1648 IfFalse->setParent(BlockPtr->getParent()); 1649 } 1650 1651 /// Connect VPBlockBases \p From and \p To bi-directionally. Append \p To to 1652 /// the successors of \p From and \p From to the predecessors of \p To. Both 1653 /// VPBlockBases must have the same parent, which can be null. Both 1654 /// VPBlockBases can be already connected to other VPBlockBases. 1655 static void connectBlocks(VPBlockBase *From, VPBlockBase *To) { 1656 assert((From->getParent() == To->getParent()) && 1657 "Can't connect two block with different parents"); 1658 assert(From->getNumSuccessors() < 2 && 1659 "Blocks can't have more than two successors."); 1660 From->appendSuccessor(To); 1661 To->appendPredecessor(From); 1662 } 1663 1664 /// Disconnect VPBlockBases \p From and \p To bi-directionally. Remove \p To 1665 /// from the successors of \p From and \p From from the predecessors of \p To. 1666 static void disconnectBlocks(VPBlockBase *From, VPBlockBase *To) { 1667 assert(To && "Successor to disconnect is null."); 1668 From->removeSuccessor(To); 1669 To->removePredecessor(From); 1670 } 1671 1672 /// Returns true if the edge \p FromBlock -> \p ToBlock is a back-edge. 1673 static bool isBackEdge(const VPBlockBase *FromBlock, 1674 const VPBlockBase *ToBlock, const VPLoopInfo *VPLI) { 1675 assert(FromBlock->getParent() == ToBlock->getParent() && 1676 FromBlock->getParent() && "Must be in same region"); 1677 const VPLoop *FromLoop = VPLI->getLoopFor(FromBlock); 1678 const VPLoop *ToLoop = VPLI->getLoopFor(ToBlock); 1679 if (!FromLoop || !ToLoop || FromLoop != ToLoop) 1680 return false; 1681 1682 // A back-edge is a branch from the loop latch to its header. 1683 return ToLoop->isLoopLatch(FromBlock) && ToBlock == ToLoop->getHeader(); 1684 } 1685 1686 /// Returns true if \p Block is a loop latch 1687 static bool blockIsLoopLatch(const VPBlockBase *Block, 1688 const VPLoopInfo *VPLInfo) { 1689 if (const VPLoop *ParentVPL = VPLInfo->getLoopFor(Block)) 1690 return ParentVPL->isLoopLatch(Block); 1691 1692 return false; 1693 } 1694 1695 /// Count and return the number of succesors of \p PredBlock excluding any 1696 /// backedges. 1697 static unsigned countSuccessorsNoBE(VPBlockBase *PredBlock, 1698 VPLoopInfo *VPLI) { 1699 unsigned Count = 0; 1700 for (VPBlockBase *SuccBlock : PredBlock->getSuccessors()) { 1701 if (!VPBlockUtils::isBackEdge(PredBlock, SuccBlock, VPLI)) 1702 Count++; 1703 } 1704 return Count; 1705 } 1706 }; 1707 1708 class VPInterleavedAccessInfo { 1709 private: 1710 DenseMap<VPInstruction *, InterleaveGroup<VPInstruction> *> 1711 InterleaveGroupMap; 1712 1713 /// Type for mapping of instruction based interleave groups to VPInstruction 1714 /// interleave groups 1715 using Old2NewTy = DenseMap<InterleaveGroup<Instruction> *, 1716 InterleaveGroup<VPInstruction> *>; 1717 1718 /// Recursively \p Region and populate VPlan based interleave groups based on 1719 /// \p IAI. 1720 void visitRegion(VPRegionBlock *Region, Old2NewTy &Old2New, 1721 InterleavedAccessInfo &IAI); 1722 /// Recursively traverse \p Block and populate VPlan based interleave groups 1723 /// based on \p IAI. 1724 void visitBlock(VPBlockBase *Block, Old2NewTy &Old2New, 1725 InterleavedAccessInfo &IAI); 1726 1727 public: 1728 VPInterleavedAccessInfo(VPlan &Plan, InterleavedAccessInfo &IAI); 1729 1730 ~VPInterleavedAccessInfo() { 1731 SmallPtrSet<InterleaveGroup<VPInstruction> *, 4> DelSet; 1732 // Avoid releasing a pointer twice. 1733 for (auto &I : InterleaveGroupMap) 1734 DelSet.insert(I.second); 1735 for (auto *Ptr : DelSet) 1736 delete Ptr; 1737 } 1738 1739 /// Get the interleave group that \p Instr belongs to. 1740 /// 1741 /// \returns nullptr if doesn't have such group. 1742 InterleaveGroup<VPInstruction> * 1743 getInterleaveGroup(VPInstruction *Instr) const { 1744 if (InterleaveGroupMap.count(Instr)) 1745 return InterleaveGroupMap.find(Instr)->second; 1746 return nullptr; 1747 } 1748 }; 1749 1750 /// Class that maps (parts of) an existing VPlan to trees of combined 1751 /// VPInstructions. 1752 class VPlanSlp { 1753 private: 1754 enum class OpMode { Failed, Load, Opcode }; 1755 1756 /// A DenseMapInfo implementation for using SmallVector<VPValue *, 4> as 1757 /// DenseMap keys. 1758 struct BundleDenseMapInfo { 1759 static SmallVector<VPValue *, 4> getEmptyKey() { 1760 return {reinterpret_cast<VPValue *>(-1)}; 1761 } 1762 1763 static SmallVector<VPValue *, 4> getTombstoneKey() { 1764 return {reinterpret_cast<VPValue *>(-2)}; 1765 } 1766 1767 static unsigned getHashValue(const SmallVector<VPValue *, 4> &V) { 1768 return static_cast<unsigned>(hash_combine_range(V.begin(), V.end())); 1769 } 1770 1771 static bool isEqual(const SmallVector<VPValue *, 4> &LHS, 1772 const SmallVector<VPValue *, 4> &RHS) { 1773 return LHS == RHS; 1774 } 1775 }; 1776 1777 /// Mapping of values in the original VPlan to a combined VPInstruction. 1778 DenseMap<SmallVector<VPValue *, 4>, VPInstruction *, BundleDenseMapInfo> 1779 BundleToCombined; 1780 1781 VPInterleavedAccessInfo &IAI; 1782 1783 /// Basic block to operate on. For now, only instructions in a single BB are 1784 /// considered. 1785 const VPBasicBlock &BB; 1786 1787 /// Indicates whether we managed to combine all visited instructions or not. 1788 bool CompletelySLP = true; 1789 1790 /// Width of the widest combined bundle in bits. 1791 unsigned WidestBundleBits = 0; 1792 1793 using MultiNodeOpTy = 1794 typename std::pair<VPInstruction *, SmallVector<VPValue *, 4>>; 1795 1796 // Input operand bundles for the current multi node. Each multi node operand 1797 // bundle contains values not matching the multi node's opcode. They will 1798 // be reordered in reorderMultiNodeOps, once we completed building a 1799 // multi node. 1800 SmallVector<MultiNodeOpTy, 4> MultiNodeOps; 1801 1802 /// Indicates whether we are building a multi node currently. 1803 bool MultiNodeActive = false; 1804 1805 /// Check if we can vectorize Operands together. 1806 bool areVectorizable(ArrayRef<VPValue *> Operands) const; 1807 1808 /// Add combined instruction \p New for the bundle \p Operands. 1809 void addCombined(ArrayRef<VPValue *> Operands, VPInstruction *New); 1810 1811 /// Indicate we hit a bundle we failed to combine. Returns nullptr for now. 1812 VPInstruction *markFailed(); 1813 1814 /// Reorder operands in the multi node to maximize sequential memory access 1815 /// and commutative operations. 1816 SmallVector<MultiNodeOpTy, 4> reorderMultiNodeOps(); 1817 1818 /// Choose the best candidate to use for the lane after \p Last. The set of 1819 /// candidates to choose from are values with an opcode matching \p Last's 1820 /// or loads consecutive to \p Last. 1821 std::pair<OpMode, VPValue *> getBest(OpMode Mode, VPValue *Last, 1822 SmallPtrSetImpl<VPValue *> &Candidates, 1823 VPInterleavedAccessInfo &IAI); 1824 1825 /// Print bundle \p Values to dbgs(). 1826 void dumpBundle(ArrayRef<VPValue *> Values); 1827 1828 public: 1829 VPlanSlp(VPInterleavedAccessInfo &IAI, VPBasicBlock &BB) : IAI(IAI), BB(BB) {} 1830 1831 ~VPlanSlp() { 1832 for (auto &KV : BundleToCombined) 1833 delete KV.second; 1834 } 1835 1836 /// Tries to build an SLP tree rooted at \p Operands and returns a 1837 /// VPInstruction combining \p Operands, if they can be combined. 1838 VPInstruction *buildGraph(ArrayRef<VPValue *> Operands); 1839 1840 /// Return the width of the widest combined bundle in bits. 1841 unsigned getWidestBundleBits() const { return WidestBundleBits; } 1842 1843 /// Return true if all visited instruction can be combined. 1844 bool isCompletelySLP() const { return CompletelySLP; } 1845 }; 1846 } // end namespace llvm 1847 1848 #endif // LLVM_TRANSFORMS_VECTORIZE_VPLAN_H 1849