LLVM 19.0.0git
VPlan.cpp
Go to the documentation of this file.
1//===- VPlan.cpp - Vectorizer Plan ----------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8///
9/// \file
10/// This is the LLVM vectorization plan. It represents a candidate for
11/// vectorization, allowing to plan and optimize how to vectorize a given loop
12/// before generating LLVM-IR.
13/// The vectorizer uses vectorization plans to estimate the costs of potential
14/// candidates and if profitable to execute the desired plan, generating vector
15/// LLVM-IR code.
16///
17//===----------------------------------------------------------------------===//
18
19#include "VPlan.h"
20#include "VPlanCFG.h"
21#include "VPlanDominatorTree.h"
22#include "VPlanPatternMatch.h"
24#include "llvm/ADT/STLExtras.h"
27#include "llvm/ADT/Twine.h"
30#include "llvm/IR/BasicBlock.h"
31#include "llvm/IR/CFG.h"
32#include "llvm/IR/IRBuilder.h"
33#include "llvm/IR/Instruction.h"
35#include "llvm/IR/Type.h"
36#include "llvm/IR/Value.h"
39#include "llvm/Support/Debug.h"
46#include <cassert>
47#include <string>
48#include <vector>
49
50using namespace llvm;
51using namespace llvm::VPlanPatternMatch;
52
53namespace llvm {
55}
56
57#define DEBUG_TYPE "vplan"
58
59#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
61 const VPInstruction *Instr = dyn_cast<VPInstruction>(&V);
63 (Instr && Instr->getParent()) ? Instr->getParent()->getPlan() : nullptr);
64 V.print(OS, SlotTracker);
65 return OS;
66}
67#endif
68
70 const ElementCount &VF) const {
71 switch (LaneKind) {
73 // Lane = RuntimeVF - VF.getKnownMinValue() + Lane
74 return Builder.CreateSub(getRuntimeVF(Builder, Builder.getInt32Ty(), VF),
75 Builder.getInt32(VF.getKnownMinValue() - Lane));
77 return Builder.getInt32(Lane);
78 }
79 llvm_unreachable("Unknown lane kind");
80}
81
82VPValue::VPValue(const unsigned char SC, Value *UV, VPDef *Def)
83 : SubclassID(SC), UnderlyingVal(UV), Def(Def) {
84 if (Def)
85 Def->addDefinedValue(this);
86}
87
89 assert(Users.empty() && "trying to delete a VPValue with remaining users");
90 if (Def)
91 Def->removeDefinedValue(this);
92}
93
94#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
96 if (const VPRecipeBase *R = dyn_cast_or_null<VPRecipeBase>(Def))
97 R->print(OS, "", SlotTracker);
98 else
100}
101
102void VPValue::dump() const {
103 const VPRecipeBase *Instr = dyn_cast_or_null<VPRecipeBase>(this->Def);
105 (Instr && Instr->getParent()) ? Instr->getParent()->getPlan() : nullptr);
107 dbgs() << "\n";
108}
109
110void VPDef::dump() const {
111 const VPRecipeBase *Instr = dyn_cast_or_null<VPRecipeBase>(this);
113 (Instr && Instr->getParent()) ? Instr->getParent()->getPlan() : nullptr);
114 print(dbgs(), "", SlotTracker);
115 dbgs() << "\n";
116}
117#endif
118
120 return cast_or_null<VPRecipeBase>(Def);
121}
122
124 return cast_or_null<VPRecipeBase>(Def);
125}
126
127// Get the top-most entry block of \p Start. This is the entry block of the
128// containing VPlan. This function is templated to support both const and non-const blocks
129template <typename T> static T *getPlanEntry(T *Start) {
130 T *Next = Start;
131 T *Current = Start;
132 while ((Next = Next->getParent()))
133 Current = Next;
134
135 SmallSetVector<T *, 8> WorkList;
136 WorkList.insert(Current);
137
138 for (unsigned i = 0; i < WorkList.size(); i++) {
139 T *Current = WorkList[i];
140 if (Current->getNumPredecessors() == 0)
141 return Current;
142 auto &Predecessors = Current->getPredecessors();
143 WorkList.insert(Predecessors.begin(), Predecessors.end());
144 }
145
146 llvm_unreachable("VPlan without any entry node without predecessors");
147}
148
149VPlan *VPBlockBase::getPlan() { return getPlanEntry(this)->Plan; }
150
151const VPlan *VPBlockBase::getPlan() const { return getPlanEntry(this)->Plan; }
152
153/// \return the VPBasicBlock that is the entry of Block, possibly indirectly.
155 const VPBlockBase *Block = this;
156 while (const VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
157 Block = Region->getEntry();
158 return cast<VPBasicBlock>(Block);
159}
160
162 VPBlockBase *Block = this;
163 while (VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
164 Block = Region->getEntry();
165 return cast<VPBasicBlock>(Block);
166}
167
168void VPBlockBase::setPlan(VPlan *ParentPlan) {
169 assert(
170 (ParentPlan->getEntry() == this || ParentPlan->getPreheader() == this) &&
171 "Can only set plan on its entry or preheader block.");
172 Plan = ParentPlan;
173}
174
175/// \return the VPBasicBlock that is the exit of Block, possibly indirectly.
177 const VPBlockBase *Block = this;
178 while (const VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
179 Block = Region->getExiting();
180 return cast<VPBasicBlock>(Block);
181}
182
184 VPBlockBase *Block = this;
185 while (VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
186 Block = Region->getExiting();
187 return cast<VPBasicBlock>(Block);
188}
189
191 if (!Successors.empty() || !Parent)
192 return this;
193 assert(Parent->getExiting() == this &&
194 "Block w/o successors not the exiting block of its parent.");
195 return Parent->getEnclosingBlockWithSuccessors();
196}
197
199 if (!Predecessors.empty() || !Parent)
200 return this;
201 assert(Parent->getEntry() == this &&
202 "Block w/o predecessors not the entry of its parent.");
203 return Parent->getEnclosingBlockWithPredecessors();
204}
205
208 delete Block;
209}
210
212 iterator It = begin();
213 while (It != end() && It->isPhi())
214 It++;
215 return It;
216}
217
219 DominatorTree *DT, IRBuilderBase &Builder,
220 InnerLoopVectorizer *ILV, VPlan *Plan,
221 LLVMContext &Ctx)
222 : VF(VF), UF(UF), CFG(DT), LI(LI), Builder(Builder), ILV(ILV), Plan(Plan),
223 LVer(nullptr),
224 TypeAnalysis(Plan->getCanonicalIV()->getScalarType(), Ctx) {}
225
227 if (Def->isLiveIn())
228 return Def->getLiveInIRValue();
229
230 if (hasScalarValue(Def, Instance)) {
231 return Data
232 .PerPartScalars[Def][Instance.Part][Instance.Lane.mapToCacheIndex(VF)];
233 }
234 if (!Instance.Lane.isFirstLane() &&
237 return Data.PerPartScalars[Def][Instance.Part][0];
238 }
239
240 assert(hasVectorValue(Def, Instance.Part));
241 auto *VecPart = Data.PerPartOutput[Def][Instance.Part];
242 if (!VecPart->getType()->isVectorTy()) {
243 assert(Instance.Lane.isFirstLane() && "cannot get lane > 0 for scalar");
244 return VecPart;
245 }
246 // TODO: Cache created scalar values.
247 Value *Lane = Instance.Lane.getAsRuntimeExpr(Builder, VF);
248 auto *Extract = Builder.CreateExtractElement(VecPart, Lane);
249 // set(Def, Extract, Instance);
250 return Extract;
251}
252
253Value *VPTransformState::get(VPValue *Def, unsigned Part, bool NeedsScalar) {
254 if (NeedsScalar) {
255 assert((VF.isScalar() || Def->isLiveIn() || hasVectorValue(Def, Part) ||
256 (hasScalarValue(Def, VPIteration(Part, 0)) &&
257 Data.PerPartScalars[Def][Part].size() == 1)) &&
258 "Trying to access a single scalar per part but has multiple scalars "
259 "per part.");
260 return get(Def, VPIteration(Part, 0));
261 }
262
263 // If Values have been set for this Def return the one relevant for \p Part.
264 if (hasVectorValue(Def, Part))
265 return Data.PerPartOutput[Def][Part];
266
267 auto GetBroadcastInstrs = [this, Def](Value *V) {
268 bool SafeToHoist = Def->isDefinedOutsideVectorRegions();
269 if (VF.isScalar())
270 return V;
271 // Place the code for broadcasting invariant variables in the new preheader.
273 if (SafeToHoist) {
274 BasicBlock *LoopVectorPreHeader = CFG.VPBB2IRBB[cast<VPBasicBlock>(
276 if (LoopVectorPreHeader)
277 Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
278 }
279
280 // Place the code for broadcasting invariant variables in the new preheader.
281 // Broadcast the scalar into all locations in the vector.
282 Value *Shuf = Builder.CreateVectorSplat(VF, V, "broadcast");
283
284 return Shuf;
285 };
286
287 if (!hasScalarValue(Def, {Part, 0})) {
288 assert(Def->isLiveIn() && "expected a live-in");
289 if (Part != 0)
290 return get(Def, 0);
291 Value *IRV = Def->getLiveInIRValue();
292 Value *B = GetBroadcastInstrs(IRV);
293 set(Def, B, Part);
294 return B;
295 }
296
297 Value *ScalarValue = get(Def, {Part, 0});
298 // If we aren't vectorizing, we can just copy the scalar map values over
299 // to the vector map.
300 if (VF.isScalar()) {
301 set(Def, ScalarValue, Part);
302 return ScalarValue;
303 }
304
305 bool IsUniform = vputils::isUniformAfterVectorization(Def);
306
307 unsigned LastLane = IsUniform ? 0 : VF.getKnownMinValue() - 1;
308 // Check if there is a scalar value for the selected lane.
309 if (!hasScalarValue(Def, {Part, LastLane})) {
310 // At the moment, VPWidenIntOrFpInductionRecipes, VPScalarIVStepsRecipes and
311 // VPExpandSCEVRecipes can also be uniform.
312 assert((isa<VPWidenIntOrFpInductionRecipe>(Def->getDefiningRecipe()) ||
313 isa<VPScalarIVStepsRecipe>(Def->getDefiningRecipe()) ||
314 isa<VPExpandSCEVRecipe>(Def->getDefiningRecipe())) &&
315 "unexpected recipe found to be invariant");
316 IsUniform = true;
317 LastLane = 0;
318 }
319
320 auto *LastInst = cast<Instruction>(get(Def, {Part, LastLane}));
321 // Set the insert point after the last scalarized instruction or after the
322 // last PHI, if LastInst is a PHI. This ensures the insertelement sequence
323 // will directly follow the scalar definitions.
324 auto OldIP = Builder.saveIP();
325 auto NewIP =
326 isa<PHINode>(LastInst)
327 ? BasicBlock::iterator(LastInst->getParent()->getFirstNonPHI())
328 : std::next(BasicBlock::iterator(LastInst));
329 Builder.SetInsertPoint(&*NewIP);
330
331 // However, if we are vectorizing, we need to construct the vector values.
332 // If the value is known to be uniform after vectorization, we can just
333 // broadcast the scalar value corresponding to lane zero for each unroll
334 // iteration. Otherwise, we construct the vector values using
335 // insertelement instructions. Since the resulting vectors are stored in
336 // State, we will only generate the insertelements once.
337 Value *VectorValue = nullptr;
338 if (IsUniform) {
339 VectorValue = GetBroadcastInstrs(ScalarValue);
340 set(Def, VectorValue, Part);
341 } else {
342 // Initialize packing with insertelements to start from undef.
343 assert(!VF.isScalable() && "VF is assumed to be non scalable.");
344 Value *Undef = PoisonValue::get(VectorType::get(LastInst->getType(), VF));
345 set(Def, Undef, Part);
346 for (unsigned Lane = 0; Lane < VF.getKnownMinValue(); ++Lane)
347 packScalarIntoVectorValue(Def, {Part, Lane});
348 VectorValue = get(Def, Part);
349 }
350 Builder.restoreIP(OldIP);
351 return VectorValue;
352}
353
355 VPRegionBlock *LoopRegion = R->getParent()->getEnclosingLoopRegion();
356 return VPBB2IRBB[LoopRegion->getPreheaderVPBB()];
357}
358
360 const Instruction *Orig) {
361 // If the loop was versioned with memchecks, add the corresponding no-alias
362 // metadata.
363 if (LVer && (isa<LoadInst>(Orig) || isa<StoreInst>(Orig)))
364 LVer->annotateInstWithNoAlias(To, Orig);
365}
366
368 // No source instruction to transfer metadata from?
369 if (!From)
370 return;
371
372 if (Instruction *ToI = dyn_cast<Instruction>(To)) {
374 addNewMetadata(ToI, From);
375 }
376}
377
379 const DILocation *DIL = DL;
380 // When a FSDiscriminator is enabled, we don't need to add the multiply
381 // factors to the discriminators.
382 if (DIL &&
384 ->getParent()
387 // FIXME: For scalable vectors, assume vscale=1.
388 auto NewDIL =
390 if (NewDIL)
392 else
393 LLVM_DEBUG(dbgs() << "Failed to create new discriminator: "
394 << DIL->getFilename() << " Line: " << DIL->getLine());
395 } else
397}
398
400 const VPIteration &Instance) {
401 Value *ScalarInst = get(Def, Instance);
402 Value *VectorValue = get(Def, Instance.Part);
403 VectorValue = Builder.CreateInsertElement(
404 VectorValue, ScalarInst, Instance.Lane.getAsRuntimeExpr(Builder, VF));
405 set(Def, VectorValue, Instance.Part);
406}
407
409VPBasicBlock::createEmptyBasicBlock(VPTransformState::CFGState &CFG) {
410 // BB stands for IR BasicBlocks. VPBB stands for VPlan VPBasicBlocks.
411 // Pred stands for Predessor. Prev stands for Previous - last visited/created.
412 BasicBlock *PrevBB = CFG.PrevBB;
413 BasicBlock *NewBB = BasicBlock::Create(PrevBB->getContext(), getName(),
414 PrevBB->getParent(), CFG.ExitBB);
415 LLVM_DEBUG(dbgs() << "LV: created " << NewBB->getName() << '\n');
416
417 // Hook up the new basic block to its predecessors.
418 for (VPBlockBase *PredVPBlock : getHierarchicalPredecessors()) {
419 VPBasicBlock *PredVPBB = PredVPBlock->getExitingBasicBlock();
420 auto &PredVPSuccessors = PredVPBB->getHierarchicalSuccessors();
421 BasicBlock *PredBB = CFG.VPBB2IRBB[PredVPBB];
422
423 assert(PredBB && "Predecessor basic-block not found building successor.");
424 auto *PredBBTerminator = PredBB->getTerminator();
425 LLVM_DEBUG(dbgs() << "LV: draw edge from" << PredBB->getName() << '\n');
426
427 auto *TermBr = dyn_cast<BranchInst>(PredBBTerminator);
428 if (isa<UnreachableInst>(PredBBTerminator)) {
429 assert(PredVPSuccessors.size() == 1 &&
430 "Predecessor ending w/o branch must have single successor.");
431 DebugLoc DL = PredBBTerminator->getDebugLoc();
432 PredBBTerminator->eraseFromParent();
433 auto *Br = BranchInst::Create(NewBB, PredBB);
434 Br->setDebugLoc(DL);
435 } else if (TermBr && !TermBr->isConditional()) {
436 TermBr->setSuccessor(0, NewBB);
437 } else {
438 // Set each forward successor here when it is created, excluding
439 // backedges. A backward successor is set when the branch is created.
440 unsigned idx = PredVPSuccessors.front() == this ? 0 : 1;
441 assert(!TermBr->getSuccessor(idx) &&
442 "Trying to reset an existing successor block.");
443 TermBr->setSuccessor(idx, NewBB);
444 }
445 CFG.DTU.applyUpdates({{DominatorTree::Insert, PredBB, NewBB}});
446 }
447 return NewBB;
448}
449
451 assert(getHierarchicalSuccessors().empty() &&
452 "VPIRBasicBlock cannot have successors at the moment");
453
454 State->Builder.SetInsertPoint(getIRBasicBlock()->getTerminator());
455 executeRecipes(State, getIRBasicBlock());
456
457 for (VPBlockBase *PredVPBlock : getHierarchicalPredecessors()) {
458 VPBasicBlock *PredVPBB = PredVPBlock->getExitingBasicBlock();
459 BasicBlock *PredBB = State->CFG.VPBB2IRBB[PredVPBB];
460 assert(PredBB && "Predecessor basic-block not found building successor.");
461 LLVM_DEBUG(dbgs() << "LV: draw edge from" << PredBB->getName() << '\n');
462
463 auto *PredBBTerminator = PredBB->getTerminator();
464 auto *TermBr = cast<BranchInst>(PredBBTerminator);
465 // Set each forward successor here when it is created, excluding
466 // backedges. A backward successor is set when the branch is created.
467 const auto &PredVPSuccessors = PredVPBB->getHierarchicalSuccessors();
468 unsigned idx = PredVPSuccessors.front() == this ? 0 : 1;
469 assert(!TermBr->getSuccessor(idx) &&
470 "Trying to reset an existing successor block.");
471 TermBr->setSuccessor(idx, IRBB);
472 State->CFG.DTU.applyUpdates({{DominatorTree::Insert, PredBB, IRBB}});
473 }
474}
475
477 bool Replica = State->Instance && !State->Instance->isFirstIteration();
478 VPBasicBlock *PrevVPBB = State->CFG.PrevVPBB;
479 VPBlockBase *SingleHPred = nullptr;
480 BasicBlock *NewBB = State->CFG.PrevBB; // Reuse it if possible.
481
482 auto IsLoopRegion = [](VPBlockBase *BB) {
483 auto *R = dyn_cast<VPRegionBlock>(BB);
484 return R && !R->isReplicator();
485 };
486
487 // 1. Create an IR basic block.
488 if (PrevVPBB && /* A */
489 !((SingleHPred = getSingleHierarchicalPredecessor()) &&
490 SingleHPred->getExitingBasicBlock() == PrevVPBB &&
491 PrevVPBB->getSingleHierarchicalSuccessor() &&
492 (SingleHPred->getParent() == getEnclosingLoopRegion() &&
493 !IsLoopRegion(SingleHPred))) && /* B */
494 !(Replica && getPredecessors().empty())) { /* C */
495 // The last IR basic block is reused, as an optimization, in three cases:
496 // A. the first VPBB reuses the loop pre-header BB - when PrevVPBB is null;
497 // B. when the current VPBB has a single (hierarchical) predecessor which
498 // is PrevVPBB and the latter has a single (hierarchical) successor which
499 // both are in the same non-replicator region; and
500 // C. when the current VPBB is an entry of a region replica - where PrevVPBB
501 // is the exiting VPBB of this region from a previous instance, or the
502 // predecessor of this region.
503
504 NewBB = createEmptyBasicBlock(State->CFG);
505 State->Builder.SetInsertPoint(NewBB);
506 // Temporarily terminate with unreachable until CFG is rewired.
507 UnreachableInst *Terminator = State->Builder.CreateUnreachable();
508 // Register NewBB in its loop. In innermost loops its the same for all
509 // BB's.
510 if (State->CurrentVectorLoop)
511 State->CurrentVectorLoop->addBasicBlockToLoop(NewBB, *State->LI);
512 State->Builder.SetInsertPoint(Terminator);
513 State->CFG.PrevBB = NewBB;
514 }
515
516 // 2. Fill the IR basic block with IR instructions.
517 executeRecipes(State, NewBB);
518}
519
521 for (VPRecipeBase &R : Recipes) {
522 for (auto *Def : R.definedValues())
523 Def->replaceAllUsesWith(NewValue);
524
525 for (unsigned I = 0, E = R.getNumOperands(); I != E; I++)
526 R.setOperand(I, NewValue);
527 }
528}
529
531 LLVM_DEBUG(dbgs() << "LV: vectorizing VPBB:" << getName()
532 << " in BB:" << BB->getName() << '\n');
533
534 State->CFG.VPBB2IRBB[this] = BB;
535 State->CFG.PrevVPBB = this;
536
537 for (VPRecipeBase &Recipe : Recipes)
538 Recipe.execute(*State);
539
540 LLVM_DEBUG(dbgs() << "LV: filled BB:" << *BB);
541}
542
544 assert((SplitAt == end() || SplitAt->getParent() == this) &&
545 "can only split at a position in the same block");
546
548 // First, disconnect the current block from its successors.
549 for (VPBlockBase *Succ : Succs)
551
552 // Create new empty block after the block to split.
553 auto *SplitBlock = new VPBasicBlock(getName() + ".split");
555
556 // Add successors for block to split to new block.
557 for (VPBlockBase *Succ : Succs)
559
560 // Finally, move the recipes starting at SplitAt to new block.
561 for (VPRecipeBase &ToMove :
562 make_early_inc_range(make_range(SplitAt, this->end())))
563 ToMove.moveBefore(*SplitBlock, SplitBlock->end());
564
565 return SplitBlock;
566}
567
570 if (P && P->isReplicator()) {
571 P = P->getParent();
572 assert(!cast<VPRegionBlock>(P)->isReplicator() &&
573 "unexpected nested replicate regions");
574 }
575 return P;
576}
577
578static bool hasConditionalTerminator(const VPBasicBlock *VPBB) {
579 if (VPBB->empty()) {
580 assert(
581 VPBB->getNumSuccessors() < 2 &&
582 "block with multiple successors doesn't have a recipe as terminator");
583 return false;
584 }
585
586 const VPRecipeBase *R = &VPBB->back();
587 bool IsCondBranch = isa<VPBranchOnMaskRecipe>(R) ||
590 (void)IsCondBranch;
591
592 if (VPBB->getNumSuccessors() >= 2 ||
593 (VPBB->isExiting() && !VPBB->getParent()->isReplicator())) {
594 assert(IsCondBranch && "block with multiple successors not terminated by "
595 "conditional branch recipe");
596
597 return true;
598 }
599
600 assert(
601 !IsCondBranch &&
602 "block with 0 or 1 successors terminated by conditional branch recipe");
603 return false;
604}
605
607 if (hasConditionalTerminator(this))
608 return &back();
609 return nullptr;
610}
611
613 if (hasConditionalTerminator(this))
614 return &back();
615 return nullptr;
616}
617
619 return getParent() && getParent()->getExitingBasicBlock() == this;
620}
621
622#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
623void VPBlockBase::printSuccessors(raw_ostream &O, const Twine &Indent) const {
624 if (getSuccessors().empty()) {
625 O << Indent << "No successors\n";
626 } else {
627 O << Indent << "Successor(s): ";
628 ListSeparator LS;
629 for (auto *Succ : getSuccessors())
630 O << LS << Succ->getName();
631 O << '\n';
632 }
633}
634
635void VPBasicBlock::print(raw_ostream &O, const Twine &Indent,
636 VPSlotTracker &SlotTracker) const {
637 O << Indent << getName() << ":\n";
638
639 auto RecipeIndent = Indent + " ";
640 for (const VPRecipeBase &Recipe : *this) {
641 Recipe.print(O, RecipeIndent, SlotTracker);
642 O << '\n';
643 }
644
645 printSuccessors(O, Indent);
646}
647#endif
648
649static std::pair<VPBlockBase *, VPBlockBase *> cloneSESE(VPBlockBase *Entry);
650
651// Clone the CFG for all nodes in the single-entry-single-exit region reachable
652// from \p Entry, this includes cloning the blocks and their recipes. Operands
653// of cloned recipes will NOT be updated. Remapping of operands must be done
654// separately. Returns a pair with the the new entry and exiting blocks of the
655// cloned region.
656static std::pair<VPBlockBase *, VPBlockBase *> cloneSESE(VPBlockBase *Entry) {
658 VPBlockBase *Exiting = nullptr;
659 // First, clone blocks reachable from Entry.
660 for (VPBlockBase *BB : vp_depth_first_shallow(Entry)) {
661 VPBlockBase *NewBB = BB->clone();
662 Old2NewVPBlocks[BB] = NewBB;
663 if (BB->getNumSuccessors() == 0) {
664 assert(!Exiting && "Multiple exiting blocks?");
665 Exiting = BB;
666 }
667 }
668
669 // Second, update the predecessors & successors of the cloned blocks.
670 for (VPBlockBase *BB : vp_depth_first_shallow(Entry)) {
671 VPBlockBase *NewBB = Old2NewVPBlocks[BB];
673 for (VPBlockBase *Pred : BB->getPredecessors()) {
674 NewPreds.push_back(Old2NewVPBlocks[Pred]);
675 }
676 NewBB->setPredecessors(NewPreds);
678 for (VPBlockBase *Succ : BB->successors()) {
679 NewSuccs.push_back(Old2NewVPBlocks[Succ]);
680 }
681 NewBB->setSuccessors(NewSuccs);
682 }
683
684#if !defined(NDEBUG)
685 // Verify that the order of predecessors and successors matches in the cloned
686 // version.
687 for (const auto &[OldBB, NewBB] :
689 vp_depth_first_shallow(Old2NewVPBlocks[Entry]))) {
690 for (const auto &[OldPred, NewPred] :
691 zip(OldBB->getPredecessors(), NewBB->getPredecessors()))
692 assert(NewPred == Old2NewVPBlocks[OldPred] && "Different predecessors");
693
694 for (const auto &[OldSucc, NewSucc] :
695 zip(OldBB->successors(), NewBB->successors()))
696 assert(NewSucc == Old2NewVPBlocks[OldSucc] && "Different successors");
697 }
698#endif
699
700 return std::make_pair(Old2NewVPBlocks[Entry], Old2NewVPBlocks[Exiting]);
701}
702
704 const auto &[NewEntry, NewExiting] = cloneSESE(getEntry());
705 auto *NewRegion =
706 new VPRegionBlock(NewEntry, NewExiting, getName(), isReplicator());
707 for (VPBlockBase *Block : vp_depth_first_shallow(NewEntry))
708 Block->setParent(NewRegion);
709 return NewRegion;
710}
711
714 // Drop all references in VPBasicBlocks and replace all uses with
715 // DummyValue.
716 Block->dropAllReferences(NewValue);
717}
718
721 RPOT(Entry);
722
723 if (!isReplicator()) {
724 // Create and register the new vector loop.
725 Loop *PrevLoop = State->CurrentVectorLoop;
726 State->CurrentVectorLoop = State->LI->AllocateLoop();
727 BasicBlock *VectorPH = State->CFG.VPBB2IRBB[getPreheaderVPBB()];
728 Loop *ParentLoop = State->LI->getLoopFor(VectorPH);
729
730 // Insert the new loop into the loop nest and register the new basic blocks
731 // before calling any utilities such as SCEV that require valid LoopInfo.
732 if (ParentLoop)
733 ParentLoop->addChildLoop(State->CurrentVectorLoop);
734 else
735 State->LI->addTopLevelLoop(State->CurrentVectorLoop);
736
737 // Visit the VPBlocks connected to "this", starting from it.
738 for (VPBlockBase *Block : RPOT) {
739 LLVM_DEBUG(dbgs() << "LV: VPBlock in RPO " << Block->getName() << '\n');
740 Block->execute(State);
741 }
742
743 State->CurrentVectorLoop = PrevLoop;
744 return;
745 }
746
747 assert(!State->Instance && "Replicating a Region with non-null instance.");
748
749 // Enter replicating mode.
750 State->Instance = VPIteration(0, 0);
751
752 for (unsigned Part = 0, UF = State->UF; Part < UF; ++Part) {
753 State->Instance->Part = Part;
754 assert(!State->VF.isScalable() && "VF is assumed to be non scalable.");
755 for (unsigned Lane = 0, VF = State->VF.getKnownMinValue(); Lane < VF;
756 ++Lane) {
757 State->Instance->Lane = VPLane(Lane, VPLane::Kind::First);
758 // Visit the VPBlocks connected to \p this, starting from it.
759 for (VPBlockBase *Block : RPOT) {
760 LLVM_DEBUG(dbgs() << "LV: VPBlock in RPO " << Block->getName() << '\n');
761 Block->execute(State);
762 }
763 }
764 }
765
766 // Exit replicating mode.
767 State->Instance.reset();
768}
769
770#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
772 VPSlotTracker &SlotTracker) const {
773 O << Indent << (isReplicator() ? "<xVFxUF> " : "<x1> ") << getName() << ": {";
774 auto NewIndent = Indent + " ";
775 for (auto *BlockBase : vp_depth_first_shallow(Entry)) {
776 O << '\n';
777 BlockBase->print(O, NewIndent, SlotTracker);
778 }
779 O << Indent << "}\n";
780
781 printSuccessors(O, Indent);
782}
783#endif
784
786 for (auto &KV : LiveOuts)
787 delete KV.second;
788 LiveOuts.clear();
789
790 if (Entry) {
791 VPValue DummyValue;
793 Block->dropAllReferences(&DummyValue);
794
796
797 Preheader->dropAllReferences(&DummyValue);
798 delete Preheader;
799 }
800 for (VPValue *VPV : VPLiveInsToFree)
801 delete VPV;
802 if (BackedgeTakenCount)
803 delete BackedgeTakenCount;
804}
805
807 BasicBlock *PH) {
808 VPIRBasicBlock *Entry = new VPIRBasicBlock(PH);
809 VPBasicBlock *VecPreheader = new VPBasicBlock("vector.ph");
810 auto Plan = std::make_unique<VPlan>(Entry, VecPreheader);
811 Plan->TripCount =
813 // Create empty VPRegionBlock, to be filled during processing later.
814 auto *TopRegion = new VPRegionBlock("vector loop", false /*isReplicator*/);
815 VPBlockUtils::insertBlockAfter(TopRegion, VecPreheader);
816 VPBasicBlock *MiddleVPBB = new VPBasicBlock("middle.block");
817 VPBlockUtils::insertBlockAfter(MiddleVPBB, TopRegion);
818 return Plan;
819}
820
821void VPlan::prepareToExecute(Value *TripCountV, Value *VectorTripCountV,
822 Value *CanonicalIVStartValue,
823 VPTransformState &State) {
824 // Check if the backedge taken count is needed, and if so build it.
825 if (BackedgeTakenCount && BackedgeTakenCount->getNumUsers()) {
827 auto *TCMO = Builder.CreateSub(TripCountV,
828 ConstantInt::get(TripCountV->getType(), 1),
829 "trip.count.minus.1");
830 BackedgeTakenCount->setUnderlyingValue(TCMO);
831 }
832
833 VectorTripCount.setUnderlyingValue(VectorTripCountV);
834
836 // FIXME: Model VF * UF computation completely in VPlan.
837 VFxUF.setUnderlyingValue(
838 createStepForVF(Builder, TripCountV->getType(), State.VF, State.UF));
839
840 // When vectorizing the epilogue loop, the canonical induction start value
841 // needs to be changed from zero to the value after the main vector loop.
842 // FIXME: Improve modeling for canonical IV start values in the epilogue loop.
843 if (CanonicalIVStartValue) {
844 VPValue *VPV = getOrAddLiveIn(CanonicalIVStartValue);
845 auto *IV = getCanonicalIV();
846 assert(all_of(IV->users(),
847 [](const VPUser *U) {
848 return isa<VPScalarIVStepsRecipe>(U) ||
849 isa<VPScalarCastRecipe>(U) ||
850 isa<VPDerivedIVRecipe>(U) ||
851 cast<VPInstruction>(U)->getOpcode() ==
852 Instruction::Add;
853 }) &&
854 "the canonical IV should only be used by its increment or "
855 "ScalarIVSteps when resetting the start value");
856 IV->setOperand(0, VPV);
857 }
858}
859
860/// Replace \p VPBB with a VPIRBasicBlock wrapping \p IRBB. All recipes from \p
861/// VPBB are moved to the newly created VPIRBasicBlock.
863 assert(VPBB->getNumSuccessors() == 0 && "VPBB must be a leave node");
864 VPIRBasicBlock *IRMiddleVPBB = new VPIRBasicBlock(IRBB);
865 for (auto &R : make_early_inc_range(*VPBB))
866 R.moveBefore(*IRMiddleVPBB, IRMiddleVPBB->end());
867 VPBlockBase *PredVPBB = VPBB->getSinglePredecessor();
868 VPBlockUtils::disconnectBlocks(PredVPBB, VPBB);
869 VPBlockUtils::connectBlocks(PredVPBB, IRMiddleVPBB);
870 delete VPBB;
871}
872
873/// Generate the code inside the preheader and body of the vectorized loop.
874/// Assumes a single pre-header basic-block was created for this. Introduce
875/// additional basic-blocks as needed, and fill them all.
877 // Initialize CFG state.
878 State->CFG.PrevVPBB = nullptr;
879 State->CFG.ExitBB = State->CFG.PrevBB->getSingleSuccessor();
880 BasicBlock *VectorPreHeader = State->CFG.PrevBB;
881 State->Builder.SetInsertPoint(VectorPreHeader->getTerminator());
883 cast<VPBasicBlock>(getVectorLoopRegion()->getSingleSuccessor()),
884 State->CFG.ExitBB);
885
886 // Disconnect VectorPreHeader from ExitBB in both the CFG and DT.
887 cast<BranchInst>(VectorPreHeader->getTerminator())->setSuccessor(0, nullptr);
888 State->CFG.DTU.applyUpdates(
889 {{DominatorTree::Delete, VectorPreHeader, State->CFG.ExitBB}});
890
891 // Generate code in the loop pre-header and body.
893 Block->execute(State);
894
895 VPBasicBlock *LatchVPBB = getVectorLoopRegion()->getExitingBasicBlock();
896 BasicBlock *VectorLatchBB = State->CFG.VPBB2IRBB[LatchVPBB];
897
898 // Fix the latch value of canonical, reduction and first-order recurrences
899 // phis in the vector loop.
900 VPBasicBlock *Header = getVectorLoopRegion()->getEntryBasicBlock();
901 for (VPRecipeBase &R : Header->phis()) {
902 // Skip phi-like recipes that generate their backedege values themselves.
903 if (isa<VPWidenPHIRecipe>(&R))
904 continue;
905
906 if (isa<VPWidenPointerInductionRecipe>(&R) ||
907 isa<VPWidenIntOrFpInductionRecipe>(&R)) {
908 PHINode *Phi = nullptr;
909 if (isa<VPWidenIntOrFpInductionRecipe>(&R)) {
910 Phi = cast<PHINode>(State->get(R.getVPSingleValue(), 0));
911 } else {
912 auto *WidenPhi = cast<VPWidenPointerInductionRecipe>(&R);
913 assert(!WidenPhi->onlyScalarsGenerated(State->VF.isScalable()) &&
914 "recipe generating only scalars should have been replaced");
915 auto *GEP = cast<GetElementPtrInst>(State->get(WidenPhi, 0));
916 Phi = cast<PHINode>(GEP->getPointerOperand());
917 }
918
919 Phi->setIncomingBlock(1, VectorLatchBB);
920
921 // Move the last step to the end of the latch block. This ensures
922 // consistent placement of all induction updates.
923 Instruction *Inc = cast<Instruction>(Phi->getIncomingValue(1));
924 Inc->moveBefore(VectorLatchBB->getTerminator()->getPrevNode());
925 continue;
926 }
927
928 auto *PhiR = cast<VPHeaderPHIRecipe>(&R);
929 // For canonical IV, first-order recurrences and in-order reduction phis,
930 // only a single part is generated, which provides the last part from the
931 // previous iteration. For non-ordered reductions all UF parts are
932 // generated.
933 bool SinglePartNeeded =
934 isa<VPCanonicalIVPHIRecipe>(PhiR) ||
935 isa<VPFirstOrderRecurrencePHIRecipe, VPEVLBasedIVPHIRecipe>(PhiR) ||
936 (isa<VPReductionPHIRecipe>(PhiR) &&
937 cast<VPReductionPHIRecipe>(PhiR)->isOrdered());
938 bool NeedsScalar =
939 isa<VPCanonicalIVPHIRecipe, VPEVLBasedIVPHIRecipe>(PhiR) ||
940 (isa<VPReductionPHIRecipe>(PhiR) &&
941 cast<VPReductionPHIRecipe>(PhiR)->isInLoop());
942 unsigned LastPartForNewPhi = SinglePartNeeded ? 1 : State->UF;
943
944 for (unsigned Part = 0; Part < LastPartForNewPhi; ++Part) {
945 Value *Phi = State->get(PhiR, Part, NeedsScalar);
946 Value *Val =
947 State->get(PhiR->getBackedgeValue(),
948 SinglePartNeeded ? State->UF - 1 : Part, NeedsScalar);
949 cast<PHINode>(Phi)->addIncoming(Val, VectorLatchBB);
950 }
951 }
952
953 State->CFG.DTU.flush();
954 assert(State->CFG.DTU.getDomTree().verify(
955 DominatorTree::VerificationLevel::Fast) &&
956 "DT not preserved correctly");
957}
958
959#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
962
963 if (VFxUF.getNumUsers() > 0) {
964 O << "\nLive-in ";
965 VFxUF.printAsOperand(O, SlotTracker);
966 O << " = VF * UF";
967 }
968
969 if (VectorTripCount.getNumUsers() > 0) {
970 O << "\nLive-in ";
971 VectorTripCount.printAsOperand(O, SlotTracker);
972 O << " = vector-trip-count";
973 }
974
975 if (BackedgeTakenCount && BackedgeTakenCount->getNumUsers()) {
976 O << "\nLive-in ";
977 BackedgeTakenCount->printAsOperand(O, SlotTracker);
978 O << " = backedge-taken count";
979 }
980
981 O << "\n";
982 if (TripCount->isLiveIn())
983 O << "Live-in ";
984 TripCount->printAsOperand(O, SlotTracker);
985 O << " = original trip-count";
986 O << "\n";
987}
988
990void VPlan::print(raw_ostream &O) const {
992
993 O << "VPlan '" << getName() << "' {";
994
995 printLiveIns(O);
996
997 if (!getPreheader()->empty()) {
998 O << "\n";
999 getPreheader()->print(O, "", SlotTracker);
1000 }
1001
1002 for (const VPBlockBase *Block : vp_depth_first_shallow(getEntry())) {
1003 O << '\n';
1004 Block->print(O, "", SlotTracker);
1005 }
1006
1007 if (!LiveOuts.empty())
1008 O << "\n";
1009 for (const auto &KV : LiveOuts) {
1010 KV.second->print(O, SlotTracker);
1011 }
1012
1013 O << "}\n";
1014}
1015
1016std::string VPlan::getName() const {
1017 std::string Out;
1018 raw_string_ostream RSO(Out);
1019 RSO << Name << " for ";
1020 if (!VFs.empty()) {
1021 RSO << "VF={" << VFs[0];
1022 for (ElementCount VF : drop_begin(VFs))
1023 RSO << "," << VF;
1024 RSO << "},";
1025 }
1026
1027 if (UFs.empty()) {
1028 RSO << "UF>=1";
1029 } else {
1030 RSO << "UF={" << UFs[0];
1031 for (unsigned UF : drop_begin(UFs))
1032 RSO << "," << UF;
1033 RSO << "}";
1034 }
1035
1036 return Out;
1037}
1038
1041 VPlanPrinter Printer(O, *this);
1042 Printer.dump();
1043}
1044
1046void VPlan::dump() const { print(dbgs()); }
1047#endif
1048
1050 assert(LiveOuts.count(PN) == 0 && "an exit value for PN already exists");
1051 LiveOuts.insert({PN, new VPLiveOut(PN, V)});
1052}
1053
1054static void remapOperands(VPBlockBase *Entry, VPBlockBase *NewEntry,
1055 DenseMap<VPValue *, VPValue *> &Old2NewVPValues) {
1056 // Update the operands of all cloned recipes starting at NewEntry. This
1057 // traverses all reachable blocks. This is done in two steps, to handle cycles
1058 // in PHI recipes.
1060 OldDeepRPOT(Entry);
1062 NewDeepRPOT(NewEntry);
1063 // First, collect all mappings from old to new VPValues defined by cloned
1064 // recipes.
1065 for (const auto &[OldBB, NewBB] :
1066 zip(VPBlockUtils::blocksOnly<VPBasicBlock>(OldDeepRPOT),
1067 VPBlockUtils::blocksOnly<VPBasicBlock>(NewDeepRPOT))) {
1068 assert(OldBB->getRecipeList().size() == NewBB->getRecipeList().size() &&
1069 "blocks must have the same number of recipes");
1070 for (const auto &[OldR, NewR] : zip(*OldBB, *NewBB)) {
1071 assert(OldR.getNumOperands() == NewR.getNumOperands() &&
1072 "recipes must have the same number of operands");
1073 assert(OldR.getNumDefinedValues() == NewR.getNumDefinedValues() &&
1074 "recipes must define the same number of operands");
1075 for (const auto &[OldV, NewV] :
1076 zip(OldR.definedValues(), NewR.definedValues()))
1077 Old2NewVPValues[OldV] = NewV;
1078 }
1079 }
1080
1081 // Update all operands to use cloned VPValues.
1082 for (VPBasicBlock *NewBB :
1083 VPBlockUtils::blocksOnly<VPBasicBlock>(NewDeepRPOT)) {
1084 for (VPRecipeBase &NewR : *NewBB)
1085 for (unsigned I = 0, E = NewR.getNumOperands(); I != E; ++I) {
1086 VPValue *NewOp = Old2NewVPValues.lookup(NewR.getOperand(I));
1087 NewR.setOperand(I, NewOp);
1088 }
1089 }
1090}
1091
1093 // Clone blocks.
1094 VPBasicBlock *NewPreheader = Preheader->clone();
1095 const auto &[NewEntry, __] = cloneSESE(Entry);
1096
1097 // Create VPlan, clone live-ins and remap operands in the cloned blocks.
1098 auto *NewPlan = new VPlan(NewPreheader, cast<VPBasicBlock>(NewEntry));
1099 DenseMap<VPValue *, VPValue *> Old2NewVPValues;
1100 for (VPValue *OldLiveIn : VPLiveInsToFree) {
1101 Old2NewVPValues[OldLiveIn] =
1102 NewPlan->getOrAddLiveIn(OldLiveIn->getLiveInIRValue());
1103 }
1104 Old2NewVPValues[&VectorTripCount] = &NewPlan->VectorTripCount;
1105 Old2NewVPValues[&VFxUF] = &NewPlan->VFxUF;
1106 if (BackedgeTakenCount) {
1107 NewPlan->BackedgeTakenCount = new VPValue();
1108 Old2NewVPValues[BackedgeTakenCount] = NewPlan->BackedgeTakenCount;
1109 }
1110 assert(TripCount && "trip count must be set");
1111 if (TripCount->isLiveIn())
1112 Old2NewVPValues[TripCount] =
1113 NewPlan->getOrAddLiveIn(TripCount->getLiveInIRValue());
1114 // else NewTripCount will be created and inserted into Old2NewVPValues when
1115 // TripCount is cloned. In any case NewPlan->TripCount is updated below.
1116
1117 remapOperands(Preheader, NewPreheader, Old2NewVPValues);
1118 remapOperands(Entry, NewEntry, Old2NewVPValues);
1119
1120 // Clone live-outs.
1121 for (const auto &[_, LO] : LiveOuts)
1122 NewPlan->addLiveOut(LO->getPhi(), Old2NewVPValues[LO->getOperand(0)]);
1123
1124 // Initialize remaining fields of cloned VPlan.
1125 NewPlan->VFs = VFs;
1126 NewPlan->UFs = UFs;
1127 // TODO: Adjust names.
1128 NewPlan->Name = Name;
1129 assert(Old2NewVPValues.contains(TripCount) &&
1130 "TripCount must have been added to Old2NewVPValues");
1131 NewPlan->TripCount = Old2NewVPValues[TripCount];
1132 return NewPlan;
1133}
1134
1135#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1136
1137Twine VPlanPrinter::getUID(const VPBlockBase *Block) {
1138 return (isa<VPRegionBlock>(Block) ? "cluster_N" : "N") +
1139 Twine(getOrCreateBID(Block));
1140}
1141
1142Twine VPlanPrinter::getOrCreateName(const VPBlockBase *Block) {
1143 const std::string &Name = Block->getName();
1144 if (!Name.empty())
1145 return Name;
1146 return "VPB" + Twine(getOrCreateBID(Block));
1147}
1148
1150 Depth = 1;
1151 bumpIndent(0);
1152 OS << "digraph VPlan {\n";
1153 OS << "graph [labelloc=t, fontsize=30; label=\"Vectorization Plan";
1154 if (!Plan.getName().empty())
1155 OS << "\\n" << DOT::EscapeString(Plan.getName());
1156
1157 {
1158 // Print live-ins.
1159 std::string Str;
1160 raw_string_ostream SS(Str);
1161 Plan.printLiveIns(SS);
1163 StringRef(Str).rtrim('\n').split(Lines, "\n");
1164 for (auto Line : Lines)
1165 OS << DOT::EscapeString(Line.str()) << "\\n";
1166 }
1167
1168 OS << "\"]\n";
1169 OS << "node [shape=rect, fontname=Courier, fontsize=30]\n";
1170 OS << "edge [fontname=Courier, fontsize=30]\n";
1171 OS << "compound=true\n";
1172
1173 dumpBlock(Plan.getPreheader());
1174
1176 dumpBlock(Block);
1177
1178 OS << "}\n";
1179}
1180
1181void VPlanPrinter::dumpBlock(const VPBlockBase *Block) {
1182 if (const VPBasicBlock *BasicBlock = dyn_cast<VPBasicBlock>(Block))
1183 dumpBasicBlock(BasicBlock);
1184 else if (const VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
1185 dumpRegion(Region);
1186 else
1187 llvm_unreachable("Unsupported kind of VPBlock.");
1188}
1189
1190void VPlanPrinter::drawEdge(const VPBlockBase *From, const VPBlockBase *To,
1191 bool Hidden, const Twine &Label) {
1192 // Due to "dot" we print an edge between two regions as an edge between the
1193 // exiting basic block and the entry basic of the respective regions.
1194 const VPBlockBase *Tail = From->getExitingBasicBlock();
1195 const VPBlockBase *Head = To->getEntryBasicBlock();
1196 OS << Indent << getUID(Tail) << " -> " << getUID(Head);
1197 OS << " [ label=\"" << Label << '\"';
1198 if (Tail != From)
1199 OS << " ltail=" << getUID(From);
1200 if (Head != To)
1201 OS << " lhead=" << getUID(To);
1202 if (Hidden)
1203 OS << "; splines=none";
1204 OS << "]\n";
1205}
1206
1207void VPlanPrinter::dumpEdges(const VPBlockBase *Block) {
1208 auto &Successors = Block->getSuccessors();
1209 if (Successors.size() == 1)
1210 drawEdge(Block, Successors.front(), false, "");
1211 else if (Successors.size() == 2) {
1212 drawEdge(Block, Successors.front(), false, "T");
1213 drawEdge(Block, Successors.back(), false, "F");
1214 } else {
1215 unsigned SuccessorNumber = 0;
1216 for (auto *Successor : Successors)
1217 drawEdge(Block, Successor, false, Twine(SuccessorNumber++));
1218 }
1219}
1220
1221void VPlanPrinter::dumpBasicBlock(const VPBasicBlock *BasicBlock) {
1222 // Implement dot-formatted dump by performing plain-text dump into the
1223 // temporary storage followed by some post-processing.
1224 OS << Indent << getUID(BasicBlock) << " [label =\n";
1225 bumpIndent(1);
1226 std::string Str;
1228 // Use no indentation as we need to wrap the lines into quotes ourselves.
1229 BasicBlock->print(SS, "", SlotTracker);
1230
1231 // We need to process each line of the output separately, so split
1232 // single-string plain-text dump.
1234 StringRef(Str).rtrim('\n').split(Lines, "\n");
1235
1236 auto EmitLine = [&](StringRef Line, StringRef Suffix) {
1237 OS << Indent << '"' << DOT::EscapeString(Line.str()) << "\\l\"" << Suffix;
1238 };
1239
1240 // Don't need the "+" after the last line.
1241 for (auto Line : make_range(Lines.begin(), Lines.end() - 1))
1242 EmitLine(Line, " +\n");
1243 EmitLine(Lines.back(), "\n");
1244
1245 bumpIndent(-1);
1246 OS << Indent << "]\n";
1247
1249}
1250
1251void VPlanPrinter::dumpRegion(const VPRegionBlock *Region) {
1252 OS << Indent << "subgraph " << getUID(Region) << " {\n";
1253 bumpIndent(1);
1254 OS << Indent << "fontname=Courier\n"
1255 << Indent << "label=\""
1256 << DOT::EscapeString(Region->isReplicator() ? "<xVFxUF> " : "<x1> ")
1257 << DOT::EscapeString(Region->getName()) << "\"\n";
1258 // Dump the blocks of the region.
1259 assert(Region->getEntry() && "Region contains no inner blocks.");
1261 dumpBlock(Block);
1262 bumpIndent(-1);
1263 OS << Indent << "}\n";
1265}
1266
1268 if (auto *Inst = dyn_cast<Instruction>(V)) {
1269 if (!Inst->getType()->isVoidTy()) {
1270 Inst->printAsOperand(O, false);
1271 O << " = ";
1272 }
1273 O << Inst->getOpcodeName() << " ";
1274 unsigned E = Inst->getNumOperands();
1275 if (E > 0) {
1276 Inst->getOperand(0)->printAsOperand(O, false);
1277 for (unsigned I = 1; I < E; ++I)
1278 Inst->getOperand(I)->printAsOperand(O << ", ", false);
1279 }
1280 } else // !Inst
1281 V->printAsOperand(O, false);
1282}
1283
1284#endif
1285
1286template void DomTreeBuilder::Calculate<VPDominatorTree>(VPDominatorTree &DT);
1287
1289 replaceUsesWithIf(New, [](VPUser &, unsigned) { return true; });
1290}
1291
1293 VPValue *New,
1294 llvm::function_ref<bool(VPUser &U, unsigned Idx)> ShouldReplace) {
1295 // Note that this early exit is required for correctness; the implementation
1296 // below relies on the number of users for this VPValue to decrease, which
1297 // isn't the case if this == New.
1298 if (this == New)
1299 return;
1300
1301 for (unsigned J = 0; J < getNumUsers();) {
1302 VPUser *User = Users[J];
1303 bool RemovedUser = false;
1304 for (unsigned I = 0, E = User->getNumOperands(); I < E; ++I) {
1305 if (User->getOperand(I) != this || !ShouldReplace(*User, I))
1306 continue;
1307
1308 RemovedUser = true;
1309 User->setOperand(I, New);
1310 }
1311 // If a user got removed after updating the current user, the next user to
1312 // update will be moved to the current position, so we only need to
1313 // increment the index if the number of users did not change.
1314 if (!RemovedUser)
1315 J++;
1316 }
1317}
1318
1319#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1321 OS << Tracker.getOrCreateName(this);
1322}
1323
1325 interleaveComma(operands(), O, [&O, &SlotTracker](VPValue *Op) {
1326 Op->printAsOperand(O, SlotTracker);
1327 });
1328}
1329#endif
1330
1331void VPInterleavedAccessInfo::visitRegion(VPRegionBlock *Region,
1332 Old2NewTy &Old2New,
1333 InterleavedAccessInfo &IAI) {
1335 RPOT(Region->getEntry());
1336 for (VPBlockBase *Base : RPOT) {
1337 visitBlock(Base, Old2New, IAI);
1338 }
1339}
1340
1341void VPInterleavedAccessInfo::visitBlock(VPBlockBase *Block, Old2NewTy &Old2New,
1342 InterleavedAccessInfo &IAI) {
1343 if (VPBasicBlock *VPBB = dyn_cast<VPBasicBlock>(Block)) {
1344 for (VPRecipeBase &VPI : *VPBB) {
1345 if (isa<VPWidenPHIRecipe>(&VPI))
1346 continue;
1347 assert(isa<VPInstruction>(&VPI) && "Can only handle VPInstructions");
1348 auto *VPInst = cast<VPInstruction>(&VPI);
1349
1350 auto *Inst = dyn_cast_or_null<Instruction>(VPInst->getUnderlyingValue());
1351 if (!Inst)
1352 continue;
1353 auto *IG = IAI.getInterleaveGroup(Inst);
1354 if (!IG)
1355 continue;
1356
1357 auto NewIGIter = Old2New.find(IG);
1358 if (NewIGIter == Old2New.end())
1359 Old2New[IG] = new InterleaveGroup<VPInstruction>(
1360 IG->getFactor(), IG->isReverse(), IG->getAlign());
1361
1362 if (Inst == IG->getInsertPos())
1363 Old2New[IG]->setInsertPos(VPInst);
1364
1365 InterleaveGroupMap[VPInst] = Old2New[IG];
1366 InterleaveGroupMap[VPInst]->insertMember(
1367 VPInst, IG->getIndex(Inst),
1368 Align(IG->isReverse() ? (-1) * int(IG->getFactor())
1369 : IG->getFactor()));
1370 }
1371 } else if (VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
1372 visitRegion(Region, Old2New, IAI);
1373 else
1374 llvm_unreachable("Unsupported kind of VPBlock.");
1375}
1376
1378 InterleavedAccessInfo &IAI) {
1379 Old2NewTy Old2New;
1380 visitRegion(Plan.getVectorLoopRegion(), Old2New, IAI);
1381}
1382
1383void VPSlotTracker::assignName(const VPValue *V) {
1384 assert(!VPValue2Name.contains(V) && "VPValue already has a name!");
1385 auto *UV = V->getUnderlyingValue();
1386 if (!UV) {
1387 VPValue2Name[V] = (Twine("vp<%") + Twine(NextSlot) + ">").str();
1388 NextSlot++;
1389 return;
1390 }
1391
1392 // Use the name of the underlying Value, wrapped in "ir<>", and versioned by
1393 // appending ".Number" to the name if there are multiple uses.
1394 std::string Name;
1396 UV->printAsOperand(S, false);
1397 assert(!Name.empty() && "Name cannot be empty.");
1398 std::string BaseName = (Twine("ir<") + Name + Twine(">")).str();
1399
1400 // First assign the base name for V.
1401 const auto &[A, _] = VPValue2Name.insert({V, BaseName});
1402 // Integer or FP constants with different types will result in he same string
1403 // due to stripping types.
1404 if (V->isLiveIn() && isa<ConstantInt, ConstantFP>(UV))
1405 return;
1406
1407 // If it is already used by C > 0 other VPValues, increase the version counter
1408 // C and use it for V.
1409 const auto &[C, UseInserted] = BaseName2Version.insert({BaseName, 0});
1410 if (!UseInserted) {
1411 C->second++;
1412 A->second = (BaseName + Twine(".") + Twine(C->second)).str();
1413 }
1414}
1415
1416void VPSlotTracker::assignNames(const VPlan &Plan) {
1417 if (Plan.VFxUF.getNumUsers() > 0)
1418 assignName(&Plan.VFxUF);
1419 assignName(&Plan.VectorTripCount);
1420 if (Plan.BackedgeTakenCount)
1421 assignName(Plan.BackedgeTakenCount);
1422 for (VPValue *LI : Plan.VPLiveInsToFree)
1423 assignName(LI);
1424 assignNames(Plan.getPreheader());
1425
1428 for (const VPBasicBlock *VPBB :
1429 VPBlockUtils::blocksOnly<const VPBasicBlock>(RPOT))
1430 assignNames(VPBB);
1431}
1432
1433void VPSlotTracker::assignNames(const VPBasicBlock *VPBB) {
1434 for (const VPRecipeBase &Recipe : *VPBB)
1435 for (VPValue *Def : Recipe.definedValues())
1436 assignName(Def);
1437}
1438
1439std::string VPSlotTracker::getOrCreateName(const VPValue *V) const {
1440 std::string Name = VPValue2Name.lookup(V);
1441 if (!Name.empty())
1442 return Name;
1443
1444 // If no name was assigned, no VPlan was provided when creating the slot
1445 // tracker or it is not reachable from the provided VPlan. This can happen,
1446 // e.g. when trying to print a recipe that has not been inserted into a VPlan
1447 // in a debugger.
1448 // TODO: Update VPSlotTracker constructor to assign names to recipes &
1449 // VPValues not associated with a VPlan, instead of constructing names ad-hoc
1450 // here.
1451 const VPRecipeBase *DefR = V->getDefiningRecipe();
1452 (void)DefR;
1453 assert((!DefR || !DefR->getParent() || !DefR->getParent()->getPlan()) &&
1454 "VPValue defined by a recipe in a VPlan?");
1455
1456 // Use the underlying value's name, if there is one.
1457 if (auto *UV = V->getUnderlyingValue()) {
1458 std::string Name;
1460 UV->printAsOperand(S, false);
1461 return (Twine("ir<") + Name + ">").str();
1462 }
1463
1464 return "<badref>";
1465}
1466
1468 return all_of(Def->users(),
1469 [Def](const VPUser *U) { return U->onlyFirstLaneUsed(Def); });
1470}
1471
1473 return all_of(Def->users(),
1474 [Def](const VPUser *U) { return U->onlyFirstPartUsed(Def); });
1475}
1476
1478 ScalarEvolution &SE) {
1479 if (auto *Expanded = Plan.getSCEVExpansion(Expr))
1480 return Expanded;
1481 VPValue *Expanded = nullptr;
1482 if (auto *E = dyn_cast<SCEVConstant>(Expr))
1483 Expanded = Plan.getOrAddLiveIn(E->getValue());
1484 else if (auto *E = dyn_cast<SCEVUnknown>(Expr))
1485 Expanded = Plan.getOrAddLiveIn(E->getValue());
1486 else {
1487 Expanded = new VPExpandSCEVRecipe(Expr, SE);
1489 }
1490 Plan.addSCEVExpansion(Expr, Expanded);
1491 return Expanded;
1492}
1493
1495 if (isa<VPActiveLaneMaskPHIRecipe>(V))
1496 return true;
1497
1498 auto IsWideCanonicalIV = [](VPValue *A) {
1499 return isa<VPWidenCanonicalIVRecipe>(A) ||
1500 (isa<VPWidenIntOrFpInductionRecipe>(A) &&
1501 cast<VPWidenIntOrFpInductionRecipe>(A)->isCanonical());
1502 };
1503
1504 VPValue *A, *B;
1506 return B == Plan.getTripCount() &&
1508 IsWideCanonicalIV(A));
1509
1510 return match(V, m_Binary<Instruction::ICmp>(m_VPValue(A), m_VPValue(B))) &&
1511 IsWideCanonicalIV(A) && B == Plan.getOrCreateBackedgeTakenCount();
1512}
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static const Function * getParent(const Value *V)
BlockVerifier::State From
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Definition: Compiler.h:537
dxil pretty DXIL Metadata Pretty Printer
Returns the sub type a function will return at a given Idx Should correspond to the result type of an ExtractValue instruction executed with just that one unsigned Idx
#define LLVM_DEBUG(X)
Definition: Debug.h:101
std::string Name
Flatten the CFG
static void dumpEdges(CFGMST< Edge, BBInfo > &MST, GCOVFunction &GF)
Generic dominator tree construction - this file provides routines to construct immediate dominator in...
Hexagon Common GEP
#define _
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
iv Induction Variable Users
Definition: IVUsers.cpp:48
#define I(x, y, z)
Definition: MD5.cpp:58
#define P(N)
This file builds on the ADT/GraphTraits.h file to build a generic graph post order iterator.
static StringRef getName(Value *V)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file contains some templates that are useful if you are working with the STL at all.
raw_pwrite_stream & OS
This file defines the SmallVector class.
This file contains some functions that are useful when dealing with strings.
This file implements dominator tree analysis for a single level of a VPlan's H-CFG.
static T * getPlanEntry(T *Start)
Definition: VPlan.cpp:129
static void replaceVPBBWithIRVPBB(VPBasicBlock *VPBB, BasicBlock *IRBB)
Replace VPBB with a VPIRBasicBlock wrapping IRBB.
Definition: VPlan.cpp:862
static std::pair< VPBlockBase *, VPBlockBase * > cloneSESE(VPBlockBase *Entry)
Definition: VPlan.cpp:656
static bool hasConditionalTerminator(const VPBasicBlock *VPBB)
Definition: VPlan.cpp:578
static void remapOperands(VPBlockBase *Entry, VPBlockBase *NewEntry, DenseMap< VPValue *, VPValue * > &Old2NewVPValues)
Definition: VPlan.cpp:1054
This file contains the declarations of the Vectorization Plan base classes:
static bool IsCondBranch(unsigned BrOpc)
static const uint32_t IV[8]
Definition: blake3_impl.h:78
LLVM Basic Block Representation.
Definition: BasicBlock.h:61
iterator end()
Definition: BasicBlock.h:451
void print(raw_ostream &OS, AssemblyAnnotationWriter *AAW=nullptr, bool ShouldPreserveUseListOrder=false, bool IsForDebug=false) const
Print the basic block to an output stream with an optional AssemblyAnnotationWriter.
Definition: AsmWriter.cpp:4862
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition: BasicBlock.h:202
const BasicBlock * getSingleSuccessor() const
Return the successor of this block if it has a single successor.
Definition: BasicBlock.cpp:487
const Function * getParent() const
Return the enclosing method, or null if none.
Definition: BasicBlock.h:209
InstListType::iterator iterator
Instruction iterators...
Definition: BasicBlock.h:167
LLVMContext & getContext() const
Get the context in which this basic block lives.
Definition: BasicBlock.cpp:168
size_t size() const
Definition: BasicBlock.h:459
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Definition: BasicBlock.h:229
static BranchInst * Create(BasicBlock *IfTrue, InsertPosition InsertBefore=nullptr)
Debug location.
std::optional< const DILocation * > cloneByMultiplyingDuplicationFactor(unsigned DF) const
Returns a new DILocation with duplication factor DF * current duplication factor encoded in the discr...
This class represents an Operation in the Expression.
A debug info location.
Definition: DebugLoc.h:33
ValueT lookup(const_arg_type_t< KeyT > Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
Definition: DenseMap.h:202
bool contains(const_arg_type_t< KeyT > Val) const
Return true if the specified key is in the map, false otherwise.
Definition: DenseMap.h:145
Core dominator tree base class.
bool verify(VerificationLevel VL=VerificationLevel::Full) const
verify - checks if the tree is correct.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition: Dominators.h:162
constexpr bool isScalar() const
Exactly one element.
Definition: TypeSize.h:319
bool shouldEmitDebugInfoForProfiling() const
Returns true if we should emit debug info for profiling.
Definition: Metadata.cpp:1834
DomTreeT & getDomTree()
Flush DomTree updates and return DomTree.
void applyUpdates(ArrayRef< typename DomTreeT::UpdateType > Updates)
Submit updates to all available trees.
void flush()
Apply all pending updates to available trees and flush all BasicBlocks awaiting deletion.
Common base class shared among various IRBuilders.
Definition: IRBuilder.h:92
Value * CreateInsertElement(Type *VecTy, Value *NewElt, Value *Idx, const Twine &Name="")
Definition: IRBuilder.h:2470
Value * CreateExtractElement(Value *Vec, Value *Idx, const Twine &Name="")
Definition: IRBuilder.h:2458
UnreachableInst * CreateUnreachable()
Definition: IRBuilder.h:1261
Value * CreateVectorSplat(unsigned NumElts, Value *V, const Twine &Name="")
Return a vector value that contains.
Definition: IRBuilder.cpp:1192
IntegerType * getInt32Ty()
Fetch the type representing a 32-bit integer.
Definition: IRBuilder.h:524
BasicBlock * GetInsertBlock() const
Definition: IRBuilder.h:172
void SetCurrentDebugLocation(DebugLoc L)
Set location information used by debugging information.
Definition: IRBuilder.h:218
InsertPoint saveIP() const
Returns the current insert point.
Definition: IRBuilder.h:275
ConstantInt * getInt32(uint32_t C)
Get a constant 32-bit value.
Definition: IRBuilder.h:484
Value * CreateSub(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition: IRBuilder.h:1342
void restoreIP(InsertPoint IP)
Sets the current insert point to a previously-saved location.
Definition: IRBuilder.h:287
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block.
Definition: IRBuilder.h:178
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition: IRBuilder.h:2664
InnerLoopVectorizer vectorizes loops which contain only one basic block to a specified vectorization ...
void moveBefore(Instruction *MovePos)
Unlink this instruction from its current basic block and insert it into the basic block that MovePos ...
The group of interleaved loads/stores sharing the same stride and close to each other.
Definition: VectorUtils.h:453
Drive the analysis of interleaved memory accesses in the loop.
Definition: VectorUtils.h:595
InterleaveGroup< Instruction > * getInterleaveGroup(const Instruction *Instr) const
Get the interleave group that Instr belongs to.
Definition: VectorUtils.h:640
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:67
void addBasicBlockToLoop(BlockT *NewBB, LoopInfoBase< BlockT, LoopT > &LI)
This method is used by other analyses to update loop information.
void addChildLoop(LoopT *NewChild)
Add the specified loop to be a child of this loop.
void addTopLevelLoop(LoopT *New)
This adds the specified loop to the collection of top-level loops.
LoopT * AllocateLoop(ArgsTy &&...Args)
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
void annotateInstWithNoAlias(Instruction *VersionedInst, const Instruction *OrigInst)
Add the noalias annotations to VersionedInst.
Represents a single loop in the control flow graph.
Definition: LoopInfo.h:44
void eraseFromParent()
This method unlinks 'this' from the containing function and deletes it.
void dump() const
User-friendly dump.
Definition: AsmWriter.cpp:5298
static PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
Definition: Constants.cpp:1814
BlockT * getEntry() const
Get the entry BasicBlock of the Region.
Definition: RegionInfo.h:322
This class represents an analyzed expression in the program.
The main scalar evolution driver.
size_type size() const
Determine the number of elements in the SetVector.
Definition: SetVector.h:98
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition: SetVector.h:162
This class provides computation of slot numbers for LLVM Assembly writing.
Definition: AsmWriter.cpp:696
A SetVector that performs no allocations if smaller than a certain size.
Definition: SetVector.h:370
void push_back(const T &Elt)
Definition: SmallVector.h:426
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1209
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
std::pair< StringRef, StringRef > split(char Separator) const
Split into two substrings around the first occurrence of a separator character.
Definition: StringRef.h:693
StringRef rtrim(char Char) const
Return string with consecutive Char characters starting from the right removed.
Definition: StringRef.h:796
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
This function has undefined behavior.
void setOperand(unsigned i, Value *Val)
Definition: User.h:174
Value * getOperand(unsigned i) const
Definition: User.h:169
unsigned getNumOperands() const
Definition: User.h:191
VPBasicBlock serves as the leaf of the Hierarchical Control-Flow Graph.
Definition: VPlan.h:2844
void appendRecipe(VPRecipeBase *Recipe)
Augment the existing recipes of a VPBasicBlock with an additional Recipe as the last recipe.
Definition: VPlan.h:2916
VPBasicBlock * clone() override
Clone the current block and it's recipes, without updating the operands of the cloned recipes.
Definition: VPlan.h:2960
RecipeListTy::iterator iterator
Instruction iterators...
Definition: VPlan.h:2868
void execute(VPTransformState *State) override
The method which generates the output IR instructions that correspond to this VPBasicBlock,...
Definition: VPlan.cpp:476
iterator end()
Definition: VPlan.h:2878
iterator begin()
Recipe iterator methods.
Definition: VPlan.h:2876
iterator getFirstNonPhi()
Return the position of the first non-phi node recipe in the block.
Definition: VPlan.cpp:211
VPRegionBlock * getEnclosingLoopRegion()
Definition: VPlan.cpp:568
void dropAllReferences(VPValue *NewValue) override
Replace all operands of VPUsers in the block with NewValue and also replaces all uses of VPValues def...
Definition: VPlan.cpp:520
VPBasicBlock * splitAt(iterator SplitAt)
Split current block at SplitAt by inserting a new block between the current block and its successors ...
Definition: VPlan.cpp:543
void executeRecipes(VPTransformState *State, BasicBlock *BB)
Execute the recipes in the IR basic block BB.
Definition: VPlan.cpp:530
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print this VPBsicBlock to O, prefixing all lines with Indent.
Definition: VPlan.cpp:635
bool isExiting() const
Returns true if the block is exiting it's parent region.
Definition: VPlan.cpp:618
VPRecipeBase * getTerminator()
If the block has multiple successors, return the branch recipe terminating the block.
Definition: VPlan.cpp:606
const VPRecipeBase & back() const
Definition: VPlan.h:2890
bool empty() const
Definition: VPlan.h:2887
VPBlockBase is the building block of the Hierarchical Control-Flow Graph.
Definition: VPlan.h:425
void setSuccessors(ArrayRef< VPBlockBase * > NewSuccs)
Set each VPBasicBlock in NewSuccss as successor of this VPBlockBase.
Definition: VPlan.h:620
VPRegionBlock * getParent()
Definition: VPlan.h:497
const VPBasicBlock * getExitingBasicBlock() const
Definition: VPlan.cpp:176
size_t getNumSuccessors() const
Definition: VPlan.h:542
iterator_range< VPBlockBase ** > successors()
Definition: VPlan.h:525
void printSuccessors(raw_ostream &O, const Twine &Indent) const
Print the successors of this block to O, prefixing all lines with Indent.
Definition: VPlan.cpp:623
void setPredecessors(ArrayRef< VPBlockBase * > NewPreds)
Set each VPBasicBlock in NewPreds as predecessor of this VPBlockBase.
Definition: VPlan.h:611
VPBlockBase * getEnclosingBlockWithPredecessors()
Definition: VPlan.cpp:198
const VPBlocksTy & getPredecessors() const
Definition: VPlan.h:527
static void deleteCFG(VPBlockBase *Entry)
Delete all blocks reachable from a given VPBlockBase, inclusive.
Definition: VPlan.cpp:206
VPlan * getPlan()
Definition: VPlan.cpp:149
void setPlan(VPlan *ParentPlan)
Sets the pointer of the plan containing the block.
Definition: VPlan.cpp:168
VPBlockBase * getSingleHierarchicalSuccessor()
Definition: VPlan.h:568
VPBlockBase * getSinglePredecessor() const
Definition: VPlan.h:538
const VPBlocksTy & getHierarchicalSuccessors()
Definition: VPlan.h:562
VPBlockBase * getEnclosingBlockWithSuccessors()
An Enclosing Block of a block B is any block containing B, including B itself.
Definition: VPlan.cpp:190
const VPBasicBlock * getEntryBasicBlock() const
Definition: VPlan.cpp:154
Helper for GraphTraits specialization that traverses through VPRegionBlocks.
Definition: VPlanCFG.h:115
static void insertBlockAfter(VPBlockBase *NewBlock, VPBlockBase *BlockPtr)
Insert disconnected VPBlockBase NewBlock after BlockPtr.
Definition: VPlan.h:3444
static void disconnectBlocks(VPBlockBase *From, VPBlockBase *To)
Disconnect VPBlockBases From and To bi-directionally.
Definition: VPlan.h:3491
static void connectBlocks(VPBlockBase *From, VPBlockBase *To)
Connect VPBlockBases From and To bi-directionally.
Definition: VPlan.h:3480
This class augments a recipe with a set of VPValues defined by the recipe.
Definition: VPlanValue.h:308
void dump() const
Dump the VPDef to stderr (for debugging).
Definition: VPlan.cpp:110
virtual void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const =0
Each concrete VPDef prints itself.
Recipe to expand a SCEV expression.
Definition: VPlan.h:2551
A special type of VPBasicBlock that wraps an existing IR basic block.
Definition: VPlan.h:2982
void execute(VPTransformState *State) override
The method which generates the output IR instructions that correspond to this VPBasicBlock,...
Definition: VPlan.cpp:450
This is a concrete Recipe that models a single VPlan-level instruction.
Definition: VPlan.h:1180
VPInterleavedAccessInfo(VPlan &Plan, InterleavedAccessInfo &IAI)
Definition: VPlan.cpp:1377
In what follows, the term "input IR" refers to code that is fed into the vectorizer whereas the term ...
Definition: VPlan.h:144
Value * getAsRuntimeExpr(IRBuilderBase &Builder, const ElementCount &VF) const
Returns an expression describing the lane index that can be used at runtime.
Definition: VPlan.cpp:69
static VPLane getFirstLane()
Definition: VPlan.h:168
@ ScalableLast
For ScalableLast, Lane is the offset from the start of the last N-element subvector in a scalable vec...
@ First
For First, Lane is the index into the first N elements of a fixed-vector <N x <ElTy>> or a scalable v...
A value that is used outside the VPlan.
Definition: VPlan.h:686
VPRecipeBase is a base class modeling a sequence of one or more output IR instructions.
Definition: VPlan.h:726
VPBasicBlock * getParent()
Definition: VPlan.h:751
VPRegionBlock represents a collection of VPBasicBlocks and VPRegionBlocks which form a Single-Entry-S...
Definition: VPlan.h:3019
VPRegionBlock * clone() override
Clone all blocks in the single-entry single-exit region of the block and their recipes without updati...
Definition: VPlan.cpp:703
const VPBlockBase * getEntry() const
Definition: VPlan.h:3058
bool isReplicator() const
An indicator whether this region is to generate multiple replicated instances of output IR correspond...
Definition: VPlan.h:3090
void dropAllReferences(VPValue *NewValue) override
Replace all operands of VPUsers in the block with NewValue and also replaces all uses of VPValues def...
Definition: VPlan.cpp:712
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print this VPRegionBlock to O (recursively), prefixing all lines with Indent.
Definition: VPlan.cpp:771
void execute(VPTransformState *State) override
The method which generates the output IR instructions that correspond to this VPRegionBlock,...
Definition: VPlan.cpp:719
const VPBlockBase * getExiting() const
Definition: VPlan.h:3070
VPBasicBlock * getPreheaderVPBB()
Returns the pre-header VPBasicBlock of the loop region.
Definition: VPlan.h:3083
This class can be used to assign names to VPValues.
Definition: VPlanValue.h:449
std::string getOrCreateName(const VPValue *V) const
Returns the name assigned to V, if there is one, otherwise try to construct one from the underlying v...
Definition: VPlan.cpp:1439
This class augments VPValue with operands which provide the inverse def-use edges from VPValue's user...
Definition: VPlanValue.h:203
void printOperands(raw_ostream &O, VPSlotTracker &SlotTracker) const
Print the operands to O.
Definition: VPlan.cpp:1324
VPRecipeBase * getDefiningRecipe()
Returns the recipe defining this VPValue or nullptr if it is not defined by a recipe,...
Definition: VPlan.cpp:119
void printAsOperand(raw_ostream &OS, VPSlotTracker &Tracker) const
Definition: VPlan.cpp:1320
void dump() const
Dump the value to stderr (for debugging).
Definition: VPlan.cpp:102
VPValue(const unsigned char SC, Value *UV=nullptr, VPDef *Def=nullptr)
Definition: VPlan.cpp:82
virtual ~VPValue()
Definition: VPlan.cpp:88
void print(raw_ostream &OS, VPSlotTracker &Tracker) const
Definition: VPlan.cpp:95
void replaceAllUsesWith(VPValue *New)
Definition: VPlan.cpp:1288
unsigned getNumUsers() const
Definition: VPlanValue.h:112
void replaceUsesWithIf(VPValue *New, llvm::function_ref< bool(VPUser &U, unsigned Idx)> ShouldReplace)
Go through the uses list for this VPValue and make each use point to New if the callback ShouldReplac...
Definition: VPlan.cpp:1292
VPDef * Def
Pointer to the VPDef that defines this VPValue.
Definition: VPlanValue.h:64
VPlanPrinter prints a given VPlan to a given output stream.
Definition: VPlan.h:3364
LLVM_DUMP_METHOD void dump()
Definition: VPlan.cpp:1149
VPlan models a candidate for vectorization, encoding various decisions take to produce efficient outp...
Definition: VPlan.h:3120
void printDOT(raw_ostream &O) const
Print this VPlan in DOT format to O.
Definition: VPlan.cpp:1040
std::string getName() const
Return a string with the name of the plan and the applicable VFs and UFs.
Definition: VPlan.cpp:1016
void prepareToExecute(Value *TripCount, Value *VectorTripCount, Value *CanonicalIVStartValue, VPTransformState &State)
Prepare the plan for execution, setting up the required live-in values.
Definition: VPlan.cpp:821
VPBasicBlock * getEntry()
Definition: VPlan.h:3215
VPValue * getTripCount() const
The trip count of the original loop.
Definition: VPlan.h:3219
VPValue * getOrCreateBackedgeTakenCount()
The backedge taken count of the original loop.
Definition: VPlan.h:3233
void addLiveOut(PHINode *PN, VPValue *V)
Definition: VPlan.cpp:1049
VPBasicBlock * getPreheader()
Definition: VPlan.h:3353
VPRegionBlock * getVectorLoopRegion()
Returns the VPRegionBlock of the vector loop.
Definition: VPlan.h:3315
void addSCEVExpansion(const SCEV *S, VPValue *V)
Definition: VPlan.h:3347
VPValue * getOrAddLiveIn(Value *V)
Gets the live-in VPValue for V or adds a new live-in (if none exists yet) for V.
Definition: VPlan.h:3281
LLVM_DUMP_METHOD void dump() const
Dump the plan to stderr (for debugging).
Definition: VPlan.cpp:1046
void execute(VPTransformState *State)
Generate the IR code for this VPlan.
Definition: VPlan.cpp:876
void print(raw_ostream &O) const
Print this VPlan to O.
Definition: VPlan.cpp:990
VPValue * getSCEVExpansion(const SCEV *S) const
Definition: VPlan.h:3343
void printLiveIns(raw_ostream &O) const
Print the live-ins of this VPlan to O.
Definition: VPlan.cpp:960
static VPlanPtr createInitialVPlan(const SCEV *TripCount, ScalarEvolution &PSE, BasicBlock *PH)
Create initial VPlan skeleton, having an "entry" VPBasicBlock (wrapping original scalar pre-header PH...
Definition: VPlan.cpp:806
VPlan * duplicate()
Clone the current VPlan, update all VPValues of the new VPlan and cloned recipes to refer to the clon...
Definition: VPlan.cpp:1092
LLVM Value Representation.
Definition: Value.h:74
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:255
StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:309
static VectorType * get(Type *ElementType, ElementCount EC)
This static method is the primary way to construct an VectorType.
Definition: Type.cpp:676
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition: TypeSize.h:171
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
Definition: TypeSize.h:168
An efficient, type-erasing, non-owning reference to a callable.
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:52
A raw_ostream that writes to an std::string.
Definition: raw_ostream.h:661
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ Tail
Attemps to make calls as fast as possible while guaranteeing that tail call optimization can always b...
Definition: CallingConv.h:76
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
std::string EscapeString(const std::string &Label)
Definition: GraphWriter.cpp:56
specific_intval< false > m_SpecificInt(const APInt &V)
Match a specific integer value or vector with all elements equal to the value.
Definition: PatternMatch.h:972
bool match(Val *V, const Pattern &P)
Definition: PatternMatch.h:49
BinaryVPInstruction_match< Op0_t, Op1_t, VPInstruction::ActiveLaneMask > m_ActiveLaneMask(const Op0_t &Op0, const Op1_t &Op1)
VPCanonicalIVPHI_match m_CanonicalIV()
VPScalarIVSteps_match< Op0_t, Op1_t > m_ScalarIVSteps(const Op0_t &Op0, const Op1_t &Op1)
BinaryVPInstruction_match< Op0_t, Op1_t, VPInstruction::BranchOnCount > m_BranchOnCount(const Op0_t &Op0, const Op1_t &Op1)
UnaryVPInstruction_match< Op0_t, VPInstruction::BranchOnCond > m_BranchOnCond(const Op0_t &Op0)
class_match< VPValue > m_VPValue()
Match an arbitrary VPValue and ignore it.
@ SS
Definition: X86.h:207
VPValue * getOrCreateVPValueForSCEVExpr(VPlan &Plan, const SCEV *Expr, ScalarEvolution &SE)
Get or create a VPValue that corresponds to the expansion of Expr.
Definition: VPlan.cpp:1477
bool isUniformAfterVectorization(VPValue *VPV)
Returns true if VPV is uniform after vectorization.
Definition: VPlan.h:3668
bool onlyFirstPartUsed(const VPValue *Def)
Returns true if only the first part of Def is used.
Definition: VPlan.cpp:1472
bool onlyFirstLaneUsed(const VPValue *Def)
Returns true if only the first lane of Def is used.
Definition: VPlan.cpp:1467
bool isHeaderMask(VPValue *V, VPlan &Plan)
Return true if V is a header mask in Plan.
Definition: VPlan.cpp:1494
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition: STLExtras.h:329
detail::zippy< detail::zip_shortest, T, U, Args... > zip(T &&t, U &&u, Args &&...args)
zip iterator for two or more iteratable types.
Definition: STLExtras.h:853
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1722
auto successors(const MachineBasicBlock *BB)
Value * getRuntimeVF(IRBuilderBase &B, Type *Ty, ElementCount VF)
Return the runtime value for VF.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
void interleaveComma(const Container &c, StreamT &os, UnaryFunctor each_fn)
Definition: STLExtras.h:2159
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition: STLExtras.h:656
iterator_range< df_iterator< VPBlockShallowTraversalWrapper< VPBlockBase * > > > vp_depth_first_shallow(VPBlockBase *G)
Returns an iterator range to traverse the graph starting at G in depth-first order.
Definition: VPlanCFG.h:214
Instruction * propagateMetadata(Instruction *I, ArrayRef< Value * > VL)
Specifically, let Kinds = [MD_tbaa, MD_alias_scope, MD_noalias, MD_fpmath, MD_nontemporal,...
Printable print(const GCNRegPressure &RP, const GCNSubtarget *ST=nullptr)
cl::opt< bool > EnableFSDiscriminator
cl::opt< bool > EnableVPlanNativePath("enable-vplan-native-path", cl::Hidden, cl::desc("Enable VPlan-native vectorization path with " "support for outer loop vectorization."))
Definition: VPlan.cpp:54
std::unique_ptr< VPlan > VPlanPtr
Definition: VPlan.h:135
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
SmallVector< ValueTypeFromRangeType< R >, Size > to_vector(R &&Range)
Given a range of type R, iterate the entire range and return a SmallVector with elements of the vecto...
Definition: SmallVector.h:1312
raw_ostream & operator<<(raw_ostream &OS, const APFixedPoint &FX)
Definition: APFixedPoint.h:293
Value * createStepForVF(IRBuilderBase &B, Type *Ty, ElementCount VF, int64_t Step)
Return a value for Step multiplied by VF.
BasicBlock * SplitBlock(BasicBlock *Old, BasicBlock::iterator SplitPt, DominatorTree *DT, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, const Twine &BBName="", bool Before=false)
Split the specified block at the specified instruction.
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition: Alignment.h:39
VPIteration represents a single point in the iteration space of the output (vectorized and/or unrolle...
Definition: VPlan.h:226
Hold state information used when constructing the CFG of the output IR, traversing the VPBasicBlocks ...
Definition: VPlan.h:366
BasicBlock * PrevBB
The previous IR BasicBlock created or used.
Definition: VPlan.h:372
SmallDenseMap< VPBasicBlock *, BasicBlock * > VPBB2IRBB
A mapping of each VPBasicBlock to the corresponding BasicBlock.
Definition: VPlan.h:380
VPBasicBlock * PrevVPBB
The previous VPBasicBlock visited. Initially set to null.
Definition: VPlan.h:368
BasicBlock * ExitBB
The last IR BasicBlock in the output IR.
Definition: VPlan.h:376
BasicBlock * getPreheaderBBFor(VPRecipeBase *R)
Returns the BasicBlock* mapped to the pre-header of the loop region containing R.
Definition: VPlan.cpp:354
DomTreeUpdater DTU
Updater for the DominatorTree.
Definition: VPlan.h:383
DenseMap< VPValue *, ScalarsPerPartValuesTy > PerPartScalars
Definition: VPlan.h:266
DenseMap< VPValue *, PerPartValuesTy > PerPartOutput
Definition: VPlan.h:263
VPTransformState holds information passed down when "executing" a VPlan, needed for generating the ou...
Definition: VPlan.h:243
Value * get(VPValue *Def, unsigned Part, bool IsScalar=false)
Get the generated vector Value for a given VPValue Def and a given Part if IsScalar is false,...
Definition: VPlan.cpp:253
LoopInfo * LI
Hold a pointer to LoopInfo to register new basic blocks in the loop.
Definition: VPlan.h:394
VPTransformState(ElementCount VF, unsigned UF, LoopInfo *LI, DominatorTree *DT, IRBuilderBase &Builder, InnerLoopVectorizer *ILV, VPlan *Plan, LLVMContext &Ctx)
Definition: VPlan.cpp:218
struct llvm::VPTransformState::DataState Data
void addMetadata(Value *To, Instruction *From)
Add metadata from one instruction to another.
Definition: VPlan.cpp:367
struct llvm::VPTransformState::CFGState CFG
LoopVersioning * LVer
LoopVersioning.
Definition: VPlan.h:413
void addNewMetadata(Instruction *To, const Instruction *Orig)
Add additional metadata to To that was not present on Orig.
Definition: VPlan.cpp:359
void packScalarIntoVectorValue(VPValue *Def, const VPIteration &Instance)
Construct the vector value of a scalarized value V one lane at a time.
Definition: VPlan.cpp:399
void set(VPValue *Def, Value *V, unsigned Part, bool IsScalar=false)
Set the generated vector Value for a given VPValue and a given Part, if IsScalar is false.
Definition: VPlan.h:295
std::optional< VPIteration > Instance
Hold the indices to generate specific scalar instructions.
Definition: VPlan.h:255
IRBuilderBase & Builder
Hold a reference to the IRBuilder used to generate output IR code.
Definition: VPlan.h:397
bool hasScalarValue(VPValue *Def, VPIteration Instance)
Definition: VPlan.h:283
VPlan * Plan
Pointer to the VPlan code is generated for.
Definition: VPlan.h:403
bool hasVectorValue(VPValue *Def, unsigned Part)
Definition: VPlan.h:277
ElementCount VF
The chosen Vectorization and Unroll Factors of the loop being vectorized.
Definition: VPlan.h:249
Loop * CurrentVectorLoop
The loop object for the current parent region, or nullptr.
Definition: VPlan.h:406
void setDebugLocFrom(DebugLoc DL)
Set the debug location in the builder using the debug location DL.
Definition: VPlan.cpp:378
void print(raw_ostream &O) const
Definition: VPlan.cpp:1267