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