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 "VPlanDominatorTree.h" 21 #include "llvm/ADT/DepthFirstIterator.h" 22 #include "llvm/ADT/PostOrderIterator.h" 23 #include "llvm/ADT/STLExtras.h" 24 #include "llvm/ADT/SmallVector.h" 25 #include "llvm/ADT/Twine.h" 26 #include "llvm/Analysis/IVDescriptors.h" 27 #include "llvm/Analysis/LoopInfo.h" 28 #include "llvm/IR/BasicBlock.h" 29 #include "llvm/IR/CFG.h" 30 #include "llvm/IR/InstrTypes.h" 31 #include "llvm/IR/Instruction.h" 32 #include "llvm/IR/Instructions.h" 33 #include "llvm/IR/Type.h" 34 #include "llvm/IR/Value.h" 35 #include "llvm/Support/Casting.h" 36 #include "llvm/Support/CommandLine.h" 37 #include "llvm/Support/Debug.h" 38 #include "llvm/Support/ErrorHandling.h" 39 #include "llvm/Support/GenericDomTreeConstruction.h" 40 #include "llvm/Support/GraphWriter.h" 41 #include "llvm/Support/raw_ostream.h" 42 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 43 #include <cassert> 44 #include <iterator> 45 #include <string> 46 #include <vector> 47 48 using namespace llvm; 49 extern cl::opt<bool> EnableVPlanNativePath; 50 51 #define DEBUG_TYPE "vplan" 52 53 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 54 raw_ostream &llvm::operator<<(raw_ostream &OS, const VPValue &V) { 55 const VPInstruction *Instr = dyn_cast<VPInstruction>(&V); 56 VPSlotTracker SlotTracker( 57 (Instr && Instr->getParent()) ? Instr->getParent()->getPlan() : nullptr); 58 V.print(OS, SlotTracker); 59 return OS; 60 } 61 #endif 62 63 Value *VPLane::getAsRuntimeExpr(IRBuilder<> &Builder, 64 const ElementCount &VF) const { 65 switch (LaneKind) { 66 case VPLane::Kind::ScalableLast: 67 // Lane = RuntimeVF - VF.getKnownMinValue() + Lane 68 return Builder.CreateSub(getRuntimeVF(Builder, Builder.getInt32Ty(), VF), 69 Builder.getInt32(VF.getKnownMinValue() - Lane)); 70 case VPLane::Kind::First: 71 return Builder.getInt32(Lane); 72 } 73 llvm_unreachable("Unknown lane kind"); 74 } 75 76 VPValue::VPValue(const unsigned char SC, Value *UV, VPDef *Def) 77 : SubclassID(SC), UnderlyingVal(UV), Def(Def) { 78 if (Def) 79 Def->addDefinedValue(this); 80 } 81 82 VPValue::~VPValue() { 83 assert(Users.empty() && "trying to delete a VPValue with remaining users"); 84 if (Def) 85 Def->removeDefinedValue(this); 86 } 87 88 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 89 void VPValue::print(raw_ostream &OS, VPSlotTracker &SlotTracker) const { 90 if (const VPRecipeBase *R = dyn_cast_or_null<VPRecipeBase>(Def)) 91 R->print(OS, "", SlotTracker); 92 else 93 printAsOperand(OS, SlotTracker); 94 } 95 96 void VPValue::dump() const { 97 const VPRecipeBase *Instr = dyn_cast_or_null<VPRecipeBase>(this->Def); 98 VPSlotTracker SlotTracker( 99 (Instr && Instr->getParent()) ? Instr->getParent()->getPlan() : nullptr); 100 print(dbgs(), SlotTracker); 101 dbgs() << "\n"; 102 } 103 104 void VPDef::dump() const { 105 const VPRecipeBase *Instr = dyn_cast_or_null<VPRecipeBase>(this); 106 VPSlotTracker SlotTracker( 107 (Instr && Instr->getParent()) ? Instr->getParent()->getPlan() : nullptr); 108 print(dbgs(), "", SlotTracker); 109 dbgs() << "\n"; 110 } 111 #endif 112 113 // Get the top-most entry block of \p Start. This is the entry block of the 114 // containing VPlan. This function is templated to support both const and non-const blocks 115 template <typename T> static T *getPlanEntry(T *Start) { 116 T *Next = Start; 117 T *Current = Start; 118 while ((Next = Next->getParent())) 119 Current = Next; 120 121 SmallSetVector<T *, 8> WorkList; 122 WorkList.insert(Current); 123 124 for (unsigned i = 0; i < WorkList.size(); i++) { 125 T *Current = WorkList[i]; 126 if (Current->getNumPredecessors() == 0) 127 return Current; 128 auto &Predecessors = Current->getPredecessors(); 129 WorkList.insert(Predecessors.begin(), Predecessors.end()); 130 } 131 132 llvm_unreachable("VPlan without any entry node without predecessors"); 133 } 134 135 VPlan *VPBlockBase::getPlan() { return getPlanEntry(this)->Plan; } 136 137 const VPlan *VPBlockBase::getPlan() const { return getPlanEntry(this)->Plan; } 138 139 /// \return the VPBasicBlock that is the entry of Block, possibly indirectly. 140 const VPBasicBlock *VPBlockBase::getEntryBasicBlock() const { 141 const VPBlockBase *Block = this; 142 while (const VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block)) 143 Block = Region->getEntry(); 144 return cast<VPBasicBlock>(Block); 145 } 146 147 VPBasicBlock *VPBlockBase::getEntryBasicBlock() { 148 VPBlockBase *Block = this; 149 while (VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block)) 150 Block = Region->getEntry(); 151 return cast<VPBasicBlock>(Block); 152 } 153 154 void VPBlockBase::setPlan(VPlan *ParentPlan) { 155 assert(ParentPlan->getEntry() == this && 156 "Can only set plan on its entry block."); 157 Plan = ParentPlan; 158 } 159 160 /// \return the VPBasicBlock that is the exit of Block, possibly indirectly. 161 const VPBasicBlock *VPBlockBase::getExitBasicBlock() const { 162 const VPBlockBase *Block = this; 163 while (const VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block)) 164 Block = Region->getExit(); 165 return cast<VPBasicBlock>(Block); 166 } 167 168 VPBasicBlock *VPBlockBase::getExitBasicBlock() { 169 VPBlockBase *Block = this; 170 while (VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block)) 171 Block = Region->getExit(); 172 return cast<VPBasicBlock>(Block); 173 } 174 175 VPBlockBase *VPBlockBase::getEnclosingBlockWithSuccessors() { 176 if (!Successors.empty() || !Parent) 177 return this; 178 assert(Parent->getExit() == this && 179 "Block w/o successors not the exit of its parent."); 180 return Parent->getEnclosingBlockWithSuccessors(); 181 } 182 183 VPBlockBase *VPBlockBase::getEnclosingBlockWithPredecessors() { 184 if (!Predecessors.empty() || !Parent) 185 return this; 186 assert(Parent->getEntry() == this && 187 "Block w/o predecessors not the entry of its parent."); 188 return Parent->getEnclosingBlockWithPredecessors(); 189 } 190 191 VPValue *VPBlockBase::getCondBit() { 192 return CondBitUser.getSingleOperandOrNull(); 193 } 194 195 const VPValue *VPBlockBase::getCondBit() const { 196 return CondBitUser.getSingleOperandOrNull(); 197 } 198 199 void VPBlockBase::setCondBit(VPValue *CV) { CondBitUser.resetSingleOpUser(CV); } 200 201 VPValue *VPBlockBase::getPredicate() { 202 return PredicateUser.getSingleOperandOrNull(); 203 } 204 205 const VPValue *VPBlockBase::getPredicate() const { 206 return PredicateUser.getSingleOperandOrNull(); 207 } 208 209 void VPBlockBase::setPredicate(VPValue *CV) { 210 PredicateUser.resetSingleOpUser(CV); 211 } 212 213 void VPBlockBase::deleteCFG(VPBlockBase *Entry) { 214 SmallVector<VPBlockBase *, 8> Blocks(depth_first(Entry)); 215 216 for (VPBlockBase *Block : Blocks) 217 delete Block; 218 } 219 220 VPBasicBlock::iterator VPBasicBlock::getFirstNonPhi() { 221 iterator It = begin(); 222 while (It != end() && It->isPhi()) 223 It++; 224 return It; 225 } 226 227 Value *VPTransformState::get(VPValue *Def, const VPIteration &Instance) { 228 if (!Def->getDef()) 229 return Def->getLiveInIRValue(); 230 231 if (hasScalarValue(Def, Instance)) { 232 return Data 233 .PerPartScalars[Def][Instance.Part][Instance.Lane.mapToCacheIndex(VF)]; 234 } 235 236 assert(hasVectorValue(Def, Instance.Part)); 237 auto *VecPart = Data.PerPartOutput[Def][Instance.Part]; 238 if (!VecPart->getType()->isVectorTy()) { 239 assert(Instance.Lane.isFirstLane() && "cannot get lane > 0 for scalar"); 240 return VecPart; 241 } 242 // TODO: Cache created scalar values. 243 Value *Lane = Instance.Lane.getAsRuntimeExpr(Builder, VF); 244 auto *Extract = Builder.CreateExtractElement(VecPart, Lane); 245 // set(Def, Extract, Instance); 246 return Extract; 247 } 248 249 BasicBlock * 250 VPBasicBlock::createEmptyBasicBlock(VPTransformState::CFGState &CFG) { 251 // BB stands for IR BasicBlocks. VPBB stands for VPlan VPBasicBlocks. 252 // Pred stands for Predessor. Prev stands for Previous - last visited/created. 253 BasicBlock *PrevBB = CFG.PrevBB; 254 BasicBlock *NewBB = BasicBlock::Create(PrevBB->getContext(), getName(), 255 PrevBB->getParent(), CFG.LastBB); 256 LLVM_DEBUG(dbgs() << "LV: created " << NewBB->getName() << '\n'); 257 258 // Hook up the new basic block to its predecessors. 259 for (VPBlockBase *PredVPBlock : getHierarchicalPredecessors()) { 260 VPBasicBlock *PredVPBB = PredVPBlock->getExitBasicBlock(); 261 auto &PredVPSuccessors = PredVPBB->getSuccessors(); 262 BasicBlock *PredBB = CFG.VPBB2IRBB[PredVPBB]; 263 264 // In outer loop vectorization scenario, the predecessor BBlock may not yet 265 // be visited(backedge). Mark the VPBasicBlock for fixup at the end of 266 // vectorization. We do not encounter this case in inner loop vectorization 267 // as we start out by building a loop skeleton with the vector loop header 268 // and latch blocks. As a result, we never enter this function for the 269 // header block in the non VPlan-native path. 270 if (!PredBB) { 271 assert(EnableVPlanNativePath && 272 "Unexpected null predecessor in non VPlan-native path"); 273 CFG.VPBBsToFix.push_back(PredVPBB); 274 continue; 275 } 276 277 assert(PredBB && "Predecessor basic-block not found building successor."); 278 auto *PredBBTerminator = PredBB->getTerminator(); 279 LLVM_DEBUG(dbgs() << "LV: draw edge from" << PredBB->getName() << '\n'); 280 if (isa<UnreachableInst>(PredBBTerminator)) { 281 assert(PredVPSuccessors.size() == 1 && 282 "Predecessor ending w/o branch must have single successor."); 283 PredBBTerminator->eraseFromParent(); 284 BranchInst::Create(NewBB, PredBB); 285 } else { 286 assert(PredVPSuccessors.size() == 2 && 287 "Predecessor ending with branch must have two successors."); 288 unsigned idx = PredVPSuccessors.front() == this ? 0 : 1; 289 assert(!PredBBTerminator->getSuccessor(idx) && 290 "Trying to reset an existing successor block."); 291 PredBBTerminator->setSuccessor(idx, NewBB); 292 } 293 } 294 return NewBB; 295 } 296 297 void VPBasicBlock::execute(VPTransformState *State) { 298 bool Replica = State->Instance && !State->Instance->isFirstIteration(); 299 VPBasicBlock *PrevVPBB = State->CFG.PrevVPBB; 300 VPBlockBase *SingleHPred = nullptr; 301 BasicBlock *NewBB = State->CFG.PrevBB; // Reuse it if possible. 302 303 // 1. Create an IR basic block, or reuse the last one if possible. 304 // The last IR basic block is reused, as an optimization, in three cases: 305 // A. the first VPBB reuses the loop header BB - when PrevVPBB is null; 306 // B. when the current VPBB has a single (hierarchical) predecessor which 307 // is PrevVPBB and the latter has a single (hierarchical) successor; and 308 // C. when the current VPBB is an entry of a region replica - where PrevVPBB 309 // is the exit of this region from a previous instance, or the predecessor 310 // of this region. 311 if (PrevVPBB && /* A */ 312 !((SingleHPred = getSingleHierarchicalPredecessor()) && 313 SingleHPred->getExitBasicBlock() == PrevVPBB && 314 PrevVPBB->getSingleHierarchicalSuccessor()) && /* B */ 315 !(Replica && getPredecessors().empty())) { /* C */ 316 NewBB = createEmptyBasicBlock(State->CFG); 317 State->Builder.SetInsertPoint(NewBB); 318 // Temporarily terminate with unreachable until CFG is rewired. 319 UnreachableInst *Terminator = State->Builder.CreateUnreachable(); 320 State->Builder.SetInsertPoint(Terminator); 321 // Register NewBB in its loop. In innermost loops its the same for all BB's. 322 Loop *L = State->LI->getLoopFor(State->CFG.LastBB); 323 L->addBasicBlockToLoop(NewBB, *State->LI); 324 State->CFG.PrevBB = NewBB; 325 } 326 327 // 2. Fill the IR basic block with IR instructions. 328 LLVM_DEBUG(dbgs() << "LV: vectorizing VPBB:" << getName() 329 << " in BB:" << NewBB->getName() << '\n'); 330 331 State->CFG.VPBB2IRBB[this] = NewBB; 332 State->CFG.PrevVPBB = this; 333 334 for (VPRecipeBase &Recipe : Recipes) 335 Recipe.execute(*State); 336 337 VPValue *CBV; 338 if (EnableVPlanNativePath && (CBV = getCondBit())) { 339 assert(CBV->getUnderlyingValue() && 340 "Unexpected null underlying value for condition bit"); 341 342 // Condition bit value in a VPBasicBlock is used as the branch selector. In 343 // the VPlan-native path case, since all branches are uniform we generate a 344 // branch instruction using the condition value from vector lane 0 and dummy 345 // successors. The successors are fixed later when the successor blocks are 346 // visited. 347 Value *NewCond = State->get(CBV, {0, 0}); 348 349 // Replace the temporary unreachable terminator with the new conditional 350 // branch. 351 auto *CurrentTerminator = NewBB->getTerminator(); 352 assert(isa<UnreachableInst>(CurrentTerminator) && 353 "Expected to replace unreachable terminator with conditional " 354 "branch."); 355 auto *CondBr = BranchInst::Create(NewBB, nullptr, NewCond); 356 CondBr->setSuccessor(0, nullptr); 357 ReplaceInstWithInst(CurrentTerminator, CondBr); 358 } 359 360 LLVM_DEBUG(dbgs() << "LV: filled BB:" << *NewBB); 361 } 362 363 void VPBasicBlock::dropAllReferences(VPValue *NewValue) { 364 for (VPRecipeBase &R : Recipes) { 365 for (auto *Def : R.definedValues()) 366 Def->replaceAllUsesWith(NewValue); 367 368 for (unsigned I = 0, E = R.getNumOperands(); I != E; I++) 369 R.setOperand(I, NewValue); 370 } 371 } 372 373 VPBasicBlock *VPBasicBlock::splitAt(iterator SplitAt) { 374 assert((SplitAt == end() || SplitAt->getParent() == this) && 375 "can only split at a position in the same block"); 376 377 SmallVector<VPBlockBase *, 2> Succs(successors()); 378 // First, disconnect the current block from its successors. 379 for (VPBlockBase *Succ : Succs) 380 VPBlockUtils::disconnectBlocks(this, Succ); 381 382 // Create new empty block after the block to split. 383 auto *SplitBlock = new VPBasicBlock(getName() + ".split"); 384 VPBlockUtils::insertBlockAfter(SplitBlock, this); 385 386 // Add successors for block to split to new block. 387 for (VPBlockBase *Succ : Succs) 388 VPBlockUtils::connectBlocks(SplitBlock, Succ); 389 390 // Finally, move the recipes starting at SplitAt to new block. 391 for (VPRecipeBase &ToMove : 392 make_early_inc_range(make_range(SplitAt, this->end()))) 393 ToMove.moveBefore(*SplitBlock, SplitBlock->end()); 394 395 return SplitBlock; 396 } 397 398 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 399 void VPBlockBase::printSuccessors(raw_ostream &O, const Twine &Indent) const { 400 if (getSuccessors().empty()) { 401 O << Indent << "No successors\n"; 402 } else { 403 O << Indent << "Successor(s): "; 404 ListSeparator LS; 405 for (auto *Succ : getSuccessors()) 406 O << LS << Succ->getName(); 407 O << '\n'; 408 } 409 } 410 411 void VPBasicBlock::print(raw_ostream &O, const Twine &Indent, 412 VPSlotTracker &SlotTracker) const { 413 O << Indent << getName() << ":\n"; 414 if (const VPValue *Pred = getPredicate()) { 415 O << Indent << "BlockPredicate:"; 416 Pred->printAsOperand(O, SlotTracker); 417 if (const auto *PredInst = dyn_cast<VPInstruction>(Pred)) 418 O << " (" << PredInst->getParent()->getName() << ")"; 419 O << '\n'; 420 } 421 422 auto RecipeIndent = Indent + " "; 423 for (const VPRecipeBase &Recipe : *this) { 424 Recipe.print(O, RecipeIndent, SlotTracker); 425 O << '\n'; 426 } 427 428 printSuccessors(O, Indent); 429 430 if (const VPValue *CBV = getCondBit()) { 431 O << Indent << "CondBit: "; 432 CBV->printAsOperand(O, SlotTracker); 433 if (const auto *CBI = dyn_cast<VPInstruction>(CBV)) 434 O << " (" << CBI->getParent()->getName() << ")"; 435 O << '\n'; 436 } 437 } 438 #endif 439 440 void VPRegionBlock::dropAllReferences(VPValue *NewValue) { 441 for (VPBlockBase *Block : depth_first(Entry)) 442 // Drop all references in VPBasicBlocks and replace all uses with 443 // DummyValue. 444 Block->dropAllReferences(NewValue); 445 } 446 447 void VPRegionBlock::execute(VPTransformState *State) { 448 ReversePostOrderTraversal<VPBlockBase *> RPOT(Entry); 449 450 if (!isReplicator()) { 451 // Visit the VPBlocks connected to "this", starting from it. 452 for (VPBlockBase *Block : RPOT) { 453 if (EnableVPlanNativePath) { 454 // The inner loop vectorization path does not represent loop preheader 455 // and exit blocks as part of the VPlan. In the VPlan-native path, skip 456 // vectorizing loop preheader block. In future, we may replace this 457 // check with the check for loop preheader. 458 if (Block->getNumPredecessors() == 0) 459 continue; 460 461 // Skip vectorizing loop exit block. In future, we may replace this 462 // check with the check for loop exit. 463 if (Block->getNumSuccessors() == 0) 464 continue; 465 } 466 467 LLVM_DEBUG(dbgs() << "LV: VPBlock in RPO " << Block->getName() << '\n'); 468 Block->execute(State); 469 } 470 return; 471 } 472 473 assert(!State->Instance && "Replicating a Region with non-null instance."); 474 475 // Enter replicating mode. 476 State->Instance = VPIteration(0, 0); 477 478 for (unsigned Part = 0, UF = State->UF; Part < UF; ++Part) { 479 State->Instance->Part = Part; 480 assert(!State->VF.isScalable() && "VF is assumed to be non scalable."); 481 for (unsigned Lane = 0, VF = State->VF.getKnownMinValue(); Lane < VF; 482 ++Lane) { 483 State->Instance->Lane = VPLane(Lane, VPLane::Kind::First); 484 // Visit the VPBlocks connected to \p this, starting from it. 485 for (VPBlockBase *Block : RPOT) { 486 LLVM_DEBUG(dbgs() << "LV: VPBlock in RPO " << Block->getName() << '\n'); 487 Block->execute(State); 488 } 489 } 490 } 491 492 // Exit replicating mode. 493 State->Instance.reset(); 494 } 495 496 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 497 void VPRegionBlock::print(raw_ostream &O, const Twine &Indent, 498 VPSlotTracker &SlotTracker) const { 499 O << Indent << (isReplicator() ? "<xVFxUF> " : "<x1> ") << getName() << ": {"; 500 auto NewIndent = Indent + " "; 501 for (auto *BlockBase : depth_first(Entry)) { 502 O << '\n'; 503 BlockBase->print(O, NewIndent, SlotTracker); 504 } 505 O << Indent << "}\n"; 506 507 printSuccessors(O, Indent); 508 } 509 #endif 510 511 bool VPRecipeBase::mayWriteToMemory() const { 512 switch (getVPDefID()) { 513 case VPWidenMemoryInstructionSC: { 514 return cast<VPWidenMemoryInstructionRecipe>(this)->isStore(); 515 } 516 case VPReplicateSC: 517 case VPWidenCallSC: 518 return cast<Instruction>(getVPSingleValue()->getUnderlyingValue()) 519 ->mayWriteToMemory(); 520 case VPBranchOnMaskSC: 521 return false; 522 case VPWidenIntOrFpInductionSC: 523 case VPWidenCanonicalIVSC: 524 case VPWidenPHISC: 525 case VPBlendSC: 526 case VPWidenSC: 527 case VPWidenGEPSC: 528 case VPReductionSC: 529 case VPWidenSelectSC: { 530 const Instruction *I = 531 dyn_cast_or_null<Instruction>(getVPSingleValue()->getUnderlyingValue()); 532 (void)I; 533 assert((!I || !I->mayWriteToMemory()) && 534 "underlying instruction may write to memory"); 535 return false; 536 } 537 default: 538 return true; 539 } 540 } 541 542 bool VPRecipeBase::mayReadFromMemory() const { 543 switch (getVPDefID()) { 544 case VPWidenMemoryInstructionSC: { 545 return !cast<VPWidenMemoryInstructionRecipe>(this)->isStore(); 546 } 547 case VPReplicateSC: 548 case VPWidenCallSC: 549 return cast<Instruction>(getVPSingleValue()->getUnderlyingValue()) 550 ->mayReadFromMemory(); 551 case VPBranchOnMaskSC: 552 return false; 553 case VPWidenIntOrFpInductionSC: 554 case VPWidenCanonicalIVSC: 555 case VPWidenPHISC: 556 case VPBlendSC: 557 case VPWidenSC: 558 case VPWidenGEPSC: 559 case VPReductionSC: 560 case VPWidenSelectSC: { 561 const Instruction *I = 562 dyn_cast_or_null<Instruction>(getVPSingleValue()->getUnderlyingValue()); 563 (void)I; 564 assert((!I || !I->mayReadFromMemory()) && 565 "underlying instruction may read from memory"); 566 return false; 567 } 568 default: 569 return true; 570 } 571 } 572 573 bool VPRecipeBase::mayHaveSideEffects() const { 574 switch (getVPDefID()) { 575 case VPBranchOnMaskSC: 576 return false; 577 case VPWidenIntOrFpInductionSC: 578 case VPWidenCanonicalIVSC: 579 case VPWidenPHISC: 580 case VPBlendSC: 581 case VPWidenSC: 582 case VPWidenGEPSC: 583 case VPReductionSC: 584 case VPWidenSelectSC: { 585 const Instruction *I = 586 dyn_cast_or_null<Instruction>(getVPSingleValue()->getUnderlyingValue()); 587 (void)I; 588 assert((!I || !I->mayHaveSideEffects()) && 589 "underlying instruction has side-effects"); 590 return false; 591 } 592 case VPReplicateSC: { 593 auto *R = cast<VPReplicateRecipe>(this); 594 return R->getUnderlyingInstr()->mayHaveSideEffects(); 595 } 596 default: 597 return true; 598 } 599 } 600 601 void VPRecipeBase::insertBefore(VPRecipeBase *InsertPos) { 602 assert(!Parent && "Recipe already in some VPBasicBlock"); 603 assert(InsertPos->getParent() && 604 "Insertion position not in any VPBasicBlock"); 605 Parent = InsertPos->getParent(); 606 Parent->getRecipeList().insert(InsertPos->getIterator(), this); 607 } 608 609 void VPRecipeBase::insertAfter(VPRecipeBase *InsertPos) { 610 assert(!Parent && "Recipe already in some VPBasicBlock"); 611 assert(InsertPos->getParent() && 612 "Insertion position not in any VPBasicBlock"); 613 Parent = InsertPos->getParent(); 614 Parent->getRecipeList().insertAfter(InsertPos->getIterator(), this); 615 } 616 617 void VPRecipeBase::removeFromParent() { 618 assert(getParent() && "Recipe not in any VPBasicBlock"); 619 getParent()->getRecipeList().remove(getIterator()); 620 Parent = nullptr; 621 } 622 623 iplist<VPRecipeBase>::iterator VPRecipeBase::eraseFromParent() { 624 assert(getParent() && "Recipe not in any VPBasicBlock"); 625 return getParent()->getRecipeList().erase(getIterator()); 626 } 627 628 void VPRecipeBase::moveAfter(VPRecipeBase *InsertPos) { 629 removeFromParent(); 630 insertAfter(InsertPos); 631 } 632 633 void VPRecipeBase::moveBefore(VPBasicBlock &BB, 634 iplist<VPRecipeBase>::iterator I) { 635 assert(I == BB.end() || I->getParent() == &BB); 636 removeFromParent(); 637 Parent = &BB; 638 BB.getRecipeList().insert(I, this); 639 } 640 641 void VPInstruction::generateInstruction(VPTransformState &State, 642 unsigned Part) { 643 IRBuilder<> &Builder = State.Builder; 644 Builder.SetCurrentDebugLocation(DL); 645 646 if (Instruction::isBinaryOp(getOpcode())) { 647 Value *A = State.get(getOperand(0), Part); 648 Value *B = State.get(getOperand(1), Part); 649 Value *V = Builder.CreateBinOp((Instruction::BinaryOps)getOpcode(), A, B); 650 State.set(this, V, Part); 651 return; 652 } 653 654 switch (getOpcode()) { 655 case VPInstruction::Not: { 656 Value *A = State.get(getOperand(0), Part); 657 Value *V = Builder.CreateNot(A); 658 State.set(this, V, Part); 659 break; 660 } 661 case VPInstruction::ICmpULE: { 662 Value *IV = State.get(getOperand(0), Part); 663 Value *TC = State.get(getOperand(1), Part); 664 Value *V = Builder.CreateICmpULE(IV, TC); 665 State.set(this, V, Part); 666 break; 667 } 668 case Instruction::Select: { 669 Value *Cond = State.get(getOperand(0), Part); 670 Value *Op1 = State.get(getOperand(1), Part); 671 Value *Op2 = State.get(getOperand(2), Part); 672 Value *V = Builder.CreateSelect(Cond, Op1, Op2); 673 State.set(this, V, Part); 674 break; 675 } 676 case VPInstruction::ActiveLaneMask: { 677 // Get first lane of vector induction variable. 678 Value *VIVElem0 = State.get(getOperand(0), VPIteration(Part, 0)); 679 // Get the original loop tripcount. 680 Value *ScalarTC = State.get(getOperand(1), Part); 681 682 auto *Int1Ty = Type::getInt1Ty(Builder.getContext()); 683 auto *PredTy = FixedVectorType::get(Int1Ty, State.VF.getKnownMinValue()); 684 Instruction *Call = Builder.CreateIntrinsic( 685 Intrinsic::get_active_lane_mask, {PredTy, ScalarTC->getType()}, 686 {VIVElem0, ScalarTC}, nullptr, "active.lane.mask"); 687 State.set(this, Call, Part); 688 break; 689 } 690 case VPInstruction::FirstOrderRecurrenceSplice: { 691 // Generate code to combine the previous and current values in vector v3. 692 // 693 // vector.ph: 694 // v_init = vector(..., ..., ..., a[-1]) 695 // br vector.body 696 // 697 // vector.body 698 // i = phi [0, vector.ph], [i+4, vector.body] 699 // v1 = phi [v_init, vector.ph], [v2, vector.body] 700 // v2 = a[i, i+1, i+2, i+3]; 701 // v3 = vector(v1(3), v2(0, 1, 2)) 702 703 // For the first part, use the recurrence phi (v1), otherwise v2. 704 auto *V1 = State.get(getOperand(0), 0); 705 Value *PartMinus1 = Part == 0 ? V1 : State.get(getOperand(1), Part - 1); 706 if (!PartMinus1->getType()->isVectorTy()) { 707 State.set(this, PartMinus1, Part); 708 } else { 709 Value *V2 = State.get(getOperand(1), Part); 710 State.set(this, Builder.CreateVectorSplice(PartMinus1, V2, -1), Part); 711 } 712 break; 713 } 714 715 case VPInstruction::CanonicalIVIncrement: 716 case VPInstruction::CanonicalIVIncrementNUW: { 717 Value *Next = nullptr; 718 if (Part == 0) { 719 bool IsNUW = getOpcode() == VPInstruction::CanonicalIVIncrementNUW; 720 auto *Phi = State.get(getOperand(0), 0); 721 // The loop step is equal to the vectorization factor (num of SIMD 722 // elements) times the unroll factor (num of SIMD instructions). 723 Value *Step = 724 createStepForVF(Builder, Phi->getType(), State.VF, State.UF); 725 Next = Builder.CreateAdd(Phi, Step, "index.next", IsNUW, false); 726 } else { 727 Next = State.get(this, 0); 728 } 729 730 State.set(this, Next, Part); 731 break; 732 } 733 case VPInstruction::BranchOnCount: { 734 if (Part != 0) 735 break; 736 // First create the compare. 737 Value *IV = State.get(getOperand(0), Part); 738 Value *TC = State.get(getOperand(1), Part); 739 Value *Cond = Builder.CreateICmpEQ(IV, TC); 740 741 // Now create the branch. 742 auto *Plan = getParent()->getPlan(); 743 VPRegionBlock *TopRegion = Plan->getVectorLoopRegion(); 744 VPBasicBlock *Header = TopRegion->getEntry()->getEntryBasicBlock(); 745 if (Header->empty()) { 746 assert(EnableVPlanNativePath && 747 "empty entry block only expected in VPlanNativePath"); 748 Header = cast<VPBasicBlock>(Header->getSingleSuccessor()); 749 } 750 // TODO: Once the exit block is modeled in VPlan, use it instead of going 751 // through State.CFG.LastBB. 752 BasicBlock *Exit = 753 cast<BranchInst>(State.CFG.LastBB->getTerminator())->getSuccessor(0); 754 755 Builder.CreateCondBr(Cond, Exit, State.CFG.VPBB2IRBB[Header]); 756 Builder.GetInsertBlock()->getTerminator()->eraseFromParent(); 757 break; 758 } 759 default: 760 llvm_unreachable("Unsupported opcode for instruction"); 761 } 762 } 763 764 void VPInstruction::execute(VPTransformState &State) { 765 assert(!State.Instance && "VPInstruction executing an Instance"); 766 IRBuilderBase::FastMathFlagGuard FMFGuard(State.Builder); 767 State.Builder.setFastMathFlags(FMF); 768 for (unsigned Part = 0; Part < State.UF; ++Part) 769 generateInstruction(State, Part); 770 } 771 772 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 773 void VPInstruction::dump() const { 774 VPSlotTracker SlotTracker(getParent()->getPlan()); 775 print(dbgs(), "", SlotTracker); 776 } 777 778 void VPInstruction::print(raw_ostream &O, const Twine &Indent, 779 VPSlotTracker &SlotTracker) const { 780 O << Indent << "EMIT "; 781 782 if (hasResult()) { 783 printAsOperand(O, SlotTracker); 784 O << " = "; 785 } 786 787 switch (getOpcode()) { 788 case VPInstruction::Not: 789 O << "not"; 790 break; 791 case VPInstruction::ICmpULE: 792 O << "icmp ule"; 793 break; 794 case VPInstruction::SLPLoad: 795 O << "combined load"; 796 break; 797 case VPInstruction::SLPStore: 798 O << "combined store"; 799 break; 800 case VPInstruction::ActiveLaneMask: 801 O << "active lane mask"; 802 break; 803 case VPInstruction::FirstOrderRecurrenceSplice: 804 O << "first-order splice"; 805 break; 806 case VPInstruction::CanonicalIVIncrement: 807 O << "VF * UF + "; 808 break; 809 case VPInstruction::CanonicalIVIncrementNUW: 810 O << "VF * UF +(nuw) "; 811 break; 812 case VPInstruction::BranchOnCount: 813 O << "branch-on-count "; 814 break; 815 default: 816 O << Instruction::getOpcodeName(getOpcode()); 817 } 818 819 O << FMF; 820 821 for (const VPValue *Operand : operands()) { 822 O << " "; 823 Operand->printAsOperand(O, SlotTracker); 824 } 825 826 if (DL) { 827 O << ", !dbg "; 828 DL.print(O); 829 } 830 } 831 #endif 832 833 void VPInstruction::setFastMathFlags(FastMathFlags FMFNew) { 834 // Make sure the VPInstruction is a floating-point operation. 835 assert((Opcode == Instruction::FAdd || Opcode == Instruction::FMul || 836 Opcode == Instruction::FNeg || Opcode == Instruction::FSub || 837 Opcode == Instruction::FDiv || Opcode == Instruction::FRem || 838 Opcode == Instruction::FCmp) && 839 "this op can't take fast-math flags"); 840 FMF = FMFNew; 841 } 842 843 void VPlan::prepareToExecute(Value *TripCountV, Value *VectorTripCountV, 844 Value *CanonicalIVStartValue, 845 VPTransformState &State) { 846 // Check if the trip count is needed, and if so build it. 847 if (TripCount && TripCount->getNumUsers()) { 848 for (unsigned Part = 0, UF = State.UF; Part < UF; ++Part) 849 State.set(TripCount, TripCountV, Part); 850 } 851 852 // Check if the backedge taken count is needed, and if so build it. 853 if (BackedgeTakenCount && BackedgeTakenCount->getNumUsers()) { 854 IRBuilder<> Builder(State.CFG.PrevBB->getTerminator()); 855 auto *TCMO = Builder.CreateSub(TripCountV, 856 ConstantInt::get(TripCountV->getType(), 1), 857 "trip.count.minus.1"); 858 auto VF = State.VF; 859 Value *VTCMO = 860 VF.isScalar() ? TCMO : Builder.CreateVectorSplat(VF, TCMO, "broadcast"); 861 for (unsigned Part = 0, UF = State.UF; Part < UF; ++Part) 862 State.set(BackedgeTakenCount, VTCMO, Part); 863 } 864 865 for (unsigned Part = 0, UF = State.UF; Part < UF; ++Part) 866 State.set(&VectorTripCount, VectorTripCountV, Part); 867 868 // When vectorizing the epilogue loop, the canonical induction start value 869 // needs to be changed from zero to the value after the main vector loop. 870 if (CanonicalIVStartValue) { 871 VPValue *VPV = new VPValue(CanonicalIVStartValue); 872 addExternalDef(VPV); 873 auto *IV = getCanonicalIV(); 874 IV->setOperand(0, VPV); 875 } 876 } 877 878 /// Generate the code inside the body of the vectorized loop. Assumes a single 879 /// LoopVectorBody basic-block was created for this. Introduce additional 880 /// basic-blocks as needed, and fill them all. 881 void VPlan::execute(VPTransformState *State) { 882 // 0. Set the reverse mapping from VPValues to Values for code generation. 883 for (auto &Entry : Value2VPValue) 884 State->VPValue2Value[Entry.second] = Entry.first; 885 886 BasicBlock *VectorPreHeaderBB = State->CFG.PrevBB; 887 State->CFG.VectorPreHeader = VectorPreHeaderBB; 888 BasicBlock *VectorHeaderBB = VectorPreHeaderBB->getSingleSuccessor(); 889 assert(VectorHeaderBB && "Loop preheader does not have a single successor."); 890 891 // 1. Make room to generate basic-blocks inside loop body if needed. 892 BasicBlock *VectorLatchBB = VectorHeaderBB->splitBasicBlock( 893 VectorHeaderBB->getFirstInsertionPt(), "vector.body.latch"); 894 Loop *L = State->LI->getLoopFor(VectorHeaderBB); 895 L->addBasicBlockToLoop(VectorLatchBB, *State->LI); 896 // Remove the edge between Header and Latch to allow other connections. 897 // Temporarily terminate with unreachable until CFG is rewired. 898 // Note: this asserts the generated code's assumption that 899 // getFirstInsertionPt() can be dereferenced into an Instruction. 900 VectorHeaderBB->getTerminator()->eraseFromParent(); 901 State->Builder.SetInsertPoint(VectorHeaderBB); 902 UnreachableInst *Terminator = State->Builder.CreateUnreachable(); 903 State->Builder.SetInsertPoint(Terminator); 904 905 // 2. Generate code in loop body. 906 State->CFG.PrevVPBB = nullptr; 907 State->CFG.PrevBB = VectorHeaderBB; 908 State->CFG.LastBB = VectorLatchBB; 909 910 for (VPBlockBase *Block : depth_first(Entry)) 911 Block->execute(State); 912 913 // Setup branch terminator successors for VPBBs in VPBBsToFix based on 914 // VPBB's successors. 915 for (auto VPBB : State->CFG.VPBBsToFix) { 916 assert(EnableVPlanNativePath && 917 "Unexpected VPBBsToFix in non VPlan-native path"); 918 BasicBlock *BB = State->CFG.VPBB2IRBB[VPBB]; 919 assert(BB && "Unexpected null basic block for VPBB"); 920 921 unsigned Idx = 0; 922 auto *BBTerminator = BB->getTerminator(); 923 924 for (VPBlockBase *SuccVPBlock : VPBB->getHierarchicalSuccessors()) { 925 VPBasicBlock *SuccVPBB = SuccVPBlock->getEntryBasicBlock(); 926 BBTerminator->setSuccessor(Idx, State->CFG.VPBB2IRBB[SuccVPBB]); 927 ++Idx; 928 } 929 } 930 931 // 3. Merge the temporary latch created with the last basic-block filled. 932 BasicBlock *LastBB = State->CFG.PrevBB; 933 assert(isa<BranchInst>(LastBB->getTerminator()) && 934 "Expected VPlan CFG to terminate with branch"); 935 936 // Move both the branch and check from LastBB to VectorLatchBB. 937 auto *LastBranch = cast<BranchInst>(LastBB->getTerminator()); 938 LastBranch->moveBefore(VectorLatchBB->getTerminator()); 939 VectorLatchBB->getTerminator()->eraseFromParent(); 940 // Move condition so it is guaranteed to be next to branch. This is only done 941 // to avoid excessive test updates. 942 // TODO: Remove special handling once the increments for all inductions are 943 // modeled explicitly in VPlan. 944 cast<Instruction>(LastBranch->getCondition())->moveBefore(LastBranch); 945 // Connect LastBB to VectorLatchBB to facilitate their merge. 946 BranchInst::Create(VectorLatchBB, LastBB); 947 948 // Merge LastBB with Latch. 949 bool Merged = MergeBlockIntoPredecessor(VectorLatchBB, nullptr, State->LI); 950 (void)Merged; 951 assert(Merged && "Could not merge last basic block with latch."); 952 VectorLatchBB = LastBB; 953 954 // Fix the latch value of canonical, reduction and first-order recurrences 955 // phis in the vector loop. 956 VPBasicBlock *Header = Entry->getEntryBasicBlock(); 957 if (Header->empty()) { 958 assert(EnableVPlanNativePath); 959 Header = cast<VPBasicBlock>(Header->getSingleSuccessor()); 960 } 961 for (VPRecipeBase &R : Header->phis()) { 962 // Skip phi-like recipes that generate their backedege values themselves. 963 // TODO: Model their backedge values explicitly. 964 if (isa<VPWidenIntOrFpInductionRecipe>(&R) || isa<VPWidenPHIRecipe>(&R)) 965 continue; 966 967 auto *PhiR = cast<VPHeaderPHIRecipe>(&R); 968 // For canonical IV, first-order recurrences and in-order reduction phis, 969 // only a single part is generated, which provides the last part from the 970 // previous iteration. For non-ordered reductions all UF parts are 971 // generated. 972 bool SinglePartNeeded = isa<VPCanonicalIVPHIRecipe>(PhiR) || 973 isa<VPFirstOrderRecurrencePHIRecipe>(PhiR) || 974 cast<VPReductionPHIRecipe>(PhiR)->isOrdered(); 975 unsigned LastPartForNewPhi = SinglePartNeeded ? 1 : State->UF; 976 977 for (unsigned Part = 0; Part < LastPartForNewPhi; ++Part) { 978 Value *Phi = State->get(PhiR, Part); 979 Value *Val = State->get(PhiR->getBackedgeValue(), 980 SinglePartNeeded ? State->UF - 1 : Part); 981 cast<PHINode>(Phi)->addIncoming(Val, VectorLatchBB); 982 } 983 } 984 985 // We do not attempt to preserve DT for outer loop vectorization currently. 986 if (!EnableVPlanNativePath) 987 updateDominatorTree(State->DT, VectorPreHeaderBB, VectorLatchBB, 988 L->getExitBlock()); 989 } 990 991 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 992 LLVM_DUMP_METHOD 993 void VPlan::print(raw_ostream &O) const { 994 VPSlotTracker SlotTracker(this); 995 996 O << "VPlan '" << Name << "' {"; 997 998 if (VectorTripCount.getNumUsers() > 0) { 999 O << "\nLive-in "; 1000 VectorTripCount.printAsOperand(O, SlotTracker); 1001 O << " = vector-trip-count\n"; 1002 } 1003 1004 if (BackedgeTakenCount && BackedgeTakenCount->getNumUsers()) { 1005 O << "\nLive-in "; 1006 BackedgeTakenCount->printAsOperand(O, SlotTracker); 1007 O << " = backedge-taken count\n"; 1008 } 1009 1010 for (const VPBlockBase *Block : depth_first(getEntry())) { 1011 O << '\n'; 1012 Block->print(O, "", SlotTracker); 1013 } 1014 O << "}\n"; 1015 } 1016 1017 LLVM_DUMP_METHOD 1018 void VPlan::printDOT(raw_ostream &O) const { 1019 VPlanPrinter Printer(O, *this); 1020 Printer.dump(); 1021 } 1022 1023 LLVM_DUMP_METHOD 1024 void VPlan::dump() const { print(dbgs()); } 1025 #endif 1026 1027 void VPlan::updateDominatorTree(DominatorTree *DT, BasicBlock *LoopPreHeaderBB, 1028 BasicBlock *LoopLatchBB, 1029 BasicBlock *LoopExitBB) { 1030 BasicBlock *LoopHeaderBB = LoopPreHeaderBB->getSingleSuccessor(); 1031 assert(LoopHeaderBB && "Loop preheader does not have a single successor."); 1032 // The vector body may be more than a single basic-block by this point. 1033 // Update the dominator tree information inside the vector body by propagating 1034 // it from header to latch, expecting only triangular control-flow, if any. 1035 BasicBlock *PostDomSucc = nullptr; 1036 for (auto *BB = LoopHeaderBB; BB != LoopLatchBB; BB = PostDomSucc) { 1037 // Get the list of successors of this block. 1038 std::vector<BasicBlock *> Succs(succ_begin(BB), succ_end(BB)); 1039 assert(Succs.size() <= 2 && 1040 "Basic block in vector loop has more than 2 successors."); 1041 PostDomSucc = Succs[0]; 1042 if (Succs.size() == 1) { 1043 assert(PostDomSucc->getSinglePredecessor() && 1044 "PostDom successor has more than one predecessor."); 1045 DT->addNewBlock(PostDomSucc, BB); 1046 continue; 1047 } 1048 BasicBlock *InterimSucc = Succs[1]; 1049 if (PostDomSucc->getSingleSuccessor() == InterimSucc) { 1050 PostDomSucc = Succs[1]; 1051 InterimSucc = Succs[0]; 1052 } 1053 assert(InterimSucc->getSingleSuccessor() == PostDomSucc && 1054 "One successor of a basic block does not lead to the other."); 1055 assert(InterimSucc->getSinglePredecessor() && 1056 "Interim successor has more than one predecessor."); 1057 assert(PostDomSucc->hasNPredecessors(2) && 1058 "PostDom successor has more than two predecessors."); 1059 DT->addNewBlock(InterimSucc, BB); 1060 DT->addNewBlock(PostDomSucc, BB); 1061 } 1062 // Latch block is a new dominator for the loop exit. 1063 DT->changeImmediateDominator(LoopExitBB, LoopLatchBB); 1064 assert(DT->verify(DominatorTree::VerificationLevel::Fast)); 1065 } 1066 1067 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1068 Twine VPlanPrinter::getUID(const VPBlockBase *Block) { 1069 return (isa<VPRegionBlock>(Block) ? "cluster_N" : "N") + 1070 Twine(getOrCreateBID(Block)); 1071 } 1072 1073 Twine VPlanPrinter::getOrCreateName(const VPBlockBase *Block) { 1074 const std::string &Name = Block->getName(); 1075 if (!Name.empty()) 1076 return Name; 1077 return "VPB" + Twine(getOrCreateBID(Block)); 1078 } 1079 1080 void VPlanPrinter::dump() { 1081 Depth = 1; 1082 bumpIndent(0); 1083 OS << "digraph VPlan {\n"; 1084 OS << "graph [labelloc=t, fontsize=30; label=\"Vectorization Plan"; 1085 if (!Plan.getName().empty()) 1086 OS << "\\n" << DOT::EscapeString(Plan.getName()); 1087 if (Plan.BackedgeTakenCount) { 1088 OS << ", where:\\n"; 1089 Plan.BackedgeTakenCount->print(OS, SlotTracker); 1090 OS << " := BackedgeTakenCount"; 1091 } 1092 OS << "\"]\n"; 1093 OS << "node [shape=rect, fontname=Courier, fontsize=30]\n"; 1094 OS << "edge [fontname=Courier, fontsize=30]\n"; 1095 OS << "compound=true\n"; 1096 1097 for (const VPBlockBase *Block : depth_first(Plan.getEntry())) 1098 dumpBlock(Block); 1099 1100 OS << "}\n"; 1101 } 1102 1103 void VPlanPrinter::dumpBlock(const VPBlockBase *Block) { 1104 if (const VPBasicBlock *BasicBlock = dyn_cast<VPBasicBlock>(Block)) 1105 dumpBasicBlock(BasicBlock); 1106 else if (const VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block)) 1107 dumpRegion(Region); 1108 else 1109 llvm_unreachable("Unsupported kind of VPBlock."); 1110 } 1111 1112 void VPlanPrinter::drawEdge(const VPBlockBase *From, const VPBlockBase *To, 1113 bool Hidden, const Twine &Label) { 1114 // Due to "dot" we print an edge between two regions as an edge between the 1115 // exit basic block and the entry basic of the respective regions. 1116 const VPBlockBase *Tail = From->getExitBasicBlock(); 1117 const VPBlockBase *Head = To->getEntryBasicBlock(); 1118 OS << Indent << getUID(Tail) << " -> " << getUID(Head); 1119 OS << " [ label=\"" << Label << '\"'; 1120 if (Tail != From) 1121 OS << " ltail=" << getUID(From); 1122 if (Head != To) 1123 OS << " lhead=" << getUID(To); 1124 if (Hidden) 1125 OS << "; splines=none"; 1126 OS << "]\n"; 1127 } 1128 1129 void VPlanPrinter::dumpEdges(const VPBlockBase *Block) { 1130 auto &Successors = Block->getSuccessors(); 1131 if (Successors.size() == 1) 1132 drawEdge(Block, Successors.front(), false, ""); 1133 else if (Successors.size() == 2) { 1134 drawEdge(Block, Successors.front(), false, "T"); 1135 drawEdge(Block, Successors.back(), false, "F"); 1136 } else { 1137 unsigned SuccessorNumber = 0; 1138 for (auto *Successor : Successors) 1139 drawEdge(Block, Successor, false, Twine(SuccessorNumber++)); 1140 } 1141 } 1142 1143 void VPlanPrinter::dumpBasicBlock(const VPBasicBlock *BasicBlock) { 1144 // Implement dot-formatted dump by performing plain-text dump into the 1145 // temporary storage followed by some post-processing. 1146 OS << Indent << getUID(BasicBlock) << " [label =\n"; 1147 bumpIndent(1); 1148 std::string Str; 1149 raw_string_ostream SS(Str); 1150 // Use no indentation as we need to wrap the lines into quotes ourselves. 1151 BasicBlock->print(SS, "", SlotTracker); 1152 1153 // We need to process each line of the output separately, so split 1154 // single-string plain-text dump. 1155 SmallVector<StringRef, 0> Lines; 1156 StringRef(Str).rtrim('\n').split(Lines, "\n"); 1157 1158 auto EmitLine = [&](StringRef Line, StringRef Suffix) { 1159 OS << Indent << '"' << DOT::EscapeString(Line.str()) << "\\l\"" << Suffix; 1160 }; 1161 1162 // Don't need the "+" after the last line. 1163 for (auto Line : make_range(Lines.begin(), Lines.end() - 1)) 1164 EmitLine(Line, " +\n"); 1165 EmitLine(Lines.back(), "\n"); 1166 1167 bumpIndent(-1); 1168 OS << Indent << "]\n"; 1169 1170 dumpEdges(BasicBlock); 1171 } 1172 1173 void VPlanPrinter::dumpRegion(const VPRegionBlock *Region) { 1174 OS << Indent << "subgraph " << getUID(Region) << " {\n"; 1175 bumpIndent(1); 1176 OS << Indent << "fontname=Courier\n" 1177 << Indent << "label=\"" 1178 << DOT::EscapeString(Region->isReplicator() ? "<xVFxUF> " : "<x1> ") 1179 << DOT::EscapeString(Region->getName()) << "\"\n"; 1180 // Dump the blocks of the region. 1181 assert(Region->getEntry() && "Region contains no inner blocks."); 1182 for (const VPBlockBase *Block : depth_first(Region->getEntry())) 1183 dumpBlock(Block); 1184 bumpIndent(-1); 1185 OS << Indent << "}\n"; 1186 dumpEdges(Region); 1187 } 1188 1189 void VPlanIngredient::print(raw_ostream &O) const { 1190 if (auto *Inst = dyn_cast<Instruction>(V)) { 1191 if (!Inst->getType()->isVoidTy()) { 1192 Inst->printAsOperand(O, false); 1193 O << " = "; 1194 } 1195 O << Inst->getOpcodeName() << " "; 1196 unsigned E = Inst->getNumOperands(); 1197 if (E > 0) { 1198 Inst->getOperand(0)->printAsOperand(O, false); 1199 for (unsigned I = 1; I < E; ++I) 1200 Inst->getOperand(I)->printAsOperand(O << ", ", false); 1201 } 1202 } else // !Inst 1203 V->printAsOperand(O, false); 1204 } 1205 1206 void VPWidenCallRecipe::print(raw_ostream &O, const Twine &Indent, 1207 VPSlotTracker &SlotTracker) const { 1208 O << Indent << "WIDEN-CALL "; 1209 1210 auto *CI = cast<CallInst>(getUnderlyingInstr()); 1211 if (CI->getType()->isVoidTy()) 1212 O << "void "; 1213 else { 1214 printAsOperand(O, SlotTracker); 1215 O << " = "; 1216 } 1217 1218 O << "call @" << CI->getCalledFunction()->getName() << "("; 1219 printOperands(O, SlotTracker); 1220 O << ")"; 1221 } 1222 1223 void VPWidenSelectRecipe::print(raw_ostream &O, const Twine &Indent, 1224 VPSlotTracker &SlotTracker) const { 1225 O << Indent << "WIDEN-SELECT "; 1226 printAsOperand(O, SlotTracker); 1227 O << " = select "; 1228 getOperand(0)->printAsOperand(O, SlotTracker); 1229 O << ", "; 1230 getOperand(1)->printAsOperand(O, SlotTracker); 1231 O << ", "; 1232 getOperand(2)->printAsOperand(O, SlotTracker); 1233 O << (InvariantCond ? " (condition is loop invariant)" : ""); 1234 } 1235 1236 void VPWidenRecipe::print(raw_ostream &O, const Twine &Indent, 1237 VPSlotTracker &SlotTracker) const { 1238 O << Indent << "WIDEN "; 1239 printAsOperand(O, SlotTracker); 1240 O << " = " << getUnderlyingInstr()->getOpcodeName() << " "; 1241 printOperands(O, SlotTracker); 1242 } 1243 1244 void VPWidenIntOrFpInductionRecipe::print(raw_ostream &O, const Twine &Indent, 1245 VPSlotTracker &SlotTracker) const { 1246 O << Indent << "WIDEN-INDUCTION"; 1247 if (getTruncInst()) { 1248 O << "\\l\""; 1249 O << " +\n" << Indent << "\" " << VPlanIngredient(IV) << "\\l\""; 1250 O << " +\n" << Indent << "\" "; 1251 getVPValue(0)->printAsOperand(O, SlotTracker); 1252 } else 1253 O << " " << VPlanIngredient(IV); 1254 } 1255 1256 void VPWidenGEPRecipe::print(raw_ostream &O, const Twine &Indent, 1257 VPSlotTracker &SlotTracker) const { 1258 O << Indent << "WIDEN-GEP "; 1259 O << (IsPtrLoopInvariant ? "Inv" : "Var"); 1260 size_t IndicesNumber = IsIndexLoopInvariant.size(); 1261 for (size_t I = 0; I < IndicesNumber; ++I) 1262 O << "[" << (IsIndexLoopInvariant[I] ? "Inv" : "Var") << "]"; 1263 1264 O << " "; 1265 printAsOperand(O, SlotTracker); 1266 O << " = getelementptr "; 1267 printOperands(O, SlotTracker); 1268 } 1269 1270 void VPWidenPHIRecipe::print(raw_ostream &O, const Twine &Indent, 1271 VPSlotTracker &SlotTracker) const { 1272 O << Indent << "WIDEN-PHI "; 1273 1274 auto *OriginalPhi = cast<PHINode>(getUnderlyingValue()); 1275 // Unless all incoming values are modeled in VPlan print the original PHI 1276 // directly. 1277 // TODO: Remove once all VPWidenPHIRecipe instances keep all relevant incoming 1278 // values as VPValues. 1279 if (getNumOperands() != OriginalPhi->getNumOperands()) { 1280 O << VPlanIngredient(OriginalPhi); 1281 return; 1282 } 1283 1284 printAsOperand(O, SlotTracker); 1285 O << " = phi "; 1286 printOperands(O, SlotTracker); 1287 } 1288 1289 void VPBlendRecipe::print(raw_ostream &O, const Twine &Indent, 1290 VPSlotTracker &SlotTracker) const { 1291 O << Indent << "BLEND "; 1292 Phi->printAsOperand(O, false); 1293 O << " ="; 1294 if (getNumIncomingValues() == 1) { 1295 // Not a User of any mask: not really blending, this is a 1296 // single-predecessor phi. 1297 O << " "; 1298 getIncomingValue(0)->printAsOperand(O, SlotTracker); 1299 } else { 1300 for (unsigned I = 0, E = getNumIncomingValues(); I < E; ++I) { 1301 O << " "; 1302 getIncomingValue(I)->printAsOperand(O, SlotTracker); 1303 O << "/"; 1304 getMask(I)->printAsOperand(O, SlotTracker); 1305 } 1306 } 1307 } 1308 1309 void VPReductionRecipe::print(raw_ostream &O, const Twine &Indent, 1310 VPSlotTracker &SlotTracker) const { 1311 O << Indent << "REDUCE "; 1312 printAsOperand(O, SlotTracker); 1313 O << " = "; 1314 getChainOp()->printAsOperand(O, SlotTracker); 1315 O << " +"; 1316 if (isa<FPMathOperator>(getUnderlyingInstr())) 1317 O << getUnderlyingInstr()->getFastMathFlags(); 1318 O << " reduce." << Instruction::getOpcodeName(RdxDesc->getOpcode()) << " ("; 1319 getVecOp()->printAsOperand(O, SlotTracker); 1320 if (getCondOp()) { 1321 O << ", "; 1322 getCondOp()->printAsOperand(O, SlotTracker); 1323 } 1324 O << ")"; 1325 } 1326 1327 void VPReplicateRecipe::print(raw_ostream &O, const Twine &Indent, 1328 VPSlotTracker &SlotTracker) const { 1329 O << Indent << (IsUniform ? "CLONE " : "REPLICATE "); 1330 1331 if (!getUnderlyingInstr()->getType()->isVoidTy()) { 1332 printAsOperand(O, SlotTracker); 1333 O << " = "; 1334 } 1335 O << Instruction::getOpcodeName(getUnderlyingInstr()->getOpcode()) << " "; 1336 printOperands(O, SlotTracker); 1337 1338 if (AlsoPack) 1339 O << " (S->V)"; 1340 } 1341 1342 void VPPredInstPHIRecipe::print(raw_ostream &O, const Twine &Indent, 1343 VPSlotTracker &SlotTracker) const { 1344 O << Indent << "PHI-PREDICATED-INSTRUCTION "; 1345 printAsOperand(O, SlotTracker); 1346 O << " = "; 1347 printOperands(O, SlotTracker); 1348 } 1349 1350 void VPWidenMemoryInstructionRecipe::print(raw_ostream &O, const Twine &Indent, 1351 VPSlotTracker &SlotTracker) const { 1352 O << Indent << "WIDEN "; 1353 1354 if (!isStore()) { 1355 getVPSingleValue()->printAsOperand(O, SlotTracker); 1356 O << " = "; 1357 } 1358 O << Instruction::getOpcodeName(Ingredient.getOpcode()) << " "; 1359 1360 printOperands(O, SlotTracker); 1361 } 1362 #endif 1363 1364 void VPCanonicalIVPHIRecipe::execute(VPTransformState &State) { 1365 Value *Start = getStartValue()->getLiveInIRValue(); 1366 PHINode *EntryPart = PHINode::Create( 1367 Start->getType(), 2, "index", &*State.CFG.PrevBB->getFirstInsertionPt()); 1368 EntryPart->addIncoming(Start, State.CFG.VectorPreHeader); 1369 EntryPart->setDebugLoc(DL); 1370 for (unsigned Part = 0, UF = State.UF; Part < UF; ++Part) 1371 State.set(this, EntryPart, Part); 1372 } 1373 1374 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1375 void VPCanonicalIVPHIRecipe::print(raw_ostream &O, const Twine &Indent, 1376 VPSlotTracker &SlotTracker) const { 1377 O << Indent << "EMIT "; 1378 getVPSingleValue()->printAsOperand(O, SlotTracker); 1379 O << " = CANONICAL-INDUCTION"; 1380 } 1381 #endif 1382 1383 void VPWidenCanonicalIVRecipe::execute(VPTransformState &State) { 1384 Value *CanonicalIV = State.get(getOperand(0), 0); 1385 Type *STy = CanonicalIV->getType(); 1386 IRBuilder<> Builder(State.CFG.PrevBB->getTerminator()); 1387 ElementCount VF = State.VF; 1388 Value *VStart = VF.isScalar() 1389 ? CanonicalIV 1390 : Builder.CreateVectorSplat(VF, CanonicalIV, "broadcast"); 1391 for (unsigned Part = 0, UF = State.UF; Part < UF; ++Part) { 1392 Value *VStep = createStepForVF(Builder, STy, VF, Part); 1393 if (VF.isVector()) { 1394 VStep = Builder.CreateVectorSplat(VF, VStep); 1395 VStep = Builder.CreateAdd(VStep, Builder.CreateStepVector(VStep->getType())); 1396 } 1397 Value *CanonicalVectorIV = Builder.CreateAdd(VStart, VStep, "vec.iv"); 1398 State.set(this, CanonicalVectorIV, Part); 1399 } 1400 } 1401 1402 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1403 void VPWidenCanonicalIVRecipe::print(raw_ostream &O, const Twine &Indent, 1404 VPSlotTracker &SlotTracker) const { 1405 O << Indent << "EMIT "; 1406 printAsOperand(O, SlotTracker); 1407 O << " = WIDEN-CANONICAL-INDUCTION "; 1408 printOperands(O, SlotTracker); 1409 } 1410 #endif 1411 1412 void VPFirstOrderRecurrencePHIRecipe::execute(VPTransformState &State) { 1413 auto &Builder = State.Builder; 1414 // Create a vector from the initial value. 1415 auto *VectorInit = getStartValue()->getLiveInIRValue(); 1416 1417 Type *VecTy = State.VF.isScalar() 1418 ? VectorInit->getType() 1419 : VectorType::get(VectorInit->getType(), State.VF); 1420 1421 if (State.VF.isVector()) { 1422 auto *IdxTy = Builder.getInt32Ty(); 1423 auto *One = ConstantInt::get(IdxTy, 1); 1424 IRBuilder<>::InsertPointGuard Guard(Builder); 1425 Builder.SetInsertPoint(State.CFG.VectorPreHeader->getTerminator()); 1426 auto *RuntimeVF = getRuntimeVF(Builder, IdxTy, State.VF); 1427 auto *LastIdx = Builder.CreateSub(RuntimeVF, One); 1428 VectorInit = Builder.CreateInsertElement( 1429 PoisonValue::get(VecTy), VectorInit, LastIdx, "vector.recur.init"); 1430 } 1431 1432 // Create a phi node for the new recurrence. 1433 PHINode *EntryPart = PHINode::Create( 1434 VecTy, 2, "vector.recur", &*State.CFG.PrevBB->getFirstInsertionPt()); 1435 EntryPart->addIncoming(VectorInit, State.CFG.VectorPreHeader); 1436 State.set(this, EntryPart, 0); 1437 } 1438 1439 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1440 void VPFirstOrderRecurrencePHIRecipe::print(raw_ostream &O, const Twine &Indent, 1441 VPSlotTracker &SlotTracker) const { 1442 O << Indent << "FIRST-ORDER-RECURRENCE-PHI "; 1443 printAsOperand(O, SlotTracker); 1444 O << " = phi "; 1445 printOperands(O, SlotTracker); 1446 } 1447 #endif 1448 1449 void VPReductionPHIRecipe::execute(VPTransformState &State) { 1450 PHINode *PN = cast<PHINode>(getUnderlyingValue()); 1451 auto &Builder = State.Builder; 1452 1453 // In order to support recurrences we need to be able to vectorize Phi nodes. 1454 // Phi nodes have cycles, so we need to vectorize them in two stages. This is 1455 // stage #1: We create a new vector PHI node with no incoming edges. We'll use 1456 // this value when we vectorize all of the instructions that use the PHI. 1457 bool ScalarPHI = State.VF.isScalar() || IsInLoop; 1458 Type *VecTy = 1459 ScalarPHI ? PN->getType() : VectorType::get(PN->getType(), State.VF); 1460 1461 BasicBlock *HeaderBB = State.CFG.PrevBB; 1462 assert(State.LI->getLoopFor(HeaderBB)->getHeader() == HeaderBB && 1463 "recipe must be in the vector loop header"); 1464 unsigned LastPartForNewPhi = isOrdered() ? 1 : State.UF; 1465 for (unsigned Part = 0; Part < LastPartForNewPhi; ++Part) { 1466 Value *EntryPart = 1467 PHINode::Create(VecTy, 2, "vec.phi", &*HeaderBB->getFirstInsertionPt()); 1468 State.set(this, EntryPart, Part); 1469 } 1470 1471 // Reductions do not have to start at zero. They can start with 1472 // any loop invariant values. 1473 VPValue *StartVPV = getStartValue(); 1474 Value *StartV = StartVPV->getLiveInIRValue(); 1475 1476 Value *Iden = nullptr; 1477 RecurKind RK = RdxDesc.getRecurrenceKind(); 1478 if (RecurrenceDescriptor::isMinMaxRecurrenceKind(RK) || 1479 RecurrenceDescriptor::isSelectCmpRecurrenceKind(RK)) { 1480 // MinMax reduction have the start value as their identify. 1481 if (ScalarPHI) { 1482 Iden = StartV; 1483 } else { 1484 IRBuilderBase::InsertPointGuard IPBuilder(Builder); 1485 Builder.SetInsertPoint(State.CFG.VectorPreHeader->getTerminator()); 1486 StartV = Iden = 1487 Builder.CreateVectorSplat(State.VF, StartV, "minmax.ident"); 1488 } 1489 } else { 1490 Iden = RdxDesc.getRecurrenceIdentity(RK, VecTy->getScalarType(), 1491 RdxDesc.getFastMathFlags()); 1492 1493 if (!ScalarPHI) { 1494 Iden = Builder.CreateVectorSplat(State.VF, Iden); 1495 IRBuilderBase::InsertPointGuard IPBuilder(Builder); 1496 Builder.SetInsertPoint(State.CFG.VectorPreHeader->getTerminator()); 1497 Constant *Zero = Builder.getInt32(0); 1498 StartV = Builder.CreateInsertElement(Iden, StartV, Zero); 1499 } 1500 } 1501 1502 for (unsigned Part = 0; Part < LastPartForNewPhi; ++Part) { 1503 Value *EntryPart = State.get(this, Part); 1504 // Make sure to add the reduction start value only to the 1505 // first unroll part. 1506 Value *StartVal = (Part == 0) ? StartV : Iden; 1507 cast<PHINode>(EntryPart)->addIncoming(StartVal, State.CFG.VectorPreHeader); 1508 } 1509 } 1510 1511 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1512 void VPReductionPHIRecipe::print(raw_ostream &O, const Twine &Indent, 1513 VPSlotTracker &SlotTracker) const { 1514 O << Indent << "WIDEN-REDUCTION-PHI "; 1515 1516 printAsOperand(O, SlotTracker); 1517 O << " = phi "; 1518 printOperands(O, SlotTracker); 1519 } 1520 #endif 1521 1522 template void DomTreeBuilder::Calculate<VPDominatorTree>(VPDominatorTree &DT); 1523 1524 void VPValue::replaceAllUsesWith(VPValue *New) { 1525 for (unsigned J = 0; J < getNumUsers();) { 1526 VPUser *User = Users[J]; 1527 unsigned NumUsers = getNumUsers(); 1528 for (unsigned I = 0, E = User->getNumOperands(); I < E; ++I) 1529 if (User->getOperand(I) == this) 1530 User->setOperand(I, New); 1531 // If a user got removed after updating the current user, the next user to 1532 // update will be moved to the current position, so we only need to 1533 // increment the index if the number of users did not change. 1534 if (NumUsers == getNumUsers()) 1535 J++; 1536 } 1537 } 1538 1539 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1540 void VPValue::printAsOperand(raw_ostream &OS, VPSlotTracker &Tracker) const { 1541 if (const Value *UV = getUnderlyingValue()) { 1542 OS << "ir<"; 1543 UV->printAsOperand(OS, false); 1544 OS << ">"; 1545 return; 1546 } 1547 1548 unsigned Slot = Tracker.getSlot(this); 1549 if (Slot == unsigned(-1)) 1550 OS << "<badref>"; 1551 else 1552 OS << "vp<%" << Tracker.getSlot(this) << ">"; 1553 } 1554 1555 void VPUser::printOperands(raw_ostream &O, VPSlotTracker &SlotTracker) const { 1556 interleaveComma(operands(), O, [&O, &SlotTracker](VPValue *Op) { 1557 Op->printAsOperand(O, SlotTracker); 1558 }); 1559 } 1560 #endif 1561 1562 void VPInterleavedAccessInfo::visitRegion(VPRegionBlock *Region, 1563 Old2NewTy &Old2New, 1564 InterleavedAccessInfo &IAI) { 1565 ReversePostOrderTraversal<VPBlockBase *> RPOT(Region->getEntry()); 1566 for (VPBlockBase *Base : RPOT) { 1567 visitBlock(Base, Old2New, IAI); 1568 } 1569 } 1570 1571 void VPInterleavedAccessInfo::visitBlock(VPBlockBase *Block, Old2NewTy &Old2New, 1572 InterleavedAccessInfo &IAI) { 1573 if (VPBasicBlock *VPBB = dyn_cast<VPBasicBlock>(Block)) { 1574 for (VPRecipeBase &VPI : *VPBB) { 1575 if (isa<VPHeaderPHIRecipe>(&VPI)) 1576 continue; 1577 assert(isa<VPInstruction>(&VPI) && "Can only handle VPInstructions"); 1578 auto *VPInst = cast<VPInstruction>(&VPI); 1579 auto *Inst = cast<Instruction>(VPInst->getUnderlyingValue()); 1580 auto *IG = IAI.getInterleaveGroup(Inst); 1581 if (!IG) 1582 continue; 1583 1584 auto NewIGIter = Old2New.find(IG); 1585 if (NewIGIter == Old2New.end()) 1586 Old2New[IG] = new InterleaveGroup<VPInstruction>( 1587 IG->getFactor(), IG->isReverse(), IG->getAlign()); 1588 1589 if (Inst == IG->getInsertPos()) 1590 Old2New[IG]->setInsertPos(VPInst); 1591 1592 InterleaveGroupMap[VPInst] = Old2New[IG]; 1593 InterleaveGroupMap[VPInst]->insertMember( 1594 VPInst, IG->getIndex(Inst), 1595 Align(IG->isReverse() ? (-1) * int(IG->getFactor()) 1596 : IG->getFactor())); 1597 } 1598 } else if (VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block)) 1599 visitRegion(Region, Old2New, IAI); 1600 else 1601 llvm_unreachable("Unsupported kind of VPBlock."); 1602 } 1603 1604 VPInterleavedAccessInfo::VPInterleavedAccessInfo(VPlan &Plan, 1605 InterleavedAccessInfo &IAI) { 1606 Old2NewTy Old2New; 1607 visitRegion(cast<VPRegionBlock>(Plan.getEntry()), Old2New, IAI); 1608 } 1609 1610 void VPSlotTracker::assignSlot(const VPValue *V) { 1611 assert(Slots.find(V) == Slots.end() && "VPValue already has a slot!"); 1612 Slots[V] = NextSlot++; 1613 } 1614 1615 void VPSlotTracker::assignSlots(const VPlan &Plan) { 1616 1617 for (const VPValue *V : Plan.VPExternalDefs) 1618 assignSlot(V); 1619 1620 assignSlot(&Plan.VectorTripCount); 1621 if (Plan.BackedgeTakenCount) 1622 assignSlot(Plan.BackedgeTakenCount); 1623 1624 ReversePostOrderTraversal< 1625 VPBlockRecursiveTraversalWrapper<const VPBlockBase *>> 1626 RPOT(VPBlockRecursiveTraversalWrapper<const VPBlockBase *>( 1627 Plan.getEntry())); 1628 for (const VPBasicBlock *VPBB : 1629 VPBlockUtils::blocksOnly<const VPBasicBlock>(RPOT)) 1630 for (const VPRecipeBase &Recipe : *VPBB) 1631 for (VPValue *Def : Recipe.definedValues()) 1632 assignSlot(Def); 1633 } 1634