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