LLVM 24.0.0git
VPlanConstruction.cpp
Go to the documentation of this file.
1//===-- VPlanConstruction.cpp - Transforms for initial VPlan construction -===//
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 file implements transforms for initial VPlan construction.
11///
12//===----------------------------------------------------------------------===//
13
15#include "VPlan.h"
16#include "VPlanAnalysis.h"
17#include "VPlanCFG.h"
18#include "VPlanDominatorTree.h"
19#include "VPlanHelpers.h"
20#include "VPlanPatternMatch.h"
21#include "VPlanTransforms.h"
22#include "VPlanUtils.h"
23#include "llvm/ADT/Sequence.h"
26#include "llvm/Analysis/Loads.h"
33#include "llvm/IR/InstrTypes.h"
34#include "llvm/IR/MDBuilder.h"
35#include "llvm/Support/Debug.h"
39
40#define DEBUG_TYPE "vplan"
41
42using namespace llvm;
43using namespace LoopVectorizationUtils;
44using namespace VPlanPatternMatch;
45
46namespace {
47// Class that is used to build the plain CFG for the incoming IR.
48class PlainCFGBuilder {
49 // The outermost loop of the input loop nest considered for vectorization.
50 Loop *TheLoop;
51
52 // Loop Info analysis.
53 LoopInfo *LI;
54
55 // Loop versioning for alias metadata.
56 LoopVersioning *LVer;
57
58 // Lazily provides branch probabilities for the incoming IR.
59 function_ref<const BranchProbabilityInfo &()> GetBPI;
60
61 // The BranchProbabilityInfo returned by GetBPI, cached on first use.
62 const BranchProbabilityInfo *BPI = nullptr;
63
64 // Vectorization plan that we are working on.
65 std::unique_ptr<VPlan> Plan;
66
67 // Builder of the VPlan instruction-level representation.
68 VPBuilder VPIRBuilder;
69
70 // NOTE: The following maps are intentionally destroyed after the plain CFG
71 // construction because subsequent VPlan-to-VPlan transformation may
72 // invalidate them.
73 // Map incoming BasicBlocks to their newly-created VPBasicBlocks.
75 // Map incoming Value definitions to their newly-created VPValues.
76 DenseMap<Value *, VPValue *> IRDef2VPValue;
77
78 // Hold phi node's that need to be fixed once the plain CFG has been built.
80
81 // Utility functions.
82 void setVPBBPredsFromBB(VPBasicBlock *VPBB, BasicBlock *BB);
83 void fixHeaderPhis();
84 VPBasicBlock *getOrCreateVPBB(BasicBlock *BB);
85#ifndef NDEBUG
86 bool isExternalDef(Value *Val);
87#endif
88 VPValue *getOrCreateVPOperand(Value *IRVal);
89 void createVPInstructionsForVPBB(VPBasicBlock *VPBB, BasicBlock *BB);
90 VPIRMetadata getTerminatorMetadata(Instruction &Term);
91
92public:
93 PlainCFGBuilder(Loop *Lp, LoopInfo *LI, LoopVersioning *LVer, Type *IdxTy,
94 function_ref<const BranchProbabilityInfo &()> GetBPI)
95 : TheLoop(Lp), LI(LI), LVer(LVer), GetBPI(GetBPI),
96 Plan(std::make_unique<VPlan>(Lp, IdxTy)) {}
97
98 /// Build plain CFG for TheLoop and connect it to Plan's entry.
99 std::unique_ptr<VPlan> buildPlainCFG();
100};
101} // anonymous namespace
102
103// Set predecessors of \p VPBB in the same order as they are in \p BB. \p VPBB
104// must have no predecessors.
105void PlainCFGBuilder::setVPBBPredsFromBB(VPBasicBlock *VPBB, BasicBlock *BB) {
106 // Collect VPBB predecessors.
108 for (BasicBlock *Pred : predecessors(BB))
109 VPBBPreds.push_back(getOrCreateVPBB(Pred));
110 VPBB->setPredecessors(VPBBPreds);
111}
112
113static bool isHeaderBB(BasicBlock *BB, Loop *L) {
114 return L && BB == L->getHeader();
115}
116
117// Add operands to VPInstructions representing phi nodes from the input IR.
118void PlainCFGBuilder::fixHeaderPhis() {
119 for (auto *Phi : PhisToFix) {
120 assert(IRDef2VPValue.count(Phi) && "Missing VPInstruction for PHINode.");
121 VPValue *VPVal = IRDef2VPValue[Phi];
122 assert(isa<VPPhi>(VPVal) && "Expected VPPhi for phi node.");
123 auto *PhiR = cast<VPPhi>(VPVal);
124 assert(PhiR->getNumOperands() == 0 && "Expected VPPhi with no operands.");
125 assert(isHeaderBB(Phi->getParent(), LI->getLoopFor(Phi->getParent())) &&
126 "Expected Phi in header block.");
127 assert(Phi->getNumOperands() == 2 &&
128 "header phi must have exactly 2 operands");
129 for (BasicBlock *Pred : predecessors(Phi->getParent()))
130 PhiR->addIncoming(
131 getOrCreateVPOperand(Phi->getIncomingValueForBlock(Pred)));
132 }
133}
134
135// Create a new empty VPBasicBlock for an incoming BasicBlock or retrieve an
136// existing one if it was already created.
137VPBasicBlock *PlainCFGBuilder::getOrCreateVPBB(BasicBlock *BB) {
138 if (auto *VPBB = BB2VPBB.lookup(BB)) {
139 // Retrieve existing VPBB.
140 return VPBB;
141 }
142
143 // Create new VPBB.
144 StringRef Name = BB->getName();
145 LLVM_DEBUG(dbgs() << "Creating VPBasicBlock for " << Name << "\n");
146 VPBasicBlock *VPBB = Plan->createVPBasicBlock(Name);
147 BB2VPBB[BB] = VPBB;
148 return VPBB;
149}
150
151#ifndef NDEBUG
152// Return true if \p Val is considered an external definition. An external
153// definition is either:
154// 1. A Value that is not an Instruction. This will be refined in the future.
155// 2. An Instruction that is outside of the IR region represented in VPlan,
156// i.e., is not part of the loop nest.
157bool PlainCFGBuilder::isExternalDef(Value *Val) {
158 // All the Values that are not Instructions are considered external
159 // definitions for now.
161 if (!Inst)
162 return true;
163
164 // Check whether Instruction definition is in loop body.
165 return !TheLoop->contains(Inst);
166}
167#endif
168
169// Create a new VPValue or retrieve an existing one for the Instruction's
170// operand \p IRVal. This function must only be used to create/retrieve VPValues
171// for *Instruction's operands* and not to create regular VPInstruction's. For
172// the latter, please, look at 'createVPInstructionsForVPBB'.
173VPValue *PlainCFGBuilder::getOrCreateVPOperand(Value *IRVal) {
174 auto VPValIt = IRDef2VPValue.find(IRVal);
175 if (VPValIt != IRDef2VPValue.end())
176 // Operand has an associated VPInstruction or VPValue that was previously
177 // created.
178 return VPValIt->second;
179
180 // Operand doesn't have a previously created VPInstruction/VPValue. This
181 // means that operand is:
182 // A) a definition external to VPlan,
183 // B) any other Value without specific representation in VPlan.
184 // For now, we use VPValue to represent A and B and classify both as external
185 // definitions. We may introduce specific VPValue subclasses for them in the
186 // future.
187 assert(isExternalDef(IRVal) && "Expected external definition as operand.");
188
189 // A and B: Create VPValue and add it to the pool of external definitions and
190 // to the Value->VPValue map.
191 VPValue *NewVPVal = Plan->getOrAddLiveIn(IRVal);
192 IRDef2VPValue[IRVal] = NewVPVal;
193 return NewVPVal;
194}
195
196// Returns the metadata to preserve for terminator \p Term.
197VPIRMetadata PlainCFGBuilder::getTerminatorMetadata(Instruction &Term) {
198 VPIRMetadata MD(Term);
199 if (MD.getMetadata(LLVMContext::MD_prof))
200 return MD;
201 // Estimates are only read for edges inside the loop region.
202 if (!TheLoop->isInnermost() || Term.getParent() == TheLoop->getLoopLatch())
203 return MD;
204 // The weights describe the edges leaving Term in the order of its successors,
205 // matching the successor order of the VPBasicBlock created for Term's parent.
206 if (!BPI)
207 BPI = &GetBPI();
208 auto Weights = map_to_vector(seq(Term.getNumSuccessors()), [&](unsigned I) {
209 return BPI->getEdgeProbability(Term.getParent(), I).getNumerator();
210 });
211 MD.setEstimatedBranchWeights(
212 MDBuilder(Plan->getContext()).createBranchWeights(Weights));
213 return MD;
214}
215
216// Create new VPInstructions in a VPBasicBlock, given its BasicBlock
217// counterpart. This function must be invoked in RPO so that the operands of a
218// VPInstruction in \p BB have been visited before (except for Phi nodes).
219void PlainCFGBuilder::createVPInstructionsForVPBB(VPBasicBlock *VPBB,
220 BasicBlock *BB) {
221 VPIRBuilder.setInsertPoint(VPBB);
222 // TODO: Model and preserve debug intrinsics in VPlan.
223 for (Instruction &InstRef : *BB) {
224 Instruction *Inst = &InstRef;
225
226 // There shouldn't be any VPValue for Inst at this point. Otherwise, we
227 // visited Inst when we shouldn't, breaking the RPO traversal order.
228 assert(!IRDef2VPValue.count(Inst) &&
229 "Instruction shouldn't have been visited.");
230
231 if (isa<UncondBrInst>(Inst))
232 // Skip the rest of the Instruction processing for Branch instructions.
233 continue;
234
235 if (auto *Br = dyn_cast<CondBrInst>(Inst)) {
236 // Conditional branch instruction are represented using BranchOnCond
237 // recipes.
238 VPValue *Cond = getOrCreateVPOperand(Br->getCondition());
239 VPIRBuilder.createNaryOp(VPInstruction::BranchOnCond, {Cond}, Inst, {},
240 getTerminatorMetadata(*Inst),
241 Inst->getDebugLoc());
242 continue;
243 }
244
245 if (auto *SI = dyn_cast<SwitchInst>(Inst)) {
246 // Don't emit recipes for unconditional switch instructions.
247 if (SI->getNumCases() == 0)
248 continue;
249 SmallVector<VPValue *> Ops = {getOrCreateVPOperand(SI->getCondition())};
250 for (auto Case : SI->cases())
251 Ops.push_back(getOrCreateVPOperand(Case.getCaseValue()));
252 VPIRBuilder.createNaryOp(Instruction::Switch, Ops, Inst, {},
253 getTerminatorMetadata(*Inst),
254 Inst->getDebugLoc());
255 continue;
256 }
257
258 VPSingleDefRecipe *NewR;
259 if (auto *Phi = dyn_cast<PHINode>(Inst)) {
260 // Phi node's operands may not have been visited at this point. We create
261 // an empty VPInstruction that we will fix once the whole plain CFG has
262 // been built.
263 NewR = VPIRBuilder.createScalarPhi({}, Phi->getDebugLoc(), "vec.phi",
264 *Phi, Phi->getType());
265 NewR->setUnderlyingValue(Phi);
266 if (isHeaderBB(Phi->getParent(), LI->getLoopFor(Phi->getParent()))) {
267 // Header phis need to be fixed after the VPBB for the latch has been
268 // created.
269 PhisToFix.push_back(Phi);
270 } else {
271 // Add operands for VPPhi in the order matching its predecessors in
272 // VPlan.
273 DenseMap<const VPBasicBlock *, VPValue *> VPPredToIncomingValue;
274 for (unsigned I = 0; I != Phi->getNumOperands(); ++I) {
275 VPPredToIncomingValue[BB2VPBB[Phi->getIncomingBlock(I)]] =
276 getOrCreateVPOperand(Phi->getIncomingValue(I));
277 }
278 for (VPBlockBase *Pred : VPBB->getPredecessors())
279 cast<VPPhi>(NewR)->addIncoming(
280 VPPredToIncomingValue.lookup(Pred->getExitingBasicBlock()));
281 }
282 } else {
283 // Build VPIRMetadata from the instruction and add loop versioning
284 // metadata for loads and stores.
285 VPIRMetadata MD(*Inst);
286 if (isa<LoadInst, StoreInst>(Inst) && LVer) {
287 const auto &[AliasScopeMD, NoAliasMD] =
288 LVer->getNoAliasMetadataFor(Inst);
289 if (AliasScopeMD)
290 MD.setMetadata(LLVMContext::MD_alias_scope, AliasScopeMD);
291 if (NoAliasMD)
292 MD.setMetadata(LLVMContext::MD_noalias, NoAliasMD);
293 }
294
296 "legality must reject aggregate-producing insertvalue");
297 // Translate LLVM-IR operands into VPValue operands and set them in the
298 // new VPInstruction.
299 SmallVector<VPValue *, 4> VPOperands;
300 for (Value *Op : Inst->operands())
301 VPOperands.push_back(getOrCreateVPOperand(Op));
302 if (auto *EVI = dyn_cast<ExtractValueInst>(Inst))
303 for (unsigned Idx : EVI->indices())
304 VPOperands.push_back(Plan->getConstantInt(32, Idx));
305 VPIRAttributes Attrs;
306 if (auto *CI = dyn_cast<CallInst>(Inst))
307 Attrs = VPIRAttributes(CI->getAttributes());
308 NewR = VPIRBuilder.createNaryOp(Inst->getOpcode(), VPOperands, Inst,
309 VPIRFlags(*Inst), MD, Inst->getDebugLoc(),
310 "", Inst->getType(), Attrs);
311 }
312
313 IRDef2VPValue[Inst] = NewR;
314 }
315}
316
317// Main interface to build the plain CFG.
318std::unique_ptr<VPlan> PlainCFGBuilder::buildPlainCFG() {
319 VPIRBasicBlock *Entry = cast<VPIRBasicBlock>(Plan->getEntry());
320 BB2VPBB[Entry->getIRBasicBlock()] = Entry;
321 for (VPIRBasicBlock *ExitVPBB : Plan->getExitBlocks())
322 BB2VPBB[ExitVPBB->getIRBasicBlock()] = ExitVPBB;
323
324 // 1. Scan the body of the loop in a topological order to visit each basic
325 // block after having visited its predecessor basic blocks. Create a VPBB for
326 // each BB and link it to its successor and predecessor VPBBs. Note that
327 // predecessors must be set in the same order as they are in the incomming IR.
328 // Otherwise, there might be problems with existing phi nodes and algorithm
329 // based on predecessors traversal.
330
331 // Loop PH needs to be explicitly visited since it's not taken into account by
332 // LoopBlocksDFS.
333 BasicBlock *ThePreheaderBB = TheLoop->getLoopPreheader();
334 assert((ThePreheaderBB->getTerminator()->getNumSuccessors() == 1) &&
335 "Unexpected loop preheader");
336 for (auto &I : *ThePreheaderBB) {
337 if (I.getType()->isVoidTy())
338 continue;
339 IRDef2VPValue[&I] = Plan->getOrAddLiveIn(&I);
340 }
341
342 LoopBlocksRPO RPO(TheLoop);
343 RPO.perform(LI);
344
345 for (BasicBlock *BB : RPO) {
346 // Create or retrieve the VPBasicBlock for this BB.
347 VPBasicBlock *VPBB = getOrCreateVPBB(BB);
348 // Set VPBB predecessors in the same order as they are in the incoming BB.
349 setVPBBPredsFromBB(VPBB, BB);
350
351 // Create VPInstructions for BB.
352 createVPInstructionsForVPBB(VPBB, BB);
353
354 // Set VPBB successors. We create empty VPBBs for successors if they don't
355 // exist already. Recipes will be created when the successor is visited
356 // during the RPO traversal.
357 if (auto *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
359 getOrCreateVPBB(SI->getDefaultDest())};
360 for (auto Case : SI->cases())
361 Succs.push_back(getOrCreateVPBB(Case.getCaseSuccessor()));
362 VPBB->setSuccessors(Succs);
363 continue;
364 }
365 if (auto *BI = dyn_cast<UncondBrInst>(BB->getTerminator())) {
366 VPBB->setOneSuccessor(getOrCreateVPBB(BI->getSuccessor()));
367 continue;
368 }
369 auto *BI = cast<CondBrInst>(BB->getTerminator());
370 BasicBlock *IRSucc0 = BI->getSuccessor(0);
371 BasicBlock *IRSucc1 = BI->getSuccessor(1);
372 VPBasicBlock *Successor0 = getOrCreateVPBB(IRSucc0);
373 VPBasicBlock *Successor1 = getOrCreateVPBB(IRSucc1);
374 VPBB->setTwoSuccessors(Successor0, Successor1);
375 }
376
377 for (auto *EB : Plan->getExitBlocks())
378 setVPBBPredsFromBB(EB, EB->getIRBasicBlock());
379
380 // 2. The whole CFG has been built at this point so all the input Values must
381 // have a VPlan counterpart. Fix VPlan header phi by adding their
382 // corresponding VPlan operands.
383 fixHeaderPhis();
384
385 Plan->getEntry()->setOneSuccessor(getOrCreateVPBB(TheLoop->getHeader()));
386 Plan->getEntry()->setPlan(&*Plan);
387
388 // Fix VPlan loop-closed-ssa exit phi's by adding incoming operands to the
389 // VPIRInstructions wrapping them.
390 // // Note that the operand order corresponds to IR predecessor order, and may
391 // need adjusting when VPlan predecessors are added, if an exit block has
392 // multiple predecessor.
393 for (auto *EB : Plan->getExitBlocks()) {
394 for (VPRecipeBase &R : EB->phis()) {
395 auto *PhiR = cast<VPIRPhi>(&R);
396 PHINode &Phi = PhiR->getIRPhi();
397 assert(PhiR->getNumOperands() == 0 &&
398 "no phi operands should be added yet");
399 for (BasicBlock *Pred : predecessors(EB->getIRBasicBlock()))
400 PhiR->addIncoming(
401 getOrCreateVPOperand(Phi.getIncomingValueForBlock(Pred)));
402 }
403 }
404
405 LLVM_DEBUG(Plan->setName("Plain CFG\n"); dbgs() << *Plan);
406 return std::move(Plan);
407}
408
409/// Checks if \p HeaderVPB is a loop header block in the plain CFG; that is, it
410/// has exactly 2 predecessors (preheader and latch), where the block
411/// dominates the latch and the preheader dominates the block. If it is a
412/// header block return true and canonicalize the predecessors of the header
413/// (making sure the preheader appears first and the latch second) and the
414/// successors of the latch (making sure the loop exit comes first). Otherwise
415/// return false.
417 const VPDominatorTree &VPDT) {
418 ArrayRef<VPBlockBase *> Preds = HeaderVPB->getPredecessors();
419 if (Preds.size() != 2)
420 return false;
421
422 auto *PreheaderVPBB = Preds[0];
423 auto *LatchVPBB = Preds[1];
424 if (!VPDT.dominates(PreheaderVPBB, HeaderVPB) ||
425 !VPDT.dominates(HeaderVPB, LatchVPBB)) {
426 std::swap(PreheaderVPBB, LatchVPBB);
427
428 if (!VPDT.dominates(PreheaderVPBB, HeaderVPB) ||
429 !VPDT.dominates(HeaderVPB, LatchVPBB))
430 return false;
431
432 // Canonicalize predecessors of header so that preheader is first and
433 // latch second.
434 HeaderVPB->swapPredecessors();
435 for (VPRecipeBase &R : cast<VPBasicBlock>(HeaderVPB)->phis())
436 R.swapOperands();
437 }
438
439 // The two successors of conditional branch match the condition, with the
440 // first successor corresponding to true and the second to false. We
441 // canonicalize the successors of the latch when introducing the region, such
442 // that the latch exits the region when its condition is true; invert the
443 // original condition if the original CFG branches to the header on true.
444 // Note that the exit edge is not yet connected for top-level loops.
445 if (LatchVPBB->getSingleSuccessor() ||
446 LatchVPBB->getSuccessors()[0] != HeaderVPB)
447 return true;
448
449 assert(LatchVPBB->getNumSuccessors() == 2 && "Must have 2 successors");
450 auto *Term = cast<VPBasicBlock>(LatchVPBB)->getTerminator();
451 assert(cast<VPInstruction>(Term)->getOpcode() ==
453 "terminator must be a BranchOnCond");
454 auto *Not = new VPInstruction(VPInstruction::Not, {Term->getOperand(0)});
455 Not->insertBefore(Term);
456 Term->setOperand(0, Not);
457 LatchVPBB->swapSuccessors();
458
459 return true;
460}
461
462/// Create a new VPRegionBlock for the loop starting at \p HeaderVPB. For the
463/// outermost loop adjust the regions exiting terminator to be based on the
464/// canonical IV.
465static void createLoopRegion(VPlan &Plan, VPBlockBase *HeaderVPB, DebugLoc DL) {
466 auto *PreheaderVPBB = HeaderVPB->getPredecessors()[0];
467 auto *LatchVPBB = cast<VPBasicBlock>(HeaderVPB->getPredecessors()[1]);
468 auto *OutermostHeaderVPBB =
470
471 VPBlockUtils::disconnectBlocks(PreheaderVPBB, HeaderVPB);
472 VPBlockUtils::disconnectBlocks(LatchVPBB, HeaderVPB);
473
474 // Create an empty region first and insert it between PreheaderVPBB and
475 // the exit blocks, taking care to preserve the original predecessor &
476 // successor order of blocks. Set region entry and exiting after both
477 // HeaderVPB and LatchVPBB have been disconnected from their
478 // predecessors/successors. Only the outermost loop has a canonical IV. Nested
479 // loops are assigned a canonical IV of null type and unknown debug location.
480 bool IsOutermost = HeaderVPB == OutermostHeaderVPBB;
481 Type *CanIVTy = nullptr;
482 if (IsOutermost)
483 CanIVTy = Plan.getVectorTripCount().getType();
484 else
486 auto *R = Plan.createLoopRegion(CanIVTy, DL);
487
488 // Transfer latch's successors to the region.
490
491 VPBlockUtils::connectBlocks(PreheaderVPBB, R);
492 R->setEntry(HeaderVPB);
493 R->setExiting(LatchVPBB);
494
495 // All VPBB's reachable shallowly from HeaderVPB belong to the current region.
496 for (VPBlockBase *VPBB : vp_depth_first_shallow(HeaderVPB))
497 VPBB->setParent(R);
498
499 if (!IsOutermost)
500 return;
501
502 auto *LatchTerm = LatchVPBB->getTerminator();
503 VPBuilder Builder(LatchTerm);
504 // Add a VPInstruction to increment the scalar canonical IV by VF * UF.
505 // Initially the induction increment is guaranteed to not wrap, but that may
506 // change later, e.g. when tail-folding, when the flags need to be dropped.
507 auto *CanonicalIVIncrement = Builder.createAdd(
508 R->getCanonicalIV(), &Plan.getVFxUF(), DL, "index.next", {true, false});
509
510 if (match(LatchTerm, m_BranchOnTwoConds())) {
511 auto *IsLatchExitTaken = Builder.createICmp(
512 CmpInst::ICMP_EQ, CanonicalIVIncrement, &Plan.getVectorTripCount());
513 LatchTerm->setOperand(1, IsLatchExitTaken);
514 } else {
515 // We are replacing the branch to exit the region. Remove the original
516 // BranchOnCond.
517 assert(match(LatchTerm, m_BranchOnCond()) && "Unexpected terminator");
518 DebugLoc LatchDL = LatchTerm->getDebugLoc();
519 Builder.createNaryOp(VPInstruction::BranchOnCount,
520 {CanonicalIVIncrement, &Plan.getVectorTripCount()},
521 LatchDL);
522 LatchTerm->eraseFromParent();
523 }
524}
525
526/// Creates extracts for values in \p Plan defined in a loop region and used
527/// outside a loop region.
528static void createExtractsForLiveOuts(VPlan &Plan, VPBasicBlock *MiddleVPBB) {
529 VPBuilder B(MiddleVPBB->getFirstNonPhi());
530 for (VPBasicBlock *EB : Plan.getExitBlocks()) {
531 if (!is_contained(EB->predecessors(), MiddleVPBB))
532 continue;
533
534 for (VPRecipeBase &R : EB->phis()) {
535 auto *ExitIRI = cast<VPIRPhi>(&R);
536 VPValue *Exiting = ExitIRI->getIncomingValueForBlock(MiddleVPBB);
537 if (isa<VPIRValue>(Exiting))
538 continue;
539 Exiting = B.createNaryOp(VPInstruction::ExtractLastPart, Exiting);
540 Exiting = B.createNaryOp(VPInstruction::ExtractLastLane, Exiting);
541 ExitIRI->setIncomingValueForBlock(MiddleVPBB, Exiting);
542 }
543 }
544}
545
546static void addInitialSkeleton(VPlan &Plan, Type *InductionTy,
547 PredicatedScalarEvolution &PSE, Loop *TheLoop) {
548 VPDominatorTree VPDT(Plan);
549
550 auto *HeaderVPBB = cast<VPBasicBlock>(Plan.getEntry()->getSingleSuccessor());
551 if (TheLoop->isInnermost()) {
552 canonicalHeaderAndLatch(HeaderVPBB, VPDT);
553 } else {
554 // When vectorizing outer loops, canonicalize all loops up front.
556 for (VPBlockBase *VPB : Blocks)
557 canonicalHeaderAndLatch(VPB, VPDT);
558 }
559 auto *LatchVPBB = cast<VPBasicBlock>(HeaderVPBB->getPredecessors()[1]);
560
561 VPBasicBlock *VecPreheader = Plan.createVPBasicBlock("vector.ph");
562 VPBlockUtils::insertBlockAfter(VecPreheader, Plan.getEntry());
563
564 VPBasicBlock *MiddleVPBB = Plan.createVPBasicBlock("middle.block");
565 // The canonical LatchVPBB has the header block as last successor. If it has
566 // another successor, this successor is an exit block - insert middle block on
567 // its edge. Otherwise, add middle block as another successor retaining header
568 // as last. In the latter case, the latch has no conditional terminator yet,
569 // so insert a placeholder BranchOnCond that always continues to the header.
570 // It will be canonicalized to a BranchOnCount later
571 if (LatchVPBB->getNumSuccessors() == 2) {
572 VPBlockBase *LatchExitVPB = LatchVPBB->getSuccessors()[0];
573 VPBlockUtils::insertOnEdge(LatchVPBB, LatchExitVPB, MiddleVPBB);
574 } else {
575 VPBlockUtils::connectBlocks(LatchVPBB, MiddleVPBB);
576 LatchVPBB->swapSuccessors();
578 {Plan.getFalse()});
579 }
580
581 // Create SCEV and VPValue for the trip count.
582 // We use the symbolic max backedge-taken-count, which works also when
583 // vectorizing loops with uncountable early exits.
584 const SCEV *BackedgeTakenCountSCEV = PSE.getSymbolicMaxBackedgeTakenCount();
585 assert(!isa<SCEVCouldNotCompute>(BackedgeTakenCountSCEV) &&
586 "Invalid backedge-taken count");
587 ScalarEvolution &SE = *PSE.getSE();
588 const SCEV *TripCount = SE.getTripCountFromExitCount(BackedgeTakenCountSCEV,
589 InductionTy, TheLoop);
591
592 VPBasicBlock *ScalarPH = Plan.createVPBasicBlock("scalar.ph");
594
595 // The connection order corresponds to the operands of the conditional branch,
596 // with the middle block already connected to the exit block.
597 VPBlockUtils::connectBlocks(MiddleVPBB, ScalarPH);
598 // Also connect the entry block to the scalar preheader.
599 // TODO: Also introduce a branch recipe together with the minimum trip count
600 // check.
601 VPBlockUtils::connectBlocks(Plan.getEntry(), ScalarPH);
602 Plan.getEntry()->swapSuccessors();
603
604 createExtractsForLiveOuts(Plan, MiddleVPBB);
605
606 // Create resume phis in the scalar preheader for each phi in the scalar loop.
607 // Their incoming value from the vector loop will be the last lane of the
608 // corresponding vector loop header phi.
609 VPBuilder MiddleBuilder(MiddleVPBB->getFirstNonPhi());
610 VPBuilder ScalarPHBuilder(ScalarPH);
611 assert(equal(ScalarPH->getPredecessors(),
612 ArrayRef<VPBlockBase *>({MiddleVPBB, Plan.getEntry()})) &&
613 "unexpected predecessor order of scalar ph");
614 for (const auto &[PhiR, ScalarPhiR] :
615 zip_equal(HeaderVPBB->phis(), Plan.getScalarHeader()->phis())) {
616 auto *VectorPhiR = cast<VPPhi>(&PhiR);
617 VPValue *BackedgeVal = VectorPhiR->getOperand(1);
618 VPValue *ResumeFromVectorLoop =
619 MiddleBuilder.createNaryOp(VPInstruction::ExtractLastPart, BackedgeVal);
620 ResumeFromVectorLoop = MiddleBuilder.createNaryOp(
621 VPInstruction::ExtractLastLane, ResumeFromVectorLoop);
622 // Create scalar resume phi, with the first operand being the incoming value
623 // from the middle block and the second operand coming from the entry block.
624 auto *ResumePhiR = ScalarPHBuilder.createScalarPhi(
625 {ResumeFromVectorLoop, VectorPhiR->getOperand(0)},
626 VectorPhiR->getDebugLoc());
627 cast<VPIRPhi>(&ScalarPhiR)->addIncoming(ResumePhiR);
628 }
629}
630
631/// To make RUN_VPLAN_PASS print initial VPlan.
633
634std::unique_ptr<VPlan> VPlanTransforms::buildVPlan0(
635 Loop *TheLoop, LoopInfo &LI, Type *InductionTy,
637 function_ref<const BranchProbabilityInfo &()> GetBPI) {
638 PlainCFGBuilder Builder(TheLoop, &LI, LVer, InductionTy, GetBPI);
639 std::unique_ptr<VPlan> VPlan0 = Builder.buildPlainCFG();
640 addInitialSkeleton(*VPlan0, InductionTy, PSE, TheLoop);
641 simplifyLiveInsWithSCEV(*VPlan0, PSE);
642
644 return VPlan0;
645}
646
650 auto Frequencies = vputils::computeExecutionFrequencies(Blocks);
651 LLVMContext &Ctx = Plan.getContext();
652 for (VPBasicBlock *VPBB : Blocks) {
653 std::optional<VPExecutionFrequency> Freq = Frequencies.lookup(VPBB);
655 VPI.setExecutionFrequency(Freq, Ctx);
656 }
657}
658
659/// Creates a VPWidenIntOrFpInductionRecipe or VPWidenPointerInductionRecipe
660/// for \p Phi based on \p IndDesc.
661static VPHeaderPHIRecipe *
663 const InductionDescriptor &IndDesc, VPlan &Plan,
664 PredicatedScalarEvolution &PSE, Loop &OrigLoop,
665 DebugLoc DL) {
666 [[maybe_unused]] ScalarEvolution &SE = *PSE.getSE();
667 assert(SE.isLoopInvariant(IndDesc.getStep(), &OrigLoop) &&
668 "step must be loop invariant");
669 assert((Plan.getLiveIn(IndDesc.getStartValue()) == Start ||
670 (SE.isSCEVable(IndDesc.getStartValue()->getType()) &&
671 PSE.getSCEV(IndDesc.getStartValue()) ==
672 vputils::getSCEVExprForVPValue(Start, PSE))) &&
673 "Start VPValue must match IndDesc's start value");
674
675 VPValue *Step =
677
678 VPValue *BackedgeVal = PhiR->getOperand(1);
679 // Replace live-out extracts of WideIV's backedge value by ExitingIVValue
680 // recipes. optimizeInductionLiveOutUsers will later compute the proper
681 // DerivedIV.
682 //
683 // For an IV that requires SCEV predicate, keep extracting the exit values
684 // from the loop directly, as the pre-computed exit value as-is would be
685 // incorrect outside the loop.
686 auto ReplaceExtractsWithExitingIVValueIfPossible = [&](VPWidenInductionRecipe
687 *WideIV) {
688 bool IsPredicated = !WideIV->getNoWrapPredicates().empty();
689 for (VPUser *U : to_vector(BackedgeVal->users())) {
691 continue;
692 auto *ExtractLastPart = cast<VPInstruction>(U);
693 VPUser *ExtractLastPartUser = ExtractLastPart->getSingleUser();
694 assert(ExtractLastPartUser && "must have a single user");
695 if (!match(ExtractLastPartUser, m_ExtractLastLane(m_VPValue())))
696 continue;
697 auto *ExtractLastLane = cast<VPInstruction>(ExtractLastPartUser);
698 assert(is_contained(ExtractLastLane->getParent()->successors(),
699 Plan.getScalarPreheader()) &&
700 "last lane must be extracted in the middle block");
701 // Keep the vector extract for exit-block live-out uses of a predicated
702 // IV.
703 if (IsPredicated &&
704 any_of(ExtractLastLane->users(), [&](VPUser *LaneUser) {
705 auto *R = cast<VPRecipeBase>(LaneUser);
706 return Plan.isExitBlock(R->getParent());
707 }))
708 continue;
709 VPBuilder Builder(ExtractLastLane);
710 ExtractLastLane->replaceAllUsesWith(
711 Builder.createNaryOp(VPInstruction::ExitingIVValue, {WideIV}));
712 ExtractLastLane->eraseFromParent();
713 ExtractLastPart->eraseFromParent();
714 }
715 };
716
718 auto *WideIV = new VPWidenPointerInductionRecipe(
719 Phi, Start, Step, &Plan.getVFxUF(), IndDesc, DL);
720 ReplaceExtractsWithExitingIVValueIfPossible(WideIV);
721 return WideIV;
722 }
723
726 "must have an integer or float induction at this point");
727
728 // Update wide induction increments to use the same step as the corresponding
729 // wide induction. This enables detecting induction increments directly in
730 // VPlan and removes redundant splats.
731 if (match(BackedgeVal, m_Add(m_Specific(PhiR), m_VPValue())))
732 BackedgeVal->getDefiningRecipe()->setOperand(1, Step);
733
734 // It is always safe to copy over the NoWrap and FastMath flags. In
735 // particular, when folding tail by masking, the masked-off lanes are never
736 // used, so it is safe.
737 VPIRFlags Flags = vputils::getFlagsForInduction(IndDesc, PhiR);
738
739 auto *WideIV = new VPWidenIntOrFpInductionRecipe(
740 Phi, Start, Step, &Plan.getVF(), IndDesc, Flags, DL);
741
742 ReplaceExtractsWithExitingIVValueIfPossible(WideIV);
743 return WideIV;
744}
745
746/// Try to sink users of \p FOR after \p Previous. \returns true if sinking
747/// succeeded or was not necessary, and false otherwise.
748static bool
750 VPRecipeBase *Previous,
751 const VPDominatorTree &VPDT) {
752 // Collect recipes that need sinking.
755 Seen.insert(Previous);
756 auto TryToPushSinkCandidate = [&](VPRecipeBase *SinkCandidate) {
757 // The previous value must not depend on the users of the recurrence phi.
758 // In that case, FOR is not a fixed order recurrence.
759 if (SinkCandidate == Previous)
760 return false;
761
762 if (isa<VPHeaderPHIRecipe>(SinkCandidate) ||
763 !Seen.insert(SinkCandidate).second ||
764 VPDT.properlyDominates(Previous, SinkCandidate))
765 return true;
766
767 if (vputils::cannotHoistOrSinkRecipe(*SinkCandidate, /*Sinking=*/true))
768 return false;
769
770 WorkList.push_back(SinkCandidate);
771 return true;
772 };
773
774 // Recursively sink users of FOR after Previous.
775 WorkList.push_back(FOR);
776 for (unsigned I = 0; I != WorkList.size(); ++I) {
777 VPRecipeBase *Current = WorkList[I];
778 assert(Current->getNumDefinedValues() == 1 &&
779 "only recipes with a single defined value expected");
780
781 for (VPUser *User : Current->getVPSingleValue()->users()) {
782 if (!TryToPushSinkCandidate(cast<VPRecipeBase>(User)))
783 return false;
784 }
785 }
786
787 // Keep recipes to sink ordered by dominance so earlier instructions are
788 // processed first.
789 sort(WorkList, [&VPDT](const VPRecipeBase *A, const VPRecipeBase *B) {
790 return VPDT.properlyDominates(A, B);
791 });
792
793 for (VPRecipeBase *SinkCandidate : WorkList) {
794 if (SinkCandidate == FOR)
795 continue;
796
797 SinkCandidate->moveAfter(Previous);
798 Previous = SinkCandidate;
799 }
800 return true;
801}
802
803/// Try to hoist \p Previous and its operands before all users of \p FOR.
804/// \returns true if hoisting succeeded or was not necessary, and false
805/// otherwise.
807 VPRecipeBase *Previous,
808 const VPDominatorTree &VPDT) {
810 return false;
811
812 // Collect recipes that need hoisting.
813 SmallVector<VPRecipeBase *> HoistCandidates;
815 // Find the closest hoist point by looking at all users of FOR and selecting
816 // the recipe dominating all other users.
817 VPRecipeBase *HoistPoint = nullptr;
818 for (VPUser *U : FOR->users()) {
819 auto *R = cast<VPRecipeBase>(U);
820 if (!HoistPoint || VPDT.properlyDominates(R, HoistPoint))
821 HoistPoint = R;
822 }
823 // Dominance is only a partial order, so the users of FOR may not have a
824 // single user dominating all others. Bail out in that case.
825 if (!HoistPoint || HoistPoint->isPhi() ||
826 any_of(FOR->users(), [&VPDT, HoistPoint](VPUser *U) {
827 auto *R = cast<VPRecipeBase>(U);
828 return HoistPoint != R && !VPDT.properlyDominates(HoistPoint, R);
829 }))
830 return false;
831
832 auto NeedsHoisting = [HoistPoint, &VPDT,
833 &Visited](VPValue *HoistCandidateV) -> VPRecipeBase * {
834 VPRecipeBase *HoistCandidate = HoistCandidateV->getDefiningRecipe();
835 if (!HoistCandidate)
836 return nullptr;
837 // Hoist candidate was already visited, no need to hoist.
838 if (!Visited.insert(HoistCandidate).second)
839 return nullptr;
840 // If we reached a recipe that dominates HoistPoint, we don't need to
841 // hoist the recipe.
842 if (VPDT.properlyDominates(HoistCandidate, HoistPoint))
843 return nullptr;
844 return HoistCandidate;
845 };
846
847 if (!NeedsHoisting(Previous->getVPSingleValue()))
848 return true;
849
850 // Recursively try to hoist Previous and its operands before all users of
851 // FOR.
852 HoistCandidates.push_back(Previous);
853
854 for (unsigned I = 0; I != HoistCandidates.size(); ++I) {
855 VPRecipeBase *Current = HoistCandidates[I];
856 assert(Current->getNumDefinedValues() == 1 &&
857 "only recipes with a single defined value expected");
859 return false;
860
861 for (VPValue *Op : Current->operands()) {
862 // If we reach FOR, it means the original Previous depends on some other
863 // recurrence that in turn depends on FOR. If that is the case, we would
864 // also need to hoist recipes involving the other FOR, which may break
865 // dependencies.
866 if (Op == FOR)
867 return false;
868
869 if (auto *R = NeedsHoisting(Op)) {
870 // Bail out if the recipe defines multiple values.
871 // TODO: Hoisting such recipes requires additional handling.
872 if (R->getNumDefinedValues() != 1)
873 return false;
874 HoistCandidates.push_back(R);
875 }
876 }
877 }
878
879 // Moving a candidate to HoistPoint keeps it dominating its other users only
880 // if HoistPoint dominates the candidate's current position.
881 if (any_of(HoistCandidates, [&VPDT, HoistPoint](VPRecipeBase *R) {
882 return !VPDT.properlyDominates(HoistPoint, R);
883 }))
884 return false;
885
886 // Order recipes to hoist by dominance so earlier instructions are processed
887 // first.
888 sort(HoistCandidates, [&VPDT](const VPRecipeBase *A, const VPRecipeBase *B) {
889 return VPDT.properlyDominates(A, B);
890 });
891
892 for (VPRecipeBase *HoistCandidate : HoistCandidates) {
893 HoistCandidate->moveBefore(HoistPoint->getIterator());
894 }
895
896 return true;
897}
898
899/// Sink users of fixed-order recurrences past or hoist before the recipe
900/// defining the previous value, introduce FirstOrderRecurrenceSplice
901/// VPInstructions, and replace FOR uses. Returns false if hoisting or sinking
902/// fails.
904 const VPDominatorTree &VPDT) {
905 auto FORs =
908 [](VPRecipeBase &R) {
909 return cast<VPFirstOrderRecurrencePHIRecipe>(&R);
910 });
911 for (VPFirstOrderRecurrencePHIRecipe *FOR : FORs) {
912 // Follow through FOR phi chains to find the actual Previous recipe.
913 // Fixed-order recurrences do not contain cycles, so this loop is
914 // guaranteed to terminate.
916 VPRecipeBase *Previous = FOR->getBackedgeValue()->getDefiningRecipe();
917 while (auto *PrevPhi =
919 assert(PrevPhi->getParent() == FOR->getParent() &&
920 "PrevPhi must be in same block as FOR");
921 assert(SeenPhis.insert(PrevPhi).second &&
922 "PrevPhi must not be visited multiple times");
923 Previous = PrevPhi->getBackedgeValue()->getDefiningRecipe();
924 }
925
926 VPBasicBlock::iterator InsertPt = FOR->getParent()->getFirstNonPhi();
927 if (Previous) {
928 // Sink FOR users after Previous or hoist Previous before FOR users.
929 if (!sinkRecurrenceUsersAfterPrevious(FOR, Previous, VPDT) &&
930 !hoistPreviousBeforeFORUsers(FOR, Previous, VPDT))
931 return false;
932 InsertPt = isa<VPHeaderPHIRecipe>(Previous)
933 ? Previous->getParent()->getFirstNonPhi()
934 : std::next(Previous->getIterator());
935 }
936
937 // Create FirstOrderRecurrenceSplice and replace FOR uses.
938 VPBuilder LoopBuilder(InsertPt);
939 auto *RecurSplice =
941 {FOR, FOR->getBackedgeValue()});
942 FOR->replaceUsesWithIf(RecurSplice, not_equal_to(RecurSplice));
943 }
944
945 return true;
946}
947
949 VPlan &Plan, PredicatedScalarEvolution &PSE, Loop &OrigLoop,
953 const SmallPtrSetImpl<const PHINode *> &FixedOrderRecurrences,
954 const SmallPtrSetImpl<PHINode *> &InLoopReductions, bool AllowReordering) {
955 // Retrieve the header manually from the intial plain-CFG VPlan.
956 auto [HeaderVPBB, LatchVPBB] = VPBlockUtils::getPlainCFGHeaderAndLatch(Plan);
957 assert(VPDT.dominates(HeaderVPBB, LatchVPBB) &&
958 "header must dominate its latch");
959
960 auto CreateHeaderPhiRecipe = [&](VPPhi *PhiR) -> VPHeaderPHIRecipe * {
961 // TODO: Gradually replace uses of underlying instruction by analyses on
962 // VPlan.
963 auto *Phi = cast<PHINode>(PhiR->getUnderlyingInstr());
964 assert(PhiR->getNumOperands() == 2 &&
965 "Must have 2 operands for header phis");
966
967 // Extract common values once.
968 VPIRValue *Start = cast<VPIRValue>(PhiR->getOperand(0));
969 VPValue *BackedgeValue = PhiR->getOperand(1);
970
971 if (FixedOrderRecurrences.contains(Phi)) {
972 // TODO: Currently fixed-order recurrences are modeled as chains of
973 // first-order recurrences. If there are no users of the intermediate
974 // recurrences in the chain, the fixed order recurrence should be
975 // modeled directly, enabling more efficient codegen.
976 return new VPFirstOrderRecurrencePHIRecipe(Phi, *Start, *BackedgeValue);
977 }
978
979 auto InductionIt = Inductions.find(Phi);
980 if (InductionIt != Inductions.end())
981 return createWidenInductionRecipe(Phi, PhiR, Start, InductionIt->second,
982 Plan, PSE, OrigLoop,
983 PhiR->getDebugLoc());
984
985 assert(Reductions.contains(Phi) && "only reductions are expected now");
986 const RecurrenceDescriptor &RdxDesc = Reductions.lookup(Phi);
988 Phi->getIncomingValueForBlock(OrigLoop.getLoopPreheader()) &&
989 "incoming value must match start value");
990 // Will be updated later to >1 if reduction is partial.
991 unsigned ScaleFactor = 1;
992 bool UseOrderedReductions = !AllowReordering && RdxDesc.isOrdered();
993 return new VPReductionPHIRecipe(
994 Phi, RdxDesc.getRecurrenceKind(), *Start, *BackedgeValue,
995 getReductionStyle(InLoopReductions.contains(Phi), UseOrderedReductions,
996 ScaleFactor),
997 Phi->getType()->isFloatingPointTy() ? RdxDesc.getFastMathFlags()
998 : VPIRFlags(),
1000 };
1001
1002 for (VPRecipeBase &R : make_early_inc_range(HeaderVPBB->phis())) {
1003 auto *PhiR = cast<VPPhi>(&R);
1004 VPHeaderPHIRecipe *HeaderPhiR = CreateHeaderPhiRecipe(PhiR);
1005 HeaderPhiR->insertBefore(PhiR);
1006 PhiR->replaceAllUsesWith(HeaderPhiR);
1007 PhiR->eraseFromParent();
1008 }
1009
1010 if (!tryToSinkOrHoistRecurrenceUsers(HeaderVPBB, VPDT)) {
1012 "Failed to sink or hoist user of first-order recurrence",
1013 "CannotSinkHoistFORUser", ORE, &OrigLoop);
1014 return false;
1015 }
1016
1017 // Skip renaming resume phi recipes, if any header phi has been removed.
1018 if (range_size(HeaderVPBB->phis()) !=
1020 return true;
1021 for (const auto &[HeaderPhiR, ScalarPhiR] :
1022 zip_equal(HeaderVPBB->phis(), Plan.getScalarPreheader()->phis())) {
1023 auto *ResumePhiR = cast<VPPhi>(&ScalarPhiR);
1024 if (isa<VPFirstOrderRecurrencePHIRecipe>(&HeaderPhiR)) {
1025 ResumePhiR->setName("scalar.recur.init");
1026 auto *ExtractLastLane = cast<VPInstruction>(ResumePhiR->getOperand(0));
1027 ExtractLastLane->setName("vector.recur.extract");
1028 continue;
1029 }
1030 ResumePhiR->setName(isa<VPWidenInductionRecipe>(HeaderPhiR)
1031 ? "bc.resume.val"
1032 : "bc.merge.rdx");
1033 }
1034 return true;
1035}
1036
1039 bool OptForSize,
1040 unsigned SCEVCheckThreshold,
1042 Loop *TheLoop) {
1043 // Collect which wide IVs have predicates and add them to PSE.
1044 auto [HeaderVPBB, _] = VPBlockUtils::getPlainCFGHeaderAndLatch(Plan);
1046 for (VPWidenInductionRecipe &WideIV :
1047 make_isa_range<VPWidenInductionRecipe>(HeaderVPBB->phis())) {
1048 if (WideIV.getNoWrapPredicates().empty())
1049 continue;
1050 PredicatedIVs.insert(&WideIV);
1051 for (const auto *P : WideIV.getNoWrapPredicates())
1052 PSE.addPredicate(*P);
1053 }
1054
1055 unsigned TotalComplexity = PSE.getPredicate().getComplexity();
1056 if (TotalComplexity && OptForSize) {
1057 LLVM_DEBUG(
1058 dbgs() << "LV: Not vectorizing: SCEV predicates needed for induction "
1059 "but optimizing for size\n");
1061 "Runtime SCEV check is required with -Os/-Oz",
1062 "runtime SCEV checks needed but optimizing for size",
1063 "CantVersionLoopWithOptForSize", ORE, TheLoop);
1064 return false;
1065 }
1066
1067 if (TotalComplexity > SCEVCheckThreshold) {
1068 LLVM_DEBUG(dbgs() << "LV: Not vectorizing: Too many SCEV checks needed ("
1069 << TotalComplexity << " > " << SCEVCheckThreshold
1070 << ")\n");
1072 "Too many SCEV checks needed",
1073 "Too many SCEV assumptions need to be made and checked at runtime",
1074 "TooManySCEVRunTimeChecks", ORE, TheLoop);
1075 return false;
1076 }
1077
1078 return true;
1079}
1080
1082 ElementCount MinVF) {
1085
1086 for (VPRecipeBase &R : Header->phis()) {
1087 auto *PhiR = dyn_cast<VPReductionPHIRecipe>(&R);
1088 if (!PhiR || !PhiR->isInLoop() || (MinVF.isScalar() && !PhiR->isOrdered()))
1089 continue;
1090
1091 RecurKind Kind = PhiR->getRecurrenceKind();
1095 "AnyOf and Find reductions are not allowed for in-loop reductions");
1096
1097 bool IsFPRecurrence =
1099 FastMathFlags FMFs =
1100 IsFPRecurrence ? FastMathFlags::getFast() : FastMathFlags();
1101
1102 // Collect the chain of "link" recipes for the reduction starting at PhiR.
1104 Worklist.insert(PhiR);
1105 for (unsigned I = 0; I != Worklist.size(); ++I) {
1106 VPSingleDefRecipe *Cur = Worklist[I];
1107 for (VPUser *U : Cur->users()) {
1108 auto *UserRecipe = cast<VPSingleDefRecipe>(U);
1109 if (!UserRecipe->getParent()->getEnclosingLoopRegion()) {
1110 assert((UserRecipe->getParent() == Plan.getMiddleBlock() ||
1111 UserRecipe->getParent() == Plan.getScalarPreheader()) &&
1112 "U must be either in the loop region, the middle block or the "
1113 "scalar preheader.");
1114 continue;
1115 }
1116
1117 // Stores using instructions will be sunk later.
1118 if (match(UserRecipe, m_VPInstruction<Instruction::Store>()))
1119 continue;
1120 Worklist.insert(UserRecipe);
1121 }
1122 }
1123
1124 // Visit operation "Links" along the reduction chain top-down starting from
1125 // the phi until LoopExitValue. We keep track of the previous item
1126 // (PreviousLink) to tell which of the two operands of a Link will remain
1127 // scalar and which will be reduced. For minmax by select(cmp), Link will be
1128 // the select instructions. Blend recipes of in-loop reduction phi's will
1129 // get folded to their non-phi operand, as the reduction recipe handles the
1130 // condition directly.
1131 VPSingleDefRecipe *PreviousLink = PhiR; // Aka Worklist[0].
1132 for (VPSingleDefRecipe *CurrentLink : drop_begin(Worklist)) {
1133 if (auto *Blend = dyn_cast<VPBlendRecipe>(CurrentLink)) {
1134 assert(Blend->getNumIncomingValues() == 2 &&
1135 "Blend must have 2 incoming values");
1136 unsigned PhiRIdx = Blend->getIncomingValue(0) == PhiR ? 0 : 1;
1137 assert(Blend->getIncomingValue(PhiRIdx) == PhiR &&
1138 "PhiR must be an operand of the blend");
1139 Blend->replaceAllUsesWith(Blend->getIncomingValue(1 - PhiRIdx));
1140 continue;
1141 }
1142
1143 if (IsFPRecurrence) {
1144 FastMathFlags CurFMF =
1145 cast<VPRecipeWithIRFlags>(CurrentLink)->getFastMathFlagsOrNone();
1146 if (match(CurrentLink, m_Select(m_VPValue(), m_VPValue(), m_VPValue())))
1147 CurFMF |= cast<VPRecipeWithIRFlags>(CurrentLink->getOperand(0))
1148 ->getFastMathFlagsOrNone();
1149 FMFs &= CurFMF;
1150 }
1151
1152 Instruction *CurrentLinkI = CurrentLink->getUnderlyingInstr();
1153
1154 // Recognize a call to the llvm.fmuladd intrinsic.
1155 bool IsFMulAdd = Kind == RecurKind::FMulAdd;
1156 VPValue *VecOp;
1157 VPBasicBlock *LinkVPBB = CurrentLink->getParent();
1158 if (IsFMulAdd) {
1160 "Expected current VPInstruction to be a call to the "
1161 "llvm.fmuladd intrinsic");
1162 assert(CurrentLink->getOperand(2) == PreviousLink &&
1163 "expected a call where the previous link is the added operand");
1164
1165 // If the instruction is a call to the llvm.fmuladd intrinsic then we
1166 // need to create an fmul recipe (multiplying the first two operands of
1167 // the fmuladd together) to use as the vector operand for the fadd
1168 // reduction.
1169 auto *FMulRecipe = new VPInstruction(
1170 Instruction::FMul,
1171 {CurrentLink->getOperand(0), CurrentLink->getOperand(1)},
1172 CurrentLinkI->getFastMathFlags());
1173 FMulRecipe->insertBefore(CurrentLink);
1174 VecOp = FMulRecipe;
1175 } else if (Kind == RecurKind::AddChainWithSubs &&
1176 match(CurrentLink, m_Sub(m_VPValue(), m_VPValue()))) {
1177 Type *PhiTy = PhiR->getScalarType();
1178 auto *Zero = Plan.getConstantInt(PhiTy, 0);
1179 VPBuilder Builder(CurrentLink);
1180 auto *Sub = Builder.createSub(Zero, CurrentLink->getOperand(1),
1181 CurrentLinkI->getDebugLoc());
1182 Sub->setUnderlyingValue(CurrentLinkI);
1183 VecOp = Sub;
1184 } else {
1185 // Index of the first operand which holds a non-mask vector operand.
1186 unsigned IndexOfFirstOperand = 0;
1188 if (match(CurrentLink, m_Cmp(m_VPValue(), m_VPValue())))
1189 continue;
1190 assert(match(CurrentLink,
1192 "must be a select recipe");
1193 IndexOfFirstOperand = 1;
1194 }
1195 // Note that for non-commutable operands (cmp-selects), the semantics of
1196 // the cmp-select are captured in the recurrence kind.
1197 unsigned VecOpId =
1198 CurrentLink->getOperand(IndexOfFirstOperand) == PreviousLink
1199 ? IndexOfFirstOperand + 1
1200 : IndexOfFirstOperand;
1201 VecOp = CurrentLink->getOperand(VecOpId);
1202 assert(
1203 VecOp != PreviousLink &&
1204 CurrentLink->getOperand(
1205 cast<VPInstruction>(CurrentLink)->getNumOperandsWithoutMask() -
1206 1 - (VecOpId - IndexOfFirstOperand)) == PreviousLink &&
1207 "PreviousLink must be the operand other than VecOp");
1208 }
1209
1210 assert(PhiR->getVFScaleFactor() == 1 &&
1211 "inloop reductions must be unscaled");
1212 VPValue *CondOp = cast<VPInstruction>(CurrentLink)->getMask();
1213 auto *RedRecipe = new VPReductionRecipe(
1214 Kind, FMFs, CurrentLinkI, PreviousLink, VecOp, CondOp,
1215 getReductionStyle(/*IsInLoop=*/true, PhiR->isOrdered(), 1),
1216 CurrentLinkI->getDebugLoc());
1217 // Append the recipe to the end of the VPBasicBlock because we need to
1218 // ensure that it comes after all of it's inputs, including CondOp.
1219 // Delete CurrentLink as it will be invalid if its operand is replaced
1220 // with a reduction defined at the bottom of the block in the next link.
1221 if (LinkVPBB->getNumSuccessors() == 0)
1222 RedRecipe->insertBefore(&*std::prev(std::prev(LinkVPBB->end())));
1223 else
1224 LinkVPBB->appendRecipe(RedRecipe);
1225
1226 CurrentLink->replaceAllUsesWith(RedRecipe);
1227 // Move any store recipes using the RedRecipe that appear before it in the
1228 // same block to just after the RedRecipe.
1229 for (VPRecipeBase *UserR : make_early_inc_range(
1230 make_isa_range<VPRecipeBase>(RedRecipe->users()))) {
1231 if (UserR->getParent() != LinkVPBB)
1232 continue;
1234 continue;
1235 UserR->moveAfter(RedRecipe);
1236 }
1237 ToDelete.push_back(CurrentLink);
1238 PreviousLink = RedRecipe;
1239 }
1240 }
1241
1242 for (VPRecipeBase *R : ToDelete)
1243 R->eraseFromParent();
1244}
1245
1247 Loop *TheLoop,
1249 DominatorTree &DT,
1250 AssumptionCache *AC) {
1251 ScalarEvolution &SE = *PSE.getSE();
1252 const DataLayout &DL = TheLoop->getHeader()->getDataLayout();
1253 for (VPBasicBlock *VPBB : vp_rpo_plain_cfg_loop_body(HeaderVPBB)) {
1254 for (VPRecipeBase &R : *VPBB) {
1255 // Pseudo-probes are profiling placeholders with side effects but no real
1256 // memory access. They are modeled as reading inaccessible memory, so skip
1257 // them here to stay consistent with isReadOnlyLoop(), which classifies
1258 // such loops as read-only.
1260 continue;
1261 auto *VPI = dyn_cast<VPInstruction>(&R);
1262 if (!VPI || VPI->getOpcode() != Instruction::Load) {
1263 assert(!R.mayReadFromMemory() && "unexpected recipe reading memory");
1264 continue;
1265 }
1266
1267 // Get the pointer SCEV for dereferenceability checking.
1268 VPValue *Ptr = VPI->getOperand(0);
1269 const SCEV *PtrSCEV = vputils::getSCEVExprForVPValue(Ptr, PSE, TheLoop);
1270 if (isa<SCEVCouldNotCompute>(PtrSCEV)) {
1271 LLVM_DEBUG(dbgs() << "LV: Not vectorizing: Found non-dereferenceable "
1272 "load with SCEVCouldNotCompute pointer\n");
1273 return false;
1274 }
1275
1276 // Check dereferenceability using the SCEV-based version.
1277 Type *LoadTy = VPI->getScalarType();
1278 const SCEV *SizeSCEV =
1279 SE.getStoreSizeOfExpr(DL.getIndexType(PtrSCEV->getType()), LoadTy);
1280 auto *Load = cast<LoadInst>(VPI->getUnderlyingValue());
1282 if (isDereferenceableAndAlignedInLoop(PtrSCEV, Load->getAlign(), SizeSCEV,
1283 TheLoop, SE, DT, AC, &Preds))
1284 continue;
1285
1286 return false;
1287 }
1288 }
1289 return true;
1290}
1291
1293 auto *MiddleVPBB = VPBlockUtils::getPlainCFGMiddleBlock(Plan);
1294 // Disconnect countable early exits from the loop, leaving it with a single
1295 // exit from the latch. Countable early exits are left for a scalar epilog.
1296 for (auto [EarlyExitingVPBB, EB] : vputils::getEarlyExits(Plan, MiddleVPBB)) {
1297 // Remove phi operands for the early exiting block.
1298 for (VPRecipeBase &R : EB->phis())
1299 cast<VPIRPhi>(&R)->removeIncomingValueFor(EarlyExitingVPBB);
1300 EarlyExitingVPBB->getTerminator()->eraseFromParent();
1301 VPBlockUtils::disconnectBlocks(EarlyExitingVPBB, EB);
1302 }
1303}
1304
1306 auto *MiddleVPBB = VPBlockUtils::getPlainCFGMiddleBlock(Plan);
1307 // If MiddleVPBB has a single successor then the original loop does not exit
1308 // via the latch and the single successor must be the scalar preheader.
1309 // There's no need to add a runtime check to MiddleVPBB.
1310 if (MiddleVPBB->getNumSuccessors() == 1) {
1311 assert(MiddleVPBB->getSingleSuccessor() == Plan.getScalarPreheader() &&
1312 "must have ScalarPH as single successor");
1313 return;
1314 }
1315
1316 assert(MiddleVPBB->getNumSuccessors() == 2 && "must have 2 successors");
1317
1318 // Add a check in the middle block to see if we have completed all of the
1319 // iterations in the first vector loop.
1320 //
1321 // Three cases:
1322 // 1) If we require a scalar epilogue, the scalar ph must execute. Set the
1323 // condition to false.
1324 // 2) If (N - N%VF) == N, then we *don't* need to run the
1325 // remainder. Thus if tail is to be folded, we know we don't need to run
1326 // the remainder and we can set the condition to true.
1327 // 3) Otherwise, construct a runtime check.
1328
1329 // We use the same DebugLoc as the scalar loop latch terminator instead of
1330 // the corresponding compare because they may have ended up with different
1331 // line numbers and we want to avoid awkward line stepping while debugging.
1332 // E.g., if the compare has got a line number inside the loop.
1333 auto *LatchVPBB = cast<VPBasicBlock>(MiddleVPBB->getSinglePredecessor());
1334 DebugLoc LatchDL = LatchVPBB->getTerminator()->getDebugLoc();
1335 VPBuilder Builder(MiddleVPBB);
1336 VPValue *Cmp =
1337 Builder.createICmp(CmpInst::ICMP_EQ, Plan.getTripCount(),
1338 &Plan.getVectorTripCount(), LatchDL, "cmp.n");
1339 Builder.createNaryOp(VPInstruction::BranchOnCond, {Cmp}, LatchDL);
1340}
1341
1343 VPDominatorTree VPDT(Plan);
1345 Plan.getEntry());
1346 // Headers and latches have been canonicalized by addInitialSkeleton.
1347 for (VPBlockBase *HeaderVPB : POT) {
1348 if (!VPBlockUtils::isHeader(HeaderVPB, VPDT))
1349 continue;
1350 assert(HeaderVPB->getPredecessors()[1]->getSuccessors().back() ==
1351 HeaderVPB &&
1352 "latch must have the header as last successor");
1353 createLoopRegion(Plan, HeaderVPB, DL);
1354 }
1355
1356 VPRegionBlock *TopRegion = Plan.getVectorLoopRegion();
1357 TopRegion->setName("vector loop");
1358 TopRegion->getEntryBasicBlock()->setName("vector.body");
1359}
1360
1362 assert(Plan.getExitBlocks().size() == 1 &&
1363 "only a single-exit block is supported currently");
1364 assert(Plan.getExitBlocks().front()->getSinglePredecessor() ==
1365 Plan.getMiddleBlock() &&
1366 "the exit block must have middle block as single predecessor");
1367
1368 VPRegionBlock *LoopRegion = Plan.getVectorLoopRegion();
1369 assert(LoopRegion->getSingleSuccessor() == Plan.getMiddleBlock() &&
1370 "The vector loop region must have the middle block as its single "
1371 "successor for now");
1372 VPBasicBlock *Header = LoopRegion->getEntryBasicBlock();
1373
1374 Header->splitAt(Header->getFirstNonPhi());
1375
1376 // Abstract header mask, materialized into concrete recipes later.
1377 VPValue *HeaderMask = LoopRegion->createHeaderMask();
1378 VPBuilder Builder(Header->getFirstNonPhi());
1379 Builder.createNaryOp(VPInstruction::BranchOnCond, HeaderMask);
1380
1381 VPBasicBlock *OrigLatch = LoopRegion->getExitingBasicBlock();
1382 VPValue *IVInc;
1383 [[maybe_unused]] bool TermBranchOnCount =
1384 match(OrigLatch->getTerminator(),
1386 m_Specific(&Plan.getVectorTripCount())));
1387 assert(TermBranchOnCount &&
1388 match(IVInc, m_Add(m_Specific(LoopRegion->getCanonicalIV()),
1389 m_Specific(&Plan.getVFxUF()))) &&
1390 std::next(IVInc->getDefiningRecipe()->getIterator()) ==
1391 OrigLatch->getTerminator()->getIterator() &&
1392 "Unexpected canonical iv increment");
1393
1394 // Split the latch at the IV update, and branch to it from the header mask.
1395 VPBasicBlock *Latch =
1396 OrigLatch->splitAt(IVInc->getDefiningRecipe()->getIterator());
1397 Latch->setName("vector.latch");
1398 VPBlockUtils::connectBlocks(Header, Latch);
1399
1400 // Collect any values defined in the loop that need a phi, that is header phis
1401 // and any value defined n the loop and used in the middle block.
1402 // TODO: Handle early exits via Plan.getExitBlocks()
1404 auto CollectBypassedOperands = [&](VPRecipeBase &R) {
1405 for (VPValue *Op : R.operands()) {
1406 auto *DefR = Op->getDefiningRecipe();
1407 if (DefR && DefR->getParent()->getEnclosingLoopRegion() == LoopRegion &&
1408 !is_contained({Header, Latch}, DefR->getParent()))
1409 NeedsPhi[Op].push_back(&R);
1410 }
1411 };
1412 for (VPRecipeBase &R : Header->phis())
1413 CollectBypassedOperands(R);
1414 for (VPRecipeBase &R : *Plan.getMiddleBlock())
1415 CollectBypassedOperands(R);
1416
1417 // Insert phis for values coming past the end of the tail.
1418 Builder.setInsertPoint(Latch->begin());
1419 for (const auto &[V, Users] : NeedsPhi) {
1420 VPValue *TailVal = Plan.getPoison(V->getScalarType());
1421 std::optional<VPIRFlags> Flags;
1423 "Value used by more than two reduction phis?");
1425 auto *RdxPhi =
1426 RedIt != Users.end() ? cast<VPReductionPHIRecipe>(*RedIt) : nullptr;
1427 if (RdxPhi && !RdxPhi->isInLoop()) {
1428 TailVal = RdxPhi;
1429 Flags = *RdxPhi;
1430 }
1431
1432 VPInstruction *Phi = Builder.createScalarPhi({V, TailVal}, {}, "", Flags);
1433 for (VPUser *U : Users)
1434 U->replaceUsesOfWith(V, Phi);
1435 }
1436
1437 // Any extract of the last element must be updated to extract from the last
1438 // active lane of the header mask instead (i.e., the lane corresponding to the
1439 // last active iteration).
1440 Builder.setInsertPoint(Plan.getMiddleBlock()->getTerminator());
1441 for (VPRecipeBase &R : *Plan.getMiddleBlock()) {
1442 VPValue *Op;
1444 continue;
1445
1446 // Compute the index of the last active lane.
1447 VPValue *LastActiveLane = Builder.createLastActiveLane(HeaderMask);
1448 auto *Ext =
1449 Builder.createNaryOp(VPInstruction::ExtractLane, {LastActiveLane, Op});
1450 R.getVPSingleValue()->replaceAllUsesWith(Ext);
1451 }
1452
1453 // VectorTripCount now equals TripCount so simplify the MiddleVPBB branch.
1457 m_Specific(&Plan.getVectorTripCount())))) &&
1458 "Unexpected MiddleVPBB branch");
1459 Plan.getMiddleBlock()->getTerminator()->setOperand(0, Plan.getTrue());
1460}
1461
1462/// Add an incoming value to all phis in \p VPBB for its just-added last
1463/// predecessor, re-using the value of the previously last one.
1465 for (VPRecipeBase &R : VPBB->phis()) {
1466 auto *Phi = cast<VPPhi>(&R);
1467 assert(Phi->getNumIncoming() == VPBB->getNumPredecessors() - 1 &&
1468 "must have incoming values for all predecessors but the new one");
1469 Phi->addIncoming(Phi->getIncomingValue(Phi->getNumIncoming() - 1));
1470 }
1471}
1472
1473/// Insert \p CheckBlockVPBB on the edge leading to the vector preheader,
1474/// connecting it to both vector and scalar preheaders. Updates scalar
1475/// preheader phis to account for the new predecessor.
1477 VPBasicBlock *CheckBlockVPBB) {
1478 VPBlockBase *VectorPH = Plan.getVectorPreheader();
1479 auto *ScalarPH = cast<VPBasicBlock>(Plan.getScalarPreheader());
1480 VPBlockBase *PreVectorPH = VectorPH->getSinglePredecessor();
1481 VPBlockUtils::insertOnEdge(PreVectorPH, VectorPH, CheckBlockVPBB);
1482 VPBlockUtils::connectBlocks(CheckBlockVPBB, ScalarPH);
1483 CheckBlockVPBB->swapSuccessors();
1485}
1486
1487VPIRBasicBlock *
1489 VPBasicBlock *MainCheck) {
1490 VPBasicBlock *VectorPH = EpiPlan.getVectorPreheader();
1491 assert(VectorPH && VectorPH->phis().empty() &&
1492 "vector preheader must exist and have no phis to update");
1493 auto *MainScalarPH = cast<VPIRBasicBlock>(MainPlan.getScalarPreheader());
1494 assert(MainScalarPH->getIRBasicBlock()->phis().empty() &&
1495 "MainPlan must not have generated phis in its scalar preheader");
1496 auto *EpilogueCheck =
1497 EpiPlan.createEmptyVPIRBasicBlock(MainScalarPH->getIRBasicBlock());
1498 VPBlockUtils::reassociateBlocks(EpiPlan.getEntry(), EpilogueCheck);
1499
1500 // Map blocks from MainPlan to new, empty VPIRBasicBlocks in EpiPlan, so the
1501 // skeleton CFG can be modeled explicitly. MainPlan's entry maps to EpiPlan's
1502 // now-disconnected entry and its scalar PH to EpilogueCheck.
1503 VPBlockBase *MainEntry = MainPlan.getEntry();
1505 MainToEpiVPBB[MainEntry] = EpiPlan.getEntry();
1507 MainEntry);
1509 // Skip entry block and exit blocks/scalar loop header; they are already
1510 // modeled in the epilogue plan.
1511 if (VPBB != MainEntry && VPBB != MainScalarPH && VPBB->hasSuccessors())
1512 MainToEpiVPBB[VPBB] =
1513 EpiPlan.createEmptyVPIRBasicBlock(VPBB->getIRBasicBlock());
1514 MainToEpiVPBB[MainScalarPH] = EpilogueCheck;
1515
1516 // First, connect the edges from the bypass blocks (minimum iteration checks,
1517 // runtime checks) to the scalar preheader, in reverse order, to preserve the
1518 // predecessor order of the generated IR. The middle block is the first
1519 // predecessor. MainCheck only bypasses the main vector loop; connect it to
1520 // the epilogue vector preheader instead.
1521 VPBasicBlock *EpiScalarPH = EpiPlan.getScalarPreheader();
1522 for (VPBlockBase *MainVPBB :
1523 reverse(drop_begin(MainScalarPH->predecessors()))) {
1524 VPBlockBase *EpiVPBB = MainToEpiVPBB.lookup(MainVPBB);
1525 if (MainVPBB == MainCheck) {
1526 VPBlockUtils::connectBlocks(EpiVPBB, VectorPH);
1527 continue;
1528 }
1529 VPBlockUtils::connectBlocks(EpiVPBB, EpiScalarPH);
1530 addIncomingForLastPredecessor(EpiScalarPH);
1531 }
1532
1533 // Mirror MainPlan's CFG, skipping the bypass edges connected above, which
1534 // come first, edges to blocks not modeled in EpiPlan and the main vector
1535 // loop's back-edge (to a block earlier in RPO), so EpiPlan contains no loop
1536 // it does not own.
1538 for (auto &[MainVPBB, EpiVPBB] : drop_end(MainToEpiVPBB)) {
1539 Visited.insert(MainVPBB);
1540 for (VPBlockBase *Succ :
1541 drop_begin(MainVPBB->getSuccessors(), EpiVPBB->getNumSuccessors()))
1542 if (auto *SuccVPBB = MainToEpiVPBB.lookup(Succ);
1543 SuccVPBB && !Visited.contains(Succ))
1544 VPBlockUtils::connectBlocks(EpiVPBB, SuccVPBB);
1545 }
1546 return EpilogueCheck;
1547}
1548
1549// Likelyhood of bypassing the vectorized loop due to a runtime check block,
1550// including memory overlap checks block and wrapping/unit-stride checks block.
1551static constexpr uint32_t CheckBypassWeights[] = {1, 127};
1552
1553/// Create a BranchOnCond terminator in \p CheckBlockVPBB. Optionally adds
1554/// branch weights.
1555static void addBypassBranch(VPlan &Plan, VPBasicBlock *CheckBlockVPBB,
1556 VPValue *Cond, bool AddBranchWeights) {
1558 auto *Term = VPBuilder(CheckBlockVPBB)
1560 if (AddBranchWeights) {
1561 MDBuilder MDB(Plan.getContext());
1562 MDNode *BranchWeights =
1563 MDB.createBranchWeights(CheckBypassWeights, /*IsExpected=*/false);
1564 Term->setMetadata(LLVMContext::MD_prof, BranchWeights);
1565 }
1566}
1567
1569 VPBasicBlock *CheckBlock,
1570 bool AddBranchWeights) {
1571 insertCheckBlockBeforeVectorLoop(Plan, CheckBlock);
1572 addBypassBranch(Plan, CheckBlock, Cond, AddBranchWeights);
1573}
1574
1576 BasicBlock *CheckBlock,
1577 bool AddBranchWeights) {
1578 VPValue *CondVPV = Plan.getOrAddLiveIn(Cond);
1579 VPBasicBlock *CheckBlockVPBB = Plan.createVPIRBasicBlock(CheckBlock);
1580 attachVPCheckBlock(Plan, CondVPV, CheckBlockVPBB, AddBranchWeights);
1581}
1582
1583/// Generate recipes for the memory runtime checks \p Checks of \p TheLoop
1584/// using \p Builder and return the condition that is true if any check fails.
1586 VPSCEVExpander &Expander,
1588 const Loop *TheLoop, ScalarEvolution &SE,
1589 DebugLoc DL) {
1590 // Expand each group's bounds once so all checks reuse the same frozen values.
1592 std::tuple<VPValue *, VPValue *, const SCEV *>, 8>
1593 GroupToBounds;
1594 for (const auto &[A, B] : Checks) {
1595 for (const RuntimeCheckingPtrGroup *CG : {A, B}) {
1596 if (GroupToBounds.contains(CG))
1597 continue;
1598 auto [Low, High, Stride] = getRuntimeCheckBounds(
1599 CG, TheLoop, SE, VectorizerParams::HoistRuntimeChecks);
1600 VPValue *Start = Expander.expand(Low);
1601 VPValue *End = Expander.expand(High);
1602 if (CG->NeedsFreeze) {
1603 Start = Builder.createFreeze(Start, DL);
1604 End = Builder.createFreeze(End, DL);
1605 }
1606 GroupToBounds[CG] = {Start, End, Stride};
1607 }
1608 }
1609
1610 VPValue *Cond = Plan.getFalse();
1611 SmallPtrSet<const SCEV *, 4> CheckedStrides;
1612 for (const auto &[A, B] : Checks) {
1613 auto [AStart, AEnd, AStride] = GroupToBounds[A];
1614 auto [BStart, BEnd, BStride] = GroupToBounds[B];
1615 VPValue *Bound0 =
1616 Builder.createICmp(CmpInst::ICMP_ULT, AStart, BEnd, DL, "bound0");
1617 VPValue *Bound1 =
1618 Builder.createICmp(CmpInst::ICMP_ULT, BStart, AEnd, DL, "bound1");
1619 VPValue *IsConflict =
1620 Builder.createAnd(Bound0, Bound1, DL, "found.conflict");
1621 for (const SCEV *Stride : {AStride, BStride}) {
1622 if (!Stride || !CheckedStrides.insert(Stride).second)
1623 continue;
1624 VPValue *StrideV = Expander.expand(Stride);
1625 VPValue *IsNegative = Builder.createICmp(
1626 CmpInst::ICMP_SLT, StrideV, Plan.getZero(StrideV->getScalarType()),
1627 DL, "stride.check");
1628 IsConflict = Builder.createOr(IsConflict, IsNegative, DL);
1629 }
1630 Cond = Builder.createOr(Cond, IsConflict, DL, "conflict.rdx");
1631 }
1632 return Cond;
1633}
1634
1635/// Generate recipes for the memory runtime difference checks \p Checks using
1636/// \p Builder and return the condition that is true if any check fails. Each
1637/// difference is compared against a threshold derived from \p VF and \p UF.
1639 VPSCEVExpander &Expander,
1642 unsigned UF, DebugLoc DL) {
1643 // Set of operand pairs of already created compares, to allow detecting and
1644 // re-using redundant compares.
1646 VPValue *Cond = Plan.getFalse();
1647 for (const auto &[SrcStart, SinkStart, AccessSize, NeedsFreeze] : Checks) {
1648 assert(UF * AccessSize > 0 &&
1649 "Threshold must be non-zero to use diff-check");
1650 Type *Ty = SinkStart->getType();
1651 const SCEV *TotalAccessSize = SE.getElementCount(Ty, VF * UF * AccessSize);
1652 const SCEV *ThresholdMinusOneSCEV =
1653 SE.getMinusSCEV(TotalAccessSize, SE.getOne(Ty));
1654 const SCEV *DiffSCEV = SE.getMinusSCEV(SinkStart, SrcStart);
1655
1656 // If the same compare has already been created earlier, there is no need to
1657 // check it again.
1658 if (!SeenCompares.insert({DiffSCEV, ThresholdMinusOneSCEV}).second)
1659 continue;
1660
1661 VPValue *ThresholdMinusOne = Expander.expand(ThresholdMinusOneSCEV);
1662 VPValue *Diff = Expander.expand(DiffSCEV);
1663 // Use (Diff - 1) <u (Threshold - 1), equivalent to 0 <u Diff <u Threshold,
1664 // to exclude Diff == 0 (equal pointers are safe).
1665 VPValue *DiffMinusOne =
1666 Builder.createSub(Diff, Plan.getConstantInt(Ty, 1), DL);
1667 VPValue *IsConflict = Builder.createICmp(
1668 CmpInst::ICMP_ULT, DiffMinusOne, ThresholdMinusOne, DL, "diff.check");
1669 if (NeedsFreeze)
1670 IsConflict = Builder.createFreeze(IsConflict, DL, "diff.check.fr");
1671 Cond = Builder.createOr(Cond, IsConflict, DL, "conflict.rdx");
1672 }
1673 return Cond;
1674}
1675
1677 VPlan &Plan, const RuntimePointerChecking &RtPtrChecking,
1678 const Loop *TheLoop, ScalarEvolution &SE, ElementCount VF, unsigned UF,
1679 bool AddBranchWeights) {
1680 assert(!RtPtrChecking.getChecks().empty() && "No checks to generate");
1681
1682 DebugLoc DL = TheLoop->getStartLoc();
1683 auto *MemCheckVPBB = Plan.createVPBasicBlock("vector.memcheck");
1684 VPBuilder Builder(MemCheckVPBB);
1685 VPSCEVExpander Expander(Builder, SE, DL, TheLoop->getParentLoop());
1686 auto DiffChecks = RtPtrChecking.getDiffChecks();
1687 VPValue *Cond =
1688 DiffChecks
1689 ? createDiffRuntimeChecks(Plan, Builder, Expander, *DiffChecks, SE,
1690 VF, UF, DL)
1691 : createRuntimeChecks(Plan, Builder, Expander,
1692 RtPtrChecking.getChecks(), TheLoop, SE, DL);
1693 attachVPCheckBlock(Plan, Cond, MemCheckVPBB, AddBranchWeights);
1694}
1695
1697 VPlan &Plan, ElementCount VF, unsigned UF,
1698 ElementCount MinProfitableTripCount, bool RequiresScalarEpilogue,
1699 bool TailFolded, Loop *OrigLoop, const uint32_t *MinItersBypassWeights,
1701 // Generate code to check if the loop's trip count is less than VF * UF, or
1702 // equal to it in case a scalar epilogue is required; this implies that the
1703 // vector trip count is zero. This check also covers the case where adding one
1704 // to the backedge-taken count overflowed leading to an incorrect trip count
1705 // of zero. In this case we will also jump to the scalar loop.
1706 CmpInst::Predicate CmpPred =
1707 RequiresScalarEpilogue ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_ULT;
1708 // If tail is to be folded, vector loop takes care of all iterations.
1709 VPValue *TripCountVPV = Plan.getTripCount();
1710 const SCEV *TripCount = vputils::getSCEVExprForVPValue(TripCountVPV, PSE);
1711 Type *TripCountTy = TripCount->getType();
1712 ScalarEvolution &SE = *PSE.getSE();
1713 auto GetMinTripCount = [&]() -> const SCEV * {
1714 // Compute max(MinProfitableTripCount, UF * VF) and return it.
1715 const SCEV *VFxUF =
1716 SE.getElementCount(TripCountTy, (VF * UF), SCEV::FlagNUW);
1717 if (UF * VF.getKnownMinValue() >=
1718 MinProfitableTripCount.getKnownMinValue()) {
1719 // TODO: SCEV should be able to simplify test.
1720 return VFxUF;
1721 }
1722 const SCEV *MinProfitableTripCountSCEV =
1723 SE.getElementCount(TripCountTy, MinProfitableTripCount, SCEV::FlagNUW);
1724 return SE.getUMaxExpr(MinProfitableTripCountSCEV, VFxUF);
1725 };
1726
1727 VPBuilder Builder(CheckBlock);
1728 VPValue *TripCountCheck = Plan.getFalse();
1729 const SCEV *Step = GetMinTripCount();
1730 // TripCountCheck = false, folding tail implies positive vector trip
1731 // count.
1732 if (!TailFolded) {
1733 // TODO: Emit unconditional branch to vector preheader instead of
1734 // conditional branch with known condition.
1735 TripCount = SE.applyLoopGuards(TripCount, OrigLoop);
1736 // Check if the trip count is < the step.
1737 if (SE.isKnownPredicate(CmpPred, TripCount, Step)) {
1738 // TODO: Ensure step is at most the trip count when determining max VF and
1739 // UF, w/o tail folding.
1740 TripCountCheck = Plan.getTrue();
1741 } else if (!SE.isKnownPredicate(CmpInst::getInversePredicate(CmpPred),
1742 TripCount, Step)) {
1743 // Generate the minimum iteration check only if we cannot prove the
1744 // check is known to be true, or known to be false.
1745 VPValue *MinTripCountVPV =
1746 VPSCEVExpander(Builder, *PSE.getSE(), DL).expand(Step);
1747 TripCountCheck = Builder.createICmp(
1748 CmpPred, TripCountVPV, MinTripCountVPV, DL, "min.iters.check");
1749 } // else step known to be < trip count, use TripCountCheck preset to false.
1750 }
1751 VPInstruction *Term =
1752 Builder.createNaryOp(VPInstruction::BranchOnCond, {TripCountCheck}, DL);
1754 MDBuilder MDB(Plan.getContext());
1755 MDNode *BranchWeights = MDB.createBranchWeights(
1756 ArrayRef(MinItersBypassWeights, 2), /*IsExpected=*/false);
1757 Term->setMetadata(LLVMContext::MD_prof, BranchWeights);
1758 }
1759}
1760
1762 VPlan &Plan, ElementCount VF, unsigned UF, bool RequiresScalarEpilogue,
1763 Loop *OrigLoop, const uint32_t *MinItersBypassWeights, DebugLoc DL,
1765 auto *CheckBlock = Plan.createVPBasicBlock("vector.main.loop.iter.check");
1766 insertCheckBlockBeforeVectorLoop(Plan, CheckBlock);
1768 RequiresScalarEpilogue, /*TailFolded=*/false,
1769 OrigLoop, MinItersBypassWeights, DL, PSE,
1770 CheckBlock);
1771}
1772
1774 VPlan &Plan, VPValue *MainVectorTripCount, bool RequiresScalarEpilogue,
1775 ElementCount EpilogueVF, unsigned MainLoopStep, unsigned EpilogueLoopStep,
1776 ScalarEvolution &SE) {
1777 // Add the minimum iteration check for the epilogue vector loop.
1778 VPValue *TC = Plan.getTripCount();
1779 VPBuilder Builder(cast<VPBasicBlock>(Plan.getEntry()));
1780 VPValue *VFxUF = Builder.createExpandSCEV(
1781 SE.getElementCount(TC->getScalarType(), EpilogueVF, SCEV::FlagNUW));
1782 Builder.setInsertPoint(
1784 VPValue *Count = Builder.createSub(TC, MainVectorTripCount,
1785 DebugLoc::getUnknown(), "n.vec.remaining");
1786
1787 // Generate code to check if the loop's trip count is less than VF * UF of
1788 // the vector epilogue loop.
1789 auto P = RequiresScalarEpilogue ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_ULT;
1790 auto *CheckMinIters = Builder.createICmp(
1791 P, Count, VFxUF, DebugLoc::getUnknown(), "min.epilog.iters.check");
1792 VPInstruction *Branch =
1793 Builder.createNaryOp(VPInstruction::BranchOnCond, CheckMinIters);
1794
1795 // We assume the remaining `Count` is equally distributed in
1796 // [0, MainLoopStep)
1797 // So the probability for `Count < EpilogueLoopStep` should be
1798 // min(MainLoopStep, EpilogueLoopStep) / MainLoopStep
1799 // TODO: Improve the estimate by taking the estimated trip count into
1800 // consideration.
1801 unsigned EstimatedSkipCount = std::min(MainLoopStep, EpilogueLoopStep);
1802 const uint32_t Weights[] = {EstimatedSkipCount,
1803 MainLoopStep - EstimatedSkipCount};
1804 MDBuilder MDB(Plan.getContext());
1805 MDNode *BranchWeights =
1806 MDB.createBranchWeights(Weights, /*IsExpected=*/false);
1807 Branch->setMetadata(LLVMContext::MD_prof, BranchWeights);
1808}
1809
1810/// Find and return the final select instruction of the FindIV result pattern
1811/// for the given \p BackedgeVal:
1812/// select(icmp ne ComputeReductionResult(ReducedIV), Sentinel),
1813/// ComputeReductionResult(ReducedIV), Start.
1815 return cast<VPInstruction>(
1816 vputils::findRecipe(BackedgeVal, [BackedgeVal](VPRecipeBase *R) {
1817 auto *VPI = dyn_cast<VPInstruction>(R);
1818 return VPI &&
1819 matchFindIVResult(VPI, m_Specific(BackedgeVal), m_VPValue());
1820 }));
1821}
1822
1824 auto GetMinOrMaxCompareValue =
1825 [](VPReductionPHIRecipe *RedPhiR) -> VPValue * {
1826 auto *MinOrMaxR =
1827 dyn_cast_or_null<VPRecipeWithIRFlags>(RedPhiR->getBackedgeValue());
1828 if (!MinOrMaxR)
1829 return nullptr;
1830
1831 // Check that MinOrMaxR is a VPWidenIntrinsicRecipe or VPReplicateRecipe
1832 // with an intrinsic that matches the reduction kind.
1833 Intrinsic::ID ExpectedIntrinsicID =
1834 getMinMaxReductionIntrinsicOp(RedPhiR->getRecurrenceKind());
1835 if (!match(MinOrMaxR, m_Intrinsic(ExpectedIntrinsicID)))
1836 return nullptr;
1837
1838 // MinOrMaxR must combine RedPhiR directly with the new element, as the NaN
1839 // check added below only covers the other operand.
1840 // TODO: Support multi-step min/max chains (e.g. maxnum(l, maxnum(k, phi)))
1841 // by checking all operands feeding the chain for NaNs.
1842 if (MinOrMaxR->getOperand(0) == RedPhiR)
1843 return MinOrMaxR->getOperand(1);
1844 if (MinOrMaxR->getOperand(1) == RedPhiR)
1845 return MinOrMaxR->getOperand(0);
1846 return nullptr;
1847 };
1848
1849 VPRegionBlock *LoopRegion = Plan.getVectorLoopRegion();
1851 MinOrMaxNumReductionsToHandle;
1852 bool HasUnsupportedPhi = false;
1853 for (auto &R : LoopRegion->getEntryBasicBlock()->phis()) {
1855 continue;
1856 auto *Cur = dyn_cast<VPReductionPHIRecipe>(&R);
1857 if (!Cur) {
1858 // TODO: Also support fixed-order recurrence phis.
1859 HasUnsupportedPhi = true;
1860 continue;
1861 }
1863 Cur->getRecurrenceKind())) {
1864 HasUnsupportedPhi = true;
1865 continue;
1866 }
1867
1868 VPValue *MinOrMaxOp = GetMinOrMaxCompareValue(Cur);
1869 if (!MinOrMaxOp)
1870 return false;
1871
1872 MinOrMaxNumReductionsToHandle.emplace_back(Cur, MinOrMaxOp);
1873 }
1874
1875 if (MinOrMaxNumReductionsToHandle.empty())
1876 return true;
1877
1878 // We won't be able to resume execution in the scalar tail, if there are
1879 // unsupported header phis or there is no scalar tail at all, due to
1880 // tail-folding.
1881 if (HasUnsupportedPhi || !Plan.hasScalarTail())
1882 return false;
1883
1884 // TODO: Support loops with uncountable early exits; their latch is not
1885 // terminated by BranchOnCount.
1886 VPBasicBlock *LatchVPBB = LoopRegion->getExitingBasicBlock();
1887 if (!match(LatchVPBB->getTerminator(), m_BranchOnCount()))
1888 return false;
1889
1890 /// Check if the vector loop of \p Plan can early exit and restart
1891 /// execution of last vector iteration in the scalar loop. This requires all
1892 /// recipes up to early exit point be side-effect free as they are
1893 /// re-executed. Currently we check that the loop is free of any recipe that
1894 /// may write to memory. Expected to operate on an early VPlan w/o nested
1895 /// regions.
1898 auto *VPBB = cast<VPBasicBlock>(VPB);
1899 for (auto &R : *VPBB) {
1900 if (R.mayWriteToMemory() && !match(&R, m_BranchOnCount()))
1901 return false;
1902 }
1903 }
1904
1905 // Freeze MinOrMaxOps since:
1906 // * multiple uses are introduced and the value may be undef
1907 // * they feed into a branch condition, so block poison propagation to
1908 // prevent immediate UB
1909 for (auto &[Phi, MinOrMaxOp] : MinOrMaxNumReductionsToHandle) {
1910 VPRecipeBase *MinOrMaxR = Phi->getBackedgeValue()->getDefiningRecipe();
1911 VPInstruction *Freeze = VPBuilder(MinOrMaxR).createFreeze(MinOrMaxOp);
1912 MinOrMaxR->replaceUsesOfWith(MinOrMaxOp, Freeze);
1913 MinOrMaxOp = Freeze;
1914 }
1915
1916 VPBuilder LatchBuilder(LatchVPBB->getTerminator());
1917 VPValue *AllNaNLanes = nullptr;
1918 SmallPtrSet<VPValue *, 2> RdxResults;
1919 for (const auto &[_, MinOrMaxOp] : MinOrMaxNumReductionsToHandle) {
1920 VPValue *RedNaNLanes =
1921 LatchBuilder.createFCmp(CmpInst::FCMP_UNO, MinOrMaxOp, MinOrMaxOp);
1922 AllNaNLanes = AllNaNLanes ? LatchBuilder.createOr(AllNaNLanes, RedNaNLanes)
1923 : RedNaNLanes;
1924 }
1925
1926 VPValue *AnyNaNLane =
1927 LatchBuilder.createNaryOp(VPInstruction::AnyOf, {AllNaNLanes});
1928 VPBasicBlock *MiddleVPBB = Plan.getMiddleBlock();
1929 VPBuilder MiddleBuilder(MiddleVPBB->begin());
1930 for (const auto &[RedPhiR, _] : MinOrMaxNumReductionsToHandle) {
1932 RedPhiR->getRecurrenceKind()) &&
1933 "unsupported reduction");
1934
1935 // If we exit early due to NaNs, compute the final reduction result based on
1936 // the reduction phi at the beginning of the last vector iteration.
1937 auto *RdxResult = vputils::findComputeReductionResult(RedPhiR);
1938 assert(RdxResult && "must find a ComputeReductionResult");
1939
1940 auto *NewSel = MiddleBuilder.createSelect(AnyNaNLane, RedPhiR,
1941 RdxResult->getOperand(0));
1942 RdxResult->setOperand(0, NewSel);
1943 assert(!RdxResults.contains(RdxResult) && "RdxResult already used");
1944 RdxResults.insert(RdxResult);
1945 }
1946
1947 auto *LatchExitingBranch = LatchVPBB->getTerminator();
1948 assert(match(LatchExitingBranch, m_BranchOnCount(m_VPValue(), m_VPValue())) &&
1949 "Unexpected terminator");
1950 auto *IsLatchExitTaken = LatchBuilder.createICmp(
1951 CmpInst::ICMP_EQ, LatchExitingBranch->getOperand(0),
1952 LatchExitingBranch->getOperand(1));
1953 auto *AnyExitTaken = LatchBuilder.createOr(AnyNaNLane, IsLatchExitTaken);
1954 LatchBuilder.createNaryOp(VPInstruction::BranchOnCond, AnyExitTaken);
1955 LatchExitingBranch->eraseFromParent();
1956
1957 // Update resume phis for inductions in the scalar preheader. If AnyNaNLane is
1958 // true, the resume from the start of the last vector iteration via the
1959 // canonical IV, otherwise from the original value.
1960 auto IsTC = [&Plan](VPValue *V) {
1961 return V == &Plan.getVectorTripCount() || V == Plan.getTripCount();
1962 };
1963 for (auto &R : Plan.getScalarPreheader()->phis()) {
1964 auto *ResumeR = cast<VPPhi>(&R);
1965 VPValue *VecV = ResumeR->getOperand(0);
1966 if (RdxResults.contains(VecV))
1967 continue;
1968 if (auto *DerivedIV = dyn_cast<VPDerivedIVRecipe>(VecV)) {
1969 VPValue *DIVTC = DerivedIV->getOperand(1);
1970 if (DerivedIV->hasOneUse() && IsTC(DIVTC)) {
1971 auto *NewSel = MiddleBuilder.createSelect(
1972 AnyNaNLane, LoopRegion->getCanonicalIV(), DIVTC);
1973 DerivedIV->moveAfter(MiddleBuilder.getRecipeAtInsertPoint());
1974 DerivedIV->setOperand(1, NewSel);
1975 continue;
1976 }
1977 }
1978 // Bail out and abandon the current, partially modified, VPlan if we
1979 // encounter resume phi that cannot be updated yet.
1980 if (!IsTC(VecV)) {
1981 LLVM_DEBUG(dbgs() << "Found resume phi we cannot update for VPlan with "
1982 "FMaxNum/FMinNum reduction.\n");
1983 return false;
1984 }
1985 auto *NewSel = MiddleBuilder.createSelect(
1986 AnyNaNLane, LoopRegion->getCanonicalIV(), VecV);
1987 ResumeR->setOperand(0, NewSel);
1988 }
1989
1990 auto *MiddleTerm = MiddleVPBB->getTerminator();
1991 MiddleBuilder.setInsertPoint(MiddleTerm);
1992 VPValue *MiddleCond = MiddleTerm->getOperand(0);
1993 VPValue *NewCond =
1994 MiddleBuilder.createAnd(MiddleCond, MiddleBuilder.createNot(AnyNaNLane));
1995 MiddleTerm->setOperand(0, NewCond);
1996 return true;
1997}
1998
2000 if (Plan.hasScalarVFOnly())
2001 return false;
2002
2003 // We want to create the following nodes:
2004 // vector.body:
2005 // ...new WidenPHI recipe introduced to keep the mask value for the latest
2006 // iteration where any lane was active.
2007 // mask.phi = phi [ ir<false>, vector.ph ], [ vp<new.mask>, vector.body ]
2008 // ...data.phi (a VPReductionPHIRecipe for a FindLast reduction) already
2009 // exists, but needs updating to use 'new.data' for the backedge value.
2010 // data.phi = phi ir<default.val>, vp<new.data>
2011 //
2012 // ...'data' and 'compare' created by existing nodes...
2013 //
2014 // ...new recipes introduced to determine whether to update the reduction
2015 // values or keep the current one.
2016 // any.active = i1 any-of ir<compare>
2017 // new.mask = select vp<any.active>, ir<compare>, vp<mask.phi>
2018 // new.data = select vp<any.active>, ir<data>, ir<data.phi>
2019 //
2020 // middle.block:
2021 // ...extract-last-active replaces compute-reduction-result.
2022 // result = extract-last-active vp<new.data>, vp<new.mask>, ir<default.val>
2023
2028 PhiR.getRecurrenceKind()))
2029 Phis.push_back(&PhiR);
2030 }
2031
2032 if (Phis.empty())
2033 return true;
2034
2035 VPValue *HeaderMask = Plan.getVectorLoopRegion()->getHeaderMask();
2036 for (VPReductionPHIRecipe *PhiR : Phis) {
2037 // Find the condition for the select/blend.
2038 VPValue *BackedgeSelect = PhiR->getBackedgeValue();
2039 VPValue *CondSelect = BackedgeSelect;
2040
2041 // If there's a header mask, the backedge select will not be the find-last
2042 // select.
2043 if (HeaderMask &&
2044 !match(BackedgeSelect,
2045 m_SelectLike(m_Specific(HeaderMask), m_VPValue(CondSelect),
2046 m_Specific(PhiR))))
2047 return false;
2048
2049 VPValue *Cond = nullptr, *Op1 = nullptr, *Op2 = nullptr;
2050
2051 // If we're matching a blend rather than a select, there should be one
2052 // incoming value which is the data, then all other incoming values should
2053 // be the phi.
2054 auto MatchBlend = [&](VPRecipeBase *R) {
2055 auto *Blend = dyn_cast<VPBlendRecipe>(R);
2056 if (!Blend)
2057 return false;
2058 assert(!Blend->isNormalized() && "must run before blend normalizaion");
2059 unsigned NumIncomingDataValues = 0;
2060 for (unsigned I = 0; I < Blend->getNumIncomingValues(); ++I) {
2061 VPValue *Incoming = Blend->getIncomingValue(I);
2062 if (Incoming != PhiR) {
2063 ++NumIncomingDataValues;
2064 Cond = Blend->getMask(I);
2065 Op1 = Incoming;
2066 Op2 = PhiR;
2067 }
2068 }
2069 return NumIncomingDataValues == 1;
2070 };
2071
2072 VPSingleDefRecipe *SelectR =
2074 if (!match(SelectR,
2075 m_Select(m_VPValue(Cond), m_VPValue(Op1), m_VPValue(Op2))) &&
2076 !MatchBlend(SelectR))
2077 return false;
2078
2079 // Bail out if PhiR has users other than the find-last select/blend and the
2080 // header mask select, e.g. nested blends. Then the data operand may be PhiR
2081 // on some paths and Cond does not determine the lanes to update.
2082 if (any_of(PhiR->users(), [&](VPUser *U) {
2083 return U != SelectR && U != BackedgeSelect->getDefiningRecipe();
2084 }))
2085 return false;
2086
2087 assert(Cond != HeaderMask && "Cond must not be HeaderMask");
2088
2089 // Find final reduction computation and replace it with an
2090 // extract.last.active intrinsic.
2091 auto *RdxResult =
2093 assert(RdxResult && "Could not find reduction result");
2094
2095 // Add mask phi.
2096 VPBuilder Builder = VPBuilder::getToInsertAfter(PhiR);
2097 auto *MaskPHI = Builder.createWidenPhi(Plan.getFalse());
2098
2099 // Add select for mask.
2100 Builder.setInsertPoint(SelectR);
2101
2102 if (Op1 == PhiR) {
2103 // Normalize to selecting the data operand when the condition is true by
2104 // swapping operands and negating the condition.
2105 std::swap(Op1, Op2);
2106 Cond = Builder.createNot(Cond);
2107 }
2108 assert(Op2 == PhiR && "data value must be selected if Cond is true");
2109
2110 if (HeaderMask)
2111 Cond = Builder.createLogicalAnd(HeaderMask, Cond);
2112
2113 Cond = Builder.createFreeze(Cond);
2114 VPValue *AnyOf = Builder.createNaryOp(VPInstruction::AnyOf, Cond);
2115 VPValue *MaskSelect = Builder.createSelect(AnyOf, Cond, MaskPHI);
2116 MaskPHI->addIncoming(MaskSelect);
2117
2118 // Replace select for data.
2119 VPValue *DataSelect =
2120 Builder.createSelect(AnyOf, Op1, Op2, SelectR->getDebugLoc());
2121 SelectR->replaceAllUsesWith(DataSelect);
2122 PhiR->setBackedgeValue(DataSelect);
2123 SelectR->eraseFromParent();
2124
2125 Builder.setInsertPoint(RdxResult);
2126 auto *ExtractLastActive =
2127 Builder.createNaryOp(VPInstruction::ExtractLastActive,
2128 {PhiR->getStartValue(), DataSelect, MaskSelect},
2129 RdxResult->getDebugLoc());
2130 RdxResult->replaceAllUsesWith(ExtractLastActive);
2131 RdxResult->eraseFromParent();
2132 }
2133
2134 return true;
2135}
2136
2137/// Given a first argmin/argmax pattern with strict predicate consisting of
2138/// 1) a MinOrMax reduction \p MinOrMaxPhiR producing \p MinOrMaxResult,
2139/// 2) a wide induction \p WideIV,
2140/// 3) a FindLastIV reduction \p FindLastIVPhiR using \p WideIV,
2141/// return the smallest index of the FindLastIV reduction result using UMin,
2142/// unless \p MinOrMaxResult equals the start value of its MinOrMax reduction.
2143/// In that case, return the start value of the FindLastIV reduction instead.
2144/// If \p WideIV is not canonical, a new canonical wide IV is added, and the
2145/// final result is scaled back to the non-canonical \p WideIV.
2146/// The final value of the FindLastIV reduction is originally computed using
2147/// \p FindIVSelect, \p FindIVCmp, and \p FindIVRdxResult, which are replaced
2148/// and removed.
2149/// Returns true if the pattern was handled successfully, false otherwise.
2151 VPlan &Plan, VPReductionPHIRecipe *MinOrMaxPhiR,
2152 VPReductionPHIRecipe *FindLastIVPhiR, VPWidenIntOrFpInductionRecipe *WideIV,
2153 VPInstruction *MinOrMaxResult, VPInstruction *FindIVSelect,
2154 VPRecipeBase *FindIVCmp, VPInstruction *FindIVRdxResult) {
2155 assert(!FindLastIVPhiR->isInLoop() && !FindLastIVPhiR->isOrdered() &&
2156 "inloop and ordered reductions not supported");
2157 assert(FindLastIVPhiR->getVFScaleFactor() == 1 &&
2158 "FindIV reduction must not be scaled");
2159
2160 // TODO: support for FP in handleFirstArgMinOrMax
2162 MinOrMaxPhiR->getRecurrenceKind()))
2163 return false;
2164
2166 // TODO: Support non (i.e., narrower than) canonical IV types.
2167 // TODO: Emit remarks for failed transformations.
2168 if (Ty != WideIV->getScalarType())
2169 return false;
2170
2171 VPValue *HeaderMask = Plan.getVectorLoopRegion()->getHeaderMask();
2172 auto *BackedgeVal = FindLastIVPhiR->getBackedgeValue();
2173 auto *FindIVSelectVal = BackedgeVal;
2174 if (HeaderMask && !match(BackedgeVal, m_Select(m_Specific(HeaderMask),
2175 m_VPValue(FindIVSelectVal),
2176 m_Specific(FindLastIVPhiR))))
2177 return false;
2178 auto *FindIVSelectR =
2179 cast<VPSingleDefRecipe>(FindIVSelectVal->getDefiningRecipe());
2180
2181 assert(
2182 match(FindIVSelectR, m_Select(m_VPValue(), m_VPValue(), m_VPValue())) &&
2183 "backedge value must be a select");
2184 if (FindIVSelectR->getOperand(1) != WideIV &&
2185 FindIVSelectR->getOperand(2) != WideIV)
2186 return false;
2187
2188 // If the original wide IV is not canonical, create a new one. The canonical
2189 // wide IV is guaranteed to not wrap for all lanes that are active in the
2190 // vector loop.
2191 if (!WideIV->isCanonical()) {
2192 VPIRValue *Zero = Plan.getConstantInt(Ty, 0);
2193 VPIRValue *One = Plan.getConstantInt(Ty, 1);
2194 auto *WidenCanIV = new VPWidenIntOrFpInductionRecipe(
2195 nullptr, Zero, One, WideIV->getVFValue(),
2196 WideIV->getInductionDescriptor(),
2197 VPIRFlags::WrapFlagsTy(/*HasNUW=*/true, /*HasNSW=*/false),
2198 WideIV->getDebugLoc());
2199 WidenCanIV->insertBefore(WideIV);
2200
2201 // Update the select to use the wide canonical IV.
2202 FindIVSelectR->setOperand(FindIVSelectR->getOperand(1) == WideIV ? 1 : 2,
2203 WidenCanIV);
2204 }
2205 FindLastIVPhiR->setOperand(0, Plan.getPoison(Ty));
2206
2207 // The reduction using MinOrMaxPhiR needs adjusting to compute the correct
2208 // result:
2209 // 1. Find the first canonical indices corresponding to partial min/max
2210 // values, using loop reductions.
2211 // 2. Find which of the partial min/max values are equal to the overall
2212 // min/max value.
2213 // 3. Select among the canonical indices those corresponding to the overall
2214 // min/max value.
2215 // 4. Find the first canonical index of overall min/max and scale it back to
2216 // the original IV using VPDerivedIVRecipe.
2217 // 5. If the overall min/max equals the starting min/max, the condition in
2218 // the loop was always false, due to being strict; return the start value
2219 // of FindLastIVPhiR in that case.
2220 //
2221 // For example, we transforms two independent reduction result computations
2222 // for
2223 //
2224 // <x1> vector loop: {
2225 // vector.body:
2226 // ...
2227 // ir<%iv> = WIDEN-INDUCTION nuw nsw ir<10>, ir<1>, vp<%0>
2228 // WIDEN-REDUCTION-PHI ir<%min.idx> = phi ir<sentinel.min.start>,
2229 // ir<%min.idx.next>
2230 // WIDEN-REDUCTION-PHI ir<%min.val> = phi ir<100>, ir<%min.val.next>
2231 // ....
2232 // WIDEN-INTRINSIC ir<%min.val.next> = call llvm.umin(ir<%min.val>, ir<%l>)
2233 // WIDEN ir<%min.idx.next> = select ir<%cmp>, ir<%iv>, ir<%min.idx>
2234 // ...
2235 // }
2236 // Successor(s): middle.block
2237 //
2238 // middle.block:
2239 // vp<%iv.rdx> = compute-reduction-result (smax) vp<%min.idx.next>
2240 // vp<%min.result> = compute-reduction-result (umin) ir<%min.val.next>
2241 // vp<%cmp> = icmp ne vp<%iv.rdx>, ir<sentinel.min.start>
2242 // vp<%find.iv.result> = select vp<%cmp>, vp<%iv.rdx>, ir<10>
2243 //
2244 //
2245 // Into:
2246 //
2247 // vp<%reduced.min> = compute-reduction-result (umin) ir<%min.val.next>
2248 // vp<%reduced.mins.mask> = icmp eq ir<%min.val.next>, vp<%reduced.min>
2249 // vp<%idxs2reduce> = select vp<%reduced.mins.mask>, ir<%min.idx.next>,
2250 // ir<MaxUInt>
2251 // vp<%reduced.idx> = compute-reduction-result (umin) vp<%idxs2reduce>
2252 // vp<%scaled.idx> = DERIVED-IV ir<20> + vp<%reduced.idx> * ir<1>
2253 // vp<%always.false> = icmp eq vp<%reduced.min>, ir<100>
2254 // vp<%final.idx> = select vp<%always.false>, ir<10>,
2255 // vp<%scaled.idx>
2256
2257 VPBuilder Builder(FindIVRdxResult);
2258 VPValue *MinOrMaxExiting = MinOrMaxResult->getOperand(0);
2259 auto *FinalMinOrMaxCmp =
2260 Builder.createICmp(CmpInst::ICMP_EQ, MinOrMaxExiting, MinOrMaxResult);
2261 VPValue *LastIVExiting = FindIVRdxResult->getOperand(0);
2262 VPValue *MaxIV =
2263 Plan.getConstantInt(APInt::getMaxValue(Ty->getIntegerBitWidth()));
2264 auto *FinalIVSelect =
2265 Builder.createSelect(FinalMinOrMaxCmp, LastIVExiting, MaxIV);
2266 VPIRFlags RdxFlags(RecurKind::UMin, false, false, FastMathFlags());
2267 VPSingleDefRecipe *FinalCanIV = Builder.createNaryOp(
2268 VPInstruction::ComputeReductionResult, {FinalIVSelect}, RdxFlags,
2269 FindIVRdxResult->getDebugLoc());
2270
2271 // If we used a new wide canonical IV convert the reduction result back to the
2272 // original IV scale before the final select.
2273 if (!WideIV->isCanonical()) {
2274 auto *DerivedIVRecipe = new VPDerivedIVRecipe(
2276 nullptr, // No FPBinOp for integer induction
2277 WideIV->getStartValue(), FinalCanIV, WideIV->getStepValue());
2278 DerivedIVRecipe->insertBefore(Builder.getRecipeAtInsertPoint());
2279 FinalCanIV = DerivedIVRecipe;
2280 }
2281
2282 // If the final min/max value matches its start value, the condition in the
2283 // loop was always false, i.e. no induction value has been selected. If that's
2284 // the case, set the result of the IV reduction to its start value.
2285 VPValue *AlwaysFalse = Builder.createICmp(CmpInst::ICMP_EQ, MinOrMaxResult,
2286 MinOrMaxPhiR->getStartValue());
2287 VPValue *FinalIV = Builder.createSelect(
2288 AlwaysFalse, FindIVSelect->getOperand(2), FinalCanIV);
2289 FindIVSelect->replaceAllUsesWith(FinalIV);
2290
2291 // Erase the old FindIV result pattern which is now dead.
2292 FindIVSelect->eraseFromParent();
2293 FindIVCmp->eraseFromParent();
2294 FindIVRdxResult->eraseFromParent();
2295 return true;
2296}
2297
2300 Loop *TheLoop) {
2301 for (auto &PhiR : make_early_inc_range(
2303 auto *MinOrMaxPhiR = dyn_cast<VPReductionPHIRecipe>(&PhiR);
2304 // TODO: check for multi-uses in VPlan directly.
2305 if (!MinOrMaxPhiR || !MinOrMaxPhiR->hasUsesOutsideReductionChain())
2306 continue;
2307
2308 // MinOrMaxPhiR has users outside the reduction cycle in the loop. Check if
2309 // the only other user is a FindLastIV reduction. MinOrMaxPhiR must have
2310 // exactly 2 users if not tailfolded:
2311 // 1) the min/max operation of the reduction cycle, and
2312 // 2) the compare of a FindLastIV reduction cycle. This compare must match
2313 // the min/max operation - comparing MinOrMaxPhiR with the operand of the
2314 // min/max operation, and be used only by the select of the FindLastIV
2315 // reduction cycle.
2316 // There is an additional user if the tail was folded:
2317 // 3) the select operation of the vector.latch block. This select uses the
2318 // original MinOrMaxPhiR if the mask is zero.
2319 RecurKind RdxKind = MinOrMaxPhiR->getRecurrenceKind();
2320 assert(
2322 "only min/max recurrences support users outside the reduction chain");
2323
2324 auto *MinOrMaxBackedgeR =
2325 dyn_cast<VPRecipeWithIRFlags>(MinOrMaxPhiR->getBackedgeValue());
2326 if (!MinOrMaxBackedgeR)
2327 return false;
2328
2329 // If the tail was folded then the backedge won't be the
2330 // reduction-intrinsic but the select in the vector.latch block that wraps
2331 // the reduction-intrinsic.
2332 auto *MinOrMaxOp = MinOrMaxBackedgeR;
2333 VPValue *HeaderMask = Plan.getVectorLoopRegion()->getHeaderMask();
2334 VPValue *MinOrMaxTailfold;
2335 if (HeaderMask) {
2336 if (!match(MinOrMaxBackedgeR, m_SelectLike(m_Specific(HeaderMask),
2337 m_VPValue(MinOrMaxTailfold),
2338 m_Specific(MinOrMaxPhiR))))
2339 return false;
2340
2341 MinOrMaxOp = dyn_cast<VPRecipeWithIRFlags>(MinOrMaxTailfold);
2342 if (!MinOrMaxOp)
2343 return false;
2344 }
2345
2346 // Check that MinOrMaxOp is a VPWidenIntrinsicRecipe or
2347 // VPReplicateRecipe with an intrinsic that matches the reduction kind.
2348 Intrinsic::ID ExpectedIntrinsicID = getMinMaxReductionIntrinsicOp(RdxKind);
2349 if (!match(MinOrMaxOp, m_Intrinsic(ExpectedIntrinsicID)))
2350 return false;
2351
2352 // Tailfolded MinOrMaxOp should only feed into the predicated
2353 // select MinOrMaxBackedgeR.
2354 assert((!HeaderMask || MinOrMaxOp->getNumUsers() == 1) &&
2355 "Tailfolded MinOrMaxOp must have exactly 1 user");
2356 // MinOrMaxBackedgeR must have 2 users: 1) MinOrMaxPhiR and 2)
2357 // ComputeReductionResult.
2358 assert(MinOrMaxBackedgeR->getNumUsers() == 2 &&
2359 "MinOrMaxBackedgeR must have exactly 2 users");
2360 // MinOrMaxOp must combine MinOrMaxPhiR directly with the new element;
2361 // reject multi-step min/max chains (e.g. max(l, max(k, phi))), which
2362 // this transform does not handle.
2363 VPValue *MinOrMaxOpValue;
2364 if (MinOrMaxOp->getOperand(0) == MinOrMaxPhiR)
2365 MinOrMaxOpValue = MinOrMaxOp->getOperand(1);
2366 else if (MinOrMaxOp->getOperand(1) == MinOrMaxPhiR)
2367 MinOrMaxOpValue = MinOrMaxOp->getOperand(0);
2368 else
2369 return false;
2370
2371 VPValue *CmpOpA;
2372 VPValue *CmpOpB;
2373 CmpPredicate Pred;
2375 MinOrMaxPhiR, m_Cmp(Pred, m_VPValue(CmpOpA), m_VPValue(CmpOpB)));
2376 if (!Cmp || Cmp->getNumUsers() != 1 ||
2377 (CmpOpA != MinOrMaxOpValue && CmpOpB != MinOrMaxOpValue))
2378 return false;
2379
2380 if (MinOrMaxOpValue != CmpOpB)
2381 Pred = CmpInst::getSwappedPredicate(Pred);
2382
2383 // MinOrMaxPhiR must have exactly 2 users if not tailfolded:
2384 // * MinOrMaxOp,
2385 // * Cmp (that's part of a FindLastIV chain).
2386 // Also an additional third user if it is tailfolded:
2387 // * Predicated HEADER-MASK select in the vector.latch block.
2388 if (MinOrMaxPhiR->getNumUsers() != (HeaderMask ? 3 : 2))
2389 return false;
2390
2391 VPInstruction *MinOrMaxResult =
2393 MinOrMaxBackedgeR);
2394 assert(MinOrMaxResult &&
2395 "MinOrMaxResult must be a user of MinOrMaxBackedgeR");
2396
2397 // Cmp must be used by the select of a FindLastIV chain.
2398 VPValue *Sel = dyn_cast<VPSingleDefRecipe>(Cmp->getSingleUser());
2399 VPValue *IVOp, *FindIV;
2400 if (!Sel || (Sel->getNumUsers() != (HeaderMask ? 1 : 2)) ||
2401 !match(Sel,
2403 return false;
2404
2406 std::swap(FindIV, IVOp);
2407 Pred = CmpInst::getInversePredicate(Pred);
2408 }
2409
2410 auto *FindIVPhiR = dyn_cast<VPReductionPHIRecipe>(FindIV);
2412 FindIVPhiR->getRecurrenceKind()))
2413 return false;
2414
2415 assert(!FindIVPhiR->isInLoop() && !FindIVPhiR->isOrdered() &&
2416 "cannot handle inloop/ordered reductions yet");
2417
2418 // Check if FindIVPhiR is a FindLast pattern by checking the MinMaxKind
2419 // on its ComputeReductionResult. SMax/UMax indicates FindLast.
2420 VPInstruction *FindIVResult =
2422 FindIVPhiR->getBackedgeValue());
2423 assert(FindIVResult &&
2424 "must be able to retrieve the FindIVResult VPInstruction");
2425 RecurKind FindIVMinMaxKind = FindIVResult->getRecurKind();
2426 if (FindIVMinMaxKind != RecurKind::SMax &&
2427 FindIVMinMaxKind != RecurKind::UMax)
2428 return false;
2429
2430 // TODO: Support cases where IVOp is the IV increment.
2431 if (!match(IVOp, m_TruncOrSelf(m_VPValue(IVOp))) ||
2433 return false;
2434
2435 // Check if the predicate is compatible with the reduction kind.
2436 bool IsValidKindPred = [RdxKind, Pred]() {
2437 switch (RdxKind) {
2438 case RecurKind::UMin:
2439 return Pred == CmpInst::ICMP_UGE || Pred == CmpInst::ICMP_UGT;
2440 case RecurKind::UMax:
2441 return Pred == CmpInst::ICMP_ULE || Pred == CmpInst::ICMP_ULT;
2442 case RecurKind::SMax:
2443 return Pred == CmpInst::ICMP_SLE || Pred == CmpInst::ICMP_SLT;
2444 case RecurKind::SMin:
2445 return Pred == CmpInst::ICMP_SGE || Pred == CmpInst::ICMP_SGT;
2446 case RecurKind::FMax:
2448 return Pred == CmpInst::FCMP_OLE || Pred == CmpInst::FCMP_OLT;
2449 case RecurKind::FMin:
2451 return Pred == CmpInst::FCMP_OGE || Pred == CmpInst::FCMP_OGT;
2452 // minnum and maxnum need special handling due to expected sNaN behaviour
2453 // minimum and maximum return NaN if either input is a NAN
2454 case RecurKind::FMinNum:
2455 case RecurKind::FMaxNum:
2458 return false;
2459 default:
2460 llvm_unreachable("unhandled recurrence kind");
2461 }
2462 }();
2463 if (!IsValidKindPred) {
2464 ORE->emit([&]() {
2466 DEBUG_TYPE, "VectorizationMultiUseReductionPredicate",
2467 TheLoop->getStartLoc(), TheLoop->getHeader())
2468 << "Multi-use reduction with predicate "
2470 << " incompatible with reduction kind";
2471 });
2472 return false;
2473 }
2474
2475 if (RdxKind == RecurKind::FMaximumNum ||
2476 RdxKind == RecurKind::FMinimumNum) {
2477 auto *StartC = dyn_cast<VPConstant>(MinOrMaxPhiR->getStartValue());
2478 if (!StartC || StartC->getConstant()->isNaN())
2479 return false;
2480 }
2481
2482 auto *FindIVSelect = findFindIVSelect(FindIVPhiR->getBackedgeValue());
2483 auto *FindIVCmp = FindIVSelect->getOperand(0)->getDefiningRecipe();
2484 auto *FindIVRdxResult = cast<VPInstruction>(FindIVCmp->getOperand(0));
2485 assert(FindIVSelect->getParent() == MinOrMaxResult->getParent() &&
2486 "both results must be computed in the same block");
2487 // Reducing to a scalar min or max value is placed right before reducing to
2488 // its scalar iteration, in order to generate instructions that use both
2489 // their operands.
2490 MinOrMaxResult->moveBefore(FindIVRdxResult->getIterator());
2491
2492 bool IsStrictPredicate = CmpInst::isStrictPredicate(Pred);
2493 if (IsStrictPredicate) {
2494 if (!handleFirstArgMinOrMax(Plan, MinOrMaxPhiR, FindIVPhiR,
2496 MinOrMaxResult, FindIVSelect, FindIVCmp,
2497 FindIVRdxResult))
2498 return false;
2499 continue;
2500 }
2501
2502 // The reduction using MinOrMaxPhiR needs adjusting to compute the correct
2503 // result:
2504 // 1. We need to find the last IV for which the condition based on the
2505 // min/max recurrence is true,
2506 // 2. Compare the partial min/max reduction result to its final value and,
2507 // 3. Select the lanes of the partial FindLastIV reductions which
2508 // correspond to the lanes matching the min/max reduction result.
2509 //
2510 // For example, this transforms
2511 // vp<%min.result> = compute-reduction-result ir<%min.val.next>
2512 // vp<%iv.rdx> = compute-reduction-result (smax) vp<%min.idx.next>
2513 // vp<%cmp> = icmp ne vp<%iv.rdx>, SENTINEL
2514 // vp<%find.iv.result> = select vp<%cmp>, vp<%iv.rdx>, ir<0>
2515 //
2516 // into:
2517 //
2518 // vp<min.result> = compute-reduction-result ir<%min.val.next>
2519 // vp<%final.min.cmp> = icmp eq ir<%min.val.next>, vp<min.result>
2520 // vp<%final.iv> = select vp<%final.min.cmp>, vp<%min.idx.next>, SENTINEL
2521 // vp<%iv.rdx> = compute-reduction-result (smax) vp<%final.iv>
2522 // vp<%cmp> = icmp ne vp<%iv.rdx>, SENTINEL
2523 // vp<%find.iv.result> = select vp<%cmp>, vp<%iv.rdx>, ir<0>
2524 //
2525 VPBuilder B(FindIVRdxResult);
2526 VPValue *MinOrMaxExiting = MinOrMaxResult->getOperand(0);
2527 auto *FinalMinOrMaxCmp =
2529 ? B.createICmp(CmpInst::ICMP_EQ, MinOrMaxExiting, MinOrMaxResult)
2530 : B.createFCmp(CmpInst::FCMP_OEQ, MinOrMaxExiting, MinOrMaxResult);
2531 VPValue *Sentinel = FindIVCmp->getOperand(1);
2532 VPValue *LastIVExiting = FindIVRdxResult->getOperand(0);
2533 auto *FinalIVSelect =
2534 B.createSelect(FinalMinOrMaxCmp, LastIVExiting, Sentinel);
2535 FindIVRdxResult->setOperand(0, FinalIVSelect);
2536 }
2537 return true;
2538}
2539
2541 VPRegionBlock *LoopRegion = Plan.getVectorLoopRegion();
2542 VPValue *HeaderMask = LoopRegion->getHeaderMask();
2543 Type *I1Ty = IntegerType::getInt1Ty(Plan.getContext());
2544
2545 VPBuilder Builder(Plan.getVectorPreheader());
2546 auto *AliasMask = Builder.createNaryOp(
2547 VPInstruction::IncomingAliasMask, {}, nullptr, {}, {},
2548 DebugLoc::getUnknown(), "incoming.alias.mask", I1Ty);
2549
2550 VPBasicBlock *Header = LoopRegion->getEntryBasicBlock();
2551 Builder = VPBuilder(Header->getFirstNonPhi());
2552
2553 // Update all existing users of the header mask to "HeaderMask & AliasMask".
2554 auto *ClampedHeaderMask = Builder.createAnd(HeaderMask, AliasMask);
2555 HeaderMask->replaceUsesWithIf(ClampedHeaderMask,
2556 not_equal_to(ClampedHeaderMask));
2557}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define DEBUG_TYPE
#define _
iv Induction Variable Users
Definition IVUsers.cpp:48
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
This file provides a LoopVectorizationPlanner class.
static constexpr uint32_t MinItersBypassWeights[]
#define I(x, y, z)
Definition MD5.cpp:57
uint64_t High
#define P(N)
SmallVector< MachineOperand, 4 > Cond
Provides some synthesis utilities to produce sequences of values.
This file defines less commonly used SmallVector utilities.
#define LLVM_DEBUG(...)
Definition Debug.h:119
This pass exposes codegen information to IR-level passes.
static bool isHeaderBB(BasicBlock *BB, Loop *L)
static bool handleFirstArgMinOrMax(VPlan &Plan, VPReductionPHIRecipe *MinOrMaxPhiR, VPReductionPHIRecipe *FindLastIVPhiR, VPWidenIntOrFpInductionRecipe *WideIV, VPInstruction *MinOrMaxResult, VPInstruction *FindIVSelect, VPRecipeBase *FindIVCmp, VPInstruction *FindIVRdxResult)
Given a first argmin/argmax pattern with strict predicate consisting of 1) a MinOrMax reduction MinOr...
static VPHeaderPHIRecipe * createWidenInductionRecipe(PHINode *Phi, VPPhi *PhiR, VPIRValue *Start, const InductionDescriptor &IndDesc, VPlan &Plan, PredicatedScalarEvolution &PSE, Loop &OrigLoop, DebugLoc DL)
Creates a VPWidenIntOrFpInductionRecipe or VPWidenPointerInductionRecipe for Phi based on IndDesc.
static void addIncomingForLastPredecessor(VPBasicBlock *VPBB)
Add an incoming value to all phis in VPBB for its just-added last predecessor, re-using the value of ...
static void insertCheckBlockBeforeVectorLoop(VPlan &Plan, VPBasicBlock *CheckBlockVPBB)
Insert CheckBlockVPBB on the edge leading to the vector preheader, connecting it to both vector and s...
static void addBypassBranch(VPlan &Plan, VPBasicBlock *CheckBlockVPBB, VPValue *Cond, bool AddBranchWeights)
Create a BranchOnCond terminator in CheckBlockVPBB.
static VPValue * createDiffRuntimeChecks(VPlan &Plan, VPBuilder &Builder, VPSCEVExpander &Expander, ArrayRef< PointerDiffInfo > Checks, ScalarEvolution &SE, ElementCount VF, unsigned UF, DebugLoc DL)
Generate recipes for the memory runtime difference checks Checks using Builder and return the conditi...
static bool sinkRecurrenceUsersAfterPrevious(VPFirstOrderRecurrencePHIRecipe *FOR, VPRecipeBase *Previous, const VPDominatorTree &VPDT)
Try to sink users of FOR after Previous.
static bool canonicalHeaderAndLatch(VPBlockBase *HeaderVPB, const VPDominatorTree &VPDT)
Checks if HeaderVPB is a loop header block in the plain CFG; that is, it has exactly 2 predecessors (...
static void addInitialSkeleton(VPlan &Plan, Type *InductionTy, PredicatedScalarEvolution &PSE, Loop *TheLoop)
static bool hoistPreviousBeforeFORUsers(VPFirstOrderRecurrencePHIRecipe *FOR, VPRecipeBase *Previous, const VPDominatorTree &VPDT)
Try to hoist Previous and its operands before all users of FOR.
static void createLoopRegion(VPlan &Plan, VPBlockBase *HeaderVPB, DebugLoc DL)
Create a new VPRegionBlock for the loop starting at HeaderVPB.
static VPInstruction * findFindIVSelect(VPValue *BackedgeVal)
Find and return the final select instruction of the FindIV result pattern for the given BackedgeVal: ...
static bool tryToSinkOrHoistRecurrenceUsers(VPBasicBlock *HeaderVPBB, const VPDominatorTree &VPDT)
Sink users of fixed-order recurrences past or hoist before the recipe defining the previous value,...
static constexpr uint32_t CheckBypassWeights[]
static void printAfterInitialConstruction(VPlan &)
To make RUN_VPLAN_PASS print initial VPlan.
static void createExtractsForLiveOuts(VPlan &Plan, VPBasicBlock *MiddleVPBB)
Creates extracts for values in Plan defined in a loop region and used outside a loop region.
static VPValue * createRuntimeChecks(VPlan &Plan, VPBuilder &Builder, VPSCEVExpander &Expander, ArrayRef< RuntimePointerCheck > Checks, const Loop *TheLoop, ScalarEvolution &SE, DebugLoc DL)
Generate recipes for the memory runtime checks Checks of TheLoop using Builder and return the conditi...
This file implements dominator tree analysis for a single level of a VPlan's H-CFG.
This file contains the declarations of different VPlan-related auxiliary helpers.
This file provides utility VPlan to VPlan transformations.
#define RUN_VPLAN_PASS_NO_VERIFY(PASS,...)
This file contains the declarations of the Vectorization Plan base classes:
static APInt getMaxValue(unsigned numBits)
Gets maximum unsigned value of APInt for specific bit width.
Definition APInt.h:202
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
Get the array size.
Definition ArrayRef.h:141
A cache of @llvm.assume calls within a function.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this basic block belongs to.
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
Analysis providing branch probability information.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:740
@ FCMP_OEQ
0 0 0 1 True if ordered and equal
Definition InstrTypes.h:743
@ ICMP_SLT
signed less than
Definition InstrTypes.h:769
@ ICMP_SLE
signed less or equal
Definition InstrTypes.h:770
@ FCMP_OLT
0 1 0 0 True if ordered and less than
Definition InstrTypes.h:746
@ FCMP_OGT
0 0 1 0 True if ordered and greater than
Definition InstrTypes.h:744
@ FCMP_OGE
0 0 1 1 True if ordered and greater than or equal
Definition InstrTypes.h:745
@ ICMP_UGE
unsigned greater or equal
Definition InstrTypes.h:764
@ ICMP_UGT
unsigned greater than
Definition InstrTypes.h:763
@ ICMP_SGT
signed greater than
Definition InstrTypes.h:767
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:765
@ FCMP_OLE
0 1 0 1 True if ordered and less than or equal
Definition InstrTypes.h:747
@ ICMP_SGE
signed greater or equal
Definition InstrTypes.h:768
@ ICMP_ULE
unsigned less or equal
Definition InstrTypes.h:766
@ FCMP_UNO
1 0 0 0 True if unordered: isnan(X) | isnan(Y)
Definition InstrTypes.h:750
Predicate getSwappedPredicate() const
For example, EQ->EQ, SLE->SGE, ULT->UGT, OEQ->OEQ, ULE->UGE, OLT->OGT, etc.
Definition InstrTypes.h:890
Predicate getInversePredicate() const
For example, EQ -> NE, UGT -> ULE, SLT -> SGE, OEQ -> UNE, UGT -> OLE, OLT -> UGE,...
Definition InstrTypes.h:852
static LLVM_ABI StringRef getPredicateName(Predicate P)
bool isStrictPredicate() const
Definition InstrTypes.h:906
An abstraction over a floating-point predicate, and a pack of an integer predicate with samesign info...
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
A debug info location.
Definition DebugLoc.h:126
static DebugLoc getUnknown()
Definition DebugLoc.h:153
bool contains(const_arg_type_t< KeyT > Val) const
Return true if the specified key is in the map, false otherwise.
Definition DenseMap.h:757
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
Definition DenseMap.h:793
bool dominates(const DomTreeNodeBase< NodeT > *A, const DomTreeNodeBase< NodeT > *B) const
dominates - Returns true iff A dominates B.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
static constexpr ElementCount getFixed(ScalarTy MinVal)
Definition TypeSize.h:306
constexpr bool isScalar() const
Exactly one element.
Definition TypeSize.h:317
Convenience struct for specifying and reasoning about fast-math flags.
Definition FMF.h:23
static FastMathFlags getFast()
Definition FMF.h:50
A struct for saving information about induction variables.
InductionKind getKind() const
const SCEV * getStep() const
@ IK_FpInduction
Floating point induction variable.
@ IK_PtrInduction
Pointer induction var. Step = C.
@ IK_IntInduction
Integer induction variable. Step = C.
Value * getStartValue() const
LLVM_ABI unsigned getNumSuccessors() const LLVM_READONLY
Return the number of successors that this instruction has.
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
LLVM_ABI FastMathFlags getFastMathFlags() const LLVM_READONLY
Convenience function for getting all the fast-math flags, which must be an operator which supports th...
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
bool contains(const LoopT *L) const
Return true if the specified loop is contained within this loop.
BlockT * getLoopLatch() const
If there is a single latch block for this loop, return it.
bool isInnermost() const
Return true if the loop does not contain any (natural) loops.
BlockT * getHeader() const
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
LoopT * getParentLoop() const
Return the parent loop if it exists or nullptr for top level loops.
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
This class emits a version of the loop where run-time checks ensure that may-alias pointers can't ove...
LLVM_ABI std::pair< MDNode *, MDNode * > getNoAliasMetadataFor(const Instruction *OrigInst) const
Returns a pair containing the alias_scope and noalias metadata nodes for OrigInst,...
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
DebugLoc getStartLoc() const
Return the debug location of the start of this loop.
Definition LoopInfo.cpp:694
LLVM_ABI MDNode * createBranchWeights(uint32_t TrueWeight, uint32_t FalseWeight, bool IsExpected=false)
Return metadata containing two branch weights.
Definition MDBuilder.cpp:38
Metadata node.
Definition Metadata.h:1081
This class implements a map that also provides access to all stored values in a deterministic order.
Definition MapVector.h:38
ValueT lookup(const KeyT &Key) const
Definition MapVector.h:110
iterator find(const KeyT &Key)
Definition MapVector.h:156
iterator end()
Definition MapVector.h:69
The optimization diagnostic interface.
LLVM_ABI void emit(DiagnosticInfoOptimizationBase &OptDiag)
Output the remark via the diagnostic handler and to the optimization record file.
Diagnostic information for missed-optimization remarks.
Post-order traversal of a graph.
An interface layer with SCEV used to manage how we see SCEV expressions for values in the context of ...
LLVM_ABI void addPredicate(const SCEVPredicate &Pred)
Adds a new predicate.
ScalarEvolution * getSE() const
Returns the ScalarEvolution analysis used.
LLVM_ABI const SCEVPredicate & getPredicate() const
LLVM_ABI const SCEV * getSymbolicMaxBackedgeTakenCount()
Get the (predicated) symbolic max backedge count for the analyzed loop.
LLVM_ABI const SCEV * getSCEV(Value *V)
Returns the SCEV expression of V, in the context of the current SCEV predicate.
The RecurrenceDescriptor is used to identify recurrences variables in a loop.
static bool isFMulAddIntrinsic(Instruction *I)
Returns true if the instruction is a call to the llvm.fmuladd intrinsic.
FastMathFlags getFastMathFlags() const
static bool isFPMinMaxNumRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is a floating-point minnum/maxnum kind.
bool hasUsesOutsideReductionChain() const
Returns true if the reduction PHI has any uses outside the reduction chain.
static bool isFindLastRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is of the form select(cmp(),x,y) where one of (x,...
TrackingVH< Value > getRecurrenceStartValue() const
static bool isAnyOfRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is of the form select(cmp(),x,y) where one of (x,...
RecurKind getRecurrenceKind() const
bool isOrdered() const
Expose an ordered FP reduction to the instance users.
static LLVM_ABI bool isFloatingPointRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is a floating point kind.
static bool isFindIVRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is of the form select(cmp(),x,y) where one of (x,...
static LLVM_ABI bool isIntegerRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is an integer kind.
static bool isMinMaxRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is any min/max kind.
Holds information about the memory runtime legality checks to verify that a group of pointers do not ...
std::optional< ArrayRef< PointerDiffInfo > > getDiffChecks() const
const SmallVectorImpl< RuntimePointerCheck > & getChecks() const
Returns the checks that generateChecks created.
virtual unsigned getComplexity() const
Returns the estimated complexity of this predicate.
This class represents an analyzed expression in the program.
static constexpr auto FlagNUW
Type * getType() const
Return the LLVM type of this SCEV expression.
The main scalar evolution driver.
LLVM_ABI const SCEV * getElementCount(Type *Ty, ElementCount EC, SCEVFlags Flags=SCEV::FlagNone)
LLVM_ABI const SCEV * getMinusSCEV(SCEVUse LHS, SCEVUse RHS, SCEVFlags Flags=SCEV::FlagNone, unsigned Depth=0)
Return LHS-RHS.
LLVM_ABI const SCEV * getTripCountFromExitCount(const SCEV *ExitCount)
A version of getTripCountFromExitCount below which always picks an evaluation type which can not resu...
const SCEV * getOne(Type *Ty)
Return a SCEV for the constant 1 of a specific type.
LLVM_ABI bool isLoopInvariant(const SCEV *S, const Loop *L)
Return true if the value of the given SCEV is unchanging in the specified loop.
LLVM_ABI bool isSCEVable(Type *Ty) const
Test if values of the given type are analyzable within the SCEV framework.
LLVM_ABI const SCEV * getUMaxExpr(SCEVUse LHS, SCEVUse RHS)
LLVM_ABI const SCEV * getStoreSizeOfExpr(Type *IntTy, Type *StoreTy)
Return an expression for the store size of StoreTy that is type IntTy.
LLVM_ABI bool isKnownPredicate(CmpPredicate Pred, SCEVUse LHS, SCEVUse RHS)
Test if the given expression is known to satisfy the condition described by Pred, LHS,...
LLVM_ABI const SCEV * applyLoopGuards(const SCEV *Expr, const Loop *L)
Try to apply information from loop guards for L to Expr.
A vector that has set insertion semantics.
Definition SetVector.h:57
size_type size() const
Determine the number of elements in the SetVector.
Definition SetVector.h:103
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:157
Implements a dense probed hash-table based set with some number of buckets stored inline.
Definition DenseSet.h:293
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
reference emplace_back(ArgTypes &&... Args)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:363
static LLVM_ABI IntegerType * getInt1Ty(LLVMContext &C)
Definition Type.cpp:296
op_range operands()
Definition User.h:267
VPBasicBlock serves as the leaf of the Hierarchical Control-Flow Graph.
Definition VPlan.h:4491
void appendRecipe(VPRecipeBase *Recipe)
Augment the existing recipes of a VPBasicBlock with an additional Recipe as the last recipe.
Definition VPlan.h:4572
RecipeListTy::iterator iterator
Instruction iterators...
Definition VPlan.h:4522
iterator end()
Definition VPlan.h:4532
iterator begin()
Recipe iterator methods.
Definition VPlan.h:4530
iterator_range< iterator > phis()
Returns an iterator range over the PHI-like recipes in the block.
Definition VPlan.h:4585
iterator getFirstNonPhi()
Return the position of the first non-phi node recipe in the block.
Definition VPlan.cpp:228
VPBasicBlock * splitAt(iterator SplitAt)
Split current block at SplitAt by inserting a new block between the current block and its successors ...
Definition VPlan.cpp:528
VPRecipeBase * getTerminator()
If the block has multiple successors, return the branch recipe terminating the block.
Definition VPlan.cpp:607
VPBlockBase is the building block of the Hierarchical Control-Flow Graph.
Definition VPlan.h:99
void setSuccessors(ArrayRef< VPBlockBase * > NewSuccs)
Set each VPBasicBlock in NewSuccss as successor of this VPBlockBase.
Definition VPlan.h:309
VPRegionBlock * getParent()
Definition VPlan.h:197
const VPBasicBlock * getExitingBasicBlock() const
Definition VPlan.cpp:198
void setName(const Twine &newName)
Definition VPlan.h:190
size_t getNumSuccessors() const
Definition VPlan.h:247
void swapSuccessors()
Swap successors of the block. The block must have exactly 2 successors.
Definition VPlan.h:331
size_t getNumPredecessors() const
Definition VPlan.h:248
void setPredecessors(ArrayRef< VPBlockBase * > NewPreds)
Set each VPBasicBlock in NewPreds as predecessor of this VPBlockBase.
Definition VPlan.h:300
bool hasSuccessors() const
Returns true if this block has any successors.
Definition VPlan.h:225
const VPBlocksTy & getPredecessors() const
Definition VPlan.h:232
void setTwoSuccessors(VPBlockBase *IfTrue, VPBlockBase *IfFalse)
Set two given VPBlockBases IfTrue and IfFalse to be the two successors of this VPBlockBase.
Definition VPlan.h:291
VPBlockBase * getSinglePredecessor() const
Definition VPlan.h:243
void swapPredecessors()
Swap predecessors of the block.
Definition VPlan.h:323
const VPBasicBlock * getEntryBasicBlock() const
Definition VPlan.cpp:183
void setOneSuccessor(VPBlockBase *Successor)
Set a given VPBlockBase Successor as the single successor of this VPBlockBase.
Definition VPlan.h:280
void setParent(VPRegionBlock *P)
Definition VPlan.h:207
VPBlockBase * getSingleSuccessor() const
Definition VPlan.h:237
const VPBlocksTy & getSuccessors() const
Definition VPlan.h:221
static auto blocksAs(T &&Range)
Return an iterator range over Range with each block cast to BlockTy.
Definition VPlanUtils.h:448
static void insertBlockAfter(VPBlockBase *NewBlock, VPBlockBase *BlockPtr)
Insert disconnected VPBlockBase NewBlock after BlockPtr.
Definition VPlanUtils.h:330
static void insertOnEdge(VPBlockBase *From, VPBlockBase *To, VPBlockBase *BlockPtr)
Inserts BlockPtr on the edge between From and To.
Definition VPlanUtils.h:467
static VPBasicBlock * getPlainCFGMiddleBlock(const VPlan &Plan)
Returns the middle block of Plan in plain CFG form (before regions are formed).
static bool isHeader(const VPBlockBase *VPB, const VPDominatorTree &VPDT)
Returns true if VPB is a loop header, based on regions or VPDT in their absence.
static void connectBlocks(VPBlockBase *From, VPBlockBase *To, unsigned PredIdx=-1u, unsigned SuccIdx=-1u)
Connect VPBlockBases From and To bi-directionally.
Definition VPlanUtils.h:375
static void disconnectBlocks(VPBlockBase *From, VPBlockBase *To)
Disconnect VPBlockBases From and To bi-directionally.
Definition VPlanUtils.h:393
static void reassociateBlocks(VPBlockBase *Old, VPBlockBase *New)
Reassociate all the blocks connected to Old so that they now point to New.
Definition VPlanUtils.h:411
static std::pair< VPBasicBlock *, VPBasicBlock * > getPlainCFGHeaderAndLatch(const VPlan &Plan)
Returns the header and latch of the outermost loop of Plan in plain CFG form (before regions are form...
static void transferSuccessors(VPBlockBase *Old, VPBlockBase *New)
Transfer successors from Old to New. New must have no successors.
Definition VPlanUtils.h:425
VPInstruction * createFreeze(VPValue *Op, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="")
static VPBuilderBase getToInsertAfter(VPRecipeBase *R)
VPPhi * createScalarPhi(ArrayRef< VPValue * > IncomingValues, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="", std::optional< VPIRFlags > Flags=std::nullopt, Type *ResultTy=nullptr)
Create a phi with IncomingValues, using the default flags for the result type, unless Flags is set.
VPInstruction * createAnd(VPValue *LHS, VPValue *RHS, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="")
VPRecipeBase * getRecipeAtInsertPoint() const
Get the recipe at the current insert point or nullptr if the insert point is the end of the block.
VPInstruction * createSelect(VPValue *Cond, VPValue *TrueVal, VPValue *FalseVal, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="", std::optional< VPIRFlags > Flags=std::nullopt)
Create a select of TrueVal and FalseVal based on Cond, using the default flags for the result type,...
VPInstruction * createNot(VPValue *Operand, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="")
void setInsertPoint(const VPInsertPoint &IP)
Set the current insert point.
VPInstruction * createNaryOp(unsigned Opcode, ArrayRef< VPValue * > Operands, Instruction *Inst=nullptr, const VPIRFlags &Flags={}, const VPIRMetadata &MD={}, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="", Type *ResultTy=nullptr, const VPIRAttributes &Attrs={})
Create an N-ary operation with Opcode, Operands and set Inst as its underlying Instruction.
VPInstruction * createFCmp(CmpInst::Predicate Pred, VPValue *A, VPValue *B, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="")
Create a new FCmp VPInstruction with predicate Pred and operands A and B.
VPInstruction * createOr(VPValue *LHS, VPValue *RHS, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="")
VPInstruction * createICmp(CmpInst::Predicate Pred, VPValue *A, VPValue *B, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="")
Create a new ICmp VPInstruction with predicate Pred and operands A and B.
unsigned getNumDefinedValues() const
Returns the number of values defined by the VPDef.
Definition VPlanValue.h:577
VPValue * getVPSingleValue()
Returns the only VPValue defined by the VPDef.
Definition VPlanValue.h:550
A recipe for converting Current into Start + Current * Step.
Definition VPlan.h:4262
Template specialization of the standard LLVM dominator tree utility for VPBlockBases.
LLVM_ABI_FOR_TEST bool properlyDominates(const VPRecipeBase *A, const VPRecipeBase *B) const
A pure virtual base class for all recipes modeling header phis, including phis for first order recurr...
Definition VPlan.h:2501
virtual VPValue * getBackedgeValue()
Returns the incoming value from the loop backedge.
Definition VPlan.h:2544
VPValue * getStartValue()
Returns the start value of the phi, if one is set.
Definition VPlan.h:2533
A special type of VPBasicBlock that wraps an existing IR basic block.
Definition VPlan.h:4650
Class to record and manage LLVM IR flags.
Definition VPlan.h:685
RecurKind getRecurKind() const
Definition VPlan.h:1029
Helper to manage IR metadata for recipes.
Definition VPlan.h:1154
This is a concrete Recipe that models a single VPlan-level instruction.
Definition VPlan.h:1324
@ ExtractLastActive
Extracts the last active lane from a set of vectors.
Definition VPlan.h:1439
@ ExtractLane
Extracts a single lane (first operand) from a set of vector operands.
Definition VPlan.h:1429
@ ExitingIVValue
Compute the exiting value of a wide induction after vectorization, that is the value of the last lane...
Definition VPlan.h:1443
@ ComputeReductionResult
Reduce the operands to the final reduction result using the operation specified via the operation's V...
Definition VPlan.h:1383
void addIncoming(VPValue *IncomingV)
Append IncomingV as an incoming value to the phi-like recipe.
Definition VPlan.h:1694
VPRecipeBase is a base class modeling a sequence of one or more output IR instructions.
Definition VPlan.h:406
void moveBefore(RecipeListTy::iterator I)
Unlink this recipe and insert it before I.
RecipeListTy::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
bool isPhi() const
Returns true for PHI-like recipes.
DebugLoc getDebugLoc() const
Returns the debug location of the recipe.
Definition VPlan.h:550
void insertBefore(VPRecipeBase *InsertPos)
Insert an unlinked recipe into a basic block immediately before the specified recipe.
void moveAfter(VPRecipeBase *MovePos)
Unlink this recipe from its current VPBasicBlock and insert it into the VPBasicBlock that MovePos liv...
Type * getScalarType() const
Returns the scalar type of this VPRecipeValue.
Definition VPlanValue.h:349
A recipe for handling reduction phis.
Definition VPlan.h:2904
bool isOrdered() const
Returns true, if the phi is part of an ordered reduction.
Definition VPlan.h:2976
unsigned getVFScaleFactor() const
Get the factor that the VF of this recipe's output should be scaled by, or 1 if it isn't scaled.
Definition VPlan.h:2960
bool isInLoop() const
Returns true if the phi is part of an in-loop reduction.
Definition VPlan.h:2979
RecurKind getRecurrenceKind() const
Returns the recurrence kind of the reduction.
Definition VPlan.h:2973
A recipe to represent inloop, ordered or partial reduction operations.
Definition VPlan.h:3287
VPRegionBlock represents a collection of VPBasicBlocks and VPRegionBlocks which form a Single-Entry-S...
Definition VPlan.h:4722
VPRegionValue * createHeaderMask()
Create the header mask for the region and return it.
Definition VPlan.h:4869
Type * getCanonicalIVType() const
Return the type of the canonical IV for loop regions.
Definition VPlan.h:4850
VPRegionValue * getCanonicalIV()
Return the canonical induction variable of the region, null for replicating regions.
Definition VPlan.h:4842
VPRegionValue * getHeaderMask() const
Return the header mask of the region, or null if not set.
Definition VPlan.h:4855
DebugLoc getDebugLoc() const
Returns the debug location of the VPRegionValue.
Definition VPlanValue.h:262
Lightweight SCEV-to-VPlan expander.
Definition VPlanUtils.h:276
VPValue * expand(const SCEV *S)
Expand S into recipes and live-ins using the builder.
VPSingleDefRecipe is a base class for recipes that model a sequence of one or more output IR that def...
Definition VPlan.h:608
Type * getType() const
Returns the scalar type of this symbolic value.
Definition VPlanValue.h:227
This class augments VPValue with operands which provide the inverse def-use edges from VPValue's user...
Definition VPlanValue.h:396
void replaceUsesOfWith(VPValue *From, VPValue *To)
Replaces all uses of From in the VPUser with To.
Definition VPlan.cpp:1508
operand_range operands()
Definition VPlanValue.h:472
void setOperand(unsigned I, VPValue *New)
Definition VPlanValue.h:445
VPValue * getOperand(unsigned N) const
Definition VPlanValue.h:437
This is the base class of the VPlan Def/Use graph, used for modeling the data flow into,...
Definition VPlanValue.h:50
Type * getScalarType() const
Returns the scalar type of this VPValue, dispatching based on the concrete subclass.
Definition VPlan.cpp:142
VPRecipeBase * getDefiningRecipe()
Returns the recipe defining this VPValue or nullptr if it is not defined by a recipe,...
Definition VPlan.cpp:123
void replaceUsesWithIf(VPValue *New, llvm::function_ref< bool(VPUser *U)> ShouldReplace)
Go through the uses list for this VPValue and make each use point to New if the callback ShouldReplac...
Definition VPlan.cpp:1481
void setUnderlyingValue(Value *Val)
Definition VPlanValue.h:204
void replaceAllUsesWith(VPValue *New)
Definition VPlan.cpp:1475
unsigned getNumUsers() const
Definition VPlanValue.h:115
user_range users()
Definition VPlanValue.h:157
Base class for widened induction (VPWidenIntOrFpInductionRecipe and VPWidenPointerInductionRecipe),...
Definition VPlan.h:2569
VPValue * getStepValue()
Returns the step value of the induction.
Definition VPlan.h:2611
const InductionDescriptor & getInductionDescriptor() const
Returns the induction descriptor for the recipe.
Definition VPlan.h:2628
A recipe for handling phi nodes of integer and floating-point inductions, producing their vector valu...
Definition VPlan.h:2657
bool isCanonical() const
Returns true if the induction is canonical, i.e.
VPlan models a candidate for vectorization, encoding various decisions take to produce efficient outp...
Definition VPlan.h:4909
VPIRValue * getLiveIn(Value *V) const
Return the live-in VPIRValue for V, if there is one or nullptr otherwise.
Definition VPlan.h:5239
LLVMContext & getContext() const
Definition VPlan.h:5106
VPBasicBlock * getEntry()
Definition VPlan.h:5001
VPValue * getTripCount() const
The trip count of the original loop.
Definition VPlan.h:5073
VPIRValue * getFalse()
Return a VPIRValue wrapping i1 false.
Definition VPlan.h:5205
VPSymbolicValue & getVFxUF()
Returns VF * UF of the vector loop region.
Definition VPlan.h:5104
VPIRBasicBlock * createEmptyVPIRBasicBlock(BasicBlock *IRBB)
Create a VPIRBasicBlock wrapping IRBB, but do not create VPIRInstructions wrapping the instructions i...
Definition VPlan.cpp:1311
VPIRValue * getPoison(Type *Ty)
Return a VPIRValue wrapping a poison value of type Ty.
Definition VPlan.h:5233
ArrayRef< VPIRBasicBlock * > getExitBlocks() const
Return an ArrayRef containing VPIRBasicBlocks wrapping the exit blocks of the original scalar loop.
Definition VPlan.h:5067
VPSymbolicValue & getVectorTripCount()
The vector trip count.
Definition VPlan.h:5094
VPIRValue * getOrAddLiveIn(Value *V)
Gets the live-in VPIRValue for V or adds a new live-in (if none exists yet) for V.
Definition VPlan.h:5182
VPRegionBlock * createLoopRegion(Type *CanIVTy, DebugLoc DL, const std::string &Name="", VPBlockBase *Entry=nullptr, VPBlockBase *Exiting=nullptr)
Create a new loop region with a canonical IV using CanIVTy and DL.
Definition VPlan.h:5278
VPIRValue * getZero(Type *Ty)
Return a VPIRValue wrapping the null value of type Ty.
Definition VPlan.h:5208
LLVM_ABI_FOR_TEST VPRegionBlock * getVectorLoopRegion()
Returns the VPRegionBlock of the vector loop.
Definition VPlan.cpp:1065
void setTripCount(VPValue *NewTripCount)
Set the trip count assuming it is currently null; if it is not - use resetTripCount().
Definition VPlan.h:5080
VPBasicBlock * getMiddleBlock()
Returns the 'middle' block of the plan, that is the block that selects whether to execute the scalar ...
Definition VPlan.h:5043
VPBasicBlock * createVPBasicBlock(const Twine &Name, VPRecipeBase *Recipe=nullptr)
Create a new VPBasicBlock with Name and containing Recipe if present.
Definition VPlan.h:5265
LLVM_ABI_FOR_TEST VPIRBasicBlock * createVPIRBasicBlock(BasicBlock *IRBB)
Create a VPIRBasicBlock from IRBB containing VPIRInstructions for all instructions in IRBB,...
Definition VPlan.cpp:1319
VPIRValue * getTrue()
Return a VPIRValue wrapping i1 true.
Definition VPlan.h:5202
VPBasicBlock * getVectorPreheader() const
Returns the preheader of the vector loop region, if one exists, or null otherwise.
Definition VPlan.h:5006
bool hasScalarVFOnly() const
Definition VPlan.h:5150
VPBasicBlock * getScalarPreheader() const
Return the VPBasicBlock for the preheader of the scalar loop.
Definition VPlan.h:5057
VPIRBasicBlock * getScalarHeader() const
Return the VPIRBasicBlock wrapping the header of the scalar loop.
Definition VPlan.h:5063
VPSymbolicValue & getVF()
Returns the VF of the vector loop region.
Definition VPlan.h:5097
bool hasScalarTail() const
Returns true if the scalar tail may execute after the vector loop, i.e.
Definition VPlan.h:5338
VPIRValue * getConstantInt(Type *Ty, uint64_t Val, bool IsSigned=false)
Return a VPIRValue wrapping a ConstantInt with the given type and value.
Definition VPlan.h:5216
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:315
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:209
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
Definition TypeSize.h:166
An efficient, type-erasing, non-owning reference to a callable.
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h:123
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Attrs[]
Key for Kernel::Metadata::mAttrs.
@ Entry
Definition COFF.h:862
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:83
void reportVectorizationFailure(const StringRef DebugMsg, const StringRef OREMsg, const StringRef ORETag, OptimizationRemarkEmitter *ORE, const Loop *TheLoop, Instruction *I=nullptr)
Reports a vectorization failure: print DebugMsg for debugging purposes along with the corresponding o...
auto m_Cmp()
Matches any compare instruction and ignore it.
BinaryOp_match< LHS, RHS, Instruction::Add > m_Add(const LHS &L, const RHS &R)
match_combine_or< CastInst_match< OpTy, TruncInst >, OpTy > m_TruncOrSelf(const OpTy &Op)
bool match(Val *V, const Pattern &P)
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
ThreeOps_match< Cond, LHS, RHS, Instruction::Select > m_Select(const Cond &C, const LHS &L, const RHS &R)
Matches SelectInst.
SpecificCmpClass_match< LHS, RHS, ICmpInst > m_SpecificICmp(CmpPredicate MatchPred, const LHS &L, const RHS &R)
SelectLike_match< CondTy, LTy, RTy > m_SelectLike(const CondTy &C, const LTy &TrueC, const RTy &FalseC)
Matches a value that behaves like a boolean-controlled select, i.e.
auto m_Intrinsic(const Ts &...Ops)
Match intrinsic calls like this: m_Intrinsic<Intrinsic::fabs>(m_Value(X))
BinaryOp_match< LHS, RHS, Instruction::Sub > m_Sub(const LHS &L, const RHS &R)
VPInstruction_match< VPInstruction::ExtractLastLane, VPInstruction_match< VPInstruction::ExtractLastPart, Op0_t > > m_ExtractLastLaneOfLastPart(const Op0_t &Op0)
RecipeTy * findSingleUser(VPValue *V, const MatchT &P)
Return the sole user of V matching pattern P, casting it to RecipeTy, or nullptr.
bool matchFindIVResult(VPInstruction *VPI, Op0_t ReducedIV, Op1_t Start)
Match FindIV result pattern: select(icmp ne ComputeReductionResult(ReducedIV), Sentinel),...
VPInstruction_match< VPInstruction::BranchOnTwoConds > m_BranchOnTwoConds()
VPInstruction_match< VPInstruction::ExtractLastLane, Op0_t > m_ExtractLastLane(const Op0_t &Op0)
VPInstruction_match< VPInstruction::BranchOnCount > m_BranchOnCount()
auto m_VPValue()
Match an arbitrary VPValue and ignore it.
VPInstruction_match< VPInstruction::ExtractLastPart, Op0_t > m_ExtractLastPart(const Op0_t &Op0)
match_bind< VPInstruction > m_VPInstruction(VPInstruction *&V)
Match a VPInstruction, capturing if we match.
VPInstruction_match< VPInstruction::BranchOnCond > m_BranchOnCond()
NodeAddr< PhiNode * > Phi
Definition RDFGraph.h:390
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
bool cannotHoistOrSinkRecipe(const VPRecipeBase &R, bool Sinking=false)
Return true if we do not know how to (mechanically) hoist or sink R.
VPInstruction * findComputeReductionResult(VPReductionPHIRecipe *PhiR)
Find the ComputeReductionResult recipe for PhiR, looking through selects inserted for predicated redu...
SmallVector< std::pair< VPBasicBlock *, VPIRBasicBlock * > > getEarlyExits(const VPlan &Plan, const VPBlockBase *MiddleVPBB)
Returns the (early exiting block, exit block) pairs of Plan, i.e.
DenseMap< const VPBasicBlock *, std::optional< VPExecutionFrequency > > computeExecutionFrequencies(ArrayRef< VPBasicBlock * > Blocks)
Computes for each block in Blocks, which must be in reverse post-order, the frequency with which it e...
VPIRFlags getFlagsForInduction(const InductionDescriptor &ID, const VPPhi *PhiR)
Extracts and returns NoWrap flags from PhiR and fast-math flags from ID.
VPRecipeBase * findRecipe(VPValue *Start, PredT Pred)
Search Start's users for a recipe satisfying Pred, looking through recipes with definitions.
Definition VPlanUtils.h:151
VPValue * getOrCreateVPValueForSCEVExpr(VPlan &Plan, const SCEV *Expr, bool ExpandInIR=false)
Get or create a VPValue that corresponds to the expansion of Expr.
LLVM_ABI_FOR_TEST const SCEV * getSCEVExprForVPValue(const VPValue *V, PredicatedScalarEvolution &PSE, const Loop *L=nullptr)
Return the SCEV expression for V.
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:316
SmallVector< VPBasicBlock * > vp_rpo_plain_cfg_loop_body(VPBasicBlock *Header)
Returns the VPBasicBlocks forming the loop body of a plain (pre-region) VPlan in reverse post-order s...
Definition VPlanCFG.h:262
@ Low
Lower the current thread's priority such that it does not affect foreground tasks significantly.
Definition Threading.h:280
constexpr auto not_equal_to(T &&Arg)
Functor variant of std::not_equal_to that can be used as a UnaryPredicate in functional algorithms li...
Definition STLExtras.h:2196
LLVM_ABI Intrinsic::ID getMinMaxReductionIntrinsicOp(Intrinsic::ID RdxID)
Returns the min/max intrinsic used when expanding a min/max reduction.
detail::zippy< detail::zip_first, T, U, Args... > zip_equal(T &&t, U &&u, Args &&...args)
zip iterator that assumes that all iteratees have the same length.
Definition STLExtras.h:856
ReductionStyle getReductionStyle(bool InLoop, bool Ordered, unsigned ScaleFactor)
Definition VPlan.h:2891
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
@ Load
The value being inserted comes from a load (InsertElement only).
VPBuilderBase<> VPBuilder
Definition VPlan.h:69
auto map_to_vector(ContainerTy &&C, FuncTy &&F)
Map a range to a SmallVector with element types deduced from the mapping.
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:649
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:250
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
auto make_isa_range(RangeT &&Range)
Return a range over Range containing only elements for which isa<T> holds, casting each of them to T.
Definition STLExtras.h:567
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
constexpr size_t range_size(R &&Range)
Returns the size of the Range, i.e., the number of elements.
Definition STLExtras.h:1710
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1652
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
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...
iterator_range< filter_iterator< detail::IterOfRange< RangeT >, PredicateT > > make_filter_range(RangeT &&Range, PredicateT Pred)
Convenience function that takes a range of elements and a predicate, and return a new filter_iterator...
Definition STLExtras.h:552
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
auto drop_end(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the last N elements excluded.
Definition STLExtras.h:323
RecurKind
These are the kinds of recurrences that we support.
@ UMin
Unsigned integer min implemented in terms of select(cmp()).
@ FMinimumNum
FP min with llvm.minimumnum semantics.
@ FindIV
FindIV reduction with select(icmp(),x,y) where one of (x,y) is a loop induction variable (increasing ...
@ FMinimum
FP min with llvm.minimum semantics.
@ FMaxNum
FP max with llvm.maxnum semantics including NaNs.
@ AnyOf
AnyOf reduction with select(cmp(),x,y) where one of (x,y) is loop invariant, and both x and y are int...
@ FMax
FP max implemented in terms of select(cmp()).
@ FMaximum
FP max with llvm.maximum semantics.
@ FMulAdd
Sum of float products with llvm.fmuladd(a * b + sum).
@ SMax
Signed integer max implemented in terms of select(cmp()).
@ SMin
Signed integer min implemented in terms of select(cmp()).
@ FMin
FP min implemented in terms of select(cmp()).
@ FMinNum
FP min with llvm.minnum semantics including NaNs.
@ Sub
Subtraction of integers.
@ AddChainWithSubs
A chain of adds and subs.
@ FMaximumNum
FP max with llvm.maximumnum semantics.
@ UMax
Unsigned integer max implemented in terms of select(cmp()).
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
DWARFExpression::Operation Op
ArrayRef(const T &OneElt) -> ArrayRef< T >
auto count_if(R &&Range, UnaryPredicate P)
Wrapper function around std::count_if to count the number of times an element satisfying a given pred...
Definition STLExtras.h:2035
LLVM_ABI RuntimeCheckBounds getRuntimeCheckBounds(const RuntimeCheckingPtrGroup *CG, const Loop *TheLoop, ScalarEvolution &SE, bool HoistRuntimeChecks)
Return the bounds of CG in TheLoop.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1788
constexpr auto seq(T Begin, T End)
Iterate over an integral type from Begin up to - but not including - End.
Definition Sequence.h:341
auto predecessors(const MachineBasicBlock *BB)
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
bool equal(L &&LRange, R &&RRange)
Wrapper function around std::equal to detect if pair-wise elements between two ranges are the same.
Definition STLExtras.h:2162
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:320
LLVM_ABI bool isDereferenceableAndAlignedInLoop(LoadInst *LI, Loop *L, ScalarEvolution &SE, DominatorTree &DT, AssumptionCache *AC=nullptr, SmallVectorImpl< const SCEVPredicate * > *Predicates=nullptr)
Return true if we can prove that the given load (which is assumed to be within the specified loop) wo...
Definition Loads.cpp:306
constexpr detail::IsaCheckPredicate< Types... > IsaPred
Function object wrapper for the llvm::isa type check.
Definition Casting.h:866
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:880
A MapVector that performs no allocations if smaller than a certain size.
Definition MapVector.h:342
A recipe for handling first-order recurrence phis.
Definition VPlan.h:2842
A VPValue representing a live-in from the input IR or a constant.
Definition VPlanValue.h:274
static void simplifyLiveInsWithSCEV(VPlan &Plan, PredicatedScalarEvolution &PSE)
Check Plan's live-ins and replace them with constants, if they can be simplified via SCEV.
static void addMinimumVectorEpilogueIterationCheck(VPlan &Plan, VPValue *MainVectorTripCount, bool RequiresScalarEpilogue, ElementCount EpilogueVF, unsigned MainLoopStep, unsigned EpilogueLoopStep, ScalarEvolution &SE)
Add a check to Plan to see if the epilogue vector loop should be executed.
static void foldTailByMasking(VPlan &Plan)
Adapts the vector loop region for tail folding by introducing a header mask and conditionally executi...
static bool handleMultiUseReductions(VPlan &Plan, OptimizationRemarkEmitter *ORE, Loop *TheLoop)
Try to legalize reductions with multiple in-loop uses.
static void recordExecutionFrequencies(VPlan &Plan)
Add execution frequencies to each recipe in the loop body of Plan.
static bool handleFindLastReductions(VPlan &Plan)
Check if Plan contains any FindLast reductions.
static void createInLoopReductionRecipes(VPlan &Plan, ElementCount MinVF)
Create VPReductionRecipes for in-loop reductions.
static LLVM_ABI_FOR_TEST void createLoopRegions(VPlan &Plan, DebugLoc DL)
Replace loops in Plan's flat CFG with VPRegionBlocks, turning Plan's flat CFG into a hierarchical CFG...
static VPIRBasicBlock * modelGeneratedMainLoopBlocks(VPlan &EpiPlan, VPlan &MainPlan, VPBasicBlock *MainCheck)
Model the blocks the executed MainPlan generated for the main vector loop in EpiPlan during epilogue ...
static LLVM_ABI_FOR_TEST void addMiddleCheck(VPlan &Plan)
If a check is needed to guard executing the scalar epilogue loop, it will be added to the middle bloc...
static void attachAliasMaskToHeaderMask(VPlan &Plan)
Attaches the alias-mask to the existing header-mask.
static bool areAllLoadsDereferenceable(VPBasicBlock *HeaderVPBB, Loop *TheLoop, PredicatedScalarEvolution &PSE, DominatorTree &DT, AssumptionCache *AC)
Check if all loads in the loop are dereferenceable.
static LLVM_ABI_FOR_TEST std::unique_ptr< VPlan > buildVPlan0(Loop *TheLoop, LoopInfo &LI, Type *InductionTy, PredicatedScalarEvolution &PSE, LoopVersioning *LVer=nullptr, function_ref< const BranchProbabilityInfo &()> GetBPI=nullptr)
Create a base VPlan0, serving as the common starting point for all later candidates.
static bool handleMaxMinNumReductions(VPlan &Plan)
Check if Plan contains any FMaxNum or FMinNum reductions.
static void attachCheckBlock(VPlan &Plan, Value *Cond, BasicBlock *CheckBlock, bool AddBranchWeights)
static LLVM_ABI_FOR_TEST void handleCountableEarlyExits(VPlan &Plan)
Disconnect countable early exits from the loop.
static bool finalizeSCEVPredicates(VPlan &Plan, PredicatedScalarEvolution &PSE, bool OptForSize, unsigned SCEVCheckThreshold, OptimizationRemarkEmitter *ORE, Loop *TheLoop)
Finalize SCEV predicates by adding induction predicates from Plan to PSE and checking constraints.
static void addIterationCountCheckBlock(VPlan &Plan, ElementCount VF, unsigned UF, bool RequiresScalarEpilogue, Loop *OrigLoop, const uint32_t *MinItersBypassWeights, DebugLoc DL, PredicatedScalarEvolution &PSE)
Add a new check block before the vector preheader to Plan to check if the main vector loop should be ...
static void attachMemoryChecks(VPlan &Plan, const RuntimePointerChecking &RtPtrChecking, const Loop *TheLoop, ScalarEvolution &SE, ElementCount VF, unsigned UF, bool AddBranchWeights)
Generate the memory runtime checks of RtPtrChecking for TheLoop as recipes and attach the check block...
static void addMinimumIterationCheck(VPlan &Plan, ElementCount VF, unsigned UF, ElementCount MinProfitableTripCount, bool RequiresScalarEpilogue, bool TailFolded, Loop *OrigLoop, const uint32_t *MinItersBypassWeights, DebugLoc DL, PredicatedScalarEvolution &PSE, VPBasicBlock *CheckBlock)
static void attachVPCheckBlock(VPlan &Plan, VPValue *Cond, VPBasicBlock *CheckBlock, bool AddBranchWeights)
Connect CheckBlock to Plan, branching on Cond.
static LLVM_ABI_FOR_TEST bool createHeaderPhiRecipes(VPlan &Plan, PredicatedScalarEvolution &PSE, Loop &OrigLoop, OptimizationRemarkEmitter *ORE, const VPDominatorTree &VPDT, const MapVector< PHINode *, InductionDescriptor > &Inductions, const MapVector< PHINode *, RecurrenceDescriptor > &Reductions, const SmallPtrSetImpl< const PHINode * > &FixedOrderRecurrences, const SmallPtrSetImpl< PHINode * > &InLoopReductions, bool AllowReordering)
Replace VPPhi recipes in Plan's header with corresponding VPHeaderPHIRecipe subclasses for inductions...
static LLVM_ABI bool HoistRuntimeChecks