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