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/IRBuilder.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 "llvm/Transforms/Utils/ScalarEvolutionExpander.h" 44 #include <cassert> 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 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 54 raw_ostream &llvm::operator<<(raw_ostream &OS, const VPValue &V) { 55 const VPInstruction *Instr = dyn_cast<VPInstruction>(&V); 56 VPSlotTracker SlotTracker( 57 (Instr && Instr->getParent()) ? Instr->getParent()->getPlan() : nullptr); 58 V.print(OS, SlotTracker); 59 return OS; 60 } 61 #endif 62 63 Value *VPLane::getAsRuntimeExpr(IRBuilderBase &Builder, 64 const ElementCount &VF) const { 65 switch (LaneKind) { 66 case VPLane::Kind::ScalableLast: 67 // Lane = RuntimeVF - VF.getKnownMinValue() + Lane 68 return Builder.CreateSub(getRuntimeVF(Builder, Builder.getInt32Ty(), VF), 69 Builder.getInt32(VF.getKnownMinValue() - Lane)); 70 case VPLane::Kind::First: 71 return Builder.getInt32(Lane); 72 } 73 llvm_unreachable("Unknown lane kind"); 74 } 75 76 VPValue::VPValue(const unsigned char SC, Value *UV, VPDef *Def) 77 : SubclassID(SC), UnderlyingVal(UV), Def(Def) { 78 if (Def) 79 Def->addDefinedValue(this); 80 } 81 82 VPValue::~VPValue() { 83 assert(Users.empty() && "trying to delete a VPValue with remaining users"); 84 if (Def) 85 Def->removeDefinedValue(this); 86 } 87 88 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 89 void VPValue::print(raw_ostream &OS, VPSlotTracker &SlotTracker) const { 90 if (const VPRecipeBase *R = dyn_cast_or_null<VPRecipeBase>(Def)) 91 R->print(OS, "", SlotTracker); 92 else 93 printAsOperand(OS, SlotTracker); 94 } 95 96 void VPValue::dump() const { 97 const VPRecipeBase *Instr = dyn_cast_or_null<VPRecipeBase>(this->Def); 98 VPSlotTracker SlotTracker( 99 (Instr && Instr->getParent()) ? Instr->getParent()->getPlan() : nullptr); 100 print(dbgs(), SlotTracker); 101 dbgs() << "\n"; 102 } 103 104 void VPDef::dump() const { 105 const VPRecipeBase *Instr = dyn_cast_or_null<VPRecipeBase>(this); 106 VPSlotTracker SlotTracker( 107 (Instr && Instr->getParent()) ? Instr->getParent()->getPlan() : nullptr); 108 print(dbgs(), "", SlotTracker); 109 dbgs() << "\n"; 110 } 111 #endif 112 113 // Get the top-most entry block of \p Start. This is the entry block of the 114 // containing VPlan. This function is templated to support both const and non-const blocks 115 template <typename T> static T *getPlanEntry(T *Start) { 116 T *Next = Start; 117 T *Current = Start; 118 while ((Next = Next->getParent())) 119 Current = Next; 120 121 SmallSetVector<T *, 8> WorkList; 122 WorkList.insert(Current); 123 124 for (unsigned i = 0; i < WorkList.size(); i++) { 125 T *Current = WorkList[i]; 126 if (Current->getNumPredecessors() == 0) 127 return Current; 128 auto &Predecessors = Current->getPredecessors(); 129 WorkList.insert(Predecessors.begin(), Predecessors.end()); 130 } 131 132 llvm_unreachable("VPlan without any entry node without predecessors"); 133 } 134 135 VPlan *VPBlockBase::getPlan() { return getPlanEntry(this)->Plan; } 136 137 const VPlan *VPBlockBase::getPlan() const { return getPlanEntry(this)->Plan; } 138 139 /// \return the VPBasicBlock that is the entry of Block, possibly indirectly. 140 const VPBasicBlock *VPBlockBase::getEntryBasicBlock() const { 141 const VPBlockBase *Block = this; 142 while (const VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block)) 143 Block = Region->getEntry(); 144 return cast<VPBasicBlock>(Block); 145 } 146 147 VPBasicBlock *VPBlockBase::getEntryBasicBlock() { 148 VPBlockBase *Block = this; 149 while (VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block)) 150 Block = Region->getEntry(); 151 return cast<VPBasicBlock>(Block); 152 } 153 154 void VPBlockBase::setPlan(VPlan *ParentPlan) { 155 assert(ParentPlan->getEntry() == this && 156 "Can only set plan on its entry block."); 157 Plan = ParentPlan; 158 } 159 160 /// \return the VPBasicBlock that is the exit of Block, possibly indirectly. 161 const VPBasicBlock *VPBlockBase::getExitBasicBlock() const { 162 const VPBlockBase *Block = this; 163 while (const VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block)) 164 Block = Region->getExit(); 165 return cast<VPBasicBlock>(Block); 166 } 167 168 VPBasicBlock *VPBlockBase::getExitBasicBlock() { 169 VPBlockBase *Block = this; 170 while (VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block)) 171 Block = Region->getExit(); 172 return cast<VPBasicBlock>(Block); 173 } 174 175 VPBlockBase *VPBlockBase::getEnclosingBlockWithSuccessors() { 176 if (!Successors.empty() || !Parent) 177 return this; 178 assert(Parent->getExit() == this && 179 "Block w/o successors not the exit of its parent."); 180 return Parent->getEnclosingBlockWithSuccessors(); 181 } 182 183 VPBlockBase *VPBlockBase::getEnclosingBlockWithPredecessors() { 184 if (!Predecessors.empty() || !Parent) 185 return this; 186 assert(Parent->getEntry() == this && 187 "Block w/o predecessors not the entry of its parent."); 188 return Parent->getEnclosingBlockWithPredecessors(); 189 } 190 191 VPValue *VPBlockBase::getCondBit() { 192 return CondBitUser.getSingleOperandOrNull(); 193 } 194 195 const VPValue *VPBlockBase::getCondBit() const { 196 return CondBitUser.getSingleOperandOrNull(); 197 } 198 199 void VPBlockBase::setCondBit(VPValue *CV) { CondBitUser.resetSingleOpUser(CV); } 200 201 VPValue *VPBlockBase::getPredicate() { 202 return PredicateUser.getSingleOperandOrNull(); 203 } 204 205 const VPValue *VPBlockBase::getPredicate() const { 206 return PredicateUser.getSingleOperandOrNull(); 207 } 208 209 void VPBlockBase::setPredicate(VPValue *CV) { 210 PredicateUser.resetSingleOpUser(CV); 211 } 212 213 void VPBlockBase::deleteCFG(VPBlockBase *Entry) { 214 SmallVector<VPBlockBase *, 8> Blocks(depth_first(Entry)); 215 216 for (VPBlockBase *Block : Blocks) 217 delete Block; 218 } 219 220 VPBasicBlock::iterator VPBasicBlock::getFirstNonPhi() { 221 iterator It = begin(); 222 while (It != end() && It->isPhi()) 223 It++; 224 return It; 225 } 226 227 Value *VPTransformState::get(VPValue *Def, const VPIteration &Instance) { 228 if (!Def->getDef()) 229 return Def->getLiveInIRValue(); 230 231 if (hasScalarValue(Def, Instance)) { 232 return Data 233 .PerPartScalars[Def][Instance.Part][Instance.Lane.mapToCacheIndex(VF)]; 234 } 235 236 assert(hasVectorValue(Def, Instance.Part)); 237 auto *VecPart = Data.PerPartOutput[Def][Instance.Part]; 238 if (!VecPart->getType()->isVectorTy()) { 239 assert(Instance.Lane.isFirstLane() && "cannot get lane > 0 for scalar"); 240 return VecPart; 241 } 242 // TODO: Cache created scalar values. 243 Value *Lane = Instance.Lane.getAsRuntimeExpr(Builder, VF); 244 auto *Extract = Builder.CreateExtractElement(VecPart, Lane); 245 // set(Def, Extract, Instance); 246 return Extract; 247 } 248 249 BasicBlock * 250 VPBasicBlock::createEmptyBasicBlock(VPTransformState::CFGState &CFG) { 251 // BB stands for IR BasicBlocks. VPBB stands for VPlan VPBasicBlocks. 252 // Pred stands for Predessor. Prev stands for Previous - last visited/created. 253 BasicBlock *PrevBB = CFG.PrevBB; 254 BasicBlock *NewBB = BasicBlock::Create(PrevBB->getContext(), getName(), 255 PrevBB->getParent(), CFG.ExitBB); 256 LLVM_DEBUG(dbgs() << "LV: created " << NewBB->getName() << '\n'); 257 258 // Hook up the new basic block to its predecessors. 259 for (VPBlockBase *PredVPBlock : getHierarchicalPredecessors()) { 260 VPBasicBlock *PredVPBB = PredVPBlock->getExitBasicBlock(); 261 auto &PredVPSuccessors = PredVPBB->getSuccessors(); 262 BasicBlock *PredBB = CFG.VPBB2IRBB[PredVPBB]; 263 264 // In outer loop vectorization scenario, the predecessor BBlock may not yet 265 // be visited(backedge). Mark the VPBasicBlock for fixup at the end of 266 // vectorization. We do not encounter this case in inner loop vectorization 267 // as we start out by building a loop skeleton with the vector loop header 268 // and latch blocks. As a result, we never enter this function for the 269 // header block in the non VPlan-native path. 270 if (!PredBB) { 271 assert(EnableVPlanNativePath && 272 "Unexpected null predecessor in non VPlan-native path"); 273 CFG.VPBBsToFix.push_back(PredVPBB); 274 continue; 275 } 276 277 assert(PredBB && "Predecessor basic-block not found building successor."); 278 auto *PredBBTerminator = PredBB->getTerminator(); 279 LLVM_DEBUG(dbgs() << "LV: draw edge from" << PredBB->getName() << '\n'); 280 if (isa<UnreachableInst>(PredBBTerminator)) { 281 assert(PredVPSuccessors.size() == 1 && 282 "Predecessor ending w/o branch must have single successor."); 283 PredBBTerminator->eraseFromParent(); 284 BranchInst::Create(NewBB, PredBB); 285 } else { 286 assert(PredVPSuccessors.size() == 2 && 287 "Predecessor ending with branch must have two successors."); 288 unsigned idx = PredVPSuccessors.front() == this ? 0 : 1; 289 assert(!PredBBTerminator->getSuccessor(idx) && 290 "Trying to reset an existing successor block."); 291 PredBBTerminator->setSuccessor(idx, NewBB); 292 } 293 } 294 return NewBB; 295 } 296 297 void VPBasicBlock::execute(VPTransformState *State) { 298 bool Replica = State->Instance && !State->Instance->isFirstIteration(); 299 VPBasicBlock *PrevVPBB = State->CFG.PrevVPBB; 300 VPBlockBase *SingleHPred = nullptr; 301 BasicBlock *NewBB = State->CFG.PrevBB; // Reuse it if possible. 302 303 // 1. Create an IR basic block, or reuse the last one if possible. 304 // The last IR basic block is reused, as an optimization, in three cases: 305 // A. the first VPBB reuses the loop header BB - when PrevVPBB is null; 306 // B. when the current VPBB has a single (hierarchical) predecessor which 307 // is PrevVPBB and the latter has a single (hierarchical) successor; and 308 // C. when the current VPBB is an entry of a region replica - where PrevVPBB 309 // is the exit of this region from a previous instance, or the predecessor 310 // of this region. 311 if (PrevVPBB && /* A */ 312 !((SingleHPred = getSingleHierarchicalPredecessor()) && 313 SingleHPred->getExitBasicBlock() == PrevVPBB && 314 PrevVPBB->getSingleHierarchicalSuccessor()) && /* B */ 315 !(Replica && getPredecessors().empty())) { /* C */ 316 NewBB = createEmptyBasicBlock(State->CFG); 317 State->Builder.SetInsertPoint(NewBB); 318 // Temporarily terminate with unreachable until CFG is rewired. 319 UnreachableInst *Terminator = State->Builder.CreateUnreachable(); 320 State->Builder.SetInsertPoint(Terminator); 321 State->CFG.PrevBB = NewBB; 322 } 323 324 if (State->CurrentVectorLoop && 325 !State->CurrentVectorLoop->contains(State->CFG.PrevBB)) { 326 // Register NewBB in its loop. In innermost loops its the same for all BB's. 327 State->CurrentVectorLoop->addBasicBlockToLoop(State->CFG.PrevBB, 328 *State->LI); 329 } 330 331 // 2. Fill the IR basic block with IR instructions. 332 LLVM_DEBUG(dbgs() << "LV: vectorizing VPBB:" << getName() 333 << " in BB:" << NewBB->getName() << '\n'); 334 335 State->CFG.VPBB2IRBB[this] = NewBB; 336 State->CFG.PrevVPBB = this; 337 338 for (VPRecipeBase &Recipe : Recipes) 339 Recipe.execute(*State); 340 341 VPValue *CBV; 342 if (EnableVPlanNativePath && (CBV = getCondBit())) { 343 assert(CBV->getUnderlyingValue() && 344 "Unexpected null underlying value for condition bit"); 345 346 // Condition bit value in a VPBasicBlock is used as the branch selector. In 347 // the VPlan-native path case, since all branches are uniform we generate a 348 // branch instruction using the condition value from vector lane 0 and dummy 349 // successors. The successors are fixed later when the successor blocks are 350 // visited. 351 Value *NewCond = State->get(CBV, {0, 0}); 352 353 // Replace the temporary unreachable terminator with the new conditional 354 // branch. 355 auto *CurrentTerminator = NewBB->getTerminator(); 356 assert(isa<UnreachableInst>(CurrentTerminator) && 357 "Expected to replace unreachable terminator with conditional " 358 "branch."); 359 auto *CondBr = BranchInst::Create(NewBB, nullptr, NewCond); 360 CondBr->setSuccessor(0, nullptr); 361 ReplaceInstWithInst(CurrentTerminator, CondBr); 362 } 363 364 LLVM_DEBUG(dbgs() << "LV: filled BB:" << *NewBB); 365 } 366 367 void VPBasicBlock::dropAllReferences(VPValue *NewValue) { 368 for (VPRecipeBase &R : Recipes) { 369 for (auto *Def : R.definedValues()) 370 Def->replaceAllUsesWith(NewValue); 371 372 for (unsigned I = 0, E = R.getNumOperands(); I != E; I++) 373 R.setOperand(I, NewValue); 374 } 375 } 376 377 VPBasicBlock *VPBasicBlock::splitAt(iterator SplitAt) { 378 assert((SplitAt == end() || SplitAt->getParent() == this) && 379 "can only split at a position in the same block"); 380 381 SmallVector<VPBlockBase *, 2> Succs(successors()); 382 // First, disconnect the current block from its successors. 383 for (VPBlockBase *Succ : Succs) 384 VPBlockUtils::disconnectBlocks(this, Succ); 385 386 // Create new empty block after the block to split. 387 auto *SplitBlock = new VPBasicBlock(getName() + ".split"); 388 VPBlockUtils::insertBlockAfter(SplitBlock, this); 389 390 // Add successors for block to split to new block. 391 for (VPBlockBase *Succ : Succs) 392 VPBlockUtils::connectBlocks(SplitBlock, Succ); 393 394 // Finally, move the recipes starting at SplitAt to new block. 395 for (VPRecipeBase &ToMove : 396 make_early_inc_range(make_range(SplitAt, this->end()))) 397 ToMove.moveBefore(*SplitBlock, SplitBlock->end()); 398 399 return SplitBlock; 400 } 401 402 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 403 void VPBlockBase::printSuccessors(raw_ostream &O, const Twine &Indent) const { 404 if (getSuccessors().empty()) { 405 O << Indent << "No successors\n"; 406 } else { 407 O << Indent << "Successor(s): "; 408 ListSeparator LS; 409 for (auto *Succ : getSuccessors()) 410 O << LS << Succ->getName(); 411 O << '\n'; 412 } 413 } 414 415 void VPBasicBlock::print(raw_ostream &O, const Twine &Indent, 416 VPSlotTracker &SlotTracker) const { 417 O << Indent << getName() << ":\n"; 418 if (const VPValue *Pred = getPredicate()) { 419 O << Indent << "BlockPredicate:"; 420 Pred->printAsOperand(O, SlotTracker); 421 if (const auto *PredInst = dyn_cast<VPInstruction>(Pred)) 422 O << " (" << PredInst->getParent()->getName() << ")"; 423 O << '\n'; 424 } 425 426 auto RecipeIndent = Indent + " "; 427 for (const VPRecipeBase &Recipe : *this) { 428 Recipe.print(O, RecipeIndent, SlotTracker); 429 O << '\n'; 430 } 431 432 printSuccessors(O, Indent); 433 434 if (const VPValue *CBV = getCondBit()) { 435 O << Indent << "CondBit: "; 436 CBV->printAsOperand(O, SlotTracker); 437 if (const auto *CBI = dyn_cast<VPInstruction>(CBV)) 438 O << " (" << CBI->getParent()->getName() << ")"; 439 O << '\n'; 440 } 441 } 442 #endif 443 444 void VPRegionBlock::dropAllReferences(VPValue *NewValue) { 445 for (VPBlockBase *Block : depth_first(Entry)) 446 // Drop all references in VPBasicBlocks and replace all uses with 447 // DummyValue. 448 Block->dropAllReferences(NewValue); 449 } 450 451 void VPRegionBlock::execute(VPTransformState *State) { 452 ReversePostOrderTraversal<VPBlockBase *> RPOT(Entry); 453 454 if (!isReplicator()) { 455 // Create and register the new vector loop. 456 Loop *PrevLoop = State->CurrentVectorLoop; 457 State->CurrentVectorLoop = State->LI->AllocateLoop(); 458 Loop *ParentLoop = State->LI->getLoopFor(State->CFG.VectorPreHeader); 459 460 // Insert the new loop into the loop nest and register the new basic blocks 461 // before calling any utilities such as SCEV that require valid LoopInfo. 462 if (ParentLoop) 463 ParentLoop->addChildLoop(State->CurrentVectorLoop); 464 else 465 State->LI->addTopLevelLoop(State->CurrentVectorLoop); 466 467 // Visit the VPBlocks connected to "this", starting from it. 468 for (VPBlockBase *Block : RPOT) { 469 if (EnableVPlanNativePath) { 470 // The inner loop vectorization path does not represent loop preheader 471 // and exit blocks as part of the VPlan. In the VPlan-native path, skip 472 // vectorizing loop preheader block. In future, we may replace this 473 // check with the check for loop preheader. 474 if (Block->getNumPredecessors() == 0) 475 continue; 476 477 // Skip vectorizing loop exit block. In future, we may replace this 478 // check with the check for loop exit. 479 if (Block->getNumSuccessors() == 0) 480 continue; 481 } 482 483 LLVM_DEBUG(dbgs() << "LV: VPBlock in RPO " << Block->getName() << '\n'); 484 Block->execute(State); 485 } 486 487 State->CurrentVectorLoop = PrevLoop; 488 return; 489 } 490 491 assert(!State->Instance && "Replicating a Region with non-null instance."); 492 493 // Enter replicating mode. 494 State->Instance = VPIteration(0, 0); 495 496 for (unsigned Part = 0, UF = State->UF; Part < UF; ++Part) { 497 State->Instance->Part = Part; 498 assert(!State->VF.isScalable() && "VF is assumed to be non scalable."); 499 for (unsigned Lane = 0, VF = State->VF.getKnownMinValue(); Lane < VF; 500 ++Lane) { 501 State->Instance->Lane = VPLane(Lane, VPLane::Kind::First); 502 // Visit the VPBlocks connected to \p this, starting from it. 503 for (VPBlockBase *Block : RPOT) { 504 LLVM_DEBUG(dbgs() << "LV: VPBlock in RPO " << Block->getName() << '\n'); 505 Block->execute(State); 506 } 507 } 508 } 509 510 // Exit replicating mode. 511 State->Instance.reset(); 512 } 513 514 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 515 void VPRegionBlock::print(raw_ostream &O, const Twine &Indent, 516 VPSlotTracker &SlotTracker) const { 517 O << Indent << (isReplicator() ? "<xVFxUF> " : "<x1> ") << getName() << ": {"; 518 auto NewIndent = Indent + " "; 519 for (auto *BlockBase : depth_first(Entry)) { 520 O << '\n'; 521 BlockBase->print(O, NewIndent, SlotTracker); 522 } 523 O << Indent << "}\n"; 524 525 printSuccessors(O, Indent); 526 } 527 #endif 528 529 bool VPRecipeBase::mayWriteToMemory() const { 530 switch (getVPDefID()) { 531 case VPWidenMemoryInstructionSC: { 532 return cast<VPWidenMemoryInstructionRecipe>(this)->isStore(); 533 } 534 case VPReplicateSC: 535 case VPWidenCallSC: 536 return cast<Instruction>(getVPSingleValue()->getUnderlyingValue()) 537 ->mayWriteToMemory(); 538 case VPBranchOnMaskSC: 539 return false; 540 case VPWidenIntOrFpInductionSC: 541 case VPWidenCanonicalIVSC: 542 case VPWidenPHISC: 543 case VPBlendSC: 544 case VPWidenSC: 545 case VPWidenGEPSC: 546 case VPReductionSC: 547 case VPWidenSelectSC: { 548 const Instruction *I = 549 dyn_cast_or_null<Instruction>(getVPSingleValue()->getUnderlyingValue()); 550 (void)I; 551 assert((!I || !I->mayWriteToMemory()) && 552 "underlying instruction may write to memory"); 553 return false; 554 } 555 default: 556 return true; 557 } 558 } 559 560 bool VPRecipeBase::mayReadFromMemory() const { 561 switch (getVPDefID()) { 562 case VPWidenMemoryInstructionSC: { 563 return !cast<VPWidenMemoryInstructionRecipe>(this)->isStore(); 564 } 565 case VPReplicateSC: 566 case VPWidenCallSC: 567 return cast<Instruction>(getVPSingleValue()->getUnderlyingValue()) 568 ->mayReadFromMemory(); 569 case VPBranchOnMaskSC: 570 return false; 571 case VPWidenIntOrFpInductionSC: 572 case VPWidenCanonicalIVSC: 573 case VPWidenPHISC: 574 case VPBlendSC: 575 case VPWidenSC: 576 case VPWidenGEPSC: 577 case VPReductionSC: 578 case VPWidenSelectSC: { 579 const Instruction *I = 580 dyn_cast_or_null<Instruction>(getVPSingleValue()->getUnderlyingValue()); 581 (void)I; 582 assert((!I || !I->mayReadFromMemory()) && 583 "underlying instruction may read from memory"); 584 return false; 585 } 586 default: 587 return true; 588 } 589 } 590 591 bool VPRecipeBase::mayHaveSideEffects() const { 592 switch (getVPDefID()) { 593 case VPBranchOnMaskSC: 594 return false; 595 case VPWidenIntOrFpInductionSC: 596 case VPWidenPointerInductionSC: 597 case VPWidenCanonicalIVSC: 598 case VPWidenPHISC: 599 case VPBlendSC: 600 case VPWidenSC: 601 case VPWidenGEPSC: 602 case VPReductionSC: 603 case VPWidenSelectSC: 604 case VPScalarIVStepsSC: { 605 const Instruction *I = 606 dyn_cast_or_null<Instruction>(getVPSingleValue()->getUnderlyingValue()); 607 (void)I; 608 assert((!I || !I->mayHaveSideEffects()) && 609 "underlying instruction has side-effects"); 610 return false; 611 } 612 case VPReplicateSC: { 613 auto *R = cast<VPReplicateRecipe>(this); 614 return R->getUnderlyingInstr()->mayHaveSideEffects(); 615 } 616 default: 617 return true; 618 } 619 } 620 621 void VPRecipeBase::insertBefore(VPRecipeBase *InsertPos) { 622 assert(!Parent && "Recipe already in some VPBasicBlock"); 623 assert(InsertPos->getParent() && 624 "Insertion position not in any VPBasicBlock"); 625 Parent = InsertPos->getParent(); 626 Parent->getRecipeList().insert(InsertPos->getIterator(), this); 627 } 628 629 void VPRecipeBase::insertBefore(VPBasicBlock &BB, 630 iplist<VPRecipeBase>::iterator I) { 631 assert(!Parent && "Recipe already in some VPBasicBlock"); 632 assert(I == BB.end() || I->getParent() == &BB); 633 Parent = &BB; 634 BB.getRecipeList().insert(I, this); 635 } 636 637 void VPRecipeBase::insertAfter(VPRecipeBase *InsertPos) { 638 assert(!Parent && "Recipe already in some VPBasicBlock"); 639 assert(InsertPos->getParent() && 640 "Insertion position not in any VPBasicBlock"); 641 Parent = InsertPos->getParent(); 642 Parent->getRecipeList().insertAfter(InsertPos->getIterator(), this); 643 } 644 645 void VPRecipeBase::removeFromParent() { 646 assert(getParent() && "Recipe not in any VPBasicBlock"); 647 getParent()->getRecipeList().remove(getIterator()); 648 Parent = nullptr; 649 } 650 651 iplist<VPRecipeBase>::iterator VPRecipeBase::eraseFromParent() { 652 assert(getParent() && "Recipe not in any VPBasicBlock"); 653 return getParent()->getRecipeList().erase(getIterator()); 654 } 655 656 void VPRecipeBase::moveAfter(VPRecipeBase *InsertPos) { 657 removeFromParent(); 658 insertAfter(InsertPos); 659 } 660 661 void VPRecipeBase::moveBefore(VPBasicBlock &BB, 662 iplist<VPRecipeBase>::iterator I) { 663 removeFromParent(); 664 insertBefore(BB, I); 665 } 666 667 void VPInstruction::generateInstruction(VPTransformState &State, 668 unsigned Part) { 669 IRBuilderBase &Builder = State.Builder; 670 Builder.SetCurrentDebugLocation(DL); 671 672 if (Instruction::isBinaryOp(getOpcode())) { 673 Value *A = State.get(getOperand(0), Part); 674 Value *B = State.get(getOperand(1), Part); 675 Value *V = Builder.CreateBinOp((Instruction::BinaryOps)getOpcode(), A, B); 676 State.set(this, V, Part); 677 return; 678 } 679 680 switch (getOpcode()) { 681 case VPInstruction::Not: { 682 Value *A = State.get(getOperand(0), Part); 683 Value *V = Builder.CreateNot(A); 684 State.set(this, V, Part); 685 break; 686 } 687 case VPInstruction::ICmpULE: { 688 Value *IV = State.get(getOperand(0), Part); 689 Value *TC = State.get(getOperand(1), Part); 690 Value *V = Builder.CreateICmpULE(IV, TC); 691 State.set(this, V, Part); 692 break; 693 } 694 case Instruction::Select: { 695 Value *Cond = State.get(getOperand(0), Part); 696 Value *Op1 = State.get(getOperand(1), Part); 697 Value *Op2 = State.get(getOperand(2), Part); 698 Value *V = Builder.CreateSelect(Cond, Op1, Op2); 699 State.set(this, V, Part); 700 break; 701 } 702 case VPInstruction::ActiveLaneMask: { 703 // Get first lane of vector induction variable. 704 Value *VIVElem0 = State.get(getOperand(0), VPIteration(Part, 0)); 705 // Get the original loop tripcount. 706 Value *ScalarTC = State.get(getOperand(1), Part); 707 708 auto *Int1Ty = Type::getInt1Ty(Builder.getContext()); 709 auto *PredTy = VectorType::get(Int1Ty, State.VF); 710 Instruction *Call = Builder.CreateIntrinsic( 711 Intrinsic::get_active_lane_mask, {PredTy, ScalarTC->getType()}, 712 {VIVElem0, ScalarTC}, nullptr, "active.lane.mask"); 713 State.set(this, Call, Part); 714 break; 715 } 716 case VPInstruction::FirstOrderRecurrenceSplice: { 717 // Generate code to combine the previous and current values in vector v3. 718 // 719 // vector.ph: 720 // v_init = vector(..., ..., ..., a[-1]) 721 // br vector.body 722 // 723 // vector.body 724 // i = phi [0, vector.ph], [i+4, vector.body] 725 // v1 = phi [v_init, vector.ph], [v2, vector.body] 726 // v2 = a[i, i+1, i+2, i+3]; 727 // v3 = vector(v1(3), v2(0, 1, 2)) 728 729 // For the first part, use the recurrence phi (v1), otherwise v2. 730 auto *V1 = State.get(getOperand(0), 0); 731 Value *PartMinus1 = Part == 0 ? V1 : State.get(getOperand(1), Part - 1); 732 if (!PartMinus1->getType()->isVectorTy()) { 733 State.set(this, PartMinus1, Part); 734 } else { 735 Value *V2 = State.get(getOperand(1), Part); 736 State.set(this, Builder.CreateVectorSplice(PartMinus1, V2, -1), Part); 737 } 738 break; 739 } 740 741 case VPInstruction::CanonicalIVIncrement: 742 case VPInstruction::CanonicalIVIncrementNUW: { 743 Value *Next = nullptr; 744 if (Part == 0) { 745 bool IsNUW = getOpcode() == VPInstruction::CanonicalIVIncrementNUW; 746 auto *Phi = State.get(getOperand(0), 0); 747 // The loop step is equal to the vectorization factor (num of SIMD 748 // elements) times the unroll factor (num of SIMD instructions). 749 Value *Step = 750 createStepForVF(Builder, Phi->getType(), State.VF, State.UF); 751 Next = Builder.CreateAdd(Phi, Step, "index.next", IsNUW, false); 752 } else { 753 Next = State.get(this, 0); 754 } 755 756 State.set(this, Next, Part); 757 break; 758 } 759 case VPInstruction::BranchOnCount: { 760 if (Part != 0) 761 break; 762 // First create the compare. 763 Value *IV = State.get(getOperand(0), Part); 764 Value *TC = State.get(getOperand(1), Part); 765 Value *Cond = Builder.CreateICmpEQ(IV, TC); 766 767 // Now create the branch. 768 auto *Plan = getParent()->getPlan(); 769 VPRegionBlock *TopRegion = Plan->getVectorLoopRegion(); 770 VPBasicBlock *Header = TopRegion->getEntry()->getEntryBasicBlock(); 771 if (Header->empty()) { 772 assert(EnableVPlanNativePath && 773 "empty entry block only expected in VPlanNativePath"); 774 Header = cast<VPBasicBlock>(Header->getSingleSuccessor()); 775 } 776 // TODO: Once the exit block is modeled in VPlan, use it instead of going 777 // through State.CFG.ExitBB. 778 BasicBlock *Exit = State.CFG.ExitBB; 779 780 Builder.CreateCondBr(Cond, Exit, State.CFG.VPBB2IRBB[Header]); 781 Builder.GetInsertBlock()->getTerminator()->eraseFromParent(); 782 break; 783 } 784 default: 785 llvm_unreachable("Unsupported opcode for instruction"); 786 } 787 } 788 789 void VPInstruction::execute(VPTransformState &State) { 790 assert(!State.Instance && "VPInstruction executing an Instance"); 791 IRBuilderBase::FastMathFlagGuard FMFGuard(State.Builder); 792 State.Builder.setFastMathFlags(FMF); 793 for (unsigned Part = 0; Part < State.UF; ++Part) 794 generateInstruction(State, Part); 795 } 796 797 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 798 void VPInstruction::dump() const { 799 VPSlotTracker SlotTracker(getParent()->getPlan()); 800 print(dbgs(), "", SlotTracker); 801 } 802 803 void VPInstruction::print(raw_ostream &O, const Twine &Indent, 804 VPSlotTracker &SlotTracker) const { 805 O << Indent << "EMIT "; 806 807 if (hasResult()) { 808 printAsOperand(O, SlotTracker); 809 O << " = "; 810 } 811 812 switch (getOpcode()) { 813 case VPInstruction::Not: 814 O << "not"; 815 break; 816 case VPInstruction::ICmpULE: 817 O << "icmp ule"; 818 break; 819 case VPInstruction::SLPLoad: 820 O << "combined load"; 821 break; 822 case VPInstruction::SLPStore: 823 O << "combined store"; 824 break; 825 case VPInstruction::ActiveLaneMask: 826 O << "active lane mask"; 827 break; 828 case VPInstruction::FirstOrderRecurrenceSplice: 829 O << "first-order splice"; 830 break; 831 case VPInstruction::CanonicalIVIncrement: 832 O << "VF * UF + "; 833 break; 834 case VPInstruction::CanonicalIVIncrementNUW: 835 O << "VF * UF +(nuw) "; 836 break; 837 case VPInstruction::BranchOnCount: 838 O << "branch-on-count "; 839 break; 840 default: 841 O << Instruction::getOpcodeName(getOpcode()); 842 } 843 844 O << FMF; 845 846 for (const VPValue *Operand : operands()) { 847 O << " "; 848 Operand->printAsOperand(O, SlotTracker); 849 } 850 851 if (DL) { 852 O << ", !dbg "; 853 DL.print(O); 854 } 855 } 856 #endif 857 858 void VPInstruction::setFastMathFlags(FastMathFlags FMFNew) { 859 // Make sure the VPInstruction is a floating-point operation. 860 assert((Opcode == Instruction::FAdd || Opcode == Instruction::FMul || 861 Opcode == Instruction::FNeg || Opcode == Instruction::FSub || 862 Opcode == Instruction::FDiv || Opcode == Instruction::FRem || 863 Opcode == Instruction::FCmp) && 864 "this op can't take fast-math flags"); 865 FMF = FMFNew; 866 } 867 868 void VPlan::prepareToExecute(Value *TripCountV, Value *VectorTripCountV, 869 Value *CanonicalIVStartValue, 870 VPTransformState &State) { 871 // Check if the trip count is needed, and if so build it. 872 if (TripCount && TripCount->getNumUsers()) { 873 for (unsigned Part = 0, UF = State.UF; Part < UF; ++Part) 874 State.set(TripCount, TripCountV, Part); 875 } 876 877 // Check if the backedge taken count is needed, and if so build it. 878 if (BackedgeTakenCount && BackedgeTakenCount->getNumUsers()) { 879 IRBuilder<> Builder(State.CFG.VectorPreHeader->getTerminator()); 880 auto *TCMO = Builder.CreateSub(TripCountV, 881 ConstantInt::get(TripCountV->getType(), 1), 882 "trip.count.minus.1"); 883 auto VF = State.VF; 884 Value *VTCMO = 885 VF.isScalar() ? TCMO : Builder.CreateVectorSplat(VF, TCMO, "broadcast"); 886 for (unsigned Part = 0, UF = State.UF; Part < UF; ++Part) 887 State.set(BackedgeTakenCount, VTCMO, Part); 888 } 889 890 for (unsigned Part = 0, UF = State.UF; Part < UF; ++Part) 891 State.set(&VectorTripCount, VectorTripCountV, Part); 892 893 // When vectorizing the epilogue loop, the canonical induction start value 894 // needs to be changed from zero to the value after the main vector loop. 895 if (CanonicalIVStartValue) { 896 VPValue *VPV = new VPValue(CanonicalIVStartValue); 897 addExternalDef(VPV); 898 auto *IV = getCanonicalIV(); 899 assert(all_of(IV->users(), 900 [](const VPUser *U) { 901 if (isa<VPScalarIVStepsRecipe>(U)) 902 return true; 903 auto *VPI = cast<VPInstruction>(U); 904 return VPI->getOpcode() == 905 VPInstruction::CanonicalIVIncrement || 906 VPI->getOpcode() == 907 VPInstruction::CanonicalIVIncrementNUW; 908 }) && 909 "the canonical IV should only be used by its increments or " 910 "ScalarIVSteps when " 911 "resetting the start value"); 912 IV->setOperand(0, VPV); 913 } 914 } 915 916 /// Generate the code inside the body of the vectorized loop. Assumes a single 917 /// LoopVectorBody basic-block was created for this. Introduce additional 918 /// basic-blocks as needed, and fill them all. 919 void VPlan::execute(VPTransformState *State) { 920 // Set the reverse mapping from VPValues to Values for code generation. 921 for (auto &Entry : Value2VPValue) 922 State->VPValue2Value[Entry.second] = Entry.first; 923 924 // Initialize CFG state. 925 State->CFG.PrevVPBB = nullptr; 926 BasicBlock *VectorHeaderBB = State->CFG.VectorPreHeader->getSingleSuccessor(); 927 State->CFG.PrevBB = VectorHeaderBB; 928 State->CFG.ExitBB = VectorHeaderBB->getSingleSuccessor(); 929 State->CurrentVectorLoop = State->LI->getLoopFor(VectorHeaderBB); 930 931 // Remove the edge between Header and Latch to allow other connections. 932 // Temporarily terminate with unreachable until CFG is rewired. 933 // Note: this asserts the generated code's assumption that 934 // getFirstInsertionPt() can be dereferenced into an Instruction. 935 VectorHeaderBB->getTerminator()->eraseFromParent(); 936 State->Builder.SetInsertPoint(VectorHeaderBB); 937 UnreachableInst *Terminator = State->Builder.CreateUnreachable(); 938 State->Builder.SetInsertPoint(Terminator); 939 940 // Generate code in loop body. 941 for (VPBlockBase *Block : depth_first(Entry)) 942 Block->execute(State); 943 944 // Setup branch terminator successors for VPBBs in VPBBsToFix based on 945 // VPBB's successors. 946 for (auto VPBB : State->CFG.VPBBsToFix) { 947 assert(EnableVPlanNativePath && 948 "Unexpected VPBBsToFix in non VPlan-native path"); 949 BasicBlock *BB = State->CFG.VPBB2IRBB[VPBB]; 950 assert(BB && "Unexpected null basic block for VPBB"); 951 952 unsigned Idx = 0; 953 auto *BBTerminator = BB->getTerminator(); 954 955 for (VPBlockBase *SuccVPBlock : VPBB->getHierarchicalSuccessors()) { 956 VPBasicBlock *SuccVPBB = SuccVPBlock->getEntryBasicBlock(); 957 BBTerminator->setSuccessor(Idx, State->CFG.VPBB2IRBB[SuccVPBB]); 958 ++Idx; 959 } 960 } 961 962 BasicBlock *VectorLatchBB = State->CFG.PrevBB; 963 964 // Fix the latch value of canonical, reduction and first-order recurrences 965 // phis in the vector loop. 966 VPBasicBlock *Header = getVectorLoopRegion()->getEntryBasicBlock(); 967 if (Header->empty()) { 968 assert(EnableVPlanNativePath); 969 Header = cast<VPBasicBlock>(Header->getSingleSuccessor()); 970 } 971 for (VPRecipeBase &R : Header->phis()) { 972 // Skip phi-like recipes that generate their backedege values themselves. 973 if (isa<VPWidenPHIRecipe>(&R)) 974 continue; 975 976 if (isa<VPWidenPointerInductionRecipe>(&R) || 977 isa<VPWidenIntOrFpInductionRecipe>(&R)) { 978 PHINode *Phi = nullptr; 979 if (isa<VPWidenIntOrFpInductionRecipe>(&R)) { 980 Phi = cast<PHINode>(State->get(R.getVPSingleValue(), 0)); 981 } else { 982 auto *WidenPhi = cast<VPWidenPointerInductionRecipe>(&R); 983 // TODO: Split off the case that all users of a pointer phi are scalar 984 // from the VPWidenPointerInductionRecipe. 985 if (all_of(WidenPhi->users(), [WidenPhi](const VPUser *U) { 986 return cast<VPRecipeBase>(U)->usesScalars(WidenPhi); 987 })) 988 continue; 989 990 auto *GEP = cast<GetElementPtrInst>(State->get(WidenPhi, 0)); 991 Phi = cast<PHINode>(GEP->getPointerOperand()); 992 } 993 994 Phi->setIncomingBlock(1, VectorLatchBB); 995 996 // Move the last step to the end of the latch block. This ensures 997 // consistent placement of all induction updates. 998 Instruction *Inc = cast<Instruction>(Phi->getIncomingValue(1)); 999 Inc->moveBefore(VectorLatchBB->getTerminator()->getPrevNode()); 1000 continue; 1001 } 1002 1003 auto *PhiR = cast<VPHeaderPHIRecipe>(&R); 1004 // For canonical IV, first-order recurrences and in-order reduction phis, 1005 // only a single part is generated, which provides the last part from the 1006 // previous iteration. For non-ordered reductions all UF parts are 1007 // generated. 1008 bool SinglePartNeeded = isa<VPCanonicalIVPHIRecipe>(PhiR) || 1009 isa<VPFirstOrderRecurrencePHIRecipe>(PhiR) || 1010 cast<VPReductionPHIRecipe>(PhiR)->isOrdered(); 1011 unsigned LastPartForNewPhi = SinglePartNeeded ? 1 : State->UF; 1012 1013 for (unsigned Part = 0; Part < LastPartForNewPhi; ++Part) { 1014 Value *Phi = State->get(PhiR, Part); 1015 Value *Val = State->get(PhiR->getBackedgeValue(), 1016 SinglePartNeeded ? State->UF - 1 : Part); 1017 cast<PHINode>(Phi)->addIncoming(Val, VectorLatchBB); 1018 } 1019 } 1020 1021 // We do not attempt to preserve DT for outer loop vectorization currently. 1022 if (!EnableVPlanNativePath) 1023 updateDominatorTree(State->DT, VectorHeaderBB, VectorLatchBB, 1024 State->CFG.ExitBB); 1025 } 1026 1027 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1028 LLVM_DUMP_METHOD 1029 void VPlan::print(raw_ostream &O) const { 1030 VPSlotTracker SlotTracker(this); 1031 1032 O << "VPlan '" << Name << "' {"; 1033 1034 if (VectorTripCount.getNumUsers() > 0) { 1035 O << "\nLive-in "; 1036 VectorTripCount.printAsOperand(O, SlotTracker); 1037 O << " = vector-trip-count\n"; 1038 } 1039 1040 if (BackedgeTakenCount && BackedgeTakenCount->getNumUsers()) { 1041 O << "\nLive-in "; 1042 BackedgeTakenCount->printAsOperand(O, SlotTracker); 1043 O << " = backedge-taken count\n"; 1044 } 1045 1046 for (const VPBlockBase *Block : depth_first(getEntry())) { 1047 O << '\n'; 1048 Block->print(O, "", SlotTracker); 1049 } 1050 O << "}\n"; 1051 } 1052 1053 LLVM_DUMP_METHOD 1054 void VPlan::printDOT(raw_ostream &O) const { 1055 VPlanPrinter Printer(O, *this); 1056 Printer.dump(); 1057 } 1058 1059 LLVM_DUMP_METHOD 1060 void VPlan::dump() const { print(dbgs()); } 1061 #endif 1062 1063 void VPlan::updateDominatorTree(DominatorTree *DT, BasicBlock *LoopHeaderBB, 1064 BasicBlock *LoopLatchBB, 1065 BasicBlock *LoopExitBB) { 1066 // The vector body may be more than a single basic-block by this point. 1067 // Update the dominator tree information inside the vector body by propagating 1068 // it from header to latch, expecting only triangular control-flow, if any. 1069 BasicBlock *PostDomSucc = nullptr; 1070 for (auto *BB = LoopHeaderBB; BB != LoopLatchBB; BB = PostDomSucc) { 1071 // Get the list of successors of this block. 1072 std::vector<BasicBlock *> Succs(succ_begin(BB), succ_end(BB)); 1073 assert(Succs.size() <= 2 && 1074 "Basic block in vector loop has more than 2 successors."); 1075 PostDomSucc = Succs[0]; 1076 if (Succs.size() == 1) { 1077 assert(PostDomSucc->getSinglePredecessor() && 1078 "PostDom successor has more than one predecessor."); 1079 DT->addNewBlock(PostDomSucc, BB); 1080 continue; 1081 } 1082 BasicBlock *InterimSucc = Succs[1]; 1083 if (PostDomSucc->getSingleSuccessor() == InterimSucc) { 1084 PostDomSucc = Succs[1]; 1085 InterimSucc = Succs[0]; 1086 } 1087 assert(InterimSucc->getSingleSuccessor() == PostDomSucc && 1088 "One successor of a basic block does not lead to the other."); 1089 assert(InterimSucc->getSinglePredecessor() && 1090 "Interim successor has more than one predecessor."); 1091 assert(PostDomSucc->hasNPredecessors(2) && 1092 "PostDom successor has more than two predecessors."); 1093 DT->addNewBlock(InterimSucc, BB); 1094 DT->addNewBlock(PostDomSucc, BB); 1095 } 1096 // Latch block is a new dominator for the loop exit. 1097 DT->changeImmediateDominator(LoopExitBB, LoopLatchBB); 1098 assert(DT->verify(DominatorTree::VerificationLevel::Fast)); 1099 } 1100 1101 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1102 Twine VPlanPrinter::getUID(const VPBlockBase *Block) { 1103 return (isa<VPRegionBlock>(Block) ? "cluster_N" : "N") + 1104 Twine(getOrCreateBID(Block)); 1105 } 1106 1107 Twine VPlanPrinter::getOrCreateName(const VPBlockBase *Block) { 1108 const std::string &Name = Block->getName(); 1109 if (!Name.empty()) 1110 return Name; 1111 return "VPB" + Twine(getOrCreateBID(Block)); 1112 } 1113 1114 void VPlanPrinter::dump() { 1115 Depth = 1; 1116 bumpIndent(0); 1117 OS << "digraph VPlan {\n"; 1118 OS << "graph [labelloc=t, fontsize=30; label=\"Vectorization Plan"; 1119 if (!Plan.getName().empty()) 1120 OS << "\\n" << DOT::EscapeString(Plan.getName()); 1121 if (Plan.BackedgeTakenCount) { 1122 OS << ", where:\\n"; 1123 Plan.BackedgeTakenCount->print(OS, SlotTracker); 1124 OS << " := BackedgeTakenCount"; 1125 } 1126 OS << "\"]\n"; 1127 OS << "node [shape=rect, fontname=Courier, fontsize=30]\n"; 1128 OS << "edge [fontname=Courier, fontsize=30]\n"; 1129 OS << "compound=true\n"; 1130 1131 for (const VPBlockBase *Block : depth_first(Plan.getEntry())) 1132 dumpBlock(Block); 1133 1134 OS << "}\n"; 1135 } 1136 1137 void VPlanPrinter::dumpBlock(const VPBlockBase *Block) { 1138 if (const VPBasicBlock *BasicBlock = dyn_cast<VPBasicBlock>(Block)) 1139 dumpBasicBlock(BasicBlock); 1140 else if (const VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block)) 1141 dumpRegion(Region); 1142 else 1143 llvm_unreachable("Unsupported kind of VPBlock."); 1144 } 1145 1146 void VPlanPrinter::drawEdge(const VPBlockBase *From, const VPBlockBase *To, 1147 bool Hidden, const Twine &Label) { 1148 // Due to "dot" we print an edge between two regions as an edge between the 1149 // exit basic block and the entry basic of the respective regions. 1150 const VPBlockBase *Tail = From->getExitBasicBlock(); 1151 const VPBlockBase *Head = To->getEntryBasicBlock(); 1152 OS << Indent << getUID(Tail) << " -> " << getUID(Head); 1153 OS << " [ label=\"" << Label << '\"'; 1154 if (Tail != From) 1155 OS << " ltail=" << getUID(From); 1156 if (Head != To) 1157 OS << " lhead=" << getUID(To); 1158 if (Hidden) 1159 OS << "; splines=none"; 1160 OS << "]\n"; 1161 } 1162 1163 void VPlanPrinter::dumpEdges(const VPBlockBase *Block) { 1164 auto &Successors = Block->getSuccessors(); 1165 if (Successors.size() == 1) 1166 drawEdge(Block, Successors.front(), false, ""); 1167 else if (Successors.size() == 2) { 1168 drawEdge(Block, Successors.front(), false, "T"); 1169 drawEdge(Block, Successors.back(), false, "F"); 1170 } else { 1171 unsigned SuccessorNumber = 0; 1172 for (auto *Successor : Successors) 1173 drawEdge(Block, Successor, false, Twine(SuccessorNumber++)); 1174 } 1175 } 1176 1177 void VPlanPrinter::dumpBasicBlock(const VPBasicBlock *BasicBlock) { 1178 // Implement dot-formatted dump by performing plain-text dump into the 1179 // temporary storage followed by some post-processing. 1180 OS << Indent << getUID(BasicBlock) << " [label =\n"; 1181 bumpIndent(1); 1182 std::string Str; 1183 raw_string_ostream SS(Str); 1184 // Use no indentation as we need to wrap the lines into quotes ourselves. 1185 BasicBlock->print(SS, "", SlotTracker); 1186 1187 // We need to process each line of the output separately, so split 1188 // single-string plain-text dump. 1189 SmallVector<StringRef, 0> Lines; 1190 StringRef(Str).rtrim('\n').split(Lines, "\n"); 1191 1192 auto EmitLine = [&](StringRef Line, StringRef Suffix) { 1193 OS << Indent << '"' << DOT::EscapeString(Line.str()) << "\\l\"" << Suffix; 1194 }; 1195 1196 // Don't need the "+" after the last line. 1197 for (auto Line : make_range(Lines.begin(), Lines.end() - 1)) 1198 EmitLine(Line, " +\n"); 1199 EmitLine(Lines.back(), "\n"); 1200 1201 bumpIndent(-1); 1202 OS << Indent << "]\n"; 1203 1204 dumpEdges(BasicBlock); 1205 } 1206 1207 void VPlanPrinter::dumpRegion(const VPRegionBlock *Region) { 1208 OS << Indent << "subgraph " << getUID(Region) << " {\n"; 1209 bumpIndent(1); 1210 OS << Indent << "fontname=Courier\n" 1211 << Indent << "label=\"" 1212 << DOT::EscapeString(Region->isReplicator() ? "<xVFxUF> " : "<x1> ") 1213 << DOT::EscapeString(Region->getName()) << "\"\n"; 1214 // Dump the blocks of the region. 1215 assert(Region->getEntry() && "Region contains no inner blocks."); 1216 for (const VPBlockBase *Block : depth_first(Region->getEntry())) 1217 dumpBlock(Block); 1218 bumpIndent(-1); 1219 OS << Indent << "}\n"; 1220 dumpEdges(Region); 1221 } 1222 1223 void VPlanIngredient::print(raw_ostream &O) const { 1224 if (auto *Inst = dyn_cast<Instruction>(V)) { 1225 if (!Inst->getType()->isVoidTy()) { 1226 Inst->printAsOperand(O, false); 1227 O << " = "; 1228 } 1229 O << Inst->getOpcodeName() << " "; 1230 unsigned E = Inst->getNumOperands(); 1231 if (E > 0) { 1232 Inst->getOperand(0)->printAsOperand(O, false); 1233 for (unsigned I = 1; I < E; ++I) 1234 Inst->getOperand(I)->printAsOperand(O << ", ", false); 1235 } 1236 } else // !Inst 1237 V->printAsOperand(O, false); 1238 } 1239 1240 void VPWidenCallRecipe::print(raw_ostream &O, const Twine &Indent, 1241 VPSlotTracker &SlotTracker) const { 1242 O << Indent << "WIDEN-CALL "; 1243 1244 auto *CI = cast<CallInst>(getUnderlyingInstr()); 1245 if (CI->getType()->isVoidTy()) 1246 O << "void "; 1247 else { 1248 printAsOperand(O, SlotTracker); 1249 O << " = "; 1250 } 1251 1252 O << "call @" << CI->getCalledFunction()->getName() << "("; 1253 printOperands(O, SlotTracker); 1254 O << ")"; 1255 } 1256 1257 void VPWidenSelectRecipe::print(raw_ostream &O, const Twine &Indent, 1258 VPSlotTracker &SlotTracker) const { 1259 O << Indent << "WIDEN-SELECT "; 1260 printAsOperand(O, SlotTracker); 1261 O << " = select "; 1262 getOperand(0)->printAsOperand(O, SlotTracker); 1263 O << ", "; 1264 getOperand(1)->printAsOperand(O, SlotTracker); 1265 O << ", "; 1266 getOperand(2)->printAsOperand(O, SlotTracker); 1267 O << (InvariantCond ? " (condition is loop invariant)" : ""); 1268 } 1269 1270 void VPWidenRecipe::print(raw_ostream &O, const Twine &Indent, 1271 VPSlotTracker &SlotTracker) const { 1272 O << Indent << "WIDEN "; 1273 printAsOperand(O, SlotTracker); 1274 O << " = " << getUnderlyingInstr()->getOpcodeName() << " "; 1275 printOperands(O, SlotTracker); 1276 } 1277 1278 void VPWidenIntOrFpInductionRecipe::print(raw_ostream &O, const Twine &Indent, 1279 VPSlotTracker &SlotTracker) const { 1280 O << Indent << "WIDEN-INDUCTION"; 1281 if (getTruncInst()) { 1282 O << "\\l\""; 1283 O << " +\n" << Indent << "\" " << VPlanIngredient(IV) << "\\l\""; 1284 O << " +\n" << Indent << "\" "; 1285 getVPValue(0)->printAsOperand(O, SlotTracker); 1286 } else 1287 O << " " << VPlanIngredient(IV); 1288 } 1289 1290 void VPWidenPointerInductionRecipe::print(raw_ostream &O, const Twine &Indent, 1291 VPSlotTracker &SlotTracker) const { 1292 O << Indent << "EMIT "; 1293 printAsOperand(O, SlotTracker); 1294 O << " = WIDEN-POINTER-INDUCTION "; 1295 getStartValue()->printAsOperand(O, SlotTracker); 1296 O << ", " << *IndDesc.getStep(); 1297 } 1298 1299 #endif 1300 1301 bool VPWidenIntOrFpInductionRecipe::isCanonical() const { 1302 auto *StartC = dyn_cast<ConstantInt>(getStartValue()->getLiveInIRValue()); 1303 auto *StepC = dyn_cast<SCEVConstant>(getInductionDescriptor().getStep()); 1304 return StartC && StartC->isZero() && StepC && StepC->isOne(); 1305 } 1306 1307 VPCanonicalIVPHIRecipe *VPScalarIVStepsRecipe::getCanonicalIV() const { 1308 return cast<VPCanonicalIVPHIRecipe>(getOperand(0)); 1309 } 1310 1311 bool VPScalarIVStepsRecipe::isCanonical() const { 1312 auto *CanIV = getCanonicalIV(); 1313 // The start value of the steps-recipe must match the start value of the 1314 // canonical induction and it must step by 1. 1315 if (CanIV->getStartValue() != getStartValue()) 1316 return false; 1317 auto *StepVPV = getStepValue(); 1318 if (StepVPV->getDef()) 1319 return false; 1320 auto *StepC = dyn_cast_or_null<ConstantInt>(StepVPV->getLiveInIRValue()); 1321 return StepC && StepC->isOne(); 1322 } 1323 1324 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1325 void VPScalarIVStepsRecipe::print(raw_ostream &O, const Twine &Indent, 1326 VPSlotTracker &SlotTracker) const { 1327 O << Indent; 1328 printAsOperand(O, SlotTracker); 1329 O << Indent << "= SCALAR-STEPS "; 1330 printOperands(O, SlotTracker); 1331 } 1332 1333 void VPWidenGEPRecipe::print(raw_ostream &O, const Twine &Indent, 1334 VPSlotTracker &SlotTracker) const { 1335 O << Indent << "WIDEN-GEP "; 1336 O << (IsPtrLoopInvariant ? "Inv" : "Var"); 1337 size_t IndicesNumber = IsIndexLoopInvariant.size(); 1338 for (size_t I = 0; I < IndicesNumber; ++I) 1339 O << "[" << (IsIndexLoopInvariant[I] ? "Inv" : "Var") << "]"; 1340 1341 O << " "; 1342 printAsOperand(O, SlotTracker); 1343 O << " = getelementptr "; 1344 printOperands(O, SlotTracker); 1345 } 1346 1347 void VPWidenPHIRecipe::print(raw_ostream &O, const Twine &Indent, 1348 VPSlotTracker &SlotTracker) const { 1349 O << Indent << "WIDEN-PHI "; 1350 1351 auto *OriginalPhi = cast<PHINode>(getUnderlyingValue()); 1352 // Unless all incoming values are modeled in VPlan print the original PHI 1353 // directly. 1354 // TODO: Remove once all VPWidenPHIRecipe instances keep all relevant incoming 1355 // values as VPValues. 1356 if (getNumOperands() != OriginalPhi->getNumOperands()) { 1357 O << VPlanIngredient(OriginalPhi); 1358 return; 1359 } 1360 1361 printAsOperand(O, SlotTracker); 1362 O << " = phi "; 1363 printOperands(O, SlotTracker); 1364 } 1365 1366 void VPBlendRecipe::print(raw_ostream &O, const Twine &Indent, 1367 VPSlotTracker &SlotTracker) const { 1368 O << Indent << "BLEND "; 1369 Phi->printAsOperand(O, false); 1370 O << " ="; 1371 if (getNumIncomingValues() == 1) { 1372 // Not a User of any mask: not really blending, this is a 1373 // single-predecessor phi. 1374 O << " "; 1375 getIncomingValue(0)->printAsOperand(O, SlotTracker); 1376 } else { 1377 for (unsigned I = 0, E = getNumIncomingValues(); I < E; ++I) { 1378 O << " "; 1379 getIncomingValue(I)->printAsOperand(O, SlotTracker); 1380 O << "/"; 1381 getMask(I)->printAsOperand(O, SlotTracker); 1382 } 1383 } 1384 } 1385 1386 void VPReductionRecipe::print(raw_ostream &O, const Twine &Indent, 1387 VPSlotTracker &SlotTracker) const { 1388 O << Indent << "REDUCE "; 1389 printAsOperand(O, SlotTracker); 1390 O << " = "; 1391 getChainOp()->printAsOperand(O, SlotTracker); 1392 O << " +"; 1393 if (isa<FPMathOperator>(getUnderlyingInstr())) 1394 O << getUnderlyingInstr()->getFastMathFlags(); 1395 O << " reduce." << Instruction::getOpcodeName(RdxDesc->getOpcode()) << " ("; 1396 getVecOp()->printAsOperand(O, SlotTracker); 1397 if (getCondOp()) { 1398 O << ", "; 1399 getCondOp()->printAsOperand(O, SlotTracker); 1400 } 1401 O << ")"; 1402 } 1403 1404 void VPReplicateRecipe::print(raw_ostream &O, const Twine &Indent, 1405 VPSlotTracker &SlotTracker) const { 1406 O << Indent << (IsUniform ? "CLONE " : "REPLICATE "); 1407 1408 if (!getUnderlyingInstr()->getType()->isVoidTy()) { 1409 printAsOperand(O, SlotTracker); 1410 O << " = "; 1411 } 1412 O << Instruction::getOpcodeName(getUnderlyingInstr()->getOpcode()) << " "; 1413 printOperands(O, SlotTracker); 1414 1415 if (AlsoPack) 1416 O << " (S->V)"; 1417 } 1418 1419 void VPPredInstPHIRecipe::print(raw_ostream &O, const Twine &Indent, 1420 VPSlotTracker &SlotTracker) const { 1421 O << Indent << "PHI-PREDICATED-INSTRUCTION "; 1422 printAsOperand(O, SlotTracker); 1423 O << " = "; 1424 printOperands(O, SlotTracker); 1425 } 1426 1427 void VPWidenMemoryInstructionRecipe::print(raw_ostream &O, const Twine &Indent, 1428 VPSlotTracker &SlotTracker) const { 1429 O << Indent << "WIDEN "; 1430 1431 if (!isStore()) { 1432 printAsOperand(O, SlotTracker); 1433 O << " = "; 1434 } 1435 O << Instruction::getOpcodeName(Ingredient.getOpcode()) << " "; 1436 1437 printOperands(O, SlotTracker); 1438 } 1439 #endif 1440 1441 void VPCanonicalIVPHIRecipe::execute(VPTransformState &State) { 1442 Value *Start = getStartValue()->getLiveInIRValue(); 1443 PHINode *EntryPart = PHINode::Create( 1444 Start->getType(), 2, "index", &*State.CFG.PrevBB->getFirstInsertionPt()); 1445 EntryPart->addIncoming(Start, State.CFG.VectorPreHeader); 1446 EntryPart->setDebugLoc(DL); 1447 for (unsigned Part = 0, UF = State.UF; Part < UF; ++Part) 1448 State.set(this, EntryPart, Part); 1449 } 1450 1451 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1452 void VPCanonicalIVPHIRecipe::print(raw_ostream &O, const Twine &Indent, 1453 VPSlotTracker &SlotTracker) const { 1454 O << Indent << "EMIT "; 1455 printAsOperand(O, SlotTracker); 1456 O << " = CANONICAL-INDUCTION"; 1457 } 1458 #endif 1459 1460 void VPExpandSCEVRecipe::execute(VPTransformState &State) { 1461 assert(!State.Instance && "cannot be used in per-lane"); 1462 const DataLayout &DL = 1463 State.CFG.VectorPreHeader->getModule()->getDataLayout(); 1464 SCEVExpander Exp(SE, DL, "induction"); 1465 Value *Res = Exp.expandCodeFor(Expr, Expr->getType(), 1466 State.CFG.VectorPreHeader->getTerminator()); 1467 1468 for (unsigned Part = 0, UF = State.UF; Part < UF; ++Part) 1469 State.set(this, Res, Part); 1470 } 1471 1472 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1473 void VPExpandSCEVRecipe::print(raw_ostream &O, const Twine &Indent, 1474 VPSlotTracker &SlotTracker) const { 1475 O << Indent << "EMIT "; 1476 getVPSingleValue()->printAsOperand(O, SlotTracker); 1477 O << " = EXPAND SCEV " << *Expr; 1478 } 1479 #endif 1480 1481 void VPWidenCanonicalIVRecipe::execute(VPTransformState &State) { 1482 Value *CanonicalIV = State.get(getOperand(0), 0); 1483 Type *STy = CanonicalIV->getType(); 1484 IRBuilder<> Builder(State.CFG.PrevBB->getTerminator()); 1485 ElementCount VF = State.VF; 1486 Value *VStart = VF.isScalar() 1487 ? CanonicalIV 1488 : Builder.CreateVectorSplat(VF, CanonicalIV, "broadcast"); 1489 for (unsigned Part = 0, UF = State.UF; Part < UF; ++Part) { 1490 Value *VStep = createStepForVF(Builder, STy, VF, Part); 1491 if (VF.isVector()) { 1492 VStep = Builder.CreateVectorSplat(VF, VStep); 1493 VStep = Builder.CreateAdd(VStep, Builder.CreateStepVector(VStep->getType())); 1494 } 1495 Value *CanonicalVectorIV = Builder.CreateAdd(VStart, VStep, "vec.iv"); 1496 State.set(this, CanonicalVectorIV, Part); 1497 } 1498 } 1499 1500 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1501 void VPWidenCanonicalIVRecipe::print(raw_ostream &O, const Twine &Indent, 1502 VPSlotTracker &SlotTracker) const { 1503 O << Indent << "EMIT "; 1504 printAsOperand(O, SlotTracker); 1505 O << " = WIDEN-CANONICAL-INDUCTION "; 1506 printOperands(O, SlotTracker); 1507 } 1508 #endif 1509 1510 void VPFirstOrderRecurrencePHIRecipe::execute(VPTransformState &State) { 1511 auto &Builder = State.Builder; 1512 // Create a vector from the initial value. 1513 auto *VectorInit = getStartValue()->getLiveInIRValue(); 1514 1515 Type *VecTy = State.VF.isScalar() 1516 ? VectorInit->getType() 1517 : VectorType::get(VectorInit->getType(), State.VF); 1518 1519 if (State.VF.isVector()) { 1520 auto *IdxTy = Builder.getInt32Ty(); 1521 auto *One = ConstantInt::get(IdxTy, 1); 1522 IRBuilder<>::InsertPointGuard Guard(Builder); 1523 Builder.SetInsertPoint(State.CFG.VectorPreHeader->getTerminator()); 1524 auto *RuntimeVF = getRuntimeVF(Builder, IdxTy, State.VF); 1525 auto *LastIdx = Builder.CreateSub(RuntimeVF, One); 1526 VectorInit = Builder.CreateInsertElement( 1527 PoisonValue::get(VecTy), VectorInit, LastIdx, "vector.recur.init"); 1528 } 1529 1530 // Create a phi node for the new recurrence. 1531 PHINode *EntryPart = PHINode::Create( 1532 VecTy, 2, "vector.recur", &*State.CFG.PrevBB->getFirstInsertionPt()); 1533 EntryPart->addIncoming(VectorInit, State.CFG.VectorPreHeader); 1534 State.set(this, EntryPart, 0); 1535 } 1536 1537 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1538 void VPFirstOrderRecurrencePHIRecipe::print(raw_ostream &O, const Twine &Indent, 1539 VPSlotTracker &SlotTracker) const { 1540 O << Indent << "FIRST-ORDER-RECURRENCE-PHI "; 1541 printAsOperand(O, SlotTracker); 1542 O << " = phi "; 1543 printOperands(O, SlotTracker); 1544 } 1545 #endif 1546 1547 void VPReductionPHIRecipe::execute(VPTransformState &State) { 1548 PHINode *PN = cast<PHINode>(getUnderlyingValue()); 1549 auto &Builder = State.Builder; 1550 1551 // In order to support recurrences we need to be able to vectorize Phi nodes. 1552 // Phi nodes have cycles, so we need to vectorize them in two stages. This is 1553 // stage #1: We create a new vector PHI node with no incoming edges. We'll use 1554 // this value when we vectorize all of the instructions that use the PHI. 1555 bool ScalarPHI = State.VF.isScalar() || IsInLoop; 1556 Type *VecTy = 1557 ScalarPHI ? PN->getType() : VectorType::get(PN->getType(), State.VF); 1558 1559 BasicBlock *HeaderBB = State.CFG.PrevBB; 1560 assert(State.CurrentVectorLoop->getHeader() == HeaderBB && 1561 "recipe must be in the vector loop header"); 1562 unsigned LastPartForNewPhi = isOrdered() ? 1 : State.UF; 1563 for (unsigned Part = 0; Part < LastPartForNewPhi; ++Part) { 1564 Value *EntryPart = 1565 PHINode::Create(VecTy, 2, "vec.phi", &*HeaderBB->getFirstInsertionPt()); 1566 State.set(this, EntryPart, Part); 1567 } 1568 1569 // Reductions do not have to start at zero. They can start with 1570 // any loop invariant values. 1571 VPValue *StartVPV = getStartValue(); 1572 Value *StartV = StartVPV->getLiveInIRValue(); 1573 1574 Value *Iden = nullptr; 1575 RecurKind RK = RdxDesc.getRecurrenceKind(); 1576 if (RecurrenceDescriptor::isMinMaxRecurrenceKind(RK) || 1577 RecurrenceDescriptor::isSelectCmpRecurrenceKind(RK)) { 1578 // MinMax reduction have the start value as their identify. 1579 if (ScalarPHI) { 1580 Iden = StartV; 1581 } else { 1582 IRBuilderBase::InsertPointGuard IPBuilder(Builder); 1583 Builder.SetInsertPoint(State.CFG.VectorPreHeader->getTerminator()); 1584 StartV = Iden = 1585 Builder.CreateVectorSplat(State.VF, StartV, "minmax.ident"); 1586 } 1587 } else { 1588 Iden = RdxDesc.getRecurrenceIdentity(RK, VecTy->getScalarType(), 1589 RdxDesc.getFastMathFlags()); 1590 1591 if (!ScalarPHI) { 1592 Iden = Builder.CreateVectorSplat(State.VF, Iden); 1593 IRBuilderBase::InsertPointGuard IPBuilder(Builder); 1594 Builder.SetInsertPoint(State.CFG.VectorPreHeader->getTerminator()); 1595 Constant *Zero = Builder.getInt32(0); 1596 StartV = Builder.CreateInsertElement(Iden, StartV, Zero); 1597 } 1598 } 1599 1600 for (unsigned Part = 0; Part < LastPartForNewPhi; ++Part) { 1601 Value *EntryPart = State.get(this, Part); 1602 // Make sure to add the reduction start value only to the 1603 // first unroll part. 1604 Value *StartVal = (Part == 0) ? StartV : Iden; 1605 cast<PHINode>(EntryPart)->addIncoming(StartVal, State.CFG.VectorPreHeader); 1606 } 1607 } 1608 1609 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1610 void VPReductionPHIRecipe::print(raw_ostream &O, const Twine &Indent, 1611 VPSlotTracker &SlotTracker) const { 1612 O << Indent << "WIDEN-REDUCTION-PHI "; 1613 1614 printAsOperand(O, SlotTracker); 1615 O << " = phi "; 1616 printOperands(O, SlotTracker); 1617 } 1618 #endif 1619 1620 template void DomTreeBuilder::Calculate<VPDominatorTree>(VPDominatorTree &DT); 1621 1622 void VPValue::replaceAllUsesWith(VPValue *New) { 1623 for (unsigned J = 0; J < getNumUsers();) { 1624 VPUser *User = Users[J]; 1625 unsigned NumUsers = getNumUsers(); 1626 for (unsigned I = 0, E = User->getNumOperands(); I < E; ++I) 1627 if (User->getOperand(I) == this) 1628 User->setOperand(I, New); 1629 // If a user got removed after updating the current user, the next user to 1630 // update will be moved to the current position, so we only need to 1631 // increment the index if the number of users did not change. 1632 if (NumUsers == getNumUsers()) 1633 J++; 1634 } 1635 } 1636 1637 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1638 void VPValue::printAsOperand(raw_ostream &OS, VPSlotTracker &Tracker) const { 1639 if (const Value *UV = getUnderlyingValue()) { 1640 OS << "ir<"; 1641 UV->printAsOperand(OS, false); 1642 OS << ">"; 1643 return; 1644 } 1645 1646 unsigned Slot = Tracker.getSlot(this); 1647 if (Slot == unsigned(-1)) 1648 OS << "<badref>"; 1649 else 1650 OS << "vp<%" << Tracker.getSlot(this) << ">"; 1651 } 1652 1653 void VPUser::printOperands(raw_ostream &O, VPSlotTracker &SlotTracker) const { 1654 interleaveComma(operands(), O, [&O, &SlotTracker](VPValue *Op) { 1655 Op->printAsOperand(O, SlotTracker); 1656 }); 1657 } 1658 #endif 1659 1660 void VPInterleavedAccessInfo::visitRegion(VPRegionBlock *Region, 1661 Old2NewTy &Old2New, 1662 InterleavedAccessInfo &IAI) { 1663 ReversePostOrderTraversal<VPBlockBase *> RPOT(Region->getEntry()); 1664 for (VPBlockBase *Base : RPOT) { 1665 visitBlock(Base, Old2New, IAI); 1666 } 1667 } 1668 1669 void VPInterleavedAccessInfo::visitBlock(VPBlockBase *Block, Old2NewTy &Old2New, 1670 InterleavedAccessInfo &IAI) { 1671 if (VPBasicBlock *VPBB = dyn_cast<VPBasicBlock>(Block)) { 1672 for (VPRecipeBase &VPI : *VPBB) { 1673 if (isa<VPHeaderPHIRecipe>(&VPI)) 1674 continue; 1675 assert(isa<VPInstruction>(&VPI) && "Can only handle VPInstructions"); 1676 auto *VPInst = cast<VPInstruction>(&VPI); 1677 auto *Inst = cast<Instruction>(VPInst->getUnderlyingValue()); 1678 auto *IG = IAI.getInterleaveGroup(Inst); 1679 if (!IG) 1680 continue; 1681 1682 auto NewIGIter = Old2New.find(IG); 1683 if (NewIGIter == Old2New.end()) 1684 Old2New[IG] = new InterleaveGroup<VPInstruction>( 1685 IG->getFactor(), IG->isReverse(), IG->getAlign()); 1686 1687 if (Inst == IG->getInsertPos()) 1688 Old2New[IG]->setInsertPos(VPInst); 1689 1690 InterleaveGroupMap[VPInst] = Old2New[IG]; 1691 InterleaveGroupMap[VPInst]->insertMember( 1692 VPInst, IG->getIndex(Inst), 1693 Align(IG->isReverse() ? (-1) * int(IG->getFactor()) 1694 : IG->getFactor())); 1695 } 1696 } else if (VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block)) 1697 visitRegion(Region, Old2New, IAI); 1698 else 1699 llvm_unreachable("Unsupported kind of VPBlock."); 1700 } 1701 1702 VPInterleavedAccessInfo::VPInterleavedAccessInfo(VPlan &Plan, 1703 InterleavedAccessInfo &IAI) { 1704 Old2NewTy Old2New; 1705 visitRegion(cast<VPRegionBlock>(Plan.getEntry()), Old2New, IAI); 1706 } 1707 1708 void VPSlotTracker::assignSlot(const VPValue *V) { 1709 assert(Slots.find(V) == Slots.end() && "VPValue already has a slot!"); 1710 Slots[V] = NextSlot++; 1711 } 1712 1713 void VPSlotTracker::assignSlots(const VPlan &Plan) { 1714 1715 for (const VPValue *V : Plan.VPExternalDefs) 1716 assignSlot(V); 1717 1718 assignSlot(&Plan.VectorTripCount); 1719 if (Plan.BackedgeTakenCount) 1720 assignSlot(Plan.BackedgeTakenCount); 1721 1722 ReversePostOrderTraversal< 1723 VPBlockRecursiveTraversalWrapper<const VPBlockBase *>> 1724 RPOT(VPBlockRecursiveTraversalWrapper<const VPBlockBase *>( 1725 Plan.getEntry())); 1726 for (const VPBasicBlock *VPBB : 1727 VPBlockUtils::blocksOnly<const VPBasicBlock>(RPOT)) 1728 for (const VPRecipeBase &Recipe : *VPBB) 1729 for (VPValue *Def : Recipe.definedValues()) 1730 assignSlot(Def); 1731 } 1732 1733 bool vputils::onlyFirstLaneUsed(VPValue *Def) { 1734 return all_of(Def->users(), [Def](VPUser *U) { 1735 return cast<VPRecipeBase>(U)->onlyFirstLaneUsed(Def); 1736 }); 1737 } 1738