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