1 //===- VPlan.cpp - Vectorizer Plan ----------------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 /// 9 /// \file 10 /// This is the LLVM vectorization plan. It represents a candidate for 11 /// vectorization, allowing to plan and optimize how to vectorize a given loop 12 /// before generating LLVM-IR. 13 /// The vectorizer uses vectorization plans to estimate the costs of potential 14 /// candidates and if profitable to execute the desired plan, generating vector 15 /// LLVM-IR code. 16 /// 17 //===----------------------------------------------------------------------===// 18 19 #include "VPlan.h" 20 #include "VPlanCFG.h" 21 #include "VPlanDominatorTree.h" 22 #include "llvm/ADT/DepthFirstIterator.h" 23 #include "llvm/ADT/PostOrderIterator.h" 24 #include "llvm/ADT/STLExtras.h" 25 #include "llvm/ADT/SmallVector.h" 26 #include "llvm/ADT/Twine.h" 27 #include "llvm/Analysis/LoopInfo.h" 28 #include "llvm/IR/BasicBlock.h" 29 #include "llvm/IR/CFG.h" 30 #include "llvm/IR/IRBuilder.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/GenericDomTreeConstruction.h" 39 #include "llvm/Support/GraphWriter.h" 40 #include "llvm/Support/raw_ostream.h" 41 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 42 #include "llvm/Transforms/Utils/LoopVersioning.h" 43 #include "llvm/Transforms/Utils/ScalarEvolutionExpander.h" 44 #include <cassert> 45 #include <string> 46 #include <vector> 47 48 using namespace llvm; 49 50 namespace llvm { 51 extern cl::opt<bool> EnableVPlanNativePath; 52 } 53 54 #define DEBUG_TYPE "vplan" 55 56 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 57 raw_ostream &llvm::operator<<(raw_ostream &OS, const VPValue &V) { 58 const VPInstruction *Instr = dyn_cast<VPInstruction>(&V); 59 VPSlotTracker SlotTracker( 60 (Instr && Instr->getParent()) ? Instr->getParent()->getPlan() : nullptr); 61 V.print(OS, SlotTracker); 62 return OS; 63 } 64 #endif 65 66 Value *VPLane::getAsRuntimeExpr(IRBuilderBase &Builder, 67 const ElementCount &VF) const { 68 switch (LaneKind) { 69 case VPLane::Kind::ScalableLast: 70 // Lane = RuntimeVF - VF.getKnownMinValue() + Lane 71 return Builder.CreateSub(getRuntimeVF(Builder, Builder.getInt32Ty(), VF), 72 Builder.getInt32(VF.getKnownMinValue() - Lane)); 73 case VPLane::Kind::First: 74 return Builder.getInt32(Lane); 75 } 76 llvm_unreachable("Unknown lane kind"); 77 } 78 79 VPValue::VPValue(const unsigned char SC, Value *UV, VPDef *Def) 80 : SubclassID(SC), UnderlyingVal(UV), Def(Def) { 81 if (Def) 82 Def->addDefinedValue(this); 83 } 84 85 VPValue::~VPValue() { 86 assert(Users.empty() && "trying to delete a VPValue with remaining users"); 87 if (Def) 88 Def->removeDefinedValue(this); 89 } 90 91 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 92 void VPValue::print(raw_ostream &OS, VPSlotTracker &SlotTracker) const { 93 if (const VPRecipeBase *R = dyn_cast_or_null<VPRecipeBase>(Def)) 94 R->print(OS, "", SlotTracker); 95 else 96 printAsOperand(OS, SlotTracker); 97 } 98 99 void VPValue::dump() const { 100 const VPRecipeBase *Instr = dyn_cast_or_null<VPRecipeBase>(this->Def); 101 VPSlotTracker SlotTracker( 102 (Instr && Instr->getParent()) ? Instr->getParent()->getPlan() : nullptr); 103 print(dbgs(), SlotTracker); 104 dbgs() << "\n"; 105 } 106 107 void VPDef::dump() const { 108 const VPRecipeBase *Instr = dyn_cast_or_null<VPRecipeBase>(this); 109 VPSlotTracker SlotTracker( 110 (Instr && Instr->getParent()) ? Instr->getParent()->getPlan() : nullptr); 111 print(dbgs(), "", SlotTracker); 112 dbgs() << "\n"; 113 } 114 #endif 115 116 VPRecipeBase *VPValue::getDefiningRecipe() { 117 return cast_or_null<VPRecipeBase>(Def); 118 } 119 120 const VPRecipeBase *VPValue::getDefiningRecipe() const { 121 return cast_or_null<VPRecipeBase>(Def); 122 } 123 124 // Get the top-most entry block of \p Start. This is the entry block of the 125 // containing VPlan. This function is templated to support both const and non-const blocks 126 template <typename T> static T *getPlanEntry(T *Start) { 127 T *Next = Start; 128 T *Current = Start; 129 while ((Next = Next->getParent())) 130 Current = Next; 131 132 SmallSetVector<T *, 8> WorkList; 133 WorkList.insert(Current); 134 135 for (unsigned i = 0; i < WorkList.size(); i++) { 136 T *Current = WorkList[i]; 137 if (Current->getNumPredecessors() == 0) 138 return Current; 139 auto &Predecessors = Current->getPredecessors(); 140 WorkList.insert(Predecessors.begin(), Predecessors.end()); 141 } 142 143 llvm_unreachable("VPlan without any entry node without predecessors"); 144 } 145 146 VPlan *VPBlockBase::getPlan() { return getPlanEntry(this)->Plan; } 147 148 const VPlan *VPBlockBase::getPlan() const { return getPlanEntry(this)->Plan; } 149 150 /// \return the VPBasicBlock that is the entry of Block, possibly indirectly. 151 const VPBasicBlock *VPBlockBase::getEntryBasicBlock() const { 152 const VPBlockBase *Block = this; 153 while (const VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block)) 154 Block = Region->getEntry(); 155 return cast<VPBasicBlock>(Block); 156 } 157 158 VPBasicBlock *VPBlockBase::getEntryBasicBlock() { 159 VPBlockBase *Block = this; 160 while (VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block)) 161 Block = Region->getEntry(); 162 return cast<VPBasicBlock>(Block); 163 } 164 165 void VPBlockBase::setPlan(VPlan *ParentPlan) { 166 assert(ParentPlan->getEntry() == this && 167 "Can only set plan on its entry block."); 168 Plan = ParentPlan; 169 } 170 171 /// \return the VPBasicBlock that is the exit of Block, possibly indirectly. 172 const VPBasicBlock *VPBlockBase::getExitingBasicBlock() const { 173 const VPBlockBase *Block = this; 174 while (const VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block)) 175 Block = Region->getExiting(); 176 return cast<VPBasicBlock>(Block); 177 } 178 179 VPBasicBlock *VPBlockBase::getExitingBasicBlock() { 180 VPBlockBase *Block = this; 181 while (VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block)) 182 Block = Region->getExiting(); 183 return cast<VPBasicBlock>(Block); 184 } 185 186 VPBlockBase *VPBlockBase::getEnclosingBlockWithSuccessors() { 187 if (!Successors.empty() || !Parent) 188 return this; 189 assert(Parent->getExiting() == this && 190 "Block w/o successors not the exiting block of its parent."); 191 return Parent->getEnclosingBlockWithSuccessors(); 192 } 193 194 VPBlockBase *VPBlockBase::getEnclosingBlockWithPredecessors() { 195 if (!Predecessors.empty() || !Parent) 196 return this; 197 assert(Parent->getEntry() == this && 198 "Block w/o predecessors not the entry of its parent."); 199 return Parent->getEnclosingBlockWithPredecessors(); 200 } 201 202 void VPBlockBase::deleteCFG(VPBlockBase *Entry) { 203 for (VPBlockBase *Block : to_vector(vp_depth_first_shallow(Entry))) 204 delete Block; 205 } 206 207 VPBasicBlock::iterator VPBasicBlock::getFirstNonPhi() { 208 iterator It = begin(); 209 while (It != end() && It->isPhi()) 210 It++; 211 return It; 212 } 213 214 Value *VPTransformState::get(VPValue *Def, const VPIteration &Instance) { 215 if (!Def->hasDefiningRecipe()) 216 return Def->getLiveInIRValue(); 217 218 if (hasScalarValue(Def, Instance)) { 219 return Data 220 .PerPartScalars[Def][Instance.Part][Instance.Lane.mapToCacheIndex(VF)]; 221 } 222 223 assert(hasVectorValue(Def, Instance.Part)); 224 auto *VecPart = Data.PerPartOutput[Def][Instance.Part]; 225 if (!VecPart->getType()->isVectorTy()) { 226 assert(Instance.Lane.isFirstLane() && "cannot get lane > 0 for scalar"); 227 return VecPart; 228 } 229 // TODO: Cache created scalar values. 230 Value *Lane = Instance.Lane.getAsRuntimeExpr(Builder, VF); 231 auto *Extract = Builder.CreateExtractElement(VecPart, Lane); 232 // set(Def, Extract, Instance); 233 return Extract; 234 } 235 BasicBlock *VPTransformState::CFGState::getPreheaderBBFor(VPRecipeBase *R) { 236 VPRegionBlock *LoopRegion = R->getParent()->getEnclosingLoopRegion(); 237 return VPBB2IRBB[LoopRegion->getPreheaderVPBB()]; 238 } 239 240 void VPTransformState::addNewMetadata(Instruction *To, 241 const Instruction *Orig) { 242 // If the loop was versioned with memchecks, add the corresponding no-alias 243 // metadata. 244 if (LVer && (isa<LoadInst>(Orig) || isa<StoreInst>(Orig))) 245 LVer->annotateInstWithNoAlias(To, Orig); 246 } 247 248 void VPTransformState::addMetadata(Instruction *To, Instruction *From) { 249 propagateMetadata(To, From); 250 addNewMetadata(To, From); 251 } 252 253 void VPTransformState::addMetadata(ArrayRef<Value *> To, Instruction *From) { 254 for (Value *V : To) { 255 if (Instruction *I = dyn_cast<Instruction>(V)) 256 addMetadata(I, From); 257 } 258 } 259 260 void VPTransformState::setDebugLocFromInst(const Value *V) { 261 const Instruction *Inst = dyn_cast<Instruction>(V); 262 if (!Inst) { 263 Builder.SetCurrentDebugLocation(DebugLoc()); 264 return; 265 } 266 267 const DILocation *DIL = Inst->getDebugLoc(); 268 // When a FSDiscriminator is enabled, we don't need to add the multiply 269 // factors to the discriminators. 270 if (DIL && Inst->getFunction()->shouldEmitDebugInfoForProfiling() && 271 !isa<DbgInfoIntrinsic>(Inst) && !EnableFSDiscriminator) { 272 // FIXME: For scalable vectors, assume vscale=1. 273 auto NewDIL = 274 DIL->cloneByMultiplyingDuplicationFactor(UF * VF.getKnownMinValue()); 275 if (NewDIL) 276 Builder.SetCurrentDebugLocation(*NewDIL); 277 else 278 LLVM_DEBUG(dbgs() << "Failed to create new discriminator: " 279 << DIL->getFilename() << " Line: " << DIL->getLine()); 280 } else 281 Builder.SetCurrentDebugLocation(DIL); 282 } 283 284 BasicBlock * 285 VPBasicBlock::createEmptyBasicBlock(VPTransformState::CFGState &CFG) { 286 // BB stands for IR BasicBlocks. VPBB stands for VPlan VPBasicBlocks. 287 // Pred stands for Predessor. Prev stands for Previous - last visited/created. 288 BasicBlock *PrevBB = CFG.PrevBB; 289 BasicBlock *NewBB = BasicBlock::Create(PrevBB->getContext(), getName(), 290 PrevBB->getParent(), CFG.ExitBB); 291 LLVM_DEBUG(dbgs() << "LV: created " << NewBB->getName() << '\n'); 292 293 // Hook up the new basic block to its predecessors. 294 for (VPBlockBase *PredVPBlock : getHierarchicalPredecessors()) { 295 VPBasicBlock *PredVPBB = PredVPBlock->getExitingBasicBlock(); 296 auto &PredVPSuccessors = PredVPBB->getHierarchicalSuccessors(); 297 BasicBlock *PredBB = CFG.VPBB2IRBB[PredVPBB]; 298 299 assert(PredBB && "Predecessor basic-block not found building successor."); 300 auto *PredBBTerminator = PredBB->getTerminator(); 301 LLVM_DEBUG(dbgs() << "LV: draw edge from" << PredBB->getName() << '\n'); 302 303 auto *TermBr = dyn_cast<BranchInst>(PredBBTerminator); 304 if (isa<UnreachableInst>(PredBBTerminator)) { 305 assert(PredVPSuccessors.size() == 1 && 306 "Predecessor ending w/o branch must have single successor."); 307 DebugLoc DL = PredBBTerminator->getDebugLoc(); 308 PredBBTerminator->eraseFromParent(); 309 auto *Br = BranchInst::Create(NewBB, PredBB); 310 Br->setDebugLoc(DL); 311 } else if (TermBr && !TermBr->isConditional()) { 312 TermBr->setSuccessor(0, NewBB); 313 } else { 314 // Set each forward successor here when it is created, excluding 315 // backedges. A backward successor is set when the branch is created. 316 unsigned idx = PredVPSuccessors.front() == this ? 0 : 1; 317 assert(!TermBr->getSuccessor(idx) && 318 "Trying to reset an existing successor block."); 319 TermBr->setSuccessor(idx, NewBB); 320 } 321 } 322 return NewBB; 323 } 324 325 void VPBasicBlock::execute(VPTransformState *State) { 326 bool Replica = State->Instance && !State->Instance->isFirstIteration(); 327 VPBasicBlock *PrevVPBB = State->CFG.PrevVPBB; 328 VPBlockBase *SingleHPred = nullptr; 329 BasicBlock *NewBB = State->CFG.PrevBB; // Reuse it if possible. 330 331 auto IsLoopRegion = [](VPBlockBase *BB) { 332 auto *R = dyn_cast<VPRegionBlock>(BB); 333 return R && !R->isReplicator(); 334 }; 335 336 // 1. Create an IR basic block, or reuse the last one or ExitBB if possible. 337 if (getPlan()->getVectorLoopRegion()->getSingleSuccessor() == this) { 338 // ExitBB can be re-used for the exit block of the Plan. 339 NewBB = State->CFG.ExitBB; 340 State->CFG.PrevBB = NewBB; 341 342 // Update the branch instruction in the predecessor to branch to ExitBB. 343 VPBlockBase *PredVPB = getSingleHierarchicalPredecessor(); 344 VPBasicBlock *ExitingVPBB = PredVPB->getExitingBasicBlock(); 345 assert(PredVPB->getSingleSuccessor() == this && 346 "predecessor must have the current block as only successor"); 347 BasicBlock *ExitingBB = State->CFG.VPBB2IRBB[ExitingVPBB]; 348 // The Exit block of a loop is always set to be successor 0 of the Exiting 349 // block. 350 cast<BranchInst>(ExitingBB->getTerminator())->setSuccessor(0, NewBB); 351 } else if (PrevVPBB && /* A */ 352 !((SingleHPred = getSingleHierarchicalPredecessor()) && 353 SingleHPred->getExitingBasicBlock() == PrevVPBB && 354 PrevVPBB->getSingleHierarchicalSuccessor() && 355 (SingleHPred->getParent() == getEnclosingLoopRegion() && 356 !IsLoopRegion(SingleHPred))) && /* B */ 357 !(Replica && getPredecessors().empty())) { /* C */ 358 // The last IR basic block is reused, as an optimization, in three cases: 359 // A. the first VPBB reuses the loop pre-header BB - when PrevVPBB is null; 360 // B. when the current VPBB has a single (hierarchical) predecessor which 361 // is PrevVPBB and the latter has a single (hierarchical) successor which 362 // both are in the same non-replicator region; and 363 // C. when the current VPBB is an entry of a region replica - where PrevVPBB 364 // is the exiting VPBB of this region from a previous instance, or the 365 // predecessor of this region. 366 367 NewBB = createEmptyBasicBlock(State->CFG); 368 State->Builder.SetInsertPoint(NewBB); 369 // Temporarily terminate with unreachable until CFG is rewired. 370 UnreachableInst *Terminator = State->Builder.CreateUnreachable(); 371 // Register NewBB in its loop. In innermost loops its the same for all 372 // BB's. 373 if (State->CurrentVectorLoop) 374 State->CurrentVectorLoop->addBasicBlockToLoop(NewBB, *State->LI); 375 State->Builder.SetInsertPoint(Terminator); 376 State->CFG.PrevBB = NewBB; 377 } 378 379 // 2. Fill the IR basic block with IR instructions. 380 LLVM_DEBUG(dbgs() << "LV: vectorizing VPBB:" << getName() 381 << " in BB:" << NewBB->getName() << '\n'); 382 383 State->CFG.VPBB2IRBB[this] = NewBB; 384 State->CFG.PrevVPBB = this; 385 386 for (VPRecipeBase &Recipe : Recipes) 387 Recipe.execute(*State); 388 389 LLVM_DEBUG(dbgs() << "LV: filled BB:" << *NewBB); 390 } 391 392 void VPBasicBlock::dropAllReferences(VPValue *NewValue) { 393 for (VPRecipeBase &R : Recipes) { 394 for (auto *Def : R.definedValues()) 395 Def->replaceAllUsesWith(NewValue); 396 397 for (unsigned I = 0, E = R.getNumOperands(); I != E; I++) 398 R.setOperand(I, NewValue); 399 } 400 } 401 402 VPBasicBlock *VPBasicBlock::splitAt(iterator SplitAt) { 403 assert((SplitAt == end() || SplitAt->getParent() == this) && 404 "can only split at a position in the same block"); 405 406 SmallVector<VPBlockBase *, 2> Succs(successors()); 407 // First, disconnect the current block from its successors. 408 for (VPBlockBase *Succ : Succs) 409 VPBlockUtils::disconnectBlocks(this, Succ); 410 411 // Create new empty block after the block to split. 412 auto *SplitBlock = new VPBasicBlock(getName() + ".split"); 413 VPBlockUtils::insertBlockAfter(SplitBlock, this); 414 415 // Add successors for block to split to new block. 416 for (VPBlockBase *Succ : Succs) 417 VPBlockUtils::connectBlocks(SplitBlock, Succ); 418 419 // Finally, move the recipes starting at SplitAt to new block. 420 for (VPRecipeBase &ToMove : 421 make_early_inc_range(make_range(SplitAt, this->end()))) 422 ToMove.moveBefore(*SplitBlock, SplitBlock->end()); 423 424 return SplitBlock; 425 } 426 427 VPRegionBlock *VPBasicBlock::getEnclosingLoopRegion() { 428 VPRegionBlock *P = getParent(); 429 if (P && P->isReplicator()) { 430 P = P->getParent(); 431 assert(!cast<VPRegionBlock>(P)->isReplicator() && 432 "unexpected nested replicate regions"); 433 } 434 return P; 435 } 436 437 static bool hasConditionalTerminator(const VPBasicBlock *VPBB) { 438 if (VPBB->empty()) { 439 assert( 440 VPBB->getNumSuccessors() < 2 && 441 "block with multiple successors doesn't have a recipe as terminator"); 442 return false; 443 } 444 445 const VPRecipeBase *R = &VPBB->back(); 446 auto *VPI = dyn_cast<VPInstruction>(R); 447 bool IsCondBranch = 448 isa<VPBranchOnMaskRecipe>(R) || 449 (VPI && (VPI->getOpcode() == VPInstruction::BranchOnCond || 450 VPI->getOpcode() == VPInstruction::BranchOnCount)); 451 (void)IsCondBranch; 452 453 if (VPBB->getNumSuccessors() >= 2 || VPBB->isExiting()) { 454 assert(IsCondBranch && "block with multiple successors not terminated by " 455 "conditional branch recipe"); 456 457 return true; 458 } 459 460 assert( 461 !IsCondBranch && 462 "block with 0 or 1 successors terminated by conditional branch recipe"); 463 return false; 464 } 465 466 VPRecipeBase *VPBasicBlock::getTerminator() { 467 if (hasConditionalTerminator(this)) 468 return &back(); 469 return nullptr; 470 } 471 472 const VPRecipeBase *VPBasicBlock::getTerminator() const { 473 if (hasConditionalTerminator(this)) 474 return &back(); 475 return nullptr; 476 } 477 478 bool VPBasicBlock::isExiting() const { 479 return getParent()->getExitingBasicBlock() == this; 480 } 481 482 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 483 void VPBlockBase::printSuccessors(raw_ostream &O, const Twine &Indent) const { 484 if (getSuccessors().empty()) { 485 O << Indent << "No successors\n"; 486 } else { 487 O << Indent << "Successor(s): "; 488 ListSeparator LS; 489 for (auto *Succ : getSuccessors()) 490 O << LS << Succ->getName(); 491 O << '\n'; 492 } 493 } 494 495 void VPBasicBlock::print(raw_ostream &O, const Twine &Indent, 496 VPSlotTracker &SlotTracker) const { 497 O << Indent << getName() << ":\n"; 498 499 auto RecipeIndent = Indent + " "; 500 for (const VPRecipeBase &Recipe : *this) { 501 Recipe.print(O, RecipeIndent, SlotTracker); 502 O << '\n'; 503 } 504 505 printSuccessors(O, Indent); 506 } 507 #endif 508 509 void VPRegionBlock::dropAllReferences(VPValue *NewValue) { 510 for (VPBlockBase *Block : vp_depth_first_shallow(Entry)) 511 // Drop all references in VPBasicBlocks and replace all uses with 512 // DummyValue. 513 Block->dropAllReferences(NewValue); 514 } 515 516 void VPRegionBlock::execute(VPTransformState *State) { 517 ReversePostOrderTraversal<VPBlockShallowTraversalWrapper<VPBlockBase *>> 518 RPOT(Entry); 519 520 if (!isReplicator()) { 521 // Create and register the new vector loop. 522 Loop *PrevLoop = State->CurrentVectorLoop; 523 State->CurrentVectorLoop = State->LI->AllocateLoop(); 524 BasicBlock *VectorPH = State->CFG.VPBB2IRBB[getPreheaderVPBB()]; 525 Loop *ParentLoop = State->LI->getLoopFor(VectorPH); 526 527 // Insert the new loop into the loop nest and register the new basic blocks 528 // before calling any utilities such as SCEV that require valid LoopInfo. 529 if (ParentLoop) 530 ParentLoop->addChildLoop(State->CurrentVectorLoop); 531 else 532 State->LI->addTopLevelLoop(State->CurrentVectorLoop); 533 534 // Visit the VPBlocks connected to "this", starting from it. 535 for (VPBlockBase *Block : RPOT) { 536 LLVM_DEBUG(dbgs() << "LV: VPBlock in RPO " << Block->getName() << '\n'); 537 Block->execute(State); 538 } 539 540 State->CurrentVectorLoop = PrevLoop; 541 return; 542 } 543 544 assert(!State->Instance && "Replicating a Region with non-null instance."); 545 546 // Enter replicating mode. 547 State->Instance = VPIteration(0, 0); 548 549 for (unsigned Part = 0, UF = State->UF; Part < UF; ++Part) { 550 State->Instance->Part = Part; 551 assert(!State->VF.isScalable() && "VF is assumed to be non scalable."); 552 for (unsigned Lane = 0, VF = State->VF.getKnownMinValue(); Lane < VF; 553 ++Lane) { 554 State->Instance->Lane = VPLane(Lane, VPLane::Kind::First); 555 // Visit the VPBlocks connected to \p this, starting from it. 556 for (VPBlockBase *Block : RPOT) { 557 LLVM_DEBUG(dbgs() << "LV: VPBlock in RPO " << Block->getName() << '\n'); 558 Block->execute(State); 559 } 560 } 561 } 562 563 // Exit replicating mode. 564 State->Instance.reset(); 565 } 566 567 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 568 void VPRegionBlock::print(raw_ostream &O, const Twine &Indent, 569 VPSlotTracker &SlotTracker) const { 570 O << Indent << (isReplicator() ? "<xVFxUF> " : "<x1> ") << getName() << ": {"; 571 auto NewIndent = Indent + " "; 572 for (auto *BlockBase : vp_depth_first_shallow(Entry)) { 573 O << '\n'; 574 BlockBase->print(O, NewIndent, SlotTracker); 575 } 576 O << Indent << "}\n"; 577 578 printSuccessors(O, Indent); 579 } 580 #endif 581 582 VPlan::~VPlan() { 583 clearLiveOuts(); 584 585 if (Entry) { 586 VPValue DummyValue; 587 for (VPBlockBase *Block : vp_depth_first_shallow(Entry)) 588 Block->dropAllReferences(&DummyValue); 589 590 VPBlockBase::deleteCFG(Entry); 591 } 592 for (VPValue *VPV : VPValuesToFree) 593 delete VPV; 594 if (TripCount) 595 delete TripCount; 596 if (BackedgeTakenCount) 597 delete BackedgeTakenCount; 598 for (auto &P : VPExternalDefs) 599 delete P.second; 600 } 601 602 VPActiveLaneMaskPHIRecipe *VPlan::getActiveLaneMaskPhi() { 603 VPBasicBlock *Header = getVectorLoopRegion()->getEntryBasicBlock(); 604 for (VPRecipeBase &R : Header->phis()) { 605 if (isa<VPActiveLaneMaskPHIRecipe>(&R)) 606 return cast<VPActiveLaneMaskPHIRecipe>(&R); 607 } 608 return nullptr; 609 } 610 611 void VPlan::prepareToExecute(Value *TripCountV, Value *VectorTripCountV, 612 Value *CanonicalIVStartValue, 613 VPTransformState &State, 614 bool IsEpilogueVectorization) { 615 616 // Check if the trip count is needed, and if so build it. 617 if (TripCount && TripCount->getNumUsers()) { 618 for (unsigned Part = 0, UF = State.UF; Part < UF; ++Part) 619 State.set(TripCount, TripCountV, Part); 620 } 621 622 // Check if the backedge taken count is needed, and if so build it. 623 if (BackedgeTakenCount && BackedgeTakenCount->getNumUsers()) { 624 IRBuilder<> Builder(State.CFG.PrevBB->getTerminator()); 625 auto *TCMO = Builder.CreateSub(TripCountV, 626 ConstantInt::get(TripCountV->getType(), 1), 627 "trip.count.minus.1"); 628 auto VF = State.VF; 629 Value *VTCMO = 630 VF.isScalar() ? TCMO : Builder.CreateVectorSplat(VF, TCMO, "broadcast"); 631 for (unsigned Part = 0, UF = State.UF; Part < UF; ++Part) 632 State.set(BackedgeTakenCount, VTCMO, Part); 633 } 634 635 for (unsigned Part = 0, UF = State.UF; Part < UF; ++Part) 636 State.set(&VectorTripCount, VectorTripCountV, Part); 637 638 // When vectorizing the epilogue loop, the canonical induction start value 639 // needs to be changed from zero to the value after the main vector loop. 640 // FIXME: Improve modeling for canonical IV start values in the epilogue loop. 641 if (CanonicalIVStartValue) { 642 VPValue *VPV = getOrAddExternalDef(CanonicalIVStartValue); 643 auto *IV = getCanonicalIV(); 644 assert(all_of(IV->users(), 645 [](const VPUser *U) { 646 if (isa<VPScalarIVStepsRecipe>(U) || 647 isa<VPDerivedIVRecipe>(U)) 648 return true; 649 auto *VPI = cast<VPInstruction>(U); 650 return VPI->getOpcode() == 651 VPInstruction::CanonicalIVIncrement || 652 VPI->getOpcode() == 653 VPInstruction::CanonicalIVIncrementNUW; 654 }) && 655 "the canonical IV should only be used by its increments or " 656 "ScalarIVSteps when " 657 "resetting the start value"); 658 IV->setOperand(0, VPV); 659 } 660 } 661 662 /// Generate the code inside the preheader and body of the vectorized loop. 663 /// Assumes a single pre-header basic-block was created for this. Introduce 664 /// additional basic-blocks as needed, and fill them all. 665 void VPlan::execute(VPTransformState *State) { 666 // Set the reverse mapping from VPValues to Values for code generation. 667 for (auto &Entry : Value2VPValue) 668 State->VPValue2Value[Entry.second] = Entry.first; 669 670 // Initialize CFG state. 671 State->CFG.PrevVPBB = nullptr; 672 State->CFG.ExitBB = State->CFG.PrevBB->getSingleSuccessor(); 673 BasicBlock *VectorPreHeader = State->CFG.PrevBB; 674 State->Builder.SetInsertPoint(VectorPreHeader->getTerminator()); 675 676 // Generate code in the loop pre-header and body. 677 for (VPBlockBase *Block : vp_depth_first_shallow(Entry)) 678 Block->execute(State); 679 680 VPBasicBlock *LatchVPBB = getVectorLoopRegion()->getExitingBasicBlock(); 681 BasicBlock *VectorLatchBB = State->CFG.VPBB2IRBB[LatchVPBB]; 682 683 // Fix the latch value of canonical, reduction and first-order recurrences 684 // phis in the vector loop. 685 VPBasicBlock *Header = getVectorLoopRegion()->getEntryBasicBlock(); 686 for (VPRecipeBase &R : Header->phis()) { 687 // Skip phi-like recipes that generate their backedege values themselves. 688 if (isa<VPWidenPHIRecipe>(&R)) 689 continue; 690 691 if (isa<VPWidenPointerInductionRecipe>(&R) || 692 isa<VPWidenIntOrFpInductionRecipe>(&R)) { 693 PHINode *Phi = nullptr; 694 if (isa<VPWidenIntOrFpInductionRecipe>(&R)) { 695 Phi = cast<PHINode>(State->get(R.getVPSingleValue(), 0)); 696 } else { 697 auto *WidenPhi = cast<VPWidenPointerInductionRecipe>(&R); 698 // TODO: Split off the case that all users of a pointer phi are scalar 699 // from the VPWidenPointerInductionRecipe. 700 if (WidenPhi->onlyScalarsGenerated(State->VF)) 701 continue; 702 703 auto *GEP = cast<GetElementPtrInst>(State->get(WidenPhi, 0)); 704 Phi = cast<PHINode>(GEP->getPointerOperand()); 705 } 706 707 Phi->setIncomingBlock(1, VectorLatchBB); 708 709 // Move the last step to the end of the latch block. This ensures 710 // consistent placement of all induction updates. 711 Instruction *Inc = cast<Instruction>(Phi->getIncomingValue(1)); 712 Inc->moveBefore(VectorLatchBB->getTerminator()->getPrevNode()); 713 continue; 714 } 715 716 auto *PhiR = cast<VPHeaderPHIRecipe>(&R); 717 // For canonical IV, first-order recurrences and in-order reduction phis, 718 // only a single part is generated, which provides the last part from the 719 // previous iteration. For non-ordered reductions all UF parts are 720 // generated. 721 bool SinglePartNeeded = isa<VPCanonicalIVPHIRecipe>(PhiR) || 722 isa<VPFirstOrderRecurrencePHIRecipe>(PhiR) || 723 (isa<VPReductionPHIRecipe>(PhiR) && 724 cast<VPReductionPHIRecipe>(PhiR)->isOrdered()); 725 unsigned LastPartForNewPhi = SinglePartNeeded ? 1 : State->UF; 726 727 for (unsigned Part = 0; Part < LastPartForNewPhi; ++Part) { 728 Value *Phi = State->get(PhiR, Part); 729 Value *Val = State->get(PhiR->getBackedgeValue(), 730 SinglePartNeeded ? State->UF - 1 : Part); 731 cast<PHINode>(Phi)->addIncoming(Val, VectorLatchBB); 732 } 733 } 734 735 // We do not attempt to preserve DT for outer loop vectorization currently. 736 if (!EnableVPlanNativePath) { 737 BasicBlock *VectorHeaderBB = State->CFG.VPBB2IRBB[Header]; 738 State->DT->addNewBlock(VectorHeaderBB, VectorPreHeader); 739 updateDominatorTree(State->DT, VectorHeaderBB, VectorLatchBB, 740 State->CFG.ExitBB); 741 } 742 } 743 744 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 745 LLVM_DUMP_METHOD 746 void VPlan::print(raw_ostream &O) const { 747 VPSlotTracker SlotTracker(this); 748 749 O << "VPlan '" << getName() << "' {"; 750 751 if (VectorTripCount.getNumUsers() > 0) { 752 O << "\nLive-in "; 753 VectorTripCount.printAsOperand(O, SlotTracker); 754 O << " = vector-trip-count\n"; 755 } 756 757 if (BackedgeTakenCount && BackedgeTakenCount->getNumUsers()) { 758 O << "\nLive-in "; 759 BackedgeTakenCount->printAsOperand(O, SlotTracker); 760 O << " = backedge-taken count\n"; 761 } 762 763 for (const VPBlockBase *Block : vp_depth_first_shallow(getEntry())) { 764 O << '\n'; 765 Block->print(O, "", SlotTracker); 766 } 767 768 if (!LiveOuts.empty()) 769 O << "\n"; 770 for (const auto &KV : LiveOuts) { 771 O << "Live-out "; 772 KV.second->getPhi()->printAsOperand(O); 773 O << " = "; 774 KV.second->getOperand(0)->printAsOperand(O, SlotTracker); 775 O << "\n"; 776 } 777 778 O << "}\n"; 779 } 780 781 std::string VPlan::getName() const { 782 std::string Out; 783 raw_string_ostream RSO(Out); 784 RSO << Name << " for "; 785 if (!VFs.empty()) { 786 RSO << "VF={" << VFs[0]; 787 for (ElementCount VF : drop_begin(VFs)) 788 RSO << "," << VF; 789 RSO << "},"; 790 } 791 792 if (UFs.empty()) { 793 RSO << "UF>=1"; 794 } else { 795 RSO << "UF={" << UFs[0]; 796 for (unsigned UF : drop_begin(UFs)) 797 RSO << "," << UF; 798 RSO << "}"; 799 } 800 801 return Out; 802 } 803 804 LLVM_DUMP_METHOD 805 void VPlan::printDOT(raw_ostream &O) const { 806 VPlanPrinter Printer(O, *this); 807 Printer.dump(); 808 } 809 810 LLVM_DUMP_METHOD 811 void VPlan::dump() const { print(dbgs()); } 812 #endif 813 814 void VPlan::addLiveOut(PHINode *PN, VPValue *V) { 815 assert(LiveOuts.count(PN) == 0 && "an exit value for PN already exists"); 816 LiveOuts.insert({PN, new VPLiveOut(PN, V)}); 817 } 818 819 void VPlan::updateDominatorTree(DominatorTree *DT, BasicBlock *LoopHeaderBB, 820 BasicBlock *LoopLatchBB, 821 BasicBlock *LoopExitBB) { 822 // The vector body may be more than a single basic-block by this point. 823 // Update the dominator tree information inside the vector body by propagating 824 // it from header to latch, expecting only triangular control-flow, if any. 825 BasicBlock *PostDomSucc = nullptr; 826 for (auto *BB = LoopHeaderBB; BB != LoopLatchBB; BB = PostDomSucc) { 827 // Get the list of successors of this block. 828 std::vector<BasicBlock *> Succs(succ_begin(BB), succ_end(BB)); 829 assert(Succs.size() <= 2 && 830 "Basic block in vector loop has more than 2 successors."); 831 PostDomSucc = Succs[0]; 832 if (Succs.size() == 1) { 833 assert(PostDomSucc->getSinglePredecessor() && 834 "PostDom successor has more than one predecessor."); 835 DT->addNewBlock(PostDomSucc, BB); 836 continue; 837 } 838 BasicBlock *InterimSucc = Succs[1]; 839 if (PostDomSucc->getSingleSuccessor() == InterimSucc) { 840 PostDomSucc = Succs[1]; 841 InterimSucc = Succs[0]; 842 } 843 assert(InterimSucc->getSingleSuccessor() == PostDomSucc && 844 "One successor of a basic block does not lead to the other."); 845 assert(InterimSucc->getSinglePredecessor() && 846 "Interim successor has more than one predecessor."); 847 assert(PostDomSucc->hasNPredecessors(2) && 848 "PostDom successor has more than two predecessors."); 849 DT->addNewBlock(InterimSucc, BB); 850 DT->addNewBlock(PostDomSucc, BB); 851 } 852 // Latch block is a new dominator for the loop exit. 853 DT->changeImmediateDominator(LoopExitBB, LoopLatchBB); 854 assert(DT->verify(DominatorTree::VerificationLevel::Fast)); 855 } 856 857 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 858 859 Twine VPlanPrinter::getUID(const VPBlockBase *Block) { 860 return (isa<VPRegionBlock>(Block) ? "cluster_N" : "N") + 861 Twine(getOrCreateBID(Block)); 862 } 863 864 Twine VPlanPrinter::getOrCreateName(const VPBlockBase *Block) { 865 const std::string &Name = Block->getName(); 866 if (!Name.empty()) 867 return Name; 868 return "VPB" + Twine(getOrCreateBID(Block)); 869 } 870 871 void VPlanPrinter::dump() { 872 Depth = 1; 873 bumpIndent(0); 874 OS << "digraph VPlan {\n"; 875 OS << "graph [labelloc=t, fontsize=30; label=\"Vectorization Plan"; 876 if (!Plan.getName().empty()) 877 OS << "\\n" << DOT::EscapeString(Plan.getName()); 878 if (Plan.BackedgeTakenCount) { 879 OS << ", where:\\n"; 880 Plan.BackedgeTakenCount->print(OS, SlotTracker); 881 OS << " := BackedgeTakenCount"; 882 } 883 OS << "\"]\n"; 884 OS << "node [shape=rect, fontname=Courier, fontsize=30]\n"; 885 OS << "edge [fontname=Courier, fontsize=30]\n"; 886 OS << "compound=true\n"; 887 888 for (const VPBlockBase *Block : vp_depth_first_shallow(Plan.getEntry())) 889 dumpBlock(Block); 890 891 OS << "}\n"; 892 } 893 894 void VPlanPrinter::dumpBlock(const VPBlockBase *Block) { 895 if (const VPBasicBlock *BasicBlock = dyn_cast<VPBasicBlock>(Block)) 896 dumpBasicBlock(BasicBlock); 897 else if (const VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block)) 898 dumpRegion(Region); 899 else 900 llvm_unreachable("Unsupported kind of VPBlock."); 901 } 902 903 void VPlanPrinter::drawEdge(const VPBlockBase *From, const VPBlockBase *To, 904 bool Hidden, const Twine &Label) { 905 // Due to "dot" we print an edge between two regions as an edge between the 906 // exiting basic block and the entry basic of the respective regions. 907 const VPBlockBase *Tail = From->getExitingBasicBlock(); 908 const VPBlockBase *Head = To->getEntryBasicBlock(); 909 OS << Indent << getUID(Tail) << " -> " << getUID(Head); 910 OS << " [ label=\"" << Label << '\"'; 911 if (Tail != From) 912 OS << " ltail=" << getUID(From); 913 if (Head != To) 914 OS << " lhead=" << getUID(To); 915 if (Hidden) 916 OS << "; splines=none"; 917 OS << "]\n"; 918 } 919 920 void VPlanPrinter::dumpEdges(const VPBlockBase *Block) { 921 auto &Successors = Block->getSuccessors(); 922 if (Successors.size() == 1) 923 drawEdge(Block, Successors.front(), false, ""); 924 else if (Successors.size() == 2) { 925 drawEdge(Block, Successors.front(), false, "T"); 926 drawEdge(Block, Successors.back(), false, "F"); 927 } else { 928 unsigned SuccessorNumber = 0; 929 for (auto *Successor : Successors) 930 drawEdge(Block, Successor, false, Twine(SuccessorNumber++)); 931 } 932 } 933 934 void VPlanPrinter::dumpBasicBlock(const VPBasicBlock *BasicBlock) { 935 // Implement dot-formatted dump by performing plain-text dump into the 936 // temporary storage followed by some post-processing. 937 OS << Indent << getUID(BasicBlock) << " [label =\n"; 938 bumpIndent(1); 939 std::string Str; 940 raw_string_ostream SS(Str); 941 // Use no indentation as we need to wrap the lines into quotes ourselves. 942 BasicBlock->print(SS, "", SlotTracker); 943 944 // We need to process each line of the output separately, so split 945 // single-string plain-text dump. 946 SmallVector<StringRef, 0> Lines; 947 StringRef(Str).rtrim('\n').split(Lines, "\n"); 948 949 auto EmitLine = [&](StringRef Line, StringRef Suffix) { 950 OS << Indent << '"' << DOT::EscapeString(Line.str()) << "\\l\"" << Suffix; 951 }; 952 953 // Don't need the "+" after the last line. 954 for (auto Line : make_range(Lines.begin(), Lines.end() - 1)) 955 EmitLine(Line, " +\n"); 956 EmitLine(Lines.back(), "\n"); 957 958 bumpIndent(-1); 959 OS << Indent << "]\n"; 960 961 dumpEdges(BasicBlock); 962 } 963 964 void VPlanPrinter::dumpRegion(const VPRegionBlock *Region) { 965 OS << Indent << "subgraph " << getUID(Region) << " {\n"; 966 bumpIndent(1); 967 OS << Indent << "fontname=Courier\n" 968 << Indent << "label=\"" 969 << DOT::EscapeString(Region->isReplicator() ? "<xVFxUF> " : "<x1> ") 970 << DOT::EscapeString(Region->getName()) << "\"\n"; 971 // Dump the blocks of the region. 972 assert(Region->getEntry() && "Region contains no inner blocks."); 973 for (const VPBlockBase *Block : vp_depth_first_shallow(Region->getEntry())) 974 dumpBlock(Block); 975 bumpIndent(-1); 976 OS << Indent << "}\n"; 977 dumpEdges(Region); 978 } 979 980 void VPlanIngredient::print(raw_ostream &O) const { 981 if (auto *Inst = dyn_cast<Instruction>(V)) { 982 if (!Inst->getType()->isVoidTy()) { 983 Inst->printAsOperand(O, false); 984 O << " = "; 985 } 986 O << Inst->getOpcodeName() << " "; 987 unsigned E = Inst->getNumOperands(); 988 if (E > 0) { 989 Inst->getOperand(0)->printAsOperand(O, false); 990 for (unsigned I = 1; I < E; ++I) 991 Inst->getOperand(I)->printAsOperand(O << ", ", false); 992 } 993 } else // !Inst 994 V->printAsOperand(O, false); 995 } 996 997 #endif 998 999 template void DomTreeBuilder::Calculate<VPDominatorTree>(VPDominatorTree &DT); 1000 1001 void VPValue::replaceAllUsesWith(VPValue *New) { 1002 for (unsigned J = 0; J < getNumUsers();) { 1003 VPUser *User = Users[J]; 1004 unsigned NumUsers = getNumUsers(); 1005 for (unsigned I = 0, E = User->getNumOperands(); I < E; ++I) 1006 if (User->getOperand(I) == this) 1007 User->setOperand(I, New); 1008 // If a user got removed after updating the current user, the next user to 1009 // update will be moved to the current position, so we only need to 1010 // increment the index if the number of users did not change. 1011 if (NumUsers == getNumUsers()) 1012 J++; 1013 } 1014 } 1015 1016 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1017 void VPValue::printAsOperand(raw_ostream &OS, VPSlotTracker &Tracker) const { 1018 if (const Value *UV = getUnderlyingValue()) { 1019 OS << "ir<"; 1020 UV->printAsOperand(OS, false); 1021 OS << ">"; 1022 return; 1023 } 1024 1025 unsigned Slot = Tracker.getSlot(this); 1026 if (Slot == unsigned(-1)) 1027 OS << "<badref>"; 1028 else 1029 OS << "vp<%" << Tracker.getSlot(this) << ">"; 1030 } 1031 1032 void VPUser::printOperands(raw_ostream &O, VPSlotTracker &SlotTracker) const { 1033 interleaveComma(operands(), O, [&O, &SlotTracker](VPValue *Op) { 1034 Op->printAsOperand(O, SlotTracker); 1035 }); 1036 } 1037 #endif 1038 1039 void VPInterleavedAccessInfo::visitRegion(VPRegionBlock *Region, 1040 Old2NewTy &Old2New, 1041 InterleavedAccessInfo &IAI) { 1042 ReversePostOrderTraversal<VPBlockShallowTraversalWrapper<VPBlockBase *>> 1043 RPOT(Region->getEntry()); 1044 for (VPBlockBase *Base : RPOT) { 1045 visitBlock(Base, Old2New, IAI); 1046 } 1047 } 1048 1049 void VPInterleavedAccessInfo::visitBlock(VPBlockBase *Block, Old2NewTy &Old2New, 1050 InterleavedAccessInfo &IAI) { 1051 if (VPBasicBlock *VPBB = dyn_cast<VPBasicBlock>(Block)) { 1052 for (VPRecipeBase &VPI : *VPBB) { 1053 if (isa<VPHeaderPHIRecipe>(&VPI)) 1054 continue; 1055 assert(isa<VPInstruction>(&VPI) && "Can only handle VPInstructions"); 1056 auto *VPInst = cast<VPInstruction>(&VPI); 1057 1058 auto *Inst = dyn_cast_or_null<Instruction>(VPInst->getUnderlyingValue()); 1059 if (!Inst) 1060 continue; 1061 auto *IG = IAI.getInterleaveGroup(Inst); 1062 if (!IG) 1063 continue; 1064 1065 auto NewIGIter = Old2New.find(IG); 1066 if (NewIGIter == Old2New.end()) 1067 Old2New[IG] = new InterleaveGroup<VPInstruction>( 1068 IG->getFactor(), IG->isReverse(), IG->getAlign()); 1069 1070 if (Inst == IG->getInsertPos()) 1071 Old2New[IG]->setInsertPos(VPInst); 1072 1073 InterleaveGroupMap[VPInst] = Old2New[IG]; 1074 InterleaveGroupMap[VPInst]->insertMember( 1075 VPInst, IG->getIndex(Inst), 1076 Align(IG->isReverse() ? (-1) * int(IG->getFactor()) 1077 : IG->getFactor())); 1078 } 1079 } else if (VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block)) 1080 visitRegion(Region, Old2New, IAI); 1081 else 1082 llvm_unreachable("Unsupported kind of VPBlock."); 1083 } 1084 1085 VPInterleavedAccessInfo::VPInterleavedAccessInfo(VPlan &Plan, 1086 InterleavedAccessInfo &IAI) { 1087 Old2NewTy Old2New; 1088 visitRegion(Plan.getVectorLoopRegion(), Old2New, IAI); 1089 } 1090 1091 void VPSlotTracker::assignSlot(const VPValue *V) { 1092 assert(Slots.find(V) == Slots.end() && "VPValue already has a slot!"); 1093 Slots[V] = NextSlot++; 1094 } 1095 1096 void VPSlotTracker::assignSlots(const VPlan &Plan) { 1097 1098 for (const auto &P : Plan.VPExternalDefs) 1099 assignSlot(P.second); 1100 1101 assignSlot(&Plan.VectorTripCount); 1102 if (Plan.BackedgeTakenCount) 1103 assignSlot(Plan.BackedgeTakenCount); 1104 1105 ReversePostOrderTraversal<VPBlockDeepTraversalWrapper<const VPBlockBase *>> 1106 RPOT(VPBlockDeepTraversalWrapper<const VPBlockBase *>(Plan.getEntry())); 1107 for (const VPBasicBlock *VPBB : 1108 VPBlockUtils::blocksOnly<const VPBasicBlock>(RPOT)) 1109 for (const VPRecipeBase &Recipe : *VPBB) 1110 for (VPValue *Def : Recipe.definedValues()) 1111 assignSlot(Def); 1112 } 1113 1114 bool vputils::onlyFirstLaneUsed(VPValue *Def) { 1115 return all_of(Def->users(), 1116 [Def](VPUser *U) { return U->onlyFirstLaneUsed(Def); }); 1117 } 1118 1119 VPValue *vputils::getOrCreateVPValueForSCEVExpr(VPlan &Plan, const SCEV *Expr, 1120 ScalarEvolution &SE) { 1121 if (auto *E = dyn_cast<SCEVConstant>(Expr)) 1122 return Plan.getOrAddExternalDef(E->getValue()); 1123 if (auto *E = dyn_cast<SCEVUnknown>(Expr)) 1124 return Plan.getOrAddExternalDef(E->getValue()); 1125 1126 VPBasicBlock *Preheader = Plan.getEntry()->getEntryBasicBlock(); 1127 VPExpandSCEVRecipe *Step = new VPExpandSCEVRecipe(Expr, SE); 1128 Preheader->appendRecipe(Step); 1129 return Step; 1130 } 1131