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