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