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::setDebugLocFromInst(const Value *V) { 364 const Instruction *Inst = dyn_cast<Instruction>(V); 365 if (!Inst) { 366 Builder.SetCurrentDebugLocation(DebugLoc()); 367 return; 368 } 369 370 const DILocation *DIL = Inst->getDebugLoc(); 371 // When a FSDiscriminator is enabled, we don't need to add the multiply 372 // factors to the discriminators. 373 if (DIL && Inst->getFunction()->shouldEmitDebugInfoForProfiling() && 374 !EnableFSDiscriminator) { 375 assert(!Inst->isDebugOrPseudoInst() && 376 "debug and pseudo instruction aren't part of VPlan"); 377 // FIXME: For scalable vectors, assume vscale=1. 378 auto NewDIL = 379 DIL->cloneByMultiplyingDuplicationFactor(UF * VF.getKnownMinValue()); 380 if (NewDIL) 381 Builder.SetCurrentDebugLocation(*NewDIL); 382 else 383 LLVM_DEBUG(dbgs() << "Failed to create new discriminator: " 384 << DIL->getFilename() << " Line: " << DIL->getLine()); 385 } else 386 Builder.SetCurrentDebugLocation(DIL); 387 } 388 389 void VPTransformState::packScalarIntoVectorValue(VPValue *Def, 390 const VPIteration &Instance) { 391 Value *ScalarInst = get(Def, Instance); 392 Value *VectorValue = get(Def, Instance.Part); 393 VectorValue = Builder.CreateInsertElement( 394 VectorValue, ScalarInst, Instance.Lane.getAsRuntimeExpr(Builder, VF)); 395 set(Def, VectorValue, Instance.Part); 396 } 397 398 BasicBlock * 399 VPBasicBlock::createEmptyBasicBlock(VPTransformState::CFGState &CFG) { 400 // BB stands for IR BasicBlocks. VPBB stands for VPlan VPBasicBlocks. 401 // Pred stands for Predessor. Prev stands for Previous - last visited/created. 402 BasicBlock *PrevBB = CFG.PrevBB; 403 BasicBlock *NewBB = BasicBlock::Create(PrevBB->getContext(), getName(), 404 PrevBB->getParent(), CFG.ExitBB); 405 LLVM_DEBUG(dbgs() << "LV: created " << NewBB->getName() << '\n'); 406 407 // Hook up the new basic block to its predecessors. 408 for (VPBlockBase *PredVPBlock : getHierarchicalPredecessors()) { 409 VPBasicBlock *PredVPBB = PredVPBlock->getExitingBasicBlock(); 410 auto &PredVPSuccessors = PredVPBB->getHierarchicalSuccessors(); 411 BasicBlock *PredBB = CFG.VPBB2IRBB[PredVPBB]; 412 413 assert(PredBB && "Predecessor basic-block not found building successor."); 414 auto *PredBBTerminator = PredBB->getTerminator(); 415 LLVM_DEBUG(dbgs() << "LV: draw edge from" << PredBB->getName() << '\n'); 416 417 auto *TermBr = dyn_cast<BranchInst>(PredBBTerminator); 418 if (isa<UnreachableInst>(PredBBTerminator)) { 419 assert(PredVPSuccessors.size() == 1 && 420 "Predecessor ending w/o branch must have single successor."); 421 DebugLoc DL = PredBBTerminator->getDebugLoc(); 422 PredBBTerminator->eraseFromParent(); 423 auto *Br = BranchInst::Create(NewBB, PredBB); 424 Br->setDebugLoc(DL); 425 } else if (TermBr && !TermBr->isConditional()) { 426 TermBr->setSuccessor(0, NewBB); 427 } else { 428 // Set each forward successor here when it is created, excluding 429 // backedges. A backward successor is set when the branch is created. 430 unsigned idx = PredVPSuccessors.front() == this ? 0 : 1; 431 assert(!TermBr->getSuccessor(idx) && 432 "Trying to reset an existing successor block."); 433 TermBr->setSuccessor(idx, NewBB); 434 } 435 } 436 return NewBB; 437 } 438 439 void VPBasicBlock::execute(VPTransformState *State) { 440 bool Replica = State->Instance && !State->Instance->isFirstIteration(); 441 VPBasicBlock *PrevVPBB = State->CFG.PrevVPBB; 442 VPBlockBase *SingleHPred = nullptr; 443 BasicBlock *NewBB = State->CFG.PrevBB; // Reuse it if possible. 444 445 auto IsLoopRegion = [](VPBlockBase *BB) { 446 auto *R = dyn_cast<VPRegionBlock>(BB); 447 return R && !R->isReplicator(); 448 }; 449 450 // 1. Create an IR basic block, or reuse the last one or ExitBB if possible. 451 if (getPlan()->getVectorLoopRegion()->getSingleSuccessor() == this) { 452 // ExitBB can be re-used for the exit block of the Plan. 453 NewBB = State->CFG.ExitBB; 454 State->CFG.PrevBB = NewBB; 455 456 // Update the branch instruction in the predecessor to branch to ExitBB. 457 VPBlockBase *PredVPB = getSingleHierarchicalPredecessor(); 458 VPBasicBlock *ExitingVPBB = PredVPB->getExitingBasicBlock(); 459 assert(PredVPB->getSingleSuccessor() == this && 460 "predecessor must have the current block as only successor"); 461 BasicBlock *ExitingBB = State->CFG.VPBB2IRBB[ExitingVPBB]; 462 // The Exit block of a loop is always set to be successor 0 of the Exiting 463 // block. 464 cast<BranchInst>(ExitingBB->getTerminator())->setSuccessor(0, NewBB); 465 } else if (PrevVPBB && /* A */ 466 !((SingleHPred = getSingleHierarchicalPredecessor()) && 467 SingleHPred->getExitingBasicBlock() == PrevVPBB && 468 PrevVPBB->getSingleHierarchicalSuccessor() && 469 (SingleHPred->getParent() == getEnclosingLoopRegion() && 470 !IsLoopRegion(SingleHPred))) && /* B */ 471 !(Replica && getPredecessors().empty())) { /* C */ 472 // The last IR basic block is reused, as an optimization, in three cases: 473 // A. the first VPBB reuses the loop pre-header BB - when PrevVPBB is null; 474 // B. when the current VPBB has a single (hierarchical) predecessor which 475 // is PrevVPBB and the latter has a single (hierarchical) successor which 476 // both are in the same non-replicator region; and 477 // C. when the current VPBB is an entry of a region replica - where PrevVPBB 478 // is the exiting VPBB of this region from a previous instance, or the 479 // predecessor of this region. 480 481 NewBB = createEmptyBasicBlock(State->CFG); 482 State->Builder.SetInsertPoint(NewBB); 483 // Temporarily terminate with unreachable until CFG is rewired. 484 UnreachableInst *Terminator = State->Builder.CreateUnreachable(); 485 // Register NewBB in its loop. In innermost loops its the same for all 486 // BB's. 487 if (State->CurrentVectorLoop) 488 State->CurrentVectorLoop->addBasicBlockToLoop(NewBB, *State->LI); 489 State->Builder.SetInsertPoint(Terminator); 490 State->CFG.PrevBB = NewBB; 491 } 492 493 // 2. Fill the IR basic block with IR instructions. 494 LLVM_DEBUG(dbgs() << "LV: vectorizing VPBB:" << getName() 495 << " in BB:" << NewBB->getName() << '\n'); 496 497 State->CFG.VPBB2IRBB[this] = NewBB; 498 State->CFG.PrevVPBB = this; 499 500 for (VPRecipeBase &Recipe : Recipes) 501 Recipe.execute(*State); 502 503 LLVM_DEBUG(dbgs() << "LV: filled BB:" << *NewBB); 504 } 505 506 void VPBasicBlock::dropAllReferences(VPValue *NewValue) { 507 for (VPRecipeBase &R : Recipes) { 508 for (auto *Def : R.definedValues()) 509 Def->replaceAllUsesWith(NewValue); 510 511 for (unsigned I = 0, E = R.getNumOperands(); I != E; I++) 512 R.setOperand(I, NewValue); 513 } 514 } 515 516 VPBasicBlock *VPBasicBlock::splitAt(iterator SplitAt) { 517 assert((SplitAt == end() || SplitAt->getParent() == this) && 518 "can only split at a position in the same block"); 519 520 SmallVector<VPBlockBase *, 2> Succs(successors()); 521 // First, disconnect the current block from its successors. 522 for (VPBlockBase *Succ : Succs) 523 VPBlockUtils::disconnectBlocks(this, Succ); 524 525 // Create new empty block after the block to split. 526 auto *SplitBlock = new VPBasicBlock(getName() + ".split"); 527 VPBlockUtils::insertBlockAfter(SplitBlock, this); 528 529 // Add successors for block to split to new block. 530 for (VPBlockBase *Succ : Succs) 531 VPBlockUtils::connectBlocks(SplitBlock, Succ); 532 533 // Finally, move the recipes starting at SplitAt to new block. 534 for (VPRecipeBase &ToMove : 535 make_early_inc_range(make_range(SplitAt, this->end()))) 536 ToMove.moveBefore(*SplitBlock, SplitBlock->end()); 537 538 return SplitBlock; 539 } 540 541 VPRegionBlock *VPBasicBlock::getEnclosingLoopRegion() { 542 VPRegionBlock *P = getParent(); 543 if (P && P->isReplicator()) { 544 P = P->getParent(); 545 assert(!cast<VPRegionBlock>(P)->isReplicator() && 546 "unexpected nested replicate regions"); 547 } 548 return P; 549 } 550 551 static bool hasConditionalTerminator(const VPBasicBlock *VPBB) { 552 if (VPBB->empty()) { 553 assert( 554 VPBB->getNumSuccessors() < 2 && 555 "block with multiple successors doesn't have a recipe as terminator"); 556 return false; 557 } 558 559 const VPRecipeBase *R = &VPBB->back(); 560 auto *VPI = dyn_cast<VPInstruction>(R); 561 bool IsCondBranch = 562 isa<VPBranchOnMaskRecipe>(R) || 563 (VPI && (VPI->getOpcode() == VPInstruction::BranchOnCond || 564 VPI->getOpcode() == VPInstruction::BranchOnCount)); 565 (void)IsCondBranch; 566 567 if (VPBB->getNumSuccessors() >= 2 || VPBB->isExiting()) { 568 assert(IsCondBranch && "block with multiple successors not terminated by " 569 "conditional branch recipe"); 570 571 return true; 572 } 573 574 assert( 575 !IsCondBranch && 576 "block with 0 or 1 successors terminated by conditional branch recipe"); 577 return false; 578 } 579 580 VPRecipeBase *VPBasicBlock::getTerminator() { 581 if (hasConditionalTerminator(this)) 582 return &back(); 583 return nullptr; 584 } 585 586 const VPRecipeBase *VPBasicBlock::getTerminator() const { 587 if (hasConditionalTerminator(this)) 588 return &back(); 589 return nullptr; 590 } 591 592 bool VPBasicBlock::isExiting() const { 593 return getParent()->getExitingBasicBlock() == this; 594 } 595 596 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 597 void VPBlockBase::printSuccessors(raw_ostream &O, const Twine &Indent) const { 598 if (getSuccessors().empty()) { 599 O << Indent << "No successors\n"; 600 } else { 601 O << Indent << "Successor(s): "; 602 ListSeparator LS; 603 for (auto *Succ : getSuccessors()) 604 O << LS << Succ->getName(); 605 O << '\n'; 606 } 607 } 608 609 void VPBasicBlock::print(raw_ostream &O, const Twine &Indent, 610 VPSlotTracker &SlotTracker) const { 611 O << Indent << getName() << ":\n"; 612 613 auto RecipeIndent = Indent + " "; 614 for (const VPRecipeBase &Recipe : *this) { 615 Recipe.print(O, RecipeIndent, SlotTracker); 616 O << '\n'; 617 } 618 619 printSuccessors(O, Indent); 620 } 621 #endif 622 623 void VPRegionBlock::dropAllReferences(VPValue *NewValue) { 624 for (VPBlockBase *Block : vp_depth_first_shallow(Entry)) 625 // Drop all references in VPBasicBlocks and replace all uses with 626 // DummyValue. 627 Block->dropAllReferences(NewValue); 628 } 629 630 void VPRegionBlock::execute(VPTransformState *State) { 631 ReversePostOrderTraversal<VPBlockShallowTraversalWrapper<VPBlockBase *>> 632 RPOT(Entry); 633 634 if (!isReplicator()) { 635 // Create and register the new vector loop. 636 Loop *PrevLoop = State->CurrentVectorLoop; 637 State->CurrentVectorLoop = State->LI->AllocateLoop(); 638 BasicBlock *VectorPH = State->CFG.VPBB2IRBB[getPreheaderVPBB()]; 639 Loop *ParentLoop = State->LI->getLoopFor(VectorPH); 640 641 // Insert the new loop into the loop nest and register the new basic blocks 642 // before calling any utilities such as SCEV that require valid LoopInfo. 643 if (ParentLoop) 644 ParentLoop->addChildLoop(State->CurrentVectorLoop); 645 else 646 State->LI->addTopLevelLoop(State->CurrentVectorLoop); 647 648 // Visit the VPBlocks connected to "this", starting from it. 649 for (VPBlockBase *Block : RPOT) { 650 LLVM_DEBUG(dbgs() << "LV: VPBlock in RPO " << Block->getName() << '\n'); 651 Block->execute(State); 652 } 653 654 State->CurrentVectorLoop = PrevLoop; 655 return; 656 } 657 658 assert(!State->Instance && "Replicating a Region with non-null instance."); 659 660 // Enter replicating mode. 661 State->Instance = VPIteration(0, 0); 662 663 for (unsigned Part = 0, UF = State->UF; Part < UF; ++Part) { 664 State->Instance->Part = Part; 665 assert(!State->VF.isScalable() && "VF is assumed to be non scalable."); 666 for (unsigned Lane = 0, VF = State->VF.getKnownMinValue(); Lane < VF; 667 ++Lane) { 668 State->Instance->Lane = VPLane(Lane, VPLane::Kind::First); 669 // Visit the VPBlocks connected to \p this, starting from it. 670 for (VPBlockBase *Block : RPOT) { 671 LLVM_DEBUG(dbgs() << "LV: VPBlock in RPO " << Block->getName() << '\n'); 672 Block->execute(State); 673 } 674 } 675 } 676 677 // Exit replicating mode. 678 State->Instance.reset(); 679 } 680 681 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 682 void VPRegionBlock::print(raw_ostream &O, const Twine &Indent, 683 VPSlotTracker &SlotTracker) const { 684 O << Indent << (isReplicator() ? "<xVFxUF> " : "<x1> ") << getName() << ": {"; 685 auto NewIndent = Indent + " "; 686 for (auto *BlockBase : vp_depth_first_shallow(Entry)) { 687 O << '\n'; 688 BlockBase->print(O, NewIndent, SlotTracker); 689 } 690 O << Indent << "}\n"; 691 692 printSuccessors(O, Indent); 693 } 694 #endif 695 696 VPlan::~VPlan() { 697 for (auto &KV : LiveOuts) 698 delete KV.second; 699 LiveOuts.clear(); 700 701 if (Entry) { 702 VPValue DummyValue; 703 for (VPBlockBase *Block : vp_depth_first_shallow(Entry)) 704 Block->dropAllReferences(&DummyValue); 705 706 VPBlockBase::deleteCFG(Entry); 707 708 Preheader->dropAllReferences(&DummyValue); 709 delete Preheader; 710 } 711 for (VPValue *VPV : VPLiveInsToFree) 712 delete VPV; 713 if (BackedgeTakenCount) 714 delete BackedgeTakenCount; 715 } 716 717 VPlanPtr VPlan::createInitialVPlan(const SCEV *TripCount, ScalarEvolution &SE) { 718 VPBasicBlock *Preheader = new VPBasicBlock("ph"); 719 VPBasicBlock *VecPreheader = new VPBasicBlock("vector.ph"); 720 auto Plan = std::make_unique<VPlan>(Preheader, VecPreheader); 721 Plan->TripCount = 722 vputils::getOrCreateVPValueForSCEVExpr(*Plan, TripCount, SE); 723 return Plan; 724 } 725 726 VPActiveLaneMaskPHIRecipe *VPlan::getActiveLaneMaskPhi() { 727 VPBasicBlock *Header = getVectorLoopRegion()->getEntryBasicBlock(); 728 for (VPRecipeBase &R : Header->phis()) { 729 if (isa<VPActiveLaneMaskPHIRecipe>(&R)) 730 return cast<VPActiveLaneMaskPHIRecipe>(&R); 731 } 732 return nullptr; 733 } 734 735 void VPlan::prepareToExecute(Value *TripCountV, Value *VectorTripCountV, 736 Value *CanonicalIVStartValue, 737 VPTransformState &State, 738 bool IsEpilogueVectorization) { 739 // Check if the backedge taken count is needed, and if so build it. 740 if (BackedgeTakenCount && BackedgeTakenCount->getNumUsers()) { 741 IRBuilder<> Builder(State.CFG.PrevBB->getTerminator()); 742 auto *TCMO = Builder.CreateSub(TripCountV, 743 ConstantInt::get(TripCountV->getType(), 1), 744 "trip.count.minus.1"); 745 auto VF = State.VF; 746 Value *VTCMO = 747 VF.isScalar() ? TCMO : Builder.CreateVectorSplat(VF, TCMO, "broadcast"); 748 for (unsigned Part = 0, UF = State.UF; Part < UF; ++Part) 749 State.set(BackedgeTakenCount, VTCMO, Part); 750 } 751 752 for (unsigned Part = 0, UF = State.UF; Part < UF; ++Part) 753 State.set(&VectorTripCount, VectorTripCountV, Part); 754 755 // When vectorizing the epilogue loop, the canonical induction start value 756 // needs to be changed from zero to the value after the main vector loop. 757 // FIXME: Improve modeling for canonical IV start values in the epilogue loop. 758 if (CanonicalIVStartValue) { 759 VPValue *VPV = getVPValueOrAddLiveIn(CanonicalIVStartValue); 760 auto *IV = getCanonicalIV(); 761 assert(all_of(IV->users(), 762 [](const VPUser *U) { 763 return isa<VPScalarIVStepsRecipe>(U) || 764 isa<VPDerivedIVRecipe>(U) || 765 cast<VPInstruction>(U)->getOpcode() == 766 VPInstruction::CanonicalIVIncrement; 767 }) && 768 "the canonical IV should only be used by its increment or " 769 "ScalarIVSteps when resetting the start value"); 770 IV->setOperand(0, VPV); 771 } 772 } 773 774 /// Generate the code inside the preheader and body of the vectorized loop. 775 /// Assumes a single pre-header basic-block was created for this. Introduce 776 /// additional basic-blocks as needed, and fill them all. 777 void VPlan::execute(VPTransformState *State) { 778 // Set the reverse mapping from VPValues to Values for code generation. 779 for (auto &Entry : Value2VPValue) 780 State->VPValue2Value[Entry.second] = Entry.first; 781 782 // Initialize CFG state. 783 State->CFG.PrevVPBB = nullptr; 784 State->CFG.ExitBB = State->CFG.PrevBB->getSingleSuccessor(); 785 BasicBlock *VectorPreHeader = State->CFG.PrevBB; 786 State->Builder.SetInsertPoint(VectorPreHeader->getTerminator()); 787 788 // Generate code in the loop pre-header and body. 789 for (VPBlockBase *Block : vp_depth_first_shallow(Entry)) 790 Block->execute(State); 791 792 VPBasicBlock *LatchVPBB = getVectorLoopRegion()->getExitingBasicBlock(); 793 BasicBlock *VectorLatchBB = State->CFG.VPBB2IRBB[LatchVPBB]; 794 795 // Fix the latch value of canonical, reduction and first-order recurrences 796 // phis in the vector loop. 797 VPBasicBlock *Header = getVectorLoopRegion()->getEntryBasicBlock(); 798 for (VPRecipeBase &R : Header->phis()) { 799 // Skip phi-like recipes that generate their backedege values themselves. 800 if (isa<VPWidenPHIRecipe>(&R)) 801 continue; 802 803 if (isa<VPWidenPointerInductionRecipe>(&R) || 804 isa<VPWidenIntOrFpInductionRecipe>(&R)) { 805 PHINode *Phi = nullptr; 806 if (isa<VPWidenIntOrFpInductionRecipe>(&R)) { 807 Phi = cast<PHINode>(State->get(R.getVPSingleValue(), 0)); 808 } else { 809 auto *WidenPhi = cast<VPWidenPointerInductionRecipe>(&R); 810 // TODO: Split off the case that all users of a pointer phi are scalar 811 // from the VPWidenPointerInductionRecipe. 812 if (WidenPhi->onlyScalarsGenerated(State->VF)) 813 continue; 814 815 auto *GEP = cast<GetElementPtrInst>(State->get(WidenPhi, 0)); 816 Phi = cast<PHINode>(GEP->getPointerOperand()); 817 } 818 819 Phi->setIncomingBlock(1, VectorLatchBB); 820 821 // Move the last step to the end of the latch block. This ensures 822 // consistent placement of all induction updates. 823 Instruction *Inc = cast<Instruction>(Phi->getIncomingValue(1)); 824 Inc->moveBefore(VectorLatchBB->getTerminator()->getPrevNode()); 825 continue; 826 } 827 828 auto *PhiR = cast<VPHeaderPHIRecipe>(&R); 829 // For canonical IV, first-order recurrences and in-order reduction phis, 830 // only a single part is generated, which provides the last part from the 831 // previous iteration. For non-ordered reductions all UF parts are 832 // generated. 833 bool SinglePartNeeded = isa<VPCanonicalIVPHIRecipe>(PhiR) || 834 isa<VPFirstOrderRecurrencePHIRecipe>(PhiR) || 835 (isa<VPReductionPHIRecipe>(PhiR) && 836 cast<VPReductionPHIRecipe>(PhiR)->isOrdered()); 837 unsigned LastPartForNewPhi = SinglePartNeeded ? 1 : State->UF; 838 839 for (unsigned Part = 0; Part < LastPartForNewPhi; ++Part) { 840 Value *Phi = State->get(PhiR, Part); 841 Value *Val = State->get(PhiR->getBackedgeValue(), 842 SinglePartNeeded ? State->UF - 1 : Part); 843 cast<PHINode>(Phi)->addIncoming(Val, VectorLatchBB); 844 } 845 } 846 847 // We do not attempt to preserve DT for outer loop vectorization currently. 848 if (!EnableVPlanNativePath) { 849 BasicBlock *VectorHeaderBB = State->CFG.VPBB2IRBB[Header]; 850 State->DT->addNewBlock(VectorHeaderBB, VectorPreHeader); 851 updateDominatorTree(State->DT, VectorHeaderBB, VectorLatchBB, 852 State->CFG.ExitBB); 853 } 854 } 855 856 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 857 LLVM_DUMP_METHOD 858 void VPlan::print(raw_ostream &O) const { 859 VPSlotTracker SlotTracker(this); 860 861 O << "VPlan '" << getName() << "' {"; 862 863 if (VectorTripCount.getNumUsers() > 0) { 864 O << "\nLive-in "; 865 VectorTripCount.printAsOperand(O, SlotTracker); 866 O << " = vector-trip-count"; 867 } 868 869 if (BackedgeTakenCount && BackedgeTakenCount->getNumUsers()) { 870 O << "\nLive-in "; 871 BackedgeTakenCount->printAsOperand(O, SlotTracker); 872 O << " = backedge-taken count"; 873 } 874 875 O << "\n"; 876 if (TripCount->isLiveIn()) 877 O << "Live-in "; 878 TripCount->printAsOperand(O, SlotTracker); 879 O << " = original trip-count"; 880 O << "\n"; 881 882 if (!getPreheader()->empty()) { 883 O << "\n"; 884 getPreheader()->print(O, "", SlotTracker); 885 } 886 887 for (const VPBlockBase *Block : vp_depth_first_shallow(getEntry())) { 888 O << '\n'; 889 Block->print(O, "", SlotTracker); 890 } 891 892 if (!LiveOuts.empty()) 893 O << "\n"; 894 for (const auto &KV : LiveOuts) { 895 KV.second->print(O, SlotTracker); 896 } 897 898 O << "}\n"; 899 } 900 901 std::string VPlan::getName() const { 902 std::string Out; 903 raw_string_ostream RSO(Out); 904 RSO << Name << " for "; 905 if (!VFs.empty()) { 906 RSO << "VF={" << VFs[0]; 907 for (ElementCount VF : drop_begin(VFs)) 908 RSO << "," << VF; 909 RSO << "},"; 910 } 911 912 if (UFs.empty()) { 913 RSO << "UF>=1"; 914 } else { 915 RSO << "UF={" << UFs[0]; 916 for (unsigned UF : drop_begin(UFs)) 917 RSO << "," << UF; 918 RSO << "}"; 919 } 920 921 return Out; 922 } 923 924 LLVM_DUMP_METHOD 925 void VPlan::printDOT(raw_ostream &O) const { 926 VPlanPrinter Printer(O, *this); 927 Printer.dump(); 928 } 929 930 LLVM_DUMP_METHOD 931 void VPlan::dump() const { print(dbgs()); } 932 #endif 933 934 void VPlan::addLiveOut(PHINode *PN, VPValue *V) { 935 assert(LiveOuts.count(PN) == 0 && "an exit value for PN already exists"); 936 LiveOuts.insert({PN, new VPLiveOut(PN, V)}); 937 } 938 939 void VPlan::updateDominatorTree(DominatorTree *DT, BasicBlock *LoopHeaderBB, 940 BasicBlock *LoopLatchBB, 941 BasicBlock *LoopExitBB) { 942 // The vector body may be more than a single basic-block by this point. 943 // Update the dominator tree information inside the vector body by propagating 944 // it from header to latch, expecting only triangular control-flow, if any. 945 BasicBlock *PostDomSucc = nullptr; 946 for (auto *BB = LoopHeaderBB; BB != LoopLatchBB; BB = PostDomSucc) { 947 // Get the list of successors of this block. 948 std::vector<BasicBlock *> Succs(succ_begin(BB), succ_end(BB)); 949 assert(Succs.size() <= 2 && 950 "Basic block in vector loop has more than 2 successors."); 951 PostDomSucc = Succs[0]; 952 if (Succs.size() == 1) { 953 assert(PostDomSucc->getSinglePredecessor() && 954 "PostDom successor has more than one predecessor."); 955 DT->addNewBlock(PostDomSucc, BB); 956 continue; 957 } 958 BasicBlock *InterimSucc = Succs[1]; 959 if (PostDomSucc->getSingleSuccessor() == InterimSucc) { 960 PostDomSucc = Succs[1]; 961 InterimSucc = Succs[0]; 962 } 963 assert(InterimSucc->getSingleSuccessor() == PostDomSucc && 964 "One successor of a basic block does not lead to the other."); 965 assert(InterimSucc->getSinglePredecessor() && 966 "Interim successor has more than one predecessor."); 967 assert(PostDomSucc->hasNPredecessors(2) && 968 "PostDom successor has more than two predecessors."); 969 DT->addNewBlock(InterimSucc, BB); 970 DT->addNewBlock(PostDomSucc, BB); 971 } 972 // Latch block is a new dominator for the loop exit. 973 DT->changeImmediateDominator(LoopExitBB, LoopLatchBB); 974 assert(DT->verify(DominatorTree::VerificationLevel::Fast)); 975 } 976 977 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 978 979 Twine VPlanPrinter::getUID(const VPBlockBase *Block) { 980 return (isa<VPRegionBlock>(Block) ? "cluster_N" : "N") + 981 Twine(getOrCreateBID(Block)); 982 } 983 984 Twine VPlanPrinter::getOrCreateName(const VPBlockBase *Block) { 985 const std::string &Name = Block->getName(); 986 if (!Name.empty()) 987 return Name; 988 return "VPB" + Twine(getOrCreateBID(Block)); 989 } 990 991 void VPlanPrinter::dump() { 992 Depth = 1; 993 bumpIndent(0); 994 OS << "digraph VPlan {\n"; 995 OS << "graph [labelloc=t, fontsize=30; label=\"Vectorization Plan"; 996 if (!Plan.getName().empty()) 997 OS << "\\n" << DOT::EscapeString(Plan.getName()); 998 if (Plan.BackedgeTakenCount) { 999 OS << ", where:\\n"; 1000 Plan.BackedgeTakenCount->print(OS, SlotTracker); 1001 OS << " := BackedgeTakenCount"; 1002 } 1003 OS << "\"]\n"; 1004 OS << "node [shape=rect, fontname=Courier, fontsize=30]\n"; 1005 OS << "edge [fontname=Courier, fontsize=30]\n"; 1006 OS << "compound=true\n"; 1007 1008 dumpBlock(Plan.getPreheader()); 1009 1010 for (const VPBlockBase *Block : vp_depth_first_shallow(Plan.getEntry())) 1011 dumpBlock(Block); 1012 1013 OS << "}\n"; 1014 } 1015 1016 void VPlanPrinter::dumpBlock(const VPBlockBase *Block) { 1017 if (const VPBasicBlock *BasicBlock = dyn_cast<VPBasicBlock>(Block)) 1018 dumpBasicBlock(BasicBlock); 1019 else if (const VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block)) 1020 dumpRegion(Region); 1021 else 1022 llvm_unreachable("Unsupported kind of VPBlock."); 1023 } 1024 1025 void VPlanPrinter::drawEdge(const VPBlockBase *From, const VPBlockBase *To, 1026 bool Hidden, const Twine &Label) { 1027 // Due to "dot" we print an edge between two regions as an edge between the 1028 // exiting basic block and the entry basic of the respective regions. 1029 const VPBlockBase *Tail = From->getExitingBasicBlock(); 1030 const VPBlockBase *Head = To->getEntryBasicBlock(); 1031 OS << Indent << getUID(Tail) << " -> " << getUID(Head); 1032 OS << " [ label=\"" << Label << '\"'; 1033 if (Tail != From) 1034 OS << " ltail=" << getUID(From); 1035 if (Head != To) 1036 OS << " lhead=" << getUID(To); 1037 if (Hidden) 1038 OS << "; splines=none"; 1039 OS << "]\n"; 1040 } 1041 1042 void VPlanPrinter::dumpEdges(const VPBlockBase *Block) { 1043 auto &Successors = Block->getSuccessors(); 1044 if (Successors.size() == 1) 1045 drawEdge(Block, Successors.front(), false, ""); 1046 else if (Successors.size() == 2) { 1047 drawEdge(Block, Successors.front(), false, "T"); 1048 drawEdge(Block, Successors.back(), false, "F"); 1049 } else { 1050 unsigned SuccessorNumber = 0; 1051 for (auto *Successor : Successors) 1052 drawEdge(Block, Successor, false, Twine(SuccessorNumber++)); 1053 } 1054 } 1055 1056 void VPlanPrinter::dumpBasicBlock(const VPBasicBlock *BasicBlock) { 1057 // Implement dot-formatted dump by performing plain-text dump into the 1058 // temporary storage followed by some post-processing. 1059 OS << Indent << getUID(BasicBlock) << " [label =\n"; 1060 bumpIndent(1); 1061 std::string Str; 1062 raw_string_ostream SS(Str); 1063 // Use no indentation as we need to wrap the lines into quotes ourselves. 1064 BasicBlock->print(SS, "", SlotTracker); 1065 1066 // We need to process each line of the output separately, so split 1067 // single-string plain-text dump. 1068 SmallVector<StringRef, 0> Lines; 1069 StringRef(Str).rtrim('\n').split(Lines, "\n"); 1070 1071 auto EmitLine = [&](StringRef Line, StringRef Suffix) { 1072 OS << Indent << '"' << DOT::EscapeString(Line.str()) << "\\l\"" << Suffix; 1073 }; 1074 1075 // Don't need the "+" after the last line. 1076 for (auto Line : make_range(Lines.begin(), Lines.end() - 1)) 1077 EmitLine(Line, " +\n"); 1078 EmitLine(Lines.back(), "\n"); 1079 1080 bumpIndent(-1); 1081 OS << Indent << "]\n"; 1082 1083 dumpEdges(BasicBlock); 1084 } 1085 1086 void VPlanPrinter::dumpRegion(const VPRegionBlock *Region) { 1087 OS << Indent << "subgraph " << getUID(Region) << " {\n"; 1088 bumpIndent(1); 1089 OS << Indent << "fontname=Courier\n" 1090 << Indent << "label=\"" 1091 << DOT::EscapeString(Region->isReplicator() ? "<xVFxUF> " : "<x1> ") 1092 << DOT::EscapeString(Region->getName()) << "\"\n"; 1093 // Dump the blocks of the region. 1094 assert(Region->getEntry() && "Region contains no inner blocks."); 1095 for (const VPBlockBase *Block : vp_depth_first_shallow(Region->getEntry())) 1096 dumpBlock(Block); 1097 bumpIndent(-1); 1098 OS << Indent << "}\n"; 1099 dumpEdges(Region); 1100 } 1101 1102 void VPlanIngredient::print(raw_ostream &O) const { 1103 if (auto *Inst = dyn_cast<Instruction>(V)) { 1104 if (!Inst->getType()->isVoidTy()) { 1105 Inst->printAsOperand(O, false); 1106 O << " = "; 1107 } 1108 O << Inst->getOpcodeName() << " "; 1109 unsigned E = Inst->getNumOperands(); 1110 if (E > 0) { 1111 Inst->getOperand(0)->printAsOperand(O, false); 1112 for (unsigned I = 1; I < E; ++I) 1113 Inst->getOperand(I)->printAsOperand(O << ", ", false); 1114 } 1115 } else // !Inst 1116 V->printAsOperand(O, false); 1117 } 1118 1119 #endif 1120 1121 template void DomTreeBuilder::Calculate<VPDominatorTree>(VPDominatorTree &DT); 1122 1123 void VPValue::replaceAllUsesWith(VPValue *New) { 1124 for (unsigned J = 0; J < getNumUsers();) { 1125 VPUser *User = Users[J]; 1126 unsigned NumUsers = getNumUsers(); 1127 for (unsigned I = 0, E = User->getNumOperands(); I < E; ++I) 1128 if (User->getOperand(I) == this) 1129 User->setOperand(I, New); 1130 // If a user got removed after updating the current user, the next user to 1131 // update will be moved to the current position, so we only need to 1132 // increment the index if the number of users did not change. 1133 if (NumUsers == getNumUsers()) 1134 J++; 1135 } 1136 } 1137 1138 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1139 void VPValue::printAsOperand(raw_ostream &OS, VPSlotTracker &Tracker) const { 1140 if (const Value *UV = getUnderlyingValue()) { 1141 OS << "ir<"; 1142 UV->printAsOperand(OS, false); 1143 OS << ">"; 1144 return; 1145 } 1146 1147 unsigned Slot = Tracker.getSlot(this); 1148 if (Slot == unsigned(-1)) 1149 OS << "<badref>"; 1150 else 1151 OS << "vp<%" << Tracker.getSlot(this) << ">"; 1152 } 1153 1154 void VPUser::printOperands(raw_ostream &O, VPSlotTracker &SlotTracker) const { 1155 interleaveComma(operands(), O, [&O, &SlotTracker](VPValue *Op) { 1156 Op->printAsOperand(O, SlotTracker); 1157 }); 1158 } 1159 #endif 1160 1161 void VPInterleavedAccessInfo::visitRegion(VPRegionBlock *Region, 1162 Old2NewTy &Old2New, 1163 InterleavedAccessInfo &IAI) { 1164 ReversePostOrderTraversal<VPBlockShallowTraversalWrapper<VPBlockBase *>> 1165 RPOT(Region->getEntry()); 1166 for (VPBlockBase *Base : RPOT) { 1167 visitBlock(Base, Old2New, IAI); 1168 } 1169 } 1170 1171 void VPInterleavedAccessInfo::visitBlock(VPBlockBase *Block, Old2NewTy &Old2New, 1172 InterleavedAccessInfo &IAI) { 1173 if (VPBasicBlock *VPBB = dyn_cast<VPBasicBlock>(Block)) { 1174 for (VPRecipeBase &VPI : *VPBB) { 1175 if (isa<VPHeaderPHIRecipe>(&VPI)) 1176 continue; 1177 assert(isa<VPInstruction>(&VPI) && "Can only handle VPInstructions"); 1178 auto *VPInst = cast<VPInstruction>(&VPI); 1179 1180 auto *Inst = dyn_cast_or_null<Instruction>(VPInst->getUnderlyingValue()); 1181 if (!Inst) 1182 continue; 1183 auto *IG = IAI.getInterleaveGroup(Inst); 1184 if (!IG) 1185 continue; 1186 1187 auto NewIGIter = Old2New.find(IG); 1188 if (NewIGIter == Old2New.end()) 1189 Old2New[IG] = new InterleaveGroup<VPInstruction>( 1190 IG->getFactor(), IG->isReverse(), IG->getAlign()); 1191 1192 if (Inst == IG->getInsertPos()) 1193 Old2New[IG]->setInsertPos(VPInst); 1194 1195 InterleaveGroupMap[VPInst] = Old2New[IG]; 1196 InterleaveGroupMap[VPInst]->insertMember( 1197 VPInst, IG->getIndex(Inst), 1198 Align(IG->isReverse() ? (-1) * int(IG->getFactor()) 1199 : IG->getFactor())); 1200 } 1201 } else if (VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block)) 1202 visitRegion(Region, Old2New, IAI); 1203 else 1204 llvm_unreachable("Unsupported kind of VPBlock."); 1205 } 1206 1207 VPInterleavedAccessInfo::VPInterleavedAccessInfo(VPlan &Plan, 1208 InterleavedAccessInfo &IAI) { 1209 Old2NewTy Old2New; 1210 visitRegion(Plan.getVectorLoopRegion(), Old2New, IAI); 1211 } 1212 1213 void VPSlotTracker::assignSlot(const VPValue *V) { 1214 assert(!Slots.contains(V) && "VPValue already has a slot!"); 1215 Slots[V] = NextSlot++; 1216 } 1217 1218 void VPSlotTracker::assignSlots(const VPlan &Plan) { 1219 assignSlot(&Plan.VectorTripCount); 1220 if (Plan.BackedgeTakenCount) 1221 assignSlot(Plan.BackedgeTakenCount); 1222 assignSlots(Plan.getPreheader()); 1223 1224 ReversePostOrderTraversal<VPBlockDeepTraversalWrapper<const VPBlockBase *>> 1225 RPOT(VPBlockDeepTraversalWrapper<const VPBlockBase *>(Plan.getEntry())); 1226 for (const VPBasicBlock *VPBB : 1227 VPBlockUtils::blocksOnly<const VPBasicBlock>(RPOT)) 1228 assignSlots(VPBB); 1229 } 1230 1231 void VPSlotTracker::assignSlots(const VPBasicBlock *VPBB) { 1232 for (const VPRecipeBase &Recipe : *VPBB) 1233 for (VPValue *Def : Recipe.definedValues()) 1234 assignSlot(Def); 1235 } 1236 1237 bool vputils::onlyFirstLaneUsed(VPValue *Def) { 1238 return all_of(Def->users(), 1239 [Def](VPUser *U) { return U->onlyFirstLaneUsed(Def); }); 1240 } 1241 1242 VPValue *vputils::getOrCreateVPValueForSCEVExpr(VPlan &Plan, const SCEV *Expr, 1243 ScalarEvolution &SE) { 1244 if (auto *Expanded = Plan.getSCEVExpansion(Expr)) 1245 return Expanded; 1246 VPValue *Expanded = nullptr; 1247 if (auto *E = dyn_cast<SCEVConstant>(Expr)) 1248 Expanded = Plan.getVPValueOrAddLiveIn(E->getValue()); 1249 else if (auto *E = dyn_cast<SCEVUnknown>(Expr)) 1250 Expanded = Plan.getVPValueOrAddLiveIn(E->getValue()); 1251 else { 1252 Expanded = new VPExpandSCEVRecipe(Expr, SE); 1253 Plan.getPreheader()->appendRecipe(Expanded->getDefiningRecipe()); 1254 } 1255 Plan.addSCEVExpansion(Expr, Expanded); 1256 return Expanded; 1257 } 1258