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