1 //===----------- VectorUtils.cpp - Vectorizer utility functions -----------===// 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 file defines vectorizer utilities. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "llvm/Analysis/VectorUtils.h" 14 #include "llvm/ADT/EquivalenceClasses.h" 15 #include "llvm/Analysis/DemandedBits.h" 16 #include "llvm/Analysis/LoopInfo.h" 17 #include "llvm/Analysis/LoopIterator.h" 18 #include "llvm/Analysis/ScalarEvolution.h" 19 #include "llvm/Analysis/ScalarEvolutionExpressions.h" 20 #include "llvm/Analysis/TargetTransformInfo.h" 21 #include "llvm/Analysis/ValueTracking.h" 22 #include "llvm/IR/Constants.h" 23 #include "llvm/IR/GetElementPtrTypeIterator.h" 24 #include "llvm/IR/IRBuilder.h" 25 #include "llvm/IR/PatternMatch.h" 26 #include "llvm/IR/Value.h" 27 #include "llvm/Support/CommandLine.h" 28 29 #define DEBUG_TYPE "vectorutils" 30 31 using namespace llvm; 32 using namespace llvm::PatternMatch; 33 34 /// Maximum factor for an interleaved memory access. 35 static cl::opt<unsigned> MaxInterleaveGroupFactor( 36 "max-interleave-group-factor", cl::Hidden, 37 cl::desc("Maximum factor for an interleaved access group (default = 8)"), 38 cl::init(8)); 39 40 /// Return true if all of the intrinsic's arguments and return type are scalars 41 /// for the scalar form of the intrinsic, and vectors for the vector form of the 42 /// intrinsic (except operands that are marked as always being scalar by 43 /// hasVectorInstrinsicScalarOpd). 44 bool llvm::isTriviallyVectorizable(Intrinsic::ID ID) { 45 switch (ID) { 46 case Intrinsic::abs: // Begin integer bit-manipulation. 47 case Intrinsic::bswap: 48 case Intrinsic::bitreverse: 49 case Intrinsic::ctpop: 50 case Intrinsic::ctlz: 51 case Intrinsic::cttz: 52 case Intrinsic::fshl: 53 case Intrinsic::fshr: 54 case Intrinsic::smax: 55 case Intrinsic::smin: 56 case Intrinsic::umax: 57 case Intrinsic::umin: 58 case Intrinsic::sadd_sat: 59 case Intrinsic::ssub_sat: 60 case Intrinsic::uadd_sat: 61 case Intrinsic::usub_sat: 62 case Intrinsic::smul_fix: 63 case Intrinsic::smul_fix_sat: 64 case Intrinsic::umul_fix: 65 case Intrinsic::umul_fix_sat: 66 case Intrinsic::sqrt: // Begin floating-point. 67 case Intrinsic::sin: 68 case Intrinsic::cos: 69 case Intrinsic::exp: 70 case Intrinsic::exp2: 71 case Intrinsic::log: 72 case Intrinsic::log10: 73 case Intrinsic::log2: 74 case Intrinsic::fabs: 75 case Intrinsic::minnum: 76 case Intrinsic::maxnum: 77 case Intrinsic::minimum: 78 case Intrinsic::maximum: 79 case Intrinsic::copysign: 80 case Intrinsic::floor: 81 case Intrinsic::ceil: 82 case Intrinsic::trunc: 83 case Intrinsic::rint: 84 case Intrinsic::nearbyint: 85 case Intrinsic::round: 86 case Intrinsic::roundeven: 87 case Intrinsic::pow: 88 case Intrinsic::fma: 89 case Intrinsic::fmuladd: 90 case Intrinsic::powi: 91 case Intrinsic::canonicalize: 92 return true; 93 default: 94 return false; 95 } 96 } 97 98 /// Identifies if the vector form of the intrinsic has a scalar operand. 99 bool llvm::hasVectorInstrinsicScalarOpd(Intrinsic::ID ID, 100 unsigned ScalarOpdIdx) { 101 switch (ID) { 102 case Intrinsic::abs: 103 case Intrinsic::ctlz: 104 case Intrinsic::cttz: 105 case Intrinsic::powi: 106 return (ScalarOpdIdx == 1); 107 case Intrinsic::smul_fix: 108 case Intrinsic::smul_fix_sat: 109 case Intrinsic::umul_fix: 110 case Intrinsic::umul_fix_sat: 111 return (ScalarOpdIdx == 2); 112 default: 113 return false; 114 } 115 } 116 117 /// Returns intrinsic ID for call. 118 /// For the input call instruction it finds mapping intrinsic and returns 119 /// its ID, in case it does not found it return not_intrinsic. 120 Intrinsic::ID llvm::getVectorIntrinsicIDForCall(const CallInst *CI, 121 const TargetLibraryInfo *TLI) { 122 Intrinsic::ID ID = getIntrinsicForCallSite(*CI, TLI); 123 if (ID == Intrinsic::not_intrinsic) 124 return Intrinsic::not_intrinsic; 125 126 if (isTriviallyVectorizable(ID) || ID == Intrinsic::lifetime_start || 127 ID == Intrinsic::lifetime_end || ID == Intrinsic::assume || 128 ID == Intrinsic::experimental_noalias_scope_decl || 129 ID == Intrinsic::sideeffect || ID == Intrinsic::pseudoprobe) 130 return ID; 131 return Intrinsic::not_intrinsic; 132 } 133 134 /// Find the operand of the GEP that should be checked for consecutive 135 /// stores. This ignores trailing indices that have no effect on the final 136 /// pointer. 137 unsigned llvm::getGEPInductionOperand(const GetElementPtrInst *Gep) { 138 const DataLayout &DL = Gep->getModule()->getDataLayout(); 139 unsigned LastOperand = Gep->getNumOperands() - 1; 140 TypeSize GEPAllocSize = DL.getTypeAllocSize(Gep->getResultElementType()); 141 142 // Walk backwards and try to peel off zeros. 143 while (LastOperand > 1 && match(Gep->getOperand(LastOperand), m_Zero())) { 144 // Find the type we're currently indexing into. 145 gep_type_iterator GEPTI = gep_type_begin(Gep); 146 std::advance(GEPTI, LastOperand - 2); 147 148 // If it's a type with the same allocation size as the result of the GEP we 149 // can peel off the zero index. 150 if (DL.getTypeAllocSize(GEPTI.getIndexedType()) != GEPAllocSize) 151 break; 152 --LastOperand; 153 } 154 155 return LastOperand; 156 } 157 158 /// If the argument is a GEP, then returns the operand identified by 159 /// getGEPInductionOperand. However, if there is some other non-loop-invariant 160 /// operand, it returns that instead. 161 Value *llvm::stripGetElementPtr(Value *Ptr, ScalarEvolution *SE, Loop *Lp) { 162 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr); 163 if (!GEP) 164 return Ptr; 165 166 unsigned InductionOperand = getGEPInductionOperand(GEP); 167 168 // Check that all of the gep indices are uniform except for our induction 169 // operand. 170 for (unsigned i = 0, e = GEP->getNumOperands(); i != e; ++i) 171 if (i != InductionOperand && 172 !SE->isLoopInvariant(SE->getSCEV(GEP->getOperand(i)), Lp)) 173 return Ptr; 174 return GEP->getOperand(InductionOperand); 175 } 176 177 /// If a value has only one user that is a CastInst, return it. 178 Value *llvm::getUniqueCastUse(Value *Ptr, Loop *Lp, Type *Ty) { 179 Value *UniqueCast = nullptr; 180 for (User *U : Ptr->users()) { 181 CastInst *CI = dyn_cast<CastInst>(U); 182 if (CI && CI->getType() == Ty) { 183 if (!UniqueCast) 184 UniqueCast = CI; 185 else 186 return nullptr; 187 } 188 } 189 return UniqueCast; 190 } 191 192 /// Get the stride of a pointer access in a loop. Looks for symbolic 193 /// strides "a[i*stride]". Returns the symbolic stride, or null otherwise. 194 Value *llvm::getStrideFromPointer(Value *Ptr, ScalarEvolution *SE, Loop *Lp) { 195 auto *PtrTy = dyn_cast<PointerType>(Ptr->getType()); 196 if (!PtrTy || PtrTy->isAggregateType()) 197 return nullptr; 198 199 // Try to remove a gep instruction to make the pointer (actually index at this 200 // point) easier analyzable. If OrigPtr is equal to Ptr we are analyzing the 201 // pointer, otherwise, we are analyzing the index. 202 Value *OrigPtr = Ptr; 203 204 // The size of the pointer access. 205 int64_t PtrAccessSize = 1; 206 207 Ptr = stripGetElementPtr(Ptr, SE, Lp); 208 const SCEV *V = SE->getSCEV(Ptr); 209 210 if (Ptr != OrigPtr) 211 // Strip off casts. 212 while (const SCEVIntegralCastExpr *C = dyn_cast<SCEVIntegralCastExpr>(V)) 213 V = C->getOperand(); 214 215 const SCEVAddRecExpr *S = dyn_cast<SCEVAddRecExpr>(V); 216 if (!S) 217 return nullptr; 218 219 V = S->getStepRecurrence(*SE); 220 if (!V) 221 return nullptr; 222 223 // Strip off the size of access multiplication if we are still analyzing the 224 // pointer. 225 if (OrigPtr == Ptr) { 226 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(V)) { 227 if (M->getOperand(0)->getSCEVType() != scConstant) 228 return nullptr; 229 230 const APInt &APStepVal = cast<SCEVConstant>(M->getOperand(0))->getAPInt(); 231 232 // Huge step value - give up. 233 if (APStepVal.getBitWidth() > 64) 234 return nullptr; 235 236 int64_t StepVal = APStepVal.getSExtValue(); 237 if (PtrAccessSize != StepVal) 238 return nullptr; 239 V = M->getOperand(1); 240 } 241 } 242 243 // Strip off casts. 244 Type *StripedOffRecurrenceCast = nullptr; 245 if (const SCEVIntegralCastExpr *C = dyn_cast<SCEVIntegralCastExpr>(V)) { 246 StripedOffRecurrenceCast = C->getType(); 247 V = C->getOperand(); 248 } 249 250 // Look for the loop invariant symbolic value. 251 const SCEVUnknown *U = dyn_cast<SCEVUnknown>(V); 252 if (!U) 253 return nullptr; 254 255 Value *Stride = U->getValue(); 256 if (!Lp->isLoopInvariant(Stride)) 257 return nullptr; 258 259 // If we have stripped off the recurrence cast we have to make sure that we 260 // return the value that is used in this loop so that we can replace it later. 261 if (StripedOffRecurrenceCast) 262 Stride = getUniqueCastUse(Stride, Lp, StripedOffRecurrenceCast); 263 264 return Stride; 265 } 266 267 /// Given a vector and an element number, see if the scalar value is 268 /// already around as a register, for example if it were inserted then extracted 269 /// from the vector. 270 Value *llvm::findScalarElement(Value *V, unsigned EltNo) { 271 assert(V->getType()->isVectorTy() && "Not looking at a vector?"); 272 VectorType *VTy = cast<VectorType>(V->getType()); 273 // For fixed-length vector, return undef for out of range access. 274 if (auto *FVTy = dyn_cast<FixedVectorType>(VTy)) { 275 unsigned Width = FVTy->getNumElements(); 276 if (EltNo >= Width) 277 return UndefValue::get(FVTy->getElementType()); 278 } 279 280 if (Constant *C = dyn_cast<Constant>(V)) 281 return C->getAggregateElement(EltNo); 282 283 if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) { 284 // If this is an insert to a variable element, we don't know what it is. 285 if (!isa<ConstantInt>(III->getOperand(2))) 286 return nullptr; 287 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue(); 288 289 // If this is an insert to the element we are looking for, return the 290 // inserted value. 291 if (EltNo == IIElt) 292 return III->getOperand(1); 293 294 // Guard against infinite loop on malformed, unreachable IR. 295 if (III == III->getOperand(0)) 296 return nullptr; 297 298 // Otherwise, the insertelement doesn't modify the value, recurse on its 299 // vector input. 300 return findScalarElement(III->getOperand(0), EltNo); 301 } 302 303 ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V); 304 // Restrict the following transformation to fixed-length vector. 305 if (SVI && isa<FixedVectorType>(SVI->getType())) { 306 unsigned LHSWidth = 307 cast<FixedVectorType>(SVI->getOperand(0)->getType())->getNumElements(); 308 int InEl = SVI->getMaskValue(EltNo); 309 if (InEl < 0) 310 return UndefValue::get(VTy->getElementType()); 311 if (InEl < (int)LHSWidth) 312 return findScalarElement(SVI->getOperand(0), InEl); 313 return findScalarElement(SVI->getOperand(1), InEl - LHSWidth); 314 } 315 316 // Extract a value from a vector add operation with a constant zero. 317 // TODO: Use getBinOpIdentity() to generalize this. 318 Value *Val; Constant *C; 319 if (match(V, m_Add(m_Value(Val), m_Constant(C)))) 320 if (Constant *Elt = C->getAggregateElement(EltNo)) 321 if (Elt->isNullValue()) 322 return findScalarElement(Val, EltNo); 323 324 // Otherwise, we don't know. 325 return nullptr; 326 } 327 328 int llvm::getSplatIndex(ArrayRef<int> Mask) { 329 int SplatIndex = -1; 330 for (int M : Mask) { 331 // Ignore invalid (undefined) mask elements. 332 if (M < 0) 333 continue; 334 335 // There can be only 1 non-negative mask element value if this is a splat. 336 if (SplatIndex != -1 && SplatIndex != M) 337 return -1; 338 339 // Initialize the splat index to the 1st non-negative mask element. 340 SplatIndex = M; 341 } 342 assert((SplatIndex == -1 || SplatIndex >= 0) && "Negative index?"); 343 return SplatIndex; 344 } 345 346 /// Get splat value if the input is a splat vector or return nullptr. 347 /// This function is not fully general. It checks only 2 cases: 348 /// the input value is (1) a splat constant vector or (2) a sequence 349 /// of instructions that broadcasts a scalar at element 0. 350 Value *llvm::getSplatValue(const Value *V) { 351 if (isa<VectorType>(V->getType())) 352 if (auto *C = dyn_cast<Constant>(V)) 353 return C->getSplatValue(); 354 355 // shuf (inselt ?, Splat, 0), ?, <0, undef, 0, ...> 356 Value *Splat; 357 if (match(V, 358 m_Shuffle(m_InsertElt(m_Value(), m_Value(Splat), m_ZeroInt()), 359 m_Value(), m_ZeroMask()))) 360 return Splat; 361 362 return nullptr; 363 } 364 365 bool llvm::isSplatValue(const Value *V, int Index, unsigned Depth) { 366 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth"); 367 368 if (isa<VectorType>(V->getType())) { 369 if (isa<UndefValue>(V)) 370 return true; 371 // FIXME: We can allow undefs, but if Index was specified, we may want to 372 // check that the constant is defined at that index. 373 if (auto *C = dyn_cast<Constant>(V)) 374 return C->getSplatValue() != nullptr; 375 } 376 377 if (auto *Shuf = dyn_cast<ShuffleVectorInst>(V)) { 378 // FIXME: We can safely allow undefs here. If Index was specified, we will 379 // check that the mask elt is defined at the required index. 380 if (!is_splat(Shuf->getShuffleMask())) 381 return false; 382 383 // Match any index. 384 if (Index == -1) 385 return true; 386 387 // Match a specific element. The mask should be defined at and match the 388 // specified index. 389 return Shuf->getMaskValue(Index) == Index; 390 } 391 392 // The remaining tests are all recursive, so bail out if we hit the limit. 393 if (Depth++ == MaxAnalysisRecursionDepth) 394 return false; 395 396 // If both operands of a binop are splats, the result is a splat. 397 Value *X, *Y, *Z; 398 if (match(V, m_BinOp(m_Value(X), m_Value(Y)))) 399 return isSplatValue(X, Index, Depth) && isSplatValue(Y, Index, Depth); 400 401 // If all operands of a select are splats, the result is a splat. 402 if (match(V, m_Select(m_Value(X), m_Value(Y), m_Value(Z)))) 403 return isSplatValue(X, Index, Depth) && isSplatValue(Y, Index, Depth) && 404 isSplatValue(Z, Index, Depth); 405 406 // TODO: Add support for unary ops (fneg), casts, intrinsics (overflow ops). 407 408 return false; 409 } 410 411 void llvm::narrowShuffleMaskElts(int Scale, ArrayRef<int> Mask, 412 SmallVectorImpl<int> &ScaledMask) { 413 assert(Scale > 0 && "Unexpected scaling factor"); 414 415 // Fast-path: if no scaling, then it is just a copy. 416 if (Scale == 1) { 417 ScaledMask.assign(Mask.begin(), Mask.end()); 418 return; 419 } 420 421 ScaledMask.clear(); 422 for (int MaskElt : Mask) { 423 if (MaskElt >= 0) { 424 assert(((uint64_t)Scale * MaskElt + (Scale - 1)) <= INT32_MAX && 425 "Overflowed 32-bits"); 426 } 427 for (int SliceElt = 0; SliceElt != Scale; ++SliceElt) 428 ScaledMask.push_back(MaskElt < 0 ? MaskElt : Scale * MaskElt + SliceElt); 429 } 430 } 431 432 bool llvm::widenShuffleMaskElts(int Scale, ArrayRef<int> Mask, 433 SmallVectorImpl<int> &ScaledMask) { 434 assert(Scale > 0 && "Unexpected scaling factor"); 435 436 // Fast-path: if no scaling, then it is just a copy. 437 if (Scale == 1) { 438 ScaledMask.assign(Mask.begin(), Mask.end()); 439 return true; 440 } 441 442 // We must map the original elements down evenly to a type with less elements. 443 int NumElts = Mask.size(); 444 if (NumElts % Scale != 0) 445 return false; 446 447 ScaledMask.clear(); 448 ScaledMask.reserve(NumElts / Scale); 449 450 // Step through the input mask by splitting into Scale-sized slices. 451 do { 452 ArrayRef<int> MaskSlice = Mask.take_front(Scale); 453 assert((int)MaskSlice.size() == Scale && "Expected Scale-sized slice."); 454 455 // The first element of the slice determines how we evaluate this slice. 456 int SliceFront = MaskSlice.front(); 457 if (SliceFront < 0) { 458 // Negative values (undef or other "sentinel" values) must be equal across 459 // the entire slice. 460 if (!is_splat(MaskSlice)) 461 return false; 462 ScaledMask.push_back(SliceFront); 463 } else { 464 // A positive mask element must be cleanly divisible. 465 if (SliceFront % Scale != 0) 466 return false; 467 // Elements of the slice must be consecutive. 468 for (int i = 1; i < Scale; ++i) 469 if (MaskSlice[i] != SliceFront + i) 470 return false; 471 ScaledMask.push_back(SliceFront / Scale); 472 } 473 Mask = Mask.drop_front(Scale); 474 } while (!Mask.empty()); 475 476 assert((int)ScaledMask.size() * Scale == NumElts && "Unexpected scaled mask"); 477 478 // All elements of the original mask can be scaled down to map to the elements 479 // of a mask with wider elements. 480 return true; 481 } 482 483 MapVector<Instruction *, uint64_t> 484 llvm::computeMinimumValueSizes(ArrayRef<BasicBlock *> Blocks, DemandedBits &DB, 485 const TargetTransformInfo *TTI) { 486 487 // DemandedBits will give us every value's live-out bits. But we want 488 // to ensure no extra casts would need to be inserted, so every DAG 489 // of connected values must have the same minimum bitwidth. 490 EquivalenceClasses<Value *> ECs; 491 SmallVector<Value *, 16> Worklist; 492 SmallPtrSet<Value *, 4> Roots; 493 SmallPtrSet<Value *, 16> Visited; 494 DenseMap<Value *, uint64_t> DBits; 495 SmallPtrSet<Instruction *, 4> InstructionSet; 496 MapVector<Instruction *, uint64_t> MinBWs; 497 498 // Determine the roots. We work bottom-up, from truncs or icmps. 499 bool SeenExtFromIllegalType = false; 500 for (auto *BB : Blocks) 501 for (auto &I : *BB) { 502 InstructionSet.insert(&I); 503 504 if (TTI && (isa<ZExtInst>(&I) || isa<SExtInst>(&I)) && 505 !TTI->isTypeLegal(I.getOperand(0)->getType())) 506 SeenExtFromIllegalType = true; 507 508 // Only deal with non-vector integers up to 64-bits wide. 509 if ((isa<TruncInst>(&I) || isa<ICmpInst>(&I)) && 510 !I.getType()->isVectorTy() && 511 I.getOperand(0)->getType()->getScalarSizeInBits() <= 64) { 512 // Don't make work for ourselves. If we know the loaded type is legal, 513 // don't add it to the worklist. 514 if (TTI && isa<TruncInst>(&I) && TTI->isTypeLegal(I.getType())) 515 continue; 516 517 Worklist.push_back(&I); 518 Roots.insert(&I); 519 } 520 } 521 // Early exit. 522 if (Worklist.empty() || (TTI && !SeenExtFromIllegalType)) 523 return MinBWs; 524 525 // Now proceed breadth-first, unioning values together. 526 while (!Worklist.empty()) { 527 Value *Val = Worklist.pop_back_val(); 528 Value *Leader = ECs.getOrInsertLeaderValue(Val); 529 530 if (Visited.count(Val)) 531 continue; 532 Visited.insert(Val); 533 534 // Non-instructions terminate a chain successfully. 535 if (!isa<Instruction>(Val)) 536 continue; 537 Instruction *I = cast<Instruction>(Val); 538 539 // If we encounter a type that is larger than 64 bits, we can't represent 540 // it so bail out. 541 if (DB.getDemandedBits(I).getBitWidth() > 64) 542 return MapVector<Instruction *, uint64_t>(); 543 544 uint64_t V = DB.getDemandedBits(I).getZExtValue(); 545 DBits[Leader] |= V; 546 DBits[I] = V; 547 548 // Casts, loads and instructions outside of our range terminate a chain 549 // successfully. 550 if (isa<SExtInst>(I) || isa<ZExtInst>(I) || isa<LoadInst>(I) || 551 !InstructionSet.count(I)) 552 continue; 553 554 // Unsafe casts terminate a chain unsuccessfully. We can't do anything 555 // useful with bitcasts, ptrtoints or inttoptrs and it'd be unsafe to 556 // transform anything that relies on them. 557 if (isa<BitCastInst>(I) || isa<PtrToIntInst>(I) || isa<IntToPtrInst>(I) || 558 !I->getType()->isIntegerTy()) { 559 DBits[Leader] |= ~0ULL; 560 continue; 561 } 562 563 // We don't modify the types of PHIs. Reductions will already have been 564 // truncated if possible, and inductions' sizes will have been chosen by 565 // indvars. 566 if (isa<PHINode>(I)) 567 continue; 568 569 if (DBits[Leader] == ~0ULL) 570 // All bits demanded, no point continuing. 571 continue; 572 573 for (Value *O : cast<User>(I)->operands()) { 574 ECs.unionSets(Leader, O); 575 Worklist.push_back(O); 576 } 577 } 578 579 // Now we've discovered all values, walk them to see if there are 580 // any users we didn't see. If there are, we can't optimize that 581 // chain. 582 for (auto &I : DBits) 583 for (auto *U : I.first->users()) 584 if (U->getType()->isIntegerTy() && DBits.count(U) == 0) 585 DBits[ECs.getOrInsertLeaderValue(I.first)] |= ~0ULL; 586 587 for (auto I = ECs.begin(), E = ECs.end(); I != E; ++I) { 588 uint64_t LeaderDemandedBits = 0; 589 for (Value *M : llvm::make_range(ECs.member_begin(I), ECs.member_end())) 590 LeaderDemandedBits |= DBits[M]; 591 592 uint64_t MinBW = (sizeof(LeaderDemandedBits) * 8) - 593 llvm::countLeadingZeros(LeaderDemandedBits); 594 // Round up to a power of 2 595 if (!isPowerOf2_64((uint64_t)MinBW)) 596 MinBW = NextPowerOf2(MinBW); 597 598 // We don't modify the types of PHIs. Reductions will already have been 599 // truncated if possible, and inductions' sizes will have been chosen by 600 // indvars. 601 // If we are required to shrink a PHI, abandon this entire equivalence class. 602 bool Abort = false; 603 for (Value *M : llvm::make_range(ECs.member_begin(I), ECs.member_end())) 604 if (isa<PHINode>(M) && MinBW < M->getType()->getScalarSizeInBits()) { 605 Abort = true; 606 break; 607 } 608 if (Abort) 609 continue; 610 611 for (Value *M : llvm::make_range(ECs.member_begin(I), ECs.member_end())) { 612 if (!isa<Instruction>(M)) 613 continue; 614 Type *Ty = M->getType(); 615 if (Roots.count(M)) 616 Ty = cast<Instruction>(M)->getOperand(0)->getType(); 617 if (MinBW < Ty->getScalarSizeInBits()) 618 MinBWs[cast<Instruction>(M)] = MinBW; 619 } 620 } 621 622 return MinBWs; 623 } 624 625 /// Add all access groups in @p AccGroups to @p List. 626 template <typename ListT> 627 static void addToAccessGroupList(ListT &List, MDNode *AccGroups) { 628 // Interpret an access group as a list containing itself. 629 if (AccGroups->getNumOperands() == 0) { 630 assert(isValidAsAccessGroup(AccGroups) && "Node must be an access group"); 631 List.insert(AccGroups); 632 return; 633 } 634 635 for (auto &AccGroupListOp : AccGroups->operands()) { 636 auto *Item = cast<MDNode>(AccGroupListOp.get()); 637 assert(isValidAsAccessGroup(Item) && "List item must be an access group"); 638 List.insert(Item); 639 } 640 } 641 642 MDNode *llvm::uniteAccessGroups(MDNode *AccGroups1, MDNode *AccGroups2) { 643 if (!AccGroups1) 644 return AccGroups2; 645 if (!AccGroups2) 646 return AccGroups1; 647 if (AccGroups1 == AccGroups2) 648 return AccGroups1; 649 650 SmallSetVector<Metadata *, 4> Union; 651 addToAccessGroupList(Union, AccGroups1); 652 addToAccessGroupList(Union, AccGroups2); 653 654 if (Union.size() == 0) 655 return nullptr; 656 if (Union.size() == 1) 657 return cast<MDNode>(Union.front()); 658 659 LLVMContext &Ctx = AccGroups1->getContext(); 660 return MDNode::get(Ctx, Union.getArrayRef()); 661 } 662 663 MDNode *llvm::intersectAccessGroups(const Instruction *Inst1, 664 const Instruction *Inst2) { 665 bool MayAccessMem1 = Inst1->mayReadOrWriteMemory(); 666 bool MayAccessMem2 = Inst2->mayReadOrWriteMemory(); 667 668 if (!MayAccessMem1 && !MayAccessMem2) 669 return nullptr; 670 if (!MayAccessMem1) 671 return Inst2->getMetadata(LLVMContext::MD_access_group); 672 if (!MayAccessMem2) 673 return Inst1->getMetadata(LLVMContext::MD_access_group); 674 675 MDNode *MD1 = Inst1->getMetadata(LLVMContext::MD_access_group); 676 MDNode *MD2 = Inst2->getMetadata(LLVMContext::MD_access_group); 677 if (!MD1 || !MD2) 678 return nullptr; 679 if (MD1 == MD2) 680 return MD1; 681 682 // Use set for scalable 'contains' check. 683 SmallPtrSet<Metadata *, 4> AccGroupSet2; 684 addToAccessGroupList(AccGroupSet2, MD2); 685 686 SmallVector<Metadata *, 4> Intersection; 687 if (MD1->getNumOperands() == 0) { 688 assert(isValidAsAccessGroup(MD1) && "Node must be an access group"); 689 if (AccGroupSet2.count(MD1)) 690 Intersection.push_back(MD1); 691 } else { 692 for (const MDOperand &Node : MD1->operands()) { 693 auto *Item = cast<MDNode>(Node.get()); 694 assert(isValidAsAccessGroup(Item) && "List item must be an access group"); 695 if (AccGroupSet2.count(Item)) 696 Intersection.push_back(Item); 697 } 698 } 699 700 if (Intersection.size() == 0) 701 return nullptr; 702 if (Intersection.size() == 1) 703 return cast<MDNode>(Intersection.front()); 704 705 LLVMContext &Ctx = Inst1->getContext(); 706 return MDNode::get(Ctx, Intersection); 707 } 708 709 /// \returns \p I after propagating metadata from \p VL. 710 Instruction *llvm::propagateMetadata(Instruction *Inst, ArrayRef<Value *> VL) { 711 if (VL.empty()) 712 return Inst; 713 Instruction *I0 = cast<Instruction>(VL[0]); 714 SmallVector<std::pair<unsigned, MDNode *>, 4> Metadata; 715 I0->getAllMetadataOtherThanDebugLoc(Metadata); 716 717 for (auto Kind : {LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope, 718 LLVMContext::MD_noalias, LLVMContext::MD_fpmath, 719 LLVMContext::MD_nontemporal, LLVMContext::MD_invariant_load, 720 LLVMContext::MD_access_group}) { 721 MDNode *MD = I0->getMetadata(Kind); 722 723 for (int J = 1, E = VL.size(); MD && J != E; ++J) { 724 const Instruction *IJ = cast<Instruction>(VL[J]); 725 MDNode *IMD = IJ->getMetadata(Kind); 726 switch (Kind) { 727 case LLVMContext::MD_tbaa: 728 MD = MDNode::getMostGenericTBAA(MD, IMD); 729 break; 730 case LLVMContext::MD_alias_scope: 731 MD = MDNode::getMostGenericAliasScope(MD, IMD); 732 break; 733 case LLVMContext::MD_fpmath: 734 MD = MDNode::getMostGenericFPMath(MD, IMD); 735 break; 736 case LLVMContext::MD_noalias: 737 case LLVMContext::MD_nontemporal: 738 case LLVMContext::MD_invariant_load: 739 MD = MDNode::intersect(MD, IMD); 740 break; 741 case LLVMContext::MD_access_group: 742 MD = intersectAccessGroups(Inst, IJ); 743 break; 744 default: 745 llvm_unreachable("unhandled metadata"); 746 } 747 } 748 749 Inst->setMetadata(Kind, MD); 750 } 751 752 return Inst; 753 } 754 755 Constant * 756 llvm::createBitMaskForGaps(IRBuilderBase &Builder, unsigned VF, 757 const InterleaveGroup<Instruction> &Group) { 758 // All 1's means mask is not needed. 759 if (Group.getNumMembers() == Group.getFactor()) 760 return nullptr; 761 762 // TODO: support reversed access. 763 assert(!Group.isReverse() && "Reversed group not supported."); 764 765 SmallVector<Constant *, 16> Mask; 766 for (unsigned i = 0; i < VF; i++) 767 for (unsigned j = 0; j < Group.getFactor(); ++j) { 768 unsigned HasMember = Group.getMember(j) ? 1 : 0; 769 Mask.push_back(Builder.getInt1(HasMember)); 770 } 771 772 return ConstantVector::get(Mask); 773 } 774 775 llvm::SmallVector<int, 16> 776 llvm::createReplicatedMask(unsigned ReplicationFactor, unsigned VF) { 777 SmallVector<int, 16> MaskVec; 778 for (unsigned i = 0; i < VF; i++) 779 for (unsigned j = 0; j < ReplicationFactor; j++) 780 MaskVec.push_back(i); 781 782 return MaskVec; 783 } 784 785 llvm::SmallVector<int, 16> llvm::createInterleaveMask(unsigned VF, 786 unsigned NumVecs) { 787 SmallVector<int, 16> Mask; 788 for (unsigned i = 0; i < VF; i++) 789 for (unsigned j = 0; j < NumVecs; j++) 790 Mask.push_back(j * VF + i); 791 792 return Mask; 793 } 794 795 llvm::SmallVector<int, 16> 796 llvm::createStrideMask(unsigned Start, unsigned Stride, unsigned VF) { 797 SmallVector<int, 16> Mask; 798 for (unsigned i = 0; i < VF; i++) 799 Mask.push_back(Start + i * Stride); 800 801 return Mask; 802 } 803 804 llvm::SmallVector<int, 16> llvm::createSequentialMask(unsigned Start, 805 unsigned NumInts, 806 unsigned NumUndefs) { 807 SmallVector<int, 16> Mask; 808 for (unsigned i = 0; i < NumInts; i++) 809 Mask.push_back(Start + i); 810 811 for (unsigned i = 0; i < NumUndefs; i++) 812 Mask.push_back(-1); 813 814 return Mask; 815 } 816 817 /// A helper function for concatenating vectors. This function concatenates two 818 /// vectors having the same element type. If the second vector has fewer 819 /// elements than the first, it is padded with undefs. 820 static Value *concatenateTwoVectors(IRBuilderBase &Builder, Value *V1, 821 Value *V2) { 822 VectorType *VecTy1 = dyn_cast<VectorType>(V1->getType()); 823 VectorType *VecTy2 = dyn_cast<VectorType>(V2->getType()); 824 assert(VecTy1 && VecTy2 && 825 VecTy1->getScalarType() == VecTy2->getScalarType() && 826 "Expect two vectors with the same element type"); 827 828 unsigned NumElts1 = cast<FixedVectorType>(VecTy1)->getNumElements(); 829 unsigned NumElts2 = cast<FixedVectorType>(VecTy2)->getNumElements(); 830 assert(NumElts1 >= NumElts2 && "Unexpect the first vector has less elements"); 831 832 if (NumElts1 > NumElts2) { 833 // Extend with UNDEFs. 834 V2 = Builder.CreateShuffleVector( 835 V2, createSequentialMask(0, NumElts2, NumElts1 - NumElts2)); 836 } 837 838 return Builder.CreateShuffleVector( 839 V1, V2, createSequentialMask(0, NumElts1 + NumElts2, 0)); 840 } 841 842 Value *llvm::concatenateVectors(IRBuilderBase &Builder, 843 ArrayRef<Value *> Vecs) { 844 unsigned NumVecs = Vecs.size(); 845 assert(NumVecs > 1 && "Should be at least two vectors"); 846 847 SmallVector<Value *, 8> ResList; 848 ResList.append(Vecs.begin(), Vecs.end()); 849 do { 850 SmallVector<Value *, 8> TmpList; 851 for (unsigned i = 0; i < NumVecs - 1; i += 2) { 852 Value *V0 = ResList[i], *V1 = ResList[i + 1]; 853 assert((V0->getType() == V1->getType() || i == NumVecs - 2) && 854 "Only the last vector may have a different type"); 855 856 TmpList.push_back(concatenateTwoVectors(Builder, V0, V1)); 857 } 858 859 // Push the last vector if the total number of vectors is odd. 860 if (NumVecs % 2 != 0) 861 TmpList.push_back(ResList[NumVecs - 1]); 862 863 ResList = TmpList; 864 NumVecs = ResList.size(); 865 } while (NumVecs > 1); 866 867 return ResList[0]; 868 } 869 870 bool llvm::maskIsAllZeroOrUndef(Value *Mask) { 871 assert(isa<VectorType>(Mask->getType()) && 872 isa<IntegerType>(Mask->getType()->getScalarType()) && 873 cast<IntegerType>(Mask->getType()->getScalarType())->getBitWidth() == 874 1 && 875 "Mask must be a vector of i1"); 876 877 auto *ConstMask = dyn_cast<Constant>(Mask); 878 if (!ConstMask) 879 return false; 880 if (ConstMask->isNullValue() || isa<UndefValue>(ConstMask)) 881 return true; 882 if (isa<ScalableVectorType>(ConstMask->getType())) 883 return false; 884 for (unsigned 885 I = 0, 886 E = cast<FixedVectorType>(ConstMask->getType())->getNumElements(); 887 I != E; ++I) { 888 if (auto *MaskElt = ConstMask->getAggregateElement(I)) 889 if (MaskElt->isNullValue() || isa<UndefValue>(MaskElt)) 890 continue; 891 return false; 892 } 893 return true; 894 } 895 896 897 bool llvm::maskIsAllOneOrUndef(Value *Mask) { 898 assert(isa<VectorType>(Mask->getType()) && 899 isa<IntegerType>(Mask->getType()->getScalarType()) && 900 cast<IntegerType>(Mask->getType()->getScalarType())->getBitWidth() == 901 1 && 902 "Mask must be a vector of i1"); 903 904 auto *ConstMask = dyn_cast<Constant>(Mask); 905 if (!ConstMask) 906 return false; 907 if (ConstMask->isAllOnesValue() || isa<UndefValue>(ConstMask)) 908 return true; 909 if (isa<ScalableVectorType>(ConstMask->getType())) 910 return false; 911 for (unsigned 912 I = 0, 913 E = cast<FixedVectorType>(ConstMask->getType())->getNumElements(); 914 I != E; ++I) { 915 if (auto *MaskElt = ConstMask->getAggregateElement(I)) 916 if (MaskElt->isAllOnesValue() || isa<UndefValue>(MaskElt)) 917 continue; 918 return false; 919 } 920 return true; 921 } 922 923 /// TODO: This is a lot like known bits, but for 924 /// vectors. Is there something we can common this with? 925 APInt llvm::possiblyDemandedEltsInMask(Value *Mask) { 926 assert(isa<FixedVectorType>(Mask->getType()) && 927 isa<IntegerType>(Mask->getType()->getScalarType()) && 928 cast<IntegerType>(Mask->getType()->getScalarType())->getBitWidth() == 929 1 && 930 "Mask must be a fixed width vector of i1"); 931 932 const unsigned VWidth = 933 cast<FixedVectorType>(Mask->getType())->getNumElements(); 934 APInt DemandedElts = APInt::getAllOnesValue(VWidth); 935 if (auto *CV = dyn_cast<ConstantVector>(Mask)) 936 for (unsigned i = 0; i < VWidth; i++) 937 if (CV->getAggregateElement(i)->isNullValue()) 938 DemandedElts.clearBit(i); 939 return DemandedElts; 940 } 941 942 bool InterleavedAccessInfo::isStrided(int Stride) { 943 unsigned Factor = std::abs(Stride); 944 return Factor >= 2 && Factor <= MaxInterleaveGroupFactor; 945 } 946 947 void InterleavedAccessInfo::collectConstStrideAccesses( 948 MapVector<Instruction *, StrideDescriptor> &AccessStrideInfo, 949 const ValueToValueMap &Strides) { 950 auto &DL = TheLoop->getHeader()->getModule()->getDataLayout(); 951 952 // Since it's desired that the load/store instructions be maintained in 953 // "program order" for the interleaved access analysis, we have to visit the 954 // blocks in the loop in reverse postorder (i.e., in a topological order). 955 // Such an ordering will ensure that any load/store that may be executed 956 // before a second load/store will precede the second load/store in 957 // AccessStrideInfo. 958 LoopBlocksDFS DFS(TheLoop); 959 DFS.perform(LI); 960 for (BasicBlock *BB : make_range(DFS.beginRPO(), DFS.endRPO())) 961 for (auto &I : *BB) { 962 auto *LI = dyn_cast<LoadInst>(&I); 963 auto *SI = dyn_cast<StoreInst>(&I); 964 if (!LI && !SI) 965 continue; 966 967 Value *Ptr = getLoadStorePointerOperand(&I); 968 // We don't check wrapping here because we don't know yet if Ptr will be 969 // part of a full group or a group with gaps. Checking wrapping for all 970 // pointers (even those that end up in groups with no gaps) will be overly 971 // conservative. For full groups, wrapping should be ok since if we would 972 // wrap around the address space we would do a memory access at nullptr 973 // even without the transformation. The wrapping checks are therefore 974 // deferred until after we've formed the interleaved groups. 975 int64_t Stride = getPtrStride(PSE, Ptr, TheLoop, Strides, 976 /*Assume=*/true, /*ShouldCheckWrap=*/false); 977 978 const SCEV *Scev = replaceSymbolicStrideSCEV(PSE, Strides, Ptr); 979 PointerType *PtrTy = cast<PointerType>(Ptr->getType()); 980 uint64_t Size = DL.getTypeAllocSize(PtrTy->getElementType()); 981 AccessStrideInfo[&I] = StrideDescriptor(Stride, Scev, Size, 982 getLoadStoreAlignment(&I)); 983 } 984 } 985 986 // Analyze interleaved accesses and collect them into interleaved load and 987 // store groups. 988 // 989 // When generating code for an interleaved load group, we effectively hoist all 990 // loads in the group to the location of the first load in program order. When 991 // generating code for an interleaved store group, we sink all stores to the 992 // location of the last store. This code motion can change the order of load 993 // and store instructions and may break dependences. 994 // 995 // The code generation strategy mentioned above ensures that we won't violate 996 // any write-after-read (WAR) dependences. 997 // 998 // E.g., for the WAR dependence: a = A[i]; // (1) 999 // A[i] = b; // (2) 1000 // 1001 // The store group of (2) is always inserted at or below (2), and the load 1002 // group of (1) is always inserted at or above (1). Thus, the instructions will 1003 // never be reordered. All other dependences are checked to ensure the 1004 // correctness of the instruction reordering. 1005 // 1006 // The algorithm visits all memory accesses in the loop in bottom-up program 1007 // order. Program order is established by traversing the blocks in the loop in 1008 // reverse postorder when collecting the accesses. 1009 // 1010 // We visit the memory accesses in bottom-up order because it can simplify the 1011 // construction of store groups in the presence of write-after-write (WAW) 1012 // dependences. 1013 // 1014 // E.g., for the WAW dependence: A[i] = a; // (1) 1015 // A[i] = b; // (2) 1016 // A[i + 1] = c; // (3) 1017 // 1018 // We will first create a store group with (3) and (2). (1) can't be added to 1019 // this group because it and (2) are dependent. However, (1) can be grouped 1020 // with other accesses that may precede it in program order. Note that a 1021 // bottom-up order does not imply that WAW dependences should not be checked. 1022 void InterleavedAccessInfo::analyzeInterleaving( 1023 bool EnablePredicatedInterleavedMemAccesses) { 1024 LLVM_DEBUG(dbgs() << "LV: Analyzing interleaved accesses...\n"); 1025 const ValueToValueMap &Strides = LAI->getSymbolicStrides(); 1026 1027 // Holds all accesses with a constant stride. 1028 MapVector<Instruction *, StrideDescriptor> AccessStrideInfo; 1029 collectConstStrideAccesses(AccessStrideInfo, Strides); 1030 1031 if (AccessStrideInfo.empty()) 1032 return; 1033 1034 // Collect the dependences in the loop. 1035 collectDependences(); 1036 1037 // Holds all interleaved store groups temporarily. 1038 SmallSetVector<InterleaveGroup<Instruction> *, 4> StoreGroups; 1039 // Holds all interleaved load groups temporarily. 1040 SmallSetVector<InterleaveGroup<Instruction> *, 4> LoadGroups; 1041 1042 // Search in bottom-up program order for pairs of accesses (A and B) that can 1043 // form interleaved load or store groups. In the algorithm below, access A 1044 // precedes access B in program order. We initialize a group for B in the 1045 // outer loop of the algorithm, and then in the inner loop, we attempt to 1046 // insert each A into B's group if: 1047 // 1048 // 1. A and B have the same stride, 1049 // 2. A and B have the same memory object size, and 1050 // 3. A belongs in B's group according to its distance from B. 1051 // 1052 // Special care is taken to ensure group formation will not break any 1053 // dependences. 1054 for (auto BI = AccessStrideInfo.rbegin(), E = AccessStrideInfo.rend(); 1055 BI != E; ++BI) { 1056 Instruction *B = BI->first; 1057 StrideDescriptor DesB = BI->second; 1058 1059 // Initialize a group for B if it has an allowable stride. Even if we don't 1060 // create a group for B, we continue with the bottom-up algorithm to ensure 1061 // we don't break any of B's dependences. 1062 InterleaveGroup<Instruction> *Group = nullptr; 1063 if (isStrided(DesB.Stride) && 1064 (!isPredicated(B->getParent()) || EnablePredicatedInterleavedMemAccesses)) { 1065 Group = getInterleaveGroup(B); 1066 if (!Group) { 1067 LLVM_DEBUG(dbgs() << "LV: Creating an interleave group with:" << *B 1068 << '\n'); 1069 Group = createInterleaveGroup(B, DesB.Stride, DesB.Alignment); 1070 } 1071 if (B->mayWriteToMemory()) 1072 StoreGroups.insert(Group); 1073 else 1074 LoadGroups.insert(Group); 1075 } 1076 1077 for (auto AI = std::next(BI); AI != E; ++AI) { 1078 Instruction *A = AI->first; 1079 StrideDescriptor DesA = AI->second; 1080 1081 // Our code motion strategy implies that we can't have dependences 1082 // between accesses in an interleaved group and other accesses located 1083 // between the first and last member of the group. Note that this also 1084 // means that a group can't have more than one member at a given offset. 1085 // The accesses in a group can have dependences with other accesses, but 1086 // we must ensure we don't extend the boundaries of the group such that 1087 // we encompass those dependent accesses. 1088 // 1089 // For example, assume we have the sequence of accesses shown below in a 1090 // stride-2 loop: 1091 // 1092 // (1, 2) is a group | A[i] = a; // (1) 1093 // | A[i-1] = b; // (2) | 1094 // A[i-3] = c; // (3) 1095 // A[i] = d; // (4) | (2, 4) is not a group 1096 // 1097 // Because accesses (2) and (3) are dependent, we can group (2) with (1) 1098 // but not with (4). If we did, the dependent access (3) would be within 1099 // the boundaries of the (2, 4) group. 1100 if (!canReorderMemAccessesForInterleavedGroups(&*AI, &*BI)) { 1101 // If a dependence exists and A is already in a group, we know that A 1102 // must be a store since A precedes B and WAR dependences are allowed. 1103 // Thus, A would be sunk below B. We release A's group to prevent this 1104 // illegal code motion. A will then be free to form another group with 1105 // instructions that precede it. 1106 if (isInterleaved(A)) { 1107 InterleaveGroup<Instruction> *StoreGroup = getInterleaveGroup(A); 1108 1109 LLVM_DEBUG(dbgs() << "LV: Invalidated store group due to " 1110 "dependence between " << *A << " and "<< *B << '\n'); 1111 1112 StoreGroups.remove(StoreGroup); 1113 releaseGroup(StoreGroup); 1114 } 1115 1116 // If a dependence exists and A is not already in a group (or it was 1117 // and we just released it), B might be hoisted above A (if B is a 1118 // load) or another store might be sunk below A (if B is a store). In 1119 // either case, we can't add additional instructions to B's group. B 1120 // will only form a group with instructions that it precedes. 1121 break; 1122 } 1123 1124 // At this point, we've checked for illegal code motion. If either A or B 1125 // isn't strided, there's nothing left to do. 1126 if (!isStrided(DesA.Stride) || !isStrided(DesB.Stride)) 1127 continue; 1128 1129 // Ignore A if it's already in a group or isn't the same kind of memory 1130 // operation as B. 1131 // Note that mayReadFromMemory() isn't mutually exclusive to 1132 // mayWriteToMemory in the case of atomic loads. We shouldn't see those 1133 // here, canVectorizeMemory() should have returned false - except for the 1134 // case we asked for optimization remarks. 1135 if (isInterleaved(A) || 1136 (A->mayReadFromMemory() != B->mayReadFromMemory()) || 1137 (A->mayWriteToMemory() != B->mayWriteToMemory())) 1138 continue; 1139 1140 // Check rules 1 and 2. Ignore A if its stride or size is different from 1141 // that of B. 1142 if (DesA.Stride != DesB.Stride || DesA.Size != DesB.Size) 1143 continue; 1144 1145 // Ignore A if the memory object of A and B don't belong to the same 1146 // address space 1147 if (getLoadStoreAddressSpace(A) != getLoadStoreAddressSpace(B)) 1148 continue; 1149 1150 // Calculate the distance from A to B. 1151 const SCEVConstant *DistToB = dyn_cast<SCEVConstant>( 1152 PSE.getSE()->getMinusSCEV(DesA.Scev, DesB.Scev)); 1153 if (!DistToB) 1154 continue; 1155 int64_t DistanceToB = DistToB->getAPInt().getSExtValue(); 1156 1157 // Check rule 3. Ignore A if its distance to B is not a multiple of the 1158 // size. 1159 if (DistanceToB % static_cast<int64_t>(DesB.Size)) 1160 continue; 1161 1162 // All members of a predicated interleave-group must have the same predicate, 1163 // and currently must reside in the same BB. 1164 BasicBlock *BlockA = A->getParent(); 1165 BasicBlock *BlockB = B->getParent(); 1166 if ((isPredicated(BlockA) || isPredicated(BlockB)) && 1167 (!EnablePredicatedInterleavedMemAccesses || BlockA != BlockB)) 1168 continue; 1169 1170 // The index of A is the index of B plus A's distance to B in multiples 1171 // of the size. 1172 int IndexA = 1173 Group->getIndex(B) + DistanceToB / static_cast<int64_t>(DesB.Size); 1174 1175 // Try to insert A into B's group. 1176 if (Group->insertMember(A, IndexA, DesA.Alignment)) { 1177 LLVM_DEBUG(dbgs() << "LV: Inserted:" << *A << '\n' 1178 << " into the interleave group with" << *B 1179 << '\n'); 1180 InterleaveGroupMap[A] = Group; 1181 1182 // Set the first load in program order as the insert position. 1183 if (A->mayReadFromMemory()) 1184 Group->setInsertPos(A); 1185 } 1186 } // Iteration over A accesses. 1187 } // Iteration over B accesses. 1188 1189 // Remove interleaved store groups with gaps. 1190 for (auto *Group : StoreGroups) 1191 if (Group->getNumMembers() != Group->getFactor()) { 1192 LLVM_DEBUG( 1193 dbgs() << "LV: Invalidate candidate interleaved store group due " 1194 "to gaps.\n"); 1195 releaseGroup(Group); 1196 } 1197 // Remove interleaved groups with gaps (currently only loads) whose memory 1198 // accesses may wrap around. We have to revisit the getPtrStride analysis, 1199 // this time with ShouldCheckWrap=true, since collectConstStrideAccesses does 1200 // not check wrapping (see documentation there). 1201 // FORNOW we use Assume=false; 1202 // TODO: Change to Assume=true but making sure we don't exceed the threshold 1203 // of runtime SCEV assumptions checks (thereby potentially failing to 1204 // vectorize altogether). 1205 // Additional optional optimizations: 1206 // TODO: If we are peeling the loop and we know that the first pointer doesn't 1207 // wrap then we can deduce that all pointers in the group don't wrap. 1208 // This means that we can forcefully peel the loop in order to only have to 1209 // check the first pointer for no-wrap. When we'll change to use Assume=true 1210 // we'll only need at most one runtime check per interleaved group. 1211 for (auto *Group : LoadGroups) { 1212 // Case 1: A full group. Can Skip the checks; For full groups, if the wide 1213 // load would wrap around the address space we would do a memory access at 1214 // nullptr even without the transformation. 1215 if (Group->getNumMembers() == Group->getFactor()) 1216 continue; 1217 1218 // Case 2: If first and last members of the group don't wrap this implies 1219 // that all the pointers in the group don't wrap. 1220 // So we check only group member 0 (which is always guaranteed to exist), 1221 // and group member Factor - 1; If the latter doesn't exist we rely on 1222 // peeling (if it is a non-reversed accsess -- see Case 3). 1223 Value *FirstMemberPtr = getLoadStorePointerOperand(Group->getMember(0)); 1224 if (!getPtrStride(PSE, FirstMemberPtr, TheLoop, Strides, /*Assume=*/false, 1225 /*ShouldCheckWrap=*/true)) { 1226 LLVM_DEBUG( 1227 dbgs() << "LV: Invalidate candidate interleaved group due to " 1228 "first group member potentially pointer-wrapping.\n"); 1229 releaseGroup(Group); 1230 continue; 1231 } 1232 Instruction *LastMember = Group->getMember(Group->getFactor() - 1); 1233 if (LastMember) { 1234 Value *LastMemberPtr = getLoadStorePointerOperand(LastMember); 1235 if (!getPtrStride(PSE, LastMemberPtr, TheLoop, Strides, /*Assume=*/false, 1236 /*ShouldCheckWrap=*/true)) { 1237 LLVM_DEBUG( 1238 dbgs() << "LV: Invalidate candidate interleaved group due to " 1239 "last group member potentially pointer-wrapping.\n"); 1240 releaseGroup(Group); 1241 } 1242 } else { 1243 // Case 3: A non-reversed interleaved load group with gaps: We need 1244 // to execute at least one scalar epilogue iteration. This will ensure 1245 // we don't speculatively access memory out-of-bounds. We only need 1246 // to look for a member at index factor - 1, since every group must have 1247 // a member at index zero. 1248 if (Group->isReverse()) { 1249 LLVM_DEBUG( 1250 dbgs() << "LV: Invalidate candidate interleaved group due to " 1251 "a reverse access with gaps.\n"); 1252 releaseGroup(Group); 1253 continue; 1254 } 1255 LLVM_DEBUG( 1256 dbgs() << "LV: Interleaved group requires epilogue iteration.\n"); 1257 RequiresScalarEpilogue = true; 1258 } 1259 } 1260 } 1261 1262 void InterleavedAccessInfo::invalidateGroupsRequiringScalarEpilogue() { 1263 // If no group had triggered the requirement to create an epilogue loop, 1264 // there is nothing to do. 1265 if (!requiresScalarEpilogue()) 1266 return; 1267 1268 bool ReleasedGroup = false; 1269 // Release groups requiring scalar epilogues. Note that this also removes them 1270 // from InterleaveGroups. 1271 for (auto *Group : make_early_inc_range(InterleaveGroups)) { 1272 if (!Group->requiresScalarEpilogue()) 1273 continue; 1274 LLVM_DEBUG( 1275 dbgs() 1276 << "LV: Invalidate candidate interleaved group due to gaps that " 1277 "require a scalar epilogue (not allowed under optsize) and cannot " 1278 "be masked (not enabled). \n"); 1279 releaseGroup(Group); 1280 ReleasedGroup = true; 1281 } 1282 assert(ReleasedGroup && "At least one group must be invalidated, as a " 1283 "scalar epilogue was required"); 1284 (void)ReleasedGroup; 1285 RequiresScalarEpilogue = false; 1286 } 1287 1288 template <typename InstT> 1289 void InterleaveGroup<InstT>::addMetadata(InstT *NewInst) const { 1290 llvm_unreachable("addMetadata can only be used for Instruction"); 1291 } 1292 1293 namespace llvm { 1294 template <> 1295 void InterleaveGroup<Instruction>::addMetadata(Instruction *NewInst) const { 1296 SmallVector<Value *, 4> VL; 1297 std::transform(Members.begin(), Members.end(), std::back_inserter(VL), 1298 [](std::pair<int, Instruction *> p) { return p.second; }); 1299 propagateMetadata(NewInst, VL); 1300 } 1301 } 1302 1303 std::string VFABI::mangleTLIVectorName(StringRef VectorName, 1304 StringRef ScalarName, unsigned numArgs, 1305 ElementCount VF) { 1306 SmallString<256> Buffer; 1307 llvm::raw_svector_ostream Out(Buffer); 1308 Out << "_ZGV" << VFABI::_LLVM_ << "N"; 1309 if (VF.isScalable()) 1310 Out << 'x'; 1311 else 1312 Out << VF.getFixedValue(); 1313 for (unsigned I = 0; I < numArgs; ++I) 1314 Out << "v"; 1315 Out << "_" << ScalarName << "(" << VectorName << ")"; 1316 return std::string(Out.str()); 1317 } 1318 1319 void VFABI::getVectorVariantNames( 1320 const CallInst &CI, SmallVectorImpl<std::string> &VariantMappings) { 1321 const StringRef S = 1322 CI.getAttribute(AttributeList::FunctionIndex, VFABI::MappingsAttrName) 1323 .getValueAsString(); 1324 if (S.empty()) 1325 return; 1326 1327 SmallVector<StringRef, 8> ListAttr; 1328 S.split(ListAttr, ","); 1329 1330 for (auto &S : SetVector<StringRef>(ListAttr.begin(), ListAttr.end())) { 1331 #ifndef NDEBUG 1332 LLVM_DEBUG(dbgs() << "VFABI: adding mapping '" << S << "'\n"); 1333 Optional<VFInfo> Info = VFABI::tryDemangleForVFABI(S, *(CI.getModule())); 1334 assert(Info.hasValue() && "Invalid name for a VFABI variant."); 1335 assert(CI.getModule()->getFunction(Info.getValue().VectorName) && 1336 "Vector function is missing."); 1337 #endif 1338 VariantMappings.push_back(std::string(S)); 1339 } 1340 } 1341 1342 bool VFShape::hasValidParameterList() const { 1343 for (unsigned Pos = 0, NumParams = Parameters.size(); Pos < NumParams; 1344 ++Pos) { 1345 assert(Parameters[Pos].ParamPos == Pos && "Broken parameter list."); 1346 1347 switch (Parameters[Pos].ParamKind) { 1348 default: // Nothing to check. 1349 break; 1350 case VFParamKind::OMP_Linear: 1351 case VFParamKind::OMP_LinearRef: 1352 case VFParamKind::OMP_LinearVal: 1353 case VFParamKind::OMP_LinearUVal: 1354 // Compile time linear steps must be non-zero. 1355 if (Parameters[Pos].LinearStepOrPos == 0) 1356 return false; 1357 break; 1358 case VFParamKind::OMP_LinearPos: 1359 case VFParamKind::OMP_LinearRefPos: 1360 case VFParamKind::OMP_LinearValPos: 1361 case VFParamKind::OMP_LinearUValPos: 1362 // The runtime linear step must be referring to some other 1363 // parameters in the signature. 1364 if (Parameters[Pos].LinearStepOrPos >= int(NumParams)) 1365 return false; 1366 // The linear step parameter must be marked as uniform. 1367 if (Parameters[Parameters[Pos].LinearStepOrPos].ParamKind != 1368 VFParamKind::OMP_Uniform) 1369 return false; 1370 // The linear step parameter can't point at itself. 1371 if (Parameters[Pos].LinearStepOrPos == int(Pos)) 1372 return false; 1373 break; 1374 case VFParamKind::GlobalPredicate: 1375 // The global predicate must be the unique. Can be placed anywhere in the 1376 // signature. 1377 for (unsigned NextPos = Pos + 1; NextPos < NumParams; ++NextPos) 1378 if (Parameters[NextPos].ParamKind == VFParamKind::GlobalPredicate) 1379 return false; 1380 break; 1381 } 1382 } 1383 return true; 1384 } 1385