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 "VPlanCFG.h" 21 #include "VPlanDominatorTree.h" 22 #include "llvm/ADT/DepthFirstIterator.h" 23 #include "llvm/ADT/PostOrderIterator.h" 24 #include "llvm/ADT/STLExtras.h" 25 #include "llvm/ADT/SmallVector.h" 26 #include "llvm/ADT/StringExtras.h" 27 #include "llvm/ADT/Twine.h" 28 #include "llvm/Analysis/LoopInfo.h" 29 #include "llvm/IR/BasicBlock.h" 30 #include "llvm/IR/CFG.h" 31 #include "llvm/IR/IRBuilder.h" 32 #include "llvm/IR/Instruction.h" 33 #include "llvm/IR/Instructions.h" 34 #include "llvm/IR/Type.h" 35 #include "llvm/IR/Value.h" 36 #include "llvm/Support/Casting.h" 37 #include "llvm/Support/CommandLine.h" 38 #include "llvm/Support/Debug.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/LoopVersioning.h" 44 #include "llvm/Transforms/Utils/ScalarEvolutionExpander.h" 45 #include <cassert> 46 #include <string> 47 #include <vector> 48 49 using namespace llvm; 50 51 namespace llvm { 52 extern cl::opt<bool> EnableVPlanNativePath; 53 } 54 55 #define DEBUG_TYPE "vplan" 56 57 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 58 raw_ostream &llvm::operator<<(raw_ostream &OS, const VPValue &V) { 59 const VPInstruction *Instr = dyn_cast<VPInstruction>(&V); 60 VPSlotTracker SlotTracker( 61 (Instr && Instr->getParent()) ? Instr->getParent()->getPlan() : nullptr); 62 V.print(OS, SlotTracker); 63 return OS; 64 } 65 #endif 66 67 Value *VPLane::getAsRuntimeExpr(IRBuilderBase &Builder, 68 const ElementCount &VF) const { 69 switch (LaneKind) { 70 case VPLane::Kind::ScalableLast: 71 // Lane = RuntimeVF - VF.getKnownMinValue() + Lane 72 return Builder.CreateSub(getRuntimeVF(Builder, Builder.getInt32Ty(), VF), 73 Builder.getInt32(VF.getKnownMinValue() - Lane)); 74 case VPLane::Kind::First: 75 return Builder.getInt32(Lane); 76 } 77 llvm_unreachable("Unknown lane kind"); 78 } 79 80 VPValue::VPValue(const unsigned char SC, Value *UV, VPDef *Def) 81 : SubclassID(SC), UnderlyingVal(UV), Def(Def) { 82 if (Def) 83 Def->addDefinedValue(this); 84 } 85 86 VPValue::~VPValue() { 87 assert(Users.empty() && "trying to delete a VPValue with remaining users"); 88 if (Def) 89 Def->removeDefinedValue(this); 90 } 91 92 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 93 void VPValue::print(raw_ostream &OS, VPSlotTracker &SlotTracker) const { 94 if (const VPRecipeBase *R = dyn_cast_or_null<VPRecipeBase>(Def)) 95 R->print(OS, "", SlotTracker); 96 else 97 printAsOperand(OS, SlotTracker); 98 } 99 100 void VPValue::dump() const { 101 const VPRecipeBase *Instr = dyn_cast_or_null<VPRecipeBase>(this->Def); 102 VPSlotTracker SlotTracker( 103 (Instr && Instr->getParent()) ? Instr->getParent()->getPlan() : nullptr); 104 print(dbgs(), SlotTracker); 105 dbgs() << "\n"; 106 } 107 108 void VPDef::dump() const { 109 const VPRecipeBase *Instr = dyn_cast_or_null<VPRecipeBase>(this); 110 VPSlotTracker SlotTracker( 111 (Instr && Instr->getParent()) ? Instr->getParent()->getPlan() : nullptr); 112 print(dbgs(), "", SlotTracker); 113 dbgs() << "\n"; 114 } 115 #endif 116 117 VPRecipeBase *VPValue::getDefiningRecipe() { 118 return cast_or_null<VPRecipeBase>(Def); 119 } 120 121 const VPRecipeBase *VPValue::getDefiningRecipe() const { 122 return cast_or_null<VPRecipeBase>(Def); 123 } 124 125 // Get the top-most entry block of \p Start. This is the entry block of the 126 // containing VPlan. This function is templated to support both const and non-const blocks 127 template <typename T> static T *getPlanEntry(T *Start) { 128 T *Next = Start; 129 T *Current = Start; 130 while ((Next = Next->getParent())) 131 Current = Next; 132 133 SmallSetVector<T *, 8> WorkList; 134 WorkList.insert(Current); 135 136 for (unsigned i = 0; i < WorkList.size(); i++) { 137 T *Current = WorkList[i]; 138 if (Current->getNumPredecessors() == 0) 139 return Current; 140 auto &Predecessors = Current->getPredecessors(); 141 WorkList.insert(Predecessors.begin(), Predecessors.end()); 142 } 143 144 llvm_unreachable("VPlan without any entry node without predecessors"); 145 } 146 147 VPlan *VPBlockBase::getPlan() { return getPlanEntry(this)->Plan; } 148 149 const VPlan *VPBlockBase::getPlan() const { return getPlanEntry(this)->Plan; } 150 151 /// \return the VPBasicBlock that is the entry of Block, possibly indirectly. 152 const VPBasicBlock *VPBlockBase::getEntryBasicBlock() const { 153 const VPBlockBase *Block = this; 154 while (const VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block)) 155 Block = Region->getEntry(); 156 return cast<VPBasicBlock>(Block); 157 } 158 159 VPBasicBlock *VPBlockBase::getEntryBasicBlock() { 160 VPBlockBase *Block = this; 161 while (VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block)) 162 Block = Region->getEntry(); 163 return cast<VPBasicBlock>(Block); 164 } 165 166 void VPBlockBase::setPlan(VPlan *ParentPlan) { 167 assert( 168 (ParentPlan->getEntry() == this || ParentPlan->getPreheader() == this) && 169 "Can only set plan on its entry or preheader block."); 170 Plan = ParentPlan; 171 } 172 173 /// \return the VPBasicBlock that is the exit of Block, possibly indirectly. 174 const VPBasicBlock *VPBlockBase::getExitingBasicBlock() const { 175 const VPBlockBase *Block = this; 176 while (const VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block)) 177 Block = Region->getExiting(); 178 return cast<VPBasicBlock>(Block); 179 } 180 181 VPBasicBlock *VPBlockBase::getExitingBasicBlock() { 182 VPBlockBase *Block = this; 183 while (VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block)) 184 Block = Region->getExiting(); 185 return cast<VPBasicBlock>(Block); 186 } 187 188 VPBlockBase *VPBlockBase::getEnclosingBlockWithSuccessors() { 189 if (!Successors.empty() || !Parent) 190 return this; 191 assert(Parent->getExiting() == this && 192 "Block w/o successors not the exiting block of its parent."); 193 return Parent->getEnclosingBlockWithSuccessors(); 194 } 195 196 VPBlockBase *VPBlockBase::getEnclosingBlockWithPredecessors() { 197 if (!Predecessors.empty() || !Parent) 198 return this; 199 assert(Parent->getEntry() == this && 200 "Block w/o predecessors not the entry of its parent."); 201 return Parent->getEnclosingBlockWithPredecessors(); 202 } 203 204 void VPBlockBase::deleteCFG(VPBlockBase *Entry) { 205 for (VPBlockBase *Block : to_vector(vp_depth_first_shallow(Entry))) 206 delete Block; 207 } 208 209 VPBasicBlock::iterator VPBasicBlock::getFirstNonPhi() { 210 iterator It = begin(); 211 while (It != end() && It->isPhi()) 212 It++; 213 return It; 214 } 215 216 Value *VPTransformState::get(VPValue *Def, const VPIteration &Instance) { 217 if (Def->isLiveIn()) 218 return Def->getLiveInIRValue(); 219 220 if (hasScalarValue(Def, Instance)) { 221 return Data 222 .PerPartScalars[Def][Instance.Part][Instance.Lane.mapToCacheIndex(VF)]; 223 } 224 225 assert(hasVectorValue(Def, Instance.Part)); 226 auto *VecPart = Data.PerPartOutput[Def][Instance.Part]; 227 if (!VecPart->getType()->isVectorTy()) { 228 assert(Instance.Lane.isFirstLane() && "cannot get lane > 0 for scalar"); 229 return VecPart; 230 } 231 // TODO: Cache created scalar values. 232 Value *Lane = Instance.Lane.getAsRuntimeExpr(Builder, VF); 233 auto *Extract = Builder.CreateExtractElement(VecPart, Lane); 234 // set(Def, Extract, Instance); 235 return Extract; 236 } 237 238 Value *VPTransformState::get(VPValue *Def, unsigned Part) { 239 // If Values have been set for this Def return the one relevant for \p Part. 240 if (hasVectorValue(Def, Part)) 241 return Data.PerPartOutput[Def][Part]; 242 243 auto GetBroadcastInstrs = [this, Def](Value *V) { 244 bool SafeToHoist = Def->isDefinedOutsideVectorRegions(); 245 if (VF.isScalar()) 246 return V; 247 // Place the code for broadcasting invariant variables in the new preheader. 248 IRBuilder<>::InsertPointGuard Guard(Builder); 249 if (SafeToHoist) { 250 BasicBlock *LoopVectorPreHeader = CFG.VPBB2IRBB[cast<VPBasicBlock>( 251 Plan->getVectorLoopRegion()->getSinglePredecessor())]; 252 if (LoopVectorPreHeader) 253 Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator()); 254 } 255 256 // Place the code for broadcasting invariant variables in the new preheader. 257 // Broadcast the scalar into all locations in the vector. 258 Value *Shuf = Builder.CreateVectorSplat(VF, V, "broadcast"); 259 260 return Shuf; 261 }; 262 263 if (!hasScalarValue(Def, {Part, 0})) { 264 assert(Def->isLiveIn() && "expected a live-in"); 265 if (Part != 0) 266 return get(Def, 0); 267 Value *IRV = Def->getLiveInIRValue(); 268 Value *B = GetBroadcastInstrs(IRV); 269 set(Def, B, Part); 270 return B; 271 } 272 273 Value *ScalarValue = get(Def, {Part, 0}); 274 // If we aren't vectorizing, we can just copy the scalar map values over 275 // to the vector map. 276 if (VF.isScalar()) { 277 set(Def, ScalarValue, Part); 278 return ScalarValue; 279 } 280 281 bool IsUniform = vputils::isUniformAfterVectorization(Def); 282 283 unsigned LastLane = IsUniform ? 0 : VF.getKnownMinValue() - 1; 284 // Check if there is a scalar value for the selected lane. 285 if (!hasScalarValue(Def, {Part, LastLane})) { 286 // At the moment, VPWidenIntOrFpInductionRecipes, VPScalarIVStepsRecipes and 287 // VPExpandSCEVRecipes can also be uniform. 288 assert((isa<VPWidenIntOrFpInductionRecipe>(Def->getDefiningRecipe()) || 289 isa<VPScalarIVStepsRecipe>(Def->getDefiningRecipe()) || 290 isa<VPExpandSCEVRecipe>(Def->getDefiningRecipe())) && 291 "unexpected recipe found to be invariant"); 292 IsUniform = true; 293 LastLane = 0; 294 } 295 296 auto *LastInst = cast<Instruction>(get(Def, {Part, LastLane})); 297 // Set the insert point after the last scalarized instruction or after the 298 // last PHI, if LastInst is a PHI. This ensures the insertelement sequence 299 // will directly follow the scalar definitions. 300 auto OldIP = Builder.saveIP(); 301 auto NewIP = 302 isa<PHINode>(LastInst) 303 ? BasicBlock::iterator(LastInst->getParent()->getFirstNonPHI()) 304 : std::next(BasicBlock::iterator(LastInst)); 305 Builder.SetInsertPoint(&*NewIP); 306 307 // However, if we are vectorizing, we need to construct the vector values. 308 // If the value is known to be uniform after vectorization, we can just 309 // broadcast the scalar value corresponding to lane zero for each unroll 310 // iteration. Otherwise, we construct the vector values using 311 // insertelement instructions. Since the resulting vectors are stored in 312 // State, we will only generate the insertelements once. 313 Value *VectorValue = nullptr; 314 if (IsUniform) { 315 VectorValue = GetBroadcastInstrs(ScalarValue); 316 set(Def, VectorValue, Part); 317 } else { 318 // Initialize packing with insertelements to start from undef. 319 assert(!VF.isScalable() && "VF is assumed to be non scalable."); 320 Value *Undef = PoisonValue::get(VectorType::get(LastInst->getType(), VF)); 321 set(Def, Undef, Part); 322 for (unsigned Lane = 0; Lane < VF.getKnownMinValue(); ++Lane) 323 packScalarIntoVectorValue(Def, {Part, Lane}); 324 VectorValue = get(Def, Part); 325 } 326 Builder.restoreIP(OldIP); 327 return VectorValue; 328 } 329 330 BasicBlock *VPTransformState::CFGState::getPreheaderBBFor(VPRecipeBase *R) { 331 VPRegionBlock *LoopRegion = R->getParent()->getEnclosingLoopRegion(); 332 return VPBB2IRBB[LoopRegion->getPreheaderVPBB()]; 333 } 334 335 void VPTransformState::addNewMetadata(Instruction *To, 336 const Instruction *Orig) { 337 // If the loop was versioned with memchecks, add the corresponding no-alias 338 // metadata. 339 if (LVer && (isa<LoadInst>(Orig) || isa<StoreInst>(Orig))) 340 LVer->annotateInstWithNoAlias(To, Orig); 341 } 342 343 void VPTransformState::addMetadata(Instruction *To, Instruction *From) { 344 // No source instruction to transfer metadata from? 345 if (!From) 346 return; 347 348 propagateMetadata(To, From); 349 addNewMetadata(To, From); 350 } 351 352 void VPTransformState::addMetadata(ArrayRef<Value *> To, Instruction *From) { 353 // No source instruction to transfer metadata from? 354 if (!From) 355 return; 356 357 for (Value *V : To) { 358 if (Instruction *I = dyn_cast<Instruction>(V)) 359 addMetadata(I, From); 360 } 361 } 362 363 void VPTransformState::setDebugLocFrom(DebugLoc DL) { 364 const DILocation *DIL = DL; 365 // When a FSDiscriminator is enabled, we don't need to add the multiply 366 // factors to the discriminators. 367 if (DIL && 368 Builder.GetInsertBlock() 369 ->getParent() 370 ->shouldEmitDebugInfoForProfiling() && 371 !EnableFSDiscriminator) { 372 // FIXME: For scalable vectors, assume vscale=1. 373 auto NewDIL = 374 DIL->cloneByMultiplyingDuplicationFactor(UF * VF.getKnownMinValue()); 375 if (NewDIL) 376 Builder.SetCurrentDebugLocation(*NewDIL); 377 else 378 LLVM_DEBUG(dbgs() << "Failed to create new discriminator: " 379 << DIL->getFilename() << " Line: " << DIL->getLine()); 380 } else 381 Builder.SetCurrentDebugLocation(DIL); 382 } 383 384 void VPTransformState::packScalarIntoVectorValue(VPValue *Def, 385 const VPIteration &Instance) { 386 Value *ScalarInst = get(Def, Instance); 387 Value *VectorValue = get(Def, Instance.Part); 388 VectorValue = Builder.CreateInsertElement( 389 VectorValue, ScalarInst, Instance.Lane.getAsRuntimeExpr(Builder, VF)); 390 set(Def, VectorValue, Instance.Part); 391 } 392 393 BasicBlock * 394 VPBasicBlock::createEmptyBasicBlock(VPTransformState::CFGState &CFG) { 395 // BB stands for IR BasicBlocks. VPBB stands for VPlan VPBasicBlocks. 396 // Pred stands for Predessor. Prev stands for Previous - last visited/created. 397 BasicBlock *PrevBB = CFG.PrevBB; 398 BasicBlock *NewBB = BasicBlock::Create(PrevBB->getContext(), getName(), 399 PrevBB->getParent(), CFG.ExitBB); 400 LLVM_DEBUG(dbgs() << "LV: created " << NewBB->getName() << '\n'); 401 402 // Hook up the new basic block to its predecessors. 403 for (VPBlockBase *PredVPBlock : getHierarchicalPredecessors()) { 404 VPBasicBlock *PredVPBB = PredVPBlock->getExitingBasicBlock(); 405 auto &PredVPSuccessors = PredVPBB->getHierarchicalSuccessors(); 406 BasicBlock *PredBB = CFG.VPBB2IRBB[PredVPBB]; 407 408 assert(PredBB && "Predecessor basic-block not found building successor."); 409 auto *PredBBTerminator = PredBB->getTerminator(); 410 LLVM_DEBUG(dbgs() << "LV: draw edge from" << PredBB->getName() << '\n'); 411 412 auto *TermBr = dyn_cast<BranchInst>(PredBBTerminator); 413 if (isa<UnreachableInst>(PredBBTerminator)) { 414 assert(PredVPSuccessors.size() == 1 && 415 "Predecessor ending w/o branch must have single successor."); 416 DebugLoc DL = PredBBTerminator->getDebugLoc(); 417 PredBBTerminator->eraseFromParent(); 418 auto *Br = BranchInst::Create(NewBB, PredBB); 419 Br->setDebugLoc(DL); 420 } else if (TermBr && !TermBr->isConditional()) { 421 TermBr->setSuccessor(0, NewBB); 422 } else { 423 // Set each forward successor here when it is created, excluding 424 // backedges. A backward successor is set when the branch is created. 425 unsigned idx = PredVPSuccessors.front() == this ? 0 : 1; 426 assert(!TermBr->getSuccessor(idx) && 427 "Trying to reset an existing successor block."); 428 TermBr->setSuccessor(idx, NewBB); 429 } 430 } 431 return NewBB; 432 } 433 434 void VPBasicBlock::execute(VPTransformState *State) { 435 bool Replica = State->Instance && !State->Instance->isFirstIteration(); 436 VPBasicBlock *PrevVPBB = State->CFG.PrevVPBB; 437 VPBlockBase *SingleHPred = nullptr; 438 BasicBlock *NewBB = State->CFG.PrevBB; // Reuse it if possible. 439 440 auto IsLoopRegion = [](VPBlockBase *BB) { 441 auto *R = dyn_cast<VPRegionBlock>(BB); 442 return R && !R->isReplicator(); 443 }; 444 445 // 1. Create an IR basic block, or reuse the last one or ExitBB if possible. 446 if (getPlan()->getVectorLoopRegion()->getSingleSuccessor() == this) { 447 // ExitBB can be re-used for the exit block of the Plan. 448 NewBB = State->CFG.ExitBB; 449 State->CFG.PrevBB = NewBB; 450 451 // Update the branch instruction in the predecessor to branch to ExitBB. 452 VPBlockBase *PredVPB = getSingleHierarchicalPredecessor(); 453 VPBasicBlock *ExitingVPBB = PredVPB->getExitingBasicBlock(); 454 assert(PredVPB->getSingleSuccessor() == this && 455 "predecessor must have the current block as only successor"); 456 BasicBlock *ExitingBB = State->CFG.VPBB2IRBB[ExitingVPBB]; 457 // The Exit block of a loop is always set to be successor 0 of the Exiting 458 // block. 459 cast<BranchInst>(ExitingBB->getTerminator())->setSuccessor(0, NewBB); 460 } else if (PrevVPBB && /* A */ 461 !((SingleHPred = getSingleHierarchicalPredecessor()) && 462 SingleHPred->getExitingBasicBlock() == PrevVPBB && 463 PrevVPBB->getSingleHierarchicalSuccessor() && 464 (SingleHPred->getParent() == getEnclosingLoopRegion() && 465 !IsLoopRegion(SingleHPred))) && /* B */ 466 !(Replica && getPredecessors().empty())) { /* C */ 467 // The last IR basic block is reused, as an optimization, in three cases: 468 // A. the first VPBB reuses the loop pre-header BB - when PrevVPBB is null; 469 // B. when the current VPBB has a single (hierarchical) predecessor which 470 // is PrevVPBB and the latter has a single (hierarchical) successor which 471 // both are in the same non-replicator region; and 472 // C. when the current VPBB is an entry of a region replica - where PrevVPBB 473 // is the exiting VPBB of this region from a previous instance, or the 474 // predecessor of this region. 475 476 NewBB = createEmptyBasicBlock(State->CFG); 477 State->Builder.SetInsertPoint(NewBB); 478 // Temporarily terminate with unreachable until CFG is rewired. 479 UnreachableInst *Terminator = State->Builder.CreateUnreachable(); 480 // Register NewBB in its loop. In innermost loops its the same for all 481 // BB's. 482 if (State->CurrentVectorLoop) 483 State->CurrentVectorLoop->addBasicBlockToLoop(NewBB, *State->LI); 484 State->Builder.SetInsertPoint(Terminator); 485 State->CFG.PrevBB = NewBB; 486 } 487 488 // 2. Fill the IR basic block with IR instructions. 489 LLVM_DEBUG(dbgs() << "LV: vectorizing VPBB:" << getName() 490 << " in BB:" << NewBB->getName() << '\n'); 491 492 State->CFG.VPBB2IRBB[this] = NewBB; 493 State->CFG.PrevVPBB = this; 494 495 for (VPRecipeBase &Recipe : Recipes) 496 Recipe.execute(*State); 497 498 LLVM_DEBUG(dbgs() << "LV: filled BB:" << *NewBB); 499 } 500 501 void VPBasicBlock::dropAllReferences(VPValue *NewValue) { 502 for (VPRecipeBase &R : Recipes) { 503 for (auto *Def : R.definedValues()) 504 Def->replaceAllUsesWith(NewValue); 505 506 for (unsigned I = 0, E = R.getNumOperands(); I != E; I++) 507 R.setOperand(I, NewValue); 508 } 509 } 510 511 VPBasicBlock *VPBasicBlock::splitAt(iterator SplitAt) { 512 assert((SplitAt == end() || SplitAt->getParent() == this) && 513 "can only split at a position in the same block"); 514 515 SmallVector<VPBlockBase *, 2> Succs(successors()); 516 // First, disconnect the current block from its successors. 517 for (VPBlockBase *Succ : Succs) 518 VPBlockUtils::disconnectBlocks(this, Succ); 519 520 // Create new empty block after the block to split. 521 auto *SplitBlock = new VPBasicBlock(getName() + ".split"); 522 VPBlockUtils::insertBlockAfter(SplitBlock, this); 523 524 // Add successors for block to split to new block. 525 for (VPBlockBase *Succ : Succs) 526 VPBlockUtils::connectBlocks(SplitBlock, Succ); 527 528 // Finally, move the recipes starting at SplitAt to new block. 529 for (VPRecipeBase &ToMove : 530 make_early_inc_range(make_range(SplitAt, this->end()))) 531 ToMove.moveBefore(*SplitBlock, SplitBlock->end()); 532 533 return SplitBlock; 534 } 535 536 VPRegionBlock *VPBasicBlock::getEnclosingLoopRegion() { 537 VPRegionBlock *P = getParent(); 538 if (P && P->isReplicator()) { 539 P = P->getParent(); 540 assert(!cast<VPRegionBlock>(P)->isReplicator() && 541 "unexpected nested replicate regions"); 542 } 543 return P; 544 } 545 546 static bool hasConditionalTerminator(const VPBasicBlock *VPBB) { 547 if (VPBB->empty()) { 548 assert( 549 VPBB->getNumSuccessors() < 2 && 550 "block with multiple successors doesn't have a recipe as terminator"); 551 return false; 552 } 553 554 const VPRecipeBase *R = &VPBB->back(); 555 auto *VPI = dyn_cast<VPInstruction>(R); 556 bool IsCondBranch = 557 isa<VPBranchOnMaskRecipe>(R) || 558 (VPI && (VPI->getOpcode() == VPInstruction::BranchOnCond || 559 VPI->getOpcode() == VPInstruction::BranchOnCount)); 560 (void)IsCondBranch; 561 562 if (VPBB->getNumSuccessors() >= 2 || VPBB->isExiting()) { 563 assert(IsCondBranch && "block with multiple successors not terminated by " 564 "conditional branch recipe"); 565 566 return true; 567 } 568 569 assert( 570 !IsCondBranch && 571 "block with 0 or 1 successors terminated by conditional branch recipe"); 572 return false; 573 } 574 575 VPRecipeBase *VPBasicBlock::getTerminator() { 576 if (hasConditionalTerminator(this)) 577 return &back(); 578 return nullptr; 579 } 580 581 const VPRecipeBase *VPBasicBlock::getTerminator() const { 582 if (hasConditionalTerminator(this)) 583 return &back(); 584 return nullptr; 585 } 586 587 bool VPBasicBlock::isExiting() const { 588 return getParent()->getExitingBasicBlock() == this; 589 } 590 591 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 592 void VPBlockBase::printSuccessors(raw_ostream &O, const Twine &Indent) const { 593 if (getSuccessors().empty()) { 594 O << Indent << "No successors\n"; 595 } else { 596 O << Indent << "Successor(s): "; 597 ListSeparator LS; 598 for (auto *Succ : getSuccessors()) 599 O << LS << Succ->getName(); 600 O << '\n'; 601 } 602 } 603 604 void VPBasicBlock::print(raw_ostream &O, const Twine &Indent, 605 VPSlotTracker &SlotTracker) const { 606 O << Indent << getName() << ":\n"; 607 608 auto RecipeIndent = Indent + " "; 609 for (const VPRecipeBase &Recipe : *this) { 610 Recipe.print(O, RecipeIndent, SlotTracker); 611 O << '\n'; 612 } 613 614 printSuccessors(O, Indent); 615 } 616 #endif 617 618 void VPRegionBlock::dropAllReferences(VPValue *NewValue) { 619 for (VPBlockBase *Block : vp_depth_first_shallow(Entry)) 620 // Drop all references in VPBasicBlocks and replace all uses with 621 // DummyValue. 622 Block->dropAllReferences(NewValue); 623 } 624 625 void VPRegionBlock::execute(VPTransformState *State) { 626 ReversePostOrderTraversal<VPBlockShallowTraversalWrapper<VPBlockBase *>> 627 RPOT(Entry); 628 629 if (!isReplicator()) { 630 // Create and register the new vector loop. 631 Loop *PrevLoop = State->CurrentVectorLoop; 632 State->CurrentVectorLoop = State->LI->AllocateLoop(); 633 BasicBlock *VectorPH = State->CFG.VPBB2IRBB[getPreheaderVPBB()]; 634 Loop *ParentLoop = State->LI->getLoopFor(VectorPH); 635 636 // Insert the new loop into the loop nest and register the new basic blocks 637 // before calling any utilities such as SCEV that require valid LoopInfo. 638 if (ParentLoop) 639 ParentLoop->addChildLoop(State->CurrentVectorLoop); 640 else 641 State->LI->addTopLevelLoop(State->CurrentVectorLoop); 642 643 // Visit the VPBlocks connected to "this", starting from it. 644 for (VPBlockBase *Block : RPOT) { 645 LLVM_DEBUG(dbgs() << "LV: VPBlock in RPO " << Block->getName() << '\n'); 646 Block->execute(State); 647 } 648 649 State->CurrentVectorLoop = PrevLoop; 650 return; 651 } 652 653 assert(!State->Instance && "Replicating a Region with non-null instance."); 654 655 // Enter replicating mode. 656 State->Instance = VPIteration(0, 0); 657 658 for (unsigned Part = 0, UF = State->UF; Part < UF; ++Part) { 659 State->Instance->Part = Part; 660 assert(!State->VF.isScalable() && "VF is assumed to be non scalable."); 661 for (unsigned Lane = 0, VF = State->VF.getKnownMinValue(); Lane < VF; 662 ++Lane) { 663 State->Instance->Lane = VPLane(Lane, VPLane::Kind::First); 664 // Visit the VPBlocks connected to \p this, starting from it. 665 for (VPBlockBase *Block : RPOT) { 666 LLVM_DEBUG(dbgs() << "LV: VPBlock in RPO " << Block->getName() << '\n'); 667 Block->execute(State); 668 } 669 } 670 } 671 672 // Exit replicating mode. 673 State->Instance.reset(); 674 } 675 676 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 677 void VPRegionBlock::print(raw_ostream &O, const Twine &Indent, 678 VPSlotTracker &SlotTracker) const { 679 O << Indent << (isReplicator() ? "<xVFxUF> " : "<x1> ") << getName() << ": {"; 680 auto NewIndent = Indent + " "; 681 for (auto *BlockBase : vp_depth_first_shallow(Entry)) { 682 O << '\n'; 683 BlockBase->print(O, NewIndent, SlotTracker); 684 } 685 O << Indent << "}\n"; 686 687 printSuccessors(O, Indent); 688 } 689 #endif 690 691 VPlan::~VPlan() { 692 for (auto &KV : LiveOuts) 693 delete KV.second; 694 LiveOuts.clear(); 695 696 if (Entry) { 697 VPValue DummyValue; 698 for (VPBlockBase *Block : vp_depth_first_shallow(Entry)) 699 Block->dropAllReferences(&DummyValue); 700 701 VPBlockBase::deleteCFG(Entry); 702 703 Preheader->dropAllReferences(&DummyValue); 704 delete Preheader; 705 } 706 for (VPValue *VPV : VPLiveInsToFree) 707 delete VPV; 708 if (BackedgeTakenCount) 709 delete BackedgeTakenCount; 710 } 711 712 VPlanPtr VPlan::createInitialVPlan(const SCEV *TripCount, ScalarEvolution &SE) { 713 VPBasicBlock *Preheader = new VPBasicBlock("ph"); 714 VPBasicBlock *VecPreheader = new VPBasicBlock("vector.ph"); 715 auto Plan = std::make_unique<VPlan>(Preheader, VecPreheader); 716 Plan->TripCount = 717 vputils::getOrCreateVPValueForSCEVExpr(*Plan, TripCount, SE); 718 return Plan; 719 } 720 721 VPActiveLaneMaskPHIRecipe *VPlan::getActiveLaneMaskPhi() { 722 VPBasicBlock *Header = getVectorLoopRegion()->getEntryBasicBlock(); 723 for (VPRecipeBase &R : Header->phis()) { 724 if (isa<VPActiveLaneMaskPHIRecipe>(&R)) 725 return cast<VPActiveLaneMaskPHIRecipe>(&R); 726 } 727 return nullptr; 728 } 729 730 void VPlan::prepareToExecute(Value *TripCountV, Value *VectorTripCountV, 731 Value *CanonicalIVStartValue, 732 VPTransformState &State, 733 bool IsEpilogueVectorization) { 734 // Check if the backedge taken count is needed, and if so build it. 735 if (BackedgeTakenCount && BackedgeTakenCount->getNumUsers()) { 736 IRBuilder<> Builder(State.CFG.PrevBB->getTerminator()); 737 auto *TCMO = Builder.CreateSub(TripCountV, 738 ConstantInt::get(TripCountV->getType(), 1), 739 "trip.count.minus.1"); 740 auto VF = State.VF; 741 Value *VTCMO = 742 VF.isScalar() ? TCMO : Builder.CreateVectorSplat(VF, TCMO, "broadcast"); 743 for (unsigned Part = 0, UF = State.UF; Part < UF; ++Part) 744 State.set(BackedgeTakenCount, VTCMO, Part); 745 } 746 747 for (unsigned Part = 0, UF = State.UF; Part < UF; ++Part) 748 State.set(&VectorTripCount, VectorTripCountV, Part); 749 750 // When vectorizing the epilogue loop, the canonical induction start value 751 // needs to be changed from zero to the value after the main vector loop. 752 // FIXME: Improve modeling for canonical IV start values in the epilogue loop. 753 if (CanonicalIVStartValue) { 754 VPValue *VPV = getVPValueOrAddLiveIn(CanonicalIVStartValue); 755 auto *IV = getCanonicalIV(); 756 assert(all_of(IV->users(), 757 [](const VPUser *U) { 758 return isa<VPScalarIVStepsRecipe>(U) || 759 isa<VPDerivedIVRecipe>(U) || 760 cast<VPInstruction>(U)->getOpcode() == 761 VPInstruction::CanonicalIVIncrement; 762 }) && 763 "the canonical IV should only be used by its increment or " 764 "ScalarIVSteps when resetting the start value"); 765 IV->setOperand(0, VPV); 766 } 767 } 768 769 /// Generate the code inside the preheader and body of the vectorized loop. 770 /// Assumes a single pre-header basic-block was created for this. Introduce 771 /// additional basic-blocks as needed, and fill them all. 772 void VPlan::execute(VPTransformState *State) { 773 // Set the reverse mapping from VPValues to Values for code generation. 774 for (auto &Entry : Value2VPValue) 775 State->VPValue2Value[Entry.second] = Entry.first; 776 777 // Initialize CFG state. 778 State->CFG.PrevVPBB = nullptr; 779 State->CFG.ExitBB = State->CFG.PrevBB->getSingleSuccessor(); 780 BasicBlock *VectorPreHeader = State->CFG.PrevBB; 781 State->Builder.SetInsertPoint(VectorPreHeader->getTerminator()); 782 783 // Generate code in the loop pre-header and body. 784 for (VPBlockBase *Block : vp_depth_first_shallow(Entry)) 785 Block->execute(State); 786 787 VPBasicBlock *LatchVPBB = getVectorLoopRegion()->getExitingBasicBlock(); 788 BasicBlock *VectorLatchBB = State->CFG.VPBB2IRBB[LatchVPBB]; 789 790 // Fix the latch value of canonical, reduction and first-order recurrences 791 // phis in the vector loop. 792 VPBasicBlock *Header = getVectorLoopRegion()->getEntryBasicBlock(); 793 for (VPRecipeBase &R : Header->phis()) { 794 // Skip phi-like recipes that generate their backedege values themselves. 795 if (isa<VPWidenPHIRecipe>(&R)) 796 continue; 797 798 if (isa<VPWidenPointerInductionRecipe>(&R) || 799 isa<VPWidenIntOrFpInductionRecipe>(&R)) { 800 PHINode *Phi = nullptr; 801 if (isa<VPWidenIntOrFpInductionRecipe>(&R)) { 802 Phi = cast<PHINode>(State->get(R.getVPSingleValue(), 0)); 803 } else { 804 auto *WidenPhi = cast<VPWidenPointerInductionRecipe>(&R); 805 // TODO: Split off the case that all users of a pointer phi are scalar 806 // from the VPWidenPointerInductionRecipe. 807 if (WidenPhi->onlyScalarsGenerated(State->VF)) 808 continue; 809 810 auto *GEP = cast<GetElementPtrInst>(State->get(WidenPhi, 0)); 811 Phi = cast<PHINode>(GEP->getPointerOperand()); 812 } 813 814 Phi->setIncomingBlock(1, VectorLatchBB); 815 816 // Move the last step to the end of the latch block. This ensures 817 // consistent placement of all induction updates. 818 Instruction *Inc = cast<Instruction>(Phi->getIncomingValue(1)); 819 Inc->moveBefore(VectorLatchBB->getTerminator()->getPrevNode()); 820 continue; 821 } 822 823 auto *PhiR = cast<VPHeaderPHIRecipe>(&R); 824 // For canonical IV, first-order recurrences and in-order reduction phis, 825 // only a single part is generated, which provides the last part from the 826 // previous iteration. For non-ordered reductions all UF parts are 827 // generated. 828 bool SinglePartNeeded = isa<VPCanonicalIVPHIRecipe>(PhiR) || 829 isa<VPFirstOrderRecurrencePHIRecipe>(PhiR) || 830 (isa<VPReductionPHIRecipe>(PhiR) && 831 cast<VPReductionPHIRecipe>(PhiR)->isOrdered()); 832 unsigned LastPartForNewPhi = SinglePartNeeded ? 1 : State->UF; 833 834 for (unsigned Part = 0; Part < LastPartForNewPhi; ++Part) { 835 Value *Phi = State->get(PhiR, Part); 836 Value *Val = State->get(PhiR->getBackedgeValue(), 837 SinglePartNeeded ? State->UF - 1 : Part); 838 cast<PHINode>(Phi)->addIncoming(Val, VectorLatchBB); 839 } 840 } 841 842 // We do not attempt to preserve DT for outer loop vectorization currently. 843 if (!EnableVPlanNativePath) { 844 BasicBlock *VectorHeaderBB = State->CFG.VPBB2IRBB[Header]; 845 State->DT->addNewBlock(VectorHeaderBB, VectorPreHeader); 846 updateDominatorTree(State->DT, VectorHeaderBB, VectorLatchBB, 847 State->CFG.ExitBB); 848 } 849 } 850 851 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 852 LLVM_DUMP_METHOD 853 void VPlan::print(raw_ostream &O) const { 854 VPSlotTracker SlotTracker(this); 855 856 O << "VPlan '" << getName() << "' {"; 857 858 if (VectorTripCount.getNumUsers() > 0) { 859 O << "\nLive-in "; 860 VectorTripCount.printAsOperand(O, SlotTracker); 861 O << " = vector-trip-count"; 862 } 863 864 if (BackedgeTakenCount && BackedgeTakenCount->getNumUsers()) { 865 O << "\nLive-in "; 866 BackedgeTakenCount->printAsOperand(O, SlotTracker); 867 O << " = backedge-taken count"; 868 } 869 870 O << "\n"; 871 if (TripCount->isLiveIn()) 872 O << "Live-in "; 873 TripCount->printAsOperand(O, SlotTracker); 874 O << " = original trip-count"; 875 O << "\n"; 876 877 if (!getPreheader()->empty()) { 878 O << "\n"; 879 getPreheader()->print(O, "", SlotTracker); 880 } 881 882 for (const VPBlockBase *Block : vp_depth_first_shallow(getEntry())) { 883 O << '\n'; 884 Block->print(O, "", SlotTracker); 885 } 886 887 if (!LiveOuts.empty()) 888 O << "\n"; 889 for (const auto &KV : LiveOuts) { 890 KV.second->print(O, SlotTracker); 891 } 892 893 O << "}\n"; 894 } 895 896 std::string VPlan::getName() const { 897 std::string Out; 898 raw_string_ostream RSO(Out); 899 RSO << Name << " for "; 900 if (!VFs.empty()) { 901 RSO << "VF={" << VFs[0]; 902 for (ElementCount VF : drop_begin(VFs)) 903 RSO << "," << VF; 904 RSO << "},"; 905 } 906 907 if (UFs.empty()) { 908 RSO << "UF>=1"; 909 } else { 910 RSO << "UF={" << UFs[0]; 911 for (unsigned UF : drop_begin(UFs)) 912 RSO << "," << UF; 913 RSO << "}"; 914 } 915 916 return Out; 917 } 918 919 LLVM_DUMP_METHOD 920 void VPlan::printDOT(raw_ostream &O) const { 921 VPlanPrinter Printer(O, *this); 922 Printer.dump(); 923 } 924 925 LLVM_DUMP_METHOD 926 void VPlan::dump() const { print(dbgs()); } 927 #endif 928 929 void VPlan::addLiveOut(PHINode *PN, VPValue *V) { 930 assert(LiveOuts.count(PN) == 0 && "an exit value for PN already exists"); 931 LiveOuts.insert({PN, new VPLiveOut(PN, V)}); 932 } 933 934 void VPlan::updateDominatorTree(DominatorTree *DT, BasicBlock *LoopHeaderBB, 935 BasicBlock *LoopLatchBB, 936 BasicBlock *LoopExitBB) { 937 // The vector body may be more than a single basic-block by this point. 938 // Update the dominator tree information inside the vector body by propagating 939 // it from header to latch, expecting only triangular control-flow, if any. 940 BasicBlock *PostDomSucc = nullptr; 941 for (auto *BB = LoopHeaderBB; BB != LoopLatchBB; BB = PostDomSucc) { 942 // Get the list of successors of this block. 943 std::vector<BasicBlock *> Succs(succ_begin(BB), succ_end(BB)); 944 assert(Succs.size() <= 2 && 945 "Basic block in vector loop has more than 2 successors."); 946 PostDomSucc = Succs[0]; 947 if (Succs.size() == 1) { 948 assert(PostDomSucc->getSinglePredecessor() && 949 "PostDom successor has more than one predecessor."); 950 DT->addNewBlock(PostDomSucc, BB); 951 continue; 952 } 953 BasicBlock *InterimSucc = Succs[1]; 954 if (PostDomSucc->getSingleSuccessor() == InterimSucc) { 955 PostDomSucc = Succs[1]; 956 InterimSucc = Succs[0]; 957 } 958 assert(InterimSucc->getSingleSuccessor() == PostDomSucc && 959 "One successor of a basic block does not lead to the other."); 960 assert(InterimSucc->getSinglePredecessor() && 961 "Interim successor has more than one predecessor."); 962 assert(PostDomSucc->hasNPredecessors(2) && 963 "PostDom successor has more than two predecessors."); 964 DT->addNewBlock(InterimSucc, BB); 965 DT->addNewBlock(PostDomSucc, BB); 966 } 967 // Latch block is a new dominator for the loop exit. 968 DT->changeImmediateDominator(LoopExitBB, LoopLatchBB); 969 assert(DT->verify(DominatorTree::VerificationLevel::Fast)); 970 } 971 972 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 973 974 Twine VPlanPrinter::getUID(const VPBlockBase *Block) { 975 return (isa<VPRegionBlock>(Block) ? "cluster_N" : "N") + 976 Twine(getOrCreateBID(Block)); 977 } 978 979 Twine VPlanPrinter::getOrCreateName(const VPBlockBase *Block) { 980 const std::string &Name = Block->getName(); 981 if (!Name.empty()) 982 return Name; 983 return "VPB" + Twine(getOrCreateBID(Block)); 984 } 985 986 void VPlanPrinter::dump() { 987 Depth = 1; 988 bumpIndent(0); 989 OS << "digraph VPlan {\n"; 990 OS << "graph [labelloc=t, fontsize=30; label=\"Vectorization Plan"; 991 if (!Plan.getName().empty()) 992 OS << "\\n" << DOT::EscapeString(Plan.getName()); 993 if (Plan.BackedgeTakenCount) { 994 OS << ", where:\\n"; 995 Plan.BackedgeTakenCount->print(OS, SlotTracker); 996 OS << " := BackedgeTakenCount"; 997 } 998 OS << "\"]\n"; 999 OS << "node [shape=rect, fontname=Courier, fontsize=30]\n"; 1000 OS << "edge [fontname=Courier, fontsize=30]\n"; 1001 OS << "compound=true\n"; 1002 1003 dumpBlock(Plan.getPreheader()); 1004 1005 for (const VPBlockBase *Block : vp_depth_first_shallow(Plan.getEntry())) 1006 dumpBlock(Block); 1007 1008 OS << "}\n"; 1009 } 1010 1011 void VPlanPrinter::dumpBlock(const VPBlockBase *Block) { 1012 if (const VPBasicBlock *BasicBlock = dyn_cast<VPBasicBlock>(Block)) 1013 dumpBasicBlock(BasicBlock); 1014 else if (const VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block)) 1015 dumpRegion(Region); 1016 else 1017 llvm_unreachable("Unsupported kind of VPBlock."); 1018 } 1019 1020 void VPlanPrinter::drawEdge(const VPBlockBase *From, const VPBlockBase *To, 1021 bool Hidden, const Twine &Label) { 1022 // Due to "dot" we print an edge between two regions as an edge between the 1023 // exiting basic block and the entry basic of the respective regions. 1024 const VPBlockBase *Tail = From->getExitingBasicBlock(); 1025 const VPBlockBase *Head = To->getEntryBasicBlock(); 1026 OS << Indent << getUID(Tail) << " -> " << getUID(Head); 1027 OS << " [ label=\"" << Label << '\"'; 1028 if (Tail != From) 1029 OS << " ltail=" << getUID(From); 1030 if (Head != To) 1031 OS << " lhead=" << getUID(To); 1032 if (Hidden) 1033 OS << "; splines=none"; 1034 OS << "]\n"; 1035 } 1036 1037 void VPlanPrinter::dumpEdges(const VPBlockBase *Block) { 1038 auto &Successors = Block->getSuccessors(); 1039 if (Successors.size() == 1) 1040 drawEdge(Block, Successors.front(), false, ""); 1041 else if (Successors.size() == 2) { 1042 drawEdge(Block, Successors.front(), false, "T"); 1043 drawEdge(Block, Successors.back(), false, "F"); 1044 } else { 1045 unsigned SuccessorNumber = 0; 1046 for (auto *Successor : Successors) 1047 drawEdge(Block, Successor, false, Twine(SuccessorNumber++)); 1048 } 1049 } 1050 1051 void VPlanPrinter::dumpBasicBlock(const VPBasicBlock *BasicBlock) { 1052 // Implement dot-formatted dump by performing plain-text dump into the 1053 // temporary storage followed by some post-processing. 1054 OS << Indent << getUID(BasicBlock) << " [label =\n"; 1055 bumpIndent(1); 1056 std::string Str; 1057 raw_string_ostream SS(Str); 1058 // Use no indentation as we need to wrap the lines into quotes ourselves. 1059 BasicBlock->print(SS, "", SlotTracker); 1060 1061 // We need to process each line of the output separately, so split 1062 // single-string plain-text dump. 1063 SmallVector<StringRef, 0> Lines; 1064 StringRef(Str).rtrim('\n').split(Lines, "\n"); 1065 1066 auto EmitLine = [&](StringRef Line, StringRef Suffix) { 1067 OS << Indent << '"' << DOT::EscapeString(Line.str()) << "\\l\"" << Suffix; 1068 }; 1069 1070 // Don't need the "+" after the last line. 1071 for (auto Line : make_range(Lines.begin(), Lines.end() - 1)) 1072 EmitLine(Line, " +\n"); 1073 EmitLine(Lines.back(), "\n"); 1074 1075 bumpIndent(-1); 1076 OS << Indent << "]\n"; 1077 1078 dumpEdges(BasicBlock); 1079 } 1080 1081 void VPlanPrinter::dumpRegion(const VPRegionBlock *Region) { 1082 OS << Indent << "subgraph " << getUID(Region) << " {\n"; 1083 bumpIndent(1); 1084 OS << Indent << "fontname=Courier\n" 1085 << Indent << "label=\"" 1086 << DOT::EscapeString(Region->isReplicator() ? "<xVFxUF> " : "<x1> ") 1087 << DOT::EscapeString(Region->getName()) << "\"\n"; 1088 // Dump the blocks of the region. 1089 assert(Region->getEntry() && "Region contains no inner blocks."); 1090 for (const VPBlockBase *Block : vp_depth_first_shallow(Region->getEntry())) 1091 dumpBlock(Block); 1092 bumpIndent(-1); 1093 OS << Indent << "}\n"; 1094 dumpEdges(Region); 1095 } 1096 1097 void VPlanIngredient::print(raw_ostream &O) const { 1098 if (auto *Inst = dyn_cast<Instruction>(V)) { 1099 if (!Inst->getType()->isVoidTy()) { 1100 Inst->printAsOperand(O, false); 1101 O << " = "; 1102 } 1103 O << Inst->getOpcodeName() << " "; 1104 unsigned E = Inst->getNumOperands(); 1105 if (E > 0) { 1106 Inst->getOperand(0)->printAsOperand(O, false); 1107 for (unsigned I = 1; I < E; ++I) 1108 Inst->getOperand(I)->printAsOperand(O << ", ", false); 1109 } 1110 } else // !Inst 1111 V->printAsOperand(O, false); 1112 } 1113 1114 #endif 1115 1116 template void DomTreeBuilder::Calculate<VPDominatorTree>(VPDominatorTree &DT); 1117 1118 void VPValue::replaceAllUsesWith(VPValue *New) { 1119 for (unsigned J = 0; J < getNumUsers();) { 1120 VPUser *User = Users[J]; 1121 unsigned NumUsers = getNumUsers(); 1122 for (unsigned I = 0, E = User->getNumOperands(); I < E; ++I) 1123 if (User->getOperand(I) == this) 1124 User->setOperand(I, New); 1125 // If a user got removed after updating the current user, the next user to 1126 // update will be moved to the current position, so we only need to 1127 // increment the index if the number of users did not change. 1128 if (NumUsers == getNumUsers()) 1129 J++; 1130 } 1131 } 1132 1133 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1134 void VPValue::printAsOperand(raw_ostream &OS, VPSlotTracker &Tracker) const { 1135 if (const Value *UV = getUnderlyingValue()) { 1136 OS << "ir<"; 1137 UV->printAsOperand(OS, false); 1138 OS << ">"; 1139 return; 1140 } 1141 1142 unsigned Slot = Tracker.getSlot(this); 1143 if (Slot == unsigned(-1)) 1144 OS << "<badref>"; 1145 else 1146 OS << "vp<%" << Tracker.getSlot(this) << ">"; 1147 } 1148 1149 void VPUser::printOperands(raw_ostream &O, VPSlotTracker &SlotTracker) const { 1150 interleaveComma(operands(), O, [&O, &SlotTracker](VPValue *Op) { 1151 Op->printAsOperand(O, SlotTracker); 1152 }); 1153 } 1154 #endif 1155 1156 void VPInterleavedAccessInfo::visitRegion(VPRegionBlock *Region, 1157 Old2NewTy &Old2New, 1158 InterleavedAccessInfo &IAI) { 1159 ReversePostOrderTraversal<VPBlockShallowTraversalWrapper<VPBlockBase *>> 1160 RPOT(Region->getEntry()); 1161 for (VPBlockBase *Base : RPOT) { 1162 visitBlock(Base, Old2New, IAI); 1163 } 1164 } 1165 1166 void VPInterleavedAccessInfo::visitBlock(VPBlockBase *Block, Old2NewTy &Old2New, 1167 InterleavedAccessInfo &IAI) { 1168 if (VPBasicBlock *VPBB = dyn_cast<VPBasicBlock>(Block)) { 1169 for (VPRecipeBase &VPI : *VPBB) { 1170 if (isa<VPHeaderPHIRecipe>(&VPI)) 1171 continue; 1172 assert(isa<VPInstruction>(&VPI) && "Can only handle VPInstructions"); 1173 auto *VPInst = cast<VPInstruction>(&VPI); 1174 1175 auto *Inst = dyn_cast_or_null<Instruction>(VPInst->getUnderlyingValue()); 1176 if (!Inst) 1177 continue; 1178 auto *IG = IAI.getInterleaveGroup(Inst); 1179 if (!IG) 1180 continue; 1181 1182 auto NewIGIter = Old2New.find(IG); 1183 if (NewIGIter == Old2New.end()) 1184 Old2New[IG] = new InterleaveGroup<VPInstruction>( 1185 IG->getFactor(), IG->isReverse(), IG->getAlign()); 1186 1187 if (Inst == IG->getInsertPos()) 1188 Old2New[IG]->setInsertPos(VPInst); 1189 1190 InterleaveGroupMap[VPInst] = Old2New[IG]; 1191 InterleaveGroupMap[VPInst]->insertMember( 1192 VPInst, IG->getIndex(Inst), 1193 Align(IG->isReverse() ? (-1) * int(IG->getFactor()) 1194 : IG->getFactor())); 1195 } 1196 } else if (VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block)) 1197 visitRegion(Region, Old2New, IAI); 1198 else 1199 llvm_unreachable("Unsupported kind of VPBlock."); 1200 } 1201 1202 VPInterleavedAccessInfo::VPInterleavedAccessInfo(VPlan &Plan, 1203 InterleavedAccessInfo &IAI) { 1204 Old2NewTy Old2New; 1205 visitRegion(Plan.getVectorLoopRegion(), Old2New, IAI); 1206 } 1207 1208 void VPSlotTracker::assignSlot(const VPValue *V) { 1209 assert(!Slots.contains(V) && "VPValue already has a slot!"); 1210 Slots[V] = NextSlot++; 1211 } 1212 1213 void VPSlotTracker::assignSlots(const VPlan &Plan) { 1214 assignSlot(&Plan.VectorTripCount); 1215 if (Plan.BackedgeTakenCount) 1216 assignSlot(Plan.BackedgeTakenCount); 1217 assignSlots(Plan.getPreheader()); 1218 1219 ReversePostOrderTraversal<VPBlockDeepTraversalWrapper<const VPBlockBase *>> 1220 RPOT(VPBlockDeepTraversalWrapper<const VPBlockBase *>(Plan.getEntry())); 1221 for (const VPBasicBlock *VPBB : 1222 VPBlockUtils::blocksOnly<const VPBasicBlock>(RPOT)) 1223 assignSlots(VPBB); 1224 } 1225 1226 void VPSlotTracker::assignSlots(const VPBasicBlock *VPBB) { 1227 for (const VPRecipeBase &Recipe : *VPBB) 1228 for (VPValue *Def : Recipe.definedValues()) 1229 assignSlot(Def); 1230 } 1231 1232 bool vputils::onlyFirstLaneUsed(VPValue *Def) { 1233 return all_of(Def->users(), 1234 [Def](VPUser *U) { return U->onlyFirstLaneUsed(Def); }); 1235 } 1236 1237 VPValue *vputils::getOrCreateVPValueForSCEVExpr(VPlan &Plan, const SCEV *Expr, 1238 ScalarEvolution &SE) { 1239 if (auto *Expanded = Plan.getSCEVExpansion(Expr)) 1240 return Expanded; 1241 VPValue *Expanded = nullptr; 1242 if (auto *E = dyn_cast<SCEVConstant>(Expr)) 1243 Expanded = Plan.getVPValueOrAddLiveIn(E->getValue()); 1244 else if (auto *E = dyn_cast<SCEVUnknown>(Expr)) 1245 Expanded = Plan.getVPValueOrAddLiveIn(E->getValue()); 1246 else { 1247 Expanded = new VPExpandSCEVRecipe(Expr, SE); 1248 Plan.getPreheader()->appendRecipe(Expanded->getDefiningRecipe()); 1249 } 1250 Plan.addSCEVExpansion(Expr, Expanded); 1251 return Expanded; 1252 } 1253