LLVM 22.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 "VPlanPatternMatch.h"
20#include "VPlanTransforms.h"
25#include "llvm/IR/InstrTypes.h"
26#include "llvm/IR/MDBuilder.h"
29
30#define DEBUG_TYPE "vplan"
31
32using namespace llvm;
33using namespace VPlanPatternMatch;
34
35namespace {
36// Class that is used to build the plain CFG for the incoming IR.
37class PlainCFGBuilder {
38 // The outermost loop of the input loop nest considered for vectorization.
39 Loop *TheLoop;
40
41 // Loop Info analysis.
42 LoopInfo *LI;
43
44 // Loop versioning for alias metadata.
45 LoopVersioning *LVer;
46
47 // Vectorization plan that we are working on.
48 std::unique_ptr<VPlan> Plan;
49
50 // Builder of the VPlan instruction-level representation.
51 VPBuilder VPIRBuilder;
52
53 // NOTE: The following maps are intentionally destroyed after the plain CFG
54 // construction because subsequent VPlan-to-VPlan transformation may
55 // invalidate them.
56 // Map incoming BasicBlocks to their newly-created VPBasicBlocks.
58 // Map incoming Value definitions to their newly-created VPValues.
59 DenseMap<Value *, VPValue *> IRDef2VPValue;
60
61 // Hold phi node's that need to be fixed once the plain CFG has been built.
63
64 // Utility functions.
65 void setVPBBPredsFromBB(VPBasicBlock *VPBB, BasicBlock *BB);
66 void fixHeaderPhis();
67 VPBasicBlock *getOrCreateVPBB(BasicBlock *BB);
68#ifndef NDEBUG
69 bool isExternalDef(Value *Val);
70#endif
71 VPValue *getOrCreateVPOperand(Value *IRVal);
72 void createVPInstructionsForVPBB(VPBasicBlock *VPBB, BasicBlock *BB);
73
74public:
75 PlainCFGBuilder(Loop *Lp, LoopInfo *LI, LoopVersioning *LVer)
76 : TheLoop(Lp), LI(LI), LVer(LVer), Plan(std::make_unique<VPlan>(Lp)) {}
77
78 /// Build plain CFG for TheLoop and connect it to Plan's entry.
79 std::unique_ptr<VPlan> buildPlainCFG();
80};
81} // anonymous namespace
82
83// Set predecessors of \p VPBB in the same order as they are in \p BB. \p VPBB
84// must have no predecessors.
85void PlainCFGBuilder::setVPBBPredsFromBB(VPBasicBlock *VPBB, BasicBlock *BB) {
86 // Collect VPBB predecessors.
88 for (BasicBlock *Pred : predecessors(BB))
89 VPBBPreds.push_back(getOrCreateVPBB(Pred));
90 VPBB->setPredecessors(VPBBPreds);
91}
92
93static bool isHeaderBB(BasicBlock *BB, Loop *L) {
94 return L && BB == L->getHeader();
95}
96
97// Add operands to VPInstructions representing phi nodes from the input IR.
98void PlainCFGBuilder::fixHeaderPhis() {
99 for (auto *Phi : PhisToFix) {
100 assert(IRDef2VPValue.count(Phi) && "Missing VPInstruction for PHINode.");
101 VPValue *VPVal = IRDef2VPValue[Phi];
102 assert(isa<VPPhi>(VPVal) && "Expected VPPhi for phi node.");
103 auto *PhiR = cast<VPPhi>(VPVal);
104 assert(PhiR->getNumOperands() == 0 && "Expected VPPhi with no operands.");
105 assert(isHeaderBB(Phi->getParent(), LI->getLoopFor(Phi->getParent())) &&
106 "Expected Phi in header block.");
107 assert(Phi->getNumOperands() == 2 &&
108 "header phi must have exactly 2 operands");
109 for (BasicBlock *Pred : predecessors(Phi->getParent()))
110 PhiR->addOperand(
111 getOrCreateVPOperand(Phi->getIncomingValueForBlock(Pred)));
112 }
113}
114
115// Create a new empty VPBasicBlock for an incoming BasicBlock or retrieve an
116// existing one if it was already created.
117VPBasicBlock *PlainCFGBuilder::getOrCreateVPBB(BasicBlock *BB) {
118 if (auto *VPBB = BB2VPBB.lookup(BB)) {
119 // Retrieve existing VPBB.
120 return VPBB;
121 }
122
123 // Create new VPBB.
124 StringRef Name = BB->getName();
125 LLVM_DEBUG(dbgs() << "Creating VPBasicBlock for " << Name << "\n");
126 VPBasicBlock *VPBB = Plan->createVPBasicBlock(Name);
127 BB2VPBB[BB] = VPBB;
128 return VPBB;
129}
130
131#ifndef NDEBUG
132// Return true if \p Val is considered an external definition. An external
133// definition is either:
134// 1. A Value that is not an Instruction. This will be refined in the future.
135// 2. An Instruction that is outside of the IR region represented in VPlan,
136// i.e., is not part of the loop nest.
137bool PlainCFGBuilder::isExternalDef(Value *Val) {
138 // All the Values that are not Instructions are considered external
139 // definitions for now.
141 if (!Inst)
142 return true;
143
144 // Check whether Instruction definition is in loop body.
145 return !TheLoop->contains(Inst);
146}
147#endif
148
149// Create a new VPValue or retrieve an existing one for the Instruction's
150// operand \p IRVal. This function must only be used to create/retrieve VPValues
151// for *Instruction's operands* and not to create regular VPInstruction's. For
152// the latter, please, look at 'createVPInstructionsForVPBB'.
153VPValue *PlainCFGBuilder::getOrCreateVPOperand(Value *IRVal) {
154 auto VPValIt = IRDef2VPValue.find(IRVal);
155 if (VPValIt != IRDef2VPValue.end())
156 // Operand has an associated VPInstruction or VPValue that was previously
157 // created.
158 return VPValIt->second;
159
160 // Operand doesn't have a previously created VPInstruction/VPValue. This
161 // means that operand is:
162 // A) a definition external to VPlan,
163 // B) any other Value without specific representation in VPlan.
164 // For now, we use VPValue to represent A and B and classify both as external
165 // definitions. We may introduce specific VPValue subclasses for them in the
166 // future.
167 assert(isExternalDef(IRVal) && "Expected external definition as operand.");
168
169 // A and B: Create VPValue and add it to the pool of external definitions and
170 // to the Value->VPValue map.
171 VPValue *NewVPVal = Plan->getOrAddLiveIn(IRVal);
172 IRDef2VPValue[IRVal] = NewVPVal;
173 return NewVPVal;
174}
175
176// Create new VPInstructions in a VPBasicBlock, given its BasicBlock
177// counterpart. This function must be invoked in RPO so that the operands of a
178// VPInstruction in \p BB have been visited before (except for Phi nodes).
179void PlainCFGBuilder::createVPInstructionsForVPBB(VPBasicBlock *VPBB,
180 BasicBlock *BB) {
181 VPIRBuilder.setInsertPoint(VPBB);
182 // TODO: Model and preserve debug intrinsics in VPlan.
183 for (Instruction &InstRef : BB->instructionsWithoutDebug(false)) {
184 Instruction *Inst = &InstRef;
185
186 // There shouldn't be any VPValue for Inst at this point. Otherwise, we
187 // visited Inst when we shouldn't, breaking the RPO traversal order.
188 assert(!IRDef2VPValue.count(Inst) &&
189 "Instruction shouldn't have been visited.");
190
191 if (auto *Br = dyn_cast<BranchInst>(Inst)) {
192 // Conditional branch instruction are represented using BranchOnCond
193 // recipes.
194 if (Br->isConditional()) {
195 VPValue *Cond = getOrCreateVPOperand(Br->getCondition());
196 VPIRBuilder.createNaryOp(VPInstruction::BranchOnCond, {Cond}, Inst, {},
197 VPIRMetadata(*Inst), Inst->getDebugLoc());
198 }
199
200 // Skip the rest of the Instruction processing for Branch instructions.
201 continue;
202 }
203
204 if (auto *SI = dyn_cast<SwitchInst>(Inst)) {
205 // Don't emit recipes for unconditional switch instructions.
206 if (SI->getNumCases() == 0)
207 continue;
208 SmallVector<VPValue *> Ops = {getOrCreateVPOperand(SI->getCondition())};
209 for (auto Case : SI->cases())
210 Ops.push_back(getOrCreateVPOperand(Case.getCaseValue()));
211 VPIRBuilder.createNaryOp(Instruction::Switch, Ops, Inst, {},
212 VPIRMetadata(*Inst), Inst->getDebugLoc());
213 continue;
214 }
215
216 VPSingleDefRecipe *NewR;
217 if (auto *Phi = dyn_cast<PHINode>(Inst)) {
218 // Phi node's operands may not have been visited at this point. We create
219 // an empty VPInstruction that we will fix once the whole plain CFG has
220 // been built.
221 NewR = VPIRBuilder.createScalarPhi({}, Phi->getDebugLoc(), "vec.phi");
222 NewR->setUnderlyingValue(Phi);
223 if (isHeaderBB(Phi->getParent(), LI->getLoopFor(Phi->getParent()))) {
224 // Header phis need to be fixed after the VPBB for the latch has been
225 // created.
226 PhisToFix.push_back(Phi);
227 } else {
228 // Add operands for VPPhi in the order matching its predecessors in
229 // VPlan.
230 DenseMap<const VPBasicBlock *, VPValue *> VPPredToIncomingValue;
231 for (unsigned I = 0; I != Phi->getNumOperands(); ++I) {
232 VPPredToIncomingValue[BB2VPBB[Phi->getIncomingBlock(I)]] =
233 getOrCreateVPOperand(Phi->getIncomingValue(I));
234 }
235 for (VPBlockBase *Pred : VPBB->getPredecessors())
236 NewR->addOperand(
237 VPPredToIncomingValue.lookup(Pred->getExitingBasicBlock()));
238 }
239 } else {
240 // Build VPIRMetadata from the instruction and add loop versioning
241 // metadata for loads and stores.
242 VPIRMetadata MD(*Inst);
243 if (isa<LoadInst, StoreInst>(Inst) && LVer) {
244 const auto &[AliasScopeMD, NoAliasMD] =
245 LVer->getNoAliasMetadataFor(Inst);
246 if (AliasScopeMD)
247 MD.setMetadata(LLVMContext::MD_alias_scope, AliasScopeMD);
248 if (NoAliasMD)
249 MD.setMetadata(LLVMContext::MD_noalias, NoAliasMD);
250 }
251
252 // Translate LLVM-IR operands into VPValue operands and set them in the
253 // new VPInstruction.
254 SmallVector<VPValue *, 4> VPOperands;
255 for (Value *Op : Inst->operands())
256 VPOperands.push_back(getOrCreateVPOperand(Op));
257
258 if (auto *CI = dyn_cast<CastInst>(Inst)) {
259 NewR = VPIRBuilder.createScalarCast(CI->getOpcode(), VPOperands[0],
260 CI->getType(), CI->getDebugLoc(),
261 VPIRFlags(*CI), MD);
262 NewR->setUnderlyingValue(CI);
263 } else {
264 // Build VPInstruction for any arbitrary Instruction without specific
265 // representation in VPlan.
266 NewR =
267 VPIRBuilder.createNaryOp(Inst->getOpcode(), VPOperands, Inst,
268 VPIRFlags(*Inst), MD, Inst->getDebugLoc());
269 }
270 }
271
272 IRDef2VPValue[Inst] = NewR;
273 }
274}
275
276// Main interface to build the plain CFG.
277std::unique_ptr<VPlan> PlainCFGBuilder::buildPlainCFG() {
278 VPIRBasicBlock *Entry = cast<VPIRBasicBlock>(Plan->getEntry());
279 BB2VPBB[Entry->getIRBasicBlock()] = Entry;
280 for (VPIRBasicBlock *ExitVPBB : Plan->getExitBlocks())
281 BB2VPBB[ExitVPBB->getIRBasicBlock()] = ExitVPBB;
282
283 // 1. Scan the body of the loop in a topological order to visit each basic
284 // block after having visited its predecessor basic blocks. Create a VPBB for
285 // each BB and link it to its successor and predecessor VPBBs. Note that
286 // predecessors must be set in the same order as they are in the incomming IR.
287 // Otherwise, there might be problems with existing phi nodes and algorithm
288 // based on predecessors traversal.
289
290 // Loop PH needs to be explicitly visited since it's not taken into account by
291 // LoopBlocksDFS.
292 BasicBlock *ThePreheaderBB = TheLoop->getLoopPreheader();
293 assert((ThePreheaderBB->getTerminator()->getNumSuccessors() == 1) &&
294 "Unexpected loop preheader");
295 for (auto &I : *ThePreheaderBB) {
296 if (I.getType()->isVoidTy())
297 continue;
298 IRDef2VPValue[&I] = Plan->getOrAddLiveIn(&I);
299 }
300
301 LoopBlocksRPO RPO(TheLoop);
302 RPO.perform(LI);
303
304 for (BasicBlock *BB : RPO) {
305 // Create or retrieve the VPBasicBlock for this BB.
306 VPBasicBlock *VPBB = getOrCreateVPBB(BB);
307 // Set VPBB predecessors in the same order as they are in the incoming BB.
308 setVPBBPredsFromBB(VPBB, BB);
309
310 // Create VPInstructions for BB.
311 createVPInstructionsForVPBB(VPBB, BB);
312
313 // Set VPBB successors. We create empty VPBBs for successors if they don't
314 // exist already. Recipes will be created when the successor is visited
315 // during the RPO traversal.
316 if (auto *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
318 getOrCreateVPBB(SI->getDefaultDest())};
319 for (auto Case : SI->cases())
320 Succs.push_back(getOrCreateVPBB(Case.getCaseSuccessor()));
321 VPBB->setSuccessors(Succs);
322 continue;
323 }
324 auto *BI = cast<BranchInst>(BB->getTerminator());
325 unsigned NumSuccs = succ_size(BB);
326 if (NumSuccs == 1) {
327 VPBB->setOneSuccessor(getOrCreateVPBB(BB->getSingleSuccessor()));
328 continue;
329 }
330 assert(BI->isConditional() && NumSuccs == 2 && BI->isConditional() &&
331 "block must have conditional branch with 2 successors");
332
333 BasicBlock *IRSucc0 = BI->getSuccessor(0);
334 BasicBlock *IRSucc1 = BI->getSuccessor(1);
335 VPBasicBlock *Successor0 = getOrCreateVPBB(IRSucc0);
336 VPBasicBlock *Successor1 = getOrCreateVPBB(IRSucc1);
337 VPBB->setTwoSuccessors(Successor0, Successor1);
338 }
339
340 for (auto *EB : Plan->getExitBlocks())
341 setVPBBPredsFromBB(EB, EB->getIRBasicBlock());
342
343 // 2. The whole CFG has been built at this point so all the input Values must
344 // have a VPlan counterpart. Fix VPlan header phi by adding their
345 // corresponding VPlan operands.
346 fixHeaderPhis();
347
348 Plan->getEntry()->setOneSuccessor(getOrCreateVPBB(TheLoop->getHeader()));
349 Plan->getEntry()->setPlan(&*Plan);
350
351 // Fix VPlan loop-closed-ssa exit phi's by adding incoming operands to the
352 // VPIRInstructions wrapping them.
353 // // Note that the operand order corresponds to IR predecessor order, and may
354 // need adjusting when VPlan predecessors are added, if an exit block has
355 // multiple predecessor.
356 for (auto *EB : Plan->getExitBlocks()) {
357 for (VPRecipeBase &R : EB->phis()) {
358 auto *PhiR = cast<VPIRPhi>(&R);
359 PHINode &Phi = PhiR->getIRPhi();
360 assert(PhiR->getNumOperands() == 0 &&
361 "no phi operands should be added yet");
362 for (BasicBlock *Pred : predecessors(EB->getIRBasicBlock()))
363 PhiR->addOperand(
364 getOrCreateVPOperand(Phi.getIncomingValueForBlock(Pred)));
365 }
366 }
367
368 LLVM_DEBUG(Plan->setName("Plain CFG\n"); dbgs() << *Plan);
369 return std::move(Plan);
370}
371
372/// Checks if \p HeaderVPB is a loop header block in the plain CFG; that is, it
373/// has exactly 2 predecessors (preheader and latch), where the block
374/// dominates the latch and the preheader dominates the block. If it is a
375/// header block return true and canonicalize the predecessors of the header
376/// (making sure the preheader appears first and the latch second) and the
377/// successors of the latch (making sure the loop exit comes first). Otherwise
378/// return false.
380 const VPDominatorTree &VPDT) {
381 ArrayRef<VPBlockBase *> Preds = HeaderVPB->getPredecessors();
382 if (Preds.size() != 2)
383 return false;
384
385 auto *PreheaderVPBB = Preds[0];
386 auto *LatchVPBB = Preds[1];
387 if (!VPDT.dominates(PreheaderVPBB, HeaderVPB) ||
388 !VPDT.dominates(HeaderVPB, LatchVPBB)) {
389 std::swap(PreheaderVPBB, LatchVPBB);
390
391 if (!VPDT.dominates(PreheaderVPBB, HeaderVPB) ||
392 !VPDT.dominates(HeaderVPB, LatchVPBB))
393 return false;
394
395 // Canonicalize predecessors of header so that preheader is first and
396 // latch second.
397 HeaderVPB->swapPredecessors();
398 for (VPRecipeBase &R : cast<VPBasicBlock>(HeaderVPB)->phis())
399 R.swapOperands();
400 }
401
402 // The two successors of conditional branch match the condition, with the
403 // first successor corresponding to true and the second to false. We
404 // canonicalize the successors of the latch when introducing the region, such
405 // that the latch exits the region when its condition is true; invert the
406 // original condition if the original CFG branches to the header on true.
407 // Note that the exit edge is not yet connected for top-level loops.
408 if (LatchVPBB->getSingleSuccessor() ||
409 LatchVPBB->getSuccessors()[0] != HeaderVPB)
410 return true;
411
412 assert(LatchVPBB->getNumSuccessors() == 2 && "Must have 2 successors");
413 auto *Term = cast<VPBasicBlock>(LatchVPBB)->getTerminator();
416 "terminator must be a BranchOnCond");
417 auto *Not = new VPInstruction(VPInstruction::Not, {Term->getOperand(0)});
418 Not->insertBefore(Term);
419 Term->setOperand(0, Not);
420 LatchVPBB->swapSuccessors();
421
422 return true;
423}
424
425/// Create a new VPRegionBlock for the loop starting at \p HeaderVPB.
426static void createLoopRegion(VPlan &Plan, VPBlockBase *HeaderVPB) {
427 auto *PreheaderVPBB = HeaderVPB->getPredecessors()[0];
428 auto *LatchVPBB = HeaderVPB->getPredecessors()[1];
429
430 VPBlockUtils::disconnectBlocks(PreheaderVPBB, HeaderVPB);
431 VPBlockUtils::disconnectBlocks(LatchVPBB, HeaderVPB);
432 VPBlockBase *LatchExitVPB = LatchVPBB->getSingleSuccessor();
433 assert(LatchExitVPB && "Latch expected to be left with a single successor");
434
435 // Create an empty region first and insert it between PreheaderVPBB and
436 // LatchExitVPB, taking care to preserve the original predecessor & successor
437 // order of blocks. Set region entry and exiting after both HeaderVPB and
438 // LatchVPBB have been disconnected from their predecessors/successors.
439 auto *R = Plan.createLoopRegion();
440 VPBlockUtils::insertOnEdge(LatchVPBB, LatchExitVPB, R);
441 VPBlockUtils::disconnectBlocks(LatchVPBB, R);
442 VPBlockUtils::connectBlocks(PreheaderVPBB, R);
443 R->setEntry(HeaderVPB);
444 R->setExiting(LatchVPBB);
445
446 // All VPBB's reachable shallowly from HeaderVPB belong to the current region.
447 for (VPBlockBase *VPBB : vp_depth_first_shallow(HeaderVPB))
448 VPBB->setParent(R);
449}
450
451// Add the necessary canonical IV and branch recipes required to control the
452// loop.
453static void addCanonicalIVRecipes(VPlan &Plan, VPBasicBlock *HeaderVPBB,
454 VPBasicBlock *LatchVPBB, Type *IdxTy,
455 DebugLoc DL) {
456 Value *StartIdx = ConstantInt::get(IdxTy, 0);
457 auto *StartV = Plan.getOrAddLiveIn(StartIdx);
458
459 // Add a VPCanonicalIVPHIRecipe starting at 0 to the header.
460 auto *CanonicalIVPHI = new VPCanonicalIVPHIRecipe(StartV, DL);
461 HeaderVPBB->insert(CanonicalIVPHI, HeaderVPBB->begin());
462
463 // We are about to replace the branch to exit the region. Remove the original
464 // BranchOnCond, if there is any.
465 DebugLoc LatchDL = DL;
466 if (!LatchVPBB->empty() && match(&LatchVPBB->back(), m_BranchOnCond())) {
467 LatchDL = LatchVPBB->getTerminator()->getDebugLoc();
468 LatchVPBB->getTerminator()->eraseFromParent();
469 }
470
471 VPBuilder Builder(LatchVPBB);
472 // Add a VPInstruction to increment the scalar canonical IV by VF * UF.
473 // Initially the induction increment is guaranteed to not wrap, but that may
474 // change later, e.g. when tail-folding, when the flags need to be dropped.
475 auto *CanonicalIVIncrement = Builder.createOverflowingOp(
476 Instruction::Add, {CanonicalIVPHI, &Plan.getVFxUF()}, {true, false}, DL,
477 "index.next");
478 CanonicalIVPHI->addOperand(CanonicalIVIncrement);
479
480 // Add the BranchOnCount VPInstruction to the latch.
481 Builder.createNaryOp(VPInstruction::BranchOnCount,
482 {CanonicalIVIncrement, &Plan.getVectorTripCount()},
483 LatchDL);
484}
485
486/// Creates extracts for values in \p Plan defined in a loop region and used
487/// outside a loop region.
488static void createExtractsForLiveOuts(VPlan &Plan, VPBasicBlock *MiddleVPBB) {
489 VPBuilder B(MiddleVPBB, MiddleVPBB->getFirstNonPhi());
490 for (VPBasicBlock *EB : Plan.getExitBlocks()) {
491 if (EB->getSinglePredecessor() != MiddleVPBB)
492 continue;
493
494 for (VPRecipeBase &R : EB->phis()) {
495 auto *ExitIRI = cast<VPIRPhi>(&R);
496 for (unsigned Idx = 0; Idx != ExitIRI->getNumIncoming(); ++Idx) {
497 VPRecipeBase *Inc = ExitIRI->getIncomingValue(Idx)->getDefiningRecipe();
498 if (!Inc)
499 continue;
500 assert(ExitIRI->getNumOperands() == 1 &&
501 ExitIRI->getParent()->getSinglePredecessor() == MiddleVPBB &&
502 "exit values from early exits must be fixed when branch to "
503 "early-exit is added");
504 ExitIRI->extractLastLaneOfLastPartOfFirstOperand(B);
505 }
506 }
507 }
508}
509
510static void addInitialSkeleton(VPlan &Plan, Type *InductionTy, DebugLoc IVDL,
511 PredicatedScalarEvolution &PSE, Loop *TheLoop) {
512 VPDominatorTree VPDT(Plan);
513
514 auto *HeaderVPBB = cast<VPBasicBlock>(Plan.getEntry()->getSingleSuccessor());
515 canonicalHeaderAndLatch(HeaderVPBB, VPDT);
516 auto *LatchVPBB = cast<VPBasicBlock>(HeaderVPBB->getPredecessors()[1]);
517
518 VPBasicBlock *VecPreheader = Plan.createVPBasicBlock("vector.ph");
519 VPBlockUtils::insertBlockAfter(VecPreheader, Plan.getEntry());
520
521 VPBasicBlock *MiddleVPBB = Plan.createVPBasicBlock("middle.block");
522 // The canonical LatchVPBB has the header block as last successor. If it has
523 // another successor, this successor is an exit block - insert middle block on
524 // its edge. Otherwise, add middle block as another successor retaining header
525 // as last.
526 if (LatchVPBB->getNumSuccessors() == 2) {
527 VPBlockBase *LatchExitVPB = LatchVPBB->getSuccessors()[0];
528 VPBlockUtils::insertOnEdge(LatchVPBB, LatchExitVPB, MiddleVPBB);
529 } else {
530 VPBlockUtils::connectBlocks(LatchVPBB, MiddleVPBB);
531 LatchVPBB->swapSuccessors();
532 }
533
534 addCanonicalIVRecipes(Plan, HeaderVPBB, LatchVPBB, InductionTy, IVDL);
535
536 // Create SCEV and VPValue for the trip count.
537 // We use the symbolic max backedge-taken-count, which works also when
538 // vectorizing loops with uncountable early exits.
539 const SCEV *BackedgeTakenCountSCEV = PSE.getSymbolicMaxBackedgeTakenCount();
540 assert(!isa<SCEVCouldNotCompute>(BackedgeTakenCountSCEV) &&
541 "Invalid backedge-taken count");
542 ScalarEvolution &SE = *PSE.getSE();
543 const SCEV *TripCount = SE.getTripCountFromExitCount(BackedgeTakenCountSCEV,
544 InductionTy, TheLoop);
546
547 VPBasicBlock *ScalarPH = Plan.createVPBasicBlock("scalar.ph");
549
550 // The connection order corresponds to the operands of the conditional branch,
551 // with the middle block already connected to the exit block.
552 VPBlockUtils::connectBlocks(MiddleVPBB, ScalarPH);
553 // Also connect the entry block to the scalar preheader.
554 // TODO: Also introduce a branch recipe together with the minimum trip count
555 // check.
556 VPBlockUtils::connectBlocks(Plan.getEntry(), ScalarPH);
557 Plan.getEntry()->swapSuccessors();
558
559 createExtractsForLiveOuts(Plan, MiddleVPBB);
560
561 VPBuilder ScalarPHBuilder(ScalarPH);
562 for (const auto &[PhiR, ScalarPhiR] : zip_equal(
563 drop_begin(HeaderVPBB->phis()), Plan.getScalarHeader()->phis())) {
564 auto *VectorPhiR = cast<VPPhi>(&PhiR);
565 auto *ResumePhiR = ScalarPHBuilder.createScalarPhi(
566 {VectorPhiR, VectorPhiR->getOperand(0)}, VectorPhiR->getDebugLoc());
567 cast<VPIRPhi>(&ScalarPhiR)->addOperand(ResumePhiR);
568 }
569}
570
571/// Check \p Plan's live-in and replace them with constants, if they can be
572/// simplified via SCEV.
575 auto GetSimplifiedLiveInViaSCEV = [&](VPValue *VPV) -> VPValue * {
576 const SCEV *Expr = vputils::getSCEVExprForVPValue(VPV, PSE);
577 if (auto *C = dyn_cast<SCEVConstant>(Expr))
578 return Plan.getOrAddLiveIn(C->getValue());
579 return nullptr;
580 };
581
582 for (VPValue *LiveIn : Plan.getLiveIns()) {
583 if (VPValue *SimplifiedLiveIn = GetSimplifiedLiveInViaSCEV(LiveIn))
584 LiveIn->replaceAllUsesWith(SimplifiedLiveIn);
585 }
586}
587
588std::unique_ptr<VPlan>
589VPlanTransforms::buildVPlan0(Loop *TheLoop, LoopInfo &LI, Type *InductionTy,
591 LoopVersioning *LVer) {
592 PlainCFGBuilder Builder(TheLoop, &LI, LVer);
593 std::unique_ptr<VPlan> VPlan0 = Builder.buildPlainCFG();
594 addInitialSkeleton(*VPlan0, InductionTy, IVDL, PSE, TheLoop);
595 simplifyLiveInsWithSCEV(*VPlan0, PSE);
596 return VPlan0;
597}
598
599/// Creates a VPWidenIntOrFpInductionRecipe or VPWidenPointerInductionRecipe
600/// for \p Phi based on \p IndDesc.
601static VPHeaderPHIRecipe *
603 const InductionDescriptor &IndDesc, VPlan &Plan,
604 PredicatedScalarEvolution &PSE, Loop &OrigLoop,
605 DebugLoc DL) {
606 [[maybe_unused]] ScalarEvolution &SE = *PSE.getSE();
607 assert(SE.isLoopInvariant(IndDesc.getStep(), &OrigLoop) &&
608 "step must be loop invariant");
609 assert((Plan.getLiveIn(IndDesc.getStartValue()) == Start ||
610 (SE.isSCEVable(IndDesc.getStartValue()->getType()) &&
611 SE.getSCEV(IndDesc.getStartValue()) ==
612 vputils::getSCEVExprForVPValue(Start, PSE))) &&
613 "Start VPValue must match IndDesc's start value");
614
615 VPValue *Step =
617
619 return new VPWidenPointerInductionRecipe(Phi, Start, Step, &Plan.getVFxUF(),
620 IndDesc, DL);
621
624 "must have an integer or float induction at this point");
625
626 // Update wide induction increments to use the same step as the corresponding
627 // wide induction. This enables detecting induction increments directly in
628 // VPlan and removes redundant splats.
629 using namespace llvm::VPlanPatternMatch;
630 if (match(PhiR->getOperand(1), m_Add(m_Specific(PhiR), m_VPValue())))
631 PhiR->getOperand(1)->getDefiningRecipe()->setOperand(1, Step);
632
633 // It is always safe to copy over the NoWrap and FastMath flags. In
634 // particular, when folding tail by masking, the masked-off lanes are never
635 // used, so it is safe.
637
638 return new VPWidenIntOrFpInductionRecipe(Phi, Start, Step, &Plan.getVF(),
639 IndDesc, Flags, DL);
640}
641
643 VPlan &Plan, PredicatedScalarEvolution &PSE, Loop &OrigLoop,
646 const SmallPtrSetImpl<const PHINode *> &FixedOrderRecurrences,
647 const SmallPtrSetImpl<PHINode *> &InLoopReductions, bool AllowReordering) {
648 // Retrieve the header manually from the intial plain-CFG VPlan.
649 VPBasicBlock *HeaderVPBB = cast<VPBasicBlock>(
650 Plan.getEntry()->getSuccessors()[1]->getSingleSuccessor());
651 assert(VPDominatorTree(Plan).dominates(HeaderVPBB,
652 HeaderVPBB->getPredecessors()[1]) &&
653 "header must dominate its latch");
654
655 auto CreateHeaderPhiRecipe = [&](VPPhi *PhiR) -> VPHeaderPHIRecipe * {
656 // TODO: Gradually replace uses of underlying instruction by analyses on
657 // VPlan.
658 auto *Phi = cast<PHINode>(PhiR->getUnderlyingInstr());
659 assert(PhiR->getNumOperands() == 2 &&
660 "Must have 2 operands for header phis");
661
662 // Extract common values once.
663 VPValue *Start = PhiR->getOperand(0);
664 VPValue *BackedgeValue = PhiR->getOperand(1);
665
666 if (FixedOrderRecurrences.contains(Phi)) {
667 // TODO: Currently fixed-order recurrences are modeled as chains of
668 // first-order recurrences. If there are no users of the intermediate
669 // recurrences in the chain, the fixed order recurrence should be
670 // modeled directly, enabling more efficient codegen.
671 return new VPFirstOrderRecurrencePHIRecipe(Phi, *Start, *BackedgeValue);
672 }
673
674 auto InductionIt = Inductions.find(Phi);
675 if (InductionIt != Inductions.end())
676 return createWidenInductionRecipe(Phi, PhiR, Start, InductionIt->second,
677 Plan, PSE, OrigLoop,
678 PhiR->getDebugLoc());
679
680 assert(Reductions.contains(Phi) && "only reductions are expected now");
681 const RecurrenceDescriptor &RdxDesc = Reductions.lookup(Phi);
683 Phi->getIncomingValueForBlock(OrigLoop.getLoopPreheader()) &&
684 "incoming value must match start value");
685 // Will be updated later to >1 if reduction is partial.
686 unsigned ScaleFactor = 1;
687 bool UseOrderedReductions = !AllowReordering && RdxDesc.isOrdered();
688 return new VPReductionPHIRecipe(
689 Phi, RdxDesc.getRecurrenceKind(), *Start, *BackedgeValue,
690 getReductionStyle(InLoopReductions.contains(Phi), UseOrderedReductions,
691 ScaleFactor),
693 };
694
695 for (VPRecipeBase &R : make_early_inc_range(HeaderVPBB->phis())) {
697 continue;
698 auto *PhiR = cast<VPPhi>(&R);
699 VPHeaderPHIRecipe *HeaderPhiR = CreateHeaderPhiRecipe(PhiR);
700 HeaderPhiR->insertBefore(PhiR);
701 PhiR->replaceAllUsesWith(HeaderPhiR);
702 PhiR->eraseFromParent();
703 }
704}
705
707 VPlan &Plan, const DenseMap<VPBasicBlock *, VPValue *> &BlockMaskCache,
708 const DenseSet<BasicBlock *> &BlocksNeedingPredication,
709 ElementCount MinVF) {
710 VPTypeAnalysis TypeInfo(Plan);
713
714 for (VPRecipeBase &R : Header->phis()) {
715 auto *PhiR = dyn_cast<VPReductionPHIRecipe>(&R);
716 if (!PhiR || !PhiR->isInLoop() || (MinVF.isScalar() && !PhiR->isOrdered()))
717 continue;
718
719 RecurKind Kind = PhiR->getRecurrenceKind();
720 assert(
723 "AnyOf and FindIV reductions are not allowed for in-loop reductions");
724
725 bool IsFPRecurrence =
727 FastMathFlags FMFs =
728 IsFPRecurrence ? FastMathFlags::getFast() : FastMathFlags();
729
730 // Collect the chain of "link" recipes for the reduction starting at PhiR.
732 Worklist.insert(PhiR);
733 for (unsigned I = 0; I != Worklist.size(); ++I) {
734 VPSingleDefRecipe *Cur = Worklist[I];
735 for (VPUser *U : Cur->users()) {
736 auto *UserRecipe = cast<VPSingleDefRecipe>(U);
737 if (!UserRecipe->getParent()->getEnclosingLoopRegion()) {
738 assert((UserRecipe->getParent() == Plan.getMiddleBlock() ||
739 UserRecipe->getParent() == Plan.getScalarPreheader()) &&
740 "U must be either in the loop region, the middle block or the "
741 "scalar preheader.");
742 continue;
743 }
744
745 // Stores using instructions will be sunk later.
747 continue;
748 Worklist.insert(UserRecipe);
749 }
750 }
751
752 // Visit operation "Links" along the reduction chain top-down starting from
753 // the phi until LoopExitValue. We keep track of the previous item
754 // (PreviousLink) to tell which of the two operands of a Link will remain
755 // scalar and which will be reduced. For minmax by select(cmp), Link will be
756 // the select instructions. Blend recipes of in-loop reduction phi's will
757 // get folded to their non-phi operand, as the reduction recipe handles the
758 // condition directly.
759 VPSingleDefRecipe *PreviousLink = PhiR; // Aka Worklist[0].
760 for (VPSingleDefRecipe *CurrentLink : drop_begin(Worklist)) {
761 if (auto *Blend = dyn_cast<VPBlendRecipe>(CurrentLink)) {
762 assert(Blend->getNumIncomingValues() == 2 &&
763 "Blend must have 2 incoming values");
764 unsigned PhiRIdx = Blend->getIncomingValue(0) == PhiR ? 0 : 1;
765 assert(Blend->getIncomingValue(PhiRIdx) == PhiR &&
766 "PhiR must be an operand of the blend");
767 Blend->replaceAllUsesWith(Blend->getIncomingValue(1 - PhiRIdx));
768 continue;
769 }
770
771 if (IsFPRecurrence) {
772 FastMathFlags CurFMF =
773 cast<VPRecipeWithIRFlags>(CurrentLink)->getFastMathFlags();
774 if (match(CurrentLink, m_Select(m_VPValue(), m_VPValue(), m_VPValue())))
775 CurFMF |= cast<VPRecipeWithIRFlags>(CurrentLink->getOperand(0))
776 ->getFastMathFlags();
777 FMFs &= CurFMF;
778 }
779
780 Instruction *CurrentLinkI = CurrentLink->getUnderlyingInstr();
781
782 // Recognize a call to the llvm.fmuladd intrinsic.
783 bool IsFMulAdd = Kind == RecurKind::FMulAdd;
784 VPValue *VecOp;
785 VPBasicBlock *LinkVPBB = CurrentLink->getParent();
786 if (IsFMulAdd) {
788 "Expected current VPInstruction to be a call to the "
789 "llvm.fmuladd intrinsic");
790 assert(CurrentLink->getOperand(2) == PreviousLink &&
791 "expected a call where the previous link is the added operand");
792
793 // If the instruction is a call to the llvm.fmuladd intrinsic then we
794 // need to create an fmul recipe (multiplying the first two operands of
795 // the fmuladd together) to use as the vector operand for the fadd
796 // reduction.
797 auto *FMulRecipe = new VPInstruction(
798 Instruction::FMul,
799 {CurrentLink->getOperand(0), CurrentLink->getOperand(1)},
800 CurrentLinkI->getFastMathFlags());
801 LinkVPBB->insert(FMulRecipe, CurrentLink->getIterator());
802 VecOp = FMulRecipe;
803 } else if (Kind == RecurKind::AddChainWithSubs &&
804 match(CurrentLink, m_Sub(m_VPValue(), m_VPValue()))) {
805 Type *PhiTy = TypeInfo.inferScalarType(PhiR);
806 auto *Zero = Plan.getConstantInt(PhiTy, 0);
807 auto *Sub = new VPInstruction(Instruction::Sub,
808 {Zero, CurrentLink->getOperand(1)}, {},
809 {}, CurrentLinkI->getDebugLoc());
810 Sub->setUnderlyingValue(CurrentLinkI);
811 LinkVPBB->insert(Sub, CurrentLink->getIterator());
812 VecOp = Sub;
813 } else {
814 // Index of the first operand which holds a non-mask vector operand.
815 unsigned IndexOfFirstOperand = 0;
817 if (match(CurrentLink, m_Cmp(m_VPValue(), m_VPValue())))
818 continue;
819 assert(match(CurrentLink,
821 "must be a select recipe");
822 IndexOfFirstOperand = 1;
823 }
824 // Note that for non-commutable operands (cmp-selects), the semantics of
825 // the cmp-select are captured in the recurrence kind.
826 unsigned VecOpId =
827 CurrentLink->getOperand(IndexOfFirstOperand) == PreviousLink
828 ? IndexOfFirstOperand + 1
829 : IndexOfFirstOperand;
830 VecOp = CurrentLink->getOperand(VecOpId);
831 assert(VecOp != PreviousLink &&
832 CurrentLink->getOperand(CurrentLink->getNumOperands() - 1 -
833 (VecOpId - IndexOfFirstOperand)) ==
834 PreviousLink &&
835 "PreviousLink must be the operand other than VecOp");
836 }
837
838 // Get block mask from BlockMaskCache if the block needs predication.
839 VPValue *CondOp = nullptr;
840 if (BlocksNeedingPredication.contains(CurrentLinkI->getParent()))
841 CondOp = BlockMaskCache.lookup(LinkVPBB);
842
843 assert(PhiR->getVFScaleFactor() == 1 &&
844 "inloop reductions must be unscaled");
845 auto *RedRecipe = new VPReductionRecipe(
846 Kind, FMFs, CurrentLinkI, PreviousLink, VecOp, CondOp,
847 getReductionStyle(/*IsInLoop=*/true, PhiR->isOrdered(), 1),
848 CurrentLinkI->getDebugLoc());
849 // Append the recipe to the end of the VPBasicBlock because we need to
850 // ensure that it comes after all of it's inputs, including CondOp.
851 // Delete CurrentLink as it will be invalid if its operand is replaced
852 // with a reduction defined at the bottom of the block in the next link.
853 if (LinkVPBB->getNumSuccessors() == 0)
854 RedRecipe->insertBefore(&*std::prev(std::prev(LinkVPBB->end())));
855 else
856 LinkVPBB->appendRecipe(RedRecipe);
857
858 CurrentLink->replaceAllUsesWith(RedRecipe);
859 ToDelete.push_back(CurrentLink);
860 PreviousLink = RedRecipe;
861 }
862 }
863
864 for (VPRecipeBase *R : ToDelete)
865 R->eraseFromParent();
866}
867
869 bool HasUncountableEarlyExit) {
870 auto *MiddleVPBB = cast<VPBasicBlock>(
872 auto *LatchVPBB = cast<VPBasicBlock>(MiddleVPBB->getSinglePredecessor());
873 VPBlockBase *HeaderVPB = cast<VPBasicBlock>(LatchVPBB->getSuccessors()[1]);
874
875 // Disconnect all early exits from the loop leaving it with a single exit from
876 // the latch. Early exits that are countable are left for a scalar epilog. The
877 // condition of uncountable early exits (currently at most one is supported)
878 // is fused into the latch exit, and used to branch from middle block to the
879 // early exit destination.
880 [[maybe_unused]] bool HandledUncountableEarlyExit = false;
881 for (VPIRBasicBlock *EB : Plan.getExitBlocks()) {
882 for (VPBlockBase *Pred : to_vector(EB->getPredecessors())) {
883 if (Pred == MiddleVPBB)
884 continue;
885 if (HasUncountableEarlyExit) {
886 assert(!HandledUncountableEarlyExit &&
887 "can handle exactly one uncountable early exit");
889 cast<VPBasicBlock>(HeaderVPB), LatchVPBB);
890 HandledUncountableEarlyExit = true;
891 } else {
892 for (VPRecipeBase &R : EB->phis())
893 cast<VPIRPhi>(&R)->removeIncomingValueFor(Pred);
894 }
895 cast<VPBasicBlock>(Pred)->getTerminator()->eraseFromParent();
897 }
898 }
899
900 assert((!HasUncountableEarlyExit || HandledUncountableEarlyExit) &&
901 "missed an uncountable exit that must be handled");
902}
903
905 bool RequiresScalarEpilogueCheck,
906 bool TailFolded) {
907 auto *MiddleVPBB = cast<VPBasicBlock>(
909 // If MiddleVPBB has a single successor then the original loop does not exit
910 // via the latch and the single successor must be the scalar preheader.
911 // There's no need to add a runtime check to MiddleVPBB.
912 if (MiddleVPBB->getNumSuccessors() == 1) {
913 assert(MiddleVPBB->getSingleSuccessor() == Plan.getScalarPreheader() &&
914 "must have ScalarPH as single successor");
915 return;
916 }
917
918 assert(MiddleVPBB->getNumSuccessors() == 2 && "must have 2 successors");
919
920 // Add a check in the middle block to see if we have completed all of the
921 // iterations in the first vector loop.
922 //
923 // Three cases:
924 // 1) If we require a scalar epilogue, the scalar ph must execute. Set the
925 // condition to false.
926 // 2) If (N - N%VF) == N, then we *don't* need to run the
927 // remainder. Thus if tail is to be folded, we know we don't need to run
928 // the remainder and we can set the condition to true.
929 // 3) Otherwise, construct a runtime check.
930
931 // We use the same DebugLoc as the scalar loop latch terminator instead of
932 // the corresponding compare because they may have ended up with different
933 // line numbers and we want to avoid awkward line stepping while debugging.
934 // E.g., if the compare has got a line number inside the loop.
935 auto *LatchVPBB = cast<VPBasicBlock>(MiddleVPBB->getSinglePredecessor());
936 DebugLoc LatchDL = LatchVPBB->getTerminator()->getDebugLoc();
937 VPBuilder Builder(MiddleVPBB);
938 VPValue *Cmp;
939 if (!RequiresScalarEpilogueCheck)
940 Cmp = Plan.getFalse();
941 else if (TailFolded)
942 Cmp = Plan.getTrue();
943 else
944 Cmp = Builder.createICmp(CmpInst::ICMP_EQ, Plan.getTripCount(),
945 &Plan.getVectorTripCount(), LatchDL, "cmp.n");
946 Builder.createNaryOp(VPInstruction::BranchOnCond, {Cmp}, LatchDL);
947}
948
950 VPDominatorTree VPDT(Plan);
951 for (VPBlockBase *HeaderVPB : vp_post_order_shallow(Plan.getEntry()))
952 if (canonicalHeaderAndLatch(HeaderVPB, VPDT))
953 createLoopRegion(Plan, HeaderVPB);
954
955 VPRegionBlock *TopRegion = Plan.getVectorLoopRegion();
956 TopRegion->setName("vector loop");
957 TopRegion->getEntryBasicBlock()->setName("vector.body");
958}
959
960// Likelyhood of bypassing the vectorized loop due to a runtime check block,
961// including memory overlap checks block and wrapping/unit-stride checks block.
962static constexpr uint32_t CheckBypassWeights[] = {1, 127};
963
965 BasicBlock *CheckBlock,
966 bool AddBranchWeights) {
967 VPValue *CondVPV = Plan.getOrAddLiveIn(Cond);
968 VPBasicBlock *CheckBlockVPBB = Plan.createVPIRBasicBlock(CheckBlock);
969 VPBlockBase *VectorPH = Plan.getVectorPreheader();
970 VPBlockBase *ScalarPH = Plan.getScalarPreheader();
971 VPBlockBase *PreVectorPH = VectorPH->getSinglePredecessor();
972 VPBlockUtils::insertOnEdge(PreVectorPH, VectorPH, CheckBlockVPBB);
973 VPBlockUtils::connectBlocks(CheckBlockVPBB, ScalarPH);
974 CheckBlockVPBB->swapSuccessors();
975
976 // We just connected a new block to the scalar preheader. Update all
977 // VPPhis by adding an incoming value for it, replicating the last value.
978 unsigned NumPredecessors = ScalarPH->getNumPredecessors();
979 for (VPRecipeBase &R : cast<VPBasicBlock>(ScalarPH)->phis()) {
980 assert(isa<VPPhi>(&R) && "Phi expected to be VPPhi");
981 assert(cast<VPPhi>(&R)->getNumIncoming() == NumPredecessors - 1 &&
982 "must have incoming values for all operands");
983 R.addOperand(R.getOperand(NumPredecessors - 2));
984 }
985
986 VPIRMetadata VPBranchWeights;
987 auto *Term =
988 VPBuilder(CheckBlockVPBB)
991 Plan.getVectorLoopRegion()->getCanonicalIV()->getDebugLoc());
992 if (AddBranchWeights) {
993 MDBuilder MDB(Plan.getContext());
994 MDNode *BranchWeights =
995 MDB.createBranchWeights(CheckBypassWeights, /*IsExpected=*/false);
996 Term->setMetadata(LLVMContext::MD_prof, BranchWeights);
997 }
998}
999
1001 VPlan &Plan, ElementCount VF, unsigned UF,
1002 ElementCount MinProfitableTripCount, bool RequiresScalarEpilogue,
1003 bool TailFolded, bool CheckNeededWithTailFolding, Loop *OrigLoop,
1006 // Generate code to check if the loop's trip count is less than VF * UF, or
1007 // equal to it in case a scalar epilogue is required; this implies that the
1008 // vector trip count is zero. This check also covers the case where adding one
1009 // to the backedge-taken count overflowed leading to an incorrect trip count
1010 // of zero. In this case we will also jump to the scalar loop.
1011 CmpInst::Predicate CmpPred =
1012 RequiresScalarEpilogue ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_ULT;
1013 // If tail is to be folded, vector loop takes care of all iterations.
1014 VPValue *TripCountVPV = Plan.getTripCount();
1015 const SCEV *TripCount = vputils::getSCEVExprForVPValue(TripCountVPV, PSE);
1016 Type *TripCountTy = TripCount->getType();
1017 ScalarEvolution &SE = *PSE.getSE();
1018 auto GetMinTripCount = [&]() -> const SCEV * {
1019 // Compute max(MinProfitableTripCount, UF * VF) and return it.
1020 const SCEV *VFxUF =
1021 SE.getElementCount(TripCountTy, (VF * UF), SCEV::FlagNUW);
1022 if (UF * VF.getKnownMinValue() >=
1023 MinProfitableTripCount.getKnownMinValue()) {
1024 // TODO: SCEV should be able to simplify test.
1025 return VFxUF;
1026 }
1027 const SCEV *MinProfitableTripCountSCEV =
1028 SE.getElementCount(TripCountTy, MinProfitableTripCount, SCEV::FlagNUW);
1029 return SE.getUMaxExpr(MinProfitableTripCountSCEV, VFxUF);
1030 };
1031
1032 VPBasicBlock *EntryVPBB = Plan.getEntry();
1033 VPBuilder Builder(EntryVPBB);
1034 VPValue *TripCountCheck = Plan.getFalse();
1035 const SCEV *Step = GetMinTripCount();
1036 if (TailFolded) {
1037 if (CheckNeededWithTailFolding) {
1038 // vscale is not necessarily a power-of-2, which means we cannot guarantee
1039 // an overflow to zero when updating induction variables and so an
1040 // additional overflow check is required before entering the vector loop.
1041
1042 // Get the maximum unsigned value for the type.
1043 VPValue *MaxUIntTripCount =
1044 Plan.getConstantInt(cast<IntegerType>(TripCountTy)->getMask());
1045 VPValue *DistanceToMax = Builder.createNaryOp(
1046 Instruction::Sub, {MaxUIntTripCount, TripCountVPV},
1048
1049 // Don't execute the vector loop if (UMax - n) < (VF * UF).
1050 // FIXME: Should only check VF * UF, but currently checks Step=max(VF*UF,
1051 // minProfitableTripCount).
1052 TripCountCheck = Builder.createICmp(ICmpInst::ICMP_ULT, DistanceToMax,
1053 Builder.createExpandSCEV(Step), DL);
1054 } else {
1055 // TripCountCheck = false, folding tail implies positive vector trip
1056 // count.
1057 }
1058 } else {
1059 // TODO: Emit unconditional branch to vector preheader instead of
1060 // conditional branch with known condition.
1061 TripCount = SE.applyLoopGuards(TripCount, OrigLoop);
1062 // Check if the trip count is < the step.
1063 if (SE.isKnownPredicate(CmpPred, TripCount, Step)) {
1064 // TODO: Ensure step is at most the trip count when determining max VF and
1065 // UF, w/o tail folding.
1066 TripCountCheck = Plan.getTrue();
1067 } else if (!SE.isKnownPredicate(CmpInst::getInversePredicate(CmpPred),
1068 TripCount, Step)) {
1069 // Generate the minimum iteration check only if we cannot prove the
1070 // check is known to be true, or known to be false.
1071 VPValue *MinTripCountVPV = Builder.createExpandSCEV(Step);
1072 TripCountCheck = Builder.createICmp(
1073 CmpPred, TripCountVPV, MinTripCountVPV, DL, "min.iters.check");
1074 } // else step known to be < trip count, use TripCountCheck preset to false.
1075 }
1076 VPInstruction *Term =
1077 Builder.createNaryOp(VPInstruction::BranchOnCond, {TripCountCheck}, DL);
1079 MDBuilder MDB(Plan.getContext());
1080 MDNode *BranchWeights = MDB.createBranchWeights(
1081 ArrayRef(MinItersBypassWeights, 2), /*IsExpected=*/false);
1082 Term->setMetadata(LLVMContext::MD_prof, BranchWeights);
1083 }
1084}
1085
1087 VPlan &Plan, Value *TripCount, Value *VectorTripCount,
1088 bool RequiresScalarEpilogue, ElementCount EpilogueVF, unsigned EpilogueUF,
1089 unsigned MainLoopStep, unsigned EpilogueLoopStep, ScalarEvolution &SE) {
1090 // Add the minimum iteration check for the epilogue vector loop.
1091 VPValue *TC = Plan.getOrAddLiveIn(TripCount);
1092 VPBuilder Builder(cast<VPBasicBlock>(Plan.getEntry()));
1093 VPValue *VFxUF = Builder.createExpandSCEV(SE.getElementCount(
1094 TripCount->getType(), (EpilogueVF * EpilogueUF), SCEV::FlagNUW));
1095 VPValue *Count = Builder.createNaryOp(
1096 Instruction::Sub, {TC, Plan.getOrAddLiveIn(VectorTripCount)},
1097 DebugLoc::getUnknown(), "n.vec.remaining");
1098
1099 // Generate code to check if the loop's trip count is less than VF * UF of
1100 // the vector epilogue loop.
1101 auto P = RequiresScalarEpilogue ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_ULT;
1102 auto *CheckMinIters = Builder.createICmp(
1103 P, Count, VFxUF, DebugLoc::getUnknown(), "min.epilog.iters.check");
1104 VPInstruction *Branch =
1105 Builder.createNaryOp(VPInstruction::BranchOnCond, CheckMinIters);
1106
1107 // We assume the remaining `Count` is equally distributed in
1108 // [0, MainLoopStep)
1109 // So the probability for `Count < EpilogueLoopStep` should be
1110 // min(MainLoopStep, EpilogueLoopStep) / MainLoopStep
1111 // TODO: Improve the estimate by taking the estimated trip count into
1112 // consideration.
1113 unsigned EstimatedSkipCount = std::min(MainLoopStep, EpilogueLoopStep);
1114 const uint32_t Weights[] = {EstimatedSkipCount,
1115 MainLoopStep - EstimatedSkipCount};
1116 MDBuilder MDB(Plan.getContext());
1117 MDNode *BranchWeights =
1118 MDB.createBranchWeights(Weights, /*IsExpected=*/false);
1119 Branch->setMetadata(LLVMContext::MD_prof, BranchWeights);
1120}
1121
1122/// If \p V is used by a recipe matching pattern \p P, return it. Otherwise
1123/// return nullptr;
1124template <typename MatchT>
1125static VPRecipeBase *findUserOf(VPValue *V, const MatchT &P) {
1126 auto It = find_if(V->users(), match_fn(P));
1127 return It == V->user_end() ? nullptr : cast<VPRecipeBase>(*It);
1128}
1129
1130/// If \p V is used by a VPInstruction with \p Opcode, return it. Otherwise
1131/// return nullptr.
1132template <unsigned Opcode> static VPInstruction *findUserOf(VPValue *V) {
1134}
1135
1137 auto GetMinMaxCompareValue = [](VPReductionPHIRecipe *RedPhiR) -> VPValue * {
1138 auto *MinMaxR =
1139 dyn_cast_or_null<VPRecipeWithIRFlags>(RedPhiR->getBackedgeValue());
1140 if (!MinMaxR)
1141 return nullptr;
1142
1143 // Check that MinMaxR is a VPWidenIntrinsicRecipe or VPReplicateRecipe
1144 // with an intrinsic that matches the reduction kind.
1145 Intrinsic::ID ExpectedIntrinsicID =
1146 getMinMaxReductionIntrinsicOp(RedPhiR->getRecurrenceKind());
1147 if (!match(MinMaxR, m_Intrinsic(ExpectedIntrinsicID)))
1148 return nullptr;
1149
1150 if (MinMaxR->getOperand(0) == RedPhiR)
1151 return MinMaxR->getOperand(1);
1152
1153 assert(MinMaxR->getOperand(1) == RedPhiR &&
1154 "Reduction phi operand expected");
1155 return MinMaxR->getOperand(0);
1156 };
1157
1158 VPRegionBlock *LoopRegion = Plan.getVectorLoopRegion();
1160 MinMaxNumReductionsToHandle;
1161 bool HasUnsupportedPhi = false;
1162 for (auto &R : LoopRegion->getEntryBasicBlock()->phis()) {
1164 continue;
1165 auto *Cur = dyn_cast<VPReductionPHIRecipe>(&R);
1166 if (!Cur) {
1167 // TODO: Also support fixed-order recurrence phis.
1168 HasUnsupportedPhi = true;
1169 continue;
1170 }
1172 Cur->getRecurrenceKind())) {
1173 HasUnsupportedPhi = true;
1174 continue;
1175 }
1176
1177 VPValue *MinMaxOp = GetMinMaxCompareValue(Cur);
1178 if (!MinMaxOp)
1179 return false;
1180
1181 MinMaxNumReductionsToHandle.emplace_back(Cur, MinMaxOp);
1182 }
1183
1184 if (MinMaxNumReductionsToHandle.empty())
1185 return true;
1186
1187 // We won't be able to resume execution in the scalar tail, if there are
1188 // unsupported header phis or there is no scalar tail at all, due to
1189 // tail-folding.
1190 if (HasUnsupportedPhi || !Plan.hasScalarTail())
1191 return false;
1192
1193 /// Check if the vector loop of \p Plan can early exit and restart
1194 /// execution of last vector iteration in the scalar loop. This requires all
1195 /// recipes up to early exit point be side-effect free as they are
1196 /// re-executed. Currently we check that the loop is free of any recipe that
1197 /// may write to memory. Expected to operate on an early VPlan w/o nested
1198 /// regions.
1201 auto *VPBB = cast<VPBasicBlock>(VPB);
1202 for (auto &R : *VPBB) {
1203 if (R.mayWriteToMemory() && !match(&R, m_BranchOnCount()))
1204 return false;
1205 }
1206 }
1207
1208 VPBasicBlock *LatchVPBB = LoopRegion->getExitingBasicBlock();
1209 VPBuilder LatchBuilder(LatchVPBB->getTerminator());
1210 VPValue *AllNaNLanes = nullptr;
1211 SmallPtrSet<VPValue *, 2> RdxResults;
1212 for (const auto &[_, MinMaxOp] : MinMaxNumReductionsToHandle) {
1213 VPValue *RedNaNLanes =
1214 LatchBuilder.createFCmp(CmpInst::FCMP_UNO, MinMaxOp, MinMaxOp);
1215 AllNaNLanes = AllNaNLanes ? LatchBuilder.createOr(AllNaNLanes, RedNaNLanes)
1216 : RedNaNLanes;
1217 }
1218
1219 VPValue *AnyNaNLane =
1220 LatchBuilder.createNaryOp(VPInstruction::AnyOf, {AllNaNLanes});
1221 VPBasicBlock *MiddleVPBB = Plan.getMiddleBlock();
1222 VPBuilder MiddleBuilder(MiddleVPBB, MiddleVPBB->begin());
1223 for (const auto &[RedPhiR, _] : MinMaxNumReductionsToHandle) {
1225 RedPhiR->getRecurrenceKind()) &&
1226 "unsupported reduction");
1227
1228 // If we exit early due to NaNs, compute the final reduction result based on
1229 // the reduction phi at the beginning of the last vector iteration.
1230 auto *RdxResult =
1232
1233 auto *NewSel = MiddleBuilder.createSelect(AnyNaNLane, RedPhiR,
1234 RdxResult->getOperand(1));
1235 RdxResult->setOperand(1, NewSel);
1236 assert(!RdxResults.contains(RdxResult) && "RdxResult already used");
1237 RdxResults.insert(RdxResult);
1238 }
1239
1240 auto *LatchExitingBranch = LatchVPBB->getTerminator();
1241 assert(match(LatchExitingBranch, m_BranchOnCount(m_VPValue(), m_VPValue())) &&
1242 "Unexpected terminator");
1243 auto *IsLatchExitTaken = LatchBuilder.createICmp(
1244 CmpInst::ICMP_EQ, LatchExitingBranch->getOperand(0),
1245 LatchExitingBranch->getOperand(1));
1246 auto *AnyExitTaken = LatchBuilder.createNaryOp(
1247 Instruction::Or, {AnyNaNLane, IsLatchExitTaken});
1248 LatchBuilder.createNaryOp(VPInstruction::BranchOnCond, AnyExitTaken);
1249 LatchExitingBranch->eraseFromParent();
1250
1251 // Update resume phis for inductions in the scalar preheader. If AnyNaNLane is
1252 // true, the resume from the start of the last vector iteration via the
1253 // canonical IV, otherwise from the original value.
1254 for (auto &R : Plan.getScalarPreheader()->phis()) {
1255 auto *ResumeR = cast<VPPhi>(&R);
1256 VPValue *VecV = ResumeR->getOperand(0);
1257 if (RdxResults.contains(VecV))
1258 continue;
1259 if (auto *DerivedIV = dyn_cast<VPDerivedIVRecipe>(VecV)) {
1260 if (DerivedIV->getNumUsers() == 1 &&
1261 DerivedIV->getOperand(1) == &Plan.getVectorTripCount()) {
1262 auto *NewSel =
1263 MiddleBuilder.createSelect(AnyNaNLane, LoopRegion->getCanonicalIV(),
1264 &Plan.getVectorTripCount());
1265 DerivedIV->moveAfter(&*MiddleBuilder.getInsertPoint());
1266 DerivedIV->setOperand(1, NewSel);
1267 continue;
1268 }
1269 }
1270 // Bail out and abandon the current, partially modified, VPlan if we
1271 // encounter resume phi that cannot be updated yet.
1272 if (VecV != &Plan.getVectorTripCount()) {
1273 LLVM_DEBUG(dbgs() << "Found resume phi we cannot update for VPlan with "
1274 "FMaxNum/FMinNum reduction.\n");
1275 return false;
1276 }
1277 auto *NewSel = MiddleBuilder.createSelect(
1278 AnyNaNLane, LoopRegion->getCanonicalIV(), VecV);
1279 ResumeR->setOperand(0, NewSel);
1280 }
1281
1282 auto *MiddleTerm = MiddleVPBB->getTerminator();
1283 MiddleBuilder.setInsertPoint(MiddleTerm);
1284 VPValue *MiddleCond = MiddleTerm->getOperand(0);
1285 VPValue *NewCond =
1286 MiddleBuilder.createAnd(MiddleCond, MiddleBuilder.createNot(AnyNaNLane));
1287 MiddleTerm->setOperand(0, NewCond);
1288 return true;
1289}
1290
1292 for (auto &PhiR : make_early_inc_range(
1294 auto *MinMaxPhiR = dyn_cast<VPReductionPHIRecipe>(&PhiR);
1295 // TODO: check for multi-uses in VPlan directly.
1296 if (!MinMaxPhiR || !MinMaxPhiR->hasUsesOutsideReductionChain())
1297 continue;
1298
1299 // MinMaxPhiR has users outside the reduction cycle in the loop. Check if
1300 // the only other user is a FindLastIV reduction. MinMaxPhiR must have
1301 // exactly 3 users: 1) the min/max operation, the compare of a FindLastIV
1302 // reduction and ComputeReductionResult. The comparisom must compare
1303 // MinMaxPhiR against the min/max operand used for the min/max reduction
1304 // and only be used by the select of the FindLastIV reduction.
1305 RecurKind RdxKind = MinMaxPhiR->getRecurrenceKind();
1306 assert(
1308 "only min/max recurrences support users outside the reduction chain");
1309
1310 auto *MinMaxOp =
1311 dyn_cast<VPRecipeWithIRFlags>(MinMaxPhiR->getBackedgeValue());
1312 if (!MinMaxOp)
1313 return false;
1314
1315 // Check that MinMaxOp is a VPWidenIntrinsicRecipe or VPReplicateRecipe
1316 // with an intrinsic that matches the reduction kind.
1317 Intrinsic::ID ExpectedIntrinsicID = getMinMaxReductionIntrinsicOp(RdxKind);
1318 if (!match(MinMaxOp, m_Intrinsic(ExpectedIntrinsicID)))
1319 return false;
1320
1321 // MinMaxOp must have 2 users: 1) MinMaxPhiR and 2) ComputeReductionResult
1322 // (asserted below).
1323 assert(MinMaxOp->getNumUsers() == 2 &&
1324 "MinMaxOp must have exactly 2 users");
1325 VPValue *MinMaxOpValue = MinMaxOp->getOperand(0);
1326 if (MinMaxOpValue == MinMaxPhiR)
1327 MinMaxOpValue = MinMaxOp->getOperand(1);
1328
1329 VPValue *CmpOpA;
1330 VPValue *CmpOpB;
1331 CmpPredicate Pred;
1333 MinMaxPhiR, m_Cmp(Pred, m_VPValue(CmpOpA), m_VPValue(CmpOpB))));
1334 if (!Cmp || Cmp->getNumUsers() != 1 ||
1335 (CmpOpA != MinMaxOpValue && CmpOpB != MinMaxOpValue))
1336 return false;
1337
1338 if (MinMaxOpValue != CmpOpB)
1339 Pred = CmpInst::getSwappedPredicate(Pred);
1340
1341 // MinMaxPhiR must have exactly 3 users:
1342 // * MinMaxOp,
1343 // * Cmp (that's part of a FindLastIV chain),
1344 // * ComputeReductionResult.
1345 if (MinMaxPhiR->getNumUsers() != 3)
1346 return false;
1347
1348 VPInstruction *MinMaxResult =
1350 assert(is_contained(MinMaxPhiR->users(), MinMaxOp) &&
1351 "one user must be MinMaxOp");
1352 assert(MinMaxResult && "MinMaxResult must be a user of MinMaxPhiR");
1353 assert(is_contained(MinMaxOp->users(), MinMaxResult) &&
1354 "MinMaxResult must be a user of MinMaxOp (and of MinMaxPhiR");
1355
1356 // Cmp must be used by the select of a FindLastIV chain.
1357 VPValue *Sel = dyn_cast<VPSingleDefRecipe>(Cmp->getSingleUser());
1358 VPValue *IVOp, *FindIV;
1359 if (!Sel || Sel->getNumUsers() != 2 ||
1360 !match(Sel,
1361 m_Select(m_Specific(Cmp), m_VPValue(IVOp), m_VPValue(FindIV))))
1362 return false;
1363
1364 if (!isa<VPReductionPHIRecipe>(FindIV)) {
1365 std::swap(FindIV, IVOp);
1366 Pred = CmpInst::getInversePredicate(Pred);
1367 }
1368
1369 auto *FindIVPhiR = dyn_cast<VPReductionPHIRecipe>(FindIV);
1371 FindIVPhiR->getRecurrenceKind()))
1372 return false;
1373
1374 // TODO: Support cases where IVOp is the IV increment.
1375 if (!match(IVOp, m_TruncOrSelf(m_VPValue(IVOp))) ||
1377 return false;
1378
1379 CmpInst::Predicate RdxPredicate = [RdxKind]() {
1380 switch (RdxKind) {
1381 case RecurKind::UMin:
1382 return CmpInst::ICMP_UGE;
1383 case RecurKind::UMax:
1384 return CmpInst::ICMP_ULE;
1385 case RecurKind::SMax:
1386 return CmpInst::ICMP_SLE;
1387 case RecurKind::SMin:
1388 return CmpInst::ICMP_SGE;
1389 default:
1390 llvm_unreachable("unhandled recurrence kind");
1391 }
1392 }();
1393
1394 // TODO: Strict predicates need to find the first IV value for which the
1395 // predicate holds, not the last.
1396 if (Pred != RdxPredicate)
1397 return false;
1398
1399 assert(!FindIVPhiR->isInLoop() && !FindIVPhiR->isOrdered() &&
1400 "cannot handle inloop/ordered reductions yet");
1401
1402 // The reduction using MinMaxPhiR needs adjusting to compute the correct
1403 // result:
1404 // 1. We need to find the last IV for which the condition based on the
1405 // min/max recurrence is true,
1406 // 2. Compare the partial min/max reduction result to its final value and,
1407 // 3. Select the lanes of the partial FindLastIV reductions which
1408 // correspond to the lanes matching the min/max reduction result.
1409 //
1410 // For example, this transforms
1411 // vp<%min.result> = compute-reduction-result ir<%min.val>,
1412 // ir<%min.val.next>
1413 // vp<%find.iv.result = compute-find-iv-result ir<%min.idx>, ir<0>,
1414 // SENTINEL, vp<%min.idx.next>
1415 //
1416 // into:
1417 //
1418 // vp<min.result> = compute-reduction-result ir<%min.val>, ir<%min.val.next>
1419 // vp<%final.min.cmp> = icmp eq ir<%min.val.next>, vp<min.result>
1420 // vp<%final.iv> = select vp<%final.min.cmp>, ir<%min.idx.next>, SENTINEL
1421 // vp<%find.iv.result> = compute-find-iv-result ir<%min.idx>, ir<0>,
1422 // SENTINEL, vp<%final.iv>
1423 VPInstruction *FindIVResult =
1425 assert(FindIVResult->getParent() == MinMaxResult->getParent() &&
1426 "both results must be computed in the same block");
1427 MinMaxResult->moveBefore(*FindIVResult->getParent(),
1428 FindIVResult->getIterator());
1429
1430 VPBuilder B(FindIVResult);
1431 VPValue *MinMaxExiting = MinMaxResult->getOperand(1);
1432 auto *FinalMinMaxCmp =
1433 B.createICmp(CmpInst::ICMP_EQ, MinMaxExiting, MinMaxResult);
1434 VPValue *Sentinel = FindIVResult->getOperand(2);
1435 VPValue *LastIVExiting = FindIVResult->getOperand(3);
1436 auto *FinalIVSelect =
1437 B.createSelect(FinalMinMaxCmp, LastIVExiting, Sentinel);
1438 FindIVResult->setOperand(3, FinalIVSelect);
1439 }
1440 return true;
1441}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define _
static std::pair< Value *, APInt > getMask(Value *WideMask, unsigned Factor, ElementCount LeafValueEC)
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
static DebugLoc getDebugLoc(MachineBasicBlock::instr_iterator FirstMI, MachineBasicBlock::instr_iterator LastMI)
Return the first DebugLoc that has line number information, given a range of instructions.
#define P(N)
const SmallVectorImpl< MachineOperand > & Cond
static bool dominates(InstrPosIndexes &PosIndexes, const MachineInstr &A, const MachineInstr &B)
#define LLVM_DEBUG(...)
Definition Debug.h:114
static void createLoopRegion(VPlan &Plan, VPBlockBase *HeaderVPB)
Create a new VPRegionBlock for the loop starting at HeaderVPB.
static bool isHeaderBB(BasicBlock *BB, Loop *L)
static void simplifyLiveInsWithSCEV(VPlan &Plan, PredicatedScalarEvolution &PSE)
Check Plan's live-in and replace them with constants, if they can be simplified via SCEV.
static VPRecipeBase * findUserOf(VPValue *V, const MatchT &P)
If V is used by a recipe matching pattern P, return it.
static void addInitialSkeleton(VPlan &Plan, Type *InductionTy, DebugLoc IVDL, PredicatedScalarEvolution &PSE, Loop *TheLoop)
static VPHeaderPHIRecipe * createWidenInductionRecipe(PHINode *Phi, VPPhi *PhiR, VPValue *Start, const InductionDescriptor &IndDesc, VPlan &Plan, PredicatedScalarEvolution &PSE, Loop &OrigLoop, DebugLoc DL)
Creates a VPWidenIntOrFpInductionRecipe or VPWidenPointerInductionRecipe for Phi based on IndDesc.
static void addCanonicalIVRecipes(VPlan &Plan, VPBasicBlock *HeaderVPBB, VPBasicBlock *LatchVPBB, Type *IdxTy, DebugLoc DL)
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 constexpr uint32_t CheckBypassWeights[]
static void createExtractsForLiveOuts(VPlan &Plan, VPBasicBlock *MiddleVPBB)
Creates extracts for values in Plan defined in a loop region and used outside a loop region.
This file implements dominator tree analysis for a single level of a VPlan's H-CFG.
static std::optional< unsigned > getOpcode(ArrayRef< VPValue * > Values)
Returns the opcode of Values or ~0 if they do not all agree.
Definition VPlanSLP.cpp:247
This file provides utility VPlan to VPlan transformations.
This file contains the declarations of the Vectorization Plan base classes:
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
size - Get the array size.
Definition ArrayRef.h:142
LLVM Basic Block Representation.
Definition BasicBlock.h:62
LLVM_ABI iterator_range< filter_iterator< BasicBlock::const_iterator, std::function< bool(const Instruction &)> > > instructionsWithoutDebug(bool SkipPseudoOp=true) const
Return a const iterator range over the instructions in the block, skipping any debug instructions.
LLVM_ABI const BasicBlock * getSingleSuccessor() const
Return the successor of this block if it has a single successor.
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Definition BasicBlock.h:233
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:676
@ ICMP_SLE
signed less or equal
Definition InstrTypes.h:706
@ ICMP_UGE
unsigned greater or equal
Definition InstrTypes.h:700
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:701
@ ICMP_SGE
signed greater or equal
Definition InstrTypes.h:704
@ ICMP_ULE
unsigned less or equal
Definition InstrTypes.h:702
@ FCMP_UNO
1 0 0 0 True if unordered: isnan(X) | isnan(Y)
Definition InstrTypes.h:686
Predicate getSwappedPredicate() const
For example, EQ->EQ, SLE->SGE, ULT->UGT, OEQ->OEQ, ULE->UGE, OLT->OGT, etc.
Definition InstrTypes.h:827
Predicate getInversePredicate() const
For example, EQ -> NE, UGT -> ULE, SLT -> SGE, OEQ -> UNE, UGT -> OLE, OLT -> UGE,...
Definition InstrTypes.h:789
An abstraction over a floating-point predicate, and a pack of an integer predicate with samesign info...
A debug info location.
Definition DebugLoc.h:123
static DebugLoc getUnknown()
Definition DebugLoc.h:161
ValueT lookup(const_arg_type_t< KeyT > Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
Definition DenseMap.h:205
Implements a dense probed hash-table based set.
Definition DenseSet.h:279
bool dominates(const DomTreeNodeBase< NodeT > *A, const DomTreeNodeBase< NodeT > *B) const
dominates - Returns true iff A dominates B.
constexpr bool isScalar() const
Exactly one element.
Definition TypeSize.h:320
Convenience struct for specifying and reasoning about fast-math flags.
Definition FMF.h:22
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.
bool contains(const LoopT *L) const
Return true if the specified loop is contained within in this loop.
BlockT * getHeader() const
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
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...
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
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:1078
This class implements a map that also provides access to all stored values in a deterministic order.
Definition MapVector.h:36
iterator end()
Definition MapVector.h:67
iterator find(const KeyT &Key)
Definition MapVector.h:154
An interface layer with SCEV used to manage how we see SCEV expressions for values in the context of ...
ScalarEvolution * getSE() const
Returns the ScalarEvolution analysis used.
LLVM_ABI const SCEV * getSymbolicMaxBackedgeTakenCount()
Get the (predicated) symbolic max backedge count for the analyzed loop.
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.
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.
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,...
static bool isFindLastIVRecurrenceKind(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 bool isIntMinMaxRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is an integer min/max kind.
static bool isMinMaxRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is any min/max kind.
This class represents an analyzed expression in the program.
LLVM_ABI Type * getType() const
Return the LLVM type of this SCEV expression.
The main scalar evolution driver.
LLVM_ABI const SCEV * getUMaxExpr(const SCEV *LHS, const SCEV *RHS)
LLVM_ABI const SCEV * getSCEV(Value *V)
Return a SCEV expression for the full generality of the specified expression.
LLVM_ABI const SCEV * getTripCountFromExitCount(const SCEV *ExitCount)
A version of getTripCountFromExitCount below which always picks an evaluation type which can not resu...
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 * getElementCount(Type *Ty, ElementCount EC, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap)
LLVM_ABI const SCEV * applyLoopGuards(const SCEV *Expr, const Loop *L)
Try to apply information from loop guards for L to Expr.
LLVM_ABI bool isKnownPredicate(CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS)
Test if the given expression is known to satisfy the condition described by Pred, LHS,...
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:151
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:45
op_range operands()
Definition User.h:293
VPBasicBlock serves as the leaf of the Hierarchical Control-Flow Graph.
Definition VPlan.h:3982
void appendRecipe(VPRecipeBase *Recipe)
Augment the existing recipes of a VPBasicBlock with an additional Recipe as the last recipe.
Definition VPlan.h:4057
iterator end()
Definition VPlan.h:4019
iterator begin()
Recipe iterator methods.
Definition VPlan.h:4017
iterator_range< iterator > phis()
Returns an iterator range over the PHI-like recipes in the block.
Definition VPlan.h:4070
iterator getFirstNonPhi()
Return the position of the first non-phi node recipe in the block.
Definition VPlan.cpp:216
VPRecipeBase * getTerminator()
If the block has multiple successors, return the branch recipe terminating the block.
Definition VPlan.cpp:623
const VPRecipeBase & back() const
Definition VPlan.h:4031
void insert(VPRecipeBase *Recipe, iterator InsertPt)
Definition VPlan.h:4048
bool empty() const
Definition VPlan.h:4028
VPBlockBase is the building block of the Hierarchical Control-Flow Graph.
Definition VPlan.h:81
void setSuccessors(ArrayRef< VPBlockBase * > NewSuccs)
Set each VPBasicBlock in NewSuccss as successor of this VPBlockBase.
Definition VPlan.h:300
VPRegionBlock * getParent()
Definition VPlan.h:173
const VPBasicBlock * getExitingBasicBlock() const
Definition VPlan.cpp:186
void setName(const Twine &newName)
Definition VPlan.h:166
size_t getNumSuccessors() const
Definition VPlan.h:219
void swapSuccessors()
Swap successors of the block. The block must have exactly 2 successors.
Definition VPlan.h:322
size_t getNumPredecessors() const
Definition VPlan.h:220
void setPredecessors(ArrayRef< VPBlockBase * > NewPreds)
Set each VPBasicBlock in NewPreds as predecessor of this VPBlockBase.
Definition VPlan.h:291
const VPBlocksTy & getPredecessors() const
Definition VPlan.h:204
void setTwoSuccessors(VPBlockBase *IfTrue, VPBlockBase *IfFalse)
Set two given VPBlockBases IfTrue and IfFalse to be the two successors of this VPBlockBase.
Definition VPlan.h:282
VPBlockBase * getSinglePredecessor() const
Definition VPlan.h:215
void swapPredecessors()
Swap predecessors of the block.
Definition VPlan.h:314
const VPBasicBlock * getEntryBasicBlock() const
Definition VPlan.cpp:166
void setOneSuccessor(VPBlockBase *Successor)
Set a given VPBlockBase Successor as the single successor of this VPBlockBase.
Definition VPlan.h:271
void setParent(VPRegionBlock *P)
Definition VPlan.h:184
VPBlockBase * getSingleSuccessor() const
Definition VPlan.h:209
const VPBlocksTy & getSuccessors() const
Definition VPlan.h:198
static void insertBlockAfter(VPBlockBase *NewBlock, VPBlockBase *BlockPtr)
Insert disconnected VPBlockBase NewBlock after BlockPtr.
Definition VPlanUtils.h:122
static void insertOnEdge(VPBlockBase *From, VPBlockBase *To, VPBlockBase *BlockPtr)
Inserts BlockPtr on the edge between From and To.
Definition VPlanUtils.h:243
static void connectBlocks(VPBlockBase *From, VPBlockBase *To, unsigned PredIdx=-1u, unsigned SuccIdx=-1u)
Connect VPBlockBases From and To bi-directionally.
Definition VPlanUtils.h:173
static void disconnectBlocks(VPBlockBase *From, VPBlockBase *To)
Disconnect VPBlockBases From and To bi-directionally.
Definition VPlanUtils.h:192
VPlan-based builder utility analogous to IRBuilder.
VPInstruction * createOr(VPValue *LHS, VPValue *RHS, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="")
VPInstruction * createScalarCast(Instruction::CastOps Opcode, VPValue *Op, Type *ResultTy, DebugLoc DL, const VPIRFlags &Flags={}, const VPIRMetadata &Metadata={})
VPInstruction * createNot(VPValue *Operand, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="")
VPInstruction * createSelect(VPValue *Cond, VPValue *TrueVal, VPValue *FalseVal, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="", std::optional< FastMathFlags > FMFs=std::nullopt)
VPBasicBlock::iterator getInsertPoint() const
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.
VPPhi * createScalarPhi(ArrayRef< VPValue * > IncomingValues, DebugLoc DL, 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.
VPInstruction * createAnd(VPValue *LHS, VPValue *RHS, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="")
void setInsertPoint(VPBasicBlock *TheBB)
This specifies that created VPInstructions should be appended to the end of the specified block.
VPInstruction * createNaryOp(unsigned Opcode, ArrayRef< VPValue * > Operands, Instruction *Inst=nullptr, const VPIRFlags &Flags={}, const VPIRMetadata &MD={}, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="")
Create an N-ary operation with Opcode, Operands and set Inst as its underlying Instruction.
Canonical scalar induction phi of the vector loop.
Definition VPlan.h:3565
Template specialization of the standard LLVM dominator tree utility for VPBlockBases.
A pure virtual base class for all recipes modeling header phis, including phis for first order recurr...
Definition VPlan.h:2056
A special type of VPBasicBlock that wraps an existing IR basic block.
Definition VPlan.h:4135
Class to record and manage LLVM IR flags.
Definition VPlan.h:609
Helper to manage IR metadata for recipes.
Definition VPlan.h:982
This is a concrete Recipe that models a single VPlan-level instruction.
Definition VPlan.h:1036
VPRecipeBase is a base class modeling a sequence of one or more output IR instructions.
Definition VPlan.h:387
VPBasicBlock * getParent()
Definition VPlan.h:408
DebugLoc getDebugLoc() const
Returns the debug location of the recipe.
Definition VPlan.h:479
void moveBefore(VPBasicBlock &BB, iplist< VPRecipeBase >::iterator I)
Unlink this recipe and insert into BB before I.
void insertBefore(VPRecipeBase *InsertPos)
Insert an unlinked recipe into a basic block immediately before the specified recipe.
iplist< VPRecipeBase >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
void moveAfter(VPRecipeBase *MovePos)
Unlink this recipe from its current VPBasicBlock and insert it into the VPBasicBlock that MovePos liv...
A recipe for handling reduction phis.
Definition VPlan.h:2437
A recipe to represent inloop, ordered or partial reduction operations.
Definition VPlan.h:2797
VPRegionBlock represents a collection of VPBasicBlocks and VPRegionBlocks which form a Single-Entry-S...
Definition VPlan.h:4170
VPCanonicalIVPHIRecipe * getCanonicalIV()
Returns the canonical induction recipe of the region.
Definition VPlan.h:4268
VPSingleDef is a base class for recipes for modeling a sequence of one or more output IR that define ...
Definition VPlan.h:531
An analysis for type-inference for VPValues.
Type * inferScalarType(const VPValue *V)
Infer the type of V. Returns the scalar type of V.
This class augments VPValue with operands which provide the inverse def-use edges from VPValue's user...
Definition VPlanValue.h:202
void setOperand(unsigned I, VPValue *New)
Definition VPlanValue.h:246
VPValue * getOperand(unsigned N) const
Definition VPlanValue.h:241
void addOperand(VPValue *Operand)
Definition VPlanValue.h:235
This is the base class of the VPlan Def/Use graph, used for modeling the data flow into,...
Definition VPlanValue.h:46
VPRecipeBase * getDefiningRecipe()
Returns the recipe defining this VPValue or nullptr if it is not defined by a recipe,...
Definition VPlan.cpp:131
void setUnderlyingValue(Value *Val)
Definition VPlanValue.h:191
unsigned getNumUsers() const
Definition VPlanValue.h:111
user_range users()
Definition VPlanValue.h:132
A recipe for handling phi nodes of integer and floating-point inductions, producing their vector valu...
Definition VPlan.h:2199
VPlan models a candidate for vectorization, encoding various decisions take to produce efficient outp...
Definition VPlan.h:4300
LLVMContext & getContext() const
Definition VPlan.h:4489
VPBasicBlock * getEntry()
Definition VPlan.h:4389
VPValue & getVectorTripCount()
The vector trip count.
Definition VPlan.h:4480
VPValue & getVFxUF()
Returns VF * UF of the vector loop region.
Definition VPlan.h:4487
VPValue & getVF()
Returns the VF of the vector loop region.
Definition VPlan.h:4483
VPValue * getTripCount() const
The trip count of the original loop.
Definition VPlan.h:4451
VPValue * getTrue()
Return a VPValue wrapping i1 true.
Definition VPlan.h:4557
auto getLiveIns() const
Return the list of live-in VPValues available in the VPlan.
Definition VPlan.h:4582
ArrayRef< VPIRBasicBlock * > getExitBlocks() const
Return an ArrayRef containing VPIRBasicBlocks wrapping the exit blocks of the original scalar loop.
Definition VPlan.h:4441
VPValue * getConstantInt(Type *Ty, uint64_t Val, bool IsSigned=false)
Return a VPValue wrapping a ConstantInt with the given type and value.
Definition VPlan.h:4563
LLVM_ABI_FOR_TEST VPRegionBlock * getVectorLoopRegion()
Returns the VPRegionBlock of the vector loop.
Definition VPlan.cpp:1010
void setTripCount(VPValue *NewTripCount)
Set the trip count assuming it is currently null; if it is not - use resetTripCount().
Definition VPlan.h:4458
VPBasicBlock * getMiddleBlock()
Returns the 'middle' block of the plan, that is the block that selects whether to execute the scalar ...
Definition VPlan.h:4414
VPBasicBlock * createVPBasicBlock(const Twine &Name, VPRecipeBase *Recipe=nullptr)
Create a new VPBasicBlock with Name and containing Recipe if present.
Definition VPlan.h:4605
LLVM_ABI_FOR_TEST VPIRBasicBlock * createVPIRBasicBlock(BasicBlock *IRBB)
Create a VPIRBasicBlock from IRBB containing VPIRInstructions for all instructions in IRBB,...
Definition VPlan.cpp:1225
VPValue * getFalse()
Return a VPValue wrapping i1 false.
Definition VPlan.h:4560
VPValue * getOrAddLiveIn(Value *V)
Gets the live-in VPValue for V or adds a new live-in (if none exists yet) for V.
Definition VPlan.h:4543
VPRegionBlock * createLoopRegion(const std::string &Name="", VPBlockBase *Entry=nullptr, VPBlockBase *Exiting=nullptr)
Create a new loop region with Name and entry and exiting blocks set to Entry and Exiting respectively...
Definition VPlan.h:4615
VPBasicBlock * getScalarPreheader() const
Return the VPBasicBlock for the preheader of the scalar loop.
Definition VPlan.h:4432
VPIRBasicBlock * getScalarHeader() const
Return the VPIRBasicBlock wrapping the header of the scalar loop.
Definition VPlan.h:4437
VPValue * getLiveIn(Value *V) const
Return the live-in VPValue for V, if there is one or nullptr otherwise.
Definition VPlan.h:4579
VPBasicBlock * getVectorPreheader()
Returns the preheader of the vector loop region, if one exists, or null otherwise.
Definition VPlan.h:4394
bool hasScalarTail() const
Returns true if the scalar tail may execute after the vector loop.
Definition VPlan.h:4659
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:256
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:322
bool contains(const_arg_type_t< ValueT > V) const
Check if the set contains the given element.
Definition DenseSet.h:175
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
Definition TypeSize.h:165
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.
@ Entry
Definition COFF.h:862
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:81
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.
IntrinsicID_match m_Intrinsic()
Match intrinsic calls like this: m_Intrinsic<Intrinsic::fabs>(m_Value(X))
ThreeOps_match< Cond, LHS, RHS, Instruction::Select > m_Select(const Cond &C, const LHS &L, const RHS &R)
Matches SelectInst.
class_match< CmpInst > m_Cmp()
Matches any compare instruction and ignore it.
MatchFunctor< Val, Pattern > match_fn(const Pattern &P)
A match functor that can be used as a UnaryPredicate in functional algorithms like all_of.
BinaryOp_match< LHS, RHS, Instruction::Sub > m_Sub(const LHS &L, const RHS &R)
VPInstruction_match< VPInstruction::BranchOnCount > m_BranchOnCount()
class_match< VPValue > m_VPValue()
Match an arbitrary VPValue and ignore it.
bind_ty< 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
VPValue * getOrCreateVPValueForSCEVExpr(VPlan &Plan, const SCEV *Expr)
Get or create a VPValue that corresponds to the expansion of Expr.
VPIRFlags getFlagsFromIndDesc(const InductionDescriptor &ID)
Extracts and returns NoWrap and FastMath flags from the induction binop in ID.
Definition VPlanUtils.h:93
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
FunctionAddr VTableAddr Value
Definition InstrProf.h:137
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:839
ReductionStyle getReductionStyle(bool InLoop, bool Ordered, unsigned ScaleFactor)
Definition VPlan.h:2423
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
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:632
auto cast_or_null(const Y &Val)
Definition Casting.h:714
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:216
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:207
FunctionAddr VTableAddr Count
Definition InstrProf.h:139
auto succ_size(const MachineBasicBlock *BB)
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...
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
iterator_range< po_iterator< VPBlockShallowTraversalWrapper< VPBlockBase * > > > vp_post_order_shallow(VPBlockBase *G)
Returns an iterator range to traverse the graph starting at G in post order.
Definition VPlanCFG.h:229
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
RecurKind
These are the kinds of recurrences that we support.
@ UMin
Unsigned integer min implemented in terms of select(cmp()).
@ 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()).
@ Sub
Subtraction of integers.
@ AddChainWithSubs
A chain of adds and subs.
@ UMax
Unsigned integer max implemented in terms of select(cmp()).
DWARFExpression::Operation Op
ArrayRef(const T &OneElt) -> ArrayRef< T >
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:1770
auto predecessors(const MachineBasicBlock *BB)
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1945
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:872
A recipe for handling first-order recurrence phis.
Definition VPlan.h:2375
static bool handleMultiUseReductions(VPlan &Plan)
Try to legalize reductions with multiple in-loop uses.
static LLVM_ABI_FOR_TEST std::unique_ptr< VPlan > buildVPlan0(Loop *TheLoop, LoopInfo &LI, Type *InductionTy, DebugLoc IVDL, PredicatedScalarEvolution &PSE, LoopVersioning *LVer=nullptr)
Create a base VPlan0, serving as the common starting point for all later candidates.
static LLVM_ABI_FOR_TEST void handleEarlyExits(VPlan &Plan, bool HasUncountableExit)
Update Plan to account for all early exits.
static void createInLoopReductionRecipes(VPlan &Plan, const DenseMap< VPBasicBlock *, VPValue * > &BlockMaskCache, const DenseSet< BasicBlock * > &BlocksNeedingPredication, ElementCount MinVF)
Create VPReductionRecipes for in-loop reductions.
static void addMinimumIterationCheck(VPlan &Plan, ElementCount VF, unsigned UF, ElementCount MinProfitableTripCount, bool RequiresScalarEpilogue, bool TailFolded, bool CheckNeededWithTailFolding, Loop *OrigLoop, const uint32_t *MinItersBypassWeights, DebugLoc DL, PredicatedScalarEvolution &PSE)
static void createHeaderPhiRecipes(VPlan &Plan, PredicatedScalarEvolution &PSE, Loop &OrigLoop, 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 bool handleMaxMinNumReductions(VPlan &Plan)
Check if Plan contains any FMaxNum or FMinNum reductions.
static LLVM_ABI_FOR_TEST void createLoopRegions(VPlan &Plan)
Replace loops in Plan's flat CFG with VPRegionBlocks, turning Plan's flat CFG into a hierarchical CFG...
static void attachCheckBlock(VPlan &Plan, Value *Cond, BasicBlock *CheckBlock, bool AddBranchWeights)
Wrap runtime check block CheckBlock in a VPIRBB and Cond in a VPValue and connect the block to Plan,...
static void handleUncountableEarlyExit(VPBasicBlock *EarlyExitingVPBB, VPBasicBlock *EarlyExitVPBB, VPlan &Plan, VPBasicBlock *HeaderVPBB, VPBasicBlock *LatchVPBB)
Update Plan to account for the uncountable early exit from EarlyExitingVPBB to EarlyExitVPBB by.
static void addMinimumVectorEpilogueIterationCheck(VPlan &Plan, Value *TripCount, Value *VectorTripCount, bool RequiresScalarEpilogue, ElementCount EpilogueVF, unsigned EpilogueUF, unsigned MainLoopStep, unsigned EpilogueLoopStep, ScalarEvolution &SE)
Add a check to Plan to see if the epilogue vector loop should be executed.
static LLVM_ABI_FOR_TEST void addMiddleCheck(VPlan &Plan, bool RequiresScalarEpilogueCheck, bool TailFolded)
If a check is needed to guard executing the scalar epilogue loop, it will be added to the middle bloc...