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