LLVM 24.0.0git
LoopIdiomVectorize.cpp
Go to the documentation of this file.
1//===-------- LoopIdiomVectorize.cpp - Loop idiom vectorization -----------===//
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// This pass implements a pass that recognizes certain loop idioms and
10// transforms them into more optimized versions of the same loop. In cases
11// where this happens, it can be a significant performance win.
12//
13// We currently support two loops:
14//
15// 1. A loop that finds the first mismatched byte in an array and returns the
16// index, i.e. something like:
17//
18// while (++i != n) {
19// if (a[i] != b[i])
20// break;
21// }
22//
23// In this example we can actually vectorize the loop despite the early exit,
24// although the loop vectorizer does not support it. It requires some extra
25// checks to deal with the possibility of faulting loads when crossing page
26// boundaries. However, even with these checks it is still profitable to do the
27// transformation.
28//
29// TODO List:
30//
31// * Add support for the inverse case where we scan for a matching element.
32// * Permit 64-bit induction variable types.
33// * Recognize loops that increment the IV *after* comparing bytes.
34// * Allow 32-bit sign-extends of the IV used by the GEP.
35//
36// 2. A loop that finds the first matching character in an array among a set of
37// possible matches, e.g.:
38//
39// for (; first != last; ++first)
40// for (s_it = s_first; s_it != s_last; ++s_it)
41// if (*first == *s_it)
42// return first;
43// return last;
44//
45// This corresponds to std::find_first_of (for arrays of bytes) from the C++
46// standard library. This function can be implemented efficiently for targets
47// that support @llvm.experimental.vector.match. For example, on AArch64 targets
48// that implement SVE2, this lower to a MATCH instruction, which enables us to
49// perform up to 16x16=256 comparisons in one go. This can lead to very
50// significant speedups.
51//
52// TODO:
53//
54// * Add support for `find_first_not_of' loops (i.e. with not-equal comparison).
55// * Make VF a configurable parameter (right now we assume 128-bit vectors).
56// * Potentially adjust the cost model to let the transformation kick-in even if
57// @llvm.experimental.vector.match doesn't have direct support in hardware.
58//
59//===----------------------------------------------------------------------===//
60//
61// NOTE: This Pass matches really specific loop patterns because it's only
62// supposed to be a temporary solution until our LoopVectorizer is powerful
63// enough to vectorize them automatically.
64//
65//===----------------------------------------------------------------------===//
66
72#include "llvm/IR/Dominators.h"
73#include "llvm/IR/IRBuilder.h"
74#include "llvm/IR/Intrinsics.h"
75#include "llvm/IR/MDBuilder.h"
79
80using namespace llvm;
81using namespace PatternMatch;
82
83#define DEBUG_TYPE "loop-idiom-vectorize"
84
85static cl::opt<bool> DisableAll("disable-loop-idiom-vectorize-all", cl::Hidden,
86 cl::init(false),
87 cl::desc("Disable Loop Idiom Vectorize Pass."));
88
90 LITVecStyle("loop-idiom-vectorize-style", cl::Hidden,
91 cl::desc("The vectorization style for loop idiom transform."),
93 "Use masked vector intrinsics"),
95 "predicated", "Use VP intrinsics")),
97
98static cl::opt<bool>
99 DisableByteCmp("disable-loop-idiom-vectorize-bytecmp", cl::Hidden,
100 cl::init(false),
101 cl::desc("Proceed with Loop Idiom Vectorize Pass, but do "
102 "not convert byte-compare loop(s)."));
103
105 ByteCmpVF("loop-idiom-vectorize-bytecmp-vf", cl::Hidden,
106 cl::desc("The vectorization factor for byte-compare patterns."),
107 cl::init(16));
108
109static cl::opt<bool>
110 DisableFindFirstByte("disable-loop-idiom-vectorize-find-first-byte",
111 cl::Hidden, cl::init(false),
112 cl::desc("Do not convert find-first-byte loop(s)."));
113
114static cl::opt<bool>
115 VerifyLoops("loop-idiom-vectorize-verify", cl::Hidden, cl::init(false),
116 cl::desc("Verify loops generated Loop Idiom Vectorize Pass."));
117
118namespace {
119class LoopIdiomVectorize {
120 LoopIdiomVectorizeStyle VectorizeStyle;
121 unsigned ByteCompareVF;
122 Loop *CurLoop = nullptr;
123 DominatorTree *DT;
124 LoopInfo *LI;
126 const DataLayout *DL;
127
128 /// Interface to emit optimization remarks.
130
131 // Blocks that will be used for inserting vectorized code.
132 BasicBlock *EndBlock = nullptr;
133 BasicBlock *VectorLoopPreheaderBlock = nullptr;
134 BasicBlock *VectorLoopStartBlock = nullptr;
135 BasicBlock *VectorLoopMismatchBlock = nullptr;
136 BasicBlock *VectorLoopIncBlock = nullptr;
137
138public:
139 LoopIdiomVectorize(LoopIdiomVectorizeStyle S, unsigned VF, DominatorTree *DT,
140 LoopInfo *LI, const TargetTransformInfo *TTI,
142 : VectorizeStyle(S), ByteCompareVF(VF), DT(DT), LI(LI), TTI(TTI), DL(DL),
143 ORE(ORE) {}
144
145 bool run(Loop *L);
146
147private:
148 /// \name Countable Loop Idiom Handling
149 /// @{
150
151 bool runOnLoopBlock(BasicBlock *BB, const SCEV *BECount,
152 SmallVectorImpl<BasicBlock *> &ExitBlocks);
153
154 bool recognizeByteCompare();
155
156 Value *expandFindMismatch(IRBuilder<> &Builder, DomTreeUpdater &DTU,
157 GetElementPtrInst *GEPA, GetElementPtrInst *GEPB,
158 Instruction *Index, Value *Start, Value *MaxLen);
159
160 Value *createMaskedFindMismatch(IRBuilder<> &Builder, DomTreeUpdater &DTU,
161 GetElementPtrInst *GEPA,
162 GetElementPtrInst *GEPB, Value *ExtStart,
163 Value *ExtEnd);
164 Value *createPredicatedFindMismatch(IRBuilder<> &Builder, DomTreeUpdater &DTU,
165 GetElementPtrInst *GEPA,
166 GetElementPtrInst *GEPB, Value *ExtStart,
167 Value *ExtEnd);
168
169 void transformByteCompare(GetElementPtrInst *GEPA, GetElementPtrInst *GEPB,
170 PHINode *IndPhi, Value *MaxLen, Instruction *Index,
171 Value *Start, bool IncIdx, BasicBlock *FoundBB,
172 BasicBlock *EndBB);
173
174 bool recognizeFindFirstByte();
175
176 Value *expandFindFirstByte(IRBuilder<> &Builder, DomTreeUpdater &DTU,
177 unsigned VF, Type *CharTy, Value *IndPhi,
178 BasicBlock *ExitSucc, BasicBlock *ExitFail,
179 Value *SearchStart, Value *SearchEnd,
180 Value *NeedleStart, Value *NeedleEnd);
181
182 void transformFindFirstByte(PHINode *IndPhi, unsigned VF, Type *CharTy,
183 BasicBlock *ExitSucc, BasicBlock *ExitFail,
184 Value *SearchStart, Value *SearchEnd,
185 Value *NeedleStart, Value *NeedleEnd);
186 /// @}
187};
188} // anonymous namespace
189
192 LPMUpdater &) {
193 if (DisableAll)
194 return PreservedAnalyses::all();
195
196 const auto *DL = &L.getHeader()->getDataLayout();
197
198 LoopIdiomVectorizeStyle VecStyle = VectorizeStyle;
199 if (LITVecStyle.getNumOccurrences())
200 VecStyle = LITVecStyle;
201
202 unsigned BCVF = ByteCompareVF;
203 if (ByteCmpVF.getNumOccurrences())
204 BCVF = ByteCmpVF;
205
206 Function &F = *L.getHeader()->getParent();
207 auto &FAMP = AM.getResult<FunctionAnalysisManagerLoopProxy>(L, AR);
208 auto *ORE = FAMP.getCachedResult<OptimizationRemarkEmitterAnalysis>(F);
209
210 std::optional<OptimizationRemarkEmitter> ORELocal;
211 if (!ORE) {
212 ORELocal.emplace(&F);
213 ORE = &*ORELocal;
214 }
215
216 LoopIdiomVectorize LIV(VecStyle, BCVF, &AR.DT, &AR.LI, &AR.TTI, DL, *ORE);
217 if (!LIV.run(&L))
218 return PreservedAnalyses::all();
219
221}
222
223//===----------------------------------------------------------------------===//
224//
225// Implementation of LoopIdiomVectorize
226//
227//===----------------------------------------------------------------------===//
228
229bool LoopIdiomVectorize::run(Loop *L) {
230 CurLoop = L;
231
232 Function &F = *L->getHeader()->getParent();
233 if (DisableAll || F.hasOptSize())
234 return false;
235
236 // Bail if vectorization is disabled on loop.
237 LoopVectorizeHints Hints(L, /*InterleaveOnlyWhenForced=*/true, ORE);
238 if (!Hints.allowVectorization(&F, L, /*VectorizeOnlyWhenForced=*/false)) {
239 LLVM_DEBUG(dbgs() << DEBUG_TYPE << " is disabled on " << L->getName()
240 << " due to vectorization hints\n");
241 return false;
242 }
243
244 if (F.hasFnAttribute(Attribute::NoImplicitFloat)) {
245 LLVM_DEBUG(dbgs() << DEBUG_TYPE << " is disabled on " << F.getName()
246 << " due to its NoImplicitFloat attribute");
247 return false;
248 }
249
250 // If the loop could not be converted to canonical form, it must have an
251 // indirectbr in it, just give up.
252 if (!L->getLoopPreheader())
253 return false;
254
255 LLVM_DEBUG(dbgs() << DEBUG_TYPE " Scanning: F[" << F.getName() << "] Loop %"
256 << CurLoop->getHeader()->getName() << "\n");
257
258 if (recognizeByteCompare())
259 return true;
260
261 if (recognizeFindFirstByte())
262 return true;
263
264 return false;
265}
266
267static void fixSuccessorPhis(Loop *L, Value *ScalarRes, Value *VectorRes,
268 BasicBlock *SuccBB, BasicBlock *IncBB) {
269 for (PHINode &PN : SuccBB->phis()) {
270 // Look through the incoming values to find ScalarRes, meaning this is a
271 // PHI collecting the results of the transformation.
272 bool ResPhi = false;
273 for (Value *Op : PN.incoming_values())
274 if (Op == ScalarRes) {
275 ResPhi = true;
276 break;
277 }
278
279 // Any PHI that depended upon the result of the transformation needs a new
280 // incoming value from IncBB.
281 if (ResPhi)
282 PN.addIncoming(VectorRes, IncBB);
283 else {
284 // There should be no other outside uses of other values in the
285 // original loop. Any incoming values should either:
286 // 1. Be for blocks outside the loop, which aren't interesting. Or ..
287 // 2. These are from blocks in the loop with values defined outside
288 // the loop. We should a similar incoming value from CmpBB.
289 for (BasicBlock *BB : PN.blocks())
290 if (L->contains(BB)) {
291 PN.addIncoming(PN.getIncomingValueForBlock(BB), IncBB);
292 break;
293 }
294 }
295 }
296}
297
298bool LoopIdiomVectorize::recognizeByteCompare() {
299 // Currently the transformation only works on scalable vector types, although
300 // there is no fundamental reason why it cannot be made to work for fixed
301 // width too.
302
303 // We also need to know the minimum page size for the target in order to
304 // generate runtime memory checks to ensure the vector version won't fault.
305 if (!TTI->supportsScalableVectors() || !TTI->getMinPageSize().has_value() ||
307 return false;
308
309 BasicBlock *Header = CurLoop->getHeader();
310
311 // In LoopIdiomVectorize::run we have already checked that the loop
312 // has a preheader so we can assume it's in a canonical form.
313 if (CurLoop->getNumBackEdges() != 1 || CurLoop->getNumBlocks() != 2)
314 return false;
315
316 PHINode *PN = dyn_cast<PHINode>(&Header->front());
317 if (!PN || PN->getNumIncomingValues() != 2)
318 return false;
319
320 auto LoopBlocks = CurLoop->getBlocks();
321 // The first block in the loop should contain only 4 instructions, e.g.
322 //
323 // while.cond:
324 // %res.phi = phi i32 [ %start, %ph ], [ %inc, %while.body ]
325 // %inc = add i32 %res.phi, 1
326 // %cmp.not = icmp eq i32 %inc, %n
327 // br i1 %cmp.not, label %while.end, label %while.body
328 //
329 if (LoopBlocks[0]->size() > 4)
330 return false;
331
332 // The second block should contain 7 instructions, e.g.
333 //
334 // while.body:
335 // %idx = zext i32 %inc to i64
336 // %idx.a = getelementptr inbounds i8, ptr %a, i64 %idx
337 // %load.a = load i8, ptr %idx.a
338 // %idx.b = getelementptr inbounds i8, ptr %b, i64 %idx
339 // %load.b = load i8, ptr %idx.b
340 // %cmp.not.ld = icmp eq i8 %load.a, %load.b
341 // br i1 %cmp.not.ld, label %while.cond, label %while.end
342 //
343 if (LoopBlocks[1]->size() > 7)
344 return false;
345
346 // The incoming value to the PHI node from the loop should be an add of 1.
347 Value *StartIdx = nullptr;
348 Instruction *Index = nullptr;
349 if (!CurLoop->contains(PN->getIncomingBlock(0))) {
350 StartIdx = PN->getIncomingValue(0);
352 } else {
353 StartIdx = PN->getIncomingValue(1);
355 }
356
357 // Limit to 32-bit types for now
358 if (!Index || !Index->getType()->isIntegerTy(32) ||
359 !match(Index, m_c_Add(m_Specific(PN), m_One())))
360 return false;
361
362 // If we match the pattern, PN and Index will be replaced with the result of
363 // the cttz.elts intrinsic. If any other instructions are used outside of
364 // the loop, we cannot replace it.
365 for (BasicBlock *BB : LoopBlocks)
366 for (Instruction &I : *BB)
367 if (&I != PN && &I != Index)
368 for (User *U : I.users())
369 if (!CurLoop->contains(cast<Instruction>(U)))
370 return false;
371
372 // Match the branch instruction for the header
373 Value *MaxLen;
374 BasicBlock *EndBB, *WhileBB;
375 if (!match(Header->getTerminator(),
377 m_Value(MaxLen)),
378 m_BasicBlock(EndBB), m_BasicBlock(WhileBB))) ||
379 !CurLoop->contains(WhileBB))
380 return false;
381
382 // WhileBB should contain the pattern of load & compare instructions. Match
383 // the pattern and find the GEP instructions used by the loads.
384 BasicBlock *FoundBB;
385 BasicBlock *TrueBB;
386 Value *LoadA, *LoadB;
387 if (!match(WhileBB->getTerminator(),
389 m_Value(LoadB)),
390 m_BasicBlock(TrueBB), m_BasicBlock(FoundBB))) ||
391 !CurLoop->contains(TrueBB))
392 return false;
393
394 Value *A, *B;
395 if (!match(LoadA, m_Load(m_Value(A))) || !match(LoadB, m_Load(m_Value(B))))
396 return false;
397
398 LoadInst *LoadAI = cast<LoadInst>(LoadA);
399 LoadInst *LoadBI = cast<LoadInst>(LoadB);
400 if (!LoadAI->isSimple() || !LoadBI->isSimple())
401 return false;
402
405
406 if (!GEPA || !GEPB)
407 return false;
408
409 Value *PtrA = GEPA->getPointerOperand();
410 Value *PtrB = GEPB->getPointerOperand();
411
412 // Check we are loading i8 values from two loop invariant pointers
413 if (!CurLoop->isLoopInvariant(PtrA) || !CurLoop->isLoopInvariant(PtrB) ||
414 !GEPA->getResultElementType()->isIntegerTy(8) ||
415 !GEPB->getResultElementType()->isIntegerTy(8) ||
416 !LoadAI->getType()->isIntegerTy(8) ||
417 !LoadBI->getType()->isIntegerTy(8) || PtrA == PtrB)
418 return false;
419
420 // Check that the index to the GEPs is the index we found earlier
421 if (GEPA->getNumIndices() > 1 || GEPB->getNumIndices() > 1)
422 return false;
423
424 Value *IdxA = GEPA->getOperand(GEPA->getNumIndices());
425 Value *IdxB = GEPB->getOperand(GEPB->getNumIndices());
426 if (IdxA != IdxB || !match(IdxA, m_ZExt(m_Specific(Index))))
427 return false;
428
429 // We only ever expect the pre-incremented index value to be used inside the
430 // loop.
431 if (!PN->hasOneUse())
432 return false;
433
434 // Ensure that when the Found and End blocks are identical the PHIs have the
435 // supported format. We don't currently allow cases like this:
436 // while.cond:
437 // ...
438 // br i1 %cmp.not, label %while.end, label %while.body
439 //
440 // while.body:
441 // ...
442 // br i1 %cmp.not2, label %while.cond, label %while.end
443 //
444 // while.end:
445 // %final_ptr = phi ptr [ %c, %while.body ], [ %d, %while.cond ]
446 //
447 // Where the incoming values for %final_ptr are unique and from each of the
448 // loop blocks, but not actually defined in the loop. This requires extra
449 // work setting up the byte.compare block, i.e. by introducing a select to
450 // choose the correct value.
451 // TODO: We could add support for this in future.
452 if (FoundBB == EndBB) {
453 for (PHINode &EndPN : EndBB->phis()) {
454 Value *WhileCondVal = EndPN.getIncomingValueForBlock(Header);
455 Value *WhileBodyVal = EndPN.getIncomingValueForBlock(WhileBB);
456
457 // The value of the index when leaving the while.cond block is always the
458 // same as the end value (MaxLen) so we permit either. The value when
459 // leaving the while.body block should only be the index. Otherwise for
460 // any other values we only allow ones that are same for both blocks.
461 if (WhileCondVal != WhileBodyVal &&
462 ((WhileCondVal != Index && WhileCondVal != MaxLen) ||
463 (WhileBodyVal != Index)))
464 return false;
465 }
466 }
467
468 LLVM_DEBUG(dbgs() << "FOUND IDIOM IN LOOP: \n"
469 << *(EndBB->getParent()) << "\n\n");
470
471 // The index is incremented before the GEP/Load pair so we need to
472 // add 1 to the start value.
473 transformByteCompare(GEPA, GEPB, PN, MaxLen, Index, StartIdx, /*IncIdx=*/true,
474 FoundBB, EndBB);
475 return true;
476}
477
478Value *LoopIdiomVectorize::createMaskedFindMismatch(
479 IRBuilder<> &Builder, DomTreeUpdater &DTU, GetElementPtrInst *GEPA,
480 GetElementPtrInst *GEPB, Value *ExtStart, Value *ExtEnd) {
481 Type *I64Type = Builder.getInt64Ty();
482 Type *ResType = Builder.getInt32Ty();
483 Type *LoadType = Builder.getInt8Ty();
484 Value *PtrA = GEPA->getPointerOperand();
485 Value *PtrB = GEPB->getPointerOperand();
486
487 ScalableVectorType *PredVTy =
488 ScalableVectorType::get(Builder.getInt1Ty(), ByteCompareVF);
489
490 Value *InitialPred = Builder.CreateIntrinsic(
491 Intrinsic::get_active_lane_mask, {PredVTy, I64Type}, {ExtStart, ExtEnd});
492
493 Value *VecLen = Builder.CreateVScale(I64Type);
494 VecLen =
495 Builder.CreateMul(VecLen, ConstantInt::get(I64Type, ByteCompareVF), "",
496 /*HasNUW=*/true, /*HasNSW=*/true);
497
498 Value *PFalse = Builder.CreateVectorSplat(PredVTy->getElementCount(),
499 Builder.getInt1(false));
500
501 Builder.CreateBr(VectorLoopStartBlock);
502
503 DTU.applyUpdates({{DominatorTree::Insert, VectorLoopPreheaderBlock,
504 VectorLoopStartBlock}});
505
506 // Set up the first vector loop block by creating the PHIs, doing the vector
507 // loads and comparing the vectors.
508 Builder.SetInsertPoint(VectorLoopStartBlock);
509 PHINode *LoopPred = Builder.CreatePHI(PredVTy, 2, "mismatch_vec_loop_pred");
510 LoopPred->addIncoming(InitialPred, VectorLoopPreheaderBlock);
511 PHINode *VectorIndexPhi = Builder.CreatePHI(I64Type, 2, "mismatch_vec_index");
512 VectorIndexPhi->addIncoming(ExtStart, VectorLoopPreheaderBlock);
513 Type *VectorLoadType =
514 ScalableVectorType::get(Builder.getInt8Ty(), ByteCompareVF);
515 Value *Passthru = ConstantInt::getNullValue(VectorLoadType);
516
517 Value *VectorLhsGep =
518 Builder.CreateGEP(LoadType, PtrA, VectorIndexPhi, "", GEPA->isInBounds());
519 Value *VectorLhsLoad = Builder.CreateMaskedLoad(VectorLoadType, VectorLhsGep,
520 Align(1), LoopPred, Passthru);
521
522 Value *VectorRhsGep =
523 Builder.CreateGEP(LoadType, PtrB, VectorIndexPhi, "", GEPB->isInBounds());
524 Value *VectorRhsLoad = Builder.CreateMaskedLoad(VectorLoadType, VectorRhsGep,
525 Align(1), LoopPred, Passthru);
526
527 Value *VectorMatchCmp = Builder.CreateICmpNE(VectorLhsLoad, VectorRhsLoad);
528 VectorMatchCmp = Builder.CreateSelect(LoopPred, VectorMatchCmp, PFalse);
529 Value *VectorMatchHasActiveLanes = Builder.CreateOrReduce(VectorMatchCmp);
530 Builder.CreateCondBr(VectorMatchHasActiveLanes, VectorLoopMismatchBlock,
531 VectorLoopIncBlock);
532
533 DTU.applyUpdates(
534 {{DominatorTree::Insert, VectorLoopStartBlock, VectorLoopMismatchBlock},
535 {DominatorTree::Insert, VectorLoopStartBlock, VectorLoopIncBlock}});
536
537 // Increment the index counter and calculate the predicate for the next
538 // iteration of the loop. We branch back to the start of the loop if there
539 // is at least one active lane.
540 Builder.SetInsertPoint(VectorLoopIncBlock);
541 Value *NewVectorIndexPhi =
542 Builder.CreateAdd(VectorIndexPhi, VecLen, "",
543 /*HasNUW=*/true, /*HasNSW=*/true);
544 VectorIndexPhi->addIncoming(NewVectorIndexPhi, VectorLoopIncBlock);
545 Value *NewPred =
546 Builder.CreateIntrinsic(Intrinsic::get_active_lane_mask,
547 {PredVTy, I64Type}, {NewVectorIndexPhi, ExtEnd});
548 LoopPred->addIncoming(NewPred, VectorLoopIncBlock);
549
550 Value *PredHasActiveLanes =
551 Builder.CreateExtractElement(NewPred, uint64_t(0));
552 Builder.CreateCondBr(PredHasActiveLanes, VectorLoopStartBlock, EndBlock);
553
554 DTU.applyUpdates(
555 {{DominatorTree::Insert, VectorLoopIncBlock, VectorLoopStartBlock},
556 {DominatorTree::Insert, VectorLoopIncBlock, EndBlock}});
557
558 // If we found a mismatch then we need to calculate which lane in the vector
559 // had a mismatch and add that on to the current loop index.
560 Builder.SetInsertPoint(VectorLoopMismatchBlock);
561 PHINode *FoundPred = Builder.CreatePHI(PredVTy, 1, "mismatch_vec_found_pred");
562 FoundPred->addIncoming(VectorMatchCmp, VectorLoopStartBlock);
563 PHINode *LastLoopPred =
564 Builder.CreatePHI(PredVTy, 1, "mismatch_vec_last_loop_pred");
565 LastLoopPred->addIncoming(LoopPred, VectorLoopStartBlock);
566 PHINode *VectorFoundIndex =
567 Builder.CreatePHI(I64Type, 1, "mismatch_vec_found_index");
568 VectorFoundIndex->addIncoming(VectorIndexPhi, VectorLoopStartBlock);
569
570 Value *PredMatchCmp = Builder.CreateAnd(LastLoopPred, FoundPred);
571 Value *Ctz = Builder.CreateCountTrailingZeroElems(ResType, PredMatchCmp);
572 Ctz = Builder.CreateZExt(Ctz, I64Type);
573 Value *VectorLoopRes64 = Builder.CreateAdd(VectorFoundIndex, Ctz, "",
574 /*HasNUW=*/true, /*HasNSW=*/true);
575 return Builder.CreateTrunc(VectorLoopRes64, ResType);
576}
577
578Value *LoopIdiomVectorize::createPredicatedFindMismatch(
579 IRBuilder<> &Builder, DomTreeUpdater &DTU, GetElementPtrInst *GEPA,
580 GetElementPtrInst *GEPB, Value *ExtStart, Value *ExtEnd) {
581 Type *I64Type = Builder.getInt64Ty();
582 Type *I32Type = Builder.getInt32Ty();
583 Type *ResType = I32Type;
584 Type *LoadType = Builder.getInt8Ty();
585 Value *PtrA = GEPA->getPointerOperand();
586 Value *PtrB = GEPB->getPointerOperand();
587
588 auto *JumpToVectorLoop = UncondBrInst::Create(VectorLoopStartBlock);
589 Builder.Insert(JumpToVectorLoop);
590
591 DTU.applyUpdates({{DominatorTree::Insert, VectorLoopPreheaderBlock,
592 VectorLoopStartBlock}});
593
594 // Set up the first Vector loop block by creating the PHIs, doing the vector
595 // loads and comparing the vectors.
596 Builder.SetInsertPoint(VectorLoopStartBlock);
597 auto *VectorIndexPhi = Builder.CreatePHI(I64Type, 2, "mismatch_vector_index");
598 VectorIndexPhi->addIncoming(ExtStart, VectorLoopPreheaderBlock);
599
600 // Calculate AVL by subtracting the vector loop index from the trip count
601 Value *AVL = Builder.CreateSub(ExtEnd, VectorIndexPhi, "avl", /*HasNUW=*/true,
602 /*HasNSW=*/true);
603
604 auto *VectorLoadType = ScalableVectorType::get(LoadType, ByteCompareVF);
605 auto *VF = ConstantInt::get(I32Type, ByteCompareVF);
606
607 Value *VL = Builder.CreateIntrinsic(Intrinsic::experimental_get_vector_length,
608 {I64Type}, {AVL, VF, Builder.getTrue()});
609 Value *GepOffset = VectorIndexPhi;
610
611 Value *VectorLhsGep =
612 Builder.CreateGEP(LoadType, PtrA, GepOffset, "", GEPA->isInBounds());
613 VectorType *TrueMaskTy =
614 VectorType::get(Builder.getInt1Ty(), VectorLoadType->getElementCount());
615 Value *AllTrueMask = Constant::getAllOnesValue(TrueMaskTy);
616 Value *VectorLhsLoad = Builder.CreateIntrinsic(
617 Intrinsic::vp_load, {VectorLoadType, VectorLhsGep->getType()},
618 {VectorLhsGep, AllTrueMask, VL}, nullptr, "lhs.load");
619
620 Value *VectorRhsGep =
621 Builder.CreateGEP(LoadType, PtrB, GepOffset, "", GEPB->isInBounds());
622 Value *VectorRhsLoad = Builder.CreateIntrinsic(
623 Intrinsic::vp_load, {VectorLoadType, VectorLhsGep->getType()},
624 {VectorRhsGep, AllTrueMask, VL}, nullptr, "rhs.load");
625
626 Value *VectorMatchCmp =
627 Builder.CreateICmpNE(VectorLhsLoad, VectorRhsLoad, "mismatch.cmp");
628 Value *CTZ = Builder.CreateIntrinsic(
629 Intrinsic::vp_cttz_elts, {ResType, VectorMatchCmp->getType()},
630 {VectorMatchCmp, /*ZeroIsPoison=*/Builder.getInt1(false), AllTrueMask,
631 VL});
632 Value *MismatchFound = Builder.CreateICmpNE(CTZ, VL);
633 auto *VectorEarlyExit = CondBrInst::Create(
634 MismatchFound, VectorLoopMismatchBlock, VectorLoopIncBlock);
635 Builder.Insert(VectorEarlyExit);
636
637 DTU.applyUpdates(
638 {{DominatorTree::Insert, VectorLoopStartBlock, VectorLoopMismatchBlock},
639 {DominatorTree::Insert, VectorLoopStartBlock, VectorLoopIncBlock}});
640
641 // Increment the index counter and calculate the predicate for the next
642 // iteration of the loop. We branch back to the start of the loop if there
643 // is at least one active lane.
644 Builder.SetInsertPoint(VectorLoopIncBlock);
645 Value *VL64 = Builder.CreateZExt(VL, I64Type);
646 Value *NewVectorIndexPhi =
647 Builder.CreateAdd(VectorIndexPhi, VL64, "",
648 /*HasNUW=*/true, /*HasNSW=*/true);
649 VectorIndexPhi->addIncoming(NewVectorIndexPhi, VectorLoopIncBlock);
650 Value *ExitCond = Builder.CreateICmpNE(NewVectorIndexPhi, ExtEnd);
651 auto *VectorLoopBranchBack =
652 CondBrInst::Create(ExitCond, VectorLoopStartBlock, EndBlock);
653 Builder.Insert(VectorLoopBranchBack);
654
655 DTU.applyUpdates(
656 {{DominatorTree::Insert, VectorLoopIncBlock, VectorLoopStartBlock},
657 {DominatorTree::Insert, VectorLoopIncBlock, EndBlock}});
658
659 // If we found a mismatch then we need to calculate which lane in the vector
660 // had a mismatch and add that on to the current loop index.
661 Builder.SetInsertPoint(VectorLoopMismatchBlock);
662
663 // Add LCSSA phis for CTZ and VectorIndexPhi.
664 auto *CTZLCSSAPhi = Builder.CreatePHI(CTZ->getType(), 1, "ctz");
665 CTZLCSSAPhi->addIncoming(CTZ, VectorLoopStartBlock);
666 auto *VectorIndexLCSSAPhi =
667 Builder.CreatePHI(VectorIndexPhi->getType(), 1, "mismatch_vector_index");
668 VectorIndexLCSSAPhi->addIncoming(VectorIndexPhi, VectorLoopStartBlock);
669
670 Value *CTZI64 = Builder.CreateZExt(CTZLCSSAPhi, I64Type);
671 Value *VectorLoopRes64 = Builder.CreateAdd(VectorIndexLCSSAPhi, CTZI64, "",
672 /*HasNUW=*/true, /*HasNSW=*/true);
673 return Builder.CreateTrunc(VectorLoopRes64, ResType);
674}
675
676Value *LoopIdiomVectorize::expandFindMismatch(
677 IRBuilder<> &Builder, DomTreeUpdater &DTU, GetElementPtrInst *GEPA,
678 GetElementPtrInst *GEPB, Instruction *Index, Value *Start, Value *MaxLen) {
679 Value *PtrA = GEPA->getPointerOperand();
680 Value *PtrB = GEPB->getPointerOperand();
681
682 // Get the arguments and types for the intrinsic.
683 BasicBlock *Preheader = CurLoop->getLoopPreheader();
684 Instruction *PHBranch = Preheader->getTerminator();
685 LLVMContext &Ctx = PHBranch->getContext();
686 Type *LoadType = Type::getInt8Ty(Ctx);
687 Type *ResType = Builder.getInt32Ty();
688
689 // Split block in the original loop preheader.
690 EndBlock = SplitBlock(Preheader, PHBranch, DT, LI, nullptr, "mismatch_end");
691
692 // Create the blocks that we're going to need:
693 // 1. A block for checking the zero-extended length exceeds 0
694 // 2. A block to check that the start and end addresses of a given array
695 // lie on the same page.
696 // 3. The vector loop preheader.
697 // 4. The first vector loop block.
698 // 5. The vector loop increment block.
699 // 6. A block we can jump to from the vector loop when a mismatch is found.
700 // 7. The first block of the scalar loop itself, containing PHIs , loads
701 // and cmp.
702 // 8. A scalar loop increment block to increment the PHIs and go back
703 // around the loop.
704
705 BasicBlock *MinItCheckBlock = BasicBlock::Create(
706 Ctx, "mismatch_min_it_check", EndBlock->getParent(), EndBlock);
707
708 // Update the terminator added by SplitBlock to branch to the first block
709 Preheader->getTerminator()->setSuccessor(0, MinItCheckBlock);
710
711 BasicBlock *MemCheckBlock = BasicBlock::Create(
712 Ctx, "mismatch_mem_check", EndBlock->getParent(), EndBlock);
713
714 VectorLoopPreheaderBlock = BasicBlock::Create(
715 Ctx, "mismatch_vec_loop_preheader", EndBlock->getParent(), EndBlock);
716
717 VectorLoopStartBlock = BasicBlock::Create(Ctx, "mismatch_vec_loop",
718 EndBlock->getParent(), EndBlock);
719
720 VectorLoopIncBlock = BasicBlock::Create(Ctx, "mismatch_vec_loop_inc",
721 EndBlock->getParent(), EndBlock);
722
723 VectorLoopMismatchBlock = BasicBlock::Create(Ctx, "mismatch_vec_loop_found",
724 EndBlock->getParent(), EndBlock);
725
726 BasicBlock *LoopPreHeaderBlock = BasicBlock::Create(
727 Ctx, "mismatch_loop_pre", EndBlock->getParent(), EndBlock);
728
729 BasicBlock *LoopStartBlock =
730 BasicBlock::Create(Ctx, "mismatch_loop", EndBlock->getParent(), EndBlock);
731
732 BasicBlock *LoopIncBlock = BasicBlock::Create(
733 Ctx, "mismatch_loop_inc", EndBlock->getParent(), EndBlock);
734
735 DTU.applyUpdates({{DominatorTree::Insert, Preheader, MinItCheckBlock},
736 {DominatorTree::Delete, Preheader, EndBlock}});
737
738 // Update LoopInfo with the new vector & scalar loops.
739 auto VectorLoop = LI->AllocateLoop();
740 auto ScalarLoop = LI->AllocateLoop();
741
742 if (CurLoop->getParentLoop()) {
743 CurLoop->getParentLoop()->addBasicBlockToLoop(MinItCheckBlock, *LI);
744 CurLoop->getParentLoop()->addBasicBlockToLoop(MemCheckBlock, *LI);
745 CurLoop->getParentLoop()->addBasicBlockToLoop(VectorLoopPreheaderBlock,
746 *LI);
747 CurLoop->getParentLoop()->addChildLoop(VectorLoop);
748 CurLoop->getParentLoop()->addBasicBlockToLoop(VectorLoopMismatchBlock, *LI);
749 CurLoop->getParentLoop()->addBasicBlockToLoop(LoopPreHeaderBlock, *LI);
750 CurLoop->getParentLoop()->addChildLoop(ScalarLoop);
751 } else {
752 LI->addTopLevelLoop(VectorLoop);
753 LI->addTopLevelLoop(ScalarLoop);
754 }
755
756 // Add the new basic blocks to their associated loops.
757 VectorLoop->addBasicBlockToLoop(VectorLoopStartBlock, *LI);
758 VectorLoop->addBasicBlockToLoop(VectorLoopIncBlock, *LI);
759
760 ScalarLoop->addBasicBlockToLoop(LoopStartBlock, *LI);
761 ScalarLoop->addBasicBlockToLoop(LoopIncBlock, *LI);
762
763 // Set up some types and constants that we intend to reuse.
764 Type *I64Type = Builder.getInt64Ty();
765
766 // Check the zero-extended iteration count > 0
767 Builder.SetInsertPoint(MinItCheckBlock);
768 Value *ExtStart = Builder.CreateZExt(Start, I64Type);
769 Value *ExtEnd = Builder.CreateZExt(MaxLen, I64Type);
770 // This check doesn't really cost us very much.
771
772 Value *LimitCheck = Builder.CreateICmpULE(Start, MaxLen);
773 CondBrInst *MinItCheckBr =
774 CondBrInst::Create(LimitCheck, MemCheckBlock, LoopPreHeaderBlock);
775 MinItCheckBr->setMetadata(
776 LLVMContext::MD_prof,
777 MDBuilder(MinItCheckBr->getContext()).createBranchWeights(99, 1));
778 Builder.Insert(MinItCheckBr);
779
780 DTU.applyUpdates(
781 {{DominatorTree::Insert, MinItCheckBlock, MemCheckBlock},
782 {DominatorTree::Insert, MinItCheckBlock, LoopPreHeaderBlock}});
783
784 // For each of the arrays, check the start/end addresses are on the same
785 // page.
786 Builder.SetInsertPoint(MemCheckBlock);
787
788 // The early exit in the original loop means that when performing vector
789 // loads we are potentially reading ahead of the early exit. So we could
790 // fault if crossing a page boundary. Therefore, we create runtime memory
791 // checks based on the minimum page size as follows:
792 // 1. Calculate the addresses of the first memory accesses in the loop,
793 // i.e. LhsStart and RhsStart.
794 // 2. Get the last accessed addresses in the loop, i.e. LhsEnd and RhsEnd.
795 // 3. Determine which pages correspond to all the memory accesses, i.e
796 // LhsStartPage, LhsEndPage, RhsStartPage, RhsEndPage.
797 // 4. If LhsStartPage == LhsEndPage and RhsStartPage == RhsEndPage, then
798 // we know we won't cross any page boundaries in the loop so we can
799 // enter the vector loop! Otherwise we fall back on the scalar loop.
800 Value *LhsStartGEP = Builder.CreateGEP(LoadType, PtrA, ExtStart);
801 Value *RhsStartGEP = Builder.CreateGEP(LoadType, PtrB, ExtStart);
802 Value *RhsStart = Builder.CreatePtrToInt(RhsStartGEP, I64Type);
803 Value *LhsStart = Builder.CreatePtrToInt(LhsStartGEP, I64Type);
804 Value *LhsEndGEP = Builder.CreateGEP(LoadType, PtrA, ExtEnd);
805 Value *RhsEndGEP = Builder.CreateGEP(LoadType, PtrB, ExtEnd);
806 Value *LhsEnd = Builder.CreatePtrToInt(LhsEndGEP, I64Type);
807 Value *RhsEnd = Builder.CreatePtrToInt(RhsEndGEP, I64Type);
808
809 const uint64_t MinPageSize = TTI->getMinPageSize().value();
810 const uint64_t AddrShiftAmt = llvm::Log2_64(MinPageSize);
811 Value *LhsStartPage = Builder.CreateLShr(LhsStart, AddrShiftAmt);
812 Value *LhsEndPage = Builder.CreateLShr(LhsEnd, AddrShiftAmt);
813 Value *RhsStartPage = Builder.CreateLShr(RhsStart, AddrShiftAmt);
814 Value *RhsEndPage = Builder.CreateLShr(RhsEnd, AddrShiftAmt);
815 Value *LhsPageCmp = Builder.CreateICmpNE(LhsStartPage, LhsEndPage);
816 Value *RhsPageCmp = Builder.CreateICmpNE(RhsStartPage, RhsEndPage);
817
818 Value *CombinedPageCmp = Builder.CreateOr(LhsPageCmp, RhsPageCmp);
819 CondBrInst *CombinedPageCmpCmpBr = CondBrInst::Create(
820 CombinedPageCmp, LoopPreHeaderBlock, VectorLoopPreheaderBlock);
821 CombinedPageCmpCmpBr->setMetadata(
822 LLVMContext::MD_prof, MDBuilder(CombinedPageCmpCmpBr->getContext())
823 .createBranchWeights(10, 90));
824 Builder.Insert(CombinedPageCmpCmpBr);
825
826 DTU.applyUpdates(
827 {{DominatorTree::Insert, MemCheckBlock, LoopPreHeaderBlock},
828 {DominatorTree::Insert, MemCheckBlock, VectorLoopPreheaderBlock}});
829
830 // Set up the vector loop preheader, i.e. calculate initial loop predicate,
831 // zero-extend MaxLen to 64-bits, determine the number of vector elements
832 // processed in each iteration, etc.
833 Builder.SetInsertPoint(VectorLoopPreheaderBlock);
834
835 // At this point we know two things must be true:
836 // 1. Start <= End
837 // 2. ExtMaxLen <= MinPageSize due to the page checks.
838 // Therefore, we know that we can use a 64-bit induction variable that
839 // starts from 0 -> ExtMaxLen and it will not overflow.
840 Value *VectorLoopRes = nullptr;
841 switch (VectorizeStyle) {
843 VectorLoopRes =
844 createMaskedFindMismatch(Builder, DTU, GEPA, GEPB, ExtStart, ExtEnd);
845 break;
847 VectorLoopRes = createPredicatedFindMismatch(Builder, DTU, GEPA, GEPB,
848 ExtStart, ExtEnd);
849 break;
850 }
851
852 Builder.CreateBr(EndBlock);
853
854 DTU.applyUpdates(
855 {{DominatorTree::Insert, VectorLoopMismatchBlock, EndBlock}});
856
857 // Generate code for scalar loop.
858 Builder.SetInsertPoint(LoopPreHeaderBlock);
859 Builder.CreateBr(LoopStartBlock);
860
861 DTU.applyUpdates(
862 {{DominatorTree::Insert, LoopPreHeaderBlock, LoopStartBlock}});
863
864 Builder.SetInsertPoint(LoopStartBlock);
865 PHINode *IndexPhi = Builder.CreatePHI(ResType, 2, "mismatch_index");
866 IndexPhi->addIncoming(Start, LoopPreHeaderBlock);
867
868 // Otherwise compare the values
869 // Load bytes from each array and compare them.
870 Value *GepOffset = Builder.CreateZExt(IndexPhi, I64Type);
871
872 Value *LhsGep =
873 Builder.CreateGEP(LoadType, PtrA, GepOffset, "", GEPA->isInBounds());
874 Value *LhsLoad = Builder.CreateLoad(LoadType, LhsGep);
875
876 Value *RhsGep =
877 Builder.CreateGEP(LoadType, PtrB, GepOffset, "", GEPB->isInBounds());
878 Value *RhsLoad = Builder.CreateLoad(LoadType, RhsGep);
879
880 Value *MatchCmp = Builder.CreateICmpEQ(LhsLoad, RhsLoad);
881 // If we have a mismatch then exit the loop ...
882 Builder.CreateCondBr(MatchCmp, LoopIncBlock, EndBlock);
883
884 DTU.applyUpdates({{DominatorTree::Insert, LoopStartBlock, LoopIncBlock},
885 {DominatorTree::Insert, LoopStartBlock, EndBlock}});
886
887 // Have we reached the maximum permitted length for the loop?
888 Builder.SetInsertPoint(LoopIncBlock);
889 Value *PhiInc = Builder.CreateAdd(IndexPhi, ConstantInt::get(ResType, 1), "",
890 /*HasNUW=*/Index->hasNoUnsignedWrap(),
891 /*HasNSW=*/Index->hasNoSignedWrap());
892 IndexPhi->addIncoming(PhiInc, LoopIncBlock);
893 Value *IVCmp = Builder.CreateICmpEQ(PhiInc, MaxLen);
894 Builder.CreateCondBr(IVCmp, EndBlock, LoopStartBlock);
895
896 DTU.applyUpdates({{DominatorTree::Insert, LoopIncBlock, EndBlock},
897 {DominatorTree::Insert, LoopIncBlock, LoopStartBlock}});
898
899 // In the end block we need to insert a PHI node to deal with three cases:
900 // 1. We didn't find a mismatch in the scalar loop, so we return MaxLen.
901 // 2. We exitted the scalar loop early due to a mismatch and need to return
902 // the index that we found.
903 // 3. We didn't find a mismatch in the vector loop, so we return MaxLen.
904 // 4. We exitted the vector loop early due to a mismatch and need to return
905 // the index that we found.
906 Builder.SetInsertPoint(EndBlock, EndBlock->getFirstInsertionPt());
907 PHINode *ResPhi = Builder.CreatePHI(ResType, 4, "mismatch_result");
908 ResPhi->addIncoming(MaxLen, LoopIncBlock);
909 ResPhi->addIncoming(IndexPhi, LoopStartBlock);
910 ResPhi->addIncoming(MaxLen, VectorLoopIncBlock);
911 ResPhi->addIncoming(VectorLoopRes, VectorLoopMismatchBlock);
912
913 Value *FinalRes = Builder.CreateTrunc(ResPhi, ResType);
914
915 if (VerifyLoops) {
916 ScalarLoop->verifyLoop();
917 VectorLoop->verifyLoop();
918 if (!VectorLoop->isRecursivelyLCSSAForm(*DT, *LI))
919 report_fatal_error("Loops must remain in LCSSA form!");
920 if (!ScalarLoop->isRecursivelyLCSSAForm(*DT, *LI))
921 report_fatal_error("Loops must remain in LCSSA form!");
922 }
923
924 return FinalRes;
925}
926
927void LoopIdiomVectorize::transformByteCompare(GetElementPtrInst *GEPA,
928 GetElementPtrInst *GEPB,
929 PHINode *IndPhi, Value *MaxLen,
930 Instruction *Index, Value *Start,
931 bool IncIdx, BasicBlock *FoundBB,
932 BasicBlock *EndBB) {
933
934 // Insert the byte compare code at the end of the preheader block
935 BasicBlock *Preheader = CurLoop->getLoopPreheader();
936 BasicBlock *Header = CurLoop->getHeader();
937 UncondBrInst *PHBranch = cast<UncondBrInst>(Preheader->getTerminator());
938 IRBuilder<> Builder(PHBranch);
939 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Lazy);
940 Builder.SetCurrentDebugLocation(PHBranch->getDebugLoc());
941
942 // Increment the pointer if this was done before the loads in the loop.
943 if (IncIdx)
944 Start = Builder.CreateAdd(Start, ConstantInt::get(Start->getType(), 1));
945
946 Value *ByteCmpRes =
947 expandFindMismatch(Builder, DTU, GEPA, GEPB, Index, Start, MaxLen);
948
949 // Replaces uses of index & induction Phi with intrinsic (we already
950 // checked that the the first instruction of Header is the Phi above).
951 assert(IndPhi->hasOneUse() && "Index phi node has more than one use!");
952 Index->replaceAllUsesWith(ByteCmpRes);
953
954 // If no mismatch was found, we can jump to the end block. Create a
955 // new basic block for the compare instruction.
956 auto *CmpBB = BasicBlock::Create(Preheader->getContext(), "byte.compare",
957 Preheader->getParent());
958 CmpBB->moveBefore(EndBB);
959
960 // Replace the branch in the preheader with an always-true conditional branch.
961 // This ensures there is still a reference to the original loop.
962 Builder.CreateCondBr(Builder.getTrue(), CmpBB, Header);
963 PHBranch->eraseFromParent();
964
965 BasicBlock *MismatchEnd = cast<Instruction>(ByteCmpRes)->getParent();
966 DTU.applyUpdates({{DominatorTree::Insert, MismatchEnd, CmpBB}});
967
968 // Create the branch to either the end or found block depending on the value
969 // returned by the intrinsic.
970 Builder.SetInsertPoint(CmpBB);
971 if (FoundBB != EndBB) {
972 Value *FoundCmp = Builder.CreateICmpEQ(ByteCmpRes, MaxLen);
973 Builder.CreateCondBr(FoundCmp, EndBB, FoundBB);
974 DTU.applyUpdates({{DominatorTree::Insert, CmpBB, FoundBB},
975 {DominatorTree::Insert, CmpBB, EndBB}});
976
977 } else {
978 Builder.CreateBr(FoundBB);
979 DTU.applyUpdates({{DominatorTree::Insert, CmpBB, FoundBB}});
980 }
981
982 // Ensure all Phis in the successors of CmpBB have an incoming value from it.
983 fixSuccessorPhis(CurLoop, ByteCmpRes, ByteCmpRes, EndBB, CmpBB);
984 if (EndBB != FoundBB)
985 fixSuccessorPhis(CurLoop, ByteCmpRes, ByteCmpRes, FoundBB, CmpBB);
986
987 // The new CmpBB block isn't part of the loop, but will need to be added to
988 // the outer loop if there is one.
989 if (!CurLoop->isOutermost())
990 CurLoop->getParentLoop()->addBasicBlockToLoop(CmpBB, *LI);
991
992 if (VerifyLoops && CurLoop->getParentLoop()) {
993 CurLoop->getParentLoop()->verifyLoop();
994 if (!CurLoop->getParentLoop()->isRecursivelyLCSSAForm(*DT, *LI))
995 report_fatal_error("Loops must remain in LCSSA form!");
996 }
997}
998
999bool LoopIdiomVectorize::recognizeFindFirstByte() {
1000 // Currently the transformation only works on scalable vector types, although
1001 // there is no fundamental reason why it cannot be made to work for fixed
1002 // vectors. We also need to know the target's minimum page size in order to
1003 // generate runtime memory checks to ensure the vector version won't fault.
1004 if (!TTI->supportsScalableVectors() || !TTI->getMinPageSize().has_value() ||
1006 return false;
1007
1008 // We exclude loops with trip counts > minimum page size via runtime checks,
1009 // so make sure that the minimum page size is something sensible such that
1010 // induction variables cannot overflow.
1011 if (uint64_t(*TTI->getMinPageSize()) >
1012 (std::numeric_limits<uint64_t>::max() / 2))
1013 return false;
1014
1015 // Define some constants we need throughout.
1016 BasicBlock *Header = CurLoop->getHeader();
1017 LLVMContext &Ctx = Header->getContext();
1018
1019 // We are expecting the four blocks defined below: Header, MatchBB, InnerBB,
1020 // and OuterBB. For now, we will bail our for almost anything else. The Four
1021 // blocks contain one nested loop.
1022 if (CurLoop->getNumBackEdges() != 1 || CurLoop->getNumBlocks() != 4 ||
1023 CurLoop->getSubLoops().size() != 1)
1024 return false;
1025
1026 auto *InnerLoop = CurLoop->getSubLoops().front();
1027 Function &F = *InnerLoop->getHeader()->getParent();
1028
1029 // Bail if vectorization is disabled on inner loop.
1030 LoopVectorizeHints Hints(InnerLoop, /*InterleaveOnlyWhenForced=*/true, ORE);
1031 if (!Hints.allowVectorization(&F, InnerLoop,
1032 /*VectorizeOnlyWhenForced=*/false)) {
1033 LLVM_DEBUG(dbgs() << DEBUG_TYPE << " is disabled on inner loop "
1034 << InnerLoop->getName()
1035 << " due to vectorization hints\n");
1036 return false;
1037 }
1038
1039 PHINode *IndPhi = dyn_cast<PHINode>(&Header->front());
1040 if (!IndPhi || IndPhi->getNumIncomingValues() != 2)
1041 return false;
1042
1043 // Check instruction counts.
1044 auto LoopBlocks = CurLoop->getBlocks();
1045 if (LoopBlocks[0]->size() > 3 || LoopBlocks[1]->size() > 4 ||
1046 LoopBlocks[2]->size() > 3 || LoopBlocks[3]->size() > 3)
1047 return false;
1048
1049 // Check that no instruction other than IndPhi has outside uses.
1050 for (BasicBlock *BB : LoopBlocks)
1051 for (Instruction &I : *BB)
1052 if (&I != IndPhi)
1053 for (User *U : I.users())
1054 if (!CurLoop->contains(cast<Instruction>(U)))
1055 return false;
1056
1057 // Match the branch instruction in the header. We are expecting an
1058 // unconditional branch to the inner loop.
1059 //
1060 // Header:
1061 // %14 = phi ptr [ %24, %OuterBB ], [ %3, %Header.preheader ]
1062 // %15 = load i8, ptr %14, align 1
1063 // br label %MatchBB
1064 BasicBlock *MatchBB;
1065 if (!match(Header->getTerminator(), m_UnconditionalBr(MatchBB)) ||
1066 !InnerLoop->contains(MatchBB))
1067 return false;
1068
1069 // MatchBB should be the entrypoint into the inner loop containing the
1070 // comparison between a search element and a needle.
1071 //
1072 // MatchBB:
1073 // %20 = phi ptr [ %7, %Header ], [ %17, %InnerBB ]
1074 // %21 = load i8, ptr %20, align 1
1075 // %22 = icmp eq i8 %15, %21
1076 // br i1 %22, label %ExitSucc, label %InnerBB
1077 BasicBlock *ExitSucc, *InnerBB;
1078 Value *LoadSearch, *LoadNeedle;
1079 CmpPredicate MatchPred;
1080 if (!match(MatchBB->getTerminator(),
1081 m_Br(m_ICmp(MatchPred, m_Value(LoadSearch), m_Value(LoadNeedle)),
1082 m_BasicBlock(ExitSucc), m_BasicBlock(InnerBB))) ||
1083 MatchPred != ICmpInst::ICMP_EQ || !InnerLoop->contains(InnerBB))
1084 return false;
1085
1086 // We expect outside uses of `IndPhi' in ExitSucc (and only there).
1087 for (User *U : IndPhi->users())
1088 if (!CurLoop->contains(cast<Instruction>(U))) {
1089 auto *PN = dyn_cast<PHINode>(U);
1090 if (!PN || PN->getParent() != ExitSucc)
1091 return false;
1092 }
1093
1094 // Match the loads and check they are simple. The loads come from two PHIs,
1095 // each with two incoming values.
1096 PHINode *PSearch, *PNeedle;
1097 if (!match(LoadSearch, m_Load(m_Phi(PSearch))) ||
1098 !match(LoadNeedle, m_Load(m_Phi(PNeedle))) ||
1099 !cast<LoadInst>(LoadSearch)->isSimple() ||
1100 !cast<LoadInst>(LoadNeedle)->isSimple())
1101 return false;
1102
1103 // Check we are loading valid characters.
1104 Type *CharTy = LoadSearch->getType();
1105 if (!CharTy->isIntegerTy() || LoadNeedle->getType() != CharTy)
1106 return false;
1107
1108 // Pick the vectorisation factor based on CharTy, work out the cost of the
1109 // match intrinsic and decide if we should use it.
1110 // Note: For the time being we assume 128-bit vectors.
1111 unsigned VF = 128 / CharTy->getIntegerBitWidth();
1113 ScalableVectorType::get(CharTy, VF), FixedVectorType::get(CharTy, VF),
1115 IntrinsicCostAttributes Attrs(Intrinsic::experimental_vector_match, Args[2],
1116 Args);
1117 if (TTI->getIntrinsicInstrCost(Attrs, TTI::TCK_SizeAndLatency) > 4)
1118 return false;
1119
1120 if (PSearch->getNumIncomingValues() != 2 ||
1121 PNeedle->getNumIncomingValues() != 2)
1122 return false;
1123
1124 // One PHI comes from the outer loop (PSearch), the other one from the inner
1125 // loop (PNeedle). PSearch effectively corresponds to IndPhi.
1126 if (InnerLoop->contains(PSearch))
1127 std::swap(PSearch, PNeedle);
1128 if (PSearch != &Header->front() || PNeedle != &MatchBB->front())
1129 return false;
1130
1131 // The incoming values of both PHI nodes should be a gep of 1.
1132 Value *SearchStart = PSearch->getIncomingValue(0);
1133 Value *SearchIndex = PSearch->getIncomingValue(1);
1134 if (CurLoop->contains(PSearch->getIncomingBlock(0)))
1135 std::swap(SearchStart, SearchIndex);
1136
1137 Value *NeedleStart = PNeedle->getIncomingValue(0);
1138 Value *NeedleIndex = PNeedle->getIncomingValue(1);
1139 if (InnerLoop->contains(PNeedle->getIncomingBlock(0)))
1140 std::swap(NeedleStart, NeedleIndex);
1141
1142 // Match the GEPs.
1143 if (!match(SearchIndex, m_GEP(m_Specific(PSearch), m_One())) ||
1144 !match(NeedleIndex, m_GEP(m_Specific(PNeedle), m_One())))
1145 return false;
1146
1147 // Check the GEPs result type matches `CharTy'.
1148 GetElementPtrInst *GEPSearch = cast<GetElementPtrInst>(SearchIndex);
1149 GetElementPtrInst *GEPNeedle = cast<GetElementPtrInst>(NeedleIndex);
1150 if (GEPSearch->getResultElementType() != CharTy ||
1151 GEPNeedle->getResultElementType() != CharTy)
1152 return false;
1153
1154 // InnerBB should increment the address of the needle pointer.
1155 //
1156 // InnerBB:
1157 // %17 = getelementptr inbounds i8, ptr %20, i64 1
1158 // %18 = icmp eq ptr %17, %10
1159 // br i1 %18, label %OuterBB, label %MatchBB
1160 BasicBlock *OuterBB;
1161 Value *NeedleEnd;
1162 if (!match(InnerBB->getTerminator(),
1164 m_Value(NeedleEnd)),
1165 m_BasicBlock(OuterBB), m_Specific(MatchBB))) ||
1166 !CurLoop->contains(OuterBB))
1167 return false;
1168
1169 // OuterBB should increment the address of the search element pointer.
1170 //
1171 // OuterBB:
1172 // %24 = getelementptr inbounds i8, ptr %14, i64 1
1173 // %25 = icmp eq ptr %24, %6
1174 // br i1 %25, label %ExitFail, label %Header
1175 BasicBlock *ExitFail;
1176 Value *SearchEnd;
1177 if (!match(OuterBB->getTerminator(),
1179 m_Value(SearchEnd)),
1180 m_BasicBlock(ExitFail), m_Specific(Header))))
1181 return false;
1182
1183 if (!CurLoop->isLoopInvariant(SearchStart) ||
1184 !CurLoop->isLoopInvariant(SearchEnd) ||
1185 !CurLoop->isLoopInvariant(NeedleStart) ||
1186 !CurLoop->isLoopInvariant(NeedleEnd))
1187 return false;
1188
1189 LLVM_DEBUG(dbgs() << "Found idiom in loop: \n" << *CurLoop << "\n\n");
1190
1191 transformFindFirstByte(IndPhi, VF, CharTy, ExitSucc, ExitFail, SearchStart,
1192 SearchEnd, NeedleStart, NeedleEnd);
1193 return true;
1194}
1195
1196Value *LoopIdiomVectorize::expandFindFirstByte(
1197 IRBuilder<> &Builder, DomTreeUpdater &DTU, unsigned VF, Type *CharTy,
1198 Value *IndPhi, BasicBlock *ExitSucc, BasicBlock *ExitFail,
1199 Value *SearchStart, Value *SearchEnd, Value *NeedleStart,
1200 Value *NeedleEnd) {
1201 // Set up some types and constants that we intend to reuse.
1202 auto *I64Ty = Builder.getInt64Ty();
1203 auto *PredVTy = ScalableVectorType::get(Builder.getInt1Ty(), VF);
1204 auto *CharVTy = ScalableVectorType::get(CharTy, VF);
1205 auto *ConstVF = ConstantInt::get(I64Ty, VF);
1206
1207 // Other common arguments.
1208 BasicBlock *Preheader = CurLoop->getLoopPreheader();
1209 LLVMContext &Ctx = Preheader->getContext();
1210 Value *Passthru = ConstantInt::getNullValue(CharVTy);
1211
1212 // Split block in the original loop preheader.
1213 // SPH is the new preheader to the old scalar loop.
1214 BasicBlock *SPH = SplitBlock(Preheader, Preheader->getTerminator(), DT, LI,
1215 nullptr, "scalar_preheader");
1216
1217 // Create the blocks that we're going to use.
1218 //
1219 // We will have the following loops:
1220 // (O) Outer loop where we iterate over the elements of the search array.
1221 // (I) Inner loop where we iterate over the elements of the needle array.
1222 //
1223 // Overall, the blocks do the following:
1224 // (0) Check if the arrays can't cross page boundaries. If so go to (1),
1225 // otherwise fall back to the original scalar loop.
1226 // (1) Load the search array. Go to (2).
1227 // (2) (a) Load the needle array.
1228 // (b) Splat the first element to the inactive lanes.
1229 // (c) Accumulate any matches found. If we haven't reached the end of the
1230 // needle array loop back to (2), otherwise go to (3).
1231 // (3) Test if we found any match. If so go to (4), otherwise go to (5).
1232 // (4) Compute the index of the first match and exit.
1233 // (5) Check if we've reached the end of the search array. If not loop back to
1234 // (1), otherwise exit.
1235 // Blocks (0,4) are not part of any loop. Blocks (1,3,5) and (2) belong to the
1236 // outer and inner loops, respectively.
1237 BasicBlock *BB0 = BasicBlock::Create(Ctx, "mem_check", SPH->getParent(), SPH);
1238 BasicBlock *BB1 =
1239 BasicBlock::Create(Ctx, "find_first_vec_header", SPH->getParent(), SPH);
1240 BasicBlock *BB2 =
1241 BasicBlock::Create(Ctx, "needle_check_vec", SPH->getParent(), SPH);
1242 BasicBlock *BB3 =
1243 BasicBlock::Create(Ctx, "match_check_vec", SPH->getParent(), SPH);
1244 BasicBlock *BB4 =
1245 BasicBlock::Create(Ctx, "calculate_match", SPH->getParent(), SPH);
1246 BasicBlock *BB5 =
1247 BasicBlock::Create(Ctx, "search_check_vec", SPH->getParent(), SPH);
1248
1249 // Update LoopInfo with the new loops.
1250 auto OuterLoop = LI->AllocateLoop();
1251 auto InnerLoop = LI->AllocateLoop();
1252
1253 if (auto ParentLoop = CurLoop->getParentLoop()) {
1254 ParentLoop->addBasicBlockToLoop(BB0, *LI);
1255 ParentLoop->addChildLoop(OuterLoop);
1256 ParentLoop->addBasicBlockToLoop(BB4, *LI);
1257 } else {
1258 LI->addTopLevelLoop(OuterLoop);
1259 }
1260
1261 // Add the inner loop to the outer.
1262 OuterLoop->addChildLoop(InnerLoop);
1263
1264 // Add the new basic blocks to the corresponding loops.
1265 OuterLoop->addBasicBlockToLoop(BB1, *LI);
1266 OuterLoop->addBasicBlockToLoop(BB3, *LI);
1267 OuterLoop->addBasicBlockToLoop(BB5, *LI);
1268 InnerLoop->addBasicBlockToLoop(BB2, *LI);
1269
1270 // Update the terminator added by SplitBlock to branch to the first block.
1271 Preheader->getTerminator()->setSuccessor(0, BB0);
1272 DTU.applyUpdates({{DominatorTree::Delete, Preheader, SPH},
1273 {DominatorTree::Insert, Preheader, BB0}});
1274
1275 // (0) Check if we could be crossing a page boundary; if so, fallback to the
1276 // old scalar loops. Also create a predicate of VF elements to be used in the
1277 // vector loops.
1278 Builder.SetInsertPoint(BB0);
1279 Value *ISearchStart =
1280 Builder.CreatePtrToInt(SearchStart, I64Ty, "search_start_int");
1281 Value *ISearchEnd =
1282 Builder.CreatePtrToInt(SearchEnd, I64Ty, "search_end_int");
1283 Value *SearchIdxInit = Constant::getNullValue(I64Ty);
1284 Value *SearchTripCount =
1285 Builder.CreateZExt(Builder.CreatePtrDiff(CharTy, SearchEnd, SearchStart,
1286 "search_trip_count"),
1287 I64Ty);
1288 Value *INeedleStart =
1289 Builder.CreatePtrToInt(NeedleStart, I64Ty, "needle_start_int");
1290 Value *INeedleEnd =
1291 Builder.CreatePtrToInt(NeedleEnd, I64Ty, "needle_end_int");
1292 Value *NeedleIdxInit = Constant::getNullValue(I64Ty);
1293 Value *NeedleTripCount =
1294 Builder.CreateZExt(Builder.CreatePtrDiff(CharTy, NeedleEnd, NeedleStart,
1295 "needle_trip_count"),
1296 I64Ty);
1297 Value *PredVF =
1298 Builder.CreateIntrinsic(Intrinsic::get_active_lane_mask, {PredVTy, I64Ty},
1299 {ConstantInt::get(I64Ty, 0), ConstVF});
1300
1301 const uint64_t MinPageSize = TTI->getMinPageSize().value();
1302 const uint64_t AddrShiftAmt = llvm::Log2_64(MinPageSize);
1303 Value *SearchStartPage =
1304 Builder.CreateLShr(ISearchStart, AddrShiftAmt, "search_start_page");
1305 Value *SearchEndPage =
1306 Builder.CreateLShr(ISearchEnd, AddrShiftAmt, "search_end_page");
1307 Value *NeedleStartPage =
1308 Builder.CreateLShr(INeedleStart, AddrShiftAmt, "needle_start_page");
1309 Value *NeedleEndPage =
1310 Builder.CreateLShr(INeedleEnd, AddrShiftAmt, "needle_end_page");
1311 Value *SearchPageCmp =
1312 Builder.CreateICmpNE(SearchStartPage, SearchEndPage, "search_page_cmp");
1313 Value *NeedlePageCmp =
1314 Builder.CreateICmpNE(NeedleStartPage, NeedleEndPage, "needle_page_cmp");
1315
1316 Value *CombinedPageCmp =
1317 Builder.CreateOr(SearchPageCmp, NeedlePageCmp, "combined_page_cmp");
1318 CondBrInst *CombinedPageBr = Builder.CreateCondBr(CombinedPageCmp, SPH, BB1);
1319 CombinedPageBr->setMetadata(LLVMContext::MD_prof,
1320 MDBuilder(Ctx).createBranchWeights(10, 90));
1321 DTU.applyUpdates(
1322 {{DominatorTree::Insert, BB0, SPH}, {DominatorTree::Insert, BB0, BB1}});
1323
1324 // (1) Load the search array and branch to the inner loop.
1325 Builder.SetInsertPoint(BB1);
1326 PHINode *SearchIdx = Builder.CreatePHI(I64Ty, 2, "search_idx");
1327 Value *PredSearch = Builder.CreateIntrinsic(
1328 Intrinsic::get_active_lane_mask, {PredVTy, I64Ty},
1329 {SearchIdx, SearchTripCount}, nullptr, "search_pred");
1330 PredSearch = Builder.CreateAnd(PredVF, PredSearch, "search_masked");
1331 Value *Search = Builder.CreateGEP(CharTy, SearchStart, SearchIdx, "psearch");
1332 Value *LoadSearch = Builder.CreateMaskedLoad(
1333 CharVTy, Search, Align(1), PredSearch, Passthru, "search_load_vec");
1334 Value *MatchInit = Constant::getNullValue(PredVTy);
1335 Builder.CreateBr(BB2);
1336 DTU.applyUpdates({{DominatorTree::Insert, BB1, BB2}});
1337
1338 // (2) Inner loop.
1339 Builder.SetInsertPoint(BB2);
1340 PHINode *NeedleIdx = Builder.CreatePHI(I64Ty, 2, "needle_idx");
1341 PHINode *Match = Builder.CreatePHI(PredVTy, 2, "pmatch");
1342
1343 // (2.a) Load the needle array.
1344 Value *PredNeedle = Builder.CreateIntrinsic(
1345 Intrinsic::get_active_lane_mask, {PredVTy, I64Ty},
1346 {NeedleIdx, NeedleTripCount}, nullptr, "needle_pred");
1347 PredNeedle = Builder.CreateAnd(PredVF, PredNeedle, "needle_masked");
1348 Value *Needle = Builder.CreateGEP(CharTy, NeedleStart, NeedleIdx, "pneedle");
1349 Value *LoadNeedle = Builder.CreateMaskedLoad(
1350 CharVTy, Needle, Align(1), PredNeedle, Passthru, "needle_load_vec");
1351
1352 // (2.b) Splat the first element to the inactive lanes.
1353 Value *Needle0 =
1354 Builder.CreateExtractElement(LoadNeedle, uint64_t(0), "needle0");
1355 Value *Needle0Splat = Builder.CreateVectorSplat(ElementCount::getScalable(VF),
1356 Needle0, "needle0");
1357 LoadNeedle = Builder.CreateSelect(PredNeedle, LoadNeedle, Needle0Splat,
1358 "needle_splat");
1359 LoadNeedle = Builder.CreateExtractVector(
1360 FixedVectorType::get(CharTy, VF), LoadNeedle, uint64_t(0), "needle_vec");
1361
1362 // (2.c) Accumulate matches.
1363 Value *MatchSeg = Builder.CreateIntrinsic(
1364 Intrinsic::experimental_vector_match, {CharVTy, LoadNeedle->getType()},
1365 {LoadSearch, LoadNeedle, PredSearch}, nullptr, "match_segment");
1366 Value *MatchAcc = Builder.CreateOr(Match, MatchSeg, "match_accumulator");
1367 Value *NextNeedleIdx =
1368 Builder.CreateAdd(NeedleIdx, ConstVF, "needle_idx_next");
1369 Builder.CreateCondBr(Builder.CreateICmpULT(NextNeedleIdx, NeedleTripCount),
1370 BB2, BB3);
1371 DTU.applyUpdates(
1372 {{DominatorTree::Insert, BB2, BB2}, {DominatorTree::Insert, BB2, BB3}});
1373
1374 // (3) Check if we found a match.
1375 Builder.SetInsertPoint(BB3);
1376 PHINode *MatchPredAccLCSSA = Builder.CreatePHI(PredVTy, 1, "match_pred");
1377 Value *IfAnyMatch = Builder.CreateOrReduce(MatchPredAccLCSSA);
1378 Builder.CreateCondBr(IfAnyMatch, BB4, BB5);
1379 DTU.applyUpdates(
1380 {{DominatorTree::Insert, BB3, BB4}, {DominatorTree::Insert, BB3, BB5}});
1381
1382 // (4) We found a match. Compute the index of its location and exit.
1383 Builder.SetInsertPoint(BB4);
1384 PHINode *MatchLCSSA =
1385 Builder.CreatePHI(SearchStart->getType(), 1, "match_start");
1386 PHINode *MatchPredLCSSA = Builder.CreatePHI(PredVTy, 1, "match_vec");
1387 Value *MatchCnt = Builder.CreateIntrinsic(
1388 Intrinsic::experimental_cttz_elts, {I64Ty, PredVTy},
1389 {MatchPredLCSSA, /*ZeroIsPoison=*/Builder.getInt1(true)}, nullptr,
1390 "match_idx");
1391 Value *MatchVal =
1392 Builder.CreateGEP(CharTy, MatchLCSSA, MatchCnt, "match_res");
1393 Builder.CreateBr(ExitSucc);
1394 DTU.applyUpdates({{DominatorTree::Insert, BB4, ExitSucc}});
1395
1396 // (5) Check if we've reached the end of the search array.
1397 Builder.SetInsertPoint(BB5);
1398 Value *NextSearchIdx =
1399 Builder.CreateAdd(SearchIdx, ConstVF, "search_idx_next");
1400 Builder.CreateCondBr(Builder.CreateICmpULT(NextSearchIdx, SearchTripCount),
1401 BB1, ExitFail);
1402 DTU.applyUpdates({{DominatorTree::Insert, BB5, BB1},
1403 {DominatorTree::Insert, BB5, ExitFail}});
1404
1405 // Set up the PHI nodes.
1406 SearchIdx->addIncoming(SearchIdxInit, BB0);
1407 SearchIdx->addIncoming(NextSearchIdx, BB5);
1408 NeedleIdx->addIncoming(NeedleIdxInit, BB1);
1409 NeedleIdx->addIncoming(NextNeedleIdx, BB2);
1410 Match->addIncoming(MatchInit, BB1);
1411 Match->addIncoming(MatchAcc, BB2);
1412 // These are needed to retain LCSSA form.
1413 MatchPredAccLCSSA->addIncoming(MatchAcc, BB2);
1414 MatchLCSSA->addIncoming(Search, BB3);
1415 MatchPredLCSSA->addIncoming(MatchPredAccLCSSA, BB3);
1416
1417 // Ensure all Phis in the successors of BB4/BB5 have an incoming value from
1418 // them.
1419 fixSuccessorPhis(CurLoop, IndPhi, MatchVal, ExitSucc, BB4);
1420 if (ExitSucc != ExitFail)
1421 fixSuccessorPhis(CurLoop, IndPhi, MatchVal, ExitFail, BB5);
1422
1423 if (VerifyLoops) {
1424 OuterLoop->verifyLoop();
1425 InnerLoop->verifyLoop();
1426 if (!OuterLoop->isRecursivelyLCSSAForm(*DT, *LI))
1427 report_fatal_error("Loops must remain in LCSSA form!");
1428 }
1429
1430 return MatchVal;
1431}
1432
1433void LoopIdiomVectorize::transformFindFirstByte(
1434 PHINode *IndPhi, unsigned VF, Type *CharTy, BasicBlock *ExitSucc,
1435 BasicBlock *ExitFail, Value *SearchStart, Value *SearchEnd,
1436 Value *NeedleStart, Value *NeedleEnd) {
1437 // Insert the find first byte code at the end of the preheader block.
1438 BasicBlock *Preheader = CurLoop->getLoopPreheader();
1439 UncondBrInst *PHBranch = cast<UncondBrInst>(Preheader->getTerminator());
1440 IRBuilder<> Builder(PHBranch);
1441 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Lazy);
1442 Builder.SetCurrentDebugLocation(PHBranch->getDebugLoc());
1443
1444 expandFindFirstByte(Builder, DTU, VF, CharTy, IndPhi, ExitSucc, ExitFail,
1445 SearchStart, SearchEnd, NeedleStart, NeedleEnd);
1446
1447 if (VerifyLoops && CurLoop->getParentLoop()) {
1448 CurLoop->getParentLoop()->verifyLoop();
1449 if (!CurLoop->getParentLoop()->isRecursivelyLCSSAForm(*DT, *LI))
1450 report_fatal_error("Loops must remain in LCSSA form!");
1451 }
1452}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
unsigned uint64_t
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 clEnumValN(ENUMVAL, FLAGNAME, DESC)
#define DEBUG_TYPE
static MDNode * createBranchWeights(LLVMContext &Context, uint64_t TrueWeight, uint64_t FalseWeight)
static cl::opt< bool > VerifyLoops("loop-idiom-vectorize-verify", cl::Hidden, cl::init(false), cl::desc("Verify loops generated Loop Idiom Vectorize Pass."))
static cl::opt< bool > DisableAll("disable-loop-idiom-vectorize-all", cl::Hidden, cl::init(false), cl::desc("Disable Loop Idiom Vectorize Pass."))
static void fixSuccessorPhis(Loop *L, Value *ScalarRes, Value *VectorRes, BasicBlock *SuccBB, BasicBlock *IncBB)
static cl::opt< LoopIdiomVectorizeStyle > LITVecStyle("loop-idiom-vectorize-style", cl::Hidden, cl::desc("The vectorization style for loop idiom transform."), cl::values(clEnumValN(LoopIdiomVectorizeStyle::Masked, "masked", "Use masked vector intrinsics"), clEnumValN(LoopIdiomVectorizeStyle::Predicated, "predicated", "Use VP intrinsics")), cl::init(LoopIdiomVectorizeStyle::Masked))
static cl::opt< bool > DisableFindFirstByte("disable-loop-idiom-vectorize-find-first-byte", cl::Hidden, cl::init(false), cl::desc("Do not convert find-first-byte loop(s)."))
static cl::opt< unsigned > ByteCmpVF("loop-idiom-vectorize-bytecmp-vf", cl::Hidden, cl::desc("The vectorization factor for byte-compare patterns."), cl::init(16))
static cl::opt< bool > DisableByteCmp("disable-loop-idiom-vectorize-bytecmp", cl::Hidden, cl::init(false), cl::desc("Proceed with Loop Idiom Vectorize Pass, but do " "not convert byte-compare loop(s)."))
This file defines the LoopVectorizationLegality class.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define LLVM_DEBUG(...)
Definition Debug.h:119
static cl::opt< unsigned > MinPageSize("min-page-size", cl::init(0), cl::Hidden, cl::desc("Use this to override the target's minimum page size."))
This pass exposes codegen information to IR-level passes.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
Definition BasicBlock.h:515
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition BasicBlock.h:206
const Instruction & front() const
Definition BasicBlock.h:469
LLVM_ABI LLVMContext & getContext() const
Get the context in which this basic block lives.
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
An abstraction over a floating-point predicate, and a pack of an integer predicate with samesign info...
Conditional Branch instruction.
static CondBrInst * Create(Value *Cond, BasicBlock *IfTrue, BasicBlock *IfFalse, InsertPosition InsertBefore=nullptr)
static LLVM_ABI Constant * getAllOnesValue(Type *Ty)
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
static constexpr ElementCount getScalable(ScalarTy MinVal)
Definition TypeSize.h:308
static LLVM_ABI FixedVectorType * get(Type *ElementType, unsigned NumElts)
Definition Type.cpp:843
void applyUpdates(ArrayRef< UpdateT > Updates)
Submit updates to all available trees.
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
LLVM_ABI bool isInBounds() const
Determine whether the GEP has the inbounds flag.
Type * getResultElementType() const
unsigned getNumIndices() const
Module * getParent()
Get the module that this global value is contained inside of...
ConstantInt * getInt1(bool V)
Get a constant value representing either true or false.
Definition IRBuilder.h:452
Value * CreateICmpULT(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:2406
IntegerType * getInt1Ty()
Fetch the type representing a single bit.
Definition IRBuilder.h:519
Value * CreateExtractElement(Value *Vec, Value *Idx, const Twine &Name="")
Definition IRBuilder.h:2665
CondBrInst * CreateCondBr(Value *Cond, BasicBlock *True, BasicBlock *False, MDNode *BranchWeights=nullptr, MDNode *Unpredictable=nullptr)
Create a conditional 'br Cond, TrueDest, FalseDest' instruction.
Definition IRBuilder.h:1224
LLVM_ABI Value * CreateVectorSplat(unsigned NumElts, Value *V, const Twine &Name="")
Return a vector value that contains.
ConstantInt * getTrue()
Get the constant value for i1 true.
Definition IRBuilder.h:457
LLVM_ABI CallInst * CreateMaskedLoad(Type *Ty, Value *Ptr, Align Alignment, Value *Mask, Value *PassThru=nullptr, const Twine &Name="")
Create a call to Masked Load intrinsic.
LLVM_ABI Value * CreateSelect(Value *C, Value *True, Value *False, const Twine &Name="", Instruction *MDFrom=nullptr)
void SetCurrentDebugLocation(const DebugLoc &L)
Set location information used by debugging information.
Definition IRBuilder.h:221
Value * CreateLShr(Value *LHS, Value *RHS, const Twine &Name="", bool isExact=false)
Definition IRBuilder.h:1540
IntegerType * getInt32Ty()
Fetch the type representing a 32-bit integer.
Definition IRBuilder.h:534
Value * CreateExtractVector(Type *DstType, Value *SrcVec, Value *Idx, const Twine &Name="")
Create a call to the vector.extract intrinsic.
Definition IRBuilder.h:1120
Value * CreateVScale(Type *Ty, const Twine &Name="")
Create a call to llvm.vscale.<Ty>().
Definition IRBuilder.h:944
IntegerType * getInt64Ty()
Fetch the type representing a 64-bit integer.
Definition IRBuilder.h:539
Value * CreateICmpNE(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:2394
Value * CreateGEP(Type *Ty, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &Name="", GEPNoWrapFlags NW=GEPNoWrapFlags::none())
Definition IRBuilder.h:2019
UncondBrInst * CreateBr(BasicBlock *Dest)
Create an unconditional 'br label X' instruction.
Definition IRBuilder.h:1218
LLVM_ABI Value * CreateOrReduce(Value *Src)
Create a vector int OR reduction intrinsic of the source vector.
PHINode * CreatePHI(Type *Ty, unsigned NumReservedValues, const Twine &Name="")
Definition IRBuilder.h:2555
Value * CreateICmpEQ(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:2390
InstTy * Insert(InstTy *I, const Twine &Name="") const
Insert and return the specified instruction.
Definition IRBuilder.h:146
Value * CreateCountTrailingZeroElems(Type *ResTy, Value *Mask, bool ZeroIsPoison=true, const Twine &Name="")
Create a call to llvm.experimental_cttz_elts.
Definition IRBuilder.h:1162
Value * CreateSub(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1447
LLVM_ABI Value * CreatePtrDiff(Value *LHS, Value *RHS, const Twine &Name="", bool IsNUW=false)
Return the difference between two pointer values.
LoadInst * CreateLoad(Type *Ty, Value *Ptr, const char *Name)
Provided to resolve 'CreateLoad(Ty, Ptr, "...")' correctly, instead of converting the string to 'bool...
Definition IRBuilder.h:1914
Value * CreateZExt(Value *V, Type *DestTy, const Twine &Name="", bool IsNonNeg=false)
Definition IRBuilder.h:2129
Value * CreateAnd(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:1578
LLVM_ABI Value * CreateIntrinsic(Intrinsic::ID ID, ArrayRef< Type * > OverloadTypes, ArrayRef< Value * > Args, FMFSource FMFSource={}, const Twine &Name="", ArrayRef< OperandBundleDef > OpBundles={}, function_ref< void(CallInst *)> SetFn=[](CallInst *) {})
Variant to create a possibly constant-folded intrinsic.
Value * CreateAdd(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1430
Value * CreatePtrToInt(Value *V, Type *DestTy, const Twine &Name="")
Definition IRBuilder.h:2241
Value * CreateTrunc(Value *V, Type *DestTy, const Twine &Name="", bool IsNUW=false, bool IsNSW=false)
Definition IRBuilder.h:2115
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block.
Definition IRBuilder.h:181
Value * CreateICmpULE(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:2410
Value * CreateOr(Value *LHS, Value *RHS, const Twine &Name="", bool IsDisjoint=false)
Definition IRBuilder.h:1600
IntegerType * getInt8Ty()
Fetch the type representing an 8-bit integer.
Definition IRBuilder.h:524
Value * CreateMul(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1464
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2903
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
iterator_range< user_iterator > users()
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
LLVM_ABI void setSuccessor(unsigned Idx, BasicBlock *BB)
Update the specified successor to point at the provided block.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
This class provides an interface for updating the loop pass manager based on mutations to the loop ne...
An instruction for reading from memory.
bool isSimple() const
LLVM_ABI PreservedAnalyses run(Loop &L, LoopAnalysisManager &AM, LoopStandardAnalysisResults &AR, LPMUpdater &U)
Utility class for getting and setting loop vectorizer hints in the form of loop metadata.
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
The optimization diagnostic interface.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Definition Analysis.h:115
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
Class to represent scalable SIMD vectors.
static LLVM_ABI ScalableVectorType * get(Type *ElementType, unsigned MinNumElts)
Definition Type.cpp:865
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
@ TCK_SizeAndLatency
The weighted sum of size and latency.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
LLVM_ABI unsigned getIntegerBitWidth() const
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
Definition Type.cpp:297
static LLVM_ABI IntegerType * getInt1Ty(LLVMContext &C)
Definition Type.cpp:296
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:252
Unconditional Branch instruction.
static UncondBrInst * Create(BasicBlock *Target, InsertPosition InsertBefore=nullptr)
Value * getOperand(unsigned i) const
Definition User.h:207
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition Value.h:441
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:260
iterator_range< user_iterator > users()
Definition Value.h:428
Base class of all SIMD vector types.
ElementCount getElementCount() const
Return an ElementCount instance to represent the (possibly scalable) number of elements in the vector...
static LLVM_ABI VectorType * get(Type *ElementType, ElementCount EC)
This static method is the primary way to construct an VectorType.
const ParentTy * getParent() const
Definition ilist_node.h:34
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
constexpr char Attrs[]
Key for Kernel::Metadata::mAttrs.
match_bind< PHINode > m_Phi(PHINode *&PN)
Match a PHI node, capturing it if we match.
br_match m_UnconditionalBr(BasicBlock *&Succ)
bool match(Val *V, const Pattern &P)
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
cst_pred_ty< is_one > m_One()
Match an integer 1 or a vector with all elements equal to 1.
auto m_BasicBlock()
Match an arbitrary basic block value and ignore it.
auto m_Value()
Match an arbitrary value and ignore it.
auto m_GEP(const OperandTypes &...Ops)
Matches GetElementPtrInst.
SpecificCmpClass_match< LHS, RHS, ICmpInst > m_SpecificICmp(CmpPredicate MatchPred, const LHS &L, const RHS &R)
OneOps_match< OpTy, Instruction::Load > m_Load(const OpTy &Op)
Matches LoadInst.
CastInst_match< OpTy, ZExtInst > m_ZExt(const OpTy &Op)
Matches ZExt.
BinaryOp_match< LHS, RHS, Instruction::Add, true > m_c_Add(const LHS &L, const RHS &R)
Matches a Add with LHS and RHS in either order.
CmpClass_match< LHS, RHS, ICmpInst > m_ICmp(CmpPredicate &Pred, const LHS &L, const RHS &R)
brc_match< Cond_t, match_bind< BasicBlock >, match_bind< BasicBlock > > m_Br(const Cond_t &C, BasicBlock *&T, BasicBlock *&F)
ValuesClass values(OptsTy... Options)
Helper to build a ValuesClass by forwarding a variable number of arguments as an initializer list to ...
initializer< Ty > init(const Ty &Val)
PointerTypeMap run(const Module &M)
Compute the PointerTypeMap for the module M.
bool isSimple(Instruction *I)
Definition SLPUtils.cpp:815
This is an optimization pass for GlobalISel generic memory operations.
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition STLExtras.h:1685
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
unsigned Log2_64(uint64_t Value)
Return the floor log base 2 of the specified value, -1 if the value is zero.
Definition MathExtras.h:332
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
AnalysisManager< Loop, LoopStandardAnalysisResults & > LoopAnalysisManager
The loop analysis manager.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
OuterAnalysisManagerProxy< FunctionAnalysisManager, Loop, LoopStandardAnalysisResults & > FunctionAnalysisManagerLoopProxy
A proxy from a FunctionAnalysisManager to a Loop.
TargetTransformInfo TTI
IRBuilder(LLVMContext &, FolderTy, InserterTy, MDNode *, ArrayRef< OperandBundleDef >) -> IRBuilder< FolderTy, InserterTy >
LLVM_ABI BasicBlock * SplitBlock(BasicBlock *Old, BasicBlock::iterator SplitPt, DominatorTree *DT, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, const Twine &BBName="")
Split the specified block at the specified instruction.
DWARFExpression::Operation Op
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:880
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
The adaptor from a function pass to a loop pass computes these analyses and makes them available to t...