1 //===- VPlan.cpp - Vectorizer Plan ----------------------------------------===// 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 is the LLVM vectorization plan. It represents a candidate for 11 /// vectorization, allowing to plan and optimize how to vectorize a given loop 12 /// before generating LLVM-IR. 13 /// The vectorizer uses vectorization plans to estimate the costs of potential 14 /// candidates and if profitable to execute the desired plan, generating vector 15 /// LLVM-IR code. 16 /// 17 //===----------------------------------------------------------------------===// 18 19 #include "VPlan.h" 20 #include "VPlanDominatorTree.h" 21 #include "llvm/ADT/DepthFirstIterator.h" 22 #include "llvm/ADT/PostOrderIterator.h" 23 #include "llvm/ADT/STLExtras.h" 24 #include "llvm/ADT/SmallVector.h" 25 #include "llvm/ADT/Twine.h" 26 #include "llvm/Analysis/IVDescriptors.h" 27 #include "llvm/Analysis/LoopInfo.h" 28 #include "llvm/IR/BasicBlock.h" 29 #include "llvm/IR/CFG.h" 30 #include "llvm/IR/InstrTypes.h" 31 #include "llvm/IR/Instruction.h" 32 #include "llvm/IR/Instructions.h" 33 #include "llvm/IR/Type.h" 34 #include "llvm/IR/Value.h" 35 #include "llvm/Support/Casting.h" 36 #include "llvm/Support/CommandLine.h" 37 #include "llvm/Support/Debug.h" 38 #include "llvm/Support/ErrorHandling.h" 39 #include "llvm/Support/GenericDomTreeConstruction.h" 40 #include "llvm/Support/GraphWriter.h" 41 #include "llvm/Support/raw_ostream.h" 42 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 43 #include <cassert> 44 #include <iterator> 45 #include <string> 46 #include <vector> 47 48 using namespace llvm; 49 extern cl::opt<bool> EnableVPlanNativePath; 50 51 #define DEBUG_TYPE "vplan" 52 53 raw_ostream &llvm::operator<<(raw_ostream &OS, const VPValue &V) { 54 const VPInstruction *Instr = dyn_cast<VPInstruction>(&V); 55 VPSlotTracker SlotTracker( 56 (Instr && Instr->getParent()) ? Instr->getParent()->getPlan() : nullptr); 57 V.print(OS, SlotTracker); 58 return OS; 59 } 60 61 VPValue::VPValue(const unsigned char SC, Value *UV, VPDef *Def) 62 : SubclassID(SC), UnderlyingVal(UV), Def(Def) { 63 if (Def) 64 Def->addDefinedValue(this); 65 } 66 67 VPValue::~VPValue() { 68 assert(Users.empty() && "trying to delete a VPValue with remaining users"); 69 if (Def) 70 Def->removeDefinedValue(this); 71 } 72 73 void VPValue::print(raw_ostream &OS, VPSlotTracker &SlotTracker) const { 74 if (const VPRecipeBase *R = dyn_cast_or_null<VPRecipeBase>(Def)) 75 R->print(OS, "", SlotTracker); 76 else 77 printAsOperand(OS, SlotTracker); 78 } 79 80 void VPValue::dump() const { 81 const VPRecipeBase *Instr = dyn_cast_or_null<VPRecipeBase>(this->Def); 82 VPSlotTracker SlotTracker( 83 (Instr && Instr->getParent()) ? Instr->getParent()->getPlan() : nullptr); 84 print(dbgs(), SlotTracker); 85 dbgs() << "\n"; 86 } 87 88 void VPDef::dump() const { 89 const VPRecipeBase *Instr = dyn_cast_or_null<VPRecipeBase>(this); 90 VPSlotTracker SlotTracker( 91 (Instr && Instr->getParent()) ? Instr->getParent()->getPlan() : nullptr); 92 print(dbgs(), "", SlotTracker); 93 dbgs() << "\n"; 94 } 95 96 VPUser *VPRecipeBase::toVPUser() { 97 if (auto *U = dyn_cast<VPInstruction>(this)) 98 return U; 99 if (auto *U = dyn_cast<VPWidenRecipe>(this)) 100 return U; 101 if (auto *U = dyn_cast<VPWidenCallRecipe>(this)) 102 return U; 103 if (auto *U = dyn_cast<VPWidenSelectRecipe>(this)) 104 return U; 105 if (auto *U = dyn_cast<VPWidenGEPRecipe>(this)) 106 return U; 107 if (auto *U = dyn_cast<VPBlendRecipe>(this)) 108 return U; 109 if (auto *U = dyn_cast<VPInterleaveRecipe>(this)) 110 return U; 111 if (auto *U = dyn_cast<VPReplicateRecipe>(this)) 112 return U; 113 if (auto *U = dyn_cast<VPBranchOnMaskRecipe>(this)) 114 return U; 115 if (auto *U = dyn_cast<VPWidenMemoryInstructionRecipe>(this)) 116 return U; 117 if (auto *U = dyn_cast<VPReductionRecipe>(this)) 118 return U; 119 if (auto *U = dyn_cast<VPPredInstPHIRecipe>(this)) 120 return U; 121 return nullptr; 122 } 123 124 // Get the top-most entry block of \p Start. This is the entry block of the 125 // containing VPlan. This function is templated to support both const and non-const blocks 126 template <typename T> static T *getPlanEntry(T *Start) { 127 T *Next = Start; 128 T *Current = Start; 129 while ((Next = Next->getParent())) 130 Current = Next; 131 132 SmallSetVector<T *, 8> WorkList; 133 WorkList.insert(Current); 134 135 for (unsigned i = 0; i < WorkList.size(); i++) { 136 T *Current = WorkList[i]; 137 if (Current->getNumPredecessors() == 0) 138 return Current; 139 auto &Predecessors = Current->getPredecessors(); 140 WorkList.insert(Predecessors.begin(), Predecessors.end()); 141 } 142 143 llvm_unreachable("VPlan without any entry node without predecessors"); 144 } 145 146 VPlan *VPBlockBase::getPlan() { return getPlanEntry(this)->Plan; } 147 148 const VPlan *VPBlockBase::getPlan() const { return getPlanEntry(this)->Plan; } 149 150 /// \return the VPBasicBlock that is the entry of Block, possibly indirectly. 151 const VPBasicBlock *VPBlockBase::getEntryBasicBlock() const { 152 const VPBlockBase *Block = this; 153 while (const VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block)) 154 Block = Region->getEntry(); 155 return cast<VPBasicBlock>(Block); 156 } 157 158 VPBasicBlock *VPBlockBase::getEntryBasicBlock() { 159 VPBlockBase *Block = this; 160 while (VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block)) 161 Block = Region->getEntry(); 162 return cast<VPBasicBlock>(Block); 163 } 164 165 void VPBlockBase::setPlan(VPlan *ParentPlan) { 166 assert(ParentPlan->getEntry() == this && 167 "Can only set plan on its entry block."); 168 Plan = ParentPlan; 169 } 170 171 /// \return the VPBasicBlock that is the exit of Block, possibly indirectly. 172 const VPBasicBlock *VPBlockBase::getExitBasicBlock() const { 173 const VPBlockBase *Block = this; 174 while (const VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block)) 175 Block = Region->getExit(); 176 return cast<VPBasicBlock>(Block); 177 } 178 179 VPBasicBlock *VPBlockBase::getExitBasicBlock() { 180 VPBlockBase *Block = this; 181 while (VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block)) 182 Block = Region->getExit(); 183 return cast<VPBasicBlock>(Block); 184 } 185 186 VPBlockBase *VPBlockBase::getEnclosingBlockWithSuccessors() { 187 if (!Successors.empty() || !Parent) 188 return this; 189 assert(Parent->getExit() == this && 190 "Block w/o successors not the exit of its parent."); 191 return Parent->getEnclosingBlockWithSuccessors(); 192 } 193 194 VPBlockBase *VPBlockBase::getEnclosingBlockWithPredecessors() { 195 if (!Predecessors.empty() || !Parent) 196 return this; 197 assert(Parent->getEntry() == this && 198 "Block w/o predecessors not the entry of its parent."); 199 return Parent->getEnclosingBlockWithPredecessors(); 200 } 201 202 void VPBlockBase::deleteCFG(VPBlockBase *Entry) { 203 SmallVector<VPBlockBase *, 8> Blocks(depth_first(Entry)); 204 205 for (VPBlockBase *Block : Blocks) 206 delete Block; 207 } 208 209 VPBasicBlock::iterator VPBasicBlock::getFirstNonPhi() { 210 iterator It = begin(); 211 while (It != end() && (isa<VPWidenPHIRecipe>(&*It) || 212 isa<VPWidenIntOrFpInductionRecipe>(&*It) || 213 isa<VPPredInstPHIRecipe>(&*It) || 214 isa<VPWidenCanonicalIVRecipe>(&*It))) 215 It++; 216 return It; 217 } 218 219 Value *VPTransformState::get(VPValue *Def, const VPIteration &Instance) { 220 if (!Def->getDef() && OrigLoop->isLoopInvariant(Def->getLiveInIRValue())) 221 return Def->getLiveInIRValue(); 222 223 if (hasScalarValue(Def, Instance)) 224 return Data.PerPartScalars[Def][Instance.Part][Instance.Lane]; 225 226 if (hasVectorValue(Def, Instance.Part)) { 227 assert(Data.PerPartOutput.count(Def)); 228 auto *VecPart = Data.PerPartOutput[Def][Instance.Part]; 229 if (!VecPart->getType()->isVectorTy()) { 230 assert(Instance.Lane == 0 && "cannot get lane > 0 for scalar"); 231 return VecPart; 232 } 233 // TODO: Cache created scalar values. 234 return Builder.CreateExtractElement(VecPart, 235 Builder.getInt32(Instance.Lane)); 236 } 237 return Callback.getOrCreateScalarValue(VPValue2Value[Def], Instance); 238 } 239 240 BasicBlock * 241 VPBasicBlock::createEmptyBasicBlock(VPTransformState::CFGState &CFG) { 242 // BB stands for IR BasicBlocks. VPBB stands for VPlan VPBasicBlocks. 243 // Pred stands for Predessor. Prev stands for Previous - last visited/created. 244 BasicBlock *PrevBB = CFG.PrevBB; 245 BasicBlock *NewBB = BasicBlock::Create(PrevBB->getContext(), getName(), 246 PrevBB->getParent(), CFG.LastBB); 247 LLVM_DEBUG(dbgs() << "LV: created " << NewBB->getName() << '\n'); 248 249 // Hook up the new basic block to its predecessors. 250 for (VPBlockBase *PredVPBlock : getHierarchicalPredecessors()) { 251 VPBasicBlock *PredVPBB = PredVPBlock->getExitBasicBlock(); 252 auto &PredVPSuccessors = PredVPBB->getSuccessors(); 253 BasicBlock *PredBB = CFG.VPBB2IRBB[PredVPBB]; 254 255 // In outer loop vectorization scenario, the predecessor BBlock may not yet 256 // be visited(backedge). Mark the VPBasicBlock for fixup at the end of 257 // vectorization. We do not encounter this case in inner loop vectorization 258 // as we start out by building a loop skeleton with the vector loop header 259 // and latch blocks. As a result, we never enter this function for the 260 // header block in the non VPlan-native path. 261 if (!PredBB) { 262 assert(EnableVPlanNativePath && 263 "Unexpected null predecessor in non VPlan-native path"); 264 CFG.VPBBsToFix.push_back(PredVPBB); 265 continue; 266 } 267 268 assert(PredBB && "Predecessor basic-block not found building successor."); 269 auto *PredBBTerminator = PredBB->getTerminator(); 270 LLVM_DEBUG(dbgs() << "LV: draw edge from" << PredBB->getName() << '\n'); 271 if (isa<UnreachableInst>(PredBBTerminator)) { 272 assert(PredVPSuccessors.size() == 1 && 273 "Predecessor ending w/o branch must have single successor."); 274 PredBBTerminator->eraseFromParent(); 275 BranchInst::Create(NewBB, PredBB); 276 } else { 277 assert(PredVPSuccessors.size() == 2 && 278 "Predecessor ending with branch must have two successors."); 279 unsigned idx = PredVPSuccessors.front() == this ? 0 : 1; 280 assert(!PredBBTerminator->getSuccessor(idx) && 281 "Trying to reset an existing successor block."); 282 PredBBTerminator->setSuccessor(idx, NewBB); 283 } 284 } 285 return NewBB; 286 } 287 288 void VPBasicBlock::execute(VPTransformState *State) { 289 bool Replica = State->Instance && !State->Instance->isFirstIteration(); 290 VPBasicBlock *PrevVPBB = State->CFG.PrevVPBB; 291 VPBlockBase *SingleHPred = nullptr; 292 BasicBlock *NewBB = State->CFG.PrevBB; // Reuse it if possible. 293 294 // 1. Create an IR basic block, or reuse the last one if possible. 295 // The last IR basic block is reused, as an optimization, in three cases: 296 // A. the first VPBB reuses the loop header BB - when PrevVPBB is null; 297 // B. when the current VPBB has a single (hierarchical) predecessor which 298 // is PrevVPBB and the latter has a single (hierarchical) successor; and 299 // C. when the current VPBB is an entry of a region replica - where PrevVPBB 300 // is the exit of this region from a previous instance, or the predecessor 301 // of this region. 302 if (PrevVPBB && /* A */ 303 !((SingleHPred = getSingleHierarchicalPredecessor()) && 304 SingleHPred->getExitBasicBlock() == PrevVPBB && 305 PrevVPBB->getSingleHierarchicalSuccessor()) && /* B */ 306 !(Replica && getPredecessors().empty())) { /* C */ 307 NewBB = createEmptyBasicBlock(State->CFG); 308 State->Builder.SetInsertPoint(NewBB); 309 // Temporarily terminate with unreachable until CFG is rewired. 310 UnreachableInst *Terminator = State->Builder.CreateUnreachable(); 311 State->Builder.SetInsertPoint(Terminator); 312 // Register NewBB in its loop. In innermost loops its the same for all BB's. 313 Loop *L = State->LI->getLoopFor(State->CFG.LastBB); 314 L->addBasicBlockToLoop(NewBB, *State->LI); 315 State->CFG.PrevBB = NewBB; 316 } 317 318 // 2. Fill the IR basic block with IR instructions. 319 LLVM_DEBUG(dbgs() << "LV: vectorizing VPBB:" << getName() 320 << " in BB:" << NewBB->getName() << '\n'); 321 322 State->CFG.VPBB2IRBB[this] = NewBB; 323 State->CFG.PrevVPBB = this; 324 325 for (VPRecipeBase &Recipe : Recipes) 326 Recipe.execute(*State); 327 328 VPValue *CBV; 329 if (EnableVPlanNativePath && (CBV = getCondBit())) { 330 Value *IRCBV = CBV->getUnderlyingValue(); 331 assert(IRCBV && "Unexpected null underlying value for condition bit"); 332 333 // Condition bit value in a VPBasicBlock is used as the branch selector. In 334 // the VPlan-native path case, since all branches are uniform we generate a 335 // branch instruction using the condition value from vector lane 0 and dummy 336 // successors. The successors are fixed later when the successor blocks are 337 // visited. 338 Value *NewCond = State->Callback.getOrCreateVectorValues(IRCBV, 0); 339 NewCond = State->Builder.CreateExtractElement(NewCond, 340 State->Builder.getInt32(0)); 341 342 // Replace the temporary unreachable terminator with the new conditional 343 // branch. 344 auto *CurrentTerminator = NewBB->getTerminator(); 345 assert(isa<UnreachableInst>(CurrentTerminator) && 346 "Expected to replace unreachable terminator with conditional " 347 "branch."); 348 auto *CondBr = BranchInst::Create(NewBB, nullptr, NewCond); 349 CondBr->setSuccessor(0, nullptr); 350 ReplaceInstWithInst(CurrentTerminator, CondBr); 351 } 352 353 LLVM_DEBUG(dbgs() << "LV: filled BB:" << *NewBB); 354 } 355 356 void VPBasicBlock::dropAllReferences(VPValue *NewValue) { 357 for (VPRecipeBase &R : Recipes) { 358 for (auto *Def : R.definedValues()) 359 Def->replaceAllUsesWith(NewValue); 360 361 if (auto *User = R.toVPUser()) 362 for (unsigned I = 0, E = User->getNumOperands(); I != E; I++) 363 User->setOperand(I, NewValue); 364 } 365 } 366 367 void VPRegionBlock::dropAllReferences(VPValue *NewValue) { 368 for (VPBlockBase *Block : depth_first(Entry)) 369 // Drop all references in VPBasicBlocks and replace all uses with 370 // DummyValue. 371 Block->dropAllReferences(NewValue); 372 } 373 374 void VPRegionBlock::execute(VPTransformState *State) { 375 ReversePostOrderTraversal<VPBlockBase *> RPOT(Entry); 376 377 if (!isReplicator()) { 378 // Visit the VPBlocks connected to "this", starting from it. 379 for (VPBlockBase *Block : RPOT) { 380 if (EnableVPlanNativePath) { 381 // The inner loop vectorization path does not represent loop preheader 382 // and exit blocks as part of the VPlan. In the VPlan-native path, skip 383 // vectorizing loop preheader block. In future, we may replace this 384 // check with the check for loop preheader. 385 if (Block->getNumPredecessors() == 0) 386 continue; 387 388 // Skip vectorizing loop exit block. In future, we may replace this 389 // check with the check for loop exit. 390 if (Block->getNumSuccessors() == 0) 391 continue; 392 } 393 394 LLVM_DEBUG(dbgs() << "LV: VPBlock in RPO " << Block->getName() << '\n'); 395 Block->execute(State); 396 } 397 return; 398 } 399 400 assert(!State->Instance && "Replicating a Region with non-null instance."); 401 402 // Enter replicating mode. 403 State->Instance = VPIteration(0, 0); 404 405 for (unsigned Part = 0, UF = State->UF; Part < UF; ++Part) { 406 State->Instance->Part = Part; 407 assert(!State->VF.isScalable() && "VF is assumed to be non scalable."); 408 for (unsigned Lane = 0, VF = State->VF.getKnownMinValue(); Lane < VF; 409 ++Lane) { 410 State->Instance->Lane = Lane; 411 // Visit the VPBlocks connected to \p this, starting from it. 412 for (VPBlockBase *Block : RPOT) { 413 LLVM_DEBUG(dbgs() << "LV: VPBlock in RPO " << Block->getName() << '\n'); 414 Block->execute(State); 415 } 416 } 417 } 418 419 // Exit replicating mode. 420 State->Instance.reset(); 421 } 422 423 void VPRecipeBase::insertBefore(VPRecipeBase *InsertPos) { 424 assert(!Parent && "Recipe already in some VPBasicBlock"); 425 assert(InsertPos->getParent() && 426 "Insertion position not in any VPBasicBlock"); 427 Parent = InsertPos->getParent(); 428 Parent->getRecipeList().insert(InsertPos->getIterator(), this); 429 } 430 431 void VPRecipeBase::insertAfter(VPRecipeBase *InsertPos) { 432 assert(!Parent && "Recipe already in some VPBasicBlock"); 433 assert(InsertPos->getParent() && 434 "Insertion position not in any VPBasicBlock"); 435 Parent = InsertPos->getParent(); 436 Parent->getRecipeList().insertAfter(InsertPos->getIterator(), this); 437 } 438 439 void VPRecipeBase::removeFromParent() { 440 assert(getParent() && "Recipe not in any VPBasicBlock"); 441 getParent()->getRecipeList().remove(getIterator()); 442 Parent = nullptr; 443 } 444 445 iplist<VPRecipeBase>::iterator VPRecipeBase::eraseFromParent() { 446 assert(getParent() && "Recipe not in any VPBasicBlock"); 447 return getParent()->getRecipeList().erase(getIterator()); 448 } 449 450 void VPRecipeBase::moveAfter(VPRecipeBase *InsertPos) { 451 removeFromParent(); 452 insertAfter(InsertPos); 453 } 454 455 void VPRecipeBase::moveBefore(VPBasicBlock &BB, 456 iplist<VPRecipeBase>::iterator I) { 457 assert(I == BB.end() || I->getParent() == &BB); 458 removeFromParent(); 459 Parent = &BB; 460 BB.getRecipeList().insert(I, this); 461 } 462 463 void VPInstruction::generateInstruction(VPTransformState &State, 464 unsigned Part) { 465 IRBuilder<> &Builder = State.Builder; 466 467 if (Instruction::isBinaryOp(getOpcode())) { 468 Value *A = State.get(getOperand(0), Part); 469 Value *B = State.get(getOperand(1), Part); 470 Value *V = Builder.CreateBinOp((Instruction::BinaryOps)getOpcode(), A, B); 471 State.set(this, V, Part); 472 return; 473 } 474 475 switch (getOpcode()) { 476 case VPInstruction::Not: { 477 Value *A = State.get(getOperand(0), Part); 478 Value *V = Builder.CreateNot(A); 479 State.set(this, V, Part); 480 break; 481 } 482 case VPInstruction::ICmpULE: { 483 Value *IV = State.get(getOperand(0), Part); 484 Value *TC = State.get(getOperand(1), Part); 485 Value *V = Builder.CreateICmpULE(IV, TC); 486 State.set(this, V, Part); 487 break; 488 } 489 case Instruction::Select: { 490 Value *Cond = State.get(getOperand(0), Part); 491 Value *Op1 = State.get(getOperand(1), Part); 492 Value *Op2 = State.get(getOperand(2), Part); 493 Value *V = Builder.CreateSelect(Cond, Op1, Op2); 494 State.set(this, V, Part); 495 break; 496 } 497 case VPInstruction::ActiveLaneMask: { 498 // Get first lane of vector induction variable. 499 Value *VIVElem0 = State.get(getOperand(0), VPIteration(Part, 0)); 500 // Get the original loop tripcount. 501 Value *ScalarTC = State.TripCount; 502 503 auto *Int1Ty = Type::getInt1Ty(Builder.getContext()); 504 auto *PredTy = FixedVectorType::get(Int1Ty, State.VF.getKnownMinValue()); 505 Instruction *Call = Builder.CreateIntrinsic( 506 Intrinsic::get_active_lane_mask, {PredTy, ScalarTC->getType()}, 507 {VIVElem0, ScalarTC}, nullptr, "active.lane.mask"); 508 State.set(this, Call, Part); 509 break; 510 } 511 default: 512 llvm_unreachable("Unsupported opcode for instruction"); 513 } 514 } 515 516 void VPInstruction::execute(VPTransformState &State) { 517 assert(!State.Instance && "VPInstruction executing an Instance"); 518 for (unsigned Part = 0; Part < State.UF; ++Part) 519 generateInstruction(State, Part); 520 } 521 522 void VPInstruction::dump() const { 523 VPSlotTracker SlotTracker(getParent()->getPlan()); 524 print(dbgs(), "", SlotTracker); 525 } 526 527 void VPInstruction::print(raw_ostream &O, const Twine &Indent, 528 VPSlotTracker &SlotTracker) const { 529 O << "EMIT "; 530 531 if (hasResult()) { 532 printAsOperand(O, SlotTracker); 533 O << " = "; 534 } 535 536 switch (getOpcode()) { 537 case VPInstruction::Not: 538 O << "not"; 539 break; 540 case VPInstruction::ICmpULE: 541 O << "icmp ule"; 542 break; 543 case VPInstruction::SLPLoad: 544 O << "combined load"; 545 break; 546 case VPInstruction::SLPStore: 547 O << "combined store"; 548 break; 549 case VPInstruction::ActiveLaneMask: 550 O << "active lane mask"; 551 break; 552 553 default: 554 O << Instruction::getOpcodeName(getOpcode()); 555 } 556 557 for (const VPValue *Operand : operands()) { 558 O << " "; 559 Operand->printAsOperand(O, SlotTracker); 560 } 561 } 562 563 /// Generate the code inside the body of the vectorized loop. Assumes a single 564 /// LoopVectorBody basic-block was created for this. Introduce additional 565 /// basic-blocks as needed, and fill them all. 566 void VPlan::execute(VPTransformState *State) { 567 // -1. Check if the backedge taken count is needed, and if so build it. 568 if (BackedgeTakenCount && BackedgeTakenCount->getNumUsers()) { 569 Value *TC = State->TripCount; 570 IRBuilder<> Builder(State->CFG.PrevBB->getTerminator()); 571 auto *TCMO = Builder.CreateSub(TC, ConstantInt::get(TC->getType(), 1), 572 "trip.count.minus.1"); 573 auto VF = State->VF; 574 Value *VTCMO = 575 VF.isScalar() ? TCMO : Builder.CreateVectorSplat(VF, TCMO, "broadcast"); 576 for (unsigned Part = 0, UF = State->UF; Part < UF; ++Part) 577 State->set(BackedgeTakenCount, VTCMO, Part); 578 } 579 580 // 0. Set the reverse mapping from VPValues to Values for code generation. 581 for (auto &Entry : Value2VPValue) 582 State->VPValue2Value[Entry.second] = Entry.first; 583 584 BasicBlock *VectorPreHeaderBB = State->CFG.PrevBB; 585 BasicBlock *VectorHeaderBB = VectorPreHeaderBB->getSingleSuccessor(); 586 assert(VectorHeaderBB && "Loop preheader does not have a single successor."); 587 588 // 1. Make room to generate basic-blocks inside loop body if needed. 589 BasicBlock *VectorLatchBB = VectorHeaderBB->splitBasicBlock( 590 VectorHeaderBB->getFirstInsertionPt(), "vector.body.latch"); 591 Loop *L = State->LI->getLoopFor(VectorHeaderBB); 592 L->addBasicBlockToLoop(VectorLatchBB, *State->LI); 593 // Remove the edge between Header and Latch to allow other connections. 594 // Temporarily terminate with unreachable until CFG is rewired. 595 // Note: this asserts the generated code's assumption that 596 // getFirstInsertionPt() can be dereferenced into an Instruction. 597 VectorHeaderBB->getTerminator()->eraseFromParent(); 598 State->Builder.SetInsertPoint(VectorHeaderBB); 599 UnreachableInst *Terminator = State->Builder.CreateUnreachable(); 600 State->Builder.SetInsertPoint(Terminator); 601 602 // 2. Generate code in loop body. 603 State->CFG.PrevVPBB = nullptr; 604 State->CFG.PrevBB = VectorHeaderBB; 605 State->CFG.LastBB = VectorLatchBB; 606 607 for (VPBlockBase *Block : depth_first(Entry)) 608 Block->execute(State); 609 610 // Setup branch terminator successors for VPBBs in VPBBsToFix based on 611 // VPBB's successors. 612 for (auto VPBB : State->CFG.VPBBsToFix) { 613 assert(EnableVPlanNativePath && 614 "Unexpected VPBBsToFix in non VPlan-native path"); 615 BasicBlock *BB = State->CFG.VPBB2IRBB[VPBB]; 616 assert(BB && "Unexpected null basic block for VPBB"); 617 618 unsigned Idx = 0; 619 auto *BBTerminator = BB->getTerminator(); 620 621 for (VPBlockBase *SuccVPBlock : VPBB->getHierarchicalSuccessors()) { 622 VPBasicBlock *SuccVPBB = SuccVPBlock->getEntryBasicBlock(); 623 BBTerminator->setSuccessor(Idx, State->CFG.VPBB2IRBB[SuccVPBB]); 624 ++Idx; 625 } 626 } 627 628 // 3. Merge the temporary latch created with the last basic-block filled. 629 BasicBlock *LastBB = State->CFG.PrevBB; 630 // Connect LastBB to VectorLatchBB to facilitate their merge. 631 assert((EnableVPlanNativePath || 632 isa<UnreachableInst>(LastBB->getTerminator())) && 633 "Expected InnerLoop VPlan CFG to terminate with unreachable"); 634 assert((!EnableVPlanNativePath || isa<BranchInst>(LastBB->getTerminator())) && 635 "Expected VPlan CFG to terminate with branch in NativePath"); 636 LastBB->getTerminator()->eraseFromParent(); 637 BranchInst::Create(VectorLatchBB, LastBB); 638 639 // Merge LastBB with Latch. 640 bool Merged = MergeBlockIntoPredecessor(VectorLatchBB, nullptr, State->LI); 641 (void)Merged; 642 assert(Merged && "Could not merge last basic block with latch."); 643 VectorLatchBB = LastBB; 644 645 // We do not attempt to preserve DT for outer loop vectorization currently. 646 if (!EnableVPlanNativePath) 647 updateDominatorTree(State->DT, VectorPreHeaderBB, VectorLatchBB, 648 L->getExitBlock()); 649 } 650 651 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 652 LLVM_DUMP_METHOD 653 void VPlan::dump() const { dbgs() << *this << '\n'; } 654 #endif 655 656 void VPlan::updateDominatorTree(DominatorTree *DT, BasicBlock *LoopPreHeaderBB, 657 BasicBlock *LoopLatchBB, 658 BasicBlock *LoopExitBB) { 659 BasicBlock *LoopHeaderBB = LoopPreHeaderBB->getSingleSuccessor(); 660 assert(LoopHeaderBB && "Loop preheader does not have a single successor."); 661 // The vector body may be more than a single basic-block by this point. 662 // Update the dominator tree information inside the vector body by propagating 663 // it from header to latch, expecting only triangular control-flow, if any. 664 BasicBlock *PostDomSucc = nullptr; 665 for (auto *BB = LoopHeaderBB; BB != LoopLatchBB; BB = PostDomSucc) { 666 // Get the list of successors of this block. 667 std::vector<BasicBlock *> Succs(succ_begin(BB), succ_end(BB)); 668 assert(Succs.size() <= 2 && 669 "Basic block in vector loop has more than 2 successors."); 670 PostDomSucc = Succs[0]; 671 if (Succs.size() == 1) { 672 assert(PostDomSucc->getSinglePredecessor() && 673 "PostDom successor has more than one predecessor."); 674 DT->addNewBlock(PostDomSucc, BB); 675 continue; 676 } 677 BasicBlock *InterimSucc = Succs[1]; 678 if (PostDomSucc->getSingleSuccessor() == InterimSucc) { 679 PostDomSucc = Succs[1]; 680 InterimSucc = Succs[0]; 681 } 682 assert(InterimSucc->getSingleSuccessor() == PostDomSucc && 683 "One successor of a basic block does not lead to the other."); 684 assert(InterimSucc->getSinglePredecessor() && 685 "Interim successor has more than one predecessor."); 686 assert(PostDomSucc->hasNPredecessors(2) && 687 "PostDom successor has more than two predecessors."); 688 DT->addNewBlock(InterimSucc, BB); 689 DT->addNewBlock(PostDomSucc, BB); 690 } 691 // Latch block is a new dominator for the loop exit. 692 DT->changeImmediateDominator(LoopExitBB, LoopLatchBB); 693 assert(DT->verify(DominatorTree::VerificationLevel::Fast)); 694 } 695 696 const Twine VPlanPrinter::getUID(const VPBlockBase *Block) { 697 return (isa<VPRegionBlock>(Block) ? "cluster_N" : "N") + 698 Twine(getOrCreateBID(Block)); 699 } 700 701 const Twine VPlanPrinter::getOrCreateName(const VPBlockBase *Block) { 702 const std::string &Name = Block->getName(); 703 if (!Name.empty()) 704 return Name; 705 return "VPB" + Twine(getOrCreateBID(Block)); 706 } 707 708 void VPlanPrinter::dump() { 709 Depth = 1; 710 bumpIndent(0); 711 OS << "digraph VPlan {\n"; 712 OS << "graph [labelloc=t, fontsize=30; label=\"Vectorization Plan"; 713 if (!Plan.getName().empty()) 714 OS << "\\n" << DOT::EscapeString(Plan.getName()); 715 if (Plan.BackedgeTakenCount) { 716 OS << ", where:\\n"; 717 Plan.BackedgeTakenCount->print(OS, SlotTracker); 718 OS << " := BackedgeTakenCount"; 719 } 720 OS << "\"]\n"; 721 OS << "node [shape=rect, fontname=Courier, fontsize=30]\n"; 722 OS << "edge [fontname=Courier, fontsize=30]\n"; 723 OS << "compound=true\n"; 724 725 for (const VPBlockBase *Block : depth_first(Plan.getEntry())) 726 dumpBlock(Block); 727 728 OS << "}\n"; 729 } 730 731 void VPlanPrinter::dumpBlock(const VPBlockBase *Block) { 732 if (const VPBasicBlock *BasicBlock = dyn_cast<VPBasicBlock>(Block)) 733 dumpBasicBlock(BasicBlock); 734 else if (const VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block)) 735 dumpRegion(Region); 736 else 737 llvm_unreachable("Unsupported kind of VPBlock."); 738 } 739 740 void VPlanPrinter::drawEdge(const VPBlockBase *From, const VPBlockBase *To, 741 bool Hidden, const Twine &Label) { 742 // Due to "dot" we print an edge between two regions as an edge between the 743 // exit basic block and the entry basic of the respective regions. 744 const VPBlockBase *Tail = From->getExitBasicBlock(); 745 const VPBlockBase *Head = To->getEntryBasicBlock(); 746 OS << Indent << getUID(Tail) << " -> " << getUID(Head); 747 OS << " [ label=\"" << Label << '\"'; 748 if (Tail != From) 749 OS << " ltail=" << getUID(From); 750 if (Head != To) 751 OS << " lhead=" << getUID(To); 752 if (Hidden) 753 OS << "; splines=none"; 754 OS << "]\n"; 755 } 756 757 void VPlanPrinter::dumpEdges(const VPBlockBase *Block) { 758 auto &Successors = Block->getSuccessors(); 759 if (Successors.size() == 1) 760 drawEdge(Block, Successors.front(), false, ""); 761 else if (Successors.size() == 2) { 762 drawEdge(Block, Successors.front(), false, "T"); 763 drawEdge(Block, Successors.back(), false, "F"); 764 } else { 765 unsigned SuccessorNumber = 0; 766 for (auto *Successor : Successors) 767 drawEdge(Block, Successor, false, Twine(SuccessorNumber++)); 768 } 769 } 770 771 void VPlanPrinter::dumpBasicBlock(const VPBasicBlock *BasicBlock) { 772 OS << Indent << getUID(BasicBlock) << " [label =\n"; 773 bumpIndent(1); 774 OS << Indent << "\"" << DOT::EscapeString(BasicBlock->getName()) << ":\\n\""; 775 bumpIndent(1); 776 777 // Dump the block predicate. 778 const VPValue *Pred = BasicBlock->getPredicate(); 779 if (Pred) { 780 OS << " +\n" << Indent << " \"BlockPredicate: \""; 781 if (const VPInstruction *PredI = dyn_cast<VPInstruction>(Pred)) { 782 PredI->printAsOperand(OS, SlotTracker); 783 OS << " (" << DOT::EscapeString(PredI->getParent()->getName()) 784 << ")\\l\""; 785 } else 786 Pred->printAsOperand(OS, SlotTracker); 787 } 788 789 for (const VPRecipeBase &Recipe : *BasicBlock) { 790 OS << " +\n" << Indent << "\""; 791 Recipe.print(OS, Indent, SlotTracker); 792 OS << "\\l\""; 793 } 794 795 // Dump the condition bit. 796 const VPValue *CBV = BasicBlock->getCondBit(); 797 if (CBV) { 798 OS << " +\n" << Indent << " \"CondBit: "; 799 if (const VPInstruction *CBI = dyn_cast<VPInstruction>(CBV)) { 800 CBI->printAsOperand(OS, SlotTracker); 801 OS << " (" << DOT::EscapeString(CBI->getParent()->getName()) << ")\\l\""; 802 } else { 803 CBV->printAsOperand(OS, SlotTracker); 804 OS << "\""; 805 } 806 } 807 808 bumpIndent(-2); 809 OS << "\n" << Indent << "]\n"; 810 dumpEdges(BasicBlock); 811 } 812 813 void VPlanPrinter::dumpRegion(const VPRegionBlock *Region) { 814 OS << Indent << "subgraph " << getUID(Region) << " {\n"; 815 bumpIndent(1); 816 OS << Indent << "fontname=Courier\n" 817 << Indent << "label=\"" 818 << DOT::EscapeString(Region->isReplicator() ? "<xVFxUF> " : "<x1> ") 819 << DOT::EscapeString(Region->getName()) << "\"\n"; 820 // Dump the blocks of the region. 821 assert(Region->getEntry() && "Region contains no inner blocks."); 822 for (const VPBlockBase *Block : depth_first(Region->getEntry())) 823 dumpBlock(Block); 824 bumpIndent(-1); 825 OS << Indent << "}\n"; 826 dumpEdges(Region); 827 } 828 829 void VPlanPrinter::printAsIngredient(raw_ostream &O, const Value *V) { 830 std::string IngredientString; 831 raw_string_ostream RSO(IngredientString); 832 if (auto *Inst = dyn_cast<Instruction>(V)) { 833 if (!Inst->getType()->isVoidTy()) { 834 Inst->printAsOperand(RSO, false); 835 RSO << " = "; 836 } 837 RSO << Inst->getOpcodeName() << " "; 838 unsigned E = Inst->getNumOperands(); 839 if (E > 0) { 840 Inst->getOperand(0)->printAsOperand(RSO, false); 841 for (unsigned I = 1; I < E; ++I) 842 Inst->getOperand(I)->printAsOperand(RSO << ", ", false); 843 } 844 } else // !Inst 845 V->printAsOperand(RSO, false); 846 RSO.flush(); 847 O << DOT::EscapeString(IngredientString); 848 } 849 850 void VPWidenCallRecipe::print(raw_ostream &O, const Twine &Indent, 851 VPSlotTracker &SlotTracker) const { 852 O << "WIDEN-CALL "; 853 854 auto *CI = cast<CallInst>(getUnderlyingInstr()); 855 if (CI->getType()->isVoidTy()) 856 O << "void "; 857 else { 858 printAsOperand(O, SlotTracker); 859 O << " = "; 860 } 861 862 O << "call @" << CI->getCalledFunction()->getName() << "("; 863 printOperands(O, SlotTracker); 864 O << ")"; 865 } 866 867 void VPWidenSelectRecipe::print(raw_ostream &O, const Twine &Indent, 868 VPSlotTracker &SlotTracker) const { 869 O << "WIDEN-SELECT "; 870 printAsOperand(O, SlotTracker); 871 O << " = select "; 872 getOperand(0)->printAsOperand(O, SlotTracker); 873 O << ", "; 874 getOperand(1)->printAsOperand(O, SlotTracker); 875 O << ", "; 876 getOperand(2)->printAsOperand(O, SlotTracker); 877 O << (InvariantCond ? " (condition is loop invariant)" : ""); 878 } 879 880 void VPWidenRecipe::print(raw_ostream &O, const Twine &Indent, 881 VPSlotTracker &SlotTracker) const { 882 O << "WIDEN "; 883 printAsOperand(O, SlotTracker); 884 O << " = " << getUnderlyingInstr()->getOpcodeName() << " "; 885 printOperands(O, SlotTracker); 886 } 887 888 void VPWidenIntOrFpInductionRecipe::print(raw_ostream &O, const Twine &Indent, 889 VPSlotTracker &SlotTracker) const { 890 O << "WIDEN-INDUCTION"; 891 if (Trunc) { 892 O << "\\l\""; 893 O << " +\n" << Indent << "\" " << VPlanIngredient(IV) << "\\l\""; 894 O << " +\n" << Indent << "\" " << VPlanIngredient(Trunc); 895 } else 896 O << " " << VPlanIngredient(IV); 897 } 898 899 void VPWidenGEPRecipe::print(raw_ostream &O, const Twine &Indent, 900 VPSlotTracker &SlotTracker) const { 901 O << "WIDEN-GEP "; 902 O << (IsPtrLoopInvariant ? "Inv" : "Var"); 903 size_t IndicesNumber = IsIndexLoopInvariant.size(); 904 for (size_t I = 0; I < IndicesNumber; ++I) 905 O << "[" << (IsIndexLoopInvariant[I] ? "Inv" : "Var") << "]"; 906 907 O << " "; 908 printAsOperand(O, SlotTracker); 909 O << " = getelementptr "; 910 printOperands(O, SlotTracker); 911 } 912 913 void VPWidenPHIRecipe::print(raw_ostream &O, const Twine &Indent, 914 VPSlotTracker &SlotTracker) const { 915 O << "WIDEN-PHI " << VPlanIngredient(Phi); 916 } 917 918 void VPBlendRecipe::print(raw_ostream &O, const Twine &Indent, 919 VPSlotTracker &SlotTracker) const { 920 O << "BLEND "; 921 Phi->printAsOperand(O, false); 922 O << " ="; 923 if (getNumIncomingValues() == 1) { 924 // Not a User of any mask: not really blending, this is a 925 // single-predecessor phi. 926 O << " "; 927 getIncomingValue(0)->printAsOperand(O, SlotTracker); 928 } else { 929 for (unsigned I = 0, E = getNumIncomingValues(); I < E; ++I) { 930 O << " "; 931 getIncomingValue(I)->printAsOperand(O, SlotTracker); 932 O << "/"; 933 getMask(I)->printAsOperand(O, SlotTracker); 934 } 935 } 936 } 937 938 void VPReductionRecipe::print(raw_ostream &O, const Twine &Indent, 939 VPSlotTracker &SlotTracker) const { 940 O << "REDUCE "; 941 printAsOperand(O, SlotTracker); 942 O << " = "; 943 getChainOp()->printAsOperand(O, SlotTracker); 944 O << " + reduce." << Instruction::getOpcodeName(RdxDesc->getOpcode()) 945 << " ("; 946 getVecOp()->printAsOperand(O, SlotTracker); 947 if (getCondOp()) { 948 O << ", "; 949 getCondOp()->printAsOperand(O, SlotTracker); 950 } 951 O << ")"; 952 } 953 954 void VPReplicateRecipe::print(raw_ostream &O, const Twine &Indent, 955 VPSlotTracker &SlotTracker) const { 956 O << (IsUniform ? "CLONE " : "REPLICATE "); 957 958 if (!getUnderlyingInstr()->getType()->isVoidTy()) { 959 printAsOperand(O, SlotTracker); 960 O << " = "; 961 } 962 O << Instruction::getOpcodeName(getUnderlyingInstr()->getOpcode()) << " "; 963 printOperands(O, SlotTracker); 964 965 if (AlsoPack) 966 O << " (S->V)"; 967 } 968 969 void VPPredInstPHIRecipe::print(raw_ostream &O, const Twine &Indent, 970 VPSlotTracker &SlotTracker) const { 971 O << "PHI-PREDICATED-INSTRUCTION "; 972 printOperands(O, SlotTracker); 973 } 974 975 void VPWidenMemoryInstructionRecipe::print(raw_ostream &O, const Twine &Indent, 976 VPSlotTracker &SlotTracker) const { 977 O << "WIDEN "; 978 979 if (!isStore()) { 980 getVPValue()->printAsOperand(O, SlotTracker); 981 O << " = "; 982 } 983 O << Instruction::getOpcodeName(Ingredient.getOpcode()) << " "; 984 985 printOperands(O, SlotTracker); 986 } 987 988 void VPWidenCanonicalIVRecipe::execute(VPTransformState &State) { 989 Value *CanonicalIV = State.CanonicalIV; 990 Type *STy = CanonicalIV->getType(); 991 IRBuilder<> Builder(State.CFG.PrevBB->getTerminator()); 992 ElementCount VF = State.VF; 993 assert(!VF.isScalable() && "the code following assumes non scalables ECs"); 994 Value *VStart = VF.isScalar() 995 ? CanonicalIV 996 : Builder.CreateVectorSplat(VF.getKnownMinValue(), 997 CanonicalIV, "broadcast"); 998 for (unsigned Part = 0, UF = State.UF; Part < UF; ++Part) { 999 SmallVector<Constant *, 8> Indices; 1000 for (unsigned Lane = 0; Lane < VF.getKnownMinValue(); ++Lane) 1001 Indices.push_back( 1002 ConstantInt::get(STy, Part * VF.getKnownMinValue() + Lane)); 1003 // If VF == 1, there is only one iteration in the loop above, thus the 1004 // element pushed back into Indices is ConstantInt::get(STy, Part) 1005 Constant *VStep = 1006 VF.isScalar() ? Indices.back() : ConstantVector::get(Indices); 1007 // Add the consecutive indices to the vector value. 1008 Value *CanonicalVectorIV = Builder.CreateAdd(VStart, VStep, "vec.iv"); 1009 State.set(getVPValue(), CanonicalVectorIV, Part); 1010 } 1011 } 1012 1013 void VPWidenCanonicalIVRecipe::print(raw_ostream &O, const Twine &Indent, 1014 VPSlotTracker &SlotTracker) const { 1015 O << "EMIT "; 1016 getVPValue()->printAsOperand(O, SlotTracker); 1017 O << " = WIDEN-CANONICAL-INDUCTION"; 1018 } 1019 1020 template void DomTreeBuilder::Calculate<VPDominatorTree>(VPDominatorTree &DT); 1021 1022 void VPValue::replaceAllUsesWith(VPValue *New) { 1023 for (unsigned J = 0; J < getNumUsers();) { 1024 VPUser *User = Users[J]; 1025 unsigned NumUsers = getNumUsers(); 1026 for (unsigned I = 0, E = User->getNumOperands(); I < E; ++I) 1027 if (User->getOperand(I) == this) 1028 User->setOperand(I, New); 1029 // If a user got removed after updating the current user, the next user to 1030 // update will be moved to the current position, so we only need to 1031 // increment the index if the number of users did not change. 1032 if (NumUsers == getNumUsers()) 1033 J++; 1034 } 1035 } 1036 1037 void VPValue::printAsOperand(raw_ostream &OS, VPSlotTracker &Tracker) const { 1038 if (const Value *UV = getUnderlyingValue()) { 1039 OS << "ir<"; 1040 UV->printAsOperand(OS, false); 1041 OS << ">"; 1042 return; 1043 } 1044 1045 unsigned Slot = Tracker.getSlot(this); 1046 if (Slot == unsigned(-1)) 1047 OS << "<badref>"; 1048 else 1049 OS << "vp<%" << Tracker.getSlot(this) << ">"; 1050 } 1051 1052 void VPUser::printOperands(raw_ostream &O, VPSlotTracker &SlotTracker) const { 1053 interleaveComma(operands(), O, [&O, &SlotTracker](VPValue *Op) { 1054 Op->printAsOperand(O, SlotTracker); 1055 }); 1056 } 1057 1058 void VPInterleavedAccessInfo::visitRegion(VPRegionBlock *Region, 1059 Old2NewTy &Old2New, 1060 InterleavedAccessInfo &IAI) { 1061 ReversePostOrderTraversal<VPBlockBase *> RPOT(Region->getEntry()); 1062 for (VPBlockBase *Base : RPOT) { 1063 visitBlock(Base, Old2New, IAI); 1064 } 1065 } 1066 1067 void VPInterleavedAccessInfo::visitBlock(VPBlockBase *Block, Old2NewTy &Old2New, 1068 InterleavedAccessInfo &IAI) { 1069 if (VPBasicBlock *VPBB = dyn_cast<VPBasicBlock>(Block)) { 1070 for (VPRecipeBase &VPI : *VPBB) { 1071 assert(isa<VPInstruction>(&VPI) && "Can only handle VPInstructions"); 1072 auto *VPInst = cast<VPInstruction>(&VPI); 1073 auto *Inst = cast<Instruction>(VPInst->getUnderlyingValue()); 1074 auto *IG = IAI.getInterleaveGroup(Inst); 1075 if (!IG) 1076 continue; 1077 1078 auto NewIGIter = Old2New.find(IG); 1079 if (NewIGIter == Old2New.end()) 1080 Old2New[IG] = new InterleaveGroup<VPInstruction>( 1081 IG->getFactor(), IG->isReverse(), IG->getAlign()); 1082 1083 if (Inst == IG->getInsertPos()) 1084 Old2New[IG]->setInsertPos(VPInst); 1085 1086 InterleaveGroupMap[VPInst] = Old2New[IG]; 1087 InterleaveGroupMap[VPInst]->insertMember( 1088 VPInst, IG->getIndex(Inst), 1089 Align(IG->isReverse() ? (-1) * int(IG->getFactor()) 1090 : IG->getFactor())); 1091 } 1092 } else if (VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block)) 1093 visitRegion(Region, Old2New, IAI); 1094 else 1095 llvm_unreachable("Unsupported kind of VPBlock."); 1096 } 1097 1098 VPInterleavedAccessInfo::VPInterleavedAccessInfo(VPlan &Plan, 1099 InterleavedAccessInfo &IAI) { 1100 Old2NewTy Old2New; 1101 visitRegion(cast<VPRegionBlock>(Plan.getEntry()), Old2New, IAI); 1102 } 1103 1104 void VPSlotTracker::assignSlot(const VPValue *V) { 1105 assert(Slots.find(V) == Slots.end() && "VPValue already has a slot!"); 1106 Slots[V] = NextSlot++; 1107 } 1108 1109 void VPSlotTracker::assignSlots(const VPBlockBase *VPBB) { 1110 if (auto *Region = dyn_cast<VPRegionBlock>(VPBB)) 1111 assignSlots(Region); 1112 else 1113 assignSlots(cast<VPBasicBlock>(VPBB)); 1114 } 1115 1116 void VPSlotTracker::assignSlots(const VPRegionBlock *Region) { 1117 ReversePostOrderTraversal<const VPBlockBase *> RPOT(Region->getEntry()); 1118 for (const VPBlockBase *Block : RPOT) 1119 assignSlots(Block); 1120 } 1121 1122 void VPSlotTracker::assignSlots(const VPBasicBlock *VPBB) { 1123 for (const VPRecipeBase &Recipe : *VPBB) { 1124 for (VPValue *Def : Recipe.definedValues()) 1125 assignSlot(Def); 1126 } 1127 } 1128 1129 void VPSlotTracker::assignSlots(const VPlan &Plan) { 1130 1131 for (const VPValue *V : Plan.VPExternalDefs) 1132 assignSlot(V); 1133 1134 for (const VPValue *V : Plan.VPCBVs) 1135 assignSlot(V); 1136 1137 if (Plan.BackedgeTakenCount) 1138 assignSlot(Plan.BackedgeTakenCount); 1139 1140 ReversePostOrderTraversal<const VPBlockBase *> RPOT(Plan.getEntry()); 1141 for (const VPBlockBase *Block : RPOT) 1142 assignSlots(Block); 1143 } 1144