1 //===- SLPVectorizer.cpp - A bottom up SLP Vectorizer ---------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This pass implements the Bottom Up SLP vectorizer. It detects consecutive 10 // stores that can be put together into vector-stores. Next, it attempts to 11 // construct vectorizable tree using the use-def chains. If a profitable tree 12 // was found, the SLP vectorizer performs vectorization on the tree. 13 // 14 // The pass is inspired by the work described in the paper: 15 // "Loop-Aware SLP in GCC" by Ira Rosen, Dorit Nuzman, Ayal Zaks. 16 // 17 //===----------------------------------------------------------------------===// 18 19 #include "llvm/Transforms/Vectorize/SLPVectorizer.h" 20 #include "llvm/ADT/DenseMap.h" 21 #include "llvm/ADT/DenseSet.h" 22 #include "llvm/ADT/Optional.h" 23 #include "llvm/ADT/PostOrderIterator.h" 24 #include "llvm/ADT/PriorityQueue.h" 25 #include "llvm/ADT/STLExtras.h" 26 #include "llvm/ADT/SetOperations.h" 27 #include "llvm/ADT/SetVector.h" 28 #include "llvm/ADT/SmallBitVector.h" 29 #include "llvm/ADT/SmallPtrSet.h" 30 #include "llvm/ADT/SmallSet.h" 31 #include "llvm/ADT/SmallString.h" 32 #include "llvm/ADT/Statistic.h" 33 #include "llvm/ADT/iterator.h" 34 #include "llvm/ADT/iterator_range.h" 35 #include "llvm/Analysis/AliasAnalysis.h" 36 #include "llvm/Analysis/AssumptionCache.h" 37 #include "llvm/Analysis/CodeMetrics.h" 38 #include "llvm/Analysis/DemandedBits.h" 39 #include "llvm/Analysis/GlobalsModRef.h" 40 #include "llvm/Analysis/IVDescriptors.h" 41 #include "llvm/Analysis/LoopAccessAnalysis.h" 42 #include "llvm/Analysis/LoopInfo.h" 43 #include "llvm/Analysis/MemoryLocation.h" 44 #include "llvm/Analysis/OptimizationRemarkEmitter.h" 45 #include "llvm/Analysis/ScalarEvolution.h" 46 #include "llvm/Analysis/ScalarEvolutionExpressions.h" 47 #include "llvm/Analysis/TargetLibraryInfo.h" 48 #include "llvm/Analysis/TargetTransformInfo.h" 49 #include "llvm/Analysis/ValueTracking.h" 50 #include "llvm/Analysis/VectorUtils.h" 51 #include "llvm/IR/Attributes.h" 52 #include "llvm/IR/BasicBlock.h" 53 #include "llvm/IR/Constant.h" 54 #include "llvm/IR/Constants.h" 55 #include "llvm/IR/DataLayout.h" 56 #include "llvm/IR/DebugLoc.h" 57 #include "llvm/IR/DerivedTypes.h" 58 #include "llvm/IR/Dominators.h" 59 #include "llvm/IR/Function.h" 60 #include "llvm/IR/IRBuilder.h" 61 #include "llvm/IR/InstrTypes.h" 62 #include "llvm/IR/Instruction.h" 63 #include "llvm/IR/Instructions.h" 64 #include "llvm/IR/IntrinsicInst.h" 65 #include "llvm/IR/Intrinsics.h" 66 #include "llvm/IR/Module.h" 67 #include "llvm/IR/NoFolder.h" 68 #include "llvm/IR/Operator.h" 69 #include "llvm/IR/PatternMatch.h" 70 #include "llvm/IR/Type.h" 71 #include "llvm/IR/Use.h" 72 #include "llvm/IR/User.h" 73 #include "llvm/IR/Value.h" 74 #include "llvm/IR/ValueHandle.h" 75 #include "llvm/IR/Verifier.h" 76 #include "llvm/InitializePasses.h" 77 #include "llvm/Pass.h" 78 #include "llvm/Support/Casting.h" 79 #include "llvm/Support/CommandLine.h" 80 #include "llvm/Support/Compiler.h" 81 #include "llvm/Support/DOTGraphTraits.h" 82 #include "llvm/Support/Debug.h" 83 #include "llvm/Support/ErrorHandling.h" 84 #include "llvm/Support/GraphWriter.h" 85 #include "llvm/Support/InstructionCost.h" 86 #include "llvm/Support/KnownBits.h" 87 #include "llvm/Support/MathExtras.h" 88 #include "llvm/Support/raw_ostream.h" 89 #include "llvm/Transforms/Utils/InjectTLIMappings.h" 90 #include "llvm/Transforms/Utils/LoopUtils.h" 91 #include "llvm/Transforms/Vectorize.h" 92 #include <algorithm> 93 #include <cassert> 94 #include <cstdint> 95 #include <iterator> 96 #include <memory> 97 #include <set> 98 #include <string> 99 #include <tuple> 100 #include <utility> 101 #include <vector> 102 103 using namespace llvm; 104 using namespace llvm::PatternMatch; 105 using namespace slpvectorizer; 106 107 #define SV_NAME "slp-vectorizer" 108 #define DEBUG_TYPE "SLP" 109 110 STATISTIC(NumVectorInstructions, "Number of vector instructions generated"); 111 112 cl::opt<bool> RunSLPVectorization("vectorize-slp", cl::init(true), cl::Hidden, 113 cl::desc("Run the SLP vectorization passes")); 114 115 static cl::opt<int> 116 SLPCostThreshold("slp-threshold", cl::init(0), cl::Hidden, 117 cl::desc("Only vectorize if you gain more than this " 118 "number ")); 119 120 static cl::opt<bool> 121 ShouldVectorizeHor("slp-vectorize-hor", cl::init(true), cl::Hidden, 122 cl::desc("Attempt to vectorize horizontal reductions")); 123 124 static cl::opt<bool> ShouldStartVectorizeHorAtStore( 125 "slp-vectorize-hor-store", cl::init(false), cl::Hidden, 126 cl::desc( 127 "Attempt to vectorize horizontal reductions feeding into a store")); 128 129 static cl::opt<int> 130 MaxVectorRegSizeOption("slp-max-reg-size", cl::init(128), cl::Hidden, 131 cl::desc("Attempt to vectorize for this register size in bits")); 132 133 static cl::opt<unsigned> 134 MaxVFOption("slp-max-vf", cl::init(0), cl::Hidden, 135 cl::desc("Maximum SLP vectorization factor (0=unlimited)")); 136 137 static cl::opt<int> 138 MaxStoreLookup("slp-max-store-lookup", cl::init(32), cl::Hidden, 139 cl::desc("Maximum depth of the lookup for consecutive stores.")); 140 141 /// Limits the size of scheduling regions in a block. 142 /// It avoid long compile times for _very_ large blocks where vector 143 /// instructions are spread over a wide range. 144 /// This limit is way higher than needed by real-world functions. 145 static cl::opt<int> 146 ScheduleRegionSizeBudget("slp-schedule-budget", cl::init(100000), cl::Hidden, 147 cl::desc("Limit the size of the SLP scheduling region per block")); 148 149 static cl::opt<int> MinVectorRegSizeOption( 150 "slp-min-reg-size", cl::init(128), cl::Hidden, 151 cl::desc("Attempt to vectorize for this register size in bits")); 152 153 static cl::opt<unsigned> RecursionMaxDepth( 154 "slp-recursion-max-depth", cl::init(12), cl::Hidden, 155 cl::desc("Limit the recursion depth when building a vectorizable tree")); 156 157 static cl::opt<unsigned> MinTreeSize( 158 "slp-min-tree-size", cl::init(3), cl::Hidden, 159 cl::desc("Only vectorize small trees if they are fully vectorizable")); 160 161 // The maximum depth that the look-ahead score heuristic will explore. 162 // The higher this value, the higher the compilation time overhead. 163 static cl::opt<int> LookAheadMaxDepth( 164 "slp-max-look-ahead-depth", cl::init(2), cl::Hidden, 165 cl::desc("The maximum look-ahead depth for operand reordering scores")); 166 167 // The Look-ahead heuristic goes through the users of the bundle to calculate 168 // the users cost in getExternalUsesCost(). To avoid compilation time increase 169 // we limit the number of users visited to this value. 170 static cl::opt<unsigned> LookAheadUsersBudget( 171 "slp-look-ahead-users-budget", cl::init(2), cl::Hidden, 172 cl::desc("The maximum number of users to visit while visiting the " 173 "predecessors. This prevents compilation time increase.")); 174 175 static cl::opt<bool> 176 ViewSLPTree("view-slp-tree", cl::Hidden, 177 cl::desc("Display the SLP trees with Graphviz")); 178 179 // Limit the number of alias checks. The limit is chosen so that 180 // it has no negative effect on the llvm benchmarks. 181 static const unsigned AliasedCheckLimit = 10; 182 183 // Another limit for the alias checks: The maximum distance between load/store 184 // instructions where alias checks are done. 185 // This limit is useful for very large basic blocks. 186 static const unsigned MaxMemDepDistance = 160; 187 188 /// If the ScheduleRegionSizeBudget is exhausted, we allow small scheduling 189 /// regions to be handled. 190 static const int MinScheduleRegionSize = 16; 191 192 /// Predicate for the element types that the SLP vectorizer supports. 193 /// 194 /// The most important thing to filter here are types which are invalid in LLVM 195 /// vectors. We also filter target specific types which have absolutely no 196 /// meaningful vectorization path such as x86_fp80 and ppc_f128. This just 197 /// avoids spending time checking the cost model and realizing that they will 198 /// be inevitably scalarized. 199 static bool isValidElementType(Type *Ty) { 200 return VectorType::isValidElementType(Ty) && !Ty->isX86_FP80Ty() && 201 !Ty->isPPC_FP128Ty(); 202 } 203 204 /// \returns True if the value is a constant (but not globals/constant 205 /// expressions). 206 static bool isConstant(Value *V) { 207 return isa<Constant>(V) && !isa<ConstantExpr>(V) && !isa<GlobalValue>(V); 208 } 209 210 /// Checks if \p V is one of vector-like instructions, i.e. undef, 211 /// insertelement/extractelement with constant indices for fixed vector type or 212 /// extractvalue instruction. 213 static bool isVectorLikeInstWithConstOps(Value *V) { 214 if (!isa<InsertElementInst, ExtractElementInst>(V) && 215 !isa<ExtractValueInst, UndefValue>(V)) 216 return false; 217 auto *I = dyn_cast<Instruction>(V); 218 if (!I || isa<ExtractValueInst>(I)) 219 return true; 220 if (!isa<FixedVectorType>(I->getOperand(0)->getType())) 221 return false; 222 if (isa<ExtractElementInst>(I)) 223 return isConstant(I->getOperand(1)); 224 assert(isa<InsertElementInst>(V) && "Expected only insertelement."); 225 return isConstant(I->getOperand(2)); 226 } 227 228 /// \returns true if all of the instructions in \p VL are in the same block or 229 /// false otherwise. 230 static bool allSameBlock(ArrayRef<Value *> VL) { 231 Instruction *I0 = dyn_cast<Instruction>(VL[0]); 232 if (!I0) 233 return false; 234 if (all_of(VL, isVectorLikeInstWithConstOps)) 235 return true; 236 237 BasicBlock *BB = I0->getParent(); 238 for (int I = 1, E = VL.size(); I < E; I++) { 239 auto *II = dyn_cast<Instruction>(VL[I]); 240 if (!II) 241 return false; 242 243 if (BB != II->getParent()) 244 return false; 245 } 246 return true; 247 } 248 249 /// \returns True if all of the values in \p VL are constants (but not 250 /// globals/constant expressions). 251 static bool allConstant(ArrayRef<Value *> VL) { 252 // Constant expressions and globals can't be vectorized like normal integer/FP 253 // constants. 254 return all_of(VL, isConstant); 255 } 256 257 /// \returns True if all of the values in \p VL are identical. 258 static bool isSplat(ArrayRef<Value *> VL) { 259 for (unsigned i = 1, e = VL.size(); i < e; ++i) 260 if (VL[i] != VL[0]) 261 return false; 262 return true; 263 } 264 265 /// \returns True if \p I is commutative, handles CmpInst and BinaryOperator. 266 static bool isCommutative(Instruction *I) { 267 if (auto *Cmp = dyn_cast<CmpInst>(I)) 268 return Cmp->isCommutative(); 269 if (auto *BO = dyn_cast<BinaryOperator>(I)) 270 return BO->isCommutative(); 271 // TODO: This should check for generic Instruction::isCommutative(), but 272 // we need to confirm that the caller code correctly handles Intrinsics 273 // for example (does not have 2 operands). 274 return false; 275 } 276 277 /// Checks if the vector of instructions can be represented as a shuffle, like: 278 /// %x0 = extractelement <4 x i8> %x, i32 0 279 /// %x3 = extractelement <4 x i8> %x, i32 3 280 /// %y1 = extractelement <4 x i8> %y, i32 1 281 /// %y2 = extractelement <4 x i8> %y, i32 2 282 /// %x0x0 = mul i8 %x0, %x0 283 /// %x3x3 = mul i8 %x3, %x3 284 /// %y1y1 = mul i8 %y1, %y1 285 /// %y2y2 = mul i8 %y2, %y2 286 /// %ins1 = insertelement <4 x i8> poison, i8 %x0x0, i32 0 287 /// %ins2 = insertelement <4 x i8> %ins1, i8 %x3x3, i32 1 288 /// %ins3 = insertelement <4 x i8> %ins2, i8 %y1y1, i32 2 289 /// %ins4 = insertelement <4 x i8> %ins3, i8 %y2y2, i32 3 290 /// ret <4 x i8> %ins4 291 /// can be transformed into: 292 /// %1 = shufflevector <4 x i8> %x, <4 x i8> %y, <4 x i32> <i32 0, i32 3, i32 5, 293 /// i32 6> 294 /// %2 = mul <4 x i8> %1, %1 295 /// ret <4 x i8> %2 296 /// We convert this initially to something like: 297 /// %x0 = extractelement <4 x i8> %x, i32 0 298 /// %x3 = extractelement <4 x i8> %x, i32 3 299 /// %y1 = extractelement <4 x i8> %y, i32 1 300 /// %y2 = extractelement <4 x i8> %y, i32 2 301 /// %1 = insertelement <4 x i8> poison, i8 %x0, i32 0 302 /// %2 = insertelement <4 x i8> %1, i8 %x3, i32 1 303 /// %3 = insertelement <4 x i8> %2, i8 %y1, i32 2 304 /// %4 = insertelement <4 x i8> %3, i8 %y2, i32 3 305 /// %5 = mul <4 x i8> %4, %4 306 /// %6 = extractelement <4 x i8> %5, i32 0 307 /// %ins1 = insertelement <4 x i8> poison, i8 %6, i32 0 308 /// %7 = extractelement <4 x i8> %5, i32 1 309 /// %ins2 = insertelement <4 x i8> %ins1, i8 %7, i32 1 310 /// %8 = extractelement <4 x i8> %5, i32 2 311 /// %ins3 = insertelement <4 x i8> %ins2, i8 %8, i32 2 312 /// %9 = extractelement <4 x i8> %5, i32 3 313 /// %ins4 = insertelement <4 x i8> %ins3, i8 %9, i32 3 314 /// ret <4 x i8> %ins4 315 /// InstCombiner transforms this into a shuffle and vector mul 316 /// Mask will return the Shuffle Mask equivalent to the extracted elements. 317 /// TODO: Can we split off and reuse the shuffle mask detection from 318 /// TargetTransformInfo::getInstructionThroughput? 319 static Optional<TargetTransformInfo::ShuffleKind> 320 isFixedVectorShuffle(ArrayRef<Value *> VL, SmallVectorImpl<int> &Mask) { 321 auto *EI0 = cast<ExtractElementInst>(VL[0]); 322 if (isa<ScalableVectorType>(EI0->getVectorOperandType())) 323 return None; 324 unsigned Size = 325 cast<FixedVectorType>(EI0->getVectorOperandType())->getNumElements(); 326 Value *Vec1 = nullptr; 327 Value *Vec2 = nullptr; 328 enum ShuffleMode { Unknown, Select, Permute }; 329 ShuffleMode CommonShuffleMode = Unknown; 330 for (unsigned I = 0, E = VL.size(); I < E; ++I) { 331 auto *EI = cast<ExtractElementInst>(VL[I]); 332 auto *Vec = EI->getVectorOperand(); 333 // All vector operands must have the same number of vector elements. 334 if (cast<FixedVectorType>(Vec->getType())->getNumElements() != Size) 335 return None; 336 auto *Idx = dyn_cast<ConstantInt>(EI->getIndexOperand()); 337 if (!Idx) 338 return None; 339 // Undefined behavior if Idx is negative or >= Size. 340 if (Idx->getValue().uge(Size)) { 341 Mask.push_back(UndefMaskElem); 342 continue; 343 } 344 unsigned IntIdx = Idx->getValue().getZExtValue(); 345 Mask.push_back(IntIdx); 346 // We can extractelement from undef or poison vector. 347 if (isa<UndefValue>(Vec)) 348 continue; 349 // For correct shuffling we have to have at most 2 different vector operands 350 // in all extractelement instructions. 351 if (!Vec1 || Vec1 == Vec) 352 Vec1 = Vec; 353 else if (!Vec2 || Vec2 == Vec) 354 Vec2 = Vec; 355 else 356 return None; 357 if (CommonShuffleMode == Permute) 358 continue; 359 // If the extract index is not the same as the operation number, it is a 360 // permutation. 361 if (IntIdx != I) { 362 CommonShuffleMode = Permute; 363 continue; 364 } 365 CommonShuffleMode = Select; 366 } 367 // If we're not crossing lanes in different vectors, consider it as blending. 368 if (CommonShuffleMode == Select && Vec2) 369 return TargetTransformInfo::SK_Select; 370 // If Vec2 was never used, we have a permutation of a single vector, otherwise 371 // we have permutation of 2 vectors. 372 return Vec2 ? TargetTransformInfo::SK_PermuteTwoSrc 373 : TargetTransformInfo::SK_PermuteSingleSrc; 374 } 375 376 namespace { 377 378 /// Main data required for vectorization of instructions. 379 struct InstructionsState { 380 /// The very first instruction in the list with the main opcode. 381 Value *OpValue = nullptr; 382 383 /// The main/alternate instruction. 384 Instruction *MainOp = nullptr; 385 Instruction *AltOp = nullptr; 386 387 /// The main/alternate opcodes for the list of instructions. 388 unsigned getOpcode() const { 389 return MainOp ? MainOp->getOpcode() : 0; 390 } 391 392 unsigned getAltOpcode() const { 393 return AltOp ? AltOp->getOpcode() : 0; 394 } 395 396 /// Some of the instructions in the list have alternate opcodes. 397 bool isAltShuffle() const { return getOpcode() != getAltOpcode(); } 398 399 bool isOpcodeOrAlt(Instruction *I) const { 400 unsigned CheckedOpcode = I->getOpcode(); 401 return getOpcode() == CheckedOpcode || getAltOpcode() == CheckedOpcode; 402 } 403 404 InstructionsState() = delete; 405 InstructionsState(Value *OpValue, Instruction *MainOp, Instruction *AltOp) 406 : OpValue(OpValue), MainOp(MainOp), AltOp(AltOp) {} 407 }; 408 409 } // end anonymous namespace 410 411 /// Chooses the correct key for scheduling data. If \p Op has the same (or 412 /// alternate) opcode as \p OpValue, the key is \p Op. Otherwise the key is \p 413 /// OpValue. 414 static Value *isOneOf(const InstructionsState &S, Value *Op) { 415 auto *I = dyn_cast<Instruction>(Op); 416 if (I && S.isOpcodeOrAlt(I)) 417 return Op; 418 return S.OpValue; 419 } 420 421 /// \returns true if \p Opcode is allowed as part of of the main/alternate 422 /// instruction for SLP vectorization. 423 /// 424 /// Example of unsupported opcode is SDIV that can potentially cause UB if the 425 /// "shuffled out" lane would result in division by zero. 426 static bool isValidForAlternation(unsigned Opcode) { 427 if (Instruction::isIntDivRem(Opcode)) 428 return false; 429 430 return true; 431 } 432 433 /// \returns analysis of the Instructions in \p VL described in 434 /// InstructionsState, the Opcode that we suppose the whole list 435 /// could be vectorized even if its structure is diverse. 436 static InstructionsState getSameOpcode(ArrayRef<Value *> VL, 437 unsigned BaseIndex = 0) { 438 // Make sure these are all Instructions. 439 if (llvm::any_of(VL, [](Value *V) { return !isa<Instruction>(V); })) 440 return InstructionsState(VL[BaseIndex], nullptr, nullptr); 441 442 bool IsCastOp = isa<CastInst>(VL[BaseIndex]); 443 bool IsBinOp = isa<BinaryOperator>(VL[BaseIndex]); 444 unsigned Opcode = cast<Instruction>(VL[BaseIndex])->getOpcode(); 445 unsigned AltOpcode = Opcode; 446 unsigned AltIndex = BaseIndex; 447 448 // Check for one alternate opcode from another BinaryOperator. 449 // TODO - generalize to support all operators (types, calls etc.). 450 for (int Cnt = 0, E = VL.size(); Cnt < E; Cnt++) { 451 unsigned InstOpcode = cast<Instruction>(VL[Cnt])->getOpcode(); 452 if (IsBinOp && isa<BinaryOperator>(VL[Cnt])) { 453 if (InstOpcode == Opcode || InstOpcode == AltOpcode) 454 continue; 455 if (Opcode == AltOpcode && isValidForAlternation(InstOpcode) && 456 isValidForAlternation(Opcode)) { 457 AltOpcode = InstOpcode; 458 AltIndex = Cnt; 459 continue; 460 } 461 } else if (IsCastOp && isa<CastInst>(VL[Cnt])) { 462 Type *Ty0 = cast<Instruction>(VL[BaseIndex])->getOperand(0)->getType(); 463 Type *Ty1 = cast<Instruction>(VL[Cnt])->getOperand(0)->getType(); 464 if (Ty0 == Ty1) { 465 if (InstOpcode == Opcode || InstOpcode == AltOpcode) 466 continue; 467 if (Opcode == AltOpcode) { 468 assert(isValidForAlternation(Opcode) && 469 isValidForAlternation(InstOpcode) && 470 "Cast isn't safe for alternation, logic needs to be updated!"); 471 AltOpcode = InstOpcode; 472 AltIndex = Cnt; 473 continue; 474 } 475 } 476 } else if (InstOpcode == Opcode || InstOpcode == AltOpcode) 477 continue; 478 return InstructionsState(VL[BaseIndex], nullptr, nullptr); 479 } 480 481 return InstructionsState(VL[BaseIndex], cast<Instruction>(VL[BaseIndex]), 482 cast<Instruction>(VL[AltIndex])); 483 } 484 485 /// \returns true if all of the values in \p VL have the same type or false 486 /// otherwise. 487 static bool allSameType(ArrayRef<Value *> VL) { 488 Type *Ty = VL[0]->getType(); 489 for (int i = 1, e = VL.size(); i < e; i++) 490 if (VL[i]->getType() != Ty) 491 return false; 492 493 return true; 494 } 495 496 /// \returns True if Extract{Value,Element} instruction extracts element Idx. 497 static Optional<unsigned> getExtractIndex(Instruction *E) { 498 unsigned Opcode = E->getOpcode(); 499 assert((Opcode == Instruction::ExtractElement || 500 Opcode == Instruction::ExtractValue) && 501 "Expected extractelement or extractvalue instruction."); 502 if (Opcode == Instruction::ExtractElement) { 503 auto *CI = dyn_cast<ConstantInt>(E->getOperand(1)); 504 if (!CI) 505 return None; 506 return CI->getZExtValue(); 507 } 508 ExtractValueInst *EI = cast<ExtractValueInst>(E); 509 if (EI->getNumIndices() != 1) 510 return None; 511 return *EI->idx_begin(); 512 } 513 514 /// \returns True if in-tree use also needs extract. This refers to 515 /// possible scalar operand in vectorized instruction. 516 static bool InTreeUserNeedToExtract(Value *Scalar, Instruction *UserInst, 517 TargetLibraryInfo *TLI) { 518 unsigned Opcode = UserInst->getOpcode(); 519 switch (Opcode) { 520 case Instruction::Load: { 521 LoadInst *LI = cast<LoadInst>(UserInst); 522 return (LI->getPointerOperand() == Scalar); 523 } 524 case Instruction::Store: { 525 StoreInst *SI = cast<StoreInst>(UserInst); 526 return (SI->getPointerOperand() == Scalar); 527 } 528 case Instruction::Call: { 529 CallInst *CI = cast<CallInst>(UserInst); 530 Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI); 531 for (unsigned i = 0, e = CI->arg_size(); i != e; ++i) { 532 if (hasVectorInstrinsicScalarOpd(ID, i)) 533 return (CI->getArgOperand(i) == Scalar); 534 } 535 LLVM_FALLTHROUGH; 536 } 537 default: 538 return false; 539 } 540 } 541 542 /// \returns the AA location that is being access by the instruction. 543 static MemoryLocation getLocation(Instruction *I, AAResults *AA) { 544 if (StoreInst *SI = dyn_cast<StoreInst>(I)) 545 return MemoryLocation::get(SI); 546 if (LoadInst *LI = dyn_cast<LoadInst>(I)) 547 return MemoryLocation::get(LI); 548 return MemoryLocation(); 549 } 550 551 /// \returns True if the instruction is not a volatile or atomic load/store. 552 static bool isSimple(Instruction *I) { 553 if (LoadInst *LI = dyn_cast<LoadInst>(I)) 554 return LI->isSimple(); 555 if (StoreInst *SI = dyn_cast<StoreInst>(I)) 556 return SI->isSimple(); 557 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) 558 return !MI->isVolatile(); 559 return true; 560 } 561 562 /// Shuffles \p Mask in accordance with the given \p SubMask. 563 static void addMask(SmallVectorImpl<int> &Mask, ArrayRef<int> SubMask) { 564 if (SubMask.empty()) 565 return; 566 if (Mask.empty()) { 567 Mask.append(SubMask.begin(), SubMask.end()); 568 return; 569 } 570 SmallVector<int> NewMask(SubMask.size(), UndefMaskElem); 571 int TermValue = std::min(Mask.size(), SubMask.size()); 572 for (int I = 0, E = SubMask.size(); I < E; ++I) { 573 if (SubMask[I] >= TermValue || SubMask[I] == UndefMaskElem || 574 Mask[SubMask[I]] >= TermValue) 575 continue; 576 NewMask[I] = Mask[SubMask[I]]; 577 } 578 Mask.swap(NewMask); 579 } 580 581 /// Order may have elements assigned special value (size) which is out of 582 /// bounds. Such indices only appear on places which correspond to undef values 583 /// (see canReuseExtract for details) and used in order to avoid undef values 584 /// have effect on operands ordering. 585 /// The first loop below simply finds all unused indices and then the next loop 586 /// nest assigns these indices for undef values positions. 587 /// As an example below Order has two undef positions and they have assigned 588 /// values 3 and 7 respectively: 589 /// before: 6 9 5 4 9 2 1 0 590 /// after: 6 3 5 4 7 2 1 0 591 static void fixupOrderingIndices(SmallVectorImpl<unsigned> &Order) { 592 const unsigned Sz = Order.size(); 593 SmallBitVector UsedIndices(Sz); 594 SmallVector<int> MaskedIndices; 595 for (unsigned I = 0; I < Sz; ++I) { 596 if (Order[I] < Sz) 597 UsedIndices.set(Order[I]); 598 else 599 MaskedIndices.push_back(I); 600 } 601 if (MaskedIndices.empty()) 602 return; 603 SmallVector<int> AvailableIndices(MaskedIndices.size()); 604 unsigned Cnt = 0; 605 int Idx = UsedIndices.find_first(); 606 do { 607 AvailableIndices[Cnt] = Idx; 608 Idx = UsedIndices.find_next(Idx); 609 ++Cnt; 610 } while (Idx > 0); 611 assert(Cnt == MaskedIndices.size() && "Non-synced masked/available indices."); 612 for (int I = 0, E = MaskedIndices.size(); I < E; ++I) 613 Order[MaskedIndices[I]] = AvailableIndices[I]; 614 } 615 616 namespace llvm { 617 618 static void inversePermutation(ArrayRef<unsigned> Indices, 619 SmallVectorImpl<int> &Mask) { 620 Mask.clear(); 621 const unsigned E = Indices.size(); 622 Mask.resize(E, UndefMaskElem); 623 for (unsigned I = 0; I < E; ++I) 624 Mask[Indices[I]] = I; 625 } 626 627 /// \returns inserting index of InsertElement or InsertValue instruction, 628 /// using Offset as base offset for index. 629 static Optional<int> getInsertIndex(Value *InsertInst, unsigned Offset) { 630 int Index = Offset; 631 if (auto *IE = dyn_cast<InsertElementInst>(InsertInst)) { 632 if (auto *CI = dyn_cast<ConstantInt>(IE->getOperand(2))) { 633 auto *VT = cast<FixedVectorType>(IE->getType()); 634 if (CI->getValue().uge(VT->getNumElements())) 635 return UndefMaskElem; 636 Index *= VT->getNumElements(); 637 Index += CI->getZExtValue(); 638 return Index; 639 } 640 if (isa<UndefValue>(IE->getOperand(2))) 641 return UndefMaskElem; 642 return None; 643 } 644 645 auto *IV = cast<InsertValueInst>(InsertInst); 646 Type *CurrentType = IV->getType(); 647 for (unsigned I : IV->indices()) { 648 if (auto *ST = dyn_cast<StructType>(CurrentType)) { 649 Index *= ST->getNumElements(); 650 CurrentType = ST->getElementType(I); 651 } else if (auto *AT = dyn_cast<ArrayType>(CurrentType)) { 652 Index *= AT->getNumElements(); 653 CurrentType = AT->getElementType(); 654 } else { 655 return None; 656 } 657 Index += I; 658 } 659 return Index; 660 } 661 662 /// Reorders the list of scalars in accordance with the given \p Order and then 663 /// the \p Mask. \p Order - is the original order of the scalars, need to 664 /// reorder scalars into an unordered state at first according to the given 665 /// order. Then the ordered scalars are shuffled once again in accordance with 666 /// the provided mask. 667 static void reorderScalars(SmallVectorImpl<Value *> &Scalars, 668 ArrayRef<int> Mask) { 669 assert(!Mask.empty() && "Expected non-empty mask."); 670 SmallVector<Value *> Prev(Scalars.size(), 671 UndefValue::get(Scalars.front()->getType())); 672 Prev.swap(Scalars); 673 for (unsigned I = 0, E = Prev.size(); I < E; ++I) 674 if (Mask[I] != UndefMaskElem) 675 Scalars[Mask[I]] = Prev[I]; 676 } 677 678 namespace slpvectorizer { 679 680 /// Bottom Up SLP Vectorizer. 681 class BoUpSLP { 682 struct TreeEntry; 683 struct ScheduleData; 684 685 public: 686 using ValueList = SmallVector<Value *, 8>; 687 using InstrList = SmallVector<Instruction *, 16>; 688 using ValueSet = SmallPtrSet<Value *, 16>; 689 using StoreList = SmallVector<StoreInst *, 8>; 690 using ExtraValueToDebugLocsMap = 691 MapVector<Value *, SmallVector<Instruction *, 2>>; 692 using OrdersType = SmallVector<unsigned, 4>; 693 694 BoUpSLP(Function *Func, ScalarEvolution *Se, TargetTransformInfo *Tti, 695 TargetLibraryInfo *TLi, AAResults *Aa, LoopInfo *Li, 696 DominatorTree *Dt, AssumptionCache *AC, DemandedBits *DB, 697 const DataLayout *DL, OptimizationRemarkEmitter *ORE) 698 : F(Func), SE(Se), TTI(Tti), TLI(TLi), AA(Aa), LI(Li), DT(Dt), AC(AC), 699 DB(DB), DL(DL), ORE(ORE), Builder(Se->getContext()) { 700 CodeMetrics::collectEphemeralValues(F, AC, EphValues); 701 // Use the vector register size specified by the target unless overridden 702 // by a command-line option. 703 // TODO: It would be better to limit the vectorization factor based on 704 // data type rather than just register size. For example, x86 AVX has 705 // 256-bit registers, but it does not support integer operations 706 // at that width (that requires AVX2). 707 if (MaxVectorRegSizeOption.getNumOccurrences()) 708 MaxVecRegSize = MaxVectorRegSizeOption; 709 else 710 MaxVecRegSize = 711 TTI->getRegisterBitWidth(TargetTransformInfo::RGK_FixedWidthVector) 712 .getFixedSize(); 713 714 if (MinVectorRegSizeOption.getNumOccurrences()) 715 MinVecRegSize = MinVectorRegSizeOption; 716 else 717 MinVecRegSize = TTI->getMinVectorRegisterBitWidth(); 718 } 719 720 /// Vectorize the tree that starts with the elements in \p VL. 721 /// Returns the vectorized root. 722 Value *vectorizeTree(); 723 724 /// Vectorize the tree but with the list of externally used values \p 725 /// ExternallyUsedValues. Values in this MapVector can be replaced but the 726 /// generated extractvalue instructions. 727 Value *vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues); 728 729 /// \returns the cost incurred by unwanted spills and fills, caused by 730 /// holding live values over call sites. 731 InstructionCost getSpillCost() const; 732 733 /// \returns the vectorization cost of the subtree that starts at \p VL. 734 /// A negative number means that this is profitable. 735 InstructionCost getTreeCost(ArrayRef<Value *> VectorizedVals = None); 736 737 /// Construct a vectorizable tree that starts at \p Roots, ignoring users for 738 /// the purpose of scheduling and extraction in the \p UserIgnoreLst. 739 void buildTree(ArrayRef<Value *> Roots, 740 ArrayRef<Value *> UserIgnoreLst = None); 741 742 /// Builds external uses of the vectorized scalars, i.e. the list of 743 /// vectorized scalars to be extracted, their lanes and their scalar users. \p 744 /// ExternallyUsedValues contains additional list of external uses to handle 745 /// vectorization of reductions. 746 void 747 buildExternalUses(const ExtraValueToDebugLocsMap &ExternallyUsedValues = {}); 748 749 /// Clear the internal data structures that are created by 'buildTree'. 750 void deleteTree() { 751 VectorizableTree.clear(); 752 ScalarToTreeEntry.clear(); 753 MustGather.clear(); 754 ExternalUses.clear(); 755 for (auto &Iter : BlocksSchedules) { 756 BlockScheduling *BS = Iter.second.get(); 757 BS->clear(); 758 } 759 MinBWs.clear(); 760 InstrElementSize.clear(); 761 } 762 763 unsigned getTreeSize() const { return VectorizableTree.size(); } 764 765 /// Perform LICM and CSE on the newly generated gather sequences. 766 void optimizeGatherSequence(); 767 768 /// Checks if the specified gather tree entry \p TE can be represented as a 769 /// shuffled vector entry + (possibly) permutation with other gathers. It 770 /// implements the checks only for possibly ordered scalars (Loads, 771 /// ExtractElement, ExtractValue), which can be part of the graph. 772 Optional<OrdersType> findReusedOrderedScalars(const TreeEntry &TE); 773 774 /// Reorders the current graph to the most profitable order starting from the 775 /// root node to the leaf nodes. The best order is chosen only from the nodes 776 /// of the same size (vectorization factor). Smaller nodes are considered 777 /// parts of subgraph with smaller VF and they are reordered independently. We 778 /// can make it because we still need to extend smaller nodes to the wider VF 779 /// and we can merge reordering shuffles with the widening shuffles. 780 void reorderTopToBottom(); 781 782 /// Reorders the current graph to the most profitable order starting from 783 /// leaves to the root. It allows to rotate small subgraphs and reduce the 784 /// number of reshuffles if the leaf nodes use the same order. In this case we 785 /// can merge the orders and just shuffle user node instead of shuffling its 786 /// operands. Plus, even the leaf nodes have different orders, it allows to 787 /// sink reordering in the graph closer to the root node and merge it later 788 /// during analysis. 789 void reorderBottomToTop(bool IgnoreReorder = false); 790 791 /// \return The vector element size in bits to use when vectorizing the 792 /// expression tree ending at \p V. If V is a store, the size is the width of 793 /// the stored value. Otherwise, the size is the width of the largest loaded 794 /// value reaching V. This method is used by the vectorizer to calculate 795 /// vectorization factors. 796 unsigned getVectorElementSize(Value *V); 797 798 /// Compute the minimum type sizes required to represent the entries in a 799 /// vectorizable tree. 800 void computeMinimumValueSizes(); 801 802 // \returns maximum vector register size as set by TTI or overridden by cl::opt. 803 unsigned getMaxVecRegSize() const { 804 return MaxVecRegSize; 805 } 806 807 // \returns minimum vector register size as set by cl::opt. 808 unsigned getMinVecRegSize() const { 809 return MinVecRegSize; 810 } 811 812 unsigned getMinVF(unsigned Sz) const { 813 return std::max(2U, getMinVecRegSize() / Sz); 814 } 815 816 unsigned getMaximumVF(unsigned ElemWidth, unsigned Opcode) const { 817 unsigned MaxVF = MaxVFOption.getNumOccurrences() ? 818 MaxVFOption : TTI->getMaximumVF(ElemWidth, Opcode); 819 return MaxVF ? MaxVF : UINT_MAX; 820 } 821 822 /// Check if homogeneous aggregate is isomorphic to some VectorType. 823 /// Accepts homogeneous multidimensional aggregate of scalars/vectors like 824 /// {[4 x i16], [4 x i16]}, { <2 x float>, <2 x float> }, 825 /// {{{i16, i16}, {i16, i16}}, {{i16, i16}, {i16, i16}}} and so on. 826 /// 827 /// \returns number of elements in vector if isomorphism exists, 0 otherwise. 828 unsigned canMapToVector(Type *T, const DataLayout &DL) const; 829 830 /// \returns True if the VectorizableTree is both tiny and not fully 831 /// vectorizable. We do not vectorize such trees. 832 bool isTreeTinyAndNotFullyVectorizable(bool ForReduction = false) const; 833 834 /// Assume that a legal-sized 'or'-reduction of shifted/zexted loaded values 835 /// can be load combined in the backend. Load combining may not be allowed in 836 /// the IR optimizer, so we do not want to alter the pattern. For example, 837 /// partially transforming a scalar bswap() pattern into vector code is 838 /// effectively impossible for the backend to undo. 839 /// TODO: If load combining is allowed in the IR optimizer, this analysis 840 /// may not be necessary. 841 bool isLoadCombineReductionCandidate(RecurKind RdxKind) const; 842 843 /// Assume that a vector of stores of bitwise-or/shifted/zexted loaded values 844 /// can be load combined in the backend. Load combining may not be allowed in 845 /// the IR optimizer, so we do not want to alter the pattern. For example, 846 /// partially transforming a scalar bswap() pattern into vector code is 847 /// effectively impossible for the backend to undo. 848 /// TODO: If load combining is allowed in the IR optimizer, this analysis 849 /// may not be necessary. 850 bool isLoadCombineCandidate() const; 851 852 OptimizationRemarkEmitter *getORE() { return ORE; } 853 854 /// This structure holds any data we need about the edges being traversed 855 /// during buildTree_rec(). We keep track of: 856 /// (i) the user TreeEntry index, and 857 /// (ii) the index of the edge. 858 struct EdgeInfo { 859 EdgeInfo() = default; 860 EdgeInfo(TreeEntry *UserTE, unsigned EdgeIdx) 861 : UserTE(UserTE), EdgeIdx(EdgeIdx) {} 862 /// The user TreeEntry. 863 TreeEntry *UserTE = nullptr; 864 /// The operand index of the use. 865 unsigned EdgeIdx = UINT_MAX; 866 #ifndef NDEBUG 867 friend inline raw_ostream &operator<<(raw_ostream &OS, 868 const BoUpSLP::EdgeInfo &EI) { 869 EI.dump(OS); 870 return OS; 871 } 872 /// Debug print. 873 void dump(raw_ostream &OS) const { 874 OS << "{User:" << (UserTE ? std::to_string(UserTE->Idx) : "null") 875 << " EdgeIdx:" << EdgeIdx << "}"; 876 } 877 LLVM_DUMP_METHOD void dump() const { dump(dbgs()); } 878 #endif 879 }; 880 881 /// A helper data structure to hold the operands of a vector of instructions. 882 /// This supports a fixed vector length for all operand vectors. 883 class VLOperands { 884 /// For each operand we need (i) the value, and (ii) the opcode that it 885 /// would be attached to if the expression was in a left-linearized form. 886 /// This is required to avoid illegal operand reordering. 887 /// For example: 888 /// \verbatim 889 /// 0 Op1 890 /// |/ 891 /// Op1 Op2 Linearized + Op2 892 /// \ / ----------> |/ 893 /// - - 894 /// 895 /// Op1 - Op2 (0 + Op1) - Op2 896 /// \endverbatim 897 /// 898 /// Value Op1 is attached to a '+' operation, and Op2 to a '-'. 899 /// 900 /// Another way to think of this is to track all the operations across the 901 /// path from the operand all the way to the root of the tree and to 902 /// calculate the operation that corresponds to this path. For example, the 903 /// path from Op2 to the root crosses the RHS of the '-', therefore the 904 /// corresponding operation is a '-' (which matches the one in the 905 /// linearized tree, as shown above). 906 /// 907 /// For lack of a better term, we refer to this operation as Accumulated 908 /// Path Operation (APO). 909 struct OperandData { 910 OperandData() = default; 911 OperandData(Value *V, bool APO, bool IsUsed) 912 : V(V), APO(APO), IsUsed(IsUsed) {} 913 /// The operand value. 914 Value *V = nullptr; 915 /// TreeEntries only allow a single opcode, or an alternate sequence of 916 /// them (e.g, +, -). Therefore, we can safely use a boolean value for the 917 /// APO. It is set to 'true' if 'V' is attached to an inverse operation 918 /// in the left-linearized form (e.g., Sub/Div), and 'false' otherwise 919 /// (e.g., Add/Mul) 920 bool APO = false; 921 /// Helper data for the reordering function. 922 bool IsUsed = false; 923 }; 924 925 /// During operand reordering, we are trying to select the operand at lane 926 /// that matches best with the operand at the neighboring lane. Our 927 /// selection is based on the type of value we are looking for. For example, 928 /// if the neighboring lane has a load, we need to look for a load that is 929 /// accessing a consecutive address. These strategies are summarized in the 930 /// 'ReorderingMode' enumerator. 931 enum class ReorderingMode { 932 Load, ///< Matching loads to consecutive memory addresses 933 Opcode, ///< Matching instructions based on opcode (same or alternate) 934 Constant, ///< Matching constants 935 Splat, ///< Matching the same instruction multiple times (broadcast) 936 Failed, ///< We failed to create a vectorizable group 937 }; 938 939 using OperandDataVec = SmallVector<OperandData, 2>; 940 941 /// A vector of operand vectors. 942 SmallVector<OperandDataVec, 4> OpsVec; 943 944 const DataLayout &DL; 945 ScalarEvolution &SE; 946 const BoUpSLP &R; 947 948 /// \returns the operand data at \p OpIdx and \p Lane. 949 OperandData &getData(unsigned OpIdx, unsigned Lane) { 950 return OpsVec[OpIdx][Lane]; 951 } 952 953 /// \returns the operand data at \p OpIdx and \p Lane. Const version. 954 const OperandData &getData(unsigned OpIdx, unsigned Lane) const { 955 return OpsVec[OpIdx][Lane]; 956 } 957 958 /// Clears the used flag for all entries. 959 void clearUsed() { 960 for (unsigned OpIdx = 0, NumOperands = getNumOperands(); 961 OpIdx != NumOperands; ++OpIdx) 962 for (unsigned Lane = 0, NumLanes = getNumLanes(); Lane != NumLanes; 963 ++Lane) 964 OpsVec[OpIdx][Lane].IsUsed = false; 965 } 966 967 /// Swap the operand at \p OpIdx1 with that one at \p OpIdx2. 968 void swap(unsigned OpIdx1, unsigned OpIdx2, unsigned Lane) { 969 std::swap(OpsVec[OpIdx1][Lane], OpsVec[OpIdx2][Lane]); 970 } 971 972 // The hard-coded scores listed here are not very important. When computing 973 // the scores of matching one sub-tree with another, we are basically 974 // counting the number of values that are matching. So even if all scores 975 // are set to 1, we would still get a decent matching result. 976 // However, sometimes we have to break ties. For example we may have to 977 // choose between matching loads vs matching opcodes. This is what these 978 // scores are helping us with: they provide the order of preference. 979 980 /// Loads from consecutive memory addresses, e.g. load(A[i]), load(A[i+1]). 981 static const int ScoreConsecutiveLoads = 3; 982 /// ExtractElementInst from same vector and consecutive indexes. 983 static const int ScoreConsecutiveExtracts = 3; 984 /// Constants. 985 static const int ScoreConstants = 2; 986 /// Instructions with the same opcode. 987 static const int ScoreSameOpcode = 2; 988 /// Instructions with alt opcodes (e.g, add + sub). 989 static const int ScoreAltOpcodes = 1; 990 /// Identical instructions (a.k.a. splat or broadcast). 991 static const int ScoreSplat = 1; 992 /// Matching with an undef is preferable to failing. 993 static const int ScoreUndef = 1; 994 /// Score for failing to find a decent match. 995 static const int ScoreFail = 0; 996 /// User exteranl to the vectorized code. 997 static const int ExternalUseCost = 1; 998 /// The user is internal but in a different lane. 999 static const int UserInDiffLaneCost = ExternalUseCost; 1000 1001 /// \returns the score of placing \p V1 and \p V2 in consecutive lanes. 1002 static int getShallowScore(Value *V1, Value *V2, const DataLayout &DL, 1003 ScalarEvolution &SE) { 1004 auto *LI1 = dyn_cast<LoadInst>(V1); 1005 auto *LI2 = dyn_cast<LoadInst>(V2); 1006 if (LI1 && LI2) { 1007 if (LI1->getParent() != LI2->getParent()) 1008 return VLOperands::ScoreFail; 1009 1010 Optional<int> Dist = getPointersDiff( 1011 LI1->getType(), LI1->getPointerOperand(), LI2->getType(), 1012 LI2->getPointerOperand(), DL, SE, /*StrictCheck=*/true); 1013 return (Dist && *Dist == 1) ? VLOperands::ScoreConsecutiveLoads 1014 : VLOperands::ScoreFail; 1015 } 1016 1017 auto *C1 = dyn_cast<Constant>(V1); 1018 auto *C2 = dyn_cast<Constant>(V2); 1019 if (C1 && C2) 1020 return VLOperands::ScoreConstants; 1021 1022 // Extracts from consecutive indexes of the same vector better score as 1023 // the extracts could be optimized away. 1024 Value *EV; 1025 ConstantInt *Ex1Idx, *Ex2Idx; 1026 if (match(V1, m_ExtractElt(m_Value(EV), m_ConstantInt(Ex1Idx))) && 1027 match(V2, m_ExtractElt(m_Deferred(EV), m_ConstantInt(Ex2Idx))) && 1028 Ex1Idx->getZExtValue() + 1 == Ex2Idx->getZExtValue()) 1029 return VLOperands::ScoreConsecutiveExtracts; 1030 1031 auto *I1 = dyn_cast<Instruction>(V1); 1032 auto *I2 = dyn_cast<Instruction>(V2); 1033 if (I1 && I2) { 1034 if (I1 == I2) 1035 return VLOperands::ScoreSplat; 1036 InstructionsState S = getSameOpcode({I1, I2}); 1037 // Note: Only consider instructions with <= 2 operands to avoid 1038 // complexity explosion. 1039 if (S.getOpcode() && S.MainOp->getNumOperands() <= 2) 1040 return S.isAltShuffle() ? VLOperands::ScoreAltOpcodes 1041 : VLOperands::ScoreSameOpcode; 1042 } 1043 1044 if (isa<UndefValue>(V2)) 1045 return VLOperands::ScoreUndef; 1046 1047 return VLOperands::ScoreFail; 1048 } 1049 1050 /// Holds the values and their lane that are taking part in the look-ahead 1051 /// score calculation. This is used in the external uses cost calculation. 1052 SmallDenseMap<Value *, int> InLookAheadValues; 1053 1054 /// \Returns the additinal cost due to uses of \p LHS and \p RHS that are 1055 /// either external to the vectorized code, or require shuffling. 1056 int getExternalUsesCost(const std::pair<Value *, int> &LHS, 1057 const std::pair<Value *, int> &RHS) { 1058 int Cost = 0; 1059 std::array<std::pair<Value *, int>, 2> Values = {{LHS, RHS}}; 1060 for (int Idx = 0, IdxE = Values.size(); Idx != IdxE; ++Idx) { 1061 Value *V = Values[Idx].first; 1062 if (isa<Constant>(V)) { 1063 // Since this is a function pass, it doesn't make semantic sense to 1064 // walk the users of a subclass of Constant. The users could be in 1065 // another function, or even another module that happens to be in 1066 // the same LLVMContext. 1067 continue; 1068 } 1069 1070 // Calculate the absolute lane, using the minimum relative lane of LHS 1071 // and RHS as base and Idx as the offset. 1072 int Ln = std::min(LHS.second, RHS.second) + Idx; 1073 assert(Ln >= 0 && "Bad lane calculation"); 1074 unsigned UsersBudget = LookAheadUsersBudget; 1075 for (User *U : V->users()) { 1076 if (const TreeEntry *UserTE = R.getTreeEntry(U)) { 1077 // The user is in the VectorizableTree. Check if we need to insert. 1078 auto It = llvm::find(UserTE->Scalars, U); 1079 assert(It != UserTE->Scalars.end() && "U is in UserTE"); 1080 int UserLn = std::distance(UserTE->Scalars.begin(), It); 1081 assert(UserLn >= 0 && "Bad lane"); 1082 if (UserLn != Ln) 1083 Cost += UserInDiffLaneCost; 1084 } else { 1085 // Check if the user is in the look-ahead code. 1086 auto It2 = InLookAheadValues.find(U); 1087 if (It2 != InLookAheadValues.end()) { 1088 // The user is in the look-ahead code. Check the lane. 1089 if (It2->second != Ln) 1090 Cost += UserInDiffLaneCost; 1091 } else { 1092 // The user is neither in SLP tree nor in the look-ahead code. 1093 Cost += ExternalUseCost; 1094 } 1095 } 1096 // Limit the number of visited uses to cap compilation time. 1097 if (--UsersBudget == 0) 1098 break; 1099 } 1100 } 1101 return Cost; 1102 } 1103 1104 /// Go through the operands of \p LHS and \p RHS recursively until \p 1105 /// MaxLevel, and return the cummulative score. For example: 1106 /// \verbatim 1107 /// A[0] B[0] A[1] B[1] C[0] D[0] B[1] A[1] 1108 /// \ / \ / \ / \ / 1109 /// + + + + 1110 /// G1 G2 G3 G4 1111 /// \endverbatim 1112 /// The getScoreAtLevelRec(G1, G2) function will try to match the nodes at 1113 /// each level recursively, accumulating the score. It starts from matching 1114 /// the additions at level 0, then moves on to the loads (level 1). The 1115 /// score of G1 and G2 is higher than G1 and G3, because {A[0],A[1]} and 1116 /// {B[0],B[1]} match with VLOperands::ScoreConsecutiveLoads, while 1117 /// {A[0],C[0]} has a score of VLOperands::ScoreFail. 1118 /// Please note that the order of the operands does not matter, as we 1119 /// evaluate the score of all profitable combinations of operands. In 1120 /// other words the score of G1 and G4 is the same as G1 and G2. This 1121 /// heuristic is based on ideas described in: 1122 /// Look-ahead SLP: Auto-vectorization in the presence of commutative 1123 /// operations, CGO 2018 by Vasileios Porpodas, Rodrigo C. O. Rocha, 1124 /// Luís F. W. Góes 1125 int getScoreAtLevelRec(const std::pair<Value *, int> &LHS, 1126 const std::pair<Value *, int> &RHS, int CurrLevel, 1127 int MaxLevel) { 1128 1129 Value *V1 = LHS.first; 1130 Value *V2 = RHS.first; 1131 // Get the shallow score of V1 and V2. 1132 int ShallowScoreAtThisLevel = 1133 std::max((int)ScoreFail, getShallowScore(V1, V2, DL, SE) - 1134 getExternalUsesCost(LHS, RHS)); 1135 int Lane1 = LHS.second; 1136 int Lane2 = RHS.second; 1137 1138 // If reached MaxLevel, 1139 // or if V1 and V2 are not instructions, 1140 // or if they are SPLAT, 1141 // or if they are not consecutive, early return the current cost. 1142 auto *I1 = dyn_cast<Instruction>(V1); 1143 auto *I2 = dyn_cast<Instruction>(V2); 1144 if (CurrLevel == MaxLevel || !(I1 && I2) || I1 == I2 || 1145 ShallowScoreAtThisLevel == VLOperands::ScoreFail || 1146 (isa<LoadInst>(I1) && isa<LoadInst>(I2) && ShallowScoreAtThisLevel)) 1147 return ShallowScoreAtThisLevel; 1148 assert(I1 && I2 && "Should have early exited."); 1149 1150 // Keep track of in-tree values for determining the external-use cost. 1151 InLookAheadValues[V1] = Lane1; 1152 InLookAheadValues[V2] = Lane2; 1153 1154 // Contains the I2 operand indexes that got matched with I1 operands. 1155 SmallSet<unsigned, 4> Op2Used; 1156 1157 // Recursion towards the operands of I1 and I2. We are trying all possbile 1158 // operand pairs, and keeping track of the best score. 1159 for (unsigned OpIdx1 = 0, NumOperands1 = I1->getNumOperands(); 1160 OpIdx1 != NumOperands1; ++OpIdx1) { 1161 // Try to pair op1I with the best operand of I2. 1162 int MaxTmpScore = 0; 1163 unsigned MaxOpIdx2 = 0; 1164 bool FoundBest = false; 1165 // If I2 is commutative try all combinations. 1166 unsigned FromIdx = isCommutative(I2) ? 0 : OpIdx1; 1167 unsigned ToIdx = isCommutative(I2) 1168 ? I2->getNumOperands() 1169 : std::min(I2->getNumOperands(), OpIdx1 + 1); 1170 assert(FromIdx <= ToIdx && "Bad index"); 1171 for (unsigned OpIdx2 = FromIdx; OpIdx2 != ToIdx; ++OpIdx2) { 1172 // Skip operands already paired with OpIdx1. 1173 if (Op2Used.count(OpIdx2)) 1174 continue; 1175 // Recursively calculate the cost at each level 1176 int TmpScore = getScoreAtLevelRec({I1->getOperand(OpIdx1), Lane1}, 1177 {I2->getOperand(OpIdx2), Lane2}, 1178 CurrLevel + 1, MaxLevel); 1179 // Look for the best score. 1180 if (TmpScore > VLOperands::ScoreFail && TmpScore > MaxTmpScore) { 1181 MaxTmpScore = TmpScore; 1182 MaxOpIdx2 = OpIdx2; 1183 FoundBest = true; 1184 } 1185 } 1186 if (FoundBest) { 1187 // Pair {OpIdx1, MaxOpIdx2} was found to be best. Never revisit it. 1188 Op2Used.insert(MaxOpIdx2); 1189 ShallowScoreAtThisLevel += MaxTmpScore; 1190 } 1191 } 1192 return ShallowScoreAtThisLevel; 1193 } 1194 1195 /// \Returns the look-ahead score, which tells us how much the sub-trees 1196 /// rooted at \p LHS and \p RHS match, the more they match the higher the 1197 /// score. This helps break ties in an informed way when we cannot decide on 1198 /// the order of the operands by just considering the immediate 1199 /// predecessors. 1200 int getLookAheadScore(const std::pair<Value *, int> &LHS, 1201 const std::pair<Value *, int> &RHS) { 1202 InLookAheadValues.clear(); 1203 return getScoreAtLevelRec(LHS, RHS, 1, LookAheadMaxDepth); 1204 } 1205 1206 // Search all operands in Ops[*][Lane] for the one that matches best 1207 // Ops[OpIdx][LastLane] and return its opreand index. 1208 // If no good match can be found, return None. 1209 Optional<unsigned> 1210 getBestOperand(unsigned OpIdx, int Lane, int LastLane, 1211 ArrayRef<ReorderingMode> ReorderingModes) { 1212 unsigned NumOperands = getNumOperands(); 1213 1214 // The operand of the previous lane at OpIdx. 1215 Value *OpLastLane = getData(OpIdx, LastLane).V; 1216 1217 // Our strategy mode for OpIdx. 1218 ReorderingMode RMode = ReorderingModes[OpIdx]; 1219 1220 // The linearized opcode of the operand at OpIdx, Lane. 1221 bool OpIdxAPO = getData(OpIdx, Lane).APO; 1222 1223 // The best operand index and its score. 1224 // Sometimes we have more than one option (e.g., Opcode and Undefs), so we 1225 // are using the score to differentiate between the two. 1226 struct BestOpData { 1227 Optional<unsigned> Idx = None; 1228 unsigned Score = 0; 1229 } BestOp; 1230 1231 // Iterate through all unused operands and look for the best. 1232 for (unsigned Idx = 0; Idx != NumOperands; ++Idx) { 1233 // Get the operand at Idx and Lane. 1234 OperandData &OpData = getData(Idx, Lane); 1235 Value *Op = OpData.V; 1236 bool OpAPO = OpData.APO; 1237 1238 // Skip already selected operands. 1239 if (OpData.IsUsed) 1240 continue; 1241 1242 // Skip if we are trying to move the operand to a position with a 1243 // different opcode in the linearized tree form. This would break the 1244 // semantics. 1245 if (OpAPO != OpIdxAPO) 1246 continue; 1247 1248 // Look for an operand that matches the current mode. 1249 switch (RMode) { 1250 case ReorderingMode::Load: 1251 case ReorderingMode::Constant: 1252 case ReorderingMode::Opcode: { 1253 bool LeftToRight = Lane > LastLane; 1254 Value *OpLeft = (LeftToRight) ? OpLastLane : Op; 1255 Value *OpRight = (LeftToRight) ? Op : OpLastLane; 1256 unsigned Score = 1257 getLookAheadScore({OpLeft, LastLane}, {OpRight, Lane}); 1258 if (Score > BestOp.Score) { 1259 BestOp.Idx = Idx; 1260 BestOp.Score = Score; 1261 } 1262 break; 1263 } 1264 case ReorderingMode::Splat: 1265 if (Op == OpLastLane) 1266 BestOp.Idx = Idx; 1267 break; 1268 case ReorderingMode::Failed: 1269 return None; 1270 } 1271 } 1272 1273 if (BestOp.Idx) { 1274 getData(BestOp.Idx.getValue(), Lane).IsUsed = true; 1275 return BestOp.Idx; 1276 } 1277 // If we could not find a good match return None. 1278 return None; 1279 } 1280 1281 /// Helper for reorderOperandVecs. \Returns the lane that we should start 1282 /// reordering from. This is the one which has the least number of operands 1283 /// that can freely move about. 1284 unsigned getBestLaneToStartReordering() const { 1285 unsigned BestLane = 0; 1286 unsigned Min = UINT_MAX; 1287 for (unsigned Lane = 0, NumLanes = getNumLanes(); Lane != NumLanes; 1288 ++Lane) { 1289 unsigned NumFreeOps = getMaxNumOperandsThatCanBeReordered(Lane); 1290 if (NumFreeOps < Min) { 1291 Min = NumFreeOps; 1292 BestLane = Lane; 1293 } 1294 } 1295 return BestLane; 1296 } 1297 1298 /// \Returns the maximum number of operands that are allowed to be reordered 1299 /// for \p Lane. This is used as a heuristic for selecting the first lane to 1300 /// start operand reordering. 1301 unsigned getMaxNumOperandsThatCanBeReordered(unsigned Lane) const { 1302 unsigned CntTrue = 0; 1303 unsigned NumOperands = getNumOperands(); 1304 // Operands with the same APO can be reordered. We therefore need to count 1305 // how many of them we have for each APO, like this: Cnt[APO] = x. 1306 // Since we only have two APOs, namely true and false, we can avoid using 1307 // a map. Instead we can simply count the number of operands that 1308 // correspond to one of them (in this case the 'true' APO), and calculate 1309 // the other by subtracting it from the total number of operands. 1310 for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) 1311 if (getData(OpIdx, Lane).APO) 1312 ++CntTrue; 1313 unsigned CntFalse = NumOperands - CntTrue; 1314 return std::max(CntTrue, CntFalse); 1315 } 1316 1317 /// Go through the instructions in VL and append their operands. 1318 void appendOperandsOfVL(ArrayRef<Value *> VL) { 1319 assert(!VL.empty() && "Bad VL"); 1320 assert((empty() || VL.size() == getNumLanes()) && 1321 "Expected same number of lanes"); 1322 assert(isa<Instruction>(VL[0]) && "Expected instruction"); 1323 unsigned NumOperands = cast<Instruction>(VL[0])->getNumOperands(); 1324 OpsVec.resize(NumOperands); 1325 unsigned NumLanes = VL.size(); 1326 for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) { 1327 OpsVec[OpIdx].resize(NumLanes); 1328 for (unsigned Lane = 0; Lane != NumLanes; ++Lane) { 1329 assert(isa<Instruction>(VL[Lane]) && "Expected instruction"); 1330 // Our tree has just 3 nodes: the root and two operands. 1331 // It is therefore trivial to get the APO. We only need to check the 1332 // opcode of VL[Lane] and whether the operand at OpIdx is the LHS or 1333 // RHS operand. The LHS operand of both add and sub is never attached 1334 // to an inversese operation in the linearized form, therefore its APO 1335 // is false. The RHS is true only if VL[Lane] is an inverse operation. 1336 1337 // Since operand reordering is performed on groups of commutative 1338 // operations or alternating sequences (e.g., +, -), we can safely 1339 // tell the inverse operations by checking commutativity. 1340 bool IsInverseOperation = !isCommutative(cast<Instruction>(VL[Lane])); 1341 bool APO = (OpIdx == 0) ? false : IsInverseOperation; 1342 OpsVec[OpIdx][Lane] = {cast<Instruction>(VL[Lane])->getOperand(OpIdx), 1343 APO, false}; 1344 } 1345 } 1346 } 1347 1348 /// \returns the number of operands. 1349 unsigned getNumOperands() const { return OpsVec.size(); } 1350 1351 /// \returns the number of lanes. 1352 unsigned getNumLanes() const { return OpsVec[0].size(); } 1353 1354 /// \returns the operand value at \p OpIdx and \p Lane. 1355 Value *getValue(unsigned OpIdx, unsigned Lane) const { 1356 return getData(OpIdx, Lane).V; 1357 } 1358 1359 /// \returns true if the data structure is empty. 1360 bool empty() const { return OpsVec.empty(); } 1361 1362 /// Clears the data. 1363 void clear() { OpsVec.clear(); } 1364 1365 /// \Returns true if there are enough operands identical to \p Op to fill 1366 /// the whole vector. 1367 /// Note: This modifies the 'IsUsed' flag, so a cleanUsed() must follow. 1368 bool shouldBroadcast(Value *Op, unsigned OpIdx, unsigned Lane) { 1369 bool OpAPO = getData(OpIdx, Lane).APO; 1370 for (unsigned Ln = 0, Lns = getNumLanes(); Ln != Lns; ++Ln) { 1371 if (Ln == Lane) 1372 continue; 1373 // This is set to true if we found a candidate for broadcast at Lane. 1374 bool FoundCandidate = false; 1375 for (unsigned OpI = 0, OpE = getNumOperands(); OpI != OpE; ++OpI) { 1376 OperandData &Data = getData(OpI, Ln); 1377 if (Data.APO != OpAPO || Data.IsUsed) 1378 continue; 1379 if (Data.V == Op) { 1380 FoundCandidate = true; 1381 Data.IsUsed = true; 1382 break; 1383 } 1384 } 1385 if (!FoundCandidate) 1386 return false; 1387 } 1388 return true; 1389 } 1390 1391 public: 1392 /// Initialize with all the operands of the instruction vector \p RootVL. 1393 VLOperands(ArrayRef<Value *> RootVL, const DataLayout &DL, 1394 ScalarEvolution &SE, const BoUpSLP &R) 1395 : DL(DL), SE(SE), R(R) { 1396 // Append all the operands of RootVL. 1397 appendOperandsOfVL(RootVL); 1398 } 1399 1400 /// \Returns a value vector with the operands across all lanes for the 1401 /// opearnd at \p OpIdx. 1402 ValueList getVL(unsigned OpIdx) const { 1403 ValueList OpVL(OpsVec[OpIdx].size()); 1404 assert(OpsVec[OpIdx].size() == getNumLanes() && 1405 "Expected same num of lanes across all operands"); 1406 for (unsigned Lane = 0, Lanes = getNumLanes(); Lane != Lanes; ++Lane) 1407 OpVL[Lane] = OpsVec[OpIdx][Lane].V; 1408 return OpVL; 1409 } 1410 1411 // Performs operand reordering for 2 or more operands. 1412 // The original operands are in OrigOps[OpIdx][Lane]. 1413 // The reordered operands are returned in 'SortedOps[OpIdx][Lane]'. 1414 void reorder() { 1415 unsigned NumOperands = getNumOperands(); 1416 unsigned NumLanes = getNumLanes(); 1417 // Each operand has its own mode. We are using this mode to help us select 1418 // the instructions for each lane, so that they match best with the ones 1419 // we have selected so far. 1420 SmallVector<ReorderingMode, 2> ReorderingModes(NumOperands); 1421 1422 // This is a greedy single-pass algorithm. We are going over each lane 1423 // once and deciding on the best order right away with no back-tracking. 1424 // However, in order to increase its effectiveness, we start with the lane 1425 // that has operands that can move the least. For example, given the 1426 // following lanes: 1427 // Lane 0 : A[0] = B[0] + C[0] // Visited 3rd 1428 // Lane 1 : A[1] = C[1] - B[1] // Visited 1st 1429 // Lane 2 : A[2] = B[2] + C[2] // Visited 2nd 1430 // Lane 3 : A[3] = C[3] - B[3] // Visited 4th 1431 // we will start at Lane 1, since the operands of the subtraction cannot 1432 // be reordered. Then we will visit the rest of the lanes in a circular 1433 // fashion. That is, Lanes 2, then Lane 0, and finally Lane 3. 1434 1435 // Find the first lane that we will start our search from. 1436 unsigned FirstLane = getBestLaneToStartReordering(); 1437 1438 // Initialize the modes. 1439 for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) { 1440 Value *OpLane0 = getValue(OpIdx, FirstLane); 1441 // Keep track if we have instructions with all the same opcode on one 1442 // side. 1443 if (isa<LoadInst>(OpLane0)) 1444 ReorderingModes[OpIdx] = ReorderingMode::Load; 1445 else if (isa<Instruction>(OpLane0)) { 1446 // Check if OpLane0 should be broadcast. 1447 if (shouldBroadcast(OpLane0, OpIdx, FirstLane)) 1448 ReorderingModes[OpIdx] = ReorderingMode::Splat; 1449 else 1450 ReorderingModes[OpIdx] = ReorderingMode::Opcode; 1451 } 1452 else if (isa<Constant>(OpLane0)) 1453 ReorderingModes[OpIdx] = ReorderingMode::Constant; 1454 else if (isa<Argument>(OpLane0)) 1455 // Our best hope is a Splat. It may save some cost in some cases. 1456 ReorderingModes[OpIdx] = ReorderingMode::Splat; 1457 else 1458 // NOTE: This should be unreachable. 1459 ReorderingModes[OpIdx] = ReorderingMode::Failed; 1460 } 1461 1462 // If the initial strategy fails for any of the operand indexes, then we 1463 // perform reordering again in a second pass. This helps avoid assigning 1464 // high priority to the failed strategy, and should improve reordering for 1465 // the non-failed operand indexes. 1466 for (int Pass = 0; Pass != 2; ++Pass) { 1467 // Skip the second pass if the first pass did not fail. 1468 bool StrategyFailed = false; 1469 // Mark all operand data as free to use. 1470 clearUsed(); 1471 // We keep the original operand order for the FirstLane, so reorder the 1472 // rest of the lanes. We are visiting the nodes in a circular fashion, 1473 // using FirstLane as the center point and increasing the radius 1474 // distance. 1475 for (unsigned Distance = 1; Distance != NumLanes; ++Distance) { 1476 // Visit the lane on the right and then the lane on the left. 1477 for (int Direction : {+1, -1}) { 1478 int Lane = FirstLane + Direction * Distance; 1479 if (Lane < 0 || Lane >= (int)NumLanes) 1480 continue; 1481 int LastLane = Lane - Direction; 1482 assert(LastLane >= 0 && LastLane < (int)NumLanes && 1483 "Out of bounds"); 1484 // Look for a good match for each operand. 1485 for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) { 1486 // Search for the operand that matches SortedOps[OpIdx][Lane-1]. 1487 Optional<unsigned> BestIdx = 1488 getBestOperand(OpIdx, Lane, LastLane, ReorderingModes); 1489 // By not selecting a value, we allow the operands that follow to 1490 // select a better matching value. We will get a non-null value in 1491 // the next run of getBestOperand(). 1492 if (BestIdx) { 1493 // Swap the current operand with the one returned by 1494 // getBestOperand(). 1495 swap(OpIdx, BestIdx.getValue(), Lane); 1496 } else { 1497 // We failed to find a best operand, set mode to 'Failed'. 1498 ReorderingModes[OpIdx] = ReorderingMode::Failed; 1499 // Enable the second pass. 1500 StrategyFailed = true; 1501 } 1502 } 1503 } 1504 } 1505 // Skip second pass if the strategy did not fail. 1506 if (!StrategyFailed) 1507 break; 1508 } 1509 } 1510 1511 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1512 LLVM_DUMP_METHOD static StringRef getModeStr(ReorderingMode RMode) { 1513 switch (RMode) { 1514 case ReorderingMode::Load: 1515 return "Load"; 1516 case ReorderingMode::Opcode: 1517 return "Opcode"; 1518 case ReorderingMode::Constant: 1519 return "Constant"; 1520 case ReorderingMode::Splat: 1521 return "Splat"; 1522 case ReorderingMode::Failed: 1523 return "Failed"; 1524 } 1525 llvm_unreachable("Unimplemented Reordering Type"); 1526 } 1527 1528 LLVM_DUMP_METHOD static raw_ostream &printMode(ReorderingMode RMode, 1529 raw_ostream &OS) { 1530 return OS << getModeStr(RMode); 1531 } 1532 1533 /// Debug print. 1534 LLVM_DUMP_METHOD static void dumpMode(ReorderingMode RMode) { 1535 printMode(RMode, dbgs()); 1536 } 1537 1538 friend raw_ostream &operator<<(raw_ostream &OS, ReorderingMode RMode) { 1539 return printMode(RMode, OS); 1540 } 1541 1542 LLVM_DUMP_METHOD raw_ostream &print(raw_ostream &OS) const { 1543 const unsigned Indent = 2; 1544 unsigned Cnt = 0; 1545 for (const OperandDataVec &OpDataVec : OpsVec) { 1546 OS << "Operand " << Cnt++ << "\n"; 1547 for (const OperandData &OpData : OpDataVec) { 1548 OS.indent(Indent) << "{"; 1549 if (Value *V = OpData.V) 1550 OS << *V; 1551 else 1552 OS << "null"; 1553 OS << ", APO:" << OpData.APO << "}\n"; 1554 } 1555 OS << "\n"; 1556 } 1557 return OS; 1558 } 1559 1560 /// Debug print. 1561 LLVM_DUMP_METHOD void dump() const { print(dbgs()); } 1562 #endif 1563 }; 1564 1565 /// Checks if the instruction is marked for deletion. 1566 bool isDeleted(Instruction *I) const { return DeletedInstructions.count(I); } 1567 1568 /// Marks values operands for later deletion by replacing them with Undefs. 1569 void eraseInstructions(ArrayRef<Value *> AV); 1570 1571 ~BoUpSLP(); 1572 1573 private: 1574 /// Checks if all users of \p I are the part of the vectorization tree. 1575 bool areAllUsersVectorized(Instruction *I, 1576 ArrayRef<Value *> VectorizedVals) const; 1577 1578 /// \returns the cost of the vectorizable entry. 1579 InstructionCost getEntryCost(const TreeEntry *E, 1580 ArrayRef<Value *> VectorizedVals); 1581 1582 /// This is the recursive part of buildTree. 1583 void buildTree_rec(ArrayRef<Value *> Roots, unsigned Depth, 1584 const EdgeInfo &EI); 1585 1586 /// \returns true if the ExtractElement/ExtractValue instructions in \p VL can 1587 /// be vectorized to use the original vector (or aggregate "bitcast" to a 1588 /// vector) and sets \p CurrentOrder to the identity permutation; otherwise 1589 /// returns false, setting \p CurrentOrder to either an empty vector or a 1590 /// non-identity permutation that allows to reuse extract instructions. 1591 bool canReuseExtract(ArrayRef<Value *> VL, Value *OpValue, 1592 SmallVectorImpl<unsigned> &CurrentOrder) const; 1593 1594 /// Vectorize a single entry in the tree. 1595 Value *vectorizeTree(TreeEntry *E); 1596 1597 /// Vectorize a single entry in the tree, starting in \p VL. 1598 Value *vectorizeTree(ArrayRef<Value *> VL); 1599 1600 /// \returns the scalarization cost for this type. Scalarization in this 1601 /// context means the creation of vectors from a group of scalars. 1602 InstructionCost 1603 getGatherCost(FixedVectorType *Ty, 1604 const DenseSet<unsigned> &ShuffledIndices) const; 1605 1606 /// Checks if the gathered \p VL can be represented as shuffle(s) of previous 1607 /// tree entries. 1608 /// \returns ShuffleKind, if gathered values can be represented as shuffles of 1609 /// previous tree entries. \p Mask is filled with the shuffle mask. 1610 Optional<TargetTransformInfo::ShuffleKind> 1611 isGatherShuffledEntry(const TreeEntry *TE, SmallVectorImpl<int> &Mask, 1612 SmallVectorImpl<const TreeEntry *> &Entries); 1613 1614 /// \returns the scalarization cost for this list of values. Assuming that 1615 /// this subtree gets vectorized, we may need to extract the values from the 1616 /// roots. This method calculates the cost of extracting the values. 1617 InstructionCost getGatherCost(ArrayRef<Value *> VL) const; 1618 1619 /// Set the Builder insert point to one after the last instruction in 1620 /// the bundle 1621 void setInsertPointAfterBundle(const TreeEntry *E); 1622 1623 /// \returns a vector from a collection of scalars in \p VL. 1624 Value *gather(ArrayRef<Value *> VL); 1625 1626 /// \returns whether the VectorizableTree is fully vectorizable and will 1627 /// be beneficial even the tree height is tiny. 1628 bool isFullyVectorizableTinyTree(bool ForReduction) const; 1629 1630 /// Reorder commutative or alt operands to get better probability of 1631 /// generating vectorized code. 1632 static void reorderInputsAccordingToOpcode(ArrayRef<Value *> VL, 1633 SmallVectorImpl<Value *> &Left, 1634 SmallVectorImpl<Value *> &Right, 1635 const DataLayout &DL, 1636 ScalarEvolution &SE, 1637 const BoUpSLP &R); 1638 struct TreeEntry { 1639 using VecTreeTy = SmallVector<std::unique_ptr<TreeEntry>, 8>; 1640 TreeEntry(VecTreeTy &Container) : Container(Container) {} 1641 1642 /// \returns true if the scalars in VL are equal to this entry. 1643 bool isSame(ArrayRef<Value *> VL) const { 1644 auto &&IsSame = [VL](ArrayRef<Value *> Scalars, ArrayRef<int> Mask) { 1645 if (Mask.size() != VL.size() && VL.size() == Scalars.size()) 1646 return std::equal(VL.begin(), VL.end(), Scalars.begin()); 1647 return VL.size() == Mask.size() && 1648 std::equal(VL.begin(), VL.end(), Mask.begin(), 1649 [Scalars](Value *V, int Idx) { 1650 return (isa<UndefValue>(V) && 1651 Idx == UndefMaskElem) || 1652 (Idx != UndefMaskElem && V == Scalars[Idx]); 1653 }); 1654 }; 1655 if (!ReorderIndices.empty()) { 1656 // TODO: implement matching if the nodes are just reordered, still can 1657 // treat the vector as the same if the list of scalars matches VL 1658 // directly, without reordering. 1659 SmallVector<int> Mask; 1660 inversePermutation(ReorderIndices, Mask); 1661 if (VL.size() == Scalars.size()) 1662 return IsSame(Scalars, Mask); 1663 if (VL.size() == ReuseShuffleIndices.size()) { 1664 ::addMask(Mask, ReuseShuffleIndices); 1665 return IsSame(Scalars, Mask); 1666 } 1667 return false; 1668 } 1669 return IsSame(Scalars, ReuseShuffleIndices); 1670 } 1671 1672 /// A vector of scalars. 1673 ValueList Scalars; 1674 1675 /// The Scalars are vectorized into this value. It is initialized to Null. 1676 Value *VectorizedValue = nullptr; 1677 1678 /// Do we need to gather this sequence or vectorize it 1679 /// (either with vector instruction or with scatter/gather 1680 /// intrinsics for store/load)? 1681 enum EntryState { Vectorize, ScatterVectorize, NeedToGather }; 1682 EntryState State; 1683 1684 /// Does this sequence require some shuffling? 1685 SmallVector<int, 4> ReuseShuffleIndices; 1686 1687 /// Does this entry require reordering? 1688 SmallVector<unsigned, 4> ReorderIndices; 1689 1690 /// Points back to the VectorizableTree. 1691 /// 1692 /// Only used for Graphviz right now. Unfortunately GraphTrait::NodeRef has 1693 /// to be a pointer and needs to be able to initialize the child iterator. 1694 /// Thus we need a reference back to the container to translate the indices 1695 /// to entries. 1696 VecTreeTy &Container; 1697 1698 /// The TreeEntry index containing the user of this entry. We can actually 1699 /// have multiple users so the data structure is not truly a tree. 1700 SmallVector<EdgeInfo, 1> UserTreeIndices; 1701 1702 /// The index of this treeEntry in VectorizableTree. 1703 int Idx = -1; 1704 1705 private: 1706 /// The operands of each instruction in each lane Operands[op_index][lane]. 1707 /// Note: This helps avoid the replication of the code that performs the 1708 /// reordering of operands during buildTree_rec() and vectorizeTree(). 1709 SmallVector<ValueList, 2> Operands; 1710 1711 /// The main/alternate instruction. 1712 Instruction *MainOp = nullptr; 1713 Instruction *AltOp = nullptr; 1714 1715 public: 1716 /// Set this bundle's \p OpIdx'th operand to \p OpVL. 1717 void setOperand(unsigned OpIdx, ArrayRef<Value *> OpVL) { 1718 if (Operands.size() < OpIdx + 1) 1719 Operands.resize(OpIdx + 1); 1720 assert(Operands[OpIdx].empty() && "Already resized?"); 1721 Operands[OpIdx].resize(Scalars.size()); 1722 for (unsigned Lane = 0, E = Scalars.size(); Lane != E; ++Lane) 1723 Operands[OpIdx][Lane] = OpVL[Lane]; 1724 } 1725 1726 /// Set the operands of this bundle in their original order. 1727 void setOperandsInOrder() { 1728 assert(Operands.empty() && "Already initialized?"); 1729 auto *I0 = cast<Instruction>(Scalars[0]); 1730 Operands.resize(I0->getNumOperands()); 1731 unsigned NumLanes = Scalars.size(); 1732 for (unsigned OpIdx = 0, NumOperands = I0->getNumOperands(); 1733 OpIdx != NumOperands; ++OpIdx) { 1734 Operands[OpIdx].resize(NumLanes); 1735 for (unsigned Lane = 0; Lane != NumLanes; ++Lane) { 1736 auto *I = cast<Instruction>(Scalars[Lane]); 1737 assert(I->getNumOperands() == NumOperands && 1738 "Expected same number of operands"); 1739 Operands[OpIdx][Lane] = I->getOperand(OpIdx); 1740 } 1741 } 1742 } 1743 1744 /// Reorders operands of the node to the given mask \p Mask. 1745 void reorderOperands(ArrayRef<int> Mask) { 1746 for (ValueList &Operand : Operands) 1747 reorderScalars(Operand, Mask); 1748 } 1749 1750 /// \returns the \p OpIdx operand of this TreeEntry. 1751 ValueList &getOperand(unsigned OpIdx) { 1752 assert(OpIdx < Operands.size() && "Off bounds"); 1753 return Operands[OpIdx]; 1754 } 1755 1756 /// \returns the number of operands. 1757 unsigned getNumOperands() const { return Operands.size(); } 1758 1759 /// \return the single \p OpIdx operand. 1760 Value *getSingleOperand(unsigned OpIdx) const { 1761 assert(OpIdx < Operands.size() && "Off bounds"); 1762 assert(!Operands[OpIdx].empty() && "No operand available"); 1763 return Operands[OpIdx][0]; 1764 } 1765 1766 /// Some of the instructions in the list have alternate opcodes. 1767 bool isAltShuffle() const { 1768 return getOpcode() != getAltOpcode(); 1769 } 1770 1771 bool isOpcodeOrAlt(Instruction *I) const { 1772 unsigned CheckedOpcode = I->getOpcode(); 1773 return (getOpcode() == CheckedOpcode || 1774 getAltOpcode() == CheckedOpcode); 1775 } 1776 1777 /// Chooses the correct key for scheduling data. If \p Op has the same (or 1778 /// alternate) opcode as \p OpValue, the key is \p Op. Otherwise the key is 1779 /// \p OpValue. 1780 Value *isOneOf(Value *Op) const { 1781 auto *I = dyn_cast<Instruction>(Op); 1782 if (I && isOpcodeOrAlt(I)) 1783 return Op; 1784 return MainOp; 1785 } 1786 1787 void setOperations(const InstructionsState &S) { 1788 MainOp = S.MainOp; 1789 AltOp = S.AltOp; 1790 } 1791 1792 Instruction *getMainOp() const { 1793 return MainOp; 1794 } 1795 1796 Instruction *getAltOp() const { 1797 return AltOp; 1798 } 1799 1800 /// The main/alternate opcodes for the list of instructions. 1801 unsigned getOpcode() const { 1802 return MainOp ? MainOp->getOpcode() : 0; 1803 } 1804 1805 unsigned getAltOpcode() const { 1806 return AltOp ? AltOp->getOpcode() : 0; 1807 } 1808 1809 /// When ReuseReorderShuffleIndices is empty it just returns position of \p 1810 /// V within vector of Scalars. Otherwise, try to remap on its reuse index. 1811 int findLaneForValue(Value *V) const { 1812 unsigned FoundLane = std::distance(Scalars.begin(), find(Scalars, V)); 1813 assert(FoundLane < Scalars.size() && "Couldn't find extract lane"); 1814 if (!ReorderIndices.empty()) 1815 FoundLane = ReorderIndices[FoundLane]; 1816 assert(FoundLane < Scalars.size() && "Couldn't find extract lane"); 1817 if (!ReuseShuffleIndices.empty()) { 1818 FoundLane = std::distance(ReuseShuffleIndices.begin(), 1819 find(ReuseShuffleIndices, FoundLane)); 1820 } 1821 return FoundLane; 1822 } 1823 1824 #ifndef NDEBUG 1825 /// Debug printer. 1826 LLVM_DUMP_METHOD void dump() const { 1827 dbgs() << Idx << ".\n"; 1828 for (unsigned OpI = 0, OpE = Operands.size(); OpI != OpE; ++OpI) { 1829 dbgs() << "Operand " << OpI << ":\n"; 1830 for (const Value *V : Operands[OpI]) 1831 dbgs().indent(2) << *V << "\n"; 1832 } 1833 dbgs() << "Scalars: \n"; 1834 for (Value *V : Scalars) 1835 dbgs().indent(2) << *V << "\n"; 1836 dbgs() << "State: "; 1837 switch (State) { 1838 case Vectorize: 1839 dbgs() << "Vectorize\n"; 1840 break; 1841 case ScatterVectorize: 1842 dbgs() << "ScatterVectorize\n"; 1843 break; 1844 case NeedToGather: 1845 dbgs() << "NeedToGather\n"; 1846 break; 1847 } 1848 dbgs() << "MainOp: "; 1849 if (MainOp) 1850 dbgs() << *MainOp << "\n"; 1851 else 1852 dbgs() << "NULL\n"; 1853 dbgs() << "AltOp: "; 1854 if (AltOp) 1855 dbgs() << *AltOp << "\n"; 1856 else 1857 dbgs() << "NULL\n"; 1858 dbgs() << "VectorizedValue: "; 1859 if (VectorizedValue) 1860 dbgs() << *VectorizedValue << "\n"; 1861 else 1862 dbgs() << "NULL\n"; 1863 dbgs() << "ReuseShuffleIndices: "; 1864 if (ReuseShuffleIndices.empty()) 1865 dbgs() << "Empty"; 1866 else 1867 for (unsigned ReuseIdx : ReuseShuffleIndices) 1868 dbgs() << ReuseIdx << ", "; 1869 dbgs() << "\n"; 1870 dbgs() << "ReorderIndices: "; 1871 for (unsigned ReorderIdx : ReorderIndices) 1872 dbgs() << ReorderIdx << ", "; 1873 dbgs() << "\n"; 1874 dbgs() << "UserTreeIndices: "; 1875 for (const auto &EInfo : UserTreeIndices) 1876 dbgs() << EInfo << ", "; 1877 dbgs() << "\n"; 1878 } 1879 #endif 1880 }; 1881 1882 #ifndef NDEBUG 1883 void dumpTreeCosts(const TreeEntry *E, InstructionCost ReuseShuffleCost, 1884 InstructionCost VecCost, 1885 InstructionCost ScalarCost) const { 1886 dbgs() << "SLP: Calculated costs for Tree:\n"; E->dump(); 1887 dbgs() << "SLP: Costs:\n"; 1888 dbgs() << "SLP: ReuseShuffleCost = " << ReuseShuffleCost << "\n"; 1889 dbgs() << "SLP: VectorCost = " << VecCost << "\n"; 1890 dbgs() << "SLP: ScalarCost = " << ScalarCost << "\n"; 1891 dbgs() << "SLP: ReuseShuffleCost + VecCost - ScalarCost = " << 1892 ReuseShuffleCost + VecCost - ScalarCost << "\n"; 1893 } 1894 #endif 1895 1896 /// Create a new VectorizableTree entry. 1897 TreeEntry *newTreeEntry(ArrayRef<Value *> VL, Optional<ScheduleData *> Bundle, 1898 const InstructionsState &S, 1899 const EdgeInfo &UserTreeIdx, 1900 ArrayRef<int> ReuseShuffleIndices = None, 1901 ArrayRef<unsigned> ReorderIndices = None) { 1902 TreeEntry::EntryState EntryState = 1903 Bundle ? TreeEntry::Vectorize : TreeEntry::NeedToGather; 1904 return newTreeEntry(VL, EntryState, Bundle, S, UserTreeIdx, 1905 ReuseShuffleIndices, ReorderIndices); 1906 } 1907 1908 TreeEntry *newTreeEntry(ArrayRef<Value *> VL, 1909 TreeEntry::EntryState EntryState, 1910 Optional<ScheduleData *> Bundle, 1911 const InstructionsState &S, 1912 const EdgeInfo &UserTreeIdx, 1913 ArrayRef<int> ReuseShuffleIndices = None, 1914 ArrayRef<unsigned> ReorderIndices = None) { 1915 assert(((!Bundle && EntryState == TreeEntry::NeedToGather) || 1916 (Bundle && EntryState != TreeEntry::NeedToGather)) && 1917 "Need to vectorize gather entry?"); 1918 VectorizableTree.push_back(std::make_unique<TreeEntry>(VectorizableTree)); 1919 TreeEntry *Last = VectorizableTree.back().get(); 1920 Last->Idx = VectorizableTree.size() - 1; 1921 Last->State = EntryState; 1922 Last->ReuseShuffleIndices.append(ReuseShuffleIndices.begin(), 1923 ReuseShuffleIndices.end()); 1924 if (ReorderIndices.empty()) { 1925 Last->Scalars.assign(VL.begin(), VL.end()); 1926 Last->setOperations(S); 1927 } else { 1928 // Reorder scalars and build final mask. 1929 Last->Scalars.assign(VL.size(), nullptr); 1930 transform(ReorderIndices, Last->Scalars.begin(), 1931 [VL](unsigned Idx) -> Value * { 1932 if (Idx >= VL.size()) 1933 return UndefValue::get(VL.front()->getType()); 1934 return VL[Idx]; 1935 }); 1936 InstructionsState S = getSameOpcode(Last->Scalars); 1937 Last->setOperations(S); 1938 Last->ReorderIndices.append(ReorderIndices.begin(), ReorderIndices.end()); 1939 } 1940 if (Last->State != TreeEntry::NeedToGather) { 1941 for (Value *V : VL) { 1942 assert(!getTreeEntry(V) && "Scalar already in tree!"); 1943 ScalarToTreeEntry[V] = Last; 1944 } 1945 // Update the scheduler bundle to point to this TreeEntry. 1946 unsigned Lane = 0; 1947 for (ScheduleData *BundleMember = Bundle.getValue(); BundleMember; 1948 BundleMember = BundleMember->NextInBundle) { 1949 BundleMember->TE = Last; 1950 BundleMember->Lane = Lane; 1951 ++Lane; 1952 } 1953 assert((!Bundle.getValue() || Lane == VL.size()) && 1954 "Bundle and VL out of sync"); 1955 } else { 1956 MustGather.insert(VL.begin(), VL.end()); 1957 } 1958 1959 if (UserTreeIdx.UserTE) 1960 Last->UserTreeIndices.push_back(UserTreeIdx); 1961 1962 return Last; 1963 } 1964 1965 /// -- Vectorization State -- 1966 /// Holds all of the tree entries. 1967 TreeEntry::VecTreeTy VectorizableTree; 1968 1969 #ifndef NDEBUG 1970 /// Debug printer. 1971 LLVM_DUMP_METHOD void dumpVectorizableTree() const { 1972 for (unsigned Id = 0, IdE = VectorizableTree.size(); Id != IdE; ++Id) { 1973 VectorizableTree[Id]->dump(); 1974 dbgs() << "\n"; 1975 } 1976 } 1977 #endif 1978 1979 TreeEntry *getTreeEntry(Value *V) { return ScalarToTreeEntry.lookup(V); } 1980 1981 const TreeEntry *getTreeEntry(Value *V) const { 1982 return ScalarToTreeEntry.lookup(V); 1983 } 1984 1985 /// Maps a specific scalar to its tree entry. 1986 SmallDenseMap<Value*, TreeEntry *> ScalarToTreeEntry; 1987 1988 /// Maps a value to the proposed vectorizable size. 1989 SmallDenseMap<Value *, unsigned> InstrElementSize; 1990 1991 /// A list of scalars that we found that we need to keep as scalars. 1992 ValueSet MustGather; 1993 1994 /// This POD struct describes one external user in the vectorized tree. 1995 struct ExternalUser { 1996 ExternalUser(Value *S, llvm::User *U, int L) 1997 : Scalar(S), User(U), Lane(L) {} 1998 1999 // Which scalar in our function. 2000 Value *Scalar; 2001 2002 // Which user that uses the scalar. 2003 llvm::User *User; 2004 2005 // Which lane does the scalar belong to. 2006 int Lane; 2007 }; 2008 using UserList = SmallVector<ExternalUser, 16>; 2009 2010 /// Checks if two instructions may access the same memory. 2011 /// 2012 /// \p Loc1 is the location of \p Inst1. It is passed explicitly because it 2013 /// is invariant in the calling loop. 2014 bool isAliased(const MemoryLocation &Loc1, Instruction *Inst1, 2015 Instruction *Inst2) { 2016 // First check if the result is already in the cache. 2017 AliasCacheKey key = std::make_pair(Inst1, Inst2); 2018 Optional<bool> &result = AliasCache[key]; 2019 if (result.hasValue()) { 2020 return result.getValue(); 2021 } 2022 bool aliased = true; 2023 if (Loc1.Ptr && isSimple(Inst1)) 2024 aliased = isModOrRefSet(AA->getModRefInfo(Inst2, Loc1)); 2025 // Store the result in the cache. 2026 result = aliased; 2027 return aliased; 2028 } 2029 2030 using AliasCacheKey = std::pair<Instruction *, Instruction *>; 2031 2032 /// Cache for alias results. 2033 /// TODO: consider moving this to the AliasAnalysis itself. 2034 DenseMap<AliasCacheKey, Optional<bool>> AliasCache; 2035 2036 /// Removes an instruction from its block and eventually deletes it. 2037 /// It's like Instruction::eraseFromParent() except that the actual deletion 2038 /// is delayed until BoUpSLP is destructed. 2039 /// This is required to ensure that there are no incorrect collisions in the 2040 /// AliasCache, which can happen if a new instruction is allocated at the 2041 /// same address as a previously deleted instruction. 2042 void eraseInstruction(Instruction *I, bool ReplaceOpsWithUndef = false) { 2043 auto It = DeletedInstructions.try_emplace(I, ReplaceOpsWithUndef).first; 2044 It->getSecond() = It->getSecond() && ReplaceOpsWithUndef; 2045 } 2046 2047 /// Temporary store for deleted instructions. Instructions will be deleted 2048 /// eventually when the BoUpSLP is destructed. 2049 DenseMap<Instruction *, bool> DeletedInstructions; 2050 2051 /// A list of values that need to extracted out of the tree. 2052 /// This list holds pairs of (Internal Scalar : External User). External User 2053 /// can be nullptr, it means that this Internal Scalar will be used later, 2054 /// after vectorization. 2055 UserList ExternalUses; 2056 2057 /// Values used only by @llvm.assume calls. 2058 SmallPtrSet<const Value *, 32> EphValues; 2059 2060 /// Holds all of the instructions that we gathered. 2061 SetVector<Instruction *> GatherSeq; 2062 2063 /// A list of blocks that we are going to CSE. 2064 SetVector<BasicBlock *> CSEBlocks; 2065 2066 /// Contains all scheduling relevant data for an instruction. 2067 /// A ScheduleData either represents a single instruction or a member of an 2068 /// instruction bundle (= a group of instructions which is combined into a 2069 /// vector instruction). 2070 struct ScheduleData { 2071 // The initial value for the dependency counters. It means that the 2072 // dependencies are not calculated yet. 2073 enum { InvalidDeps = -1 }; 2074 2075 ScheduleData() = default; 2076 2077 void init(int BlockSchedulingRegionID, Value *OpVal) { 2078 FirstInBundle = this; 2079 NextInBundle = nullptr; 2080 NextLoadStore = nullptr; 2081 IsScheduled = false; 2082 SchedulingRegionID = BlockSchedulingRegionID; 2083 UnscheduledDepsInBundle = UnscheduledDeps; 2084 clearDependencies(); 2085 OpValue = OpVal; 2086 TE = nullptr; 2087 Lane = -1; 2088 } 2089 2090 /// Returns true if the dependency information has been calculated. 2091 bool hasValidDependencies() const { return Dependencies != InvalidDeps; } 2092 2093 /// Returns true for single instructions and for bundle representatives 2094 /// (= the head of a bundle). 2095 bool isSchedulingEntity() const { return FirstInBundle == this; } 2096 2097 /// Returns true if it represents an instruction bundle and not only a 2098 /// single instruction. 2099 bool isPartOfBundle() const { 2100 return NextInBundle != nullptr || FirstInBundle != this; 2101 } 2102 2103 /// Returns true if it is ready for scheduling, i.e. it has no more 2104 /// unscheduled depending instructions/bundles. 2105 bool isReady() const { 2106 assert(isSchedulingEntity() && 2107 "can't consider non-scheduling entity for ready list"); 2108 return UnscheduledDepsInBundle == 0 && !IsScheduled; 2109 } 2110 2111 /// Modifies the number of unscheduled dependencies, also updating it for 2112 /// the whole bundle. 2113 int incrementUnscheduledDeps(int Incr) { 2114 UnscheduledDeps += Incr; 2115 return FirstInBundle->UnscheduledDepsInBundle += Incr; 2116 } 2117 2118 /// Sets the number of unscheduled dependencies to the number of 2119 /// dependencies. 2120 void resetUnscheduledDeps() { 2121 incrementUnscheduledDeps(Dependencies - UnscheduledDeps); 2122 } 2123 2124 /// Clears all dependency information. 2125 void clearDependencies() { 2126 Dependencies = InvalidDeps; 2127 resetUnscheduledDeps(); 2128 MemoryDependencies.clear(); 2129 } 2130 2131 void dump(raw_ostream &os) const { 2132 if (!isSchedulingEntity()) { 2133 os << "/ " << *Inst; 2134 } else if (NextInBundle) { 2135 os << '[' << *Inst; 2136 ScheduleData *SD = NextInBundle; 2137 while (SD) { 2138 os << ';' << *SD->Inst; 2139 SD = SD->NextInBundle; 2140 } 2141 os << ']'; 2142 } else { 2143 os << *Inst; 2144 } 2145 } 2146 2147 Instruction *Inst = nullptr; 2148 2149 /// Points to the head in an instruction bundle (and always to this for 2150 /// single instructions). 2151 ScheduleData *FirstInBundle = nullptr; 2152 2153 /// Single linked list of all instructions in a bundle. Null if it is a 2154 /// single instruction. 2155 ScheduleData *NextInBundle = nullptr; 2156 2157 /// Single linked list of all memory instructions (e.g. load, store, call) 2158 /// in the block - until the end of the scheduling region. 2159 ScheduleData *NextLoadStore = nullptr; 2160 2161 /// The dependent memory instructions. 2162 /// This list is derived on demand in calculateDependencies(). 2163 SmallVector<ScheduleData *, 4> MemoryDependencies; 2164 2165 /// This ScheduleData is in the current scheduling region if this matches 2166 /// the current SchedulingRegionID of BlockScheduling. 2167 int SchedulingRegionID = 0; 2168 2169 /// Used for getting a "good" final ordering of instructions. 2170 int SchedulingPriority = 0; 2171 2172 /// The number of dependencies. Constitutes of the number of users of the 2173 /// instruction plus the number of dependent memory instructions (if any). 2174 /// This value is calculated on demand. 2175 /// If InvalidDeps, the number of dependencies is not calculated yet. 2176 int Dependencies = InvalidDeps; 2177 2178 /// The number of dependencies minus the number of dependencies of scheduled 2179 /// instructions. As soon as this is zero, the instruction/bundle gets ready 2180 /// for scheduling. 2181 /// Note that this is negative as long as Dependencies is not calculated. 2182 int UnscheduledDeps = InvalidDeps; 2183 2184 /// The sum of UnscheduledDeps in a bundle. Equals to UnscheduledDeps for 2185 /// single instructions. 2186 int UnscheduledDepsInBundle = InvalidDeps; 2187 2188 /// True if this instruction is scheduled (or considered as scheduled in the 2189 /// dry-run). 2190 bool IsScheduled = false; 2191 2192 /// Opcode of the current instruction in the schedule data. 2193 Value *OpValue = nullptr; 2194 2195 /// The TreeEntry that this instruction corresponds to. 2196 TreeEntry *TE = nullptr; 2197 2198 /// The lane of this node in the TreeEntry. 2199 int Lane = -1; 2200 }; 2201 2202 #ifndef NDEBUG 2203 friend inline raw_ostream &operator<<(raw_ostream &os, 2204 const BoUpSLP::ScheduleData &SD) { 2205 SD.dump(os); 2206 return os; 2207 } 2208 #endif 2209 2210 friend struct GraphTraits<BoUpSLP *>; 2211 friend struct DOTGraphTraits<BoUpSLP *>; 2212 2213 /// Contains all scheduling data for a basic block. 2214 struct BlockScheduling { 2215 BlockScheduling(BasicBlock *BB) 2216 : BB(BB), ChunkSize(BB->size()), ChunkPos(ChunkSize) {} 2217 2218 void clear() { 2219 ReadyInsts.clear(); 2220 ScheduleStart = nullptr; 2221 ScheduleEnd = nullptr; 2222 FirstLoadStoreInRegion = nullptr; 2223 LastLoadStoreInRegion = nullptr; 2224 2225 // Reduce the maximum schedule region size by the size of the 2226 // previous scheduling run. 2227 ScheduleRegionSizeLimit -= ScheduleRegionSize; 2228 if (ScheduleRegionSizeLimit < MinScheduleRegionSize) 2229 ScheduleRegionSizeLimit = MinScheduleRegionSize; 2230 ScheduleRegionSize = 0; 2231 2232 // Make a new scheduling region, i.e. all existing ScheduleData is not 2233 // in the new region yet. 2234 ++SchedulingRegionID; 2235 } 2236 2237 ScheduleData *getScheduleData(Value *V) { 2238 ScheduleData *SD = ScheduleDataMap[V]; 2239 if (SD && SD->SchedulingRegionID == SchedulingRegionID) 2240 return SD; 2241 return nullptr; 2242 } 2243 2244 ScheduleData *getScheduleData(Value *V, Value *Key) { 2245 if (V == Key) 2246 return getScheduleData(V); 2247 auto I = ExtraScheduleDataMap.find(V); 2248 if (I != ExtraScheduleDataMap.end()) { 2249 ScheduleData *SD = I->second[Key]; 2250 if (SD && SD->SchedulingRegionID == SchedulingRegionID) 2251 return SD; 2252 } 2253 return nullptr; 2254 } 2255 2256 bool isInSchedulingRegion(ScheduleData *SD) const { 2257 return SD->SchedulingRegionID == SchedulingRegionID; 2258 } 2259 2260 /// Marks an instruction as scheduled and puts all dependent ready 2261 /// instructions into the ready-list. 2262 template <typename ReadyListType> 2263 void schedule(ScheduleData *SD, ReadyListType &ReadyList) { 2264 SD->IsScheduled = true; 2265 LLVM_DEBUG(dbgs() << "SLP: schedule " << *SD << "\n"); 2266 2267 ScheduleData *BundleMember = SD; 2268 while (BundleMember) { 2269 if (BundleMember->Inst != BundleMember->OpValue) { 2270 BundleMember = BundleMember->NextInBundle; 2271 continue; 2272 } 2273 // Handle the def-use chain dependencies. 2274 2275 // Decrement the unscheduled counter and insert to ready list if ready. 2276 auto &&DecrUnsched = [this, &ReadyList](Instruction *I) { 2277 doForAllOpcodes(I, [&ReadyList](ScheduleData *OpDef) { 2278 if (OpDef && OpDef->hasValidDependencies() && 2279 OpDef->incrementUnscheduledDeps(-1) == 0) { 2280 // There are no more unscheduled dependencies after 2281 // decrementing, so we can put the dependent instruction 2282 // into the ready list. 2283 ScheduleData *DepBundle = OpDef->FirstInBundle; 2284 assert(!DepBundle->IsScheduled && 2285 "already scheduled bundle gets ready"); 2286 ReadyList.insert(DepBundle); 2287 LLVM_DEBUG(dbgs() 2288 << "SLP: gets ready (def): " << *DepBundle << "\n"); 2289 } 2290 }); 2291 }; 2292 2293 // If BundleMember is a vector bundle, its operands may have been 2294 // reordered duiring buildTree(). We therefore need to get its operands 2295 // through the TreeEntry. 2296 if (TreeEntry *TE = BundleMember->TE) { 2297 int Lane = BundleMember->Lane; 2298 assert(Lane >= 0 && "Lane not set"); 2299 2300 // Since vectorization tree is being built recursively this assertion 2301 // ensures that the tree entry has all operands set before reaching 2302 // this code. Couple of exceptions known at the moment are extracts 2303 // where their second (immediate) operand is not added. Since 2304 // immediates do not affect scheduler behavior this is considered 2305 // okay. 2306 auto *In = TE->getMainOp(); 2307 assert(In && 2308 (isa<ExtractValueInst>(In) || isa<ExtractElementInst>(In) || 2309 In->getNumOperands() == TE->getNumOperands()) && 2310 "Missed TreeEntry operands?"); 2311 (void)In; // fake use to avoid build failure when assertions disabled 2312 2313 for (unsigned OpIdx = 0, NumOperands = TE->getNumOperands(); 2314 OpIdx != NumOperands; ++OpIdx) 2315 if (auto *I = dyn_cast<Instruction>(TE->getOperand(OpIdx)[Lane])) 2316 DecrUnsched(I); 2317 } else { 2318 // If BundleMember is a stand-alone instruction, no operand reordering 2319 // has taken place, so we directly access its operands. 2320 for (Use &U : BundleMember->Inst->operands()) 2321 if (auto *I = dyn_cast<Instruction>(U.get())) 2322 DecrUnsched(I); 2323 } 2324 // Handle the memory dependencies. 2325 for (ScheduleData *MemoryDepSD : BundleMember->MemoryDependencies) { 2326 if (MemoryDepSD->incrementUnscheduledDeps(-1) == 0) { 2327 // There are no more unscheduled dependencies after decrementing, 2328 // so we can put the dependent instruction into the ready list. 2329 ScheduleData *DepBundle = MemoryDepSD->FirstInBundle; 2330 assert(!DepBundle->IsScheduled && 2331 "already scheduled bundle gets ready"); 2332 ReadyList.insert(DepBundle); 2333 LLVM_DEBUG(dbgs() 2334 << "SLP: gets ready (mem): " << *DepBundle << "\n"); 2335 } 2336 } 2337 BundleMember = BundleMember->NextInBundle; 2338 } 2339 } 2340 2341 void doForAllOpcodes(Value *V, 2342 function_ref<void(ScheduleData *SD)> Action) { 2343 if (ScheduleData *SD = getScheduleData(V)) 2344 Action(SD); 2345 auto I = ExtraScheduleDataMap.find(V); 2346 if (I != ExtraScheduleDataMap.end()) 2347 for (auto &P : I->second) 2348 if (P.second->SchedulingRegionID == SchedulingRegionID) 2349 Action(P.second); 2350 } 2351 2352 /// Put all instructions into the ReadyList which are ready for scheduling. 2353 template <typename ReadyListType> 2354 void initialFillReadyList(ReadyListType &ReadyList) { 2355 for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) { 2356 doForAllOpcodes(I, [&](ScheduleData *SD) { 2357 if (SD->isSchedulingEntity() && SD->isReady()) { 2358 ReadyList.insert(SD); 2359 LLVM_DEBUG(dbgs() 2360 << "SLP: initially in ready list: " << *I << "\n"); 2361 } 2362 }); 2363 } 2364 } 2365 2366 /// Checks if a bundle of instructions can be scheduled, i.e. has no 2367 /// cyclic dependencies. This is only a dry-run, no instructions are 2368 /// actually moved at this stage. 2369 /// \returns the scheduling bundle. The returned Optional value is non-None 2370 /// if \p VL is allowed to be scheduled. 2371 Optional<ScheduleData *> 2372 tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP, 2373 const InstructionsState &S); 2374 2375 /// Un-bundles a group of instructions. 2376 void cancelScheduling(ArrayRef<Value *> VL, Value *OpValue); 2377 2378 /// Allocates schedule data chunk. 2379 ScheduleData *allocateScheduleDataChunks(); 2380 2381 /// Extends the scheduling region so that V is inside the region. 2382 /// \returns true if the region size is within the limit. 2383 bool extendSchedulingRegion(Value *V, const InstructionsState &S); 2384 2385 /// Initialize the ScheduleData structures for new instructions in the 2386 /// scheduling region. 2387 void initScheduleData(Instruction *FromI, Instruction *ToI, 2388 ScheduleData *PrevLoadStore, 2389 ScheduleData *NextLoadStore); 2390 2391 /// Updates the dependency information of a bundle and of all instructions/ 2392 /// bundles which depend on the original bundle. 2393 void calculateDependencies(ScheduleData *SD, bool InsertInReadyList, 2394 BoUpSLP *SLP); 2395 2396 /// Sets all instruction in the scheduling region to un-scheduled. 2397 void resetSchedule(); 2398 2399 BasicBlock *BB; 2400 2401 /// Simple memory allocation for ScheduleData. 2402 std::vector<std::unique_ptr<ScheduleData[]>> ScheduleDataChunks; 2403 2404 /// The size of a ScheduleData array in ScheduleDataChunks. 2405 int ChunkSize; 2406 2407 /// The allocator position in the current chunk, which is the last entry 2408 /// of ScheduleDataChunks. 2409 int ChunkPos; 2410 2411 /// Attaches ScheduleData to Instruction. 2412 /// Note that the mapping survives during all vectorization iterations, i.e. 2413 /// ScheduleData structures are recycled. 2414 DenseMap<Value *, ScheduleData *> ScheduleDataMap; 2415 2416 /// Attaches ScheduleData to Instruction with the leading key. 2417 DenseMap<Value *, SmallDenseMap<Value *, ScheduleData *>> 2418 ExtraScheduleDataMap; 2419 2420 struct ReadyList : SmallVector<ScheduleData *, 8> { 2421 void insert(ScheduleData *SD) { push_back(SD); } 2422 }; 2423 2424 /// The ready-list for scheduling (only used for the dry-run). 2425 ReadyList ReadyInsts; 2426 2427 /// The first instruction of the scheduling region. 2428 Instruction *ScheduleStart = nullptr; 2429 2430 /// The first instruction _after_ the scheduling region. 2431 Instruction *ScheduleEnd = nullptr; 2432 2433 /// The first memory accessing instruction in the scheduling region 2434 /// (can be null). 2435 ScheduleData *FirstLoadStoreInRegion = nullptr; 2436 2437 /// The last memory accessing instruction in the scheduling region 2438 /// (can be null). 2439 ScheduleData *LastLoadStoreInRegion = nullptr; 2440 2441 /// The current size of the scheduling region. 2442 int ScheduleRegionSize = 0; 2443 2444 /// The maximum size allowed for the scheduling region. 2445 int ScheduleRegionSizeLimit = ScheduleRegionSizeBudget; 2446 2447 /// The ID of the scheduling region. For a new vectorization iteration this 2448 /// is incremented which "removes" all ScheduleData from the region. 2449 // Make sure that the initial SchedulingRegionID is greater than the 2450 // initial SchedulingRegionID in ScheduleData (which is 0). 2451 int SchedulingRegionID = 1; 2452 }; 2453 2454 /// Attaches the BlockScheduling structures to basic blocks. 2455 MapVector<BasicBlock *, std::unique_ptr<BlockScheduling>> BlocksSchedules; 2456 2457 /// Performs the "real" scheduling. Done before vectorization is actually 2458 /// performed in a basic block. 2459 void scheduleBlock(BlockScheduling *BS); 2460 2461 /// List of users to ignore during scheduling and that don't need extracting. 2462 ArrayRef<Value *> UserIgnoreList; 2463 2464 /// A DenseMapInfo implementation for holding DenseMaps and DenseSets of 2465 /// sorted SmallVectors of unsigned. 2466 struct OrdersTypeDenseMapInfo { 2467 static OrdersType getEmptyKey() { 2468 OrdersType V; 2469 V.push_back(~1U); 2470 return V; 2471 } 2472 2473 static OrdersType getTombstoneKey() { 2474 OrdersType V; 2475 V.push_back(~2U); 2476 return V; 2477 } 2478 2479 static unsigned getHashValue(const OrdersType &V) { 2480 return static_cast<unsigned>(hash_combine_range(V.begin(), V.end())); 2481 } 2482 2483 static bool isEqual(const OrdersType &LHS, const OrdersType &RHS) { 2484 return LHS == RHS; 2485 } 2486 }; 2487 2488 // Analysis and block reference. 2489 Function *F; 2490 ScalarEvolution *SE; 2491 TargetTransformInfo *TTI; 2492 TargetLibraryInfo *TLI; 2493 AAResults *AA; 2494 LoopInfo *LI; 2495 DominatorTree *DT; 2496 AssumptionCache *AC; 2497 DemandedBits *DB; 2498 const DataLayout *DL; 2499 OptimizationRemarkEmitter *ORE; 2500 2501 unsigned MaxVecRegSize; // This is set by TTI or overridden by cl::opt. 2502 unsigned MinVecRegSize; // Set by cl::opt (default: 128). 2503 2504 /// Instruction builder to construct the vectorized tree. 2505 IRBuilder<> Builder; 2506 2507 /// A map of scalar integer values to the smallest bit width with which they 2508 /// can legally be represented. The values map to (width, signed) pairs, 2509 /// where "width" indicates the minimum bit width and "signed" is True if the 2510 /// value must be signed-extended, rather than zero-extended, back to its 2511 /// original width. 2512 MapVector<Value *, std::pair<uint64_t, bool>> MinBWs; 2513 }; 2514 2515 } // end namespace slpvectorizer 2516 2517 template <> struct GraphTraits<BoUpSLP *> { 2518 using TreeEntry = BoUpSLP::TreeEntry; 2519 2520 /// NodeRef has to be a pointer per the GraphWriter. 2521 using NodeRef = TreeEntry *; 2522 2523 using ContainerTy = BoUpSLP::TreeEntry::VecTreeTy; 2524 2525 /// Add the VectorizableTree to the index iterator to be able to return 2526 /// TreeEntry pointers. 2527 struct ChildIteratorType 2528 : public iterator_adaptor_base< 2529 ChildIteratorType, SmallVector<BoUpSLP::EdgeInfo, 1>::iterator> { 2530 ContainerTy &VectorizableTree; 2531 2532 ChildIteratorType(SmallVector<BoUpSLP::EdgeInfo, 1>::iterator W, 2533 ContainerTy &VT) 2534 : ChildIteratorType::iterator_adaptor_base(W), VectorizableTree(VT) {} 2535 2536 NodeRef operator*() { return I->UserTE; } 2537 }; 2538 2539 static NodeRef getEntryNode(BoUpSLP &R) { 2540 return R.VectorizableTree[0].get(); 2541 } 2542 2543 static ChildIteratorType child_begin(NodeRef N) { 2544 return {N->UserTreeIndices.begin(), N->Container}; 2545 } 2546 2547 static ChildIteratorType child_end(NodeRef N) { 2548 return {N->UserTreeIndices.end(), N->Container}; 2549 } 2550 2551 /// For the node iterator we just need to turn the TreeEntry iterator into a 2552 /// TreeEntry* iterator so that it dereferences to NodeRef. 2553 class nodes_iterator { 2554 using ItTy = ContainerTy::iterator; 2555 ItTy It; 2556 2557 public: 2558 nodes_iterator(const ItTy &It2) : It(It2) {} 2559 NodeRef operator*() { return It->get(); } 2560 nodes_iterator operator++() { 2561 ++It; 2562 return *this; 2563 } 2564 bool operator!=(const nodes_iterator &N2) const { return N2.It != It; } 2565 }; 2566 2567 static nodes_iterator nodes_begin(BoUpSLP *R) { 2568 return nodes_iterator(R->VectorizableTree.begin()); 2569 } 2570 2571 static nodes_iterator nodes_end(BoUpSLP *R) { 2572 return nodes_iterator(R->VectorizableTree.end()); 2573 } 2574 2575 static unsigned size(BoUpSLP *R) { return R->VectorizableTree.size(); } 2576 }; 2577 2578 template <> struct DOTGraphTraits<BoUpSLP *> : public DefaultDOTGraphTraits { 2579 using TreeEntry = BoUpSLP::TreeEntry; 2580 2581 DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {} 2582 2583 std::string getNodeLabel(const TreeEntry *Entry, const BoUpSLP *R) { 2584 std::string Str; 2585 raw_string_ostream OS(Str); 2586 if (isSplat(Entry->Scalars)) { 2587 OS << "<splat> " << *Entry->Scalars[0]; 2588 return Str; 2589 } 2590 for (auto V : Entry->Scalars) { 2591 OS << *V; 2592 if (llvm::any_of(R->ExternalUses, [&](const BoUpSLP::ExternalUser &EU) { 2593 return EU.Scalar == V; 2594 })) 2595 OS << " <extract>"; 2596 OS << "\n"; 2597 } 2598 return Str; 2599 } 2600 2601 static std::string getNodeAttributes(const TreeEntry *Entry, 2602 const BoUpSLP *) { 2603 if (Entry->State == TreeEntry::NeedToGather) 2604 return "color=red"; 2605 return ""; 2606 } 2607 }; 2608 2609 } // end namespace llvm 2610 2611 BoUpSLP::~BoUpSLP() { 2612 for (const auto &Pair : DeletedInstructions) { 2613 // Replace operands of ignored instructions with Undefs in case if they were 2614 // marked for deletion. 2615 if (Pair.getSecond()) { 2616 Value *Undef = UndefValue::get(Pair.getFirst()->getType()); 2617 Pair.getFirst()->replaceAllUsesWith(Undef); 2618 } 2619 Pair.getFirst()->dropAllReferences(); 2620 } 2621 for (const auto &Pair : DeletedInstructions) { 2622 assert(Pair.getFirst()->use_empty() && 2623 "trying to erase instruction with users."); 2624 Pair.getFirst()->eraseFromParent(); 2625 } 2626 #ifdef EXPENSIVE_CHECKS 2627 // If we could guarantee that this call is not extremely slow, we could 2628 // remove the ifdef limitation (see PR47712). 2629 assert(!verifyFunction(*F, &dbgs())); 2630 #endif 2631 } 2632 2633 void BoUpSLP::eraseInstructions(ArrayRef<Value *> AV) { 2634 for (auto *V : AV) { 2635 if (auto *I = dyn_cast<Instruction>(V)) 2636 eraseInstruction(I, /*ReplaceOpsWithUndef=*/true); 2637 }; 2638 } 2639 2640 /// Reorders the given \p Reuses mask according to the given \p Mask. \p Reuses 2641 /// contains original mask for the scalars reused in the node. Procedure 2642 /// transform this mask in accordance with the given \p Mask. 2643 static void reorderReuses(SmallVectorImpl<int> &Reuses, ArrayRef<int> Mask) { 2644 assert(!Mask.empty() && Reuses.size() == Mask.size() && 2645 "Expected non-empty mask."); 2646 SmallVector<int> Prev(Reuses.begin(), Reuses.end()); 2647 Prev.swap(Reuses); 2648 for (unsigned I = 0, E = Prev.size(); I < E; ++I) 2649 if (Mask[I] != UndefMaskElem) 2650 Reuses[Mask[I]] = Prev[I]; 2651 } 2652 2653 /// Reorders the given \p Order according to the given \p Mask. \p Order - is 2654 /// the original order of the scalars. Procedure transforms the provided order 2655 /// in accordance with the given \p Mask. If the resulting \p Order is just an 2656 /// identity order, \p Order is cleared. 2657 static void reorderOrder(SmallVectorImpl<unsigned> &Order, ArrayRef<int> Mask) { 2658 assert(!Mask.empty() && "Expected non-empty mask."); 2659 SmallVector<int> MaskOrder; 2660 if (Order.empty()) { 2661 MaskOrder.resize(Mask.size()); 2662 std::iota(MaskOrder.begin(), MaskOrder.end(), 0); 2663 } else { 2664 inversePermutation(Order, MaskOrder); 2665 } 2666 reorderReuses(MaskOrder, Mask); 2667 if (ShuffleVectorInst::isIdentityMask(MaskOrder)) { 2668 Order.clear(); 2669 return; 2670 } 2671 Order.assign(Mask.size(), Mask.size()); 2672 for (unsigned I = 0, E = Mask.size(); I < E; ++I) 2673 if (MaskOrder[I] != UndefMaskElem) 2674 Order[MaskOrder[I]] = I; 2675 fixupOrderingIndices(Order); 2676 } 2677 2678 Optional<BoUpSLP::OrdersType> 2679 BoUpSLP::findReusedOrderedScalars(const BoUpSLP::TreeEntry &TE) { 2680 assert(TE.State == TreeEntry::NeedToGather && "Expected gather node only."); 2681 unsigned NumScalars = TE.Scalars.size(); 2682 OrdersType CurrentOrder(NumScalars, NumScalars); 2683 SmallVector<int> Positions; 2684 SmallBitVector UsedPositions(NumScalars); 2685 const TreeEntry *STE = nullptr; 2686 // Try to find all gathered scalars that are gets vectorized in other 2687 // vectorize node. Here we can have only one single tree vector node to 2688 // correctly identify order of the gathered scalars. 2689 for (unsigned I = 0; I < NumScalars; ++I) { 2690 Value *V = TE.Scalars[I]; 2691 if (!isa<LoadInst, ExtractElementInst, ExtractValueInst>(V)) 2692 continue; 2693 if (const auto *LocalSTE = getTreeEntry(V)) { 2694 if (!STE) 2695 STE = LocalSTE; 2696 else if (STE != LocalSTE) 2697 // Take the order only from the single vector node. 2698 return None; 2699 unsigned Lane = 2700 std::distance(STE->Scalars.begin(), find(STE->Scalars, V)); 2701 if (Lane >= NumScalars) 2702 return None; 2703 if (CurrentOrder[Lane] != NumScalars) { 2704 if (Lane != I) 2705 continue; 2706 UsedPositions.reset(CurrentOrder[Lane]); 2707 } 2708 // The partial identity (where only some elements of the gather node are 2709 // in the identity order) is good. 2710 CurrentOrder[Lane] = I; 2711 UsedPositions.set(I); 2712 } 2713 } 2714 // Need to keep the order if we have a vector entry and at least 2 scalars or 2715 // the vectorized entry has just 2 scalars. 2716 if (STE && (UsedPositions.count() > 1 || STE->Scalars.size() == 2)) { 2717 auto &&IsIdentityOrder = [NumScalars](ArrayRef<unsigned> CurrentOrder) { 2718 for (unsigned I = 0; I < NumScalars; ++I) 2719 if (CurrentOrder[I] != I && CurrentOrder[I] != NumScalars) 2720 return false; 2721 return true; 2722 }; 2723 if (IsIdentityOrder(CurrentOrder)) { 2724 CurrentOrder.clear(); 2725 return CurrentOrder; 2726 } 2727 auto *It = CurrentOrder.begin(); 2728 for (unsigned I = 0; I < NumScalars;) { 2729 if (UsedPositions.test(I)) { 2730 ++I; 2731 continue; 2732 } 2733 if (*It == NumScalars) { 2734 *It = I; 2735 ++I; 2736 } 2737 ++It; 2738 } 2739 return CurrentOrder; 2740 } 2741 return None; 2742 } 2743 2744 void BoUpSLP::reorderTopToBottom() { 2745 // Maps VF to the graph nodes. 2746 DenseMap<unsigned, SmallPtrSet<TreeEntry *, 4>> VFToOrderedEntries; 2747 // ExtractElement gather nodes which can be vectorized and need to handle 2748 // their ordering. 2749 DenseMap<const TreeEntry *, OrdersType> GathersToOrders; 2750 // Find all reorderable nodes with the given VF. 2751 // Currently the are vectorized loads,extracts + some gathering of extracts. 2752 for_each(VectorizableTree, [this, &VFToOrderedEntries, &GathersToOrders]( 2753 const std::unique_ptr<TreeEntry> &TE) { 2754 // No need to reorder if need to shuffle reuses, still need to shuffle the 2755 // node. 2756 if (!TE->ReuseShuffleIndices.empty()) 2757 return; 2758 if (TE->State == TreeEntry::Vectorize && 2759 isa<LoadInst, ExtractElementInst, ExtractValueInst, StoreInst, 2760 InsertElementInst>(TE->getMainOp()) && 2761 !TE->isAltShuffle()) { 2762 VFToOrderedEntries[TE->Scalars.size()].insert(TE.get()); 2763 return; 2764 } 2765 if (TE->State == TreeEntry::NeedToGather) { 2766 if (TE->getOpcode() == Instruction::ExtractElement && 2767 !TE->isAltShuffle() && 2768 isa<FixedVectorType>(cast<ExtractElementInst>(TE->getMainOp()) 2769 ->getVectorOperandType()) && 2770 allSameType(TE->Scalars) && allSameBlock(TE->Scalars)) { 2771 // Check that gather of extractelements can be represented as 2772 // just a shuffle of a single vector. 2773 OrdersType CurrentOrder; 2774 bool Reuse = 2775 canReuseExtract(TE->Scalars, TE->getMainOp(), CurrentOrder); 2776 if (Reuse || !CurrentOrder.empty()) { 2777 VFToOrderedEntries[TE->Scalars.size()].insert(TE.get()); 2778 GathersToOrders.try_emplace(TE.get(), CurrentOrder); 2779 return; 2780 } 2781 } 2782 if (Optional<OrdersType> CurrentOrder = 2783 findReusedOrderedScalars(*TE.get())) { 2784 VFToOrderedEntries[TE->Scalars.size()].insert(TE.get()); 2785 GathersToOrders.try_emplace(TE.get(), *CurrentOrder); 2786 } 2787 } 2788 }); 2789 2790 // Reorder the graph nodes according to their vectorization factor. 2791 for (unsigned VF = VectorizableTree.front()->Scalars.size(); VF > 1; 2792 VF /= 2) { 2793 auto It = VFToOrderedEntries.find(VF); 2794 if (It == VFToOrderedEntries.end()) 2795 continue; 2796 // Try to find the most profitable order. We just are looking for the most 2797 // used order and reorder scalar elements in the nodes according to this 2798 // mostly used order. 2799 const SmallPtrSetImpl<TreeEntry *> &OrderedEntries = It->getSecond(); 2800 // All operands are reordered and used only in this node - propagate the 2801 // most used order to the user node. 2802 MapVector<OrdersType, unsigned, 2803 DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo>> 2804 OrdersUses; 2805 SmallPtrSet<const TreeEntry *, 4> VisitedOps; 2806 for (const TreeEntry *OpTE : OrderedEntries) { 2807 // No need to reorder this nodes, still need to extend and to use shuffle, 2808 // just need to merge reordering shuffle and the reuse shuffle. 2809 if (!OpTE->ReuseShuffleIndices.empty()) 2810 continue; 2811 // Count number of orders uses. 2812 const auto &Order = [OpTE, &GathersToOrders]() -> const OrdersType & { 2813 if (OpTE->State == TreeEntry::NeedToGather) 2814 return GathersToOrders.find(OpTE)->second; 2815 return OpTE->ReorderIndices; 2816 }(); 2817 // Stores actually store the mask, not the order, need to invert. 2818 if (OpTE->State == TreeEntry::Vectorize && !OpTE->isAltShuffle() && 2819 OpTE->getOpcode() == Instruction::Store && !Order.empty()) { 2820 SmallVector<int> Mask; 2821 inversePermutation(Order, Mask); 2822 unsigned E = Order.size(); 2823 OrdersType CurrentOrder(E, E); 2824 transform(Mask, CurrentOrder.begin(), [E](int Idx) { 2825 return Idx == UndefMaskElem ? E : static_cast<unsigned>(Idx); 2826 }); 2827 fixupOrderingIndices(CurrentOrder); 2828 ++OrdersUses.insert(std::make_pair(CurrentOrder, 0)).first->second; 2829 } else { 2830 ++OrdersUses.insert(std::make_pair(Order, 0)).first->second; 2831 } 2832 } 2833 // Set order of the user node. 2834 if (OrdersUses.empty()) 2835 continue; 2836 // Choose the most used order. 2837 ArrayRef<unsigned> BestOrder = OrdersUses.front().first; 2838 unsigned Cnt = OrdersUses.front().second; 2839 for (const auto &Pair : drop_begin(OrdersUses)) { 2840 if (Cnt < Pair.second || (Cnt == Pair.second && Pair.first.empty())) { 2841 BestOrder = Pair.first; 2842 Cnt = Pair.second; 2843 } 2844 } 2845 // Set order of the user node. 2846 if (BestOrder.empty()) 2847 continue; 2848 SmallVector<int> Mask; 2849 inversePermutation(BestOrder, Mask); 2850 SmallVector<int> MaskOrder(BestOrder.size(), UndefMaskElem); 2851 unsigned E = BestOrder.size(); 2852 transform(BestOrder, MaskOrder.begin(), [E](unsigned I) { 2853 return I < E ? static_cast<int>(I) : UndefMaskElem; 2854 }); 2855 // Do an actual reordering, if profitable. 2856 for (std::unique_ptr<TreeEntry> &TE : VectorizableTree) { 2857 // Just do the reordering for the nodes with the given VF. 2858 if (TE->Scalars.size() != VF) { 2859 if (TE->ReuseShuffleIndices.size() == VF) { 2860 // Need to reorder the reuses masks of the operands with smaller VF to 2861 // be able to find the match between the graph nodes and scalar 2862 // operands of the given node during vectorization/cost estimation. 2863 assert(all_of(TE->UserTreeIndices, 2864 [VF, &TE](const EdgeInfo &EI) { 2865 return EI.UserTE->Scalars.size() == VF || 2866 EI.UserTE->Scalars.size() == 2867 TE->Scalars.size(); 2868 }) && 2869 "All users must be of VF size."); 2870 // Update ordering of the operands with the smaller VF than the given 2871 // one. 2872 reorderReuses(TE->ReuseShuffleIndices, Mask); 2873 } 2874 continue; 2875 } 2876 if (TE->State == TreeEntry::Vectorize && 2877 isa<ExtractElementInst, ExtractValueInst, LoadInst, StoreInst, 2878 InsertElementInst>(TE->getMainOp()) && 2879 !TE->isAltShuffle()) { 2880 // Build correct orders for extract{element,value}, loads and 2881 // stores. 2882 reorderOrder(TE->ReorderIndices, Mask); 2883 if (isa<InsertElementInst, StoreInst>(TE->getMainOp())) 2884 TE->reorderOperands(Mask); 2885 } else { 2886 // Reorder the node and its operands. 2887 TE->reorderOperands(Mask); 2888 assert(TE->ReorderIndices.empty() && 2889 "Expected empty reorder sequence."); 2890 reorderScalars(TE->Scalars, Mask); 2891 } 2892 if (!TE->ReuseShuffleIndices.empty()) { 2893 // Apply reversed order to keep the original ordering of the reused 2894 // elements to avoid extra reorder indices shuffling. 2895 OrdersType CurrentOrder; 2896 reorderOrder(CurrentOrder, MaskOrder); 2897 SmallVector<int> NewReuses; 2898 inversePermutation(CurrentOrder, NewReuses); 2899 addMask(NewReuses, TE->ReuseShuffleIndices); 2900 TE->ReuseShuffleIndices.swap(NewReuses); 2901 } 2902 } 2903 } 2904 } 2905 2906 void BoUpSLP::reorderBottomToTop(bool IgnoreReorder) { 2907 SetVector<TreeEntry *> OrderedEntries; 2908 DenseMap<const TreeEntry *, OrdersType> GathersToOrders; 2909 // Find all reorderable leaf nodes with the given VF. 2910 // Currently the are vectorized loads,extracts without alternate operands + 2911 // some gathering of extracts. 2912 SmallVector<TreeEntry *> NonVectorized; 2913 for_each(VectorizableTree, [this, &OrderedEntries, &GathersToOrders, 2914 &NonVectorized]( 2915 const std::unique_ptr<TreeEntry> &TE) { 2916 if (TE->State != TreeEntry::Vectorize) 2917 NonVectorized.push_back(TE.get()); 2918 // No need to reorder if need to shuffle reuses, still need to shuffle the 2919 // node. 2920 if (!TE->ReuseShuffleIndices.empty()) 2921 return; 2922 if (TE->State == TreeEntry::Vectorize && 2923 isa<LoadInst, ExtractElementInst, ExtractValueInst>(TE->getMainOp()) && 2924 !TE->isAltShuffle()) { 2925 OrderedEntries.insert(TE.get()); 2926 return; 2927 } 2928 if (TE->State == TreeEntry::NeedToGather) { 2929 if (TE->getOpcode() == Instruction::ExtractElement && 2930 !TE->isAltShuffle() && 2931 isa<FixedVectorType>(cast<ExtractElementInst>(TE->getMainOp()) 2932 ->getVectorOperandType()) && 2933 allSameType(TE->Scalars) && allSameBlock(TE->Scalars)) { 2934 // Check that gather of extractelements can be represented as 2935 // just a shuffle of a single vector with a single user only. 2936 OrdersType CurrentOrder; 2937 bool Reuse = 2938 canReuseExtract(TE->Scalars, TE->getMainOp(), CurrentOrder); 2939 if ((Reuse || !CurrentOrder.empty()) && 2940 !any_of(VectorizableTree, 2941 [&TE](const std::unique_ptr<TreeEntry> &Entry) { 2942 return Entry->State == TreeEntry::NeedToGather && 2943 Entry.get() != TE.get() && 2944 Entry->isSame(TE->Scalars); 2945 })) { 2946 OrderedEntries.insert(TE.get()); 2947 GathersToOrders.try_emplace(TE.get(), CurrentOrder); 2948 return; 2949 } 2950 } 2951 if (Optional<OrdersType> CurrentOrder = 2952 findReusedOrderedScalars(*TE.get())) { 2953 OrderedEntries.insert(TE.get()); 2954 GathersToOrders.try_emplace(TE.get(), *CurrentOrder); 2955 } 2956 } 2957 }); 2958 2959 // Checks if the operands of the users are reordarable and have only single 2960 // use. 2961 auto &&CheckOperands = 2962 [this, &NonVectorized](const auto &Data, 2963 SmallVectorImpl<TreeEntry *> &GatherOps) { 2964 for (unsigned I = 0, E = Data.first->getNumOperands(); I < E; ++I) { 2965 if (any_of(Data.second, 2966 [I](const std::pair<unsigned, TreeEntry *> &OpData) { 2967 return OpData.first == I && 2968 OpData.second->State == TreeEntry::Vectorize; 2969 })) 2970 continue; 2971 ArrayRef<Value *> VL = Data.first->getOperand(I); 2972 const TreeEntry *TE = nullptr; 2973 const auto *It = find_if(VL, [this, &TE](Value *V) { 2974 TE = getTreeEntry(V); 2975 return TE; 2976 }); 2977 if (It != VL.end() && TE->isSame(VL)) 2978 return false; 2979 TreeEntry *Gather = nullptr; 2980 if (count_if(NonVectorized, [VL, &Gather](TreeEntry *TE) { 2981 assert(TE->State != TreeEntry::Vectorize && 2982 "Only non-vectorized nodes are expected."); 2983 if (TE->isSame(VL)) { 2984 Gather = TE; 2985 return true; 2986 } 2987 return false; 2988 }) > 1) 2989 return false; 2990 if (Gather) 2991 GatherOps.push_back(Gather); 2992 } 2993 return true; 2994 }; 2995 // 1. Propagate order to the graph nodes, which use only reordered nodes. 2996 // I.e., if the node has operands, that are reordered, try to make at least 2997 // one operand order in the natural order and reorder others + reorder the 2998 // user node itself. 2999 SmallPtrSet<const TreeEntry *, 4> Visited; 3000 while (!OrderedEntries.empty()) { 3001 // 1. Filter out only reordered nodes. 3002 // 2. If the entry has multiple uses - skip it and jump to the next node. 3003 MapVector<TreeEntry *, SmallVector<std::pair<unsigned, TreeEntry *>>> Users; 3004 SmallVector<TreeEntry *> Filtered; 3005 for (TreeEntry *TE : OrderedEntries) { 3006 if (!(TE->State == TreeEntry::Vectorize || 3007 (TE->State == TreeEntry::NeedToGather && 3008 GathersToOrders.count(TE))) || 3009 TE->UserTreeIndices.empty() || !TE->ReuseShuffleIndices.empty() || 3010 !all_of(drop_begin(TE->UserTreeIndices), 3011 [TE](const EdgeInfo &EI) { 3012 return EI.UserTE == TE->UserTreeIndices.front().UserTE; 3013 }) || 3014 !Visited.insert(TE).second) { 3015 Filtered.push_back(TE); 3016 continue; 3017 } 3018 // Build a map between user nodes and their operands order to speedup 3019 // search. The graph currently does not provide this dependency directly. 3020 for (EdgeInfo &EI : TE->UserTreeIndices) { 3021 TreeEntry *UserTE = EI.UserTE; 3022 auto It = Users.find(UserTE); 3023 if (It == Users.end()) 3024 It = Users.insert({UserTE, {}}).first; 3025 It->second.emplace_back(EI.EdgeIdx, TE); 3026 } 3027 } 3028 // Erase filtered entries. 3029 for_each(Filtered, 3030 [&OrderedEntries](TreeEntry *TE) { OrderedEntries.remove(TE); }); 3031 for (const auto &Data : Users) { 3032 // Check that operands are used only in the User node. 3033 SmallVector<TreeEntry *> GatherOps; 3034 if (!CheckOperands(Data, GatherOps)) { 3035 for_each(Data.second, 3036 [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) { 3037 OrderedEntries.remove(Op.second); 3038 }); 3039 continue; 3040 } 3041 // All operands are reordered and used only in this node - propagate the 3042 // most used order to the user node. 3043 MapVector<OrdersType, unsigned, 3044 DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo>> 3045 OrdersUses; 3046 SmallPtrSet<const TreeEntry *, 4> VisitedOps; 3047 for (const auto &Op : Data.second) { 3048 TreeEntry *OpTE = Op.second; 3049 if (!OpTE->ReuseShuffleIndices.empty() || 3050 (IgnoreReorder && OpTE == VectorizableTree.front().get())) 3051 continue; 3052 const auto &Order = [OpTE, &GathersToOrders]() -> const OrdersType & { 3053 if (OpTE->State == TreeEntry::NeedToGather) 3054 return GathersToOrders.find(OpTE)->second; 3055 return OpTE->ReorderIndices; 3056 }(); 3057 // Stores actually store the mask, not the order, need to invert. 3058 if (OpTE->State == TreeEntry::Vectorize && !OpTE->isAltShuffle() && 3059 OpTE->getOpcode() == Instruction::Store && !Order.empty()) { 3060 SmallVector<int> Mask; 3061 inversePermutation(Order, Mask); 3062 unsigned E = Order.size(); 3063 OrdersType CurrentOrder(E, E); 3064 transform(Mask, CurrentOrder.begin(), [E](int Idx) { 3065 return Idx == UndefMaskElem ? E : static_cast<unsigned>(Idx); 3066 }); 3067 fixupOrderingIndices(CurrentOrder); 3068 ++OrdersUses.insert(std::make_pair(CurrentOrder, 0)).first->second; 3069 } else { 3070 ++OrdersUses.insert(std::make_pair(Order, 0)).first->second; 3071 } 3072 if (VisitedOps.insert(OpTE).second) 3073 OrdersUses.insert(std::make_pair(OrdersType(), 0)).first->second += 3074 OpTE->UserTreeIndices.size(); 3075 assert(OrdersUses[{}] > 0 && "Counter cannot be less than 0."); 3076 --OrdersUses[{}]; 3077 } 3078 // If no orders - skip current nodes and jump to the next one, if any. 3079 if (OrdersUses.empty()) { 3080 for_each(Data.second, 3081 [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) { 3082 OrderedEntries.remove(Op.second); 3083 }); 3084 continue; 3085 } 3086 // Choose the best order. 3087 ArrayRef<unsigned> BestOrder = OrdersUses.front().first; 3088 unsigned Cnt = OrdersUses.front().second; 3089 for (const auto &Pair : drop_begin(OrdersUses)) { 3090 if (Cnt < Pair.second || (Cnt == Pair.second && Pair.first.empty())) { 3091 BestOrder = Pair.first; 3092 Cnt = Pair.second; 3093 } 3094 } 3095 // Set order of the user node (reordering of operands and user nodes). 3096 if (BestOrder.empty()) { 3097 for_each(Data.second, 3098 [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) { 3099 OrderedEntries.remove(Op.second); 3100 }); 3101 continue; 3102 } 3103 // Erase operands from OrderedEntries list and adjust their orders. 3104 VisitedOps.clear(); 3105 SmallVector<int> Mask; 3106 inversePermutation(BestOrder, Mask); 3107 SmallVector<int> MaskOrder(BestOrder.size(), UndefMaskElem); 3108 unsigned E = BestOrder.size(); 3109 transform(BestOrder, MaskOrder.begin(), [E](unsigned I) { 3110 return I < E ? static_cast<int>(I) : UndefMaskElem; 3111 }); 3112 for (const std::pair<unsigned, TreeEntry *> &Op : Data.second) { 3113 TreeEntry *TE = Op.second; 3114 OrderedEntries.remove(TE); 3115 if (!VisitedOps.insert(TE).second) 3116 continue; 3117 if (!TE->ReuseShuffleIndices.empty() && TE->ReorderIndices.empty()) { 3118 // Just reorder reuses indices. 3119 reorderReuses(TE->ReuseShuffleIndices, Mask); 3120 continue; 3121 } 3122 // Gathers are processed separately. 3123 if (TE->State != TreeEntry::Vectorize) 3124 continue; 3125 assert((BestOrder.size() == TE->ReorderIndices.size() || 3126 TE->ReorderIndices.empty()) && 3127 "Non-matching sizes of user/operand entries."); 3128 reorderOrder(TE->ReorderIndices, Mask); 3129 } 3130 // For gathers just need to reorder its scalars. 3131 for (TreeEntry *Gather : GatherOps) { 3132 assert(Gather->ReorderIndices.empty() && 3133 "Unexpected reordering of gathers."); 3134 if (!Gather->ReuseShuffleIndices.empty()) { 3135 // Just reorder reuses indices. 3136 reorderReuses(Gather->ReuseShuffleIndices, Mask); 3137 continue; 3138 } 3139 reorderScalars(Gather->Scalars, Mask); 3140 OrderedEntries.remove(Gather); 3141 } 3142 // Reorder operands of the user node and set the ordering for the user 3143 // node itself. 3144 if (Data.first->State != TreeEntry::Vectorize || 3145 !isa<ExtractElementInst, ExtractValueInst, LoadInst>( 3146 Data.first->getMainOp()) || 3147 Data.first->isAltShuffle()) 3148 Data.first->reorderOperands(Mask); 3149 if (!isa<InsertElementInst, StoreInst>(Data.first->getMainOp()) || 3150 Data.first->isAltShuffle()) { 3151 reorderScalars(Data.first->Scalars, Mask); 3152 reorderOrder(Data.first->ReorderIndices, MaskOrder); 3153 if (Data.first->ReuseShuffleIndices.empty() && 3154 !Data.first->ReorderIndices.empty() && 3155 !Data.first->isAltShuffle()) { 3156 // Insert user node to the list to try to sink reordering deeper in 3157 // the graph. 3158 OrderedEntries.insert(Data.first); 3159 } 3160 } else { 3161 reorderOrder(Data.first->ReorderIndices, Mask); 3162 } 3163 } 3164 } 3165 // If the reordering is unnecessary, just remove the reorder. 3166 if (IgnoreReorder && !VectorizableTree.front()->ReorderIndices.empty() && 3167 VectorizableTree.front()->ReuseShuffleIndices.empty()) 3168 VectorizableTree.front()->ReorderIndices.clear(); 3169 } 3170 3171 void BoUpSLP::buildExternalUses( 3172 const ExtraValueToDebugLocsMap &ExternallyUsedValues) { 3173 // Collect the values that we need to extract from the tree. 3174 for (auto &TEPtr : VectorizableTree) { 3175 TreeEntry *Entry = TEPtr.get(); 3176 3177 // No need to handle users of gathered values. 3178 if (Entry->State == TreeEntry::NeedToGather) 3179 continue; 3180 3181 // For each lane: 3182 for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) { 3183 Value *Scalar = Entry->Scalars[Lane]; 3184 int FoundLane = Entry->findLaneForValue(Scalar); 3185 3186 // Check if the scalar is externally used as an extra arg. 3187 auto ExtI = ExternallyUsedValues.find(Scalar); 3188 if (ExtI != ExternallyUsedValues.end()) { 3189 LLVM_DEBUG(dbgs() << "SLP: Need to extract: Extra arg from lane " 3190 << Lane << " from " << *Scalar << ".\n"); 3191 ExternalUses.emplace_back(Scalar, nullptr, FoundLane); 3192 } 3193 for (User *U : Scalar->users()) { 3194 LLVM_DEBUG(dbgs() << "SLP: Checking user:" << *U << ".\n"); 3195 3196 Instruction *UserInst = dyn_cast<Instruction>(U); 3197 if (!UserInst) 3198 continue; 3199 3200 if (isDeleted(UserInst)) 3201 continue; 3202 3203 // Skip in-tree scalars that become vectors 3204 if (TreeEntry *UseEntry = getTreeEntry(U)) { 3205 Value *UseScalar = UseEntry->Scalars[0]; 3206 // Some in-tree scalars will remain as scalar in vectorized 3207 // instructions. If that is the case, the one in Lane 0 will 3208 // be used. 3209 if (UseScalar != U || 3210 UseEntry->State == TreeEntry::ScatterVectorize || 3211 !InTreeUserNeedToExtract(Scalar, UserInst, TLI)) { 3212 LLVM_DEBUG(dbgs() << "SLP: \tInternal user will be removed:" << *U 3213 << ".\n"); 3214 assert(UseEntry->State != TreeEntry::NeedToGather && "Bad state"); 3215 continue; 3216 } 3217 } 3218 3219 // Ignore users in the user ignore list. 3220 if (is_contained(UserIgnoreList, UserInst)) 3221 continue; 3222 3223 LLVM_DEBUG(dbgs() << "SLP: Need to extract:" << *U << " from lane " 3224 << Lane << " from " << *Scalar << ".\n"); 3225 ExternalUses.push_back(ExternalUser(Scalar, U, FoundLane)); 3226 } 3227 } 3228 } 3229 } 3230 3231 void BoUpSLP::buildTree(ArrayRef<Value *> Roots, 3232 ArrayRef<Value *> UserIgnoreLst) { 3233 deleteTree(); 3234 UserIgnoreList = UserIgnoreLst; 3235 if (!allSameType(Roots)) 3236 return; 3237 buildTree_rec(Roots, 0, EdgeInfo()); 3238 } 3239 3240 namespace { 3241 /// Tracks the state we can represent the loads in the given sequence. 3242 enum class LoadsState { Gather, Vectorize, ScatterVectorize }; 3243 } // anonymous namespace 3244 3245 /// Checks if the given array of loads can be represented as a vectorized, 3246 /// scatter or just simple gather. 3247 static LoadsState canVectorizeLoads(ArrayRef<Value *> VL, const Value *VL0, 3248 const TargetTransformInfo &TTI, 3249 const DataLayout &DL, ScalarEvolution &SE, 3250 SmallVectorImpl<unsigned> &Order, 3251 SmallVectorImpl<Value *> &PointerOps) { 3252 // Check that a vectorized load would load the same memory as a scalar 3253 // load. For example, we don't want to vectorize loads that are smaller 3254 // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM 3255 // treats loading/storing it as an i8 struct. If we vectorize loads/stores 3256 // from such a struct, we read/write packed bits disagreeing with the 3257 // unvectorized version. 3258 Type *ScalarTy = VL0->getType(); 3259 3260 if (DL.getTypeSizeInBits(ScalarTy) != DL.getTypeAllocSizeInBits(ScalarTy)) 3261 return LoadsState::Gather; 3262 3263 // Make sure all loads in the bundle are simple - we can't vectorize 3264 // atomic or volatile loads. 3265 PointerOps.clear(); 3266 PointerOps.resize(VL.size()); 3267 auto *POIter = PointerOps.begin(); 3268 for (Value *V : VL) { 3269 auto *L = cast<LoadInst>(V); 3270 if (!L->isSimple()) 3271 return LoadsState::Gather; 3272 *POIter = L->getPointerOperand(); 3273 ++POIter; 3274 } 3275 3276 Order.clear(); 3277 // Check the order of pointer operands. 3278 if (llvm::sortPtrAccesses(PointerOps, ScalarTy, DL, SE, Order)) { 3279 Value *Ptr0; 3280 Value *PtrN; 3281 if (Order.empty()) { 3282 Ptr0 = PointerOps.front(); 3283 PtrN = PointerOps.back(); 3284 } else { 3285 Ptr0 = PointerOps[Order.front()]; 3286 PtrN = PointerOps[Order.back()]; 3287 } 3288 Optional<int> Diff = 3289 getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, DL, SE); 3290 // Check that the sorted loads are consecutive. 3291 if (static_cast<unsigned>(*Diff) == VL.size() - 1) 3292 return LoadsState::Vectorize; 3293 Align CommonAlignment = cast<LoadInst>(VL0)->getAlign(); 3294 for (Value *V : VL) 3295 CommonAlignment = 3296 commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign()); 3297 if (TTI.isLegalMaskedGather(FixedVectorType::get(ScalarTy, VL.size()), 3298 CommonAlignment)) 3299 return LoadsState::ScatterVectorize; 3300 } 3301 3302 return LoadsState::Gather; 3303 } 3304 3305 void BoUpSLP::buildTree_rec(ArrayRef<Value *> VL, unsigned Depth, 3306 const EdgeInfo &UserTreeIdx) { 3307 assert((allConstant(VL) || allSameType(VL)) && "Invalid types!"); 3308 3309 SmallVector<int> ReuseShuffleIndicies; 3310 SmallVector<Value *> UniqueValues; 3311 auto &&TryToFindDuplicates = [&VL, &ReuseShuffleIndicies, &UniqueValues, 3312 &UserTreeIdx, 3313 this](const InstructionsState &S) { 3314 // Check that every instruction appears once in this bundle. 3315 DenseMap<Value *, unsigned> UniquePositions; 3316 for (Value *V : VL) { 3317 auto Res = UniquePositions.try_emplace(V, UniqueValues.size()); 3318 ReuseShuffleIndicies.emplace_back(isa<UndefValue>(V) ? -1 3319 : Res.first->second); 3320 if (Res.second) 3321 UniqueValues.emplace_back(V); 3322 } 3323 size_t NumUniqueScalarValues = UniqueValues.size(); 3324 if (NumUniqueScalarValues == VL.size()) { 3325 ReuseShuffleIndicies.clear(); 3326 } else { 3327 LLVM_DEBUG(dbgs() << "SLP: Shuffle for reused scalars.\n"); 3328 if (NumUniqueScalarValues <= 1 || 3329 !llvm::isPowerOf2_32(NumUniqueScalarValues)) { 3330 LLVM_DEBUG(dbgs() << "SLP: Scalar used twice in bundle.\n"); 3331 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx); 3332 return false; 3333 } 3334 VL = UniqueValues; 3335 } 3336 return true; 3337 }; 3338 3339 InstructionsState S = getSameOpcode(VL); 3340 if (Depth == RecursionMaxDepth) { 3341 LLVM_DEBUG(dbgs() << "SLP: Gathering due to max recursion depth.\n"); 3342 if (TryToFindDuplicates(S)) 3343 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 3344 ReuseShuffleIndicies); 3345 return; 3346 } 3347 3348 // Don't handle scalable vectors 3349 if (S.getOpcode() == Instruction::ExtractElement && 3350 isa<ScalableVectorType>( 3351 cast<ExtractElementInst>(S.OpValue)->getVectorOperandType())) { 3352 LLVM_DEBUG(dbgs() << "SLP: Gathering due to scalable vector type.\n"); 3353 if (TryToFindDuplicates(S)) 3354 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 3355 ReuseShuffleIndicies); 3356 return; 3357 } 3358 3359 // Don't handle vectors. 3360 if (S.OpValue->getType()->isVectorTy() && 3361 !isa<InsertElementInst>(S.OpValue)) { 3362 LLVM_DEBUG(dbgs() << "SLP: Gathering due to vector type.\n"); 3363 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx); 3364 return; 3365 } 3366 3367 if (StoreInst *SI = dyn_cast<StoreInst>(S.OpValue)) 3368 if (SI->getValueOperand()->getType()->isVectorTy()) { 3369 LLVM_DEBUG(dbgs() << "SLP: Gathering due to store vector type.\n"); 3370 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx); 3371 return; 3372 } 3373 3374 // If all of the operands are identical or constant we have a simple solution. 3375 // If we deal with insert/extract instructions, they all must have constant 3376 // indices, otherwise we should gather them, not try to vectorize. 3377 if (allConstant(VL) || isSplat(VL) || !allSameBlock(VL) || !S.getOpcode() || 3378 (isa<InsertElementInst, ExtractValueInst, ExtractElementInst>(S.MainOp) && 3379 !all_of(VL, isVectorLikeInstWithConstOps))) { 3380 LLVM_DEBUG(dbgs() << "SLP: Gathering due to C,S,B,O. \n"); 3381 if (TryToFindDuplicates(S)) 3382 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 3383 ReuseShuffleIndicies); 3384 return; 3385 } 3386 3387 // We now know that this is a vector of instructions of the same type from 3388 // the same block. 3389 3390 // Don't vectorize ephemeral values. 3391 for (Value *V : VL) { 3392 if (EphValues.count(V)) { 3393 LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V 3394 << ") is ephemeral.\n"); 3395 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx); 3396 return; 3397 } 3398 } 3399 3400 // Check if this is a duplicate of another entry. 3401 if (TreeEntry *E = getTreeEntry(S.OpValue)) { 3402 LLVM_DEBUG(dbgs() << "SLP: \tChecking bundle: " << *S.OpValue << ".\n"); 3403 if (!E->isSame(VL)) { 3404 LLVM_DEBUG(dbgs() << "SLP: Gathering due to partial overlap.\n"); 3405 if (TryToFindDuplicates(S)) 3406 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 3407 ReuseShuffleIndicies); 3408 return; 3409 } 3410 // Record the reuse of the tree node. FIXME, currently this is only used to 3411 // properly draw the graph rather than for the actual vectorization. 3412 E->UserTreeIndices.push_back(UserTreeIdx); 3413 LLVM_DEBUG(dbgs() << "SLP: Perfect diamond merge at " << *S.OpValue 3414 << ".\n"); 3415 return; 3416 } 3417 3418 // Check that none of the instructions in the bundle are already in the tree. 3419 for (Value *V : VL) { 3420 auto *I = dyn_cast<Instruction>(V); 3421 if (!I) 3422 continue; 3423 if (getTreeEntry(I)) { 3424 LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V 3425 << ") is already in tree.\n"); 3426 if (TryToFindDuplicates(S)) 3427 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 3428 ReuseShuffleIndicies); 3429 return; 3430 } 3431 } 3432 3433 // If any of the scalars is marked as a value that needs to stay scalar, then 3434 // we need to gather the scalars. 3435 // The reduction nodes (stored in UserIgnoreList) also should stay scalar. 3436 for (Value *V : VL) { 3437 if (MustGather.count(V) || is_contained(UserIgnoreList, V)) { 3438 LLVM_DEBUG(dbgs() << "SLP: Gathering due to gathered scalar.\n"); 3439 if (TryToFindDuplicates(S)) 3440 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 3441 ReuseShuffleIndicies); 3442 return; 3443 } 3444 } 3445 3446 // Check that all of the users of the scalars that we want to vectorize are 3447 // schedulable. 3448 auto *VL0 = cast<Instruction>(S.OpValue); 3449 BasicBlock *BB = VL0->getParent(); 3450 3451 if (!DT->isReachableFromEntry(BB)) { 3452 // Don't go into unreachable blocks. They may contain instructions with 3453 // dependency cycles which confuse the final scheduling. 3454 LLVM_DEBUG(dbgs() << "SLP: bundle in unreachable block.\n"); 3455 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx); 3456 return; 3457 } 3458 3459 // Check that every instruction appears once in this bundle. 3460 if (!TryToFindDuplicates(S)) 3461 return; 3462 3463 auto &BSRef = BlocksSchedules[BB]; 3464 if (!BSRef) 3465 BSRef = std::make_unique<BlockScheduling>(BB); 3466 3467 BlockScheduling &BS = *BSRef.get(); 3468 3469 Optional<ScheduleData *> Bundle = BS.tryScheduleBundle(VL, this, S); 3470 if (!Bundle) { 3471 LLVM_DEBUG(dbgs() << "SLP: We are not able to schedule this bundle!\n"); 3472 assert((!BS.getScheduleData(VL0) || 3473 !BS.getScheduleData(VL0)->isPartOfBundle()) && 3474 "tryScheduleBundle should cancelScheduling on failure"); 3475 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 3476 ReuseShuffleIndicies); 3477 return; 3478 } 3479 LLVM_DEBUG(dbgs() << "SLP: We are able to schedule this bundle.\n"); 3480 3481 unsigned ShuffleOrOp = S.isAltShuffle() ? 3482 (unsigned) Instruction::ShuffleVector : S.getOpcode(); 3483 switch (ShuffleOrOp) { 3484 case Instruction::PHI: { 3485 auto *PH = cast<PHINode>(VL0); 3486 3487 // Check for terminator values (e.g. invoke). 3488 for (Value *V : VL) 3489 for (unsigned I = 0, E = PH->getNumIncomingValues(); I < E; ++I) { 3490 Instruction *Term = dyn_cast<Instruction>( 3491 cast<PHINode>(V)->getIncomingValueForBlock( 3492 PH->getIncomingBlock(I))); 3493 if (Term && Term->isTerminator()) { 3494 LLVM_DEBUG(dbgs() 3495 << "SLP: Need to swizzle PHINodes (terminator use).\n"); 3496 BS.cancelScheduling(VL, VL0); 3497 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 3498 ReuseShuffleIndicies); 3499 return; 3500 } 3501 } 3502 3503 TreeEntry *TE = 3504 newTreeEntry(VL, Bundle, S, UserTreeIdx, ReuseShuffleIndicies); 3505 LLVM_DEBUG(dbgs() << "SLP: added a vector of PHINodes.\n"); 3506 3507 // Keeps the reordered operands to avoid code duplication. 3508 SmallVector<ValueList, 2> OperandsVec; 3509 for (unsigned I = 0, E = PH->getNumIncomingValues(); I < E; ++I) { 3510 if (!DT->isReachableFromEntry(PH->getIncomingBlock(I))) { 3511 ValueList Operands(VL.size(), PoisonValue::get(PH->getType())); 3512 TE->setOperand(I, Operands); 3513 OperandsVec.push_back(Operands); 3514 continue; 3515 } 3516 ValueList Operands; 3517 // Prepare the operand vector. 3518 for (Value *V : VL) 3519 Operands.push_back(cast<PHINode>(V)->getIncomingValueForBlock( 3520 PH->getIncomingBlock(I))); 3521 TE->setOperand(I, Operands); 3522 OperandsVec.push_back(Operands); 3523 } 3524 for (unsigned OpIdx = 0, OpE = OperandsVec.size(); OpIdx != OpE; ++OpIdx) 3525 buildTree_rec(OperandsVec[OpIdx], Depth + 1, {TE, OpIdx}); 3526 return; 3527 } 3528 case Instruction::ExtractValue: 3529 case Instruction::ExtractElement: { 3530 OrdersType CurrentOrder; 3531 bool Reuse = canReuseExtract(VL, VL0, CurrentOrder); 3532 if (Reuse) { 3533 LLVM_DEBUG(dbgs() << "SLP: Reusing or shuffling extract sequence.\n"); 3534 newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, 3535 ReuseShuffleIndicies); 3536 // This is a special case, as it does not gather, but at the same time 3537 // we are not extending buildTree_rec() towards the operands. 3538 ValueList Op0; 3539 Op0.assign(VL.size(), VL0->getOperand(0)); 3540 VectorizableTree.back()->setOperand(0, Op0); 3541 return; 3542 } 3543 if (!CurrentOrder.empty()) { 3544 LLVM_DEBUG({ 3545 dbgs() << "SLP: Reusing or shuffling of reordered extract sequence " 3546 "with order"; 3547 for (unsigned Idx : CurrentOrder) 3548 dbgs() << " " << Idx; 3549 dbgs() << "\n"; 3550 }); 3551 fixupOrderingIndices(CurrentOrder); 3552 // Insert new order with initial value 0, if it does not exist, 3553 // otherwise return the iterator to the existing one. 3554 newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, 3555 ReuseShuffleIndicies, CurrentOrder); 3556 // This is a special case, as it does not gather, but at the same time 3557 // we are not extending buildTree_rec() towards the operands. 3558 ValueList Op0; 3559 Op0.assign(VL.size(), VL0->getOperand(0)); 3560 VectorizableTree.back()->setOperand(0, Op0); 3561 return; 3562 } 3563 LLVM_DEBUG(dbgs() << "SLP: Gather extract sequence.\n"); 3564 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 3565 ReuseShuffleIndicies); 3566 BS.cancelScheduling(VL, VL0); 3567 return; 3568 } 3569 case Instruction::InsertElement: { 3570 assert(ReuseShuffleIndicies.empty() && "All inserts should be unique"); 3571 3572 // Check that we have a buildvector and not a shuffle of 2 or more 3573 // different vectors. 3574 ValueSet SourceVectors; 3575 int MinIdx = std::numeric_limits<int>::max(); 3576 for (Value *V : VL) { 3577 SourceVectors.insert(cast<Instruction>(V)->getOperand(0)); 3578 Optional<int> Idx = *getInsertIndex(V, 0); 3579 if (!Idx || *Idx == UndefMaskElem) 3580 continue; 3581 MinIdx = std::min(MinIdx, *Idx); 3582 } 3583 3584 if (count_if(VL, [&SourceVectors](Value *V) { 3585 return !SourceVectors.contains(V); 3586 }) >= 2) { 3587 // Found 2nd source vector - cancel. 3588 LLVM_DEBUG(dbgs() << "SLP: Gather of insertelement vectors with " 3589 "different source vectors.\n"); 3590 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx); 3591 BS.cancelScheduling(VL, VL0); 3592 return; 3593 } 3594 3595 auto OrdCompare = [](const std::pair<int, int> &P1, 3596 const std::pair<int, int> &P2) { 3597 return P1.first > P2.first; 3598 }; 3599 PriorityQueue<std::pair<int, int>, SmallVector<std::pair<int, int>>, 3600 decltype(OrdCompare)> 3601 Indices(OrdCompare); 3602 for (int I = 0, E = VL.size(); I < E; ++I) { 3603 Optional<int> Idx = *getInsertIndex(VL[I], 0); 3604 if (!Idx || *Idx == UndefMaskElem) 3605 continue; 3606 Indices.emplace(*Idx, I); 3607 } 3608 OrdersType CurrentOrder(VL.size(), VL.size()); 3609 bool IsIdentity = true; 3610 for (int I = 0, E = VL.size(); I < E; ++I) { 3611 CurrentOrder[Indices.top().second] = I; 3612 IsIdentity &= Indices.top().second == I; 3613 Indices.pop(); 3614 } 3615 if (IsIdentity) 3616 CurrentOrder.clear(); 3617 TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, 3618 None, CurrentOrder); 3619 LLVM_DEBUG(dbgs() << "SLP: added inserts bundle.\n"); 3620 3621 constexpr int NumOps = 2; 3622 ValueList VectorOperands[NumOps]; 3623 for (int I = 0; I < NumOps; ++I) { 3624 for (Value *V : VL) 3625 VectorOperands[I].push_back(cast<Instruction>(V)->getOperand(I)); 3626 3627 TE->setOperand(I, VectorOperands[I]); 3628 } 3629 buildTree_rec(VectorOperands[NumOps - 1], Depth + 1, {TE, NumOps - 1}); 3630 return; 3631 } 3632 case Instruction::Load: { 3633 // Check that a vectorized load would load the same memory as a scalar 3634 // load. For example, we don't want to vectorize loads that are smaller 3635 // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM 3636 // treats loading/storing it as an i8 struct. If we vectorize loads/stores 3637 // from such a struct, we read/write packed bits disagreeing with the 3638 // unvectorized version. 3639 SmallVector<Value *> PointerOps; 3640 OrdersType CurrentOrder; 3641 TreeEntry *TE = nullptr; 3642 switch (canVectorizeLoads(VL, VL0, *TTI, *DL, *SE, CurrentOrder, 3643 PointerOps)) { 3644 case LoadsState::Vectorize: 3645 if (CurrentOrder.empty()) { 3646 // Original loads are consecutive and does not require reordering. 3647 TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, 3648 ReuseShuffleIndicies); 3649 LLVM_DEBUG(dbgs() << "SLP: added a vector of loads.\n"); 3650 } else { 3651 fixupOrderingIndices(CurrentOrder); 3652 // Need to reorder. 3653 TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, 3654 ReuseShuffleIndicies, CurrentOrder); 3655 LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled loads.\n"); 3656 } 3657 TE->setOperandsInOrder(); 3658 break; 3659 case LoadsState::ScatterVectorize: 3660 // Vectorizing non-consecutive loads with `llvm.masked.gather`. 3661 TE = newTreeEntry(VL, TreeEntry::ScatterVectorize, Bundle, S, 3662 UserTreeIdx, ReuseShuffleIndicies); 3663 TE->setOperandsInOrder(); 3664 buildTree_rec(PointerOps, Depth + 1, {TE, 0}); 3665 LLVM_DEBUG(dbgs() << "SLP: added a vector of non-consecutive loads.\n"); 3666 break; 3667 case LoadsState::Gather: 3668 BS.cancelScheduling(VL, VL0); 3669 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 3670 ReuseShuffleIndicies); 3671 #ifndef NDEBUG 3672 Type *ScalarTy = VL0->getType(); 3673 if (DL->getTypeSizeInBits(ScalarTy) != 3674 DL->getTypeAllocSizeInBits(ScalarTy)) 3675 LLVM_DEBUG(dbgs() << "SLP: Gathering loads of non-packed type.\n"); 3676 else if (any_of(VL, [](Value *V) { 3677 return !cast<LoadInst>(V)->isSimple(); 3678 })) 3679 LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple loads.\n"); 3680 else 3681 LLVM_DEBUG(dbgs() << "SLP: Gathering non-consecutive loads.\n"); 3682 #endif // NDEBUG 3683 break; 3684 } 3685 return; 3686 } 3687 case Instruction::ZExt: 3688 case Instruction::SExt: 3689 case Instruction::FPToUI: 3690 case Instruction::FPToSI: 3691 case Instruction::FPExt: 3692 case Instruction::PtrToInt: 3693 case Instruction::IntToPtr: 3694 case Instruction::SIToFP: 3695 case Instruction::UIToFP: 3696 case Instruction::Trunc: 3697 case Instruction::FPTrunc: 3698 case Instruction::BitCast: { 3699 Type *SrcTy = VL0->getOperand(0)->getType(); 3700 for (Value *V : VL) { 3701 Type *Ty = cast<Instruction>(V)->getOperand(0)->getType(); 3702 if (Ty != SrcTy || !isValidElementType(Ty)) { 3703 BS.cancelScheduling(VL, VL0); 3704 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 3705 ReuseShuffleIndicies); 3706 LLVM_DEBUG(dbgs() 3707 << "SLP: Gathering casts with different src types.\n"); 3708 return; 3709 } 3710 } 3711 TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, 3712 ReuseShuffleIndicies); 3713 LLVM_DEBUG(dbgs() << "SLP: added a vector of casts.\n"); 3714 3715 TE->setOperandsInOrder(); 3716 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) { 3717 ValueList Operands; 3718 // Prepare the operand vector. 3719 for (Value *V : VL) 3720 Operands.push_back(cast<Instruction>(V)->getOperand(i)); 3721 3722 buildTree_rec(Operands, Depth + 1, {TE, i}); 3723 } 3724 return; 3725 } 3726 case Instruction::ICmp: 3727 case Instruction::FCmp: { 3728 // Check that all of the compares have the same predicate. 3729 CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate(); 3730 CmpInst::Predicate SwapP0 = CmpInst::getSwappedPredicate(P0); 3731 Type *ComparedTy = VL0->getOperand(0)->getType(); 3732 for (Value *V : VL) { 3733 CmpInst *Cmp = cast<CmpInst>(V); 3734 if ((Cmp->getPredicate() != P0 && Cmp->getPredicate() != SwapP0) || 3735 Cmp->getOperand(0)->getType() != ComparedTy) { 3736 BS.cancelScheduling(VL, VL0); 3737 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 3738 ReuseShuffleIndicies); 3739 LLVM_DEBUG(dbgs() 3740 << "SLP: Gathering cmp with different predicate.\n"); 3741 return; 3742 } 3743 } 3744 3745 TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, 3746 ReuseShuffleIndicies); 3747 LLVM_DEBUG(dbgs() << "SLP: added a vector of compares.\n"); 3748 3749 ValueList Left, Right; 3750 if (cast<CmpInst>(VL0)->isCommutative()) { 3751 // Commutative predicate - collect + sort operands of the instructions 3752 // so that each side is more likely to have the same opcode. 3753 assert(P0 == SwapP0 && "Commutative Predicate mismatch"); 3754 reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this); 3755 } else { 3756 // Collect operands - commute if it uses the swapped predicate. 3757 for (Value *V : VL) { 3758 auto *Cmp = cast<CmpInst>(V); 3759 Value *LHS = Cmp->getOperand(0); 3760 Value *RHS = Cmp->getOperand(1); 3761 if (Cmp->getPredicate() != P0) 3762 std::swap(LHS, RHS); 3763 Left.push_back(LHS); 3764 Right.push_back(RHS); 3765 } 3766 } 3767 TE->setOperand(0, Left); 3768 TE->setOperand(1, Right); 3769 buildTree_rec(Left, Depth + 1, {TE, 0}); 3770 buildTree_rec(Right, Depth + 1, {TE, 1}); 3771 return; 3772 } 3773 case Instruction::Select: 3774 case Instruction::FNeg: 3775 case Instruction::Add: 3776 case Instruction::FAdd: 3777 case Instruction::Sub: 3778 case Instruction::FSub: 3779 case Instruction::Mul: 3780 case Instruction::FMul: 3781 case Instruction::UDiv: 3782 case Instruction::SDiv: 3783 case Instruction::FDiv: 3784 case Instruction::URem: 3785 case Instruction::SRem: 3786 case Instruction::FRem: 3787 case Instruction::Shl: 3788 case Instruction::LShr: 3789 case Instruction::AShr: 3790 case Instruction::And: 3791 case Instruction::Or: 3792 case Instruction::Xor: { 3793 TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, 3794 ReuseShuffleIndicies); 3795 LLVM_DEBUG(dbgs() << "SLP: added a vector of un/bin op.\n"); 3796 3797 // Sort operands of the instructions so that each side is more likely to 3798 // have the same opcode. 3799 if (isa<BinaryOperator>(VL0) && VL0->isCommutative()) { 3800 ValueList Left, Right; 3801 reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this); 3802 TE->setOperand(0, Left); 3803 TE->setOperand(1, Right); 3804 buildTree_rec(Left, Depth + 1, {TE, 0}); 3805 buildTree_rec(Right, Depth + 1, {TE, 1}); 3806 return; 3807 } 3808 3809 TE->setOperandsInOrder(); 3810 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) { 3811 ValueList Operands; 3812 // Prepare the operand vector. 3813 for (Value *V : VL) 3814 Operands.push_back(cast<Instruction>(V)->getOperand(i)); 3815 3816 buildTree_rec(Operands, Depth + 1, {TE, i}); 3817 } 3818 return; 3819 } 3820 case Instruction::GetElementPtr: { 3821 // We don't combine GEPs with complicated (nested) indexing. 3822 for (Value *V : VL) { 3823 if (cast<Instruction>(V)->getNumOperands() != 2) { 3824 LLVM_DEBUG(dbgs() << "SLP: not-vectorizable GEP (nested indexes).\n"); 3825 BS.cancelScheduling(VL, VL0); 3826 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 3827 ReuseShuffleIndicies); 3828 return; 3829 } 3830 } 3831 3832 // We can't combine several GEPs into one vector if they operate on 3833 // different types. 3834 Type *Ty0 = VL0->getOperand(0)->getType(); 3835 for (Value *V : VL) { 3836 Type *CurTy = cast<Instruction>(V)->getOperand(0)->getType(); 3837 if (Ty0 != CurTy) { 3838 LLVM_DEBUG(dbgs() 3839 << "SLP: not-vectorizable GEP (different types).\n"); 3840 BS.cancelScheduling(VL, VL0); 3841 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 3842 ReuseShuffleIndicies); 3843 return; 3844 } 3845 } 3846 3847 // We don't combine GEPs with non-constant indexes. 3848 Type *Ty1 = VL0->getOperand(1)->getType(); 3849 for (Value *V : VL) { 3850 auto Op = cast<Instruction>(V)->getOperand(1); 3851 if (!isa<ConstantInt>(Op) || 3852 (Op->getType() != Ty1 && 3853 Op->getType()->getScalarSizeInBits() > 3854 DL->getIndexSizeInBits( 3855 V->getType()->getPointerAddressSpace()))) { 3856 LLVM_DEBUG(dbgs() 3857 << "SLP: not-vectorizable GEP (non-constant indexes).\n"); 3858 BS.cancelScheduling(VL, VL0); 3859 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 3860 ReuseShuffleIndicies); 3861 return; 3862 } 3863 } 3864 3865 TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, 3866 ReuseShuffleIndicies); 3867 LLVM_DEBUG(dbgs() << "SLP: added a vector of GEPs.\n"); 3868 TE->setOperandsInOrder(); 3869 for (unsigned i = 0, e = 2; i < e; ++i) { 3870 ValueList Operands; 3871 // Prepare the operand vector. 3872 for (Value *V : VL) 3873 Operands.push_back(cast<Instruction>(V)->getOperand(i)); 3874 3875 buildTree_rec(Operands, Depth + 1, {TE, i}); 3876 } 3877 return; 3878 } 3879 case Instruction::Store: { 3880 // Check if the stores are consecutive or if we need to swizzle them. 3881 llvm::Type *ScalarTy = cast<StoreInst>(VL0)->getValueOperand()->getType(); 3882 // Avoid types that are padded when being allocated as scalars, while 3883 // being packed together in a vector (such as i1). 3884 if (DL->getTypeSizeInBits(ScalarTy) != 3885 DL->getTypeAllocSizeInBits(ScalarTy)) { 3886 BS.cancelScheduling(VL, VL0); 3887 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 3888 ReuseShuffleIndicies); 3889 LLVM_DEBUG(dbgs() << "SLP: Gathering stores of non-packed type.\n"); 3890 return; 3891 } 3892 // Make sure all stores in the bundle are simple - we can't vectorize 3893 // atomic or volatile stores. 3894 SmallVector<Value *, 4> PointerOps(VL.size()); 3895 ValueList Operands(VL.size()); 3896 auto POIter = PointerOps.begin(); 3897 auto OIter = Operands.begin(); 3898 for (Value *V : VL) { 3899 auto *SI = cast<StoreInst>(V); 3900 if (!SI->isSimple()) { 3901 BS.cancelScheduling(VL, VL0); 3902 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 3903 ReuseShuffleIndicies); 3904 LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple stores.\n"); 3905 return; 3906 } 3907 *POIter = SI->getPointerOperand(); 3908 *OIter = SI->getValueOperand(); 3909 ++POIter; 3910 ++OIter; 3911 } 3912 3913 OrdersType CurrentOrder; 3914 // Check the order of pointer operands. 3915 if (llvm::sortPtrAccesses(PointerOps, ScalarTy, *DL, *SE, CurrentOrder)) { 3916 Value *Ptr0; 3917 Value *PtrN; 3918 if (CurrentOrder.empty()) { 3919 Ptr0 = PointerOps.front(); 3920 PtrN = PointerOps.back(); 3921 } else { 3922 Ptr0 = PointerOps[CurrentOrder.front()]; 3923 PtrN = PointerOps[CurrentOrder.back()]; 3924 } 3925 Optional<int> Dist = 3926 getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, *DL, *SE); 3927 // Check that the sorted pointer operands are consecutive. 3928 if (static_cast<unsigned>(*Dist) == VL.size() - 1) { 3929 if (CurrentOrder.empty()) { 3930 // Original stores are consecutive and does not require reordering. 3931 TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, 3932 UserTreeIdx, ReuseShuffleIndicies); 3933 TE->setOperandsInOrder(); 3934 buildTree_rec(Operands, Depth + 1, {TE, 0}); 3935 LLVM_DEBUG(dbgs() << "SLP: added a vector of stores.\n"); 3936 } else { 3937 fixupOrderingIndices(CurrentOrder); 3938 TreeEntry *TE = 3939 newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, 3940 ReuseShuffleIndicies, CurrentOrder); 3941 TE->setOperandsInOrder(); 3942 buildTree_rec(Operands, Depth + 1, {TE, 0}); 3943 LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled stores.\n"); 3944 } 3945 return; 3946 } 3947 } 3948 3949 BS.cancelScheduling(VL, VL0); 3950 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 3951 ReuseShuffleIndicies); 3952 LLVM_DEBUG(dbgs() << "SLP: Non-consecutive store.\n"); 3953 return; 3954 } 3955 case Instruction::Call: { 3956 // Check if the calls are all to the same vectorizable intrinsic or 3957 // library function. 3958 CallInst *CI = cast<CallInst>(VL0); 3959 Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI); 3960 3961 VFShape Shape = VFShape::get( 3962 *CI, ElementCount::getFixed(static_cast<unsigned int>(VL.size())), 3963 false /*HasGlobalPred*/); 3964 Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape); 3965 3966 if (!VecFunc && !isTriviallyVectorizable(ID)) { 3967 BS.cancelScheduling(VL, VL0); 3968 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 3969 ReuseShuffleIndicies); 3970 LLVM_DEBUG(dbgs() << "SLP: Non-vectorizable call.\n"); 3971 return; 3972 } 3973 Function *F = CI->getCalledFunction(); 3974 unsigned NumArgs = CI->arg_size(); 3975 SmallVector<Value*, 4> ScalarArgs(NumArgs, nullptr); 3976 for (unsigned j = 0; j != NumArgs; ++j) 3977 if (hasVectorInstrinsicScalarOpd(ID, j)) 3978 ScalarArgs[j] = CI->getArgOperand(j); 3979 for (Value *V : VL) { 3980 CallInst *CI2 = dyn_cast<CallInst>(V); 3981 if (!CI2 || CI2->getCalledFunction() != F || 3982 getVectorIntrinsicIDForCall(CI2, TLI) != ID || 3983 (VecFunc && 3984 VecFunc != VFDatabase(*CI2).getVectorizedFunction(Shape)) || 3985 !CI->hasIdenticalOperandBundleSchema(*CI2)) { 3986 BS.cancelScheduling(VL, VL0); 3987 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 3988 ReuseShuffleIndicies); 3989 LLVM_DEBUG(dbgs() << "SLP: mismatched calls:" << *CI << "!=" << *V 3990 << "\n"); 3991 return; 3992 } 3993 // Some intrinsics have scalar arguments and should be same in order for 3994 // them to be vectorized. 3995 for (unsigned j = 0; j != NumArgs; ++j) { 3996 if (hasVectorInstrinsicScalarOpd(ID, j)) { 3997 Value *A1J = CI2->getArgOperand(j); 3998 if (ScalarArgs[j] != A1J) { 3999 BS.cancelScheduling(VL, VL0); 4000 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4001 ReuseShuffleIndicies); 4002 LLVM_DEBUG(dbgs() << "SLP: mismatched arguments in call:" << *CI 4003 << " argument " << ScalarArgs[j] << "!=" << A1J 4004 << "\n"); 4005 return; 4006 } 4007 } 4008 } 4009 // Verify that the bundle operands are identical between the two calls. 4010 if (CI->hasOperandBundles() && 4011 !std::equal(CI->op_begin() + CI->getBundleOperandsStartIndex(), 4012 CI->op_begin() + CI->getBundleOperandsEndIndex(), 4013 CI2->op_begin() + CI2->getBundleOperandsStartIndex())) { 4014 BS.cancelScheduling(VL, VL0); 4015 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4016 ReuseShuffleIndicies); 4017 LLVM_DEBUG(dbgs() << "SLP: mismatched bundle operands in calls:" 4018 << *CI << "!=" << *V << '\n'); 4019 return; 4020 } 4021 } 4022 4023 TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, 4024 ReuseShuffleIndicies); 4025 TE->setOperandsInOrder(); 4026 for (unsigned i = 0, e = CI->arg_size(); i != e; ++i) { 4027 ValueList Operands; 4028 // Prepare the operand vector. 4029 for (Value *V : VL) { 4030 auto *CI2 = cast<CallInst>(V); 4031 Operands.push_back(CI2->getArgOperand(i)); 4032 } 4033 buildTree_rec(Operands, Depth + 1, {TE, i}); 4034 } 4035 return; 4036 } 4037 case Instruction::ShuffleVector: { 4038 // If this is not an alternate sequence of opcode like add-sub 4039 // then do not vectorize this instruction. 4040 if (!S.isAltShuffle()) { 4041 BS.cancelScheduling(VL, VL0); 4042 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4043 ReuseShuffleIndicies); 4044 LLVM_DEBUG(dbgs() << "SLP: ShuffleVector are not vectorized.\n"); 4045 return; 4046 } 4047 TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, 4048 ReuseShuffleIndicies); 4049 LLVM_DEBUG(dbgs() << "SLP: added a ShuffleVector op.\n"); 4050 4051 // Reorder operands if reordering would enable vectorization. 4052 if (isa<BinaryOperator>(VL0)) { 4053 ValueList Left, Right; 4054 reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this); 4055 TE->setOperand(0, Left); 4056 TE->setOperand(1, Right); 4057 buildTree_rec(Left, Depth + 1, {TE, 0}); 4058 buildTree_rec(Right, Depth + 1, {TE, 1}); 4059 return; 4060 } 4061 4062 TE->setOperandsInOrder(); 4063 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) { 4064 ValueList Operands; 4065 // Prepare the operand vector. 4066 for (Value *V : VL) 4067 Operands.push_back(cast<Instruction>(V)->getOperand(i)); 4068 4069 buildTree_rec(Operands, Depth + 1, {TE, i}); 4070 } 4071 return; 4072 } 4073 default: 4074 BS.cancelScheduling(VL, VL0); 4075 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4076 ReuseShuffleIndicies); 4077 LLVM_DEBUG(dbgs() << "SLP: Gathering unknown instruction.\n"); 4078 return; 4079 } 4080 } 4081 4082 unsigned BoUpSLP::canMapToVector(Type *T, const DataLayout &DL) const { 4083 unsigned N = 1; 4084 Type *EltTy = T; 4085 4086 while (isa<StructType>(EltTy) || isa<ArrayType>(EltTy) || 4087 isa<VectorType>(EltTy)) { 4088 if (auto *ST = dyn_cast<StructType>(EltTy)) { 4089 // Check that struct is homogeneous. 4090 for (const auto *Ty : ST->elements()) 4091 if (Ty != *ST->element_begin()) 4092 return 0; 4093 N *= ST->getNumElements(); 4094 EltTy = *ST->element_begin(); 4095 } else if (auto *AT = dyn_cast<ArrayType>(EltTy)) { 4096 N *= AT->getNumElements(); 4097 EltTy = AT->getElementType(); 4098 } else { 4099 auto *VT = cast<FixedVectorType>(EltTy); 4100 N *= VT->getNumElements(); 4101 EltTy = VT->getElementType(); 4102 } 4103 } 4104 4105 if (!isValidElementType(EltTy)) 4106 return 0; 4107 uint64_t VTSize = DL.getTypeStoreSizeInBits(FixedVectorType::get(EltTy, N)); 4108 if (VTSize < MinVecRegSize || VTSize > MaxVecRegSize || VTSize != DL.getTypeStoreSizeInBits(T)) 4109 return 0; 4110 return N; 4111 } 4112 4113 bool BoUpSLP::canReuseExtract(ArrayRef<Value *> VL, Value *OpValue, 4114 SmallVectorImpl<unsigned> &CurrentOrder) const { 4115 Instruction *E0 = cast<Instruction>(OpValue); 4116 assert(E0->getOpcode() == Instruction::ExtractElement || 4117 E0->getOpcode() == Instruction::ExtractValue); 4118 assert(E0->getOpcode() == getSameOpcode(VL).getOpcode() && "Invalid opcode"); 4119 // Check if all of the extracts come from the same vector and from the 4120 // correct offset. 4121 Value *Vec = E0->getOperand(0); 4122 4123 CurrentOrder.clear(); 4124 4125 // We have to extract from a vector/aggregate with the same number of elements. 4126 unsigned NElts; 4127 if (E0->getOpcode() == Instruction::ExtractValue) { 4128 const DataLayout &DL = E0->getModule()->getDataLayout(); 4129 NElts = canMapToVector(Vec->getType(), DL); 4130 if (!NElts) 4131 return false; 4132 // Check if load can be rewritten as load of vector. 4133 LoadInst *LI = dyn_cast<LoadInst>(Vec); 4134 if (!LI || !LI->isSimple() || !LI->hasNUses(VL.size())) 4135 return false; 4136 } else { 4137 NElts = cast<FixedVectorType>(Vec->getType())->getNumElements(); 4138 } 4139 4140 if (NElts != VL.size()) 4141 return false; 4142 4143 // Check that all of the indices extract from the correct offset. 4144 bool ShouldKeepOrder = true; 4145 unsigned E = VL.size(); 4146 // Assign to all items the initial value E + 1 so we can check if the extract 4147 // instruction index was used already. 4148 // Also, later we can check that all the indices are used and we have a 4149 // consecutive access in the extract instructions, by checking that no 4150 // element of CurrentOrder still has value E + 1. 4151 CurrentOrder.assign(E, E + 1); 4152 unsigned I = 0; 4153 for (; I < E; ++I) { 4154 auto *Inst = cast<Instruction>(VL[I]); 4155 if (Inst->getOperand(0) != Vec) 4156 break; 4157 Optional<unsigned> Idx = getExtractIndex(Inst); 4158 if (!Idx) 4159 break; 4160 const unsigned ExtIdx = *Idx; 4161 if (ExtIdx != I) { 4162 if (ExtIdx >= E || CurrentOrder[ExtIdx] != E + 1) 4163 break; 4164 ShouldKeepOrder = false; 4165 CurrentOrder[ExtIdx] = I; 4166 } else { 4167 if (CurrentOrder[I] != E + 1) 4168 break; 4169 CurrentOrder[I] = I; 4170 } 4171 } 4172 if (I < E) { 4173 CurrentOrder.clear(); 4174 return false; 4175 } 4176 4177 return ShouldKeepOrder; 4178 } 4179 4180 bool BoUpSLP::areAllUsersVectorized(Instruction *I, 4181 ArrayRef<Value *> VectorizedVals) const { 4182 return (I->hasOneUse() && is_contained(VectorizedVals, I)) || 4183 llvm::all_of(I->users(), [this](User *U) { 4184 return ScalarToTreeEntry.count(U) > 0; 4185 }); 4186 } 4187 4188 static std::pair<InstructionCost, InstructionCost> 4189 getVectorCallCosts(CallInst *CI, FixedVectorType *VecTy, 4190 TargetTransformInfo *TTI, TargetLibraryInfo *TLI) { 4191 Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI); 4192 4193 // Calculate the cost of the scalar and vector calls. 4194 SmallVector<Type *, 4> VecTys; 4195 for (Use &Arg : CI->args()) 4196 VecTys.push_back( 4197 FixedVectorType::get(Arg->getType(), VecTy->getNumElements())); 4198 FastMathFlags FMF; 4199 if (auto *FPCI = dyn_cast<FPMathOperator>(CI)) 4200 FMF = FPCI->getFastMathFlags(); 4201 SmallVector<const Value *> Arguments(CI->args()); 4202 IntrinsicCostAttributes CostAttrs(ID, VecTy, Arguments, VecTys, FMF, 4203 dyn_cast<IntrinsicInst>(CI)); 4204 auto IntrinsicCost = 4205 TTI->getIntrinsicInstrCost(CostAttrs, TTI::TCK_RecipThroughput); 4206 4207 auto Shape = VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>( 4208 VecTy->getNumElements())), 4209 false /*HasGlobalPred*/); 4210 Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape); 4211 auto LibCost = IntrinsicCost; 4212 if (!CI->isNoBuiltin() && VecFunc) { 4213 // Calculate the cost of the vector library call. 4214 // If the corresponding vector call is cheaper, return its cost. 4215 LibCost = TTI->getCallInstrCost(nullptr, VecTy, VecTys, 4216 TTI::TCK_RecipThroughput); 4217 } 4218 return {IntrinsicCost, LibCost}; 4219 } 4220 4221 /// Compute the cost of creating a vector of type \p VecTy containing the 4222 /// extracted values from \p VL. 4223 static InstructionCost 4224 computeExtractCost(ArrayRef<Value *> VL, FixedVectorType *VecTy, 4225 TargetTransformInfo::ShuffleKind ShuffleKind, 4226 ArrayRef<int> Mask, TargetTransformInfo &TTI) { 4227 unsigned NumOfParts = TTI.getNumberOfParts(VecTy); 4228 4229 if (ShuffleKind != TargetTransformInfo::SK_PermuteSingleSrc || !NumOfParts || 4230 VecTy->getNumElements() < NumOfParts) 4231 return TTI.getShuffleCost(ShuffleKind, VecTy, Mask); 4232 4233 bool AllConsecutive = true; 4234 unsigned EltsPerVector = VecTy->getNumElements() / NumOfParts; 4235 unsigned Idx = -1; 4236 InstructionCost Cost = 0; 4237 4238 // Process extracts in blocks of EltsPerVector to check if the source vector 4239 // operand can be re-used directly. If not, add the cost of creating a shuffle 4240 // to extract the values into a vector register. 4241 for (auto *V : VL) { 4242 ++Idx; 4243 4244 // Reached the start of a new vector registers. 4245 if (Idx % EltsPerVector == 0) { 4246 AllConsecutive = true; 4247 continue; 4248 } 4249 4250 // Check all extracts for a vector register on the target directly 4251 // extract values in order. 4252 unsigned CurrentIdx = *getExtractIndex(cast<Instruction>(V)); 4253 unsigned PrevIdx = *getExtractIndex(cast<Instruction>(VL[Idx - 1])); 4254 AllConsecutive &= PrevIdx + 1 == CurrentIdx && 4255 CurrentIdx % EltsPerVector == Idx % EltsPerVector; 4256 4257 if (AllConsecutive) 4258 continue; 4259 4260 // Skip all indices, except for the last index per vector block. 4261 if ((Idx + 1) % EltsPerVector != 0 && Idx + 1 != VL.size()) 4262 continue; 4263 4264 // If we have a series of extracts which are not consecutive and hence 4265 // cannot re-use the source vector register directly, compute the shuffle 4266 // cost to extract the a vector with EltsPerVector elements. 4267 Cost += TTI.getShuffleCost( 4268 TargetTransformInfo::SK_PermuteSingleSrc, 4269 FixedVectorType::get(VecTy->getElementType(), EltsPerVector)); 4270 } 4271 return Cost; 4272 } 4273 4274 /// Build shuffle mask for shuffle graph entries and lists of main and alternate 4275 /// operations operands. 4276 static void 4277 buildSuffleEntryMask(ArrayRef<Value *> VL, ArrayRef<unsigned> ReorderIndices, 4278 ArrayRef<int> ReusesIndices, 4279 const function_ref<bool(Instruction *)> IsAltOp, 4280 SmallVectorImpl<int> &Mask, 4281 SmallVectorImpl<Value *> *OpScalars = nullptr, 4282 SmallVectorImpl<Value *> *AltScalars = nullptr) { 4283 unsigned Sz = VL.size(); 4284 Mask.assign(Sz, UndefMaskElem); 4285 SmallVector<int> OrderMask; 4286 if (!ReorderIndices.empty()) 4287 inversePermutation(ReorderIndices, OrderMask); 4288 for (unsigned I = 0; I < Sz; ++I) { 4289 unsigned Idx = I; 4290 if (!ReorderIndices.empty()) 4291 Idx = OrderMask[I]; 4292 auto *OpInst = cast<Instruction>(VL[Idx]); 4293 if (IsAltOp(OpInst)) { 4294 Mask[I] = Sz + Idx; 4295 if (AltScalars) 4296 AltScalars->push_back(OpInst); 4297 } else { 4298 Mask[I] = Idx; 4299 if (OpScalars) 4300 OpScalars->push_back(OpInst); 4301 } 4302 } 4303 if (!ReusesIndices.empty()) { 4304 SmallVector<int> NewMask(ReusesIndices.size(), UndefMaskElem); 4305 transform(ReusesIndices, NewMask.begin(), [&Mask](int Idx) { 4306 return Idx != UndefMaskElem ? Mask[Idx] : UndefMaskElem; 4307 }); 4308 Mask.swap(NewMask); 4309 } 4310 } 4311 4312 InstructionCost BoUpSLP::getEntryCost(const TreeEntry *E, 4313 ArrayRef<Value *> VectorizedVals) { 4314 ArrayRef<Value*> VL = E->Scalars; 4315 4316 Type *ScalarTy = VL[0]->getType(); 4317 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0])) 4318 ScalarTy = SI->getValueOperand()->getType(); 4319 else if (CmpInst *CI = dyn_cast<CmpInst>(VL[0])) 4320 ScalarTy = CI->getOperand(0)->getType(); 4321 else if (auto *IE = dyn_cast<InsertElementInst>(VL[0])) 4322 ScalarTy = IE->getOperand(1)->getType(); 4323 auto *VecTy = FixedVectorType::get(ScalarTy, VL.size()); 4324 TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput; 4325 4326 // If we have computed a smaller type for the expression, update VecTy so 4327 // that the costs will be accurate. 4328 if (MinBWs.count(VL[0])) 4329 VecTy = FixedVectorType::get( 4330 IntegerType::get(F->getContext(), MinBWs[VL[0]].first), VL.size()); 4331 auto *FinalVecTy = VecTy; 4332 4333 unsigned ReuseShuffleNumbers = E->ReuseShuffleIndices.size(); 4334 bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty(); 4335 if (NeedToShuffleReuses) 4336 FinalVecTy = 4337 FixedVectorType::get(VecTy->getElementType(), ReuseShuffleNumbers); 4338 // FIXME: it tries to fix a problem with MSVC buildbots. 4339 TargetTransformInfo &TTIRef = *TTI; 4340 auto &&AdjustExtractsCost = [this, &TTIRef, CostKind, VL, VecTy, 4341 VectorizedVals](InstructionCost &Cost, 4342 bool IsGather) { 4343 DenseMap<Value *, int> ExtractVectorsTys; 4344 for (auto *V : VL) { 4345 // If all users of instruction are going to be vectorized and this 4346 // instruction itself is not going to be vectorized, consider this 4347 // instruction as dead and remove its cost from the final cost of the 4348 // vectorized tree. 4349 if (!areAllUsersVectorized(cast<Instruction>(V), VectorizedVals) || 4350 (IsGather && ScalarToTreeEntry.count(V))) 4351 continue; 4352 auto *EE = cast<ExtractElementInst>(V); 4353 unsigned Idx = *getExtractIndex(EE); 4354 if (TTIRef.getNumberOfParts(VecTy) != 4355 TTIRef.getNumberOfParts(EE->getVectorOperandType())) { 4356 auto It = 4357 ExtractVectorsTys.try_emplace(EE->getVectorOperand(), Idx).first; 4358 It->getSecond() = std::min<int>(It->second, Idx); 4359 } 4360 // Take credit for instruction that will become dead. 4361 if (EE->hasOneUse()) { 4362 Instruction *Ext = EE->user_back(); 4363 if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) && 4364 all_of(Ext->users(), 4365 [](User *U) { return isa<GetElementPtrInst>(U); })) { 4366 // Use getExtractWithExtendCost() to calculate the cost of 4367 // extractelement/ext pair. 4368 Cost -= 4369 TTIRef.getExtractWithExtendCost(Ext->getOpcode(), Ext->getType(), 4370 EE->getVectorOperandType(), Idx); 4371 // Add back the cost of s|zext which is subtracted separately. 4372 Cost += TTIRef.getCastInstrCost( 4373 Ext->getOpcode(), Ext->getType(), EE->getType(), 4374 TTI::getCastContextHint(Ext), CostKind, Ext); 4375 continue; 4376 } 4377 } 4378 Cost -= TTIRef.getVectorInstrCost(Instruction::ExtractElement, 4379 EE->getVectorOperandType(), Idx); 4380 } 4381 // Add a cost for subvector extracts/inserts if required. 4382 for (const auto &Data : ExtractVectorsTys) { 4383 auto *EEVTy = cast<FixedVectorType>(Data.first->getType()); 4384 unsigned NumElts = VecTy->getNumElements(); 4385 if (TTIRef.getNumberOfParts(EEVTy) > TTIRef.getNumberOfParts(VecTy)) { 4386 unsigned Idx = (Data.second / NumElts) * NumElts; 4387 unsigned EENumElts = EEVTy->getNumElements(); 4388 if (Idx + NumElts <= EENumElts) { 4389 Cost += 4390 TTIRef.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector, 4391 EEVTy, None, Idx, VecTy); 4392 } else { 4393 // Need to round up the subvector type vectorization factor to avoid a 4394 // crash in cost model functions. Make SubVT so that Idx + VF of SubVT 4395 // <= EENumElts. 4396 auto *SubVT = 4397 FixedVectorType::get(VecTy->getElementType(), EENumElts - Idx); 4398 Cost += 4399 TTIRef.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector, 4400 EEVTy, None, Idx, SubVT); 4401 } 4402 } else { 4403 Cost += TTIRef.getShuffleCost(TargetTransformInfo::SK_InsertSubvector, 4404 VecTy, None, 0, EEVTy); 4405 } 4406 } 4407 }; 4408 if (E->State == TreeEntry::NeedToGather) { 4409 if (allConstant(VL)) 4410 return 0; 4411 if (isa<InsertElementInst>(VL[0])) 4412 return InstructionCost::getInvalid(); 4413 SmallVector<int> Mask; 4414 SmallVector<const TreeEntry *> Entries; 4415 Optional<TargetTransformInfo::ShuffleKind> Shuffle = 4416 isGatherShuffledEntry(E, Mask, Entries); 4417 if (Shuffle.hasValue()) { 4418 InstructionCost GatherCost = 0; 4419 if (ShuffleVectorInst::isIdentityMask(Mask)) { 4420 // Perfect match in the graph, will reuse the previously vectorized 4421 // node. Cost is 0. 4422 LLVM_DEBUG( 4423 dbgs() 4424 << "SLP: perfect diamond match for gather bundle that starts with " 4425 << *VL.front() << ".\n"); 4426 if (NeedToShuffleReuses) 4427 GatherCost = 4428 TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, 4429 FinalVecTy, E->ReuseShuffleIndices); 4430 } else { 4431 LLVM_DEBUG(dbgs() << "SLP: shuffled " << Entries.size() 4432 << " entries for bundle that starts with " 4433 << *VL.front() << ".\n"); 4434 // Detected that instead of gather we can emit a shuffle of single/two 4435 // previously vectorized nodes. Add the cost of the permutation rather 4436 // than gather. 4437 ::addMask(Mask, E->ReuseShuffleIndices); 4438 GatherCost = TTI->getShuffleCost(*Shuffle, FinalVecTy, Mask); 4439 } 4440 return GatherCost; 4441 } 4442 if (isSplat(VL)) { 4443 // Found the broadcasting of the single scalar, calculate the cost as the 4444 // broadcast. 4445 return TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy); 4446 } 4447 if (E->getOpcode() == Instruction::ExtractElement && allSameType(VL) && 4448 allSameBlock(VL) && 4449 !isa<ScalableVectorType>( 4450 cast<ExtractElementInst>(E->getMainOp())->getVectorOperandType())) { 4451 // Check that gather of extractelements can be represented as just a 4452 // shuffle of a single/two vectors the scalars are extracted from. 4453 SmallVector<int> Mask; 4454 Optional<TargetTransformInfo::ShuffleKind> ShuffleKind = 4455 isFixedVectorShuffle(VL, Mask); 4456 if (ShuffleKind.hasValue()) { 4457 // Found the bunch of extractelement instructions that must be gathered 4458 // into a vector and can be represented as a permutation elements in a 4459 // single input vector or of 2 input vectors. 4460 InstructionCost Cost = 4461 computeExtractCost(VL, VecTy, *ShuffleKind, Mask, *TTI); 4462 AdjustExtractsCost(Cost, /*IsGather=*/true); 4463 if (NeedToShuffleReuses) 4464 Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, 4465 FinalVecTy, E->ReuseShuffleIndices); 4466 return Cost; 4467 } 4468 } 4469 InstructionCost ReuseShuffleCost = 0; 4470 if (NeedToShuffleReuses) 4471 ReuseShuffleCost = TTI->getShuffleCost( 4472 TTI::SK_PermuteSingleSrc, FinalVecTy, E->ReuseShuffleIndices); 4473 // Improve gather cost for gather of loads, if we can group some of the 4474 // loads into vector loads. 4475 if (VL.size() > 2 && E->getOpcode() == Instruction::Load && 4476 !E->isAltShuffle()) { 4477 BoUpSLP::ValueSet VectorizedLoads; 4478 unsigned StartIdx = 0; 4479 unsigned VF = VL.size() / 2; 4480 unsigned VectorizedCnt = 0; 4481 unsigned ScatterVectorizeCnt = 0; 4482 const unsigned Sz = DL->getTypeSizeInBits(E->getMainOp()->getType()); 4483 for (unsigned MinVF = getMinVF(2 * Sz); VF >= MinVF; VF /= 2) { 4484 for (unsigned Cnt = StartIdx, End = VL.size(); Cnt + VF <= End; 4485 Cnt += VF) { 4486 ArrayRef<Value *> Slice = VL.slice(Cnt, VF); 4487 if (!VectorizedLoads.count(Slice.front()) && 4488 !VectorizedLoads.count(Slice.back()) && allSameBlock(Slice)) { 4489 SmallVector<Value *> PointerOps; 4490 OrdersType CurrentOrder; 4491 LoadsState LS = canVectorizeLoads(Slice, Slice.front(), *TTI, *DL, 4492 *SE, CurrentOrder, PointerOps); 4493 switch (LS) { 4494 case LoadsState::Vectorize: 4495 case LoadsState::ScatterVectorize: 4496 // Mark the vectorized loads so that we don't vectorize them 4497 // again. 4498 if (LS == LoadsState::Vectorize) 4499 ++VectorizedCnt; 4500 else 4501 ++ScatterVectorizeCnt; 4502 VectorizedLoads.insert(Slice.begin(), Slice.end()); 4503 // If we vectorized initial block, no need to try to vectorize it 4504 // again. 4505 if (Cnt == StartIdx) 4506 StartIdx += VF; 4507 break; 4508 case LoadsState::Gather: 4509 break; 4510 } 4511 } 4512 } 4513 // Check if the whole array was vectorized already - exit. 4514 if (StartIdx >= VL.size()) 4515 break; 4516 // Found vectorizable parts - exit. 4517 if (!VectorizedLoads.empty()) 4518 break; 4519 } 4520 if (!VectorizedLoads.empty()) { 4521 InstructionCost GatherCost = 0; 4522 unsigned NumParts = TTI->getNumberOfParts(VecTy); 4523 bool NeedInsertSubvectorAnalysis = 4524 !NumParts || (VL.size() / VF) > NumParts; 4525 // Get the cost for gathered loads. 4526 for (unsigned I = 0, End = VL.size(); I < End; I += VF) { 4527 if (VectorizedLoads.contains(VL[I])) 4528 continue; 4529 GatherCost += getGatherCost(VL.slice(I, VF)); 4530 } 4531 // The cost for vectorized loads. 4532 InstructionCost ScalarsCost = 0; 4533 for (Value *V : VectorizedLoads) { 4534 auto *LI = cast<LoadInst>(V); 4535 ScalarsCost += TTI->getMemoryOpCost( 4536 Instruction::Load, LI->getType(), LI->getAlign(), 4537 LI->getPointerAddressSpace(), CostKind, LI); 4538 } 4539 auto *LI = cast<LoadInst>(E->getMainOp()); 4540 auto *LoadTy = FixedVectorType::get(LI->getType(), VF); 4541 Align Alignment = LI->getAlign(); 4542 GatherCost += 4543 VectorizedCnt * 4544 TTI->getMemoryOpCost(Instruction::Load, LoadTy, Alignment, 4545 LI->getPointerAddressSpace(), CostKind, LI); 4546 GatherCost += ScatterVectorizeCnt * 4547 TTI->getGatherScatterOpCost( 4548 Instruction::Load, LoadTy, LI->getPointerOperand(), 4549 /*VariableMask=*/false, Alignment, CostKind, LI); 4550 if (NeedInsertSubvectorAnalysis) { 4551 // Add the cost for the subvectors insert. 4552 for (int I = VF, E = VL.size(); I < E; I += VF) 4553 GatherCost += TTI->getShuffleCost(TTI::SK_InsertSubvector, VecTy, 4554 None, I, LoadTy); 4555 } 4556 return ReuseShuffleCost + GatherCost - ScalarsCost; 4557 } 4558 } 4559 return ReuseShuffleCost + getGatherCost(VL); 4560 } 4561 InstructionCost CommonCost = 0; 4562 SmallVector<int> Mask; 4563 if (!E->ReorderIndices.empty()) { 4564 SmallVector<int> NewMask; 4565 if (E->getOpcode() == Instruction::Store) { 4566 // For stores the order is actually a mask. 4567 NewMask.resize(E->ReorderIndices.size()); 4568 copy(E->ReorderIndices, NewMask.begin()); 4569 } else { 4570 inversePermutation(E->ReorderIndices, NewMask); 4571 } 4572 ::addMask(Mask, NewMask); 4573 } 4574 if (NeedToShuffleReuses) 4575 ::addMask(Mask, E->ReuseShuffleIndices); 4576 if (!Mask.empty() && !ShuffleVectorInst::isIdentityMask(Mask)) 4577 CommonCost = 4578 TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, FinalVecTy, Mask); 4579 assert((E->State == TreeEntry::Vectorize || 4580 E->State == TreeEntry::ScatterVectorize) && 4581 "Unhandled state"); 4582 assert(E->getOpcode() && allSameType(VL) && allSameBlock(VL) && "Invalid VL"); 4583 Instruction *VL0 = E->getMainOp(); 4584 unsigned ShuffleOrOp = 4585 E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode(); 4586 switch (ShuffleOrOp) { 4587 case Instruction::PHI: 4588 return 0; 4589 4590 case Instruction::ExtractValue: 4591 case Instruction::ExtractElement: { 4592 // The common cost of removal ExtractElement/ExtractValue instructions + 4593 // the cost of shuffles, if required to resuffle the original vector. 4594 if (NeedToShuffleReuses) { 4595 unsigned Idx = 0; 4596 for (unsigned I : E->ReuseShuffleIndices) { 4597 if (ShuffleOrOp == Instruction::ExtractElement) { 4598 auto *EE = cast<ExtractElementInst>(VL[I]); 4599 CommonCost -= TTI->getVectorInstrCost(Instruction::ExtractElement, 4600 EE->getVectorOperandType(), 4601 *getExtractIndex(EE)); 4602 } else { 4603 CommonCost -= TTI->getVectorInstrCost(Instruction::ExtractElement, 4604 VecTy, Idx); 4605 ++Idx; 4606 } 4607 } 4608 Idx = ReuseShuffleNumbers; 4609 for (Value *V : VL) { 4610 if (ShuffleOrOp == Instruction::ExtractElement) { 4611 auto *EE = cast<ExtractElementInst>(V); 4612 CommonCost += TTI->getVectorInstrCost(Instruction::ExtractElement, 4613 EE->getVectorOperandType(), 4614 *getExtractIndex(EE)); 4615 } else { 4616 --Idx; 4617 CommonCost += TTI->getVectorInstrCost(Instruction::ExtractElement, 4618 VecTy, Idx); 4619 } 4620 } 4621 } 4622 if (ShuffleOrOp == Instruction::ExtractValue) { 4623 for (unsigned I = 0, E = VL.size(); I < E; ++I) { 4624 auto *EI = cast<Instruction>(VL[I]); 4625 // Take credit for instruction that will become dead. 4626 if (EI->hasOneUse()) { 4627 Instruction *Ext = EI->user_back(); 4628 if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) && 4629 all_of(Ext->users(), 4630 [](User *U) { return isa<GetElementPtrInst>(U); })) { 4631 // Use getExtractWithExtendCost() to calculate the cost of 4632 // extractelement/ext pair. 4633 CommonCost -= TTI->getExtractWithExtendCost( 4634 Ext->getOpcode(), Ext->getType(), VecTy, I); 4635 // Add back the cost of s|zext which is subtracted separately. 4636 CommonCost += TTI->getCastInstrCost( 4637 Ext->getOpcode(), Ext->getType(), EI->getType(), 4638 TTI::getCastContextHint(Ext), CostKind, Ext); 4639 continue; 4640 } 4641 } 4642 CommonCost -= 4643 TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, I); 4644 } 4645 } else { 4646 AdjustExtractsCost(CommonCost, /*IsGather=*/false); 4647 } 4648 return CommonCost; 4649 } 4650 case Instruction::InsertElement: { 4651 assert(E->ReuseShuffleIndices.empty() && 4652 "Unique insertelements only are expected."); 4653 auto *SrcVecTy = cast<FixedVectorType>(VL0->getType()); 4654 4655 unsigned const NumElts = SrcVecTy->getNumElements(); 4656 unsigned const NumScalars = VL.size(); 4657 APInt DemandedElts = APInt::getZero(NumElts); 4658 // TODO: Add support for Instruction::InsertValue. 4659 SmallVector<int> Mask; 4660 if (!E->ReorderIndices.empty()) { 4661 inversePermutation(E->ReorderIndices, Mask); 4662 Mask.append(NumElts - NumScalars, UndefMaskElem); 4663 } else { 4664 Mask.assign(NumElts, UndefMaskElem); 4665 std::iota(Mask.begin(), std::next(Mask.begin(), NumScalars), 0); 4666 } 4667 unsigned Offset = *getInsertIndex(VL0, 0); 4668 bool IsIdentity = true; 4669 SmallVector<int> PrevMask(NumElts, UndefMaskElem); 4670 Mask.swap(PrevMask); 4671 for (unsigned I = 0; I < NumScalars; ++I) { 4672 Optional<int> InsertIdx = getInsertIndex(VL[PrevMask[I]], 0); 4673 if (!InsertIdx || *InsertIdx == UndefMaskElem) 4674 continue; 4675 DemandedElts.setBit(*InsertIdx); 4676 IsIdentity &= *InsertIdx - Offset == I; 4677 Mask[*InsertIdx - Offset] = I; 4678 } 4679 assert(Offset < NumElts && "Failed to find vector index offset"); 4680 4681 InstructionCost Cost = 0; 4682 Cost -= TTI->getScalarizationOverhead(SrcVecTy, DemandedElts, 4683 /*Insert*/ true, /*Extract*/ false); 4684 4685 if (IsIdentity && NumElts != NumScalars && Offset % NumScalars != 0) { 4686 // FIXME: Replace with SK_InsertSubvector once it is properly supported. 4687 unsigned Sz = PowerOf2Ceil(Offset + NumScalars); 4688 Cost += TTI->getShuffleCost( 4689 TargetTransformInfo::SK_PermuteSingleSrc, 4690 FixedVectorType::get(SrcVecTy->getElementType(), Sz)); 4691 } else if (!IsIdentity) { 4692 auto *FirstInsert = 4693 cast<Instruction>(*find_if(E->Scalars, [E](Value *V) { 4694 return !is_contained(E->Scalars, 4695 cast<Instruction>(V)->getOperand(0)); 4696 })); 4697 if (isa<UndefValue>(FirstInsert->getOperand(0))) { 4698 Cost += TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, SrcVecTy, Mask); 4699 } else { 4700 SmallVector<int> InsertMask(NumElts); 4701 std::iota(InsertMask.begin(), InsertMask.end(), 0); 4702 for (unsigned I = 0; I < NumElts; I++) { 4703 if (Mask[I] != UndefMaskElem) 4704 InsertMask[Offset + I] = NumElts + I; 4705 } 4706 Cost += 4707 TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, SrcVecTy, InsertMask); 4708 } 4709 } 4710 4711 return Cost; 4712 } 4713 case Instruction::ZExt: 4714 case Instruction::SExt: 4715 case Instruction::FPToUI: 4716 case Instruction::FPToSI: 4717 case Instruction::FPExt: 4718 case Instruction::PtrToInt: 4719 case Instruction::IntToPtr: 4720 case Instruction::SIToFP: 4721 case Instruction::UIToFP: 4722 case Instruction::Trunc: 4723 case Instruction::FPTrunc: 4724 case Instruction::BitCast: { 4725 Type *SrcTy = VL0->getOperand(0)->getType(); 4726 InstructionCost ScalarEltCost = 4727 TTI->getCastInstrCost(E->getOpcode(), ScalarTy, SrcTy, 4728 TTI::getCastContextHint(VL0), CostKind, VL0); 4729 if (NeedToShuffleReuses) { 4730 CommonCost -= (ReuseShuffleNumbers - VL.size()) * ScalarEltCost; 4731 } 4732 4733 // Calculate the cost of this instruction. 4734 InstructionCost ScalarCost = VL.size() * ScalarEltCost; 4735 4736 auto *SrcVecTy = FixedVectorType::get(SrcTy, VL.size()); 4737 InstructionCost VecCost = 0; 4738 // Check if the values are candidates to demote. 4739 if (!MinBWs.count(VL0) || VecTy != SrcVecTy) { 4740 VecCost = CommonCost + TTI->getCastInstrCost( 4741 E->getOpcode(), VecTy, SrcVecTy, 4742 TTI::getCastContextHint(VL0), CostKind, VL0); 4743 } 4744 LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost)); 4745 return VecCost - ScalarCost; 4746 } 4747 case Instruction::FCmp: 4748 case Instruction::ICmp: 4749 case Instruction::Select: { 4750 // Calculate the cost of this instruction. 4751 InstructionCost ScalarEltCost = 4752 TTI->getCmpSelInstrCost(E->getOpcode(), ScalarTy, Builder.getInt1Ty(), 4753 CmpInst::BAD_ICMP_PREDICATE, CostKind, VL0); 4754 if (NeedToShuffleReuses) { 4755 CommonCost -= (ReuseShuffleNumbers - VL.size()) * ScalarEltCost; 4756 } 4757 auto *MaskTy = FixedVectorType::get(Builder.getInt1Ty(), VL.size()); 4758 InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost; 4759 4760 // Check if all entries in VL are either compares or selects with compares 4761 // as condition that have the same predicates. 4762 CmpInst::Predicate VecPred = CmpInst::BAD_ICMP_PREDICATE; 4763 bool First = true; 4764 for (auto *V : VL) { 4765 CmpInst::Predicate CurrentPred; 4766 auto MatchCmp = m_Cmp(CurrentPred, m_Value(), m_Value()); 4767 if ((!match(V, m_Select(MatchCmp, m_Value(), m_Value())) && 4768 !match(V, MatchCmp)) || 4769 (!First && VecPred != CurrentPred)) { 4770 VecPred = CmpInst::BAD_ICMP_PREDICATE; 4771 break; 4772 } 4773 First = false; 4774 VecPred = CurrentPred; 4775 } 4776 4777 InstructionCost VecCost = TTI->getCmpSelInstrCost( 4778 E->getOpcode(), VecTy, MaskTy, VecPred, CostKind, VL0); 4779 // Check if it is possible and profitable to use min/max for selects in 4780 // VL. 4781 // 4782 auto IntrinsicAndUse = canConvertToMinOrMaxIntrinsic(VL); 4783 if (IntrinsicAndUse.first != Intrinsic::not_intrinsic) { 4784 IntrinsicCostAttributes CostAttrs(IntrinsicAndUse.first, VecTy, 4785 {VecTy, VecTy}); 4786 InstructionCost IntrinsicCost = 4787 TTI->getIntrinsicInstrCost(CostAttrs, CostKind); 4788 // If the selects are the only uses of the compares, they will be dead 4789 // and we can adjust the cost by removing their cost. 4790 if (IntrinsicAndUse.second) 4791 IntrinsicCost -= 4792 TTI->getCmpSelInstrCost(Instruction::ICmp, VecTy, MaskTy, 4793 CmpInst::BAD_ICMP_PREDICATE, CostKind); 4794 VecCost = std::min(VecCost, IntrinsicCost); 4795 } 4796 LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost)); 4797 return CommonCost + VecCost - ScalarCost; 4798 } 4799 case Instruction::FNeg: 4800 case Instruction::Add: 4801 case Instruction::FAdd: 4802 case Instruction::Sub: 4803 case Instruction::FSub: 4804 case Instruction::Mul: 4805 case Instruction::FMul: 4806 case Instruction::UDiv: 4807 case Instruction::SDiv: 4808 case Instruction::FDiv: 4809 case Instruction::URem: 4810 case Instruction::SRem: 4811 case Instruction::FRem: 4812 case Instruction::Shl: 4813 case Instruction::LShr: 4814 case Instruction::AShr: 4815 case Instruction::And: 4816 case Instruction::Or: 4817 case Instruction::Xor: { 4818 // Certain instructions can be cheaper to vectorize if they have a 4819 // constant second vector operand. 4820 TargetTransformInfo::OperandValueKind Op1VK = 4821 TargetTransformInfo::OK_AnyValue; 4822 TargetTransformInfo::OperandValueKind Op2VK = 4823 TargetTransformInfo::OK_UniformConstantValue; 4824 TargetTransformInfo::OperandValueProperties Op1VP = 4825 TargetTransformInfo::OP_None; 4826 TargetTransformInfo::OperandValueProperties Op2VP = 4827 TargetTransformInfo::OP_PowerOf2; 4828 4829 // If all operands are exactly the same ConstantInt then set the 4830 // operand kind to OK_UniformConstantValue. 4831 // If instead not all operands are constants, then set the operand kind 4832 // to OK_AnyValue. If all operands are constants but not the same, 4833 // then set the operand kind to OK_NonUniformConstantValue. 4834 ConstantInt *CInt0 = nullptr; 4835 for (unsigned i = 0, e = VL.size(); i < e; ++i) { 4836 const Instruction *I = cast<Instruction>(VL[i]); 4837 unsigned OpIdx = isa<BinaryOperator>(I) ? 1 : 0; 4838 ConstantInt *CInt = dyn_cast<ConstantInt>(I->getOperand(OpIdx)); 4839 if (!CInt) { 4840 Op2VK = TargetTransformInfo::OK_AnyValue; 4841 Op2VP = TargetTransformInfo::OP_None; 4842 break; 4843 } 4844 if (Op2VP == TargetTransformInfo::OP_PowerOf2 && 4845 !CInt->getValue().isPowerOf2()) 4846 Op2VP = TargetTransformInfo::OP_None; 4847 if (i == 0) { 4848 CInt0 = CInt; 4849 continue; 4850 } 4851 if (CInt0 != CInt) 4852 Op2VK = TargetTransformInfo::OK_NonUniformConstantValue; 4853 } 4854 4855 SmallVector<const Value *, 4> Operands(VL0->operand_values()); 4856 InstructionCost ScalarEltCost = 4857 TTI->getArithmeticInstrCost(E->getOpcode(), ScalarTy, CostKind, Op1VK, 4858 Op2VK, Op1VP, Op2VP, Operands, VL0); 4859 if (NeedToShuffleReuses) { 4860 CommonCost -= (ReuseShuffleNumbers - VL.size()) * ScalarEltCost; 4861 } 4862 InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost; 4863 InstructionCost VecCost = 4864 TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, CostKind, Op1VK, 4865 Op2VK, Op1VP, Op2VP, Operands, VL0); 4866 LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost)); 4867 return CommonCost + VecCost - ScalarCost; 4868 } 4869 case Instruction::GetElementPtr: { 4870 TargetTransformInfo::OperandValueKind Op1VK = 4871 TargetTransformInfo::OK_AnyValue; 4872 TargetTransformInfo::OperandValueKind Op2VK = 4873 TargetTransformInfo::OK_UniformConstantValue; 4874 4875 InstructionCost ScalarEltCost = TTI->getArithmeticInstrCost( 4876 Instruction::Add, ScalarTy, CostKind, Op1VK, Op2VK); 4877 if (NeedToShuffleReuses) { 4878 CommonCost -= (ReuseShuffleNumbers - VL.size()) * ScalarEltCost; 4879 } 4880 InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost; 4881 InstructionCost VecCost = TTI->getArithmeticInstrCost( 4882 Instruction::Add, VecTy, CostKind, Op1VK, Op2VK); 4883 LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost)); 4884 return CommonCost + VecCost - ScalarCost; 4885 } 4886 case Instruction::Load: { 4887 // Cost of wide load - cost of scalar loads. 4888 Align Alignment = cast<LoadInst>(VL0)->getAlign(); 4889 InstructionCost ScalarEltCost = TTI->getMemoryOpCost( 4890 Instruction::Load, ScalarTy, Alignment, 0, CostKind, VL0); 4891 if (NeedToShuffleReuses) { 4892 CommonCost -= (ReuseShuffleNumbers - VL.size()) * ScalarEltCost; 4893 } 4894 InstructionCost ScalarLdCost = VecTy->getNumElements() * ScalarEltCost; 4895 InstructionCost VecLdCost; 4896 if (E->State == TreeEntry::Vectorize) { 4897 VecLdCost = TTI->getMemoryOpCost(Instruction::Load, VecTy, Alignment, 0, 4898 CostKind, VL0); 4899 } else { 4900 assert(E->State == TreeEntry::ScatterVectorize && "Unknown EntryState"); 4901 Align CommonAlignment = Alignment; 4902 for (Value *V : VL) 4903 CommonAlignment = 4904 commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign()); 4905 VecLdCost = TTI->getGatherScatterOpCost( 4906 Instruction::Load, VecTy, cast<LoadInst>(VL0)->getPointerOperand(), 4907 /*VariableMask=*/false, CommonAlignment, CostKind, VL0); 4908 } 4909 LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecLdCost, ScalarLdCost)); 4910 return CommonCost + VecLdCost - ScalarLdCost; 4911 } 4912 case Instruction::Store: { 4913 // We know that we can merge the stores. Calculate the cost. 4914 bool IsReorder = !E->ReorderIndices.empty(); 4915 auto *SI = 4916 cast<StoreInst>(IsReorder ? VL[E->ReorderIndices.front()] : VL0); 4917 Align Alignment = SI->getAlign(); 4918 InstructionCost ScalarEltCost = TTI->getMemoryOpCost( 4919 Instruction::Store, ScalarTy, Alignment, 0, CostKind, VL0); 4920 InstructionCost ScalarStCost = VecTy->getNumElements() * ScalarEltCost; 4921 InstructionCost VecStCost = TTI->getMemoryOpCost( 4922 Instruction::Store, VecTy, Alignment, 0, CostKind, VL0); 4923 LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecStCost, ScalarStCost)); 4924 return CommonCost + VecStCost - ScalarStCost; 4925 } 4926 case Instruction::Call: { 4927 CallInst *CI = cast<CallInst>(VL0); 4928 Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI); 4929 4930 // Calculate the cost of the scalar and vector calls. 4931 IntrinsicCostAttributes CostAttrs(ID, *CI, 1); 4932 InstructionCost ScalarEltCost = 4933 TTI->getIntrinsicInstrCost(CostAttrs, CostKind); 4934 if (NeedToShuffleReuses) { 4935 CommonCost -= (ReuseShuffleNumbers - VL.size()) * ScalarEltCost; 4936 } 4937 InstructionCost ScalarCallCost = VecTy->getNumElements() * ScalarEltCost; 4938 4939 auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI); 4940 InstructionCost VecCallCost = 4941 std::min(VecCallCosts.first, VecCallCosts.second); 4942 4943 LLVM_DEBUG(dbgs() << "SLP: Call cost " << VecCallCost - ScalarCallCost 4944 << " (" << VecCallCost << "-" << ScalarCallCost << ")" 4945 << " for " << *CI << "\n"); 4946 4947 return CommonCost + VecCallCost - ScalarCallCost; 4948 } 4949 case Instruction::ShuffleVector: { 4950 assert(E->isAltShuffle() && 4951 ((Instruction::isBinaryOp(E->getOpcode()) && 4952 Instruction::isBinaryOp(E->getAltOpcode())) || 4953 (Instruction::isCast(E->getOpcode()) && 4954 Instruction::isCast(E->getAltOpcode()))) && 4955 "Invalid Shuffle Vector Operand"); 4956 InstructionCost ScalarCost = 0; 4957 if (NeedToShuffleReuses) { 4958 for (unsigned Idx : E->ReuseShuffleIndices) { 4959 Instruction *I = cast<Instruction>(VL[Idx]); 4960 CommonCost -= TTI->getInstructionCost(I, CostKind); 4961 } 4962 for (Value *V : VL) { 4963 Instruction *I = cast<Instruction>(V); 4964 CommonCost += TTI->getInstructionCost(I, CostKind); 4965 } 4966 } 4967 for (Value *V : VL) { 4968 Instruction *I = cast<Instruction>(V); 4969 assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode"); 4970 ScalarCost += TTI->getInstructionCost(I, CostKind); 4971 } 4972 // VecCost is equal to sum of the cost of creating 2 vectors 4973 // and the cost of creating shuffle. 4974 InstructionCost VecCost = 0; 4975 if (Instruction::isBinaryOp(E->getOpcode())) { 4976 VecCost = TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, CostKind); 4977 VecCost += TTI->getArithmeticInstrCost(E->getAltOpcode(), VecTy, 4978 CostKind); 4979 } else { 4980 Type *Src0SclTy = E->getMainOp()->getOperand(0)->getType(); 4981 Type *Src1SclTy = E->getAltOp()->getOperand(0)->getType(); 4982 auto *Src0Ty = FixedVectorType::get(Src0SclTy, VL.size()); 4983 auto *Src1Ty = FixedVectorType::get(Src1SclTy, VL.size()); 4984 VecCost = TTI->getCastInstrCost(E->getOpcode(), VecTy, Src0Ty, 4985 TTI::CastContextHint::None, CostKind); 4986 VecCost += TTI->getCastInstrCost(E->getAltOpcode(), VecTy, Src1Ty, 4987 TTI::CastContextHint::None, CostKind); 4988 } 4989 4990 SmallVector<int> Mask; 4991 buildSuffleEntryMask( 4992 E->Scalars, E->ReorderIndices, E->ReuseShuffleIndices, 4993 [E](Instruction *I) { 4994 assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode"); 4995 return I->getOpcode() == E->getAltOpcode(); 4996 }, 4997 Mask); 4998 CommonCost = 4999 TTI->getShuffleCost(TargetTransformInfo::SK_Select, FinalVecTy, Mask); 5000 LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost)); 5001 return CommonCost + VecCost - ScalarCost; 5002 } 5003 default: 5004 llvm_unreachable("Unknown instruction"); 5005 } 5006 } 5007 5008 bool BoUpSLP::isFullyVectorizableTinyTree(bool ForReduction) const { 5009 LLVM_DEBUG(dbgs() << "SLP: Check whether the tree with height " 5010 << VectorizableTree.size() << " is fully vectorizable .\n"); 5011 5012 auto &&AreVectorizableGathers = [this](const TreeEntry *TE, unsigned Limit) { 5013 SmallVector<int> Mask; 5014 return TE->State == TreeEntry::NeedToGather && 5015 !any_of(TE->Scalars, 5016 [this](Value *V) { return EphValues.contains(V); }) && 5017 (allConstant(TE->Scalars) || isSplat(TE->Scalars) || 5018 TE->Scalars.size() < Limit || 5019 (TE->getOpcode() == Instruction::ExtractElement && 5020 isFixedVectorShuffle(TE->Scalars, Mask)) || 5021 (TE->State == TreeEntry::NeedToGather && 5022 TE->getOpcode() == Instruction::Load && !TE->isAltShuffle())); 5023 }; 5024 5025 // We only handle trees of heights 1 and 2. 5026 if (VectorizableTree.size() == 1 && 5027 (VectorizableTree[0]->State == TreeEntry::Vectorize || 5028 (ForReduction && 5029 AreVectorizableGathers(VectorizableTree[0].get(), 5030 VectorizableTree[0]->Scalars.size()) && 5031 (VectorizableTree[0]->Scalars.size() > 2 || 5032 VectorizableTree[0]->ReuseShuffleIndices.size() > 2)))) 5033 return true; 5034 5035 if (VectorizableTree.size() != 2) 5036 return false; 5037 5038 // Handle splat and all-constants stores. Also try to vectorize tiny trees 5039 // with the second gather nodes if they have less scalar operands rather than 5040 // the initial tree element (may be profitable to shuffle the second gather) 5041 // or they are extractelements, which form shuffle. 5042 SmallVector<int> Mask; 5043 if (VectorizableTree[0]->State == TreeEntry::Vectorize && 5044 AreVectorizableGathers(VectorizableTree[1].get(), 5045 VectorizableTree[0]->Scalars.size())) 5046 return true; 5047 5048 // Gathering cost would be too much for tiny trees. 5049 if (VectorizableTree[0]->State == TreeEntry::NeedToGather || 5050 (VectorizableTree[1]->State == TreeEntry::NeedToGather && 5051 VectorizableTree[0]->State != TreeEntry::ScatterVectorize)) 5052 return false; 5053 5054 return true; 5055 } 5056 5057 static bool isLoadCombineCandidateImpl(Value *Root, unsigned NumElts, 5058 TargetTransformInfo *TTI, 5059 bool MustMatchOrInst) { 5060 // Look past the root to find a source value. Arbitrarily follow the 5061 // path through operand 0 of any 'or'. Also, peek through optional 5062 // shift-left-by-multiple-of-8-bits. 5063 Value *ZextLoad = Root; 5064 const APInt *ShAmtC; 5065 bool FoundOr = false; 5066 while (!isa<ConstantExpr>(ZextLoad) && 5067 (match(ZextLoad, m_Or(m_Value(), m_Value())) || 5068 (match(ZextLoad, m_Shl(m_Value(), m_APInt(ShAmtC))) && 5069 ShAmtC->urem(8) == 0))) { 5070 auto *BinOp = cast<BinaryOperator>(ZextLoad); 5071 ZextLoad = BinOp->getOperand(0); 5072 if (BinOp->getOpcode() == Instruction::Or) 5073 FoundOr = true; 5074 } 5075 // Check if the input is an extended load of the required or/shift expression. 5076 Value *LoadPtr; 5077 if ((MustMatchOrInst && !FoundOr) || ZextLoad == Root || 5078 !match(ZextLoad, m_ZExt(m_Load(m_Value(LoadPtr))))) 5079 return false; 5080 5081 // Require that the total load bit width is a legal integer type. 5082 // For example, <8 x i8> --> i64 is a legal integer on a 64-bit target. 5083 // But <16 x i8> --> i128 is not, so the backend probably can't reduce it. 5084 Type *SrcTy = LoadPtr->getType()->getPointerElementType(); 5085 unsigned LoadBitWidth = SrcTy->getIntegerBitWidth() * NumElts; 5086 if (!TTI->isTypeLegal(IntegerType::get(Root->getContext(), LoadBitWidth))) 5087 return false; 5088 5089 // Everything matched - assume that we can fold the whole sequence using 5090 // load combining. 5091 LLVM_DEBUG(dbgs() << "SLP: Assume load combining for tree starting at " 5092 << *(cast<Instruction>(Root)) << "\n"); 5093 5094 return true; 5095 } 5096 5097 bool BoUpSLP::isLoadCombineReductionCandidate(RecurKind RdxKind) const { 5098 if (RdxKind != RecurKind::Or) 5099 return false; 5100 5101 unsigned NumElts = VectorizableTree[0]->Scalars.size(); 5102 Value *FirstReduced = VectorizableTree[0]->Scalars[0]; 5103 return isLoadCombineCandidateImpl(FirstReduced, NumElts, TTI, 5104 /* MatchOr */ false); 5105 } 5106 5107 bool BoUpSLP::isLoadCombineCandidate() const { 5108 // Peek through a final sequence of stores and check if all operations are 5109 // likely to be load-combined. 5110 unsigned NumElts = VectorizableTree[0]->Scalars.size(); 5111 for (Value *Scalar : VectorizableTree[0]->Scalars) { 5112 Value *X; 5113 if (!match(Scalar, m_Store(m_Value(X), m_Value())) || 5114 !isLoadCombineCandidateImpl(X, NumElts, TTI, /* MatchOr */ true)) 5115 return false; 5116 } 5117 return true; 5118 } 5119 5120 bool BoUpSLP::isTreeTinyAndNotFullyVectorizable(bool ForReduction) const { 5121 // No need to vectorize inserts of gathered values. 5122 if (VectorizableTree.size() == 2 && 5123 isa<InsertElementInst>(VectorizableTree[0]->Scalars[0]) && 5124 VectorizableTree[1]->State == TreeEntry::NeedToGather) 5125 return true; 5126 5127 // We can vectorize the tree if its size is greater than or equal to the 5128 // minimum size specified by the MinTreeSize command line option. 5129 if (VectorizableTree.size() >= MinTreeSize) 5130 return false; 5131 5132 // If we have a tiny tree (a tree whose size is less than MinTreeSize), we 5133 // can vectorize it if we can prove it fully vectorizable. 5134 if (isFullyVectorizableTinyTree(ForReduction)) 5135 return false; 5136 5137 assert(VectorizableTree.empty() 5138 ? ExternalUses.empty() 5139 : true && "We shouldn't have any external users"); 5140 5141 // Otherwise, we can't vectorize the tree. It is both tiny and not fully 5142 // vectorizable. 5143 return true; 5144 } 5145 5146 InstructionCost BoUpSLP::getSpillCost() const { 5147 // Walk from the bottom of the tree to the top, tracking which values are 5148 // live. When we see a call instruction that is not part of our tree, 5149 // query TTI to see if there is a cost to keeping values live over it 5150 // (for example, if spills and fills are required). 5151 unsigned BundleWidth = VectorizableTree.front()->Scalars.size(); 5152 InstructionCost Cost = 0; 5153 5154 SmallPtrSet<Instruction*, 4> LiveValues; 5155 Instruction *PrevInst = nullptr; 5156 5157 // The entries in VectorizableTree are not necessarily ordered by their 5158 // position in basic blocks. Collect them and order them by dominance so later 5159 // instructions are guaranteed to be visited first. For instructions in 5160 // different basic blocks, we only scan to the beginning of the block, so 5161 // their order does not matter, as long as all instructions in a basic block 5162 // are grouped together. Using dominance ensures a deterministic order. 5163 SmallVector<Instruction *, 16> OrderedScalars; 5164 for (const auto &TEPtr : VectorizableTree) { 5165 Instruction *Inst = dyn_cast<Instruction>(TEPtr->Scalars[0]); 5166 if (!Inst) 5167 continue; 5168 OrderedScalars.push_back(Inst); 5169 } 5170 llvm::sort(OrderedScalars, [&](Instruction *A, Instruction *B) { 5171 auto *NodeA = DT->getNode(A->getParent()); 5172 auto *NodeB = DT->getNode(B->getParent()); 5173 assert(NodeA && "Should only process reachable instructions"); 5174 assert(NodeB && "Should only process reachable instructions"); 5175 assert((NodeA == NodeB) == (NodeA->getDFSNumIn() == NodeB->getDFSNumIn()) && 5176 "Different nodes should have different DFS numbers"); 5177 if (NodeA != NodeB) 5178 return NodeA->getDFSNumIn() < NodeB->getDFSNumIn(); 5179 return B->comesBefore(A); 5180 }); 5181 5182 for (Instruction *Inst : OrderedScalars) { 5183 if (!PrevInst) { 5184 PrevInst = Inst; 5185 continue; 5186 } 5187 5188 // Update LiveValues. 5189 LiveValues.erase(PrevInst); 5190 for (auto &J : PrevInst->operands()) { 5191 if (isa<Instruction>(&*J) && getTreeEntry(&*J)) 5192 LiveValues.insert(cast<Instruction>(&*J)); 5193 } 5194 5195 LLVM_DEBUG({ 5196 dbgs() << "SLP: #LV: " << LiveValues.size(); 5197 for (auto *X : LiveValues) 5198 dbgs() << " " << X->getName(); 5199 dbgs() << ", Looking at "; 5200 Inst->dump(); 5201 }); 5202 5203 // Now find the sequence of instructions between PrevInst and Inst. 5204 unsigned NumCalls = 0; 5205 BasicBlock::reverse_iterator InstIt = ++Inst->getIterator().getReverse(), 5206 PrevInstIt = 5207 PrevInst->getIterator().getReverse(); 5208 while (InstIt != PrevInstIt) { 5209 if (PrevInstIt == PrevInst->getParent()->rend()) { 5210 PrevInstIt = Inst->getParent()->rbegin(); 5211 continue; 5212 } 5213 5214 // Debug information does not impact spill cost. 5215 if ((isa<CallInst>(&*PrevInstIt) && 5216 !isa<DbgInfoIntrinsic>(&*PrevInstIt)) && 5217 &*PrevInstIt != PrevInst) 5218 NumCalls++; 5219 5220 ++PrevInstIt; 5221 } 5222 5223 if (NumCalls) { 5224 SmallVector<Type*, 4> V; 5225 for (auto *II : LiveValues) { 5226 auto *ScalarTy = II->getType(); 5227 if (auto *VectorTy = dyn_cast<FixedVectorType>(ScalarTy)) 5228 ScalarTy = VectorTy->getElementType(); 5229 V.push_back(FixedVectorType::get(ScalarTy, BundleWidth)); 5230 } 5231 Cost += NumCalls * TTI->getCostOfKeepingLiveOverCall(V); 5232 } 5233 5234 PrevInst = Inst; 5235 } 5236 5237 return Cost; 5238 } 5239 5240 InstructionCost BoUpSLP::getTreeCost(ArrayRef<Value *> VectorizedVals) { 5241 InstructionCost Cost = 0; 5242 LLVM_DEBUG(dbgs() << "SLP: Calculating cost for tree of size " 5243 << VectorizableTree.size() << ".\n"); 5244 5245 unsigned BundleWidth = VectorizableTree[0]->Scalars.size(); 5246 5247 for (unsigned I = 0, E = VectorizableTree.size(); I < E; ++I) { 5248 TreeEntry &TE = *VectorizableTree[I].get(); 5249 5250 InstructionCost C = getEntryCost(&TE, VectorizedVals); 5251 Cost += C; 5252 LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C 5253 << " for bundle that starts with " << *TE.Scalars[0] 5254 << ".\n" 5255 << "SLP: Current total cost = " << Cost << "\n"); 5256 } 5257 5258 SmallPtrSet<Value *, 16> ExtractCostCalculated; 5259 InstructionCost ExtractCost = 0; 5260 SmallVector<unsigned> VF; 5261 SmallVector<SmallVector<int>> ShuffleMask; 5262 SmallVector<Value *> FirstUsers; 5263 SmallVector<APInt> DemandedElts; 5264 for (ExternalUser &EU : ExternalUses) { 5265 // We only add extract cost once for the same scalar. 5266 if (!ExtractCostCalculated.insert(EU.Scalar).second) 5267 continue; 5268 5269 // Uses by ephemeral values are free (because the ephemeral value will be 5270 // removed prior to code generation, and so the extraction will be 5271 // removed as well). 5272 if (EphValues.count(EU.User)) 5273 continue; 5274 5275 // No extract cost for vector "scalar" 5276 if (isa<FixedVectorType>(EU.Scalar->getType())) 5277 continue; 5278 5279 // Already counted the cost for external uses when tried to adjust the cost 5280 // for extractelements, no need to add it again. 5281 if (isa<ExtractElementInst>(EU.Scalar)) 5282 continue; 5283 5284 // If found user is an insertelement, do not calculate extract cost but try 5285 // to detect it as a final shuffled/identity match. 5286 if (EU.User && isa<InsertElementInst>(EU.User)) { 5287 if (auto *FTy = dyn_cast<FixedVectorType>(EU.User->getType())) { 5288 Optional<int> InsertIdx = getInsertIndex(EU.User, 0); 5289 if (!InsertIdx || *InsertIdx == UndefMaskElem) 5290 continue; 5291 Value *VU = EU.User; 5292 auto *It = find_if(FirstUsers, [VU](Value *V) { 5293 // Checks if 2 insertelements are from the same buildvector. 5294 if (VU->getType() != V->getType()) 5295 return false; 5296 auto *IE1 = cast<InsertElementInst>(VU); 5297 auto *IE2 = cast<InsertElementInst>(V); 5298 // Go though of insertelement instructions trying to find either VU as 5299 // the original vector for IE2 or V as the original vector for IE1. 5300 do { 5301 if (IE1 == VU || IE2 == V) 5302 return true; 5303 if (IE1) 5304 IE1 = dyn_cast<InsertElementInst>(IE1->getOperand(0)); 5305 if (IE2) 5306 IE2 = dyn_cast<InsertElementInst>(IE2->getOperand(0)); 5307 } while (IE1 || IE2); 5308 return false; 5309 }); 5310 int VecId = -1; 5311 if (It == FirstUsers.end()) { 5312 VF.push_back(FTy->getNumElements()); 5313 ShuffleMask.emplace_back(VF.back(), UndefMaskElem); 5314 FirstUsers.push_back(EU.User); 5315 DemandedElts.push_back(APInt::getZero(VF.back())); 5316 VecId = FirstUsers.size() - 1; 5317 } else { 5318 VecId = std::distance(FirstUsers.begin(), It); 5319 } 5320 int Idx = *InsertIdx; 5321 ShuffleMask[VecId][Idx] = EU.Lane; 5322 DemandedElts[VecId].setBit(Idx); 5323 } 5324 } 5325 5326 // If we plan to rewrite the tree in a smaller type, we will need to sign 5327 // extend the extracted value back to the original type. Here, we account 5328 // for the extract and the added cost of the sign extend if needed. 5329 auto *VecTy = FixedVectorType::get(EU.Scalar->getType(), BundleWidth); 5330 auto *ScalarRoot = VectorizableTree[0]->Scalars[0]; 5331 if (MinBWs.count(ScalarRoot)) { 5332 auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first); 5333 auto Extend = 5334 MinBWs[ScalarRoot].second ? Instruction::SExt : Instruction::ZExt; 5335 VecTy = FixedVectorType::get(MinTy, BundleWidth); 5336 ExtractCost += TTI->getExtractWithExtendCost(Extend, EU.Scalar->getType(), 5337 VecTy, EU.Lane); 5338 } else { 5339 ExtractCost += 5340 TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, EU.Lane); 5341 } 5342 } 5343 5344 InstructionCost SpillCost = getSpillCost(); 5345 Cost += SpillCost + ExtractCost; 5346 for (int I = 0, E = FirstUsers.size(); I < E; ++I) { 5347 // For the very first element - simple shuffle of the source vector. 5348 int Limit = ShuffleMask[I].size() * 2; 5349 if (I == 0 && 5350 all_of(ShuffleMask[I], [Limit](int Idx) { return Idx < Limit; }) && 5351 !ShuffleVectorInst::isIdentityMask(ShuffleMask[I])) { 5352 InstructionCost C = TTI->getShuffleCost( 5353 TTI::SK_PermuteSingleSrc, 5354 cast<FixedVectorType>(FirstUsers[I]->getType()), ShuffleMask[I]); 5355 LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C 5356 << " for final shuffle of insertelement external users " 5357 << *VectorizableTree.front()->Scalars.front() << ".\n" 5358 << "SLP: Current total cost = " << Cost << "\n"); 5359 Cost += C; 5360 continue; 5361 } 5362 // Other elements - permutation of 2 vectors (the initial one and the next 5363 // Ith incoming vector). 5364 unsigned VF = ShuffleMask[I].size(); 5365 for (unsigned Idx = 0; Idx < VF; ++Idx) { 5366 int &Mask = ShuffleMask[I][Idx]; 5367 Mask = Mask == UndefMaskElem ? Idx : VF + Mask; 5368 } 5369 InstructionCost C = TTI->getShuffleCost( 5370 TTI::SK_PermuteTwoSrc, cast<FixedVectorType>(FirstUsers[I]->getType()), 5371 ShuffleMask[I]); 5372 LLVM_DEBUG( 5373 dbgs() 5374 << "SLP: Adding cost " << C 5375 << " for final shuffle of vector node and external insertelement users " 5376 << *VectorizableTree.front()->Scalars.front() << ".\n" 5377 << "SLP: Current total cost = " << Cost << "\n"); 5378 Cost += C; 5379 InstructionCost InsertCost = TTI->getScalarizationOverhead( 5380 cast<FixedVectorType>(FirstUsers[I]->getType()), DemandedElts[I], 5381 /*Insert*/ true, 5382 /*Extract*/ false); 5383 Cost -= InsertCost; 5384 LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost 5385 << " for insertelements gather.\n" 5386 << "SLP: Current total cost = " << Cost << "\n"); 5387 } 5388 5389 #ifndef NDEBUG 5390 SmallString<256> Str; 5391 { 5392 raw_svector_ostream OS(Str); 5393 OS << "SLP: Spill Cost = " << SpillCost << ".\n" 5394 << "SLP: Extract Cost = " << ExtractCost << ".\n" 5395 << "SLP: Total Cost = " << Cost << ".\n"; 5396 } 5397 LLVM_DEBUG(dbgs() << Str); 5398 if (ViewSLPTree) 5399 ViewGraph(this, "SLP" + F->getName(), false, Str); 5400 #endif 5401 5402 return Cost; 5403 } 5404 5405 Optional<TargetTransformInfo::ShuffleKind> 5406 BoUpSLP::isGatherShuffledEntry(const TreeEntry *TE, SmallVectorImpl<int> &Mask, 5407 SmallVectorImpl<const TreeEntry *> &Entries) { 5408 // TODO: currently checking only for Scalars in the tree entry, need to count 5409 // reused elements too for better cost estimation. 5410 Mask.assign(TE->Scalars.size(), UndefMaskElem); 5411 Entries.clear(); 5412 // Build a lists of values to tree entries. 5413 DenseMap<Value *, SmallPtrSet<const TreeEntry *, 4>> ValueToTEs; 5414 for (const std::unique_ptr<TreeEntry> &EntryPtr : VectorizableTree) { 5415 if (EntryPtr.get() == TE) 5416 break; 5417 if (EntryPtr->State != TreeEntry::NeedToGather) 5418 continue; 5419 for (Value *V : EntryPtr->Scalars) 5420 ValueToTEs.try_emplace(V).first->getSecond().insert(EntryPtr.get()); 5421 } 5422 // Find all tree entries used by the gathered values. If no common entries 5423 // found - not a shuffle. 5424 // Here we build a set of tree nodes for each gathered value and trying to 5425 // find the intersection between these sets. If we have at least one common 5426 // tree node for each gathered value - we have just a permutation of the 5427 // single vector. If we have 2 different sets, we're in situation where we 5428 // have a permutation of 2 input vectors. 5429 SmallVector<SmallPtrSet<const TreeEntry *, 4>> UsedTEs; 5430 DenseMap<Value *, int> UsedValuesEntry; 5431 for (Value *V : TE->Scalars) { 5432 if (isa<UndefValue>(V)) 5433 continue; 5434 // Build a list of tree entries where V is used. 5435 SmallPtrSet<const TreeEntry *, 4> VToTEs; 5436 auto It = ValueToTEs.find(V); 5437 if (It != ValueToTEs.end()) 5438 VToTEs = It->second; 5439 if (const TreeEntry *VTE = getTreeEntry(V)) 5440 VToTEs.insert(VTE); 5441 if (VToTEs.empty()) 5442 return None; 5443 if (UsedTEs.empty()) { 5444 // The first iteration, just insert the list of nodes to vector. 5445 UsedTEs.push_back(VToTEs); 5446 } else { 5447 // Need to check if there are any previously used tree nodes which use V. 5448 // If there are no such nodes, consider that we have another one input 5449 // vector. 5450 SmallPtrSet<const TreeEntry *, 4> SavedVToTEs(VToTEs); 5451 unsigned Idx = 0; 5452 for (SmallPtrSet<const TreeEntry *, 4> &Set : UsedTEs) { 5453 // Do we have a non-empty intersection of previously listed tree entries 5454 // and tree entries using current V? 5455 set_intersect(VToTEs, Set); 5456 if (!VToTEs.empty()) { 5457 // Yes, write the new subset and continue analysis for the next 5458 // scalar. 5459 Set.swap(VToTEs); 5460 break; 5461 } 5462 VToTEs = SavedVToTEs; 5463 ++Idx; 5464 } 5465 // No non-empty intersection found - need to add a second set of possible 5466 // source vectors. 5467 if (Idx == UsedTEs.size()) { 5468 // If the number of input vectors is greater than 2 - not a permutation, 5469 // fallback to the regular gather. 5470 if (UsedTEs.size() == 2) 5471 return None; 5472 UsedTEs.push_back(SavedVToTEs); 5473 Idx = UsedTEs.size() - 1; 5474 } 5475 UsedValuesEntry.try_emplace(V, Idx); 5476 } 5477 } 5478 5479 unsigned VF = 0; 5480 if (UsedTEs.size() == 1) { 5481 // Try to find the perfect match in another gather node at first. 5482 auto It = find_if(UsedTEs.front(), [TE](const TreeEntry *EntryPtr) { 5483 return EntryPtr->isSame(TE->Scalars); 5484 }); 5485 if (It != UsedTEs.front().end()) { 5486 Entries.push_back(*It); 5487 std::iota(Mask.begin(), Mask.end(), 0); 5488 return TargetTransformInfo::SK_PermuteSingleSrc; 5489 } 5490 // No perfect match, just shuffle, so choose the first tree node. 5491 Entries.push_back(*UsedTEs.front().begin()); 5492 } else { 5493 // Try to find nodes with the same vector factor. 5494 assert(UsedTEs.size() == 2 && "Expected at max 2 permuted entries."); 5495 // FIXME: Shall be replaced by GetVF function once non-power-2 patch is 5496 // landed. 5497 auto &&GetVF = [](const TreeEntry *TE) { 5498 if (!TE->ReuseShuffleIndices.empty()) 5499 return TE->ReuseShuffleIndices.size(); 5500 return TE->Scalars.size(); 5501 }; 5502 DenseMap<int, const TreeEntry *> VFToTE; 5503 for (const TreeEntry *TE : UsedTEs.front()) 5504 VFToTE.try_emplace(GetVF(TE), TE); 5505 for (const TreeEntry *TE : UsedTEs.back()) { 5506 auto It = VFToTE.find(GetVF(TE)); 5507 if (It != VFToTE.end()) { 5508 VF = It->first; 5509 Entries.push_back(It->second); 5510 Entries.push_back(TE); 5511 break; 5512 } 5513 } 5514 // No 2 source vectors with the same vector factor - give up and do regular 5515 // gather. 5516 if (Entries.empty()) 5517 return None; 5518 } 5519 5520 // Build a shuffle mask for better cost estimation and vector emission. 5521 for (int I = 0, E = TE->Scalars.size(); I < E; ++I) { 5522 Value *V = TE->Scalars[I]; 5523 if (isa<UndefValue>(V)) 5524 continue; 5525 unsigned Idx = UsedValuesEntry.lookup(V); 5526 const TreeEntry *VTE = Entries[Idx]; 5527 int FoundLane = VTE->findLaneForValue(V); 5528 Mask[I] = Idx * VF + FoundLane; 5529 // Extra check required by isSingleSourceMaskImpl function (called by 5530 // ShuffleVectorInst::isSingleSourceMask). 5531 if (Mask[I] >= 2 * E) 5532 return None; 5533 } 5534 switch (Entries.size()) { 5535 case 1: 5536 return TargetTransformInfo::SK_PermuteSingleSrc; 5537 case 2: 5538 return TargetTransformInfo::SK_PermuteTwoSrc; 5539 default: 5540 break; 5541 } 5542 return None; 5543 } 5544 5545 InstructionCost 5546 BoUpSLP::getGatherCost(FixedVectorType *Ty, 5547 const DenseSet<unsigned> &ShuffledIndices) const { 5548 unsigned NumElts = Ty->getNumElements(); 5549 APInt DemandedElts = APInt::getZero(NumElts); 5550 for (unsigned I = 0; I < NumElts; ++I) 5551 if (!ShuffledIndices.count(I)) 5552 DemandedElts.setBit(I); 5553 InstructionCost Cost = 5554 TTI->getScalarizationOverhead(Ty, DemandedElts, /*Insert*/ true, 5555 /*Extract*/ false); 5556 if (!ShuffledIndices.empty()) 5557 Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, Ty); 5558 return Cost; 5559 } 5560 5561 InstructionCost BoUpSLP::getGatherCost(ArrayRef<Value *> VL) const { 5562 // Find the type of the operands in VL. 5563 Type *ScalarTy = VL[0]->getType(); 5564 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0])) 5565 ScalarTy = SI->getValueOperand()->getType(); 5566 auto *VecTy = FixedVectorType::get(ScalarTy, VL.size()); 5567 // Find the cost of inserting/extracting values from the vector. 5568 // Check if the same elements are inserted several times and count them as 5569 // shuffle candidates. 5570 DenseSet<unsigned> ShuffledElements; 5571 DenseSet<Value *> UniqueElements; 5572 // Iterate in reverse order to consider insert elements with the high cost. 5573 for (unsigned I = VL.size(); I > 0; --I) { 5574 unsigned Idx = I - 1; 5575 if (isConstant(VL[Idx])) 5576 continue; 5577 if (!UniqueElements.insert(VL[Idx]).second) 5578 ShuffledElements.insert(Idx); 5579 } 5580 return getGatherCost(VecTy, ShuffledElements); 5581 } 5582 5583 // Perform operand reordering on the instructions in VL and return the reordered 5584 // operands in Left and Right. 5585 void BoUpSLP::reorderInputsAccordingToOpcode(ArrayRef<Value *> VL, 5586 SmallVectorImpl<Value *> &Left, 5587 SmallVectorImpl<Value *> &Right, 5588 const DataLayout &DL, 5589 ScalarEvolution &SE, 5590 const BoUpSLP &R) { 5591 if (VL.empty()) 5592 return; 5593 VLOperands Ops(VL, DL, SE, R); 5594 // Reorder the operands in place. 5595 Ops.reorder(); 5596 Left = Ops.getVL(0); 5597 Right = Ops.getVL(1); 5598 } 5599 5600 void BoUpSLP::setInsertPointAfterBundle(const TreeEntry *E) { 5601 // Get the basic block this bundle is in. All instructions in the bundle 5602 // should be in this block. 5603 auto *Front = E->getMainOp(); 5604 auto *BB = Front->getParent(); 5605 assert(llvm::all_of(E->Scalars, [=](Value *V) -> bool { 5606 auto *I = cast<Instruction>(V); 5607 return !E->isOpcodeOrAlt(I) || I->getParent() == BB; 5608 })); 5609 5610 // The last instruction in the bundle in program order. 5611 Instruction *LastInst = nullptr; 5612 5613 // Find the last instruction. The common case should be that BB has been 5614 // scheduled, and the last instruction is VL.back(). So we start with 5615 // VL.back() and iterate over schedule data until we reach the end of the 5616 // bundle. The end of the bundle is marked by null ScheduleData. 5617 if (BlocksSchedules.count(BB)) { 5618 auto *Bundle = 5619 BlocksSchedules[BB]->getScheduleData(E->isOneOf(E->Scalars.back())); 5620 if (Bundle && Bundle->isPartOfBundle()) 5621 for (; Bundle; Bundle = Bundle->NextInBundle) 5622 if (Bundle->OpValue == Bundle->Inst) 5623 LastInst = Bundle->Inst; 5624 } 5625 5626 // LastInst can still be null at this point if there's either not an entry 5627 // for BB in BlocksSchedules or there's no ScheduleData available for 5628 // VL.back(). This can be the case if buildTree_rec aborts for various 5629 // reasons (e.g., the maximum recursion depth is reached, the maximum region 5630 // size is reached, etc.). ScheduleData is initialized in the scheduling 5631 // "dry-run". 5632 // 5633 // If this happens, we can still find the last instruction by brute force. We 5634 // iterate forwards from Front (inclusive) until we either see all 5635 // instructions in the bundle or reach the end of the block. If Front is the 5636 // last instruction in program order, LastInst will be set to Front, and we 5637 // will visit all the remaining instructions in the block. 5638 // 5639 // One of the reasons we exit early from buildTree_rec is to place an upper 5640 // bound on compile-time. Thus, taking an additional compile-time hit here is 5641 // not ideal. However, this should be exceedingly rare since it requires that 5642 // we both exit early from buildTree_rec and that the bundle be out-of-order 5643 // (causing us to iterate all the way to the end of the block). 5644 if (!LastInst) { 5645 SmallPtrSet<Value *, 16> Bundle(E->Scalars.begin(), E->Scalars.end()); 5646 for (auto &I : make_range(BasicBlock::iterator(Front), BB->end())) { 5647 if (Bundle.erase(&I) && E->isOpcodeOrAlt(&I)) 5648 LastInst = &I; 5649 if (Bundle.empty()) 5650 break; 5651 } 5652 } 5653 assert(LastInst && "Failed to find last instruction in bundle"); 5654 5655 // Set the insertion point after the last instruction in the bundle. Set the 5656 // debug location to Front. 5657 Builder.SetInsertPoint(BB, ++LastInst->getIterator()); 5658 Builder.SetCurrentDebugLocation(Front->getDebugLoc()); 5659 } 5660 5661 Value *BoUpSLP::gather(ArrayRef<Value *> VL) { 5662 // List of instructions/lanes from current block and/or the blocks which are 5663 // part of the current loop. These instructions will be inserted at the end to 5664 // make it possible to optimize loops and hoist invariant instructions out of 5665 // the loops body with better chances for success. 5666 SmallVector<std::pair<Value *, unsigned>, 4> PostponedInsts; 5667 SmallSet<int, 4> PostponedIndices; 5668 Loop *L = LI->getLoopFor(Builder.GetInsertBlock()); 5669 auto &&CheckPredecessor = [](BasicBlock *InstBB, BasicBlock *InsertBB) { 5670 SmallPtrSet<BasicBlock *, 4> Visited; 5671 while (InsertBB && InsertBB != InstBB && Visited.insert(InsertBB).second) 5672 InsertBB = InsertBB->getSinglePredecessor(); 5673 return InsertBB && InsertBB == InstBB; 5674 }; 5675 for (int I = 0, E = VL.size(); I < E; ++I) { 5676 if (auto *Inst = dyn_cast<Instruction>(VL[I])) 5677 if ((CheckPredecessor(Inst->getParent(), Builder.GetInsertBlock()) || 5678 getTreeEntry(Inst) || (L && (L->contains(Inst)))) && 5679 PostponedIndices.insert(I).second) 5680 PostponedInsts.emplace_back(Inst, I); 5681 } 5682 5683 auto &&CreateInsertElement = [this](Value *Vec, Value *V, unsigned Pos) { 5684 Vec = Builder.CreateInsertElement(Vec, V, Builder.getInt32(Pos)); 5685 auto *InsElt = dyn_cast<InsertElementInst>(Vec); 5686 if (!InsElt) 5687 return Vec; 5688 GatherSeq.insert(InsElt); 5689 CSEBlocks.insert(InsElt->getParent()); 5690 // Add to our 'need-to-extract' list. 5691 if (TreeEntry *Entry = getTreeEntry(V)) { 5692 // Find which lane we need to extract. 5693 unsigned FoundLane = Entry->findLaneForValue(V); 5694 ExternalUses.emplace_back(V, InsElt, FoundLane); 5695 } 5696 return Vec; 5697 }; 5698 Value *Val0 = 5699 isa<StoreInst>(VL[0]) ? cast<StoreInst>(VL[0])->getValueOperand() : VL[0]; 5700 FixedVectorType *VecTy = FixedVectorType::get(Val0->getType(), VL.size()); 5701 Value *Vec = PoisonValue::get(VecTy); 5702 SmallVector<int> NonConsts; 5703 // Insert constant values at first. 5704 for (int I = 0, E = VL.size(); I < E; ++I) { 5705 if (PostponedIndices.contains(I)) 5706 continue; 5707 if (!isConstant(VL[I])) { 5708 NonConsts.push_back(I); 5709 continue; 5710 } 5711 Vec = CreateInsertElement(Vec, VL[I], I); 5712 } 5713 // Insert non-constant values. 5714 for (int I : NonConsts) 5715 Vec = CreateInsertElement(Vec, VL[I], I); 5716 // Append instructions, which are/may be part of the loop, in the end to make 5717 // it possible to hoist non-loop-based instructions. 5718 for (const std::pair<Value *, unsigned> &Pair : PostponedInsts) 5719 Vec = CreateInsertElement(Vec, Pair.first, Pair.second); 5720 5721 return Vec; 5722 } 5723 5724 namespace { 5725 /// Merges shuffle masks and emits final shuffle instruction, if required. 5726 class ShuffleInstructionBuilder { 5727 IRBuilderBase &Builder; 5728 const unsigned VF = 0; 5729 bool IsFinalized = false; 5730 SmallVector<int, 4> Mask; 5731 5732 public: 5733 ShuffleInstructionBuilder(IRBuilderBase &Builder, unsigned VF) 5734 : Builder(Builder), VF(VF) {} 5735 5736 /// Adds a mask, inverting it before applying. 5737 void addInversedMask(ArrayRef<unsigned> SubMask) { 5738 if (SubMask.empty()) 5739 return; 5740 SmallVector<int, 4> NewMask; 5741 inversePermutation(SubMask, NewMask); 5742 addMask(NewMask); 5743 } 5744 5745 /// Functions adds masks, merging them into single one. 5746 void addMask(ArrayRef<unsigned> SubMask) { 5747 SmallVector<int, 4> NewMask(SubMask.begin(), SubMask.end()); 5748 addMask(NewMask); 5749 } 5750 5751 void addMask(ArrayRef<int> SubMask) { ::addMask(Mask, SubMask); } 5752 5753 Value *finalize(Value *V) { 5754 IsFinalized = true; 5755 unsigned ValueVF = cast<FixedVectorType>(V->getType())->getNumElements(); 5756 if (VF == ValueVF && Mask.empty()) 5757 return V; 5758 SmallVector<int, 4> NormalizedMask(VF, UndefMaskElem); 5759 std::iota(NormalizedMask.begin(), NormalizedMask.end(), 0); 5760 addMask(NormalizedMask); 5761 5762 if (VF == ValueVF && ShuffleVectorInst::isIdentityMask(Mask)) 5763 return V; 5764 return Builder.CreateShuffleVector(V, Mask, "shuffle"); 5765 } 5766 5767 ~ShuffleInstructionBuilder() { 5768 assert((IsFinalized || Mask.empty()) && 5769 "Shuffle construction must be finalized."); 5770 } 5771 }; 5772 } // namespace 5773 5774 Value *BoUpSLP::vectorizeTree(ArrayRef<Value *> VL) { 5775 unsigned VF = VL.size(); 5776 InstructionsState S = getSameOpcode(VL); 5777 if (S.getOpcode()) { 5778 if (TreeEntry *E = getTreeEntry(S.OpValue)) 5779 if (E->isSame(VL)) { 5780 Value *V = vectorizeTree(E); 5781 if (VF != cast<FixedVectorType>(V->getType())->getNumElements()) { 5782 if (!E->ReuseShuffleIndices.empty()) { 5783 // Reshuffle to get only unique values. 5784 // If some of the scalars are duplicated in the vectorization tree 5785 // entry, we do not vectorize them but instead generate a mask for 5786 // the reuses. But if there are several users of the same entry, 5787 // they may have different vectorization factors. This is especially 5788 // important for PHI nodes. In this case, we need to adapt the 5789 // resulting instruction for the user vectorization factor and have 5790 // to reshuffle it again to take only unique elements of the vector. 5791 // Without this code the function incorrectly returns reduced vector 5792 // instruction with the same elements, not with the unique ones. 5793 5794 // block: 5795 // %phi = phi <2 x > { .., %entry} {%shuffle, %block} 5796 // %2 = shuffle <2 x > %phi, poison, <4 x > <1, 1, 0, 0> 5797 // ... (use %2) 5798 // %shuffle = shuffle <2 x> %2, poison, <2 x> {2, 0} 5799 // br %block 5800 SmallVector<int> UniqueIdxs(VF, UndefMaskElem); 5801 SmallSet<int, 4> UsedIdxs; 5802 int Pos = 0; 5803 int Sz = VL.size(); 5804 for (int Idx : E->ReuseShuffleIndices) { 5805 if (Idx != Sz && Idx != UndefMaskElem && 5806 UsedIdxs.insert(Idx).second) 5807 UniqueIdxs[Idx] = Pos; 5808 ++Pos; 5809 } 5810 assert(VF >= UsedIdxs.size() && "Expected vectorization factor " 5811 "less than original vector size."); 5812 UniqueIdxs.append(VF - UsedIdxs.size(), UndefMaskElem); 5813 V = Builder.CreateShuffleVector(V, UniqueIdxs, "shrink.shuffle"); 5814 } else { 5815 assert(VF < cast<FixedVectorType>(V->getType())->getNumElements() && 5816 "Expected vectorization factor less " 5817 "than original vector size."); 5818 SmallVector<int> UniformMask(VF, 0); 5819 std::iota(UniformMask.begin(), UniformMask.end(), 0); 5820 V = Builder.CreateShuffleVector(V, UniformMask, "shrink.shuffle"); 5821 } 5822 } 5823 return V; 5824 } 5825 } 5826 5827 // Check that every instruction appears once in this bundle. 5828 SmallVector<int> ReuseShuffleIndicies; 5829 SmallVector<Value *> UniqueValues; 5830 if (VL.size() > 2) { 5831 DenseMap<Value *, unsigned> UniquePositions; 5832 unsigned NumValues = 5833 std::distance(VL.begin(), find_if(reverse(VL), [](Value *V) { 5834 return !isa<UndefValue>(V); 5835 }).base()); 5836 VF = std::max<unsigned>(VF, PowerOf2Ceil(NumValues)); 5837 int UniqueVals = 0; 5838 for (Value *V : VL.drop_back(VL.size() - VF)) { 5839 if (isa<UndefValue>(V)) { 5840 ReuseShuffleIndicies.emplace_back(UndefMaskElem); 5841 continue; 5842 } 5843 if (isConstant(V)) { 5844 ReuseShuffleIndicies.emplace_back(UniqueValues.size()); 5845 UniqueValues.emplace_back(V); 5846 continue; 5847 } 5848 auto Res = UniquePositions.try_emplace(V, UniqueValues.size()); 5849 ReuseShuffleIndicies.emplace_back(Res.first->second); 5850 if (Res.second) { 5851 UniqueValues.emplace_back(V); 5852 ++UniqueVals; 5853 } 5854 } 5855 if (UniqueVals == 1 && UniqueValues.size() == 1) { 5856 // Emit pure splat vector. 5857 ReuseShuffleIndicies.append(VF - ReuseShuffleIndicies.size(), 5858 UndefMaskElem); 5859 } else if (UniqueValues.size() >= VF - 1 || UniqueValues.size() <= 1) { 5860 ReuseShuffleIndicies.clear(); 5861 UniqueValues.clear(); 5862 UniqueValues.append(VL.begin(), std::next(VL.begin(), NumValues)); 5863 } 5864 UniqueValues.append(VF - UniqueValues.size(), 5865 PoisonValue::get(VL[0]->getType())); 5866 VL = UniqueValues; 5867 } 5868 5869 ShuffleInstructionBuilder ShuffleBuilder(Builder, VF); 5870 Value *Vec = gather(VL); 5871 if (!ReuseShuffleIndicies.empty()) { 5872 ShuffleBuilder.addMask(ReuseShuffleIndicies); 5873 Vec = ShuffleBuilder.finalize(Vec); 5874 if (auto *I = dyn_cast<Instruction>(Vec)) { 5875 GatherSeq.insert(I); 5876 CSEBlocks.insert(I->getParent()); 5877 } 5878 } 5879 return Vec; 5880 } 5881 5882 Value *BoUpSLP::vectorizeTree(TreeEntry *E) { 5883 IRBuilder<>::InsertPointGuard Guard(Builder); 5884 5885 if (E->VectorizedValue) { 5886 LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n"); 5887 return E->VectorizedValue; 5888 } 5889 5890 bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty(); 5891 unsigned VF = E->Scalars.size(); 5892 if (NeedToShuffleReuses) 5893 VF = E->ReuseShuffleIndices.size(); 5894 ShuffleInstructionBuilder ShuffleBuilder(Builder, VF); 5895 if (E->State == TreeEntry::NeedToGather) { 5896 if (E->getMainOp()) 5897 setInsertPointAfterBundle(E); 5898 Value *Vec; 5899 SmallVector<int> Mask; 5900 SmallVector<const TreeEntry *> Entries; 5901 Optional<TargetTransformInfo::ShuffleKind> Shuffle = 5902 isGatherShuffledEntry(E, Mask, Entries); 5903 if (Shuffle.hasValue()) { 5904 assert((Entries.size() == 1 || Entries.size() == 2) && 5905 "Expected shuffle of 1 or 2 entries."); 5906 Vec = Builder.CreateShuffleVector(Entries.front()->VectorizedValue, 5907 Entries.back()->VectorizedValue, Mask); 5908 } else { 5909 Vec = gather(E->Scalars); 5910 } 5911 if (NeedToShuffleReuses) { 5912 ShuffleBuilder.addMask(E->ReuseShuffleIndices); 5913 Vec = ShuffleBuilder.finalize(Vec); 5914 if (auto *I = dyn_cast<Instruction>(Vec)) { 5915 GatherSeq.insert(I); 5916 CSEBlocks.insert(I->getParent()); 5917 } 5918 } 5919 E->VectorizedValue = Vec; 5920 return Vec; 5921 } 5922 5923 assert((E->State == TreeEntry::Vectorize || 5924 E->State == TreeEntry::ScatterVectorize) && 5925 "Unhandled state"); 5926 unsigned ShuffleOrOp = 5927 E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode(); 5928 Instruction *VL0 = E->getMainOp(); 5929 Type *ScalarTy = VL0->getType(); 5930 if (auto *Store = dyn_cast<StoreInst>(VL0)) 5931 ScalarTy = Store->getValueOperand()->getType(); 5932 else if (auto *IE = dyn_cast<InsertElementInst>(VL0)) 5933 ScalarTy = IE->getOperand(1)->getType(); 5934 auto *VecTy = FixedVectorType::get(ScalarTy, E->Scalars.size()); 5935 switch (ShuffleOrOp) { 5936 case Instruction::PHI: { 5937 assert( 5938 (E->ReorderIndices.empty() || E != VectorizableTree.front().get()) && 5939 "PHI reordering is free."); 5940 auto *PH = cast<PHINode>(VL0); 5941 Builder.SetInsertPoint(PH->getParent()->getFirstNonPHI()); 5942 Builder.SetCurrentDebugLocation(PH->getDebugLoc()); 5943 PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues()); 5944 Value *V = NewPhi; 5945 ShuffleBuilder.addInversedMask(E->ReorderIndices); 5946 ShuffleBuilder.addMask(E->ReuseShuffleIndices); 5947 V = ShuffleBuilder.finalize(V); 5948 5949 E->VectorizedValue = V; 5950 5951 // PHINodes may have multiple entries from the same block. We want to 5952 // visit every block once. 5953 SmallPtrSet<BasicBlock*, 4> VisitedBBs; 5954 5955 for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) { 5956 ValueList Operands; 5957 BasicBlock *IBB = PH->getIncomingBlock(i); 5958 5959 if (!VisitedBBs.insert(IBB).second) { 5960 NewPhi->addIncoming(NewPhi->getIncomingValueForBlock(IBB), IBB); 5961 continue; 5962 } 5963 5964 Builder.SetInsertPoint(IBB->getTerminator()); 5965 Builder.SetCurrentDebugLocation(PH->getDebugLoc()); 5966 Value *Vec = vectorizeTree(E->getOperand(i)); 5967 NewPhi->addIncoming(Vec, IBB); 5968 } 5969 5970 assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() && 5971 "Invalid number of incoming values"); 5972 return V; 5973 } 5974 5975 case Instruction::ExtractElement: { 5976 Value *V = E->getSingleOperand(0); 5977 Builder.SetInsertPoint(VL0); 5978 ShuffleBuilder.addInversedMask(E->ReorderIndices); 5979 ShuffleBuilder.addMask(E->ReuseShuffleIndices); 5980 V = ShuffleBuilder.finalize(V); 5981 E->VectorizedValue = V; 5982 return V; 5983 } 5984 case Instruction::ExtractValue: { 5985 auto *LI = cast<LoadInst>(E->getSingleOperand(0)); 5986 Builder.SetInsertPoint(LI); 5987 auto *PtrTy = PointerType::get(VecTy, LI->getPointerAddressSpace()); 5988 Value *Ptr = Builder.CreateBitCast(LI->getOperand(0), PtrTy); 5989 LoadInst *V = Builder.CreateAlignedLoad(VecTy, Ptr, LI->getAlign()); 5990 Value *NewV = propagateMetadata(V, E->Scalars); 5991 ShuffleBuilder.addInversedMask(E->ReorderIndices); 5992 ShuffleBuilder.addMask(E->ReuseShuffleIndices); 5993 NewV = ShuffleBuilder.finalize(NewV); 5994 E->VectorizedValue = NewV; 5995 return NewV; 5996 } 5997 case Instruction::InsertElement: { 5998 assert(E->ReuseShuffleIndices.empty() && "All inserts should be unique"); 5999 Builder.SetInsertPoint(cast<Instruction>(E->Scalars.back())); 6000 Value *V = vectorizeTree(E->getOperand(1)); 6001 6002 // Create InsertVector shuffle if necessary 6003 auto *FirstInsert = cast<Instruction>(*find_if(E->Scalars, [E](Value *V) { 6004 return !is_contained(E->Scalars, cast<Instruction>(V)->getOperand(0)); 6005 })); 6006 const unsigned NumElts = 6007 cast<FixedVectorType>(FirstInsert->getType())->getNumElements(); 6008 const unsigned NumScalars = E->Scalars.size(); 6009 6010 unsigned Offset = *getInsertIndex(VL0, 0); 6011 assert(Offset < NumElts && "Failed to find vector index offset"); 6012 6013 // Create shuffle to resize vector 6014 SmallVector<int> Mask; 6015 if (!E->ReorderIndices.empty()) { 6016 inversePermutation(E->ReorderIndices, Mask); 6017 Mask.append(NumElts - NumScalars, UndefMaskElem); 6018 } else { 6019 Mask.assign(NumElts, UndefMaskElem); 6020 std::iota(Mask.begin(), std::next(Mask.begin(), NumScalars), 0); 6021 } 6022 // Create InsertVector shuffle if necessary 6023 bool IsIdentity = true; 6024 SmallVector<int> PrevMask(NumElts, UndefMaskElem); 6025 Mask.swap(PrevMask); 6026 for (unsigned I = 0; I < NumScalars; ++I) { 6027 Value *Scalar = E->Scalars[PrevMask[I]]; 6028 Optional<int> InsertIdx = getInsertIndex(Scalar, 0); 6029 if (!InsertIdx || *InsertIdx == UndefMaskElem) 6030 continue; 6031 IsIdentity &= *InsertIdx - Offset == I; 6032 Mask[*InsertIdx - Offset] = I; 6033 } 6034 if (!IsIdentity || NumElts != NumScalars) 6035 V = Builder.CreateShuffleVector(V, Mask); 6036 6037 if ((!IsIdentity || Offset != 0 || 6038 !isa<UndefValue>(FirstInsert->getOperand(0))) && 6039 NumElts != NumScalars) { 6040 SmallVector<int> InsertMask(NumElts); 6041 std::iota(InsertMask.begin(), InsertMask.end(), 0); 6042 for (unsigned I = 0; I < NumElts; I++) { 6043 if (Mask[I] != UndefMaskElem) 6044 InsertMask[Offset + I] = NumElts + I; 6045 } 6046 6047 V = Builder.CreateShuffleVector( 6048 FirstInsert->getOperand(0), V, InsertMask, 6049 cast<Instruction>(E->Scalars.back())->getName()); 6050 } 6051 6052 ++NumVectorInstructions; 6053 E->VectorizedValue = V; 6054 return V; 6055 } 6056 case Instruction::ZExt: 6057 case Instruction::SExt: 6058 case Instruction::FPToUI: 6059 case Instruction::FPToSI: 6060 case Instruction::FPExt: 6061 case Instruction::PtrToInt: 6062 case Instruction::IntToPtr: 6063 case Instruction::SIToFP: 6064 case Instruction::UIToFP: 6065 case Instruction::Trunc: 6066 case Instruction::FPTrunc: 6067 case Instruction::BitCast: { 6068 setInsertPointAfterBundle(E); 6069 6070 Value *InVec = vectorizeTree(E->getOperand(0)); 6071 6072 if (E->VectorizedValue) { 6073 LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n"); 6074 return E->VectorizedValue; 6075 } 6076 6077 auto *CI = cast<CastInst>(VL0); 6078 Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy); 6079 ShuffleBuilder.addInversedMask(E->ReorderIndices); 6080 ShuffleBuilder.addMask(E->ReuseShuffleIndices); 6081 V = ShuffleBuilder.finalize(V); 6082 6083 E->VectorizedValue = V; 6084 ++NumVectorInstructions; 6085 return V; 6086 } 6087 case Instruction::FCmp: 6088 case Instruction::ICmp: { 6089 setInsertPointAfterBundle(E); 6090 6091 Value *L = vectorizeTree(E->getOperand(0)); 6092 Value *R = vectorizeTree(E->getOperand(1)); 6093 6094 if (E->VectorizedValue) { 6095 LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n"); 6096 return E->VectorizedValue; 6097 } 6098 6099 CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate(); 6100 Value *V = Builder.CreateCmp(P0, L, R); 6101 propagateIRFlags(V, E->Scalars, VL0); 6102 ShuffleBuilder.addInversedMask(E->ReorderIndices); 6103 ShuffleBuilder.addMask(E->ReuseShuffleIndices); 6104 V = ShuffleBuilder.finalize(V); 6105 6106 E->VectorizedValue = V; 6107 ++NumVectorInstructions; 6108 return V; 6109 } 6110 case Instruction::Select: { 6111 setInsertPointAfterBundle(E); 6112 6113 Value *Cond = vectorizeTree(E->getOperand(0)); 6114 Value *True = vectorizeTree(E->getOperand(1)); 6115 Value *False = vectorizeTree(E->getOperand(2)); 6116 6117 if (E->VectorizedValue) { 6118 LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n"); 6119 return E->VectorizedValue; 6120 } 6121 6122 Value *V = Builder.CreateSelect(Cond, True, False); 6123 ShuffleBuilder.addInversedMask(E->ReorderIndices); 6124 ShuffleBuilder.addMask(E->ReuseShuffleIndices); 6125 V = ShuffleBuilder.finalize(V); 6126 6127 E->VectorizedValue = V; 6128 ++NumVectorInstructions; 6129 return V; 6130 } 6131 case Instruction::FNeg: { 6132 setInsertPointAfterBundle(E); 6133 6134 Value *Op = vectorizeTree(E->getOperand(0)); 6135 6136 if (E->VectorizedValue) { 6137 LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n"); 6138 return E->VectorizedValue; 6139 } 6140 6141 Value *V = Builder.CreateUnOp( 6142 static_cast<Instruction::UnaryOps>(E->getOpcode()), Op); 6143 propagateIRFlags(V, E->Scalars, VL0); 6144 if (auto *I = dyn_cast<Instruction>(V)) 6145 V = propagateMetadata(I, E->Scalars); 6146 6147 ShuffleBuilder.addInversedMask(E->ReorderIndices); 6148 ShuffleBuilder.addMask(E->ReuseShuffleIndices); 6149 V = ShuffleBuilder.finalize(V); 6150 6151 E->VectorizedValue = V; 6152 ++NumVectorInstructions; 6153 6154 return V; 6155 } 6156 case Instruction::Add: 6157 case Instruction::FAdd: 6158 case Instruction::Sub: 6159 case Instruction::FSub: 6160 case Instruction::Mul: 6161 case Instruction::FMul: 6162 case Instruction::UDiv: 6163 case Instruction::SDiv: 6164 case Instruction::FDiv: 6165 case Instruction::URem: 6166 case Instruction::SRem: 6167 case Instruction::FRem: 6168 case Instruction::Shl: 6169 case Instruction::LShr: 6170 case Instruction::AShr: 6171 case Instruction::And: 6172 case Instruction::Or: 6173 case Instruction::Xor: { 6174 setInsertPointAfterBundle(E); 6175 6176 Value *LHS = vectorizeTree(E->getOperand(0)); 6177 Value *RHS = vectorizeTree(E->getOperand(1)); 6178 6179 if (E->VectorizedValue) { 6180 LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n"); 6181 return E->VectorizedValue; 6182 } 6183 6184 Value *V = Builder.CreateBinOp( 6185 static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS, 6186 RHS); 6187 propagateIRFlags(V, E->Scalars, VL0); 6188 if (auto *I = dyn_cast<Instruction>(V)) 6189 V = propagateMetadata(I, E->Scalars); 6190 6191 ShuffleBuilder.addInversedMask(E->ReorderIndices); 6192 ShuffleBuilder.addMask(E->ReuseShuffleIndices); 6193 V = ShuffleBuilder.finalize(V); 6194 6195 E->VectorizedValue = V; 6196 ++NumVectorInstructions; 6197 6198 return V; 6199 } 6200 case Instruction::Load: { 6201 // Loads are inserted at the head of the tree because we don't want to 6202 // sink them all the way down past store instructions. 6203 setInsertPointAfterBundle(E); 6204 6205 LoadInst *LI = cast<LoadInst>(VL0); 6206 Instruction *NewLI; 6207 unsigned AS = LI->getPointerAddressSpace(); 6208 Value *PO = LI->getPointerOperand(); 6209 if (E->State == TreeEntry::Vectorize) { 6210 6211 Value *VecPtr = Builder.CreateBitCast(PO, VecTy->getPointerTo(AS)); 6212 6213 // The pointer operand uses an in-tree scalar so we add the new BitCast 6214 // to ExternalUses list to make sure that an extract will be generated 6215 // in the future. 6216 if (TreeEntry *Entry = getTreeEntry(PO)) { 6217 // Find which lane we need to extract. 6218 unsigned FoundLane = Entry->findLaneForValue(PO); 6219 ExternalUses.emplace_back(PO, cast<User>(VecPtr), FoundLane); 6220 } 6221 6222 NewLI = Builder.CreateAlignedLoad(VecTy, VecPtr, LI->getAlign()); 6223 } else { 6224 assert(E->State == TreeEntry::ScatterVectorize && "Unhandled state"); 6225 Value *VecPtr = vectorizeTree(E->getOperand(0)); 6226 // Use the minimum alignment of the gathered loads. 6227 Align CommonAlignment = LI->getAlign(); 6228 for (Value *V : E->Scalars) 6229 CommonAlignment = 6230 commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign()); 6231 NewLI = Builder.CreateMaskedGather(VecTy, VecPtr, CommonAlignment); 6232 } 6233 Value *V = propagateMetadata(NewLI, E->Scalars); 6234 6235 ShuffleBuilder.addInversedMask(E->ReorderIndices); 6236 ShuffleBuilder.addMask(E->ReuseShuffleIndices); 6237 V = ShuffleBuilder.finalize(V); 6238 E->VectorizedValue = V; 6239 ++NumVectorInstructions; 6240 return V; 6241 } 6242 case Instruction::Store: { 6243 auto *SI = cast<StoreInst>(VL0); 6244 unsigned AS = SI->getPointerAddressSpace(); 6245 6246 setInsertPointAfterBundle(E); 6247 6248 Value *VecValue = vectorizeTree(E->getOperand(0)); 6249 ShuffleBuilder.addMask(E->ReorderIndices); 6250 VecValue = ShuffleBuilder.finalize(VecValue); 6251 6252 Value *ScalarPtr = SI->getPointerOperand(); 6253 Value *VecPtr = Builder.CreateBitCast( 6254 ScalarPtr, VecValue->getType()->getPointerTo(AS)); 6255 StoreInst *ST = Builder.CreateAlignedStore(VecValue, VecPtr, 6256 SI->getAlign()); 6257 6258 // The pointer operand uses an in-tree scalar, so add the new BitCast to 6259 // ExternalUses to make sure that an extract will be generated in the 6260 // future. 6261 if (TreeEntry *Entry = getTreeEntry(ScalarPtr)) { 6262 // Find which lane we need to extract. 6263 unsigned FoundLane = Entry->findLaneForValue(ScalarPtr); 6264 ExternalUses.push_back( 6265 ExternalUser(ScalarPtr, cast<User>(VecPtr), FoundLane)); 6266 } 6267 6268 Value *V = propagateMetadata(ST, E->Scalars); 6269 6270 E->VectorizedValue = V; 6271 ++NumVectorInstructions; 6272 return V; 6273 } 6274 case Instruction::GetElementPtr: { 6275 setInsertPointAfterBundle(E); 6276 6277 Value *Op0 = vectorizeTree(E->getOperand(0)); 6278 6279 std::vector<Value *> OpVecs; 6280 for (int j = 1, e = cast<GetElementPtrInst>(VL0)->getNumOperands(); j < e; 6281 ++j) { 6282 ValueList &VL = E->getOperand(j); 6283 // Need to cast all elements to the same type before vectorization to 6284 // avoid crash. 6285 Type *VL0Ty = VL0->getOperand(j)->getType(); 6286 Type *Ty = llvm::all_of( 6287 VL, [VL0Ty](Value *V) { return VL0Ty == V->getType(); }) 6288 ? VL0Ty 6289 : DL->getIndexType(cast<GetElementPtrInst>(VL0) 6290 ->getPointerOperandType() 6291 ->getScalarType()); 6292 for (Value *&V : VL) { 6293 auto *CI = cast<ConstantInt>(V); 6294 V = ConstantExpr::getIntegerCast(CI, Ty, 6295 CI->getValue().isSignBitSet()); 6296 } 6297 Value *OpVec = vectorizeTree(VL); 6298 OpVecs.push_back(OpVec); 6299 } 6300 6301 Value *V = Builder.CreateGEP( 6302 cast<GetElementPtrInst>(VL0)->getSourceElementType(), Op0, OpVecs); 6303 if (Instruction *I = dyn_cast<Instruction>(V)) 6304 V = propagateMetadata(I, E->Scalars); 6305 6306 ShuffleBuilder.addInversedMask(E->ReorderIndices); 6307 ShuffleBuilder.addMask(E->ReuseShuffleIndices); 6308 V = ShuffleBuilder.finalize(V); 6309 6310 E->VectorizedValue = V; 6311 ++NumVectorInstructions; 6312 6313 return V; 6314 } 6315 case Instruction::Call: { 6316 CallInst *CI = cast<CallInst>(VL0); 6317 setInsertPointAfterBundle(E); 6318 6319 Intrinsic::ID IID = Intrinsic::not_intrinsic; 6320 if (Function *FI = CI->getCalledFunction()) 6321 IID = FI->getIntrinsicID(); 6322 6323 Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI); 6324 6325 auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI); 6326 bool UseIntrinsic = ID != Intrinsic::not_intrinsic && 6327 VecCallCosts.first <= VecCallCosts.second; 6328 6329 Value *ScalarArg = nullptr; 6330 std::vector<Value *> OpVecs; 6331 SmallVector<Type *, 2> TysForDecl = 6332 {FixedVectorType::get(CI->getType(), E->Scalars.size())}; 6333 for (int j = 0, e = CI->arg_size(); j < e; ++j) { 6334 ValueList OpVL; 6335 // Some intrinsics have scalar arguments. This argument should not be 6336 // vectorized. 6337 if (UseIntrinsic && hasVectorInstrinsicScalarOpd(IID, j)) { 6338 CallInst *CEI = cast<CallInst>(VL0); 6339 ScalarArg = CEI->getArgOperand(j); 6340 OpVecs.push_back(CEI->getArgOperand(j)); 6341 if (hasVectorInstrinsicOverloadedScalarOpd(IID, j)) 6342 TysForDecl.push_back(ScalarArg->getType()); 6343 continue; 6344 } 6345 6346 Value *OpVec = vectorizeTree(E->getOperand(j)); 6347 LLVM_DEBUG(dbgs() << "SLP: OpVec[" << j << "]: " << *OpVec << "\n"); 6348 OpVecs.push_back(OpVec); 6349 } 6350 6351 Function *CF; 6352 if (!UseIntrinsic) { 6353 VFShape Shape = 6354 VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>( 6355 VecTy->getNumElements())), 6356 false /*HasGlobalPred*/); 6357 CF = VFDatabase(*CI).getVectorizedFunction(Shape); 6358 } else { 6359 CF = Intrinsic::getDeclaration(F->getParent(), ID, TysForDecl); 6360 } 6361 6362 SmallVector<OperandBundleDef, 1> OpBundles; 6363 CI->getOperandBundlesAsDefs(OpBundles); 6364 Value *V = Builder.CreateCall(CF, OpVecs, OpBundles); 6365 6366 // The scalar argument uses an in-tree scalar so we add the new vectorized 6367 // call to ExternalUses list to make sure that an extract will be 6368 // generated in the future. 6369 if (ScalarArg) { 6370 if (TreeEntry *Entry = getTreeEntry(ScalarArg)) { 6371 // Find which lane we need to extract. 6372 unsigned FoundLane = Entry->findLaneForValue(ScalarArg); 6373 ExternalUses.push_back( 6374 ExternalUser(ScalarArg, cast<User>(V), FoundLane)); 6375 } 6376 } 6377 6378 propagateIRFlags(V, E->Scalars, VL0); 6379 ShuffleBuilder.addInversedMask(E->ReorderIndices); 6380 ShuffleBuilder.addMask(E->ReuseShuffleIndices); 6381 V = ShuffleBuilder.finalize(V); 6382 6383 E->VectorizedValue = V; 6384 ++NumVectorInstructions; 6385 return V; 6386 } 6387 case Instruction::ShuffleVector: { 6388 assert(E->isAltShuffle() && 6389 ((Instruction::isBinaryOp(E->getOpcode()) && 6390 Instruction::isBinaryOp(E->getAltOpcode())) || 6391 (Instruction::isCast(E->getOpcode()) && 6392 Instruction::isCast(E->getAltOpcode()))) && 6393 "Invalid Shuffle Vector Operand"); 6394 6395 Value *LHS = nullptr, *RHS = nullptr; 6396 if (Instruction::isBinaryOp(E->getOpcode())) { 6397 setInsertPointAfterBundle(E); 6398 LHS = vectorizeTree(E->getOperand(0)); 6399 RHS = vectorizeTree(E->getOperand(1)); 6400 } else { 6401 setInsertPointAfterBundle(E); 6402 LHS = vectorizeTree(E->getOperand(0)); 6403 } 6404 6405 if (E->VectorizedValue) { 6406 LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n"); 6407 return E->VectorizedValue; 6408 } 6409 6410 Value *V0, *V1; 6411 if (Instruction::isBinaryOp(E->getOpcode())) { 6412 V0 = Builder.CreateBinOp( 6413 static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS, RHS); 6414 V1 = Builder.CreateBinOp( 6415 static_cast<Instruction::BinaryOps>(E->getAltOpcode()), LHS, RHS); 6416 } else { 6417 V0 = Builder.CreateCast( 6418 static_cast<Instruction::CastOps>(E->getOpcode()), LHS, VecTy); 6419 V1 = Builder.CreateCast( 6420 static_cast<Instruction::CastOps>(E->getAltOpcode()), LHS, VecTy); 6421 } 6422 6423 // Create shuffle to take alternate operations from the vector. 6424 // Also, gather up main and alt scalar ops to propagate IR flags to 6425 // each vector operation. 6426 ValueList OpScalars, AltScalars; 6427 SmallVector<int> Mask; 6428 buildSuffleEntryMask( 6429 E->Scalars, E->ReorderIndices, E->ReuseShuffleIndices, 6430 [E](Instruction *I) { 6431 assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode"); 6432 return I->getOpcode() == E->getAltOpcode(); 6433 }, 6434 Mask, &OpScalars, &AltScalars); 6435 6436 propagateIRFlags(V0, OpScalars); 6437 propagateIRFlags(V1, AltScalars); 6438 6439 Value *V = Builder.CreateShuffleVector(V0, V1, Mask); 6440 if (Instruction *I = dyn_cast<Instruction>(V)) 6441 V = propagateMetadata(I, E->Scalars); 6442 V = ShuffleBuilder.finalize(V); 6443 6444 E->VectorizedValue = V; 6445 ++NumVectorInstructions; 6446 6447 return V; 6448 } 6449 default: 6450 llvm_unreachable("unknown inst"); 6451 } 6452 return nullptr; 6453 } 6454 6455 Value *BoUpSLP::vectorizeTree() { 6456 ExtraValueToDebugLocsMap ExternallyUsedValues; 6457 return vectorizeTree(ExternallyUsedValues); 6458 } 6459 6460 Value * 6461 BoUpSLP::vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues) { 6462 // All blocks must be scheduled before any instructions are inserted. 6463 for (auto &BSIter : BlocksSchedules) { 6464 scheduleBlock(BSIter.second.get()); 6465 } 6466 6467 Builder.SetInsertPoint(&F->getEntryBlock().front()); 6468 auto *VectorRoot = vectorizeTree(VectorizableTree[0].get()); 6469 6470 // If the vectorized tree can be rewritten in a smaller type, we truncate the 6471 // vectorized root. InstCombine will then rewrite the entire expression. We 6472 // sign extend the extracted values below. 6473 auto *ScalarRoot = VectorizableTree[0]->Scalars[0]; 6474 if (MinBWs.count(ScalarRoot)) { 6475 if (auto *I = dyn_cast<Instruction>(VectorRoot)) { 6476 // If current instr is a phi and not the last phi, insert it after the 6477 // last phi node. 6478 if (isa<PHINode>(I)) 6479 Builder.SetInsertPoint(&*I->getParent()->getFirstInsertionPt()); 6480 else 6481 Builder.SetInsertPoint(&*++BasicBlock::iterator(I)); 6482 } 6483 auto BundleWidth = VectorizableTree[0]->Scalars.size(); 6484 auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first); 6485 auto *VecTy = FixedVectorType::get(MinTy, BundleWidth); 6486 auto *Trunc = Builder.CreateTrunc(VectorRoot, VecTy); 6487 VectorizableTree[0]->VectorizedValue = Trunc; 6488 } 6489 6490 LLVM_DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size() 6491 << " values .\n"); 6492 6493 // Extract all of the elements with the external uses. 6494 for (const auto &ExternalUse : ExternalUses) { 6495 Value *Scalar = ExternalUse.Scalar; 6496 llvm::User *User = ExternalUse.User; 6497 6498 // Skip users that we already RAUW. This happens when one instruction 6499 // has multiple uses of the same value. 6500 if (User && !is_contained(Scalar->users(), User)) 6501 continue; 6502 TreeEntry *E = getTreeEntry(Scalar); 6503 assert(E && "Invalid scalar"); 6504 assert(E->State != TreeEntry::NeedToGather && 6505 "Extracting from a gather list"); 6506 6507 Value *Vec = E->VectorizedValue; 6508 assert(Vec && "Can't find vectorizable value"); 6509 6510 Value *Lane = Builder.getInt32(ExternalUse.Lane); 6511 auto ExtractAndExtendIfNeeded = [&](Value *Vec) { 6512 if (Scalar->getType() != Vec->getType()) { 6513 Value *Ex; 6514 // "Reuse" the existing extract to improve final codegen. 6515 if (auto *ES = dyn_cast<ExtractElementInst>(Scalar)) { 6516 Ex = Builder.CreateExtractElement(ES->getOperand(0), 6517 ES->getOperand(1)); 6518 } else { 6519 Ex = Builder.CreateExtractElement(Vec, Lane); 6520 } 6521 // If necessary, sign-extend or zero-extend ScalarRoot 6522 // to the larger type. 6523 if (!MinBWs.count(ScalarRoot)) 6524 return Ex; 6525 if (MinBWs[ScalarRoot].second) 6526 return Builder.CreateSExt(Ex, Scalar->getType()); 6527 return Builder.CreateZExt(Ex, Scalar->getType()); 6528 } 6529 assert(isa<FixedVectorType>(Scalar->getType()) && 6530 isa<InsertElementInst>(Scalar) && 6531 "In-tree scalar of vector type is not insertelement?"); 6532 return Vec; 6533 }; 6534 // If User == nullptr, the Scalar is used as extra arg. Generate 6535 // ExtractElement instruction and update the record for this scalar in 6536 // ExternallyUsedValues. 6537 if (!User) { 6538 assert(ExternallyUsedValues.count(Scalar) && 6539 "Scalar with nullptr as an external user must be registered in " 6540 "ExternallyUsedValues map"); 6541 if (auto *VecI = dyn_cast<Instruction>(Vec)) { 6542 Builder.SetInsertPoint(VecI->getParent(), 6543 std::next(VecI->getIterator())); 6544 } else { 6545 Builder.SetInsertPoint(&F->getEntryBlock().front()); 6546 } 6547 Value *NewInst = ExtractAndExtendIfNeeded(Vec); 6548 CSEBlocks.insert(cast<Instruction>(Scalar)->getParent()); 6549 auto &NewInstLocs = ExternallyUsedValues[NewInst]; 6550 auto It = ExternallyUsedValues.find(Scalar); 6551 assert(It != ExternallyUsedValues.end() && 6552 "Externally used scalar is not found in ExternallyUsedValues"); 6553 NewInstLocs.append(It->second); 6554 ExternallyUsedValues.erase(Scalar); 6555 // Required to update internally referenced instructions. 6556 Scalar->replaceAllUsesWith(NewInst); 6557 continue; 6558 } 6559 6560 // Generate extracts for out-of-tree users. 6561 // Find the insertion point for the extractelement lane. 6562 if (auto *VecI = dyn_cast<Instruction>(Vec)) { 6563 if (PHINode *PH = dyn_cast<PHINode>(User)) { 6564 for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) { 6565 if (PH->getIncomingValue(i) == Scalar) { 6566 Instruction *IncomingTerminator = 6567 PH->getIncomingBlock(i)->getTerminator(); 6568 if (isa<CatchSwitchInst>(IncomingTerminator)) { 6569 Builder.SetInsertPoint(VecI->getParent(), 6570 std::next(VecI->getIterator())); 6571 } else { 6572 Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator()); 6573 } 6574 Value *NewInst = ExtractAndExtendIfNeeded(Vec); 6575 CSEBlocks.insert(PH->getIncomingBlock(i)); 6576 PH->setOperand(i, NewInst); 6577 } 6578 } 6579 } else { 6580 Builder.SetInsertPoint(cast<Instruction>(User)); 6581 Value *NewInst = ExtractAndExtendIfNeeded(Vec); 6582 CSEBlocks.insert(cast<Instruction>(User)->getParent()); 6583 User->replaceUsesOfWith(Scalar, NewInst); 6584 } 6585 } else { 6586 Builder.SetInsertPoint(&F->getEntryBlock().front()); 6587 Value *NewInst = ExtractAndExtendIfNeeded(Vec); 6588 CSEBlocks.insert(&F->getEntryBlock()); 6589 User->replaceUsesOfWith(Scalar, NewInst); 6590 } 6591 6592 LLVM_DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n"); 6593 } 6594 6595 // For each vectorized value: 6596 for (auto &TEPtr : VectorizableTree) { 6597 TreeEntry *Entry = TEPtr.get(); 6598 6599 // No need to handle users of gathered values. 6600 if (Entry->State == TreeEntry::NeedToGather) 6601 continue; 6602 6603 assert(Entry->VectorizedValue && "Can't find vectorizable value"); 6604 6605 // For each lane: 6606 for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) { 6607 Value *Scalar = Entry->Scalars[Lane]; 6608 6609 #ifndef NDEBUG 6610 Type *Ty = Scalar->getType(); 6611 if (!Ty->isVoidTy()) { 6612 for (User *U : Scalar->users()) { 6613 LLVM_DEBUG(dbgs() << "SLP: \tvalidating user:" << *U << ".\n"); 6614 6615 // It is legal to delete users in the ignorelist. 6616 assert((getTreeEntry(U) || is_contained(UserIgnoreList, U) || 6617 (isa_and_nonnull<Instruction>(U) && 6618 isDeleted(cast<Instruction>(U)))) && 6619 "Deleting out-of-tree value"); 6620 } 6621 } 6622 #endif 6623 LLVM_DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n"); 6624 eraseInstruction(cast<Instruction>(Scalar)); 6625 } 6626 } 6627 6628 Builder.ClearInsertionPoint(); 6629 InstrElementSize.clear(); 6630 6631 return VectorizableTree[0]->VectorizedValue; 6632 } 6633 6634 void BoUpSLP::optimizeGatherSequence() { 6635 LLVM_DEBUG(dbgs() << "SLP: Optimizing " << GatherSeq.size() 6636 << " gather sequences instructions.\n"); 6637 // LICM InsertElementInst sequences. 6638 for (Instruction *I : GatherSeq) { 6639 if (isDeleted(I)) 6640 continue; 6641 6642 // Check if this block is inside a loop. 6643 Loop *L = LI->getLoopFor(I->getParent()); 6644 if (!L) 6645 continue; 6646 6647 // Check if it has a preheader. 6648 BasicBlock *PreHeader = L->getLoopPreheader(); 6649 if (!PreHeader) 6650 continue; 6651 6652 // If the vector or the element that we insert into it are 6653 // instructions that are defined in this basic block then we can't 6654 // hoist this instruction. 6655 auto *Op0 = dyn_cast<Instruction>(I->getOperand(0)); 6656 auto *Op1 = dyn_cast<Instruction>(I->getOperand(1)); 6657 if (Op0 && L->contains(Op0)) 6658 continue; 6659 if (Op1 && L->contains(Op1)) 6660 continue; 6661 6662 // We can hoist this instruction. Move it to the pre-header. 6663 I->moveBefore(PreHeader->getTerminator()); 6664 } 6665 6666 // Make a list of all reachable blocks in our CSE queue. 6667 SmallVector<const DomTreeNode *, 8> CSEWorkList; 6668 CSEWorkList.reserve(CSEBlocks.size()); 6669 for (BasicBlock *BB : CSEBlocks) 6670 if (DomTreeNode *N = DT->getNode(BB)) { 6671 assert(DT->isReachableFromEntry(N)); 6672 CSEWorkList.push_back(N); 6673 } 6674 6675 // Sort blocks by domination. This ensures we visit a block after all blocks 6676 // dominating it are visited. 6677 llvm::sort(CSEWorkList, [](const DomTreeNode *A, const DomTreeNode *B) { 6678 assert((A == B) == (A->getDFSNumIn() == B->getDFSNumIn()) && 6679 "Different nodes should have different DFS numbers"); 6680 return A->getDFSNumIn() < B->getDFSNumIn(); 6681 }); 6682 6683 // Perform O(N^2) search over the gather sequences and merge identical 6684 // instructions. TODO: We can further optimize this scan if we split the 6685 // instructions into different buckets based on the insert lane. 6686 SmallVector<Instruction *, 16> Visited; 6687 for (auto I = CSEWorkList.begin(), E = CSEWorkList.end(); I != E; ++I) { 6688 assert(*I && 6689 (I == CSEWorkList.begin() || !DT->dominates(*I, *std::prev(I))) && 6690 "Worklist not sorted properly!"); 6691 BasicBlock *BB = (*I)->getBlock(); 6692 // For all instructions in blocks containing gather sequences: 6693 for (Instruction &In : llvm::make_early_inc_range(*BB)) { 6694 if (isDeleted(&In)) 6695 continue; 6696 if (!isa<InsertElementInst>(&In) && !isa<ExtractElementInst>(&In) && 6697 !isa<ShuffleVectorInst>(&In)) 6698 continue; 6699 6700 // Check if we can replace this instruction with any of the 6701 // visited instructions. 6702 bool Replaced = false; 6703 for (Instruction *v : Visited) { 6704 if (In.isIdenticalTo(v) && 6705 DT->dominates(v->getParent(), In.getParent())) { 6706 In.replaceAllUsesWith(v); 6707 eraseInstruction(&In); 6708 Replaced = true; 6709 break; 6710 } 6711 } 6712 if (!Replaced) { 6713 assert(!is_contained(Visited, &In)); 6714 Visited.push_back(&In); 6715 } 6716 } 6717 } 6718 CSEBlocks.clear(); 6719 GatherSeq.clear(); 6720 } 6721 6722 // Groups the instructions to a bundle (which is then a single scheduling entity) 6723 // and schedules instructions until the bundle gets ready. 6724 Optional<BoUpSLP::ScheduleData *> 6725 BoUpSLP::BlockScheduling::tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP, 6726 const InstructionsState &S) { 6727 // No need to schedule PHIs, insertelement, extractelement and extractvalue 6728 // instructions. 6729 if (isa<PHINode>(S.OpValue) || isVectorLikeInstWithConstOps(S.OpValue)) 6730 return nullptr; 6731 6732 // Initialize the instruction bundle. 6733 Instruction *OldScheduleEnd = ScheduleEnd; 6734 ScheduleData *PrevInBundle = nullptr; 6735 ScheduleData *Bundle = nullptr; 6736 bool ReSchedule = false; 6737 LLVM_DEBUG(dbgs() << "SLP: bundle: " << *S.OpValue << "\n"); 6738 6739 auto &&TryScheduleBundle = [this, OldScheduleEnd, SLP](bool ReSchedule, 6740 ScheduleData *Bundle) { 6741 // The scheduling region got new instructions at the lower end (or it is a 6742 // new region for the first bundle). This makes it necessary to 6743 // recalculate all dependencies. 6744 // It is seldom that this needs to be done a second time after adding the 6745 // initial bundle to the region. 6746 if (ScheduleEnd != OldScheduleEnd) { 6747 for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) 6748 doForAllOpcodes(I, [](ScheduleData *SD) { SD->clearDependencies(); }); 6749 ReSchedule = true; 6750 } 6751 if (ReSchedule) { 6752 resetSchedule(); 6753 initialFillReadyList(ReadyInsts); 6754 } 6755 if (Bundle) { 6756 LLVM_DEBUG(dbgs() << "SLP: try schedule bundle " << *Bundle 6757 << " in block " << BB->getName() << "\n"); 6758 calculateDependencies(Bundle, /*InsertInReadyList=*/true, SLP); 6759 } 6760 6761 // Now try to schedule the new bundle or (if no bundle) just calculate 6762 // dependencies. As soon as the bundle is "ready" it means that there are no 6763 // cyclic dependencies and we can schedule it. Note that's important that we 6764 // don't "schedule" the bundle yet (see cancelScheduling). 6765 while (((!Bundle && ReSchedule) || (Bundle && !Bundle->isReady())) && 6766 !ReadyInsts.empty()) { 6767 ScheduleData *Picked = ReadyInsts.pop_back_val(); 6768 if (Picked->isSchedulingEntity() && Picked->isReady()) 6769 schedule(Picked, ReadyInsts); 6770 } 6771 }; 6772 6773 // Make sure that the scheduling region contains all 6774 // instructions of the bundle. 6775 for (Value *V : VL) { 6776 if (!extendSchedulingRegion(V, S)) { 6777 // If the scheduling region got new instructions at the lower end (or it 6778 // is a new region for the first bundle). This makes it necessary to 6779 // recalculate all dependencies. 6780 // Otherwise the compiler may crash trying to incorrectly calculate 6781 // dependencies and emit instruction in the wrong order at the actual 6782 // scheduling. 6783 TryScheduleBundle(/*ReSchedule=*/false, nullptr); 6784 return None; 6785 } 6786 } 6787 6788 for (Value *V : VL) { 6789 ScheduleData *BundleMember = getScheduleData(V); 6790 assert(BundleMember && 6791 "no ScheduleData for bundle member (maybe not in same basic block)"); 6792 if (BundleMember->IsScheduled) { 6793 // A bundle member was scheduled as single instruction before and now 6794 // needs to be scheduled as part of the bundle. We just get rid of the 6795 // existing schedule. 6796 LLVM_DEBUG(dbgs() << "SLP: reset schedule because " << *BundleMember 6797 << " was already scheduled\n"); 6798 ReSchedule = true; 6799 } 6800 assert(BundleMember->isSchedulingEntity() && 6801 "bundle member already part of other bundle"); 6802 if (PrevInBundle) { 6803 PrevInBundle->NextInBundle = BundleMember; 6804 } else { 6805 Bundle = BundleMember; 6806 } 6807 BundleMember->UnscheduledDepsInBundle = 0; 6808 Bundle->UnscheduledDepsInBundle += BundleMember->UnscheduledDeps; 6809 6810 // Group the instructions to a bundle. 6811 BundleMember->FirstInBundle = Bundle; 6812 PrevInBundle = BundleMember; 6813 } 6814 assert(Bundle && "Failed to find schedule bundle"); 6815 TryScheduleBundle(ReSchedule, Bundle); 6816 if (!Bundle->isReady()) { 6817 cancelScheduling(VL, S.OpValue); 6818 return None; 6819 } 6820 return Bundle; 6821 } 6822 6823 void BoUpSLP::BlockScheduling::cancelScheduling(ArrayRef<Value *> VL, 6824 Value *OpValue) { 6825 if (isa<PHINode>(OpValue) || isVectorLikeInstWithConstOps(OpValue)) 6826 return; 6827 6828 ScheduleData *Bundle = getScheduleData(OpValue); 6829 LLVM_DEBUG(dbgs() << "SLP: cancel scheduling of " << *Bundle << "\n"); 6830 assert(!Bundle->IsScheduled && 6831 "Can't cancel bundle which is already scheduled"); 6832 assert(Bundle->isSchedulingEntity() && Bundle->isPartOfBundle() && 6833 "tried to unbundle something which is not a bundle"); 6834 6835 // Un-bundle: make single instructions out of the bundle. 6836 ScheduleData *BundleMember = Bundle; 6837 while (BundleMember) { 6838 assert(BundleMember->FirstInBundle == Bundle && "corrupt bundle links"); 6839 BundleMember->FirstInBundle = BundleMember; 6840 ScheduleData *Next = BundleMember->NextInBundle; 6841 BundleMember->NextInBundle = nullptr; 6842 BundleMember->UnscheduledDepsInBundle = BundleMember->UnscheduledDeps; 6843 if (BundleMember->UnscheduledDepsInBundle == 0) { 6844 ReadyInsts.insert(BundleMember); 6845 } 6846 BundleMember = Next; 6847 } 6848 } 6849 6850 BoUpSLP::ScheduleData *BoUpSLP::BlockScheduling::allocateScheduleDataChunks() { 6851 // Allocate a new ScheduleData for the instruction. 6852 if (ChunkPos >= ChunkSize) { 6853 ScheduleDataChunks.push_back(std::make_unique<ScheduleData[]>(ChunkSize)); 6854 ChunkPos = 0; 6855 } 6856 return &(ScheduleDataChunks.back()[ChunkPos++]); 6857 } 6858 6859 bool BoUpSLP::BlockScheduling::extendSchedulingRegion(Value *V, 6860 const InstructionsState &S) { 6861 if (getScheduleData(V, isOneOf(S, V))) 6862 return true; 6863 Instruction *I = dyn_cast<Instruction>(V); 6864 assert(I && "bundle member must be an instruction"); 6865 assert(!isa<PHINode>(I) && !isVectorLikeInstWithConstOps(I) && 6866 "phi nodes/insertelements/extractelements/extractvalues don't need to " 6867 "be scheduled"); 6868 auto &&CheckSheduleForI = [this, &S](Instruction *I) -> bool { 6869 ScheduleData *ISD = getScheduleData(I); 6870 if (!ISD) 6871 return false; 6872 assert(isInSchedulingRegion(ISD) && 6873 "ScheduleData not in scheduling region"); 6874 ScheduleData *SD = allocateScheduleDataChunks(); 6875 SD->Inst = I; 6876 SD->init(SchedulingRegionID, S.OpValue); 6877 ExtraScheduleDataMap[I][S.OpValue] = SD; 6878 return true; 6879 }; 6880 if (CheckSheduleForI(I)) 6881 return true; 6882 if (!ScheduleStart) { 6883 // It's the first instruction in the new region. 6884 initScheduleData(I, I->getNextNode(), nullptr, nullptr); 6885 ScheduleStart = I; 6886 ScheduleEnd = I->getNextNode(); 6887 if (isOneOf(S, I) != I) 6888 CheckSheduleForI(I); 6889 assert(ScheduleEnd && "tried to vectorize a terminator?"); 6890 LLVM_DEBUG(dbgs() << "SLP: initialize schedule region to " << *I << "\n"); 6891 return true; 6892 } 6893 // Search up and down at the same time, because we don't know if the new 6894 // instruction is above or below the existing scheduling region. 6895 BasicBlock::reverse_iterator UpIter = 6896 ++ScheduleStart->getIterator().getReverse(); 6897 BasicBlock::reverse_iterator UpperEnd = BB->rend(); 6898 BasicBlock::iterator DownIter = ScheduleEnd->getIterator(); 6899 BasicBlock::iterator LowerEnd = BB->end(); 6900 while (UpIter != UpperEnd && DownIter != LowerEnd && &*UpIter != I && 6901 &*DownIter != I) { 6902 if (++ScheduleRegionSize > ScheduleRegionSizeLimit) { 6903 LLVM_DEBUG(dbgs() << "SLP: exceeded schedule region size limit\n"); 6904 return false; 6905 } 6906 6907 ++UpIter; 6908 ++DownIter; 6909 } 6910 if (DownIter == LowerEnd || (UpIter != UpperEnd && &*UpIter == I)) { 6911 assert(I->getParent() == ScheduleStart->getParent() && 6912 "Instruction is in wrong basic block."); 6913 initScheduleData(I, ScheduleStart, nullptr, FirstLoadStoreInRegion); 6914 ScheduleStart = I; 6915 if (isOneOf(S, I) != I) 6916 CheckSheduleForI(I); 6917 LLVM_DEBUG(dbgs() << "SLP: extend schedule region start to " << *I 6918 << "\n"); 6919 return true; 6920 } 6921 assert((UpIter == UpperEnd || (DownIter != LowerEnd && &*DownIter == I)) && 6922 "Expected to reach top of the basic block or instruction down the " 6923 "lower end."); 6924 assert(I->getParent() == ScheduleEnd->getParent() && 6925 "Instruction is in wrong basic block."); 6926 initScheduleData(ScheduleEnd, I->getNextNode(), LastLoadStoreInRegion, 6927 nullptr); 6928 ScheduleEnd = I->getNextNode(); 6929 if (isOneOf(S, I) != I) 6930 CheckSheduleForI(I); 6931 assert(ScheduleEnd && "tried to vectorize a terminator?"); 6932 LLVM_DEBUG(dbgs() << "SLP: extend schedule region end to " << *I << "\n"); 6933 return true; 6934 } 6935 6936 void BoUpSLP::BlockScheduling::initScheduleData(Instruction *FromI, 6937 Instruction *ToI, 6938 ScheduleData *PrevLoadStore, 6939 ScheduleData *NextLoadStore) { 6940 ScheduleData *CurrentLoadStore = PrevLoadStore; 6941 for (Instruction *I = FromI; I != ToI; I = I->getNextNode()) { 6942 ScheduleData *SD = ScheduleDataMap[I]; 6943 if (!SD) { 6944 SD = allocateScheduleDataChunks(); 6945 ScheduleDataMap[I] = SD; 6946 SD->Inst = I; 6947 } 6948 assert(!isInSchedulingRegion(SD) && 6949 "new ScheduleData already in scheduling region"); 6950 SD->init(SchedulingRegionID, I); 6951 6952 if (I->mayReadOrWriteMemory() && 6953 (!isa<IntrinsicInst>(I) || 6954 (cast<IntrinsicInst>(I)->getIntrinsicID() != Intrinsic::sideeffect && 6955 cast<IntrinsicInst>(I)->getIntrinsicID() != 6956 Intrinsic::pseudoprobe))) { 6957 // Update the linked list of memory accessing instructions. 6958 if (CurrentLoadStore) { 6959 CurrentLoadStore->NextLoadStore = SD; 6960 } else { 6961 FirstLoadStoreInRegion = SD; 6962 } 6963 CurrentLoadStore = SD; 6964 } 6965 } 6966 if (NextLoadStore) { 6967 if (CurrentLoadStore) 6968 CurrentLoadStore->NextLoadStore = NextLoadStore; 6969 } else { 6970 LastLoadStoreInRegion = CurrentLoadStore; 6971 } 6972 } 6973 6974 void BoUpSLP::BlockScheduling::calculateDependencies(ScheduleData *SD, 6975 bool InsertInReadyList, 6976 BoUpSLP *SLP) { 6977 assert(SD->isSchedulingEntity()); 6978 6979 SmallVector<ScheduleData *, 10> WorkList; 6980 WorkList.push_back(SD); 6981 6982 while (!WorkList.empty()) { 6983 ScheduleData *SD = WorkList.pop_back_val(); 6984 6985 ScheduleData *BundleMember = SD; 6986 while (BundleMember) { 6987 assert(isInSchedulingRegion(BundleMember)); 6988 if (!BundleMember->hasValidDependencies()) { 6989 6990 LLVM_DEBUG(dbgs() << "SLP: update deps of " << *BundleMember 6991 << "\n"); 6992 BundleMember->Dependencies = 0; 6993 BundleMember->resetUnscheduledDeps(); 6994 6995 // Handle def-use chain dependencies. 6996 if (BundleMember->OpValue != BundleMember->Inst) { 6997 ScheduleData *UseSD = getScheduleData(BundleMember->Inst); 6998 if (UseSD && isInSchedulingRegion(UseSD->FirstInBundle)) { 6999 BundleMember->Dependencies++; 7000 ScheduleData *DestBundle = UseSD->FirstInBundle; 7001 if (!DestBundle->IsScheduled) 7002 BundleMember->incrementUnscheduledDeps(1); 7003 if (!DestBundle->hasValidDependencies()) 7004 WorkList.push_back(DestBundle); 7005 } 7006 } else { 7007 for (User *U : BundleMember->Inst->users()) { 7008 if (isa<Instruction>(U)) { 7009 ScheduleData *UseSD = getScheduleData(U); 7010 if (UseSD && isInSchedulingRegion(UseSD->FirstInBundle)) { 7011 BundleMember->Dependencies++; 7012 ScheduleData *DestBundle = UseSD->FirstInBundle; 7013 if (!DestBundle->IsScheduled) 7014 BundleMember->incrementUnscheduledDeps(1); 7015 if (!DestBundle->hasValidDependencies()) 7016 WorkList.push_back(DestBundle); 7017 } 7018 } else { 7019 // I'm not sure if this can ever happen. But we need to be safe. 7020 // This lets the instruction/bundle never be scheduled and 7021 // eventually disable vectorization. 7022 BundleMember->Dependencies++; 7023 BundleMember->incrementUnscheduledDeps(1); 7024 } 7025 } 7026 } 7027 7028 // Handle the memory dependencies. 7029 ScheduleData *DepDest = BundleMember->NextLoadStore; 7030 if (DepDest) { 7031 Instruction *SrcInst = BundleMember->Inst; 7032 MemoryLocation SrcLoc = getLocation(SrcInst, SLP->AA); 7033 bool SrcMayWrite = BundleMember->Inst->mayWriteToMemory(); 7034 unsigned numAliased = 0; 7035 unsigned DistToSrc = 1; 7036 7037 while (DepDest) { 7038 assert(isInSchedulingRegion(DepDest)); 7039 7040 // We have two limits to reduce the complexity: 7041 // 1) AliasedCheckLimit: It's a small limit to reduce calls to 7042 // SLP->isAliased (which is the expensive part in this loop). 7043 // 2) MaxMemDepDistance: It's for very large blocks and it aborts 7044 // the whole loop (even if the loop is fast, it's quadratic). 7045 // It's important for the loop break condition (see below) to 7046 // check this limit even between two read-only instructions. 7047 if (DistToSrc >= MaxMemDepDistance || 7048 ((SrcMayWrite || DepDest->Inst->mayWriteToMemory()) && 7049 (numAliased >= AliasedCheckLimit || 7050 SLP->isAliased(SrcLoc, SrcInst, DepDest->Inst)))) { 7051 7052 // We increment the counter only if the locations are aliased 7053 // (instead of counting all alias checks). This gives a better 7054 // balance between reduced runtime and accurate dependencies. 7055 numAliased++; 7056 7057 DepDest->MemoryDependencies.push_back(BundleMember); 7058 BundleMember->Dependencies++; 7059 ScheduleData *DestBundle = DepDest->FirstInBundle; 7060 if (!DestBundle->IsScheduled) { 7061 BundleMember->incrementUnscheduledDeps(1); 7062 } 7063 if (!DestBundle->hasValidDependencies()) { 7064 WorkList.push_back(DestBundle); 7065 } 7066 } 7067 DepDest = DepDest->NextLoadStore; 7068 7069 // Example, explaining the loop break condition: Let's assume our 7070 // starting instruction is i0 and MaxMemDepDistance = 3. 7071 // 7072 // +--------v--v--v 7073 // i0,i1,i2,i3,i4,i5,i6,i7,i8 7074 // +--------^--^--^ 7075 // 7076 // MaxMemDepDistance let us stop alias-checking at i3 and we add 7077 // dependencies from i0 to i3,i4,.. (even if they are not aliased). 7078 // Previously we already added dependencies from i3 to i6,i7,i8 7079 // (because of MaxMemDepDistance). As we added a dependency from 7080 // i0 to i3, we have transitive dependencies from i0 to i6,i7,i8 7081 // and we can abort this loop at i6. 7082 if (DistToSrc >= 2 * MaxMemDepDistance) 7083 break; 7084 DistToSrc++; 7085 } 7086 } 7087 } 7088 BundleMember = BundleMember->NextInBundle; 7089 } 7090 if (InsertInReadyList && SD->isReady()) { 7091 ReadyInsts.push_back(SD); 7092 LLVM_DEBUG(dbgs() << "SLP: gets ready on update: " << *SD->Inst 7093 << "\n"); 7094 } 7095 } 7096 } 7097 7098 void BoUpSLP::BlockScheduling::resetSchedule() { 7099 assert(ScheduleStart && 7100 "tried to reset schedule on block which has not been scheduled"); 7101 for (Instruction *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) { 7102 doForAllOpcodes(I, [&](ScheduleData *SD) { 7103 assert(isInSchedulingRegion(SD) && 7104 "ScheduleData not in scheduling region"); 7105 SD->IsScheduled = false; 7106 SD->resetUnscheduledDeps(); 7107 }); 7108 } 7109 ReadyInsts.clear(); 7110 } 7111 7112 void BoUpSLP::scheduleBlock(BlockScheduling *BS) { 7113 if (!BS->ScheduleStart) 7114 return; 7115 7116 LLVM_DEBUG(dbgs() << "SLP: schedule block " << BS->BB->getName() << "\n"); 7117 7118 BS->resetSchedule(); 7119 7120 // For the real scheduling we use a more sophisticated ready-list: it is 7121 // sorted by the original instruction location. This lets the final schedule 7122 // be as close as possible to the original instruction order. 7123 struct ScheduleDataCompare { 7124 bool operator()(ScheduleData *SD1, ScheduleData *SD2) const { 7125 return SD2->SchedulingPriority < SD1->SchedulingPriority; 7126 } 7127 }; 7128 std::set<ScheduleData *, ScheduleDataCompare> ReadyInsts; 7129 7130 // Ensure that all dependency data is updated and fill the ready-list with 7131 // initial instructions. 7132 int Idx = 0; 7133 int NumToSchedule = 0; 7134 for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd; 7135 I = I->getNextNode()) { 7136 BS->doForAllOpcodes(I, [this, &Idx, &NumToSchedule, BS](ScheduleData *SD) { 7137 assert((isVectorLikeInstWithConstOps(SD->Inst) || 7138 SD->isPartOfBundle() == (getTreeEntry(SD->Inst) != nullptr)) && 7139 "scheduler and vectorizer bundle mismatch"); 7140 SD->FirstInBundle->SchedulingPriority = Idx++; 7141 if (SD->isSchedulingEntity()) { 7142 BS->calculateDependencies(SD, false, this); 7143 NumToSchedule++; 7144 } 7145 }); 7146 } 7147 BS->initialFillReadyList(ReadyInsts); 7148 7149 Instruction *LastScheduledInst = BS->ScheduleEnd; 7150 7151 // Do the "real" scheduling. 7152 while (!ReadyInsts.empty()) { 7153 ScheduleData *picked = *ReadyInsts.begin(); 7154 ReadyInsts.erase(ReadyInsts.begin()); 7155 7156 // Move the scheduled instruction(s) to their dedicated places, if not 7157 // there yet. 7158 ScheduleData *BundleMember = picked; 7159 while (BundleMember) { 7160 Instruction *pickedInst = BundleMember->Inst; 7161 if (pickedInst->getNextNode() != LastScheduledInst) { 7162 BS->BB->getInstList().remove(pickedInst); 7163 BS->BB->getInstList().insert(LastScheduledInst->getIterator(), 7164 pickedInst); 7165 } 7166 LastScheduledInst = pickedInst; 7167 BundleMember = BundleMember->NextInBundle; 7168 } 7169 7170 BS->schedule(picked, ReadyInsts); 7171 NumToSchedule--; 7172 } 7173 assert(NumToSchedule == 0 && "could not schedule all instructions"); 7174 7175 // Avoid duplicate scheduling of the block. 7176 BS->ScheduleStart = nullptr; 7177 } 7178 7179 unsigned BoUpSLP::getVectorElementSize(Value *V) { 7180 // If V is a store, just return the width of the stored value (or value 7181 // truncated just before storing) without traversing the expression tree. 7182 // This is the common case. 7183 if (auto *Store = dyn_cast<StoreInst>(V)) { 7184 if (auto *Trunc = dyn_cast<TruncInst>(Store->getValueOperand())) 7185 return DL->getTypeSizeInBits(Trunc->getSrcTy()); 7186 return DL->getTypeSizeInBits(Store->getValueOperand()->getType()); 7187 } 7188 7189 if (auto *IEI = dyn_cast<InsertElementInst>(V)) 7190 return getVectorElementSize(IEI->getOperand(1)); 7191 7192 auto E = InstrElementSize.find(V); 7193 if (E != InstrElementSize.end()) 7194 return E->second; 7195 7196 // If V is not a store, we can traverse the expression tree to find loads 7197 // that feed it. The type of the loaded value may indicate a more suitable 7198 // width than V's type. We want to base the vector element size on the width 7199 // of memory operations where possible. 7200 SmallVector<std::pair<Instruction *, BasicBlock *>, 16> Worklist; 7201 SmallPtrSet<Instruction *, 16> Visited; 7202 if (auto *I = dyn_cast<Instruction>(V)) { 7203 Worklist.emplace_back(I, I->getParent()); 7204 Visited.insert(I); 7205 } 7206 7207 // Traverse the expression tree in bottom-up order looking for loads. If we 7208 // encounter an instruction we don't yet handle, we give up. 7209 auto Width = 0u; 7210 while (!Worklist.empty()) { 7211 Instruction *I; 7212 BasicBlock *Parent; 7213 std::tie(I, Parent) = Worklist.pop_back_val(); 7214 7215 // We should only be looking at scalar instructions here. If the current 7216 // instruction has a vector type, skip. 7217 auto *Ty = I->getType(); 7218 if (isa<VectorType>(Ty)) 7219 continue; 7220 7221 // If the current instruction is a load, update MaxWidth to reflect the 7222 // width of the loaded value. 7223 if (isa<LoadInst>(I) || isa<ExtractElementInst>(I) || 7224 isa<ExtractValueInst>(I)) 7225 Width = std::max<unsigned>(Width, DL->getTypeSizeInBits(Ty)); 7226 7227 // Otherwise, we need to visit the operands of the instruction. We only 7228 // handle the interesting cases from buildTree here. If an operand is an 7229 // instruction we haven't yet visited and from the same basic block as the 7230 // user or the use is a PHI node, we add it to the worklist. 7231 else if (isa<PHINode>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) || 7232 isa<CmpInst>(I) || isa<SelectInst>(I) || isa<BinaryOperator>(I) || 7233 isa<UnaryOperator>(I)) { 7234 for (Use &U : I->operands()) 7235 if (auto *J = dyn_cast<Instruction>(U.get())) 7236 if (Visited.insert(J).second && 7237 (isa<PHINode>(I) || J->getParent() == Parent)) 7238 Worklist.emplace_back(J, J->getParent()); 7239 } else { 7240 break; 7241 } 7242 } 7243 7244 // If we didn't encounter a memory access in the expression tree, or if we 7245 // gave up for some reason, just return the width of V. Otherwise, return the 7246 // maximum width we found. 7247 if (!Width) { 7248 if (auto *CI = dyn_cast<CmpInst>(V)) 7249 V = CI->getOperand(0); 7250 Width = DL->getTypeSizeInBits(V->getType()); 7251 } 7252 7253 for (Instruction *I : Visited) 7254 InstrElementSize[I] = Width; 7255 7256 return Width; 7257 } 7258 7259 // Determine if a value V in a vectorizable expression Expr can be demoted to a 7260 // smaller type with a truncation. We collect the values that will be demoted 7261 // in ToDemote and additional roots that require investigating in Roots. 7262 static bool collectValuesToDemote(Value *V, SmallPtrSetImpl<Value *> &Expr, 7263 SmallVectorImpl<Value *> &ToDemote, 7264 SmallVectorImpl<Value *> &Roots) { 7265 // We can always demote constants. 7266 if (isa<Constant>(V)) { 7267 ToDemote.push_back(V); 7268 return true; 7269 } 7270 7271 // If the value is not an instruction in the expression with only one use, it 7272 // cannot be demoted. 7273 auto *I = dyn_cast<Instruction>(V); 7274 if (!I || !I->hasOneUse() || !Expr.count(I)) 7275 return false; 7276 7277 switch (I->getOpcode()) { 7278 7279 // We can always demote truncations and extensions. Since truncations can 7280 // seed additional demotion, we save the truncated value. 7281 case Instruction::Trunc: 7282 Roots.push_back(I->getOperand(0)); 7283 break; 7284 case Instruction::ZExt: 7285 case Instruction::SExt: 7286 if (isa<ExtractElementInst>(I->getOperand(0)) || 7287 isa<InsertElementInst>(I->getOperand(0))) 7288 return false; 7289 break; 7290 7291 // We can demote certain binary operations if we can demote both of their 7292 // operands. 7293 case Instruction::Add: 7294 case Instruction::Sub: 7295 case Instruction::Mul: 7296 case Instruction::And: 7297 case Instruction::Or: 7298 case Instruction::Xor: 7299 if (!collectValuesToDemote(I->getOperand(0), Expr, ToDemote, Roots) || 7300 !collectValuesToDemote(I->getOperand(1), Expr, ToDemote, Roots)) 7301 return false; 7302 break; 7303 7304 // We can demote selects if we can demote their true and false values. 7305 case Instruction::Select: { 7306 SelectInst *SI = cast<SelectInst>(I); 7307 if (!collectValuesToDemote(SI->getTrueValue(), Expr, ToDemote, Roots) || 7308 !collectValuesToDemote(SI->getFalseValue(), Expr, ToDemote, Roots)) 7309 return false; 7310 break; 7311 } 7312 7313 // We can demote phis if we can demote all their incoming operands. Note that 7314 // we don't need to worry about cycles since we ensure single use above. 7315 case Instruction::PHI: { 7316 PHINode *PN = cast<PHINode>(I); 7317 for (Value *IncValue : PN->incoming_values()) 7318 if (!collectValuesToDemote(IncValue, Expr, ToDemote, Roots)) 7319 return false; 7320 break; 7321 } 7322 7323 // Otherwise, conservatively give up. 7324 default: 7325 return false; 7326 } 7327 7328 // Record the value that we can demote. 7329 ToDemote.push_back(V); 7330 return true; 7331 } 7332 7333 void BoUpSLP::computeMinimumValueSizes() { 7334 // If there are no external uses, the expression tree must be rooted by a 7335 // store. We can't demote in-memory values, so there is nothing to do here. 7336 if (ExternalUses.empty()) 7337 return; 7338 7339 // We only attempt to truncate integer expressions. 7340 auto &TreeRoot = VectorizableTree[0]->Scalars; 7341 auto *TreeRootIT = dyn_cast<IntegerType>(TreeRoot[0]->getType()); 7342 if (!TreeRootIT) 7343 return; 7344 7345 // If the expression is not rooted by a store, these roots should have 7346 // external uses. We will rely on InstCombine to rewrite the expression in 7347 // the narrower type. However, InstCombine only rewrites single-use values. 7348 // This means that if a tree entry other than a root is used externally, it 7349 // must have multiple uses and InstCombine will not rewrite it. The code 7350 // below ensures that only the roots are used externally. 7351 SmallPtrSet<Value *, 32> Expr(TreeRoot.begin(), TreeRoot.end()); 7352 for (auto &EU : ExternalUses) 7353 if (!Expr.erase(EU.Scalar)) 7354 return; 7355 if (!Expr.empty()) 7356 return; 7357 7358 // Collect the scalar values of the vectorizable expression. We will use this 7359 // context to determine which values can be demoted. If we see a truncation, 7360 // we mark it as seeding another demotion. 7361 for (auto &EntryPtr : VectorizableTree) 7362 Expr.insert(EntryPtr->Scalars.begin(), EntryPtr->Scalars.end()); 7363 7364 // Ensure the roots of the vectorizable tree don't form a cycle. They must 7365 // have a single external user that is not in the vectorizable tree. 7366 for (auto *Root : TreeRoot) 7367 if (!Root->hasOneUse() || Expr.count(*Root->user_begin())) 7368 return; 7369 7370 // Conservatively determine if we can actually truncate the roots of the 7371 // expression. Collect the values that can be demoted in ToDemote and 7372 // additional roots that require investigating in Roots. 7373 SmallVector<Value *, 32> ToDemote; 7374 SmallVector<Value *, 4> Roots; 7375 for (auto *Root : TreeRoot) 7376 if (!collectValuesToDemote(Root, Expr, ToDemote, Roots)) 7377 return; 7378 7379 // The maximum bit width required to represent all the values that can be 7380 // demoted without loss of precision. It would be safe to truncate the roots 7381 // of the expression to this width. 7382 auto MaxBitWidth = 8u; 7383 7384 // We first check if all the bits of the roots are demanded. If they're not, 7385 // we can truncate the roots to this narrower type. 7386 for (auto *Root : TreeRoot) { 7387 auto Mask = DB->getDemandedBits(cast<Instruction>(Root)); 7388 MaxBitWidth = std::max<unsigned>( 7389 Mask.getBitWidth() - Mask.countLeadingZeros(), MaxBitWidth); 7390 } 7391 7392 // True if the roots can be zero-extended back to their original type, rather 7393 // than sign-extended. We know that if the leading bits are not demanded, we 7394 // can safely zero-extend. So we initialize IsKnownPositive to True. 7395 bool IsKnownPositive = true; 7396 7397 // If all the bits of the roots are demanded, we can try a little harder to 7398 // compute a narrower type. This can happen, for example, if the roots are 7399 // getelementptr indices. InstCombine promotes these indices to the pointer 7400 // width. Thus, all their bits are technically demanded even though the 7401 // address computation might be vectorized in a smaller type. 7402 // 7403 // We start by looking at each entry that can be demoted. We compute the 7404 // maximum bit width required to store the scalar by using ValueTracking to 7405 // compute the number of high-order bits we can truncate. 7406 if (MaxBitWidth == DL->getTypeSizeInBits(TreeRoot[0]->getType()) && 7407 llvm::all_of(TreeRoot, [](Value *R) { 7408 assert(R->hasOneUse() && "Root should have only one use!"); 7409 return isa<GetElementPtrInst>(R->user_back()); 7410 })) { 7411 MaxBitWidth = 8u; 7412 7413 // Determine if the sign bit of all the roots is known to be zero. If not, 7414 // IsKnownPositive is set to False. 7415 IsKnownPositive = llvm::all_of(TreeRoot, [&](Value *R) { 7416 KnownBits Known = computeKnownBits(R, *DL); 7417 return Known.isNonNegative(); 7418 }); 7419 7420 // Determine the maximum number of bits required to store the scalar 7421 // values. 7422 for (auto *Scalar : ToDemote) { 7423 auto NumSignBits = ComputeNumSignBits(Scalar, *DL, 0, AC, nullptr, DT); 7424 auto NumTypeBits = DL->getTypeSizeInBits(Scalar->getType()); 7425 MaxBitWidth = std::max<unsigned>(NumTypeBits - NumSignBits, MaxBitWidth); 7426 } 7427 7428 // If we can't prove that the sign bit is zero, we must add one to the 7429 // maximum bit width to account for the unknown sign bit. This preserves 7430 // the existing sign bit so we can safely sign-extend the root back to the 7431 // original type. Otherwise, if we know the sign bit is zero, we will 7432 // zero-extend the root instead. 7433 // 7434 // FIXME: This is somewhat suboptimal, as there will be cases where adding 7435 // one to the maximum bit width will yield a larger-than-necessary 7436 // type. In general, we need to add an extra bit only if we can't 7437 // prove that the upper bit of the original type is equal to the 7438 // upper bit of the proposed smaller type. If these two bits are the 7439 // same (either zero or one) we know that sign-extending from the 7440 // smaller type will result in the same value. Here, since we can't 7441 // yet prove this, we are just making the proposed smaller type 7442 // larger to ensure correctness. 7443 if (!IsKnownPositive) 7444 ++MaxBitWidth; 7445 } 7446 7447 // Round MaxBitWidth up to the next power-of-two. 7448 if (!isPowerOf2_64(MaxBitWidth)) 7449 MaxBitWidth = NextPowerOf2(MaxBitWidth); 7450 7451 // If the maximum bit width we compute is less than the with of the roots' 7452 // type, we can proceed with the narrowing. Otherwise, do nothing. 7453 if (MaxBitWidth >= TreeRootIT->getBitWidth()) 7454 return; 7455 7456 // If we can truncate the root, we must collect additional values that might 7457 // be demoted as a result. That is, those seeded by truncations we will 7458 // modify. 7459 while (!Roots.empty()) 7460 collectValuesToDemote(Roots.pop_back_val(), Expr, ToDemote, Roots); 7461 7462 // Finally, map the values we can demote to the maximum bit with we computed. 7463 for (auto *Scalar : ToDemote) 7464 MinBWs[Scalar] = std::make_pair(MaxBitWidth, !IsKnownPositive); 7465 } 7466 7467 namespace { 7468 7469 /// The SLPVectorizer Pass. 7470 struct SLPVectorizer : public FunctionPass { 7471 SLPVectorizerPass Impl; 7472 7473 /// Pass identification, replacement for typeid 7474 static char ID; 7475 7476 explicit SLPVectorizer() : FunctionPass(ID) { 7477 initializeSLPVectorizerPass(*PassRegistry::getPassRegistry()); 7478 } 7479 7480 bool doInitialization(Module &M) override { return false; } 7481 7482 bool runOnFunction(Function &F) override { 7483 if (skipFunction(F)) 7484 return false; 7485 7486 auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE(); 7487 auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F); 7488 auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>(); 7489 auto *TLI = TLIP ? &TLIP->getTLI(F) : nullptr; 7490 auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults(); 7491 auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 7492 auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 7493 auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F); 7494 auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits(); 7495 auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE(); 7496 7497 return Impl.runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE); 7498 } 7499 7500 void getAnalysisUsage(AnalysisUsage &AU) const override { 7501 FunctionPass::getAnalysisUsage(AU); 7502 AU.addRequired<AssumptionCacheTracker>(); 7503 AU.addRequired<ScalarEvolutionWrapperPass>(); 7504 AU.addRequired<AAResultsWrapperPass>(); 7505 AU.addRequired<TargetTransformInfoWrapperPass>(); 7506 AU.addRequired<LoopInfoWrapperPass>(); 7507 AU.addRequired<DominatorTreeWrapperPass>(); 7508 AU.addRequired<DemandedBitsWrapperPass>(); 7509 AU.addRequired<OptimizationRemarkEmitterWrapperPass>(); 7510 AU.addRequired<InjectTLIMappingsLegacy>(); 7511 AU.addPreserved<LoopInfoWrapperPass>(); 7512 AU.addPreserved<DominatorTreeWrapperPass>(); 7513 AU.addPreserved<AAResultsWrapperPass>(); 7514 AU.addPreserved<GlobalsAAWrapperPass>(); 7515 AU.setPreservesCFG(); 7516 } 7517 }; 7518 7519 } // end anonymous namespace 7520 7521 PreservedAnalyses SLPVectorizerPass::run(Function &F, FunctionAnalysisManager &AM) { 7522 auto *SE = &AM.getResult<ScalarEvolutionAnalysis>(F); 7523 auto *TTI = &AM.getResult<TargetIRAnalysis>(F); 7524 auto *TLI = AM.getCachedResult<TargetLibraryAnalysis>(F); 7525 auto *AA = &AM.getResult<AAManager>(F); 7526 auto *LI = &AM.getResult<LoopAnalysis>(F); 7527 auto *DT = &AM.getResult<DominatorTreeAnalysis>(F); 7528 auto *AC = &AM.getResult<AssumptionAnalysis>(F); 7529 auto *DB = &AM.getResult<DemandedBitsAnalysis>(F); 7530 auto *ORE = &AM.getResult<OptimizationRemarkEmitterAnalysis>(F); 7531 7532 bool Changed = runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE); 7533 if (!Changed) 7534 return PreservedAnalyses::all(); 7535 7536 PreservedAnalyses PA; 7537 PA.preserveSet<CFGAnalyses>(); 7538 return PA; 7539 } 7540 7541 bool SLPVectorizerPass::runImpl(Function &F, ScalarEvolution *SE_, 7542 TargetTransformInfo *TTI_, 7543 TargetLibraryInfo *TLI_, AAResults *AA_, 7544 LoopInfo *LI_, DominatorTree *DT_, 7545 AssumptionCache *AC_, DemandedBits *DB_, 7546 OptimizationRemarkEmitter *ORE_) { 7547 if (!RunSLPVectorization) 7548 return false; 7549 SE = SE_; 7550 TTI = TTI_; 7551 TLI = TLI_; 7552 AA = AA_; 7553 LI = LI_; 7554 DT = DT_; 7555 AC = AC_; 7556 DB = DB_; 7557 DL = &F.getParent()->getDataLayout(); 7558 7559 Stores.clear(); 7560 GEPs.clear(); 7561 bool Changed = false; 7562 7563 // If the target claims to have no vector registers don't attempt 7564 // vectorization. 7565 if (!TTI->getNumberOfRegisters(TTI->getRegisterClassForType(true))) 7566 return false; 7567 7568 // Don't vectorize when the attribute NoImplicitFloat is used. 7569 if (F.hasFnAttribute(Attribute::NoImplicitFloat)) 7570 return false; 7571 7572 LLVM_DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n"); 7573 7574 // Use the bottom up slp vectorizer to construct chains that start with 7575 // store instructions. 7576 BoUpSLP R(&F, SE, TTI, TLI, AA, LI, DT, AC, DB, DL, ORE_); 7577 7578 // A general note: the vectorizer must use BoUpSLP::eraseInstruction() to 7579 // delete instructions. 7580 7581 // Update DFS numbers now so that we can use them for ordering. 7582 DT->updateDFSNumbers(); 7583 7584 // Scan the blocks in the function in post order. 7585 for (auto BB : post_order(&F.getEntryBlock())) { 7586 collectSeedInstructions(BB); 7587 7588 // Vectorize trees that end at stores. 7589 if (!Stores.empty()) { 7590 LLVM_DEBUG(dbgs() << "SLP: Found stores for " << Stores.size() 7591 << " underlying objects.\n"); 7592 Changed |= vectorizeStoreChains(R); 7593 } 7594 7595 // Vectorize trees that end at reductions. 7596 Changed |= vectorizeChainsInBlock(BB, R); 7597 7598 // Vectorize the index computations of getelementptr instructions. This 7599 // is primarily intended to catch gather-like idioms ending at 7600 // non-consecutive loads. 7601 if (!GEPs.empty()) { 7602 LLVM_DEBUG(dbgs() << "SLP: Found GEPs for " << GEPs.size() 7603 << " underlying objects.\n"); 7604 Changed |= vectorizeGEPIndices(BB, R); 7605 } 7606 } 7607 7608 if (Changed) { 7609 R.optimizeGatherSequence(); 7610 LLVM_DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n"); 7611 } 7612 return Changed; 7613 } 7614 7615 bool SLPVectorizerPass::vectorizeStoreChain(ArrayRef<Value *> Chain, BoUpSLP &R, 7616 unsigned Idx) { 7617 LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << Chain.size() 7618 << "\n"); 7619 const unsigned Sz = R.getVectorElementSize(Chain[0]); 7620 const unsigned MinVF = R.getMinVecRegSize() / Sz; 7621 unsigned VF = Chain.size(); 7622 7623 if (!isPowerOf2_32(Sz) || !isPowerOf2_32(VF) || VF < 2 || VF < MinVF) 7624 return false; 7625 7626 LLVM_DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << Idx 7627 << "\n"); 7628 7629 R.buildTree(Chain); 7630 if (R.isTreeTinyAndNotFullyVectorizable()) 7631 return false; 7632 if (R.isLoadCombineCandidate()) 7633 return false; 7634 R.reorderTopToBottom(); 7635 R.reorderBottomToTop(); 7636 R.buildExternalUses(); 7637 7638 R.computeMinimumValueSizes(); 7639 7640 InstructionCost Cost = R.getTreeCost(); 7641 7642 LLVM_DEBUG(dbgs() << "SLP: Found cost = " << Cost << " for VF =" << VF << "\n"); 7643 if (Cost < -SLPCostThreshold) { 7644 LLVM_DEBUG(dbgs() << "SLP: Decided to vectorize cost = " << Cost << "\n"); 7645 7646 using namespace ore; 7647 7648 R.getORE()->emit(OptimizationRemark(SV_NAME, "StoresVectorized", 7649 cast<StoreInst>(Chain[0])) 7650 << "Stores SLP vectorized with cost " << NV("Cost", Cost) 7651 << " and with tree size " 7652 << NV("TreeSize", R.getTreeSize())); 7653 7654 R.vectorizeTree(); 7655 return true; 7656 } 7657 7658 return false; 7659 } 7660 7661 bool SLPVectorizerPass::vectorizeStores(ArrayRef<StoreInst *> Stores, 7662 BoUpSLP &R) { 7663 // We may run into multiple chains that merge into a single chain. We mark the 7664 // stores that we vectorized so that we don't visit the same store twice. 7665 BoUpSLP::ValueSet VectorizedStores; 7666 bool Changed = false; 7667 7668 int E = Stores.size(); 7669 SmallBitVector Tails(E, false); 7670 int MaxIter = MaxStoreLookup.getValue(); 7671 SmallVector<std::pair<int, int>, 16> ConsecutiveChain( 7672 E, std::make_pair(E, INT_MAX)); 7673 SmallVector<SmallBitVector, 4> CheckedPairs(E, SmallBitVector(E, false)); 7674 int IterCnt; 7675 auto &&FindConsecutiveAccess = [this, &Stores, &Tails, &IterCnt, MaxIter, 7676 &CheckedPairs, 7677 &ConsecutiveChain](int K, int Idx) { 7678 if (IterCnt >= MaxIter) 7679 return true; 7680 if (CheckedPairs[Idx].test(K)) 7681 return ConsecutiveChain[K].second == 1 && 7682 ConsecutiveChain[K].first == Idx; 7683 ++IterCnt; 7684 CheckedPairs[Idx].set(K); 7685 CheckedPairs[K].set(Idx); 7686 Optional<int> Diff = getPointersDiff( 7687 Stores[K]->getValueOperand()->getType(), Stores[K]->getPointerOperand(), 7688 Stores[Idx]->getValueOperand()->getType(), 7689 Stores[Idx]->getPointerOperand(), *DL, *SE, /*StrictCheck=*/true); 7690 if (!Diff || *Diff == 0) 7691 return false; 7692 int Val = *Diff; 7693 if (Val < 0) { 7694 if (ConsecutiveChain[Idx].second > -Val) { 7695 Tails.set(K); 7696 ConsecutiveChain[Idx] = std::make_pair(K, -Val); 7697 } 7698 return false; 7699 } 7700 if (ConsecutiveChain[K].second <= Val) 7701 return false; 7702 7703 Tails.set(Idx); 7704 ConsecutiveChain[K] = std::make_pair(Idx, Val); 7705 return Val == 1; 7706 }; 7707 // Do a quadratic search on all of the given stores in reverse order and find 7708 // all of the pairs of stores that follow each other. 7709 for (int Idx = E - 1; Idx >= 0; --Idx) { 7710 // If a store has multiple consecutive store candidates, search according 7711 // to the sequence: Idx-1, Idx+1, Idx-2, Idx+2, ... 7712 // This is because usually pairing with immediate succeeding or preceding 7713 // candidate create the best chance to find slp vectorization opportunity. 7714 const int MaxLookDepth = std::max(E - Idx, Idx + 1); 7715 IterCnt = 0; 7716 for (int Offset = 1, F = MaxLookDepth; Offset < F; ++Offset) 7717 if ((Idx >= Offset && FindConsecutiveAccess(Idx - Offset, Idx)) || 7718 (Idx + Offset < E && FindConsecutiveAccess(Idx + Offset, Idx))) 7719 break; 7720 } 7721 7722 // Tracks if we tried to vectorize stores starting from the given tail 7723 // already. 7724 SmallBitVector TriedTails(E, false); 7725 // For stores that start but don't end a link in the chain: 7726 for (int Cnt = E; Cnt > 0; --Cnt) { 7727 int I = Cnt - 1; 7728 if (ConsecutiveChain[I].first == E || Tails.test(I)) 7729 continue; 7730 // We found a store instr that starts a chain. Now follow the chain and try 7731 // to vectorize it. 7732 BoUpSLP::ValueList Operands; 7733 // Collect the chain into a list. 7734 while (I != E && !VectorizedStores.count(Stores[I])) { 7735 Operands.push_back(Stores[I]); 7736 Tails.set(I); 7737 if (ConsecutiveChain[I].second != 1) { 7738 // Mark the new end in the chain and go back, if required. It might be 7739 // required if the original stores come in reversed order, for example. 7740 if (ConsecutiveChain[I].first != E && 7741 Tails.test(ConsecutiveChain[I].first) && !TriedTails.test(I) && 7742 !VectorizedStores.count(Stores[ConsecutiveChain[I].first])) { 7743 TriedTails.set(I); 7744 Tails.reset(ConsecutiveChain[I].first); 7745 if (Cnt < ConsecutiveChain[I].first + 2) 7746 Cnt = ConsecutiveChain[I].first + 2; 7747 } 7748 break; 7749 } 7750 // Move to the next value in the chain. 7751 I = ConsecutiveChain[I].first; 7752 } 7753 assert(!Operands.empty() && "Expected non-empty list of stores."); 7754 7755 unsigned MaxVecRegSize = R.getMaxVecRegSize(); 7756 unsigned EltSize = R.getVectorElementSize(Operands[0]); 7757 unsigned MaxElts = llvm::PowerOf2Floor(MaxVecRegSize / EltSize); 7758 7759 unsigned MinVF = R.getMinVF(EltSize); 7760 unsigned MaxVF = std::min(R.getMaximumVF(EltSize, Instruction::Store), 7761 MaxElts); 7762 7763 // FIXME: Is division-by-2 the correct step? Should we assert that the 7764 // register size is a power-of-2? 7765 unsigned StartIdx = 0; 7766 for (unsigned Size = MaxVF; Size >= MinVF; Size /= 2) { 7767 for (unsigned Cnt = StartIdx, E = Operands.size(); Cnt + Size <= E;) { 7768 ArrayRef<Value *> Slice = makeArrayRef(Operands).slice(Cnt, Size); 7769 if (!VectorizedStores.count(Slice.front()) && 7770 !VectorizedStores.count(Slice.back()) && 7771 vectorizeStoreChain(Slice, R, Cnt)) { 7772 // Mark the vectorized stores so that we don't vectorize them again. 7773 VectorizedStores.insert(Slice.begin(), Slice.end()); 7774 Changed = true; 7775 // If we vectorized initial block, no need to try to vectorize it 7776 // again. 7777 if (Cnt == StartIdx) 7778 StartIdx += Size; 7779 Cnt += Size; 7780 continue; 7781 } 7782 ++Cnt; 7783 } 7784 // Check if the whole array was vectorized already - exit. 7785 if (StartIdx >= Operands.size()) 7786 break; 7787 } 7788 } 7789 7790 return Changed; 7791 } 7792 7793 void SLPVectorizerPass::collectSeedInstructions(BasicBlock *BB) { 7794 // Initialize the collections. We will make a single pass over the block. 7795 Stores.clear(); 7796 GEPs.clear(); 7797 7798 // Visit the store and getelementptr instructions in BB and organize them in 7799 // Stores and GEPs according to the underlying objects of their pointer 7800 // operands. 7801 for (Instruction &I : *BB) { 7802 // Ignore store instructions that are volatile or have a pointer operand 7803 // that doesn't point to a scalar type. 7804 if (auto *SI = dyn_cast<StoreInst>(&I)) { 7805 if (!SI->isSimple()) 7806 continue; 7807 if (!isValidElementType(SI->getValueOperand()->getType())) 7808 continue; 7809 Stores[getUnderlyingObject(SI->getPointerOperand())].push_back(SI); 7810 } 7811 7812 // Ignore getelementptr instructions that have more than one index, a 7813 // constant index, or a pointer operand that doesn't point to a scalar 7814 // type. 7815 else if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) { 7816 auto Idx = GEP->idx_begin()->get(); 7817 if (GEP->getNumIndices() > 1 || isa<Constant>(Idx)) 7818 continue; 7819 if (!isValidElementType(Idx->getType())) 7820 continue; 7821 if (GEP->getType()->isVectorTy()) 7822 continue; 7823 GEPs[GEP->getPointerOperand()].push_back(GEP); 7824 } 7825 } 7826 } 7827 7828 bool SLPVectorizerPass::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) { 7829 if (!A || !B) 7830 return false; 7831 Value *VL[] = {A, B}; 7832 return tryToVectorizeList(VL, R); 7833 } 7834 7835 bool SLPVectorizerPass::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R, 7836 bool LimitForRegisterSize) { 7837 if (VL.size() < 2) 7838 return false; 7839 7840 LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize a list of length = " 7841 << VL.size() << ".\n"); 7842 7843 // Check that all of the parts are instructions of the same type, 7844 // we permit an alternate opcode via InstructionsState. 7845 InstructionsState S = getSameOpcode(VL); 7846 if (!S.getOpcode()) 7847 return false; 7848 7849 Instruction *I0 = cast<Instruction>(S.OpValue); 7850 // Make sure invalid types (including vector type) are rejected before 7851 // determining vectorization factor for scalar instructions. 7852 for (Value *V : VL) { 7853 Type *Ty = V->getType(); 7854 if (!isa<InsertElementInst>(V) && !isValidElementType(Ty)) { 7855 // NOTE: the following will give user internal llvm type name, which may 7856 // not be useful. 7857 R.getORE()->emit([&]() { 7858 std::string type_str; 7859 llvm::raw_string_ostream rso(type_str); 7860 Ty->print(rso); 7861 return OptimizationRemarkMissed(SV_NAME, "UnsupportedType", I0) 7862 << "Cannot SLP vectorize list: type " 7863 << rso.str() + " is unsupported by vectorizer"; 7864 }); 7865 return false; 7866 } 7867 } 7868 7869 unsigned Sz = R.getVectorElementSize(I0); 7870 unsigned MinVF = R.getMinVF(Sz); 7871 unsigned MaxVF = std::max<unsigned>(PowerOf2Floor(VL.size()), MinVF); 7872 MaxVF = std::min(R.getMaximumVF(Sz, S.getOpcode()), MaxVF); 7873 if (MaxVF < 2) { 7874 R.getORE()->emit([&]() { 7875 return OptimizationRemarkMissed(SV_NAME, "SmallVF", I0) 7876 << "Cannot SLP vectorize list: vectorization factor " 7877 << "less than 2 is not supported"; 7878 }); 7879 return false; 7880 } 7881 7882 bool Changed = false; 7883 bool CandidateFound = false; 7884 InstructionCost MinCost = SLPCostThreshold.getValue(); 7885 Type *ScalarTy = VL[0]->getType(); 7886 if (auto *IE = dyn_cast<InsertElementInst>(VL[0])) 7887 ScalarTy = IE->getOperand(1)->getType(); 7888 7889 unsigned NextInst = 0, MaxInst = VL.size(); 7890 for (unsigned VF = MaxVF; NextInst + 1 < MaxInst && VF >= MinVF; VF /= 2) { 7891 // No actual vectorization should happen, if number of parts is the same as 7892 // provided vectorization factor (i.e. the scalar type is used for vector 7893 // code during codegen). 7894 auto *VecTy = FixedVectorType::get(ScalarTy, VF); 7895 if (TTI->getNumberOfParts(VecTy) == VF) 7896 continue; 7897 for (unsigned I = NextInst; I < MaxInst; ++I) { 7898 unsigned OpsWidth = 0; 7899 7900 if (I + VF > MaxInst) 7901 OpsWidth = MaxInst - I; 7902 else 7903 OpsWidth = VF; 7904 7905 if (!isPowerOf2_32(OpsWidth)) 7906 continue; 7907 7908 if ((LimitForRegisterSize && OpsWidth < MaxVF) || 7909 (VF > MinVF && OpsWidth <= VF / 2) || (VF == MinVF && OpsWidth < 2)) 7910 break; 7911 7912 ArrayRef<Value *> Ops = VL.slice(I, OpsWidth); 7913 // Check that a previous iteration of this loop did not delete the Value. 7914 if (llvm::any_of(Ops, [&R](Value *V) { 7915 auto *I = dyn_cast<Instruction>(V); 7916 return I && R.isDeleted(I); 7917 })) 7918 continue; 7919 7920 LLVM_DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth << " operations " 7921 << "\n"); 7922 7923 R.buildTree(Ops); 7924 if (R.isTreeTinyAndNotFullyVectorizable()) 7925 continue; 7926 R.reorderTopToBottom(); 7927 R.reorderBottomToTop(); 7928 R.buildExternalUses(); 7929 7930 R.computeMinimumValueSizes(); 7931 InstructionCost Cost = R.getTreeCost(); 7932 CandidateFound = true; 7933 MinCost = std::min(MinCost, Cost); 7934 7935 if (Cost < -SLPCostThreshold) { 7936 LLVM_DEBUG(dbgs() << "SLP: Vectorizing list at cost:" << Cost << ".\n"); 7937 R.getORE()->emit(OptimizationRemark(SV_NAME, "VectorizedList", 7938 cast<Instruction>(Ops[0])) 7939 << "SLP vectorized with cost " << ore::NV("Cost", Cost) 7940 << " and with tree size " 7941 << ore::NV("TreeSize", R.getTreeSize())); 7942 7943 R.vectorizeTree(); 7944 // Move to the next bundle. 7945 I += VF - 1; 7946 NextInst = I + 1; 7947 Changed = true; 7948 } 7949 } 7950 } 7951 7952 if (!Changed && CandidateFound) { 7953 R.getORE()->emit([&]() { 7954 return OptimizationRemarkMissed(SV_NAME, "NotBeneficial", I0) 7955 << "List vectorization was possible but not beneficial with cost " 7956 << ore::NV("Cost", MinCost) << " >= " 7957 << ore::NV("Treshold", -SLPCostThreshold); 7958 }); 7959 } else if (!Changed) { 7960 R.getORE()->emit([&]() { 7961 return OptimizationRemarkMissed(SV_NAME, "NotPossible", I0) 7962 << "Cannot SLP vectorize list: vectorization was impossible" 7963 << " with available vectorization factors"; 7964 }); 7965 } 7966 return Changed; 7967 } 7968 7969 bool SLPVectorizerPass::tryToVectorize(Instruction *I, BoUpSLP &R) { 7970 if (!I) 7971 return false; 7972 7973 if (!isa<BinaryOperator>(I) && !isa<CmpInst>(I)) 7974 return false; 7975 7976 Value *P = I->getParent(); 7977 7978 // Vectorize in current basic block only. 7979 auto *Op0 = dyn_cast<Instruction>(I->getOperand(0)); 7980 auto *Op1 = dyn_cast<Instruction>(I->getOperand(1)); 7981 if (!Op0 || !Op1 || Op0->getParent() != P || Op1->getParent() != P) 7982 return false; 7983 7984 // Try to vectorize V. 7985 if (tryToVectorizePair(Op0, Op1, R)) 7986 return true; 7987 7988 auto *A = dyn_cast<BinaryOperator>(Op0); 7989 auto *B = dyn_cast<BinaryOperator>(Op1); 7990 // Try to skip B. 7991 if (B && B->hasOneUse()) { 7992 auto *B0 = dyn_cast<BinaryOperator>(B->getOperand(0)); 7993 auto *B1 = dyn_cast<BinaryOperator>(B->getOperand(1)); 7994 if (B0 && B0->getParent() == P && tryToVectorizePair(A, B0, R)) 7995 return true; 7996 if (B1 && B1->getParent() == P && tryToVectorizePair(A, B1, R)) 7997 return true; 7998 } 7999 8000 // Try to skip A. 8001 if (A && A->hasOneUse()) { 8002 auto *A0 = dyn_cast<BinaryOperator>(A->getOperand(0)); 8003 auto *A1 = dyn_cast<BinaryOperator>(A->getOperand(1)); 8004 if (A0 && A0->getParent() == P && tryToVectorizePair(A0, B, R)) 8005 return true; 8006 if (A1 && A1->getParent() == P && tryToVectorizePair(A1, B, R)) 8007 return true; 8008 } 8009 return false; 8010 } 8011 8012 namespace { 8013 8014 /// Model horizontal reductions. 8015 /// 8016 /// A horizontal reduction is a tree of reduction instructions that has values 8017 /// that can be put into a vector as its leaves. For example: 8018 /// 8019 /// mul mul mul mul 8020 /// \ / \ / 8021 /// + + 8022 /// \ / 8023 /// + 8024 /// This tree has "mul" as its leaf values and "+" as its reduction 8025 /// instructions. A reduction can feed into a store or a binary operation 8026 /// feeding a phi. 8027 /// ... 8028 /// \ / 8029 /// + 8030 /// | 8031 /// phi += 8032 /// 8033 /// Or: 8034 /// ... 8035 /// \ / 8036 /// + 8037 /// | 8038 /// *p = 8039 /// 8040 class HorizontalReduction { 8041 using ReductionOpsType = SmallVector<Value *, 16>; 8042 using ReductionOpsListType = SmallVector<ReductionOpsType, 2>; 8043 ReductionOpsListType ReductionOps; 8044 SmallVector<Value *, 32> ReducedVals; 8045 // Use map vector to make stable output. 8046 MapVector<Instruction *, Value *> ExtraArgs; 8047 WeakTrackingVH ReductionRoot; 8048 /// The type of reduction operation. 8049 RecurKind RdxKind; 8050 8051 const unsigned INVALID_OPERAND_INDEX = std::numeric_limits<unsigned>::max(); 8052 8053 static bool isCmpSelMinMax(Instruction *I) { 8054 return match(I, m_Select(m_Cmp(), m_Value(), m_Value())) && 8055 RecurrenceDescriptor::isMinMaxRecurrenceKind(getRdxKind(I)); 8056 } 8057 8058 // And/or are potentially poison-safe logical patterns like: 8059 // select x, y, false 8060 // select x, true, y 8061 static bool isBoolLogicOp(Instruction *I) { 8062 return match(I, m_LogicalAnd(m_Value(), m_Value())) || 8063 match(I, m_LogicalOr(m_Value(), m_Value())); 8064 } 8065 8066 /// Checks if instruction is associative and can be vectorized. 8067 static bool isVectorizable(RecurKind Kind, Instruction *I) { 8068 if (Kind == RecurKind::None) 8069 return false; 8070 8071 // Integer ops that map to select instructions or intrinsics are fine. 8072 if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(Kind) || 8073 isBoolLogicOp(I)) 8074 return true; 8075 8076 if (Kind == RecurKind::FMax || Kind == RecurKind::FMin) { 8077 // FP min/max are associative except for NaN and -0.0. We do not 8078 // have to rule out -0.0 here because the intrinsic semantics do not 8079 // specify a fixed result for it. 8080 return I->getFastMathFlags().noNaNs(); 8081 } 8082 8083 return I->isAssociative(); 8084 } 8085 8086 static Value *getRdxOperand(Instruction *I, unsigned Index) { 8087 // Poison-safe 'or' takes the form: select X, true, Y 8088 // To make that work with the normal operand processing, we skip the 8089 // true value operand. 8090 // TODO: Change the code and data structures to handle this without a hack. 8091 if (getRdxKind(I) == RecurKind::Or && isa<SelectInst>(I) && Index == 1) 8092 return I->getOperand(2); 8093 return I->getOperand(Index); 8094 } 8095 8096 /// Checks if the ParentStackElem.first should be marked as a reduction 8097 /// operation with an extra argument or as extra argument itself. 8098 void markExtraArg(std::pair<Instruction *, unsigned> &ParentStackElem, 8099 Value *ExtraArg) { 8100 if (ExtraArgs.count(ParentStackElem.first)) { 8101 ExtraArgs[ParentStackElem.first] = nullptr; 8102 // We ran into something like: 8103 // ParentStackElem.first = ExtraArgs[ParentStackElem.first] + ExtraArg. 8104 // The whole ParentStackElem.first should be considered as an extra value 8105 // in this case. 8106 // Do not perform analysis of remaining operands of ParentStackElem.first 8107 // instruction, this whole instruction is an extra argument. 8108 ParentStackElem.second = INVALID_OPERAND_INDEX; 8109 } else { 8110 // We ran into something like: 8111 // ParentStackElem.first += ... + ExtraArg + ... 8112 ExtraArgs[ParentStackElem.first] = ExtraArg; 8113 } 8114 } 8115 8116 /// Creates reduction operation with the current opcode. 8117 static Value *createOp(IRBuilder<> &Builder, RecurKind Kind, Value *LHS, 8118 Value *RHS, const Twine &Name, bool UseSelect) { 8119 unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(Kind); 8120 switch (Kind) { 8121 case RecurKind::Or: 8122 if (UseSelect && 8123 LHS->getType() == CmpInst::makeCmpResultType(LHS->getType())) 8124 return Builder.CreateSelect(LHS, Builder.getTrue(), RHS, Name); 8125 return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS, 8126 Name); 8127 case RecurKind::And: 8128 if (UseSelect && 8129 LHS->getType() == CmpInst::makeCmpResultType(LHS->getType())) 8130 return Builder.CreateSelect(LHS, RHS, Builder.getFalse(), Name); 8131 return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS, 8132 Name); 8133 case RecurKind::Add: 8134 case RecurKind::Mul: 8135 case RecurKind::Xor: 8136 case RecurKind::FAdd: 8137 case RecurKind::FMul: 8138 return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS, 8139 Name); 8140 case RecurKind::FMax: 8141 return Builder.CreateBinaryIntrinsic(Intrinsic::maxnum, LHS, RHS); 8142 case RecurKind::FMin: 8143 return Builder.CreateBinaryIntrinsic(Intrinsic::minnum, LHS, RHS); 8144 case RecurKind::SMax: 8145 if (UseSelect) { 8146 Value *Cmp = Builder.CreateICmpSGT(LHS, RHS, Name); 8147 return Builder.CreateSelect(Cmp, LHS, RHS, Name); 8148 } 8149 return Builder.CreateBinaryIntrinsic(Intrinsic::smax, LHS, RHS); 8150 case RecurKind::SMin: 8151 if (UseSelect) { 8152 Value *Cmp = Builder.CreateICmpSLT(LHS, RHS, Name); 8153 return Builder.CreateSelect(Cmp, LHS, RHS, Name); 8154 } 8155 return Builder.CreateBinaryIntrinsic(Intrinsic::smin, LHS, RHS); 8156 case RecurKind::UMax: 8157 if (UseSelect) { 8158 Value *Cmp = Builder.CreateICmpUGT(LHS, RHS, Name); 8159 return Builder.CreateSelect(Cmp, LHS, RHS, Name); 8160 } 8161 return Builder.CreateBinaryIntrinsic(Intrinsic::umax, LHS, RHS); 8162 case RecurKind::UMin: 8163 if (UseSelect) { 8164 Value *Cmp = Builder.CreateICmpULT(LHS, RHS, Name); 8165 return Builder.CreateSelect(Cmp, LHS, RHS, Name); 8166 } 8167 return Builder.CreateBinaryIntrinsic(Intrinsic::umin, LHS, RHS); 8168 default: 8169 llvm_unreachable("Unknown reduction operation."); 8170 } 8171 } 8172 8173 /// Creates reduction operation with the current opcode with the IR flags 8174 /// from \p ReductionOps. 8175 static Value *createOp(IRBuilder<> &Builder, RecurKind RdxKind, Value *LHS, 8176 Value *RHS, const Twine &Name, 8177 const ReductionOpsListType &ReductionOps) { 8178 bool UseSelect = ReductionOps.size() == 2 || 8179 // Logical or/and. 8180 (ReductionOps.size() == 1 && 8181 isa<SelectInst>(ReductionOps.front().front())); 8182 assert((!UseSelect || ReductionOps.size() != 2 || 8183 isa<SelectInst>(ReductionOps[1][0])) && 8184 "Expected cmp + select pairs for reduction"); 8185 Value *Op = createOp(Builder, RdxKind, LHS, RHS, Name, UseSelect); 8186 if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(RdxKind)) { 8187 if (auto *Sel = dyn_cast<SelectInst>(Op)) { 8188 propagateIRFlags(Sel->getCondition(), ReductionOps[0]); 8189 propagateIRFlags(Op, ReductionOps[1]); 8190 return Op; 8191 } 8192 } 8193 propagateIRFlags(Op, ReductionOps[0]); 8194 return Op; 8195 } 8196 8197 /// Creates reduction operation with the current opcode with the IR flags 8198 /// from \p I. 8199 static Value *createOp(IRBuilder<> &Builder, RecurKind RdxKind, Value *LHS, 8200 Value *RHS, const Twine &Name, Instruction *I) { 8201 auto *SelI = dyn_cast<SelectInst>(I); 8202 Value *Op = createOp(Builder, RdxKind, LHS, RHS, Name, SelI != nullptr); 8203 if (SelI && RecurrenceDescriptor::isIntMinMaxRecurrenceKind(RdxKind)) { 8204 if (auto *Sel = dyn_cast<SelectInst>(Op)) 8205 propagateIRFlags(Sel->getCondition(), SelI->getCondition()); 8206 } 8207 propagateIRFlags(Op, I); 8208 return Op; 8209 } 8210 8211 static RecurKind getRdxKind(Instruction *I) { 8212 assert(I && "Expected instruction for reduction matching"); 8213 TargetTransformInfo::ReductionFlags RdxFlags; 8214 if (match(I, m_Add(m_Value(), m_Value()))) 8215 return RecurKind::Add; 8216 if (match(I, m_Mul(m_Value(), m_Value()))) 8217 return RecurKind::Mul; 8218 if (match(I, m_And(m_Value(), m_Value())) || 8219 match(I, m_LogicalAnd(m_Value(), m_Value()))) 8220 return RecurKind::And; 8221 if (match(I, m_Or(m_Value(), m_Value())) || 8222 match(I, m_LogicalOr(m_Value(), m_Value()))) 8223 return RecurKind::Or; 8224 if (match(I, m_Xor(m_Value(), m_Value()))) 8225 return RecurKind::Xor; 8226 if (match(I, m_FAdd(m_Value(), m_Value()))) 8227 return RecurKind::FAdd; 8228 if (match(I, m_FMul(m_Value(), m_Value()))) 8229 return RecurKind::FMul; 8230 8231 if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(), m_Value()))) 8232 return RecurKind::FMax; 8233 if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(), m_Value()))) 8234 return RecurKind::FMin; 8235 8236 // This matches either cmp+select or intrinsics. SLP is expected to handle 8237 // either form. 8238 // TODO: If we are canonicalizing to intrinsics, we can remove several 8239 // special-case paths that deal with selects. 8240 if (match(I, m_SMax(m_Value(), m_Value()))) 8241 return RecurKind::SMax; 8242 if (match(I, m_SMin(m_Value(), m_Value()))) 8243 return RecurKind::SMin; 8244 if (match(I, m_UMax(m_Value(), m_Value()))) 8245 return RecurKind::UMax; 8246 if (match(I, m_UMin(m_Value(), m_Value()))) 8247 return RecurKind::UMin; 8248 8249 if (auto *Select = dyn_cast<SelectInst>(I)) { 8250 // Try harder: look for min/max pattern based on instructions producing 8251 // same values such as: select ((cmp Inst1, Inst2), Inst1, Inst2). 8252 // During the intermediate stages of SLP, it's very common to have 8253 // pattern like this (since optimizeGatherSequence is run only once 8254 // at the end): 8255 // %1 = extractelement <2 x i32> %a, i32 0 8256 // %2 = extractelement <2 x i32> %a, i32 1 8257 // %cond = icmp sgt i32 %1, %2 8258 // %3 = extractelement <2 x i32> %a, i32 0 8259 // %4 = extractelement <2 x i32> %a, i32 1 8260 // %select = select i1 %cond, i32 %3, i32 %4 8261 CmpInst::Predicate Pred; 8262 Instruction *L1; 8263 Instruction *L2; 8264 8265 Value *LHS = Select->getTrueValue(); 8266 Value *RHS = Select->getFalseValue(); 8267 Value *Cond = Select->getCondition(); 8268 8269 // TODO: Support inverse predicates. 8270 if (match(Cond, m_Cmp(Pred, m_Specific(LHS), m_Instruction(L2)))) { 8271 if (!isa<ExtractElementInst>(RHS) || 8272 !L2->isIdenticalTo(cast<Instruction>(RHS))) 8273 return RecurKind::None; 8274 } else if (match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Specific(RHS)))) { 8275 if (!isa<ExtractElementInst>(LHS) || 8276 !L1->isIdenticalTo(cast<Instruction>(LHS))) 8277 return RecurKind::None; 8278 } else { 8279 if (!isa<ExtractElementInst>(LHS) || !isa<ExtractElementInst>(RHS)) 8280 return RecurKind::None; 8281 if (!match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Instruction(L2))) || 8282 !L1->isIdenticalTo(cast<Instruction>(LHS)) || 8283 !L2->isIdenticalTo(cast<Instruction>(RHS))) 8284 return RecurKind::None; 8285 } 8286 8287 TargetTransformInfo::ReductionFlags RdxFlags; 8288 switch (Pred) { 8289 default: 8290 return RecurKind::None; 8291 case CmpInst::ICMP_SGT: 8292 case CmpInst::ICMP_SGE: 8293 return RecurKind::SMax; 8294 case CmpInst::ICMP_SLT: 8295 case CmpInst::ICMP_SLE: 8296 return RecurKind::SMin; 8297 case CmpInst::ICMP_UGT: 8298 case CmpInst::ICMP_UGE: 8299 return RecurKind::UMax; 8300 case CmpInst::ICMP_ULT: 8301 case CmpInst::ICMP_ULE: 8302 return RecurKind::UMin; 8303 } 8304 } 8305 return RecurKind::None; 8306 } 8307 8308 /// Get the index of the first operand. 8309 static unsigned getFirstOperandIndex(Instruction *I) { 8310 return isCmpSelMinMax(I) ? 1 : 0; 8311 } 8312 8313 /// Total number of operands in the reduction operation. 8314 static unsigned getNumberOfOperands(Instruction *I) { 8315 return isCmpSelMinMax(I) ? 3 : 2; 8316 } 8317 8318 /// Checks if the instruction is in basic block \p BB. 8319 /// For a cmp+sel min/max reduction check that both ops are in \p BB. 8320 static bool hasSameParent(Instruction *I, BasicBlock *BB) { 8321 if (isCmpSelMinMax(I) || (isBoolLogicOp(I) && isa<SelectInst>(I))) { 8322 auto *Sel = cast<SelectInst>(I); 8323 auto *Cmp = dyn_cast<Instruction>(Sel->getCondition()); 8324 return Sel->getParent() == BB && Cmp && Cmp->getParent() == BB; 8325 } 8326 return I->getParent() == BB; 8327 } 8328 8329 /// Expected number of uses for reduction operations/reduced values. 8330 static bool hasRequiredNumberOfUses(bool IsCmpSelMinMax, Instruction *I) { 8331 if (IsCmpSelMinMax) { 8332 // SelectInst must be used twice while the condition op must have single 8333 // use only. 8334 if (auto *Sel = dyn_cast<SelectInst>(I)) 8335 return Sel->hasNUses(2) && Sel->getCondition()->hasOneUse(); 8336 return I->hasNUses(2); 8337 } 8338 8339 // Arithmetic reduction operation must be used once only. 8340 return I->hasOneUse(); 8341 } 8342 8343 /// Initializes the list of reduction operations. 8344 void initReductionOps(Instruction *I) { 8345 if (isCmpSelMinMax(I)) 8346 ReductionOps.assign(2, ReductionOpsType()); 8347 else 8348 ReductionOps.assign(1, ReductionOpsType()); 8349 } 8350 8351 /// Add all reduction operations for the reduction instruction \p I. 8352 void addReductionOps(Instruction *I) { 8353 if (isCmpSelMinMax(I)) { 8354 ReductionOps[0].emplace_back(cast<SelectInst>(I)->getCondition()); 8355 ReductionOps[1].emplace_back(I); 8356 } else { 8357 ReductionOps[0].emplace_back(I); 8358 } 8359 } 8360 8361 static Value *getLHS(RecurKind Kind, Instruction *I) { 8362 if (Kind == RecurKind::None) 8363 return nullptr; 8364 return I->getOperand(getFirstOperandIndex(I)); 8365 } 8366 static Value *getRHS(RecurKind Kind, Instruction *I) { 8367 if (Kind == RecurKind::None) 8368 return nullptr; 8369 return I->getOperand(getFirstOperandIndex(I) + 1); 8370 } 8371 8372 public: 8373 HorizontalReduction() = default; 8374 8375 /// Try to find a reduction tree. 8376 bool matchAssociativeReduction(PHINode *Phi, Instruction *Inst) { 8377 assert((!Phi || is_contained(Phi->operands(), Inst)) && 8378 "Phi needs to use the binary operator"); 8379 assert((isa<BinaryOperator>(Inst) || isa<SelectInst>(Inst) || 8380 isa<IntrinsicInst>(Inst)) && 8381 "Expected binop, select, or intrinsic for reduction matching"); 8382 RdxKind = getRdxKind(Inst); 8383 8384 // We could have a initial reductions that is not an add. 8385 // r *= v1 + v2 + v3 + v4 8386 // In such a case start looking for a tree rooted in the first '+'. 8387 if (Phi) { 8388 if (getLHS(RdxKind, Inst) == Phi) { 8389 Phi = nullptr; 8390 Inst = dyn_cast<Instruction>(getRHS(RdxKind, Inst)); 8391 if (!Inst) 8392 return false; 8393 RdxKind = getRdxKind(Inst); 8394 } else if (getRHS(RdxKind, Inst) == Phi) { 8395 Phi = nullptr; 8396 Inst = dyn_cast<Instruction>(getLHS(RdxKind, Inst)); 8397 if (!Inst) 8398 return false; 8399 RdxKind = getRdxKind(Inst); 8400 } 8401 } 8402 8403 if (!isVectorizable(RdxKind, Inst)) 8404 return false; 8405 8406 // Analyze "regular" integer/FP types for reductions - no target-specific 8407 // types or pointers. 8408 Type *Ty = Inst->getType(); 8409 if (!isValidElementType(Ty) || Ty->isPointerTy()) 8410 return false; 8411 8412 // Though the ultimate reduction may have multiple uses, its condition must 8413 // have only single use. 8414 if (auto *Sel = dyn_cast<SelectInst>(Inst)) 8415 if (!Sel->getCondition()->hasOneUse()) 8416 return false; 8417 8418 ReductionRoot = Inst; 8419 8420 // The opcode for leaf values that we perform a reduction on. 8421 // For example: load(x) + load(y) + load(z) + fptoui(w) 8422 // The leaf opcode for 'w' does not match, so we don't include it as a 8423 // potential candidate for the reduction. 8424 unsigned LeafOpcode = 0; 8425 8426 // Post-order traverse the reduction tree starting at Inst. We only handle 8427 // true trees containing binary operators or selects. 8428 SmallVector<std::pair<Instruction *, unsigned>, 32> Stack; 8429 Stack.push_back(std::make_pair(Inst, getFirstOperandIndex(Inst))); 8430 initReductionOps(Inst); 8431 while (!Stack.empty()) { 8432 Instruction *TreeN = Stack.back().first; 8433 unsigned EdgeToVisit = Stack.back().second++; 8434 const RecurKind TreeRdxKind = getRdxKind(TreeN); 8435 bool IsReducedValue = TreeRdxKind != RdxKind; 8436 8437 // Postorder visit. 8438 if (IsReducedValue || EdgeToVisit >= getNumberOfOperands(TreeN)) { 8439 if (IsReducedValue) 8440 ReducedVals.push_back(TreeN); 8441 else { 8442 auto ExtraArgsIter = ExtraArgs.find(TreeN); 8443 if (ExtraArgsIter != ExtraArgs.end() && !ExtraArgsIter->second) { 8444 // Check if TreeN is an extra argument of its parent operation. 8445 if (Stack.size() <= 1) { 8446 // TreeN can't be an extra argument as it is a root reduction 8447 // operation. 8448 return false; 8449 } 8450 // Yes, TreeN is an extra argument, do not add it to a list of 8451 // reduction operations. 8452 // Stack[Stack.size() - 2] always points to the parent operation. 8453 markExtraArg(Stack[Stack.size() - 2], TreeN); 8454 ExtraArgs.erase(TreeN); 8455 } else 8456 addReductionOps(TreeN); 8457 } 8458 // Retract. 8459 Stack.pop_back(); 8460 continue; 8461 } 8462 8463 // Visit operands. 8464 Value *EdgeVal = getRdxOperand(TreeN, EdgeToVisit); 8465 auto *EdgeInst = dyn_cast<Instruction>(EdgeVal); 8466 if (!EdgeInst) { 8467 // Edge value is not a reduction instruction or a leaf instruction. 8468 // (It may be a constant, function argument, or something else.) 8469 markExtraArg(Stack.back(), EdgeVal); 8470 continue; 8471 } 8472 RecurKind EdgeRdxKind = getRdxKind(EdgeInst); 8473 // Continue analysis if the next operand is a reduction operation or 8474 // (possibly) a leaf value. If the leaf value opcode is not set, 8475 // the first met operation != reduction operation is considered as the 8476 // leaf opcode. 8477 // Only handle trees in the current basic block. 8478 // Each tree node needs to have minimal number of users except for the 8479 // ultimate reduction. 8480 const bool IsRdxInst = EdgeRdxKind == RdxKind; 8481 if (EdgeInst != Phi && EdgeInst != Inst && 8482 hasSameParent(EdgeInst, Inst->getParent()) && 8483 hasRequiredNumberOfUses(isCmpSelMinMax(Inst), EdgeInst) && 8484 (!LeafOpcode || LeafOpcode == EdgeInst->getOpcode() || IsRdxInst)) { 8485 if (IsRdxInst) { 8486 // We need to be able to reassociate the reduction operations. 8487 if (!isVectorizable(EdgeRdxKind, EdgeInst)) { 8488 // I is an extra argument for TreeN (its parent operation). 8489 markExtraArg(Stack.back(), EdgeInst); 8490 continue; 8491 } 8492 } else if (!LeafOpcode) { 8493 LeafOpcode = EdgeInst->getOpcode(); 8494 } 8495 Stack.push_back( 8496 std::make_pair(EdgeInst, getFirstOperandIndex(EdgeInst))); 8497 continue; 8498 } 8499 // I is an extra argument for TreeN (its parent operation). 8500 markExtraArg(Stack.back(), EdgeInst); 8501 } 8502 return true; 8503 } 8504 8505 /// Attempt to vectorize the tree found by matchAssociativeReduction. 8506 Value *tryToReduce(BoUpSLP &V, TargetTransformInfo *TTI) { 8507 // If there are a sufficient number of reduction values, reduce 8508 // to a nearby power-of-2. We can safely generate oversized 8509 // vectors and rely on the backend to split them to legal sizes. 8510 unsigned NumReducedVals = ReducedVals.size(); 8511 if (NumReducedVals < 4) 8512 return nullptr; 8513 8514 // Intersect the fast-math-flags from all reduction operations. 8515 FastMathFlags RdxFMF; 8516 RdxFMF.set(); 8517 for (ReductionOpsType &RdxOp : ReductionOps) { 8518 for (Value *RdxVal : RdxOp) { 8519 if (auto *FPMO = dyn_cast<FPMathOperator>(RdxVal)) 8520 RdxFMF &= FPMO->getFastMathFlags(); 8521 } 8522 } 8523 8524 IRBuilder<> Builder(cast<Instruction>(ReductionRoot)); 8525 Builder.setFastMathFlags(RdxFMF); 8526 8527 BoUpSLP::ExtraValueToDebugLocsMap ExternallyUsedValues; 8528 // The same extra argument may be used several times, so log each attempt 8529 // to use it. 8530 for (const std::pair<Instruction *, Value *> &Pair : ExtraArgs) { 8531 assert(Pair.first && "DebugLoc must be set."); 8532 ExternallyUsedValues[Pair.second].push_back(Pair.first); 8533 } 8534 8535 // The compare instruction of a min/max is the insertion point for new 8536 // instructions and may be replaced with a new compare instruction. 8537 auto getCmpForMinMaxReduction = [](Instruction *RdxRootInst) { 8538 assert(isa<SelectInst>(RdxRootInst) && 8539 "Expected min/max reduction to have select root instruction"); 8540 Value *ScalarCond = cast<SelectInst>(RdxRootInst)->getCondition(); 8541 assert(isa<Instruction>(ScalarCond) && 8542 "Expected min/max reduction to have compare condition"); 8543 return cast<Instruction>(ScalarCond); 8544 }; 8545 8546 // The reduction root is used as the insertion point for new instructions, 8547 // so set it as externally used to prevent it from being deleted. 8548 ExternallyUsedValues[ReductionRoot]; 8549 SmallVector<Value *, 16> IgnoreList; 8550 for (ReductionOpsType &RdxOp : ReductionOps) 8551 IgnoreList.append(RdxOp.begin(), RdxOp.end()); 8552 8553 unsigned ReduxWidth = PowerOf2Floor(NumReducedVals); 8554 if (NumReducedVals > ReduxWidth) { 8555 // In the loop below, we are building a tree based on a window of 8556 // 'ReduxWidth' values. 8557 // If the operands of those values have common traits (compare predicate, 8558 // constant operand, etc), then we want to group those together to 8559 // minimize the cost of the reduction. 8560 8561 // TODO: This should be extended to count common operands for 8562 // compares and binops. 8563 8564 // Step 1: Count the number of times each compare predicate occurs. 8565 SmallDenseMap<unsigned, unsigned> PredCountMap; 8566 for (Value *RdxVal : ReducedVals) { 8567 CmpInst::Predicate Pred; 8568 if (match(RdxVal, m_Cmp(Pred, m_Value(), m_Value()))) 8569 ++PredCountMap[Pred]; 8570 } 8571 // Step 2: Sort the values so the most common predicates come first. 8572 stable_sort(ReducedVals, [&PredCountMap](Value *A, Value *B) { 8573 CmpInst::Predicate PredA, PredB; 8574 if (match(A, m_Cmp(PredA, m_Value(), m_Value())) && 8575 match(B, m_Cmp(PredB, m_Value(), m_Value()))) { 8576 return PredCountMap[PredA] > PredCountMap[PredB]; 8577 } 8578 return false; 8579 }); 8580 } 8581 8582 Value *VectorizedTree = nullptr; 8583 unsigned i = 0; 8584 while (i < NumReducedVals - ReduxWidth + 1 && ReduxWidth > 2) { 8585 ArrayRef<Value *> VL(&ReducedVals[i], ReduxWidth); 8586 V.buildTree(VL, IgnoreList); 8587 if (V.isTreeTinyAndNotFullyVectorizable(/*ForReduction=*/true)) 8588 break; 8589 if (V.isLoadCombineReductionCandidate(RdxKind)) 8590 break; 8591 V.reorderTopToBottom(); 8592 V.reorderBottomToTop(/*IgnoreReorder=*/true); 8593 V.buildExternalUses(ExternallyUsedValues); 8594 8595 // For a poison-safe boolean logic reduction, do not replace select 8596 // instructions with logic ops. All reduced values will be frozen (see 8597 // below) to prevent leaking poison. 8598 if (isa<SelectInst>(ReductionRoot) && 8599 isBoolLogicOp(cast<Instruction>(ReductionRoot)) && 8600 NumReducedVals != ReduxWidth) 8601 break; 8602 8603 V.computeMinimumValueSizes(); 8604 8605 // Estimate cost. 8606 InstructionCost TreeCost = 8607 V.getTreeCost(makeArrayRef(&ReducedVals[i], ReduxWidth)); 8608 InstructionCost ReductionCost = 8609 getReductionCost(TTI, ReducedVals[i], ReduxWidth, RdxFMF); 8610 InstructionCost Cost = TreeCost + ReductionCost; 8611 if (!Cost.isValid()) { 8612 LLVM_DEBUG(dbgs() << "Encountered invalid baseline cost.\n"); 8613 return nullptr; 8614 } 8615 if (Cost >= -SLPCostThreshold) { 8616 V.getORE()->emit([&]() { 8617 return OptimizationRemarkMissed(SV_NAME, "HorSLPNotBeneficial", 8618 cast<Instruction>(VL[0])) 8619 << "Vectorizing horizontal reduction is possible" 8620 << "but not beneficial with cost " << ore::NV("Cost", Cost) 8621 << " and threshold " 8622 << ore::NV("Threshold", -SLPCostThreshold); 8623 }); 8624 break; 8625 } 8626 8627 LLVM_DEBUG(dbgs() << "SLP: Vectorizing horizontal reduction at cost:" 8628 << Cost << ". (HorRdx)\n"); 8629 V.getORE()->emit([&]() { 8630 return OptimizationRemark(SV_NAME, "VectorizedHorizontalReduction", 8631 cast<Instruction>(VL[0])) 8632 << "Vectorized horizontal reduction with cost " 8633 << ore::NV("Cost", Cost) << " and with tree size " 8634 << ore::NV("TreeSize", V.getTreeSize()); 8635 }); 8636 8637 // Vectorize a tree. 8638 DebugLoc Loc = cast<Instruction>(ReducedVals[i])->getDebugLoc(); 8639 Value *VectorizedRoot = V.vectorizeTree(ExternallyUsedValues); 8640 8641 // Emit a reduction. If the root is a select (min/max idiom), the insert 8642 // point is the compare condition of that select. 8643 Instruction *RdxRootInst = cast<Instruction>(ReductionRoot); 8644 if (isCmpSelMinMax(RdxRootInst)) 8645 Builder.SetInsertPoint(getCmpForMinMaxReduction(RdxRootInst)); 8646 else 8647 Builder.SetInsertPoint(RdxRootInst); 8648 8649 // To prevent poison from leaking across what used to be sequential, safe, 8650 // scalar boolean logic operations, the reduction operand must be frozen. 8651 if (isa<SelectInst>(RdxRootInst) && isBoolLogicOp(RdxRootInst)) 8652 VectorizedRoot = Builder.CreateFreeze(VectorizedRoot); 8653 8654 Value *ReducedSubTree = 8655 emitReduction(VectorizedRoot, Builder, ReduxWidth, TTI); 8656 8657 if (!VectorizedTree) { 8658 // Initialize the final value in the reduction. 8659 VectorizedTree = ReducedSubTree; 8660 } else { 8661 // Update the final value in the reduction. 8662 Builder.SetCurrentDebugLocation(Loc); 8663 VectorizedTree = createOp(Builder, RdxKind, VectorizedTree, 8664 ReducedSubTree, "op.rdx", ReductionOps); 8665 } 8666 i += ReduxWidth; 8667 ReduxWidth = PowerOf2Floor(NumReducedVals - i); 8668 } 8669 8670 if (VectorizedTree) { 8671 // Finish the reduction. 8672 for (; i < NumReducedVals; ++i) { 8673 auto *I = cast<Instruction>(ReducedVals[i]); 8674 Builder.SetCurrentDebugLocation(I->getDebugLoc()); 8675 VectorizedTree = 8676 createOp(Builder, RdxKind, VectorizedTree, I, "", ReductionOps); 8677 } 8678 for (auto &Pair : ExternallyUsedValues) { 8679 // Add each externally used value to the final reduction. 8680 for (auto *I : Pair.second) { 8681 Builder.SetCurrentDebugLocation(I->getDebugLoc()); 8682 VectorizedTree = createOp(Builder, RdxKind, VectorizedTree, 8683 Pair.first, "op.extra", I); 8684 } 8685 } 8686 8687 ReductionRoot->replaceAllUsesWith(VectorizedTree); 8688 8689 // Mark all scalar reduction ops for deletion, they are replaced by the 8690 // vector reductions. 8691 V.eraseInstructions(IgnoreList); 8692 } 8693 return VectorizedTree; 8694 } 8695 8696 unsigned numReductionValues() const { return ReducedVals.size(); } 8697 8698 private: 8699 /// Calculate the cost of a reduction. 8700 InstructionCost getReductionCost(TargetTransformInfo *TTI, 8701 Value *FirstReducedVal, unsigned ReduxWidth, 8702 FastMathFlags FMF) { 8703 TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput; 8704 Type *ScalarTy = FirstReducedVal->getType(); 8705 FixedVectorType *VectorTy = FixedVectorType::get(ScalarTy, ReduxWidth); 8706 InstructionCost VectorCost, ScalarCost; 8707 switch (RdxKind) { 8708 case RecurKind::Add: 8709 case RecurKind::Mul: 8710 case RecurKind::Or: 8711 case RecurKind::And: 8712 case RecurKind::Xor: 8713 case RecurKind::FAdd: 8714 case RecurKind::FMul: { 8715 unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(RdxKind); 8716 VectorCost = 8717 TTI->getArithmeticReductionCost(RdxOpcode, VectorTy, FMF, CostKind); 8718 ScalarCost = TTI->getArithmeticInstrCost(RdxOpcode, ScalarTy, CostKind); 8719 break; 8720 } 8721 case RecurKind::FMax: 8722 case RecurKind::FMin: { 8723 auto *SclCondTy = CmpInst::makeCmpResultType(ScalarTy); 8724 auto *VecCondTy = cast<VectorType>(CmpInst::makeCmpResultType(VectorTy)); 8725 VectorCost = TTI->getMinMaxReductionCost(VectorTy, VecCondTy, 8726 /*unsigned=*/false, CostKind); 8727 CmpInst::Predicate RdxPred = getMinMaxReductionPredicate(RdxKind); 8728 ScalarCost = TTI->getCmpSelInstrCost(Instruction::FCmp, ScalarTy, 8729 SclCondTy, RdxPred, CostKind) + 8730 TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy, 8731 SclCondTy, RdxPred, CostKind); 8732 break; 8733 } 8734 case RecurKind::SMax: 8735 case RecurKind::SMin: 8736 case RecurKind::UMax: 8737 case RecurKind::UMin: { 8738 auto *SclCondTy = CmpInst::makeCmpResultType(ScalarTy); 8739 auto *VecCondTy = cast<VectorType>(CmpInst::makeCmpResultType(VectorTy)); 8740 bool IsUnsigned = 8741 RdxKind == RecurKind::UMax || RdxKind == RecurKind::UMin; 8742 VectorCost = TTI->getMinMaxReductionCost(VectorTy, VecCondTy, IsUnsigned, 8743 CostKind); 8744 CmpInst::Predicate RdxPred = getMinMaxReductionPredicate(RdxKind); 8745 ScalarCost = TTI->getCmpSelInstrCost(Instruction::ICmp, ScalarTy, 8746 SclCondTy, RdxPred, CostKind) + 8747 TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy, 8748 SclCondTy, RdxPred, CostKind); 8749 break; 8750 } 8751 default: 8752 llvm_unreachable("Expected arithmetic or min/max reduction operation"); 8753 } 8754 8755 // Scalar cost is repeated for N-1 elements. 8756 ScalarCost *= (ReduxWidth - 1); 8757 LLVM_DEBUG(dbgs() << "SLP: Adding cost " << VectorCost - ScalarCost 8758 << " for reduction that starts with " << *FirstReducedVal 8759 << " (It is a splitting reduction)\n"); 8760 return VectorCost - ScalarCost; 8761 } 8762 8763 /// Emit a horizontal reduction of the vectorized value. 8764 Value *emitReduction(Value *VectorizedValue, IRBuilder<> &Builder, 8765 unsigned ReduxWidth, const TargetTransformInfo *TTI) { 8766 assert(VectorizedValue && "Need to have a vectorized tree node"); 8767 assert(isPowerOf2_32(ReduxWidth) && 8768 "We only handle power-of-two reductions for now"); 8769 8770 ++NumVectorInstructions; 8771 return createSimpleTargetReduction(Builder, TTI, VectorizedValue, RdxKind, 8772 ReductionOps.back()); 8773 } 8774 }; 8775 8776 } // end anonymous namespace 8777 8778 static Optional<unsigned> getAggregateSize(Instruction *InsertInst) { 8779 if (auto *IE = dyn_cast<InsertElementInst>(InsertInst)) 8780 return cast<FixedVectorType>(IE->getType())->getNumElements(); 8781 8782 unsigned AggregateSize = 1; 8783 auto *IV = cast<InsertValueInst>(InsertInst); 8784 Type *CurrentType = IV->getType(); 8785 do { 8786 if (auto *ST = dyn_cast<StructType>(CurrentType)) { 8787 for (auto *Elt : ST->elements()) 8788 if (Elt != ST->getElementType(0)) // check homogeneity 8789 return None; 8790 AggregateSize *= ST->getNumElements(); 8791 CurrentType = ST->getElementType(0); 8792 } else if (auto *AT = dyn_cast<ArrayType>(CurrentType)) { 8793 AggregateSize *= AT->getNumElements(); 8794 CurrentType = AT->getElementType(); 8795 } else if (auto *VT = dyn_cast<FixedVectorType>(CurrentType)) { 8796 AggregateSize *= VT->getNumElements(); 8797 return AggregateSize; 8798 } else if (CurrentType->isSingleValueType()) { 8799 return AggregateSize; 8800 } else { 8801 return None; 8802 } 8803 } while (true); 8804 } 8805 8806 static bool findBuildAggregate_rec(Instruction *LastInsertInst, 8807 TargetTransformInfo *TTI, 8808 SmallVectorImpl<Value *> &BuildVectorOpds, 8809 SmallVectorImpl<Value *> &InsertElts, 8810 unsigned OperandOffset) { 8811 do { 8812 Value *InsertedOperand = LastInsertInst->getOperand(1); 8813 Optional<int> OperandIndex = getInsertIndex(LastInsertInst, OperandOffset); 8814 if (!OperandIndex) 8815 return false; 8816 if (isa<InsertElementInst>(InsertedOperand) || 8817 isa<InsertValueInst>(InsertedOperand)) { 8818 if (!findBuildAggregate_rec(cast<Instruction>(InsertedOperand), TTI, 8819 BuildVectorOpds, InsertElts, *OperandIndex)) 8820 return false; 8821 } else { 8822 BuildVectorOpds[*OperandIndex] = InsertedOperand; 8823 InsertElts[*OperandIndex] = LastInsertInst; 8824 } 8825 LastInsertInst = dyn_cast<Instruction>(LastInsertInst->getOperand(0)); 8826 } while (LastInsertInst != nullptr && 8827 (isa<InsertValueInst>(LastInsertInst) || 8828 isa<InsertElementInst>(LastInsertInst)) && 8829 LastInsertInst->hasOneUse()); 8830 return true; 8831 } 8832 8833 /// Recognize construction of vectors like 8834 /// %ra = insertelement <4 x float> poison, float %s0, i32 0 8835 /// %rb = insertelement <4 x float> %ra, float %s1, i32 1 8836 /// %rc = insertelement <4 x float> %rb, float %s2, i32 2 8837 /// %rd = insertelement <4 x float> %rc, float %s3, i32 3 8838 /// starting from the last insertelement or insertvalue instruction. 8839 /// 8840 /// Also recognize homogeneous aggregates like {<2 x float>, <2 x float>}, 8841 /// {{float, float}, {float, float}}, [2 x {float, float}] and so on. 8842 /// See llvm/test/Transforms/SLPVectorizer/X86/pr42022.ll for examples. 8843 /// 8844 /// Assume LastInsertInst is of InsertElementInst or InsertValueInst type. 8845 /// 8846 /// \return true if it matches. 8847 static bool findBuildAggregate(Instruction *LastInsertInst, 8848 TargetTransformInfo *TTI, 8849 SmallVectorImpl<Value *> &BuildVectorOpds, 8850 SmallVectorImpl<Value *> &InsertElts) { 8851 8852 assert((isa<InsertElementInst>(LastInsertInst) || 8853 isa<InsertValueInst>(LastInsertInst)) && 8854 "Expected insertelement or insertvalue instruction!"); 8855 8856 assert((BuildVectorOpds.empty() && InsertElts.empty()) && 8857 "Expected empty result vectors!"); 8858 8859 Optional<unsigned> AggregateSize = getAggregateSize(LastInsertInst); 8860 if (!AggregateSize) 8861 return false; 8862 BuildVectorOpds.resize(*AggregateSize); 8863 InsertElts.resize(*AggregateSize); 8864 8865 if (findBuildAggregate_rec(LastInsertInst, TTI, BuildVectorOpds, InsertElts, 8866 0)) { 8867 llvm::erase_value(BuildVectorOpds, nullptr); 8868 llvm::erase_value(InsertElts, nullptr); 8869 if (BuildVectorOpds.size() >= 2) 8870 return true; 8871 } 8872 8873 return false; 8874 } 8875 8876 /// Try and get a reduction value from a phi node. 8877 /// 8878 /// Given a phi node \p P in a block \p ParentBB, consider possible reductions 8879 /// if they come from either \p ParentBB or a containing loop latch. 8880 /// 8881 /// \returns A candidate reduction value if possible, or \code nullptr \endcode 8882 /// if not possible. 8883 static Value *getReductionValue(const DominatorTree *DT, PHINode *P, 8884 BasicBlock *ParentBB, LoopInfo *LI) { 8885 // There are situations where the reduction value is not dominated by the 8886 // reduction phi. Vectorizing such cases has been reported to cause 8887 // miscompiles. See PR25787. 8888 auto DominatedReduxValue = [&](Value *R) { 8889 return isa<Instruction>(R) && 8890 DT->dominates(P->getParent(), cast<Instruction>(R)->getParent()); 8891 }; 8892 8893 Value *Rdx = nullptr; 8894 8895 // Return the incoming value if it comes from the same BB as the phi node. 8896 if (P->getIncomingBlock(0) == ParentBB) { 8897 Rdx = P->getIncomingValue(0); 8898 } else if (P->getIncomingBlock(1) == ParentBB) { 8899 Rdx = P->getIncomingValue(1); 8900 } 8901 8902 if (Rdx && DominatedReduxValue(Rdx)) 8903 return Rdx; 8904 8905 // Otherwise, check whether we have a loop latch to look at. 8906 Loop *BBL = LI->getLoopFor(ParentBB); 8907 if (!BBL) 8908 return nullptr; 8909 BasicBlock *BBLatch = BBL->getLoopLatch(); 8910 if (!BBLatch) 8911 return nullptr; 8912 8913 // There is a loop latch, return the incoming value if it comes from 8914 // that. This reduction pattern occasionally turns up. 8915 if (P->getIncomingBlock(0) == BBLatch) { 8916 Rdx = P->getIncomingValue(0); 8917 } else if (P->getIncomingBlock(1) == BBLatch) { 8918 Rdx = P->getIncomingValue(1); 8919 } 8920 8921 if (Rdx && DominatedReduxValue(Rdx)) 8922 return Rdx; 8923 8924 return nullptr; 8925 } 8926 8927 static bool matchRdxBop(Instruction *I, Value *&V0, Value *&V1) { 8928 if (match(I, m_BinOp(m_Value(V0), m_Value(V1)))) 8929 return true; 8930 if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(V0), m_Value(V1)))) 8931 return true; 8932 if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(V0), m_Value(V1)))) 8933 return true; 8934 if (match(I, m_Intrinsic<Intrinsic::smax>(m_Value(V0), m_Value(V1)))) 8935 return true; 8936 if (match(I, m_Intrinsic<Intrinsic::smin>(m_Value(V0), m_Value(V1)))) 8937 return true; 8938 if (match(I, m_Intrinsic<Intrinsic::umax>(m_Value(V0), m_Value(V1)))) 8939 return true; 8940 if (match(I, m_Intrinsic<Intrinsic::umin>(m_Value(V0), m_Value(V1)))) 8941 return true; 8942 return false; 8943 } 8944 8945 /// Attempt to reduce a horizontal reduction. 8946 /// If it is legal to match a horizontal reduction feeding the phi node \a P 8947 /// with reduction operators \a Root (or one of its operands) in a basic block 8948 /// \a BB, then check if it can be done. If horizontal reduction is not found 8949 /// and root instruction is a binary operation, vectorization of the operands is 8950 /// attempted. 8951 /// \returns true if a horizontal reduction was matched and reduced or operands 8952 /// of one of the binary instruction were vectorized. 8953 /// \returns false if a horizontal reduction was not matched (or not possible) 8954 /// or no vectorization of any binary operation feeding \a Root instruction was 8955 /// performed. 8956 static bool tryToVectorizeHorReductionOrInstOperands( 8957 PHINode *P, Instruction *Root, BasicBlock *BB, BoUpSLP &R, 8958 TargetTransformInfo *TTI, 8959 const function_ref<bool(Instruction *, BoUpSLP &)> Vectorize) { 8960 if (!ShouldVectorizeHor) 8961 return false; 8962 8963 if (!Root) 8964 return false; 8965 8966 if (Root->getParent() != BB || isa<PHINode>(Root)) 8967 return false; 8968 // Start analysis starting from Root instruction. If horizontal reduction is 8969 // found, try to vectorize it. If it is not a horizontal reduction or 8970 // vectorization is not possible or not effective, and currently analyzed 8971 // instruction is a binary operation, try to vectorize the operands, using 8972 // pre-order DFS traversal order. If the operands were not vectorized, repeat 8973 // the same procedure considering each operand as a possible root of the 8974 // horizontal reduction. 8975 // Interrupt the process if the Root instruction itself was vectorized or all 8976 // sub-trees not higher that RecursionMaxDepth were analyzed/vectorized. 8977 // Skip the analysis of CmpInsts.Compiler implements postanalysis of the 8978 // CmpInsts so we can skip extra attempts in 8979 // tryToVectorizeHorReductionOrInstOperands and save compile time. 8980 std::queue<std::pair<Instruction *, unsigned>> Stack; 8981 Stack.emplace(Root, 0); 8982 SmallPtrSet<Value *, 8> VisitedInstrs; 8983 SmallVector<WeakTrackingVH> PostponedInsts; 8984 bool Res = false; 8985 auto &&TryToReduce = [TTI, &P, &R](Instruction *Inst, Value *&B0, 8986 Value *&B1) -> Value * { 8987 bool IsBinop = matchRdxBop(Inst, B0, B1); 8988 bool IsSelect = match(Inst, m_Select(m_Value(), m_Value(), m_Value())); 8989 if (IsBinop || IsSelect) { 8990 HorizontalReduction HorRdx; 8991 if (HorRdx.matchAssociativeReduction(P, Inst)) 8992 return HorRdx.tryToReduce(R, TTI); 8993 } 8994 return nullptr; 8995 }; 8996 while (!Stack.empty()) { 8997 Instruction *Inst; 8998 unsigned Level; 8999 std::tie(Inst, Level) = Stack.front(); 9000 Stack.pop(); 9001 // Do not try to analyze instruction that has already been vectorized. 9002 // This may happen when we vectorize instruction operands on a previous 9003 // iteration while stack was populated before that happened. 9004 if (R.isDeleted(Inst)) 9005 continue; 9006 Value *B0 = nullptr, *B1 = nullptr; 9007 if (Value *V = TryToReduce(Inst, B0, B1)) { 9008 Res = true; 9009 // Set P to nullptr to avoid re-analysis of phi node in 9010 // matchAssociativeReduction function unless this is the root node. 9011 P = nullptr; 9012 if (auto *I = dyn_cast<Instruction>(V)) { 9013 // Try to find another reduction. 9014 Stack.emplace(I, Level); 9015 continue; 9016 } 9017 } else { 9018 bool IsBinop = B0 && B1; 9019 if (P && IsBinop) { 9020 Inst = dyn_cast<Instruction>(B0); 9021 if (Inst == P) 9022 Inst = dyn_cast<Instruction>(B1); 9023 if (!Inst) { 9024 // Set P to nullptr to avoid re-analysis of phi node in 9025 // matchAssociativeReduction function unless this is the root node. 9026 P = nullptr; 9027 continue; 9028 } 9029 } 9030 // Set P to nullptr to avoid re-analysis of phi node in 9031 // matchAssociativeReduction function unless this is the root node. 9032 P = nullptr; 9033 // Do not try to vectorize CmpInst operands, this is done separately. 9034 // Final attempt for binop args vectorization should happen after the loop 9035 // to try to find reductions. 9036 if (!isa<CmpInst>(Inst)) 9037 PostponedInsts.push_back(Inst); 9038 } 9039 9040 // Try to vectorize operands. 9041 // Continue analysis for the instruction from the same basic block only to 9042 // save compile time. 9043 if (++Level < RecursionMaxDepth) 9044 for (auto *Op : Inst->operand_values()) 9045 if (VisitedInstrs.insert(Op).second) 9046 if (auto *I = dyn_cast<Instruction>(Op)) 9047 // Do not try to vectorize CmpInst operands, this is done 9048 // separately. 9049 if (!isa<PHINode>(I) && !isa<CmpInst>(I) && !R.isDeleted(I) && 9050 I->getParent() == BB) 9051 Stack.emplace(I, Level); 9052 } 9053 // Try to vectorized binops where reductions were not found. 9054 for (Value *V : PostponedInsts) 9055 if (auto *Inst = dyn_cast<Instruction>(V)) 9056 if (!R.isDeleted(Inst)) 9057 Res |= Vectorize(Inst, R); 9058 return Res; 9059 } 9060 9061 bool SLPVectorizerPass::vectorizeRootInstruction(PHINode *P, Value *V, 9062 BasicBlock *BB, BoUpSLP &R, 9063 TargetTransformInfo *TTI) { 9064 auto *I = dyn_cast_or_null<Instruction>(V); 9065 if (!I) 9066 return false; 9067 9068 if (!isa<BinaryOperator>(I)) 9069 P = nullptr; 9070 // Try to match and vectorize a horizontal reduction. 9071 auto &&ExtraVectorization = [this](Instruction *I, BoUpSLP &R) -> bool { 9072 return tryToVectorize(I, R); 9073 }; 9074 return tryToVectorizeHorReductionOrInstOperands(P, I, BB, R, TTI, 9075 ExtraVectorization); 9076 } 9077 9078 bool SLPVectorizerPass::vectorizeInsertValueInst(InsertValueInst *IVI, 9079 BasicBlock *BB, BoUpSLP &R) { 9080 const DataLayout &DL = BB->getModule()->getDataLayout(); 9081 if (!R.canMapToVector(IVI->getType(), DL)) 9082 return false; 9083 9084 SmallVector<Value *, 16> BuildVectorOpds; 9085 SmallVector<Value *, 16> BuildVectorInsts; 9086 if (!findBuildAggregate(IVI, TTI, BuildVectorOpds, BuildVectorInsts)) 9087 return false; 9088 9089 LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IVI << "\n"); 9090 // Aggregate value is unlikely to be processed in vector register, we need to 9091 // extract scalars into scalar registers, so NeedExtraction is set true. 9092 return tryToVectorizeList(BuildVectorOpds, R); 9093 } 9094 9095 bool SLPVectorizerPass::vectorizeInsertElementInst(InsertElementInst *IEI, 9096 BasicBlock *BB, BoUpSLP &R) { 9097 SmallVector<Value *, 16> BuildVectorInsts; 9098 SmallVector<Value *, 16> BuildVectorOpds; 9099 SmallVector<int> Mask; 9100 if (!findBuildAggregate(IEI, TTI, BuildVectorOpds, BuildVectorInsts) || 9101 (llvm::all_of(BuildVectorOpds, 9102 [](Value *V) { return isa<ExtractElementInst>(V); }) && 9103 isFixedVectorShuffle(BuildVectorOpds, Mask))) 9104 return false; 9105 9106 LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IEI << "\n"); 9107 return tryToVectorizeList(BuildVectorInsts, R); 9108 } 9109 9110 bool SLPVectorizerPass::vectorizeSimpleInstructions( 9111 SmallVectorImpl<Instruction *> &Instructions, BasicBlock *BB, BoUpSLP &R, 9112 bool AtTerminator) { 9113 bool OpsChanged = false; 9114 SmallVector<Instruction *, 4> PostponedCmps; 9115 for (auto *I : reverse(Instructions)) { 9116 if (R.isDeleted(I)) 9117 continue; 9118 if (auto *LastInsertValue = dyn_cast<InsertValueInst>(I)) 9119 OpsChanged |= vectorizeInsertValueInst(LastInsertValue, BB, R); 9120 else if (auto *LastInsertElem = dyn_cast<InsertElementInst>(I)) 9121 OpsChanged |= vectorizeInsertElementInst(LastInsertElem, BB, R); 9122 else if (isa<CmpInst>(I)) 9123 PostponedCmps.push_back(I); 9124 } 9125 if (AtTerminator) { 9126 // Try to find reductions first. 9127 for (Instruction *I : PostponedCmps) { 9128 if (R.isDeleted(I)) 9129 continue; 9130 for (Value *Op : I->operands()) 9131 OpsChanged |= vectorizeRootInstruction(nullptr, Op, BB, R, TTI); 9132 } 9133 // Try to vectorize operands as vector bundles. 9134 for (Instruction *I : PostponedCmps) { 9135 if (R.isDeleted(I)) 9136 continue; 9137 OpsChanged |= tryToVectorize(I, R); 9138 } 9139 Instructions.clear(); 9140 } else { 9141 // Insert in reverse order since the PostponedCmps vector was filled in 9142 // reverse order. 9143 Instructions.assign(PostponedCmps.rbegin(), PostponedCmps.rend()); 9144 } 9145 return OpsChanged; 9146 } 9147 9148 template <typename T> 9149 static bool 9150 tryToVectorizeSequence(SmallVectorImpl<T *> &Incoming, 9151 function_ref<unsigned(T *)> Limit, 9152 function_ref<bool(T *, T *)> Comparator, 9153 function_ref<bool(T *, T *)> AreCompatible, 9154 function_ref<bool(ArrayRef<T *>, bool)> TryToVectorize, 9155 bool LimitForRegisterSize) { 9156 bool Changed = false; 9157 // Sort by type, parent, operands. 9158 stable_sort(Incoming, Comparator); 9159 9160 // Try to vectorize elements base on their type. 9161 SmallVector<T *> Candidates; 9162 for (auto *IncIt = Incoming.begin(), *E = Incoming.end(); IncIt != E;) { 9163 // Look for the next elements with the same type, parent and operand 9164 // kinds. 9165 auto *SameTypeIt = IncIt; 9166 while (SameTypeIt != E && AreCompatible(*SameTypeIt, *IncIt)) 9167 ++SameTypeIt; 9168 9169 // Try to vectorize them. 9170 unsigned NumElts = (SameTypeIt - IncIt); 9171 LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize starting at nodes (" 9172 << NumElts << ")\n"); 9173 // The vectorization is a 3-state attempt: 9174 // 1. Try to vectorize instructions with the same/alternate opcodes with the 9175 // size of maximal register at first. 9176 // 2. Try to vectorize remaining instructions with the same type, if 9177 // possible. This may result in the better vectorization results rather than 9178 // if we try just to vectorize instructions with the same/alternate opcodes. 9179 // 3. Final attempt to try to vectorize all instructions with the 9180 // same/alternate ops only, this may result in some extra final 9181 // vectorization. 9182 if (NumElts > 1 && 9183 TryToVectorize(makeArrayRef(IncIt, NumElts), LimitForRegisterSize)) { 9184 // Success start over because instructions might have been changed. 9185 Changed = true; 9186 } else if (NumElts < Limit(*IncIt) && 9187 (Candidates.empty() || 9188 Candidates.front()->getType() == (*IncIt)->getType())) { 9189 Candidates.append(IncIt, std::next(IncIt, NumElts)); 9190 } 9191 // Final attempt to vectorize instructions with the same types. 9192 if (Candidates.size() > 1 && 9193 (SameTypeIt == E || (*SameTypeIt)->getType() != (*IncIt)->getType())) { 9194 if (TryToVectorize(Candidates, /*LimitForRegisterSize=*/false)) { 9195 // Success start over because instructions might have been changed. 9196 Changed = true; 9197 } else if (LimitForRegisterSize) { 9198 // Try to vectorize using small vectors. 9199 for (auto *It = Candidates.begin(), *End = Candidates.end(); 9200 It != End;) { 9201 auto *SameTypeIt = It; 9202 while (SameTypeIt != End && AreCompatible(*SameTypeIt, *It)) 9203 ++SameTypeIt; 9204 unsigned NumElts = (SameTypeIt - It); 9205 if (NumElts > 1 && TryToVectorize(makeArrayRef(It, NumElts), 9206 /*LimitForRegisterSize=*/false)) 9207 Changed = true; 9208 It = SameTypeIt; 9209 } 9210 } 9211 Candidates.clear(); 9212 } 9213 9214 // Start over at the next instruction of a different type (or the end). 9215 IncIt = SameTypeIt; 9216 } 9217 return Changed; 9218 } 9219 9220 bool SLPVectorizerPass::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) { 9221 bool Changed = false; 9222 SmallVector<Value *, 4> Incoming; 9223 SmallPtrSet<Value *, 16> VisitedInstrs; 9224 // Maps phi nodes to the non-phi nodes found in the use tree for each phi 9225 // node. Allows better to identify the chains that can be vectorized in the 9226 // better way. 9227 DenseMap<Value *, SmallVector<Value *, 4>> PHIToOpcodes; 9228 auto PHICompare = [this, &PHIToOpcodes](Value *V1, Value *V2) { 9229 assert(isValidElementType(V1->getType()) && 9230 isValidElementType(V2->getType()) && 9231 "Expected vectorizable types only."); 9232 // It is fine to compare type IDs here, since we expect only vectorizable 9233 // types, like ints, floats and pointers, we don't care about other type. 9234 if (V1->getType()->getTypeID() < V2->getType()->getTypeID()) 9235 return true; 9236 if (V1->getType()->getTypeID() > V2->getType()->getTypeID()) 9237 return false; 9238 ArrayRef<Value *> Opcodes1 = PHIToOpcodes[V1]; 9239 ArrayRef<Value *> Opcodes2 = PHIToOpcodes[V2]; 9240 if (Opcodes1.size() < Opcodes2.size()) 9241 return true; 9242 if (Opcodes1.size() > Opcodes2.size()) 9243 return false; 9244 for (int I = 0, E = Opcodes1.size(); I < E; ++I) { 9245 // Undefs are compatible with any other value. 9246 if (isa<UndefValue>(Opcodes1[I]) || isa<UndefValue>(Opcodes2[I])) 9247 continue; 9248 if (auto *I1 = dyn_cast<Instruction>(Opcodes1[I])) 9249 if (auto *I2 = dyn_cast<Instruction>(Opcodes2[I])) { 9250 DomTreeNodeBase<BasicBlock> *NodeI1 = DT->getNode(I1->getParent()); 9251 DomTreeNodeBase<BasicBlock> *NodeI2 = DT->getNode(I2->getParent()); 9252 if (!NodeI1) 9253 return NodeI2 != nullptr; 9254 if (!NodeI2) 9255 return false; 9256 assert((NodeI1 == NodeI2) == 9257 (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) && 9258 "Different nodes should have different DFS numbers"); 9259 if (NodeI1 != NodeI2) 9260 return NodeI1->getDFSNumIn() < NodeI2->getDFSNumIn(); 9261 InstructionsState S = getSameOpcode({I1, I2}); 9262 if (S.getOpcode()) 9263 continue; 9264 return I1->getOpcode() < I2->getOpcode(); 9265 } 9266 if (isa<Constant>(Opcodes1[I]) && isa<Constant>(Opcodes2[I])) 9267 continue; 9268 if (Opcodes1[I]->getValueID() < Opcodes2[I]->getValueID()) 9269 return true; 9270 if (Opcodes1[I]->getValueID() > Opcodes2[I]->getValueID()) 9271 return false; 9272 } 9273 return false; 9274 }; 9275 auto AreCompatiblePHIs = [&PHIToOpcodes](Value *V1, Value *V2) { 9276 if (V1 == V2) 9277 return true; 9278 if (V1->getType() != V2->getType()) 9279 return false; 9280 ArrayRef<Value *> Opcodes1 = PHIToOpcodes[V1]; 9281 ArrayRef<Value *> Opcodes2 = PHIToOpcodes[V2]; 9282 if (Opcodes1.size() != Opcodes2.size()) 9283 return false; 9284 for (int I = 0, E = Opcodes1.size(); I < E; ++I) { 9285 // Undefs are compatible with any other value. 9286 if (isa<UndefValue>(Opcodes1[I]) || isa<UndefValue>(Opcodes2[I])) 9287 continue; 9288 if (auto *I1 = dyn_cast<Instruction>(Opcodes1[I])) 9289 if (auto *I2 = dyn_cast<Instruction>(Opcodes2[I])) { 9290 if (I1->getParent() != I2->getParent()) 9291 return false; 9292 InstructionsState S = getSameOpcode({I1, I2}); 9293 if (S.getOpcode()) 9294 continue; 9295 return false; 9296 } 9297 if (isa<Constant>(Opcodes1[I]) && isa<Constant>(Opcodes2[I])) 9298 continue; 9299 if (Opcodes1[I]->getValueID() != Opcodes2[I]->getValueID()) 9300 return false; 9301 } 9302 return true; 9303 }; 9304 auto Limit = [&R](Value *V) { 9305 unsigned EltSize = R.getVectorElementSize(V); 9306 return std::max(2U, R.getMaxVecRegSize() / EltSize); 9307 }; 9308 9309 bool HaveVectorizedPhiNodes = false; 9310 do { 9311 // Collect the incoming values from the PHIs. 9312 Incoming.clear(); 9313 for (Instruction &I : *BB) { 9314 PHINode *P = dyn_cast<PHINode>(&I); 9315 if (!P) 9316 break; 9317 9318 // No need to analyze deleted, vectorized and non-vectorizable 9319 // instructions. 9320 if (!VisitedInstrs.count(P) && !R.isDeleted(P) && 9321 isValidElementType(P->getType())) 9322 Incoming.push_back(P); 9323 } 9324 9325 // Find the corresponding non-phi nodes for better matching when trying to 9326 // build the tree. 9327 for (Value *V : Incoming) { 9328 SmallVectorImpl<Value *> &Opcodes = 9329 PHIToOpcodes.try_emplace(V).first->getSecond(); 9330 if (!Opcodes.empty()) 9331 continue; 9332 SmallVector<Value *, 4> Nodes(1, V); 9333 SmallPtrSet<Value *, 4> Visited; 9334 while (!Nodes.empty()) { 9335 auto *PHI = cast<PHINode>(Nodes.pop_back_val()); 9336 if (!Visited.insert(PHI).second) 9337 continue; 9338 for (Value *V : PHI->incoming_values()) { 9339 if (auto *PHI1 = dyn_cast<PHINode>((V))) { 9340 Nodes.push_back(PHI1); 9341 continue; 9342 } 9343 Opcodes.emplace_back(V); 9344 } 9345 } 9346 } 9347 9348 HaveVectorizedPhiNodes = tryToVectorizeSequence<Value>( 9349 Incoming, Limit, PHICompare, AreCompatiblePHIs, 9350 [this, &R](ArrayRef<Value *> Candidates, bool LimitForRegisterSize) { 9351 return tryToVectorizeList(Candidates, R, LimitForRegisterSize); 9352 }, 9353 /*LimitForRegisterSize=*/true); 9354 Changed |= HaveVectorizedPhiNodes; 9355 VisitedInstrs.insert(Incoming.begin(), Incoming.end()); 9356 } while (HaveVectorizedPhiNodes); 9357 9358 VisitedInstrs.clear(); 9359 9360 SmallVector<Instruction *, 8> PostProcessInstructions; 9361 SmallDenseSet<Instruction *, 4> KeyNodes; 9362 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) { 9363 // Skip instructions with scalable type. The num of elements is unknown at 9364 // compile-time for scalable type. 9365 if (isa<ScalableVectorType>(it->getType())) 9366 continue; 9367 9368 // Skip instructions marked for the deletion. 9369 if (R.isDeleted(&*it)) 9370 continue; 9371 // We may go through BB multiple times so skip the one we have checked. 9372 if (!VisitedInstrs.insert(&*it).second) { 9373 if (it->use_empty() && KeyNodes.contains(&*it) && 9374 vectorizeSimpleInstructions(PostProcessInstructions, BB, R, 9375 it->isTerminator())) { 9376 // We would like to start over since some instructions are deleted 9377 // and the iterator may become invalid value. 9378 Changed = true; 9379 it = BB->begin(); 9380 e = BB->end(); 9381 } 9382 continue; 9383 } 9384 9385 if (isa<DbgInfoIntrinsic>(it)) 9386 continue; 9387 9388 // Try to vectorize reductions that use PHINodes. 9389 if (PHINode *P = dyn_cast<PHINode>(it)) { 9390 // Check that the PHI is a reduction PHI. 9391 if (P->getNumIncomingValues() == 2) { 9392 // Try to match and vectorize a horizontal reduction. 9393 if (vectorizeRootInstruction(P, getReductionValue(DT, P, BB, LI), BB, R, 9394 TTI)) { 9395 Changed = true; 9396 it = BB->begin(); 9397 e = BB->end(); 9398 continue; 9399 } 9400 } 9401 // Try to vectorize the incoming values of the PHI, to catch reductions 9402 // that feed into PHIs. 9403 for (unsigned I = 0, E = P->getNumIncomingValues(); I != E; I++) { 9404 // Skip if the incoming block is the current BB for now. Also, bypass 9405 // unreachable IR for efficiency and to avoid crashing. 9406 // TODO: Collect the skipped incoming values and try to vectorize them 9407 // after processing BB. 9408 if (BB == P->getIncomingBlock(I) || 9409 !DT->isReachableFromEntry(P->getIncomingBlock(I))) 9410 continue; 9411 9412 Changed |= vectorizeRootInstruction(nullptr, P->getIncomingValue(I), 9413 P->getIncomingBlock(I), R, TTI); 9414 } 9415 continue; 9416 } 9417 9418 // Ran into an instruction without users, like terminator, or function call 9419 // with ignored return value, store. Ignore unused instructions (basing on 9420 // instruction type, except for CallInst and InvokeInst). 9421 if (it->use_empty() && (it->getType()->isVoidTy() || isa<CallInst>(it) || 9422 isa<InvokeInst>(it))) { 9423 KeyNodes.insert(&*it); 9424 bool OpsChanged = false; 9425 if (ShouldStartVectorizeHorAtStore || !isa<StoreInst>(it)) { 9426 for (auto *V : it->operand_values()) { 9427 // Try to match and vectorize a horizontal reduction. 9428 OpsChanged |= vectorizeRootInstruction(nullptr, V, BB, R, TTI); 9429 } 9430 } 9431 // Start vectorization of post-process list of instructions from the 9432 // top-tree instructions to try to vectorize as many instructions as 9433 // possible. 9434 OpsChanged |= vectorizeSimpleInstructions(PostProcessInstructions, BB, R, 9435 it->isTerminator()); 9436 if (OpsChanged) { 9437 // We would like to start over since some instructions are deleted 9438 // and the iterator may become invalid value. 9439 Changed = true; 9440 it = BB->begin(); 9441 e = BB->end(); 9442 continue; 9443 } 9444 } 9445 9446 if (isa<InsertElementInst>(it) || isa<CmpInst>(it) || 9447 isa<InsertValueInst>(it)) 9448 PostProcessInstructions.push_back(&*it); 9449 } 9450 9451 return Changed; 9452 } 9453 9454 bool SLPVectorizerPass::vectorizeGEPIndices(BasicBlock *BB, BoUpSLP &R) { 9455 auto Changed = false; 9456 for (auto &Entry : GEPs) { 9457 // If the getelementptr list has fewer than two elements, there's nothing 9458 // to do. 9459 if (Entry.second.size() < 2) 9460 continue; 9461 9462 LLVM_DEBUG(dbgs() << "SLP: Analyzing a getelementptr list of length " 9463 << Entry.second.size() << ".\n"); 9464 9465 // Process the GEP list in chunks suitable for the target's supported 9466 // vector size. If a vector register can't hold 1 element, we are done. We 9467 // are trying to vectorize the index computations, so the maximum number of 9468 // elements is based on the size of the index expression, rather than the 9469 // size of the GEP itself (the target's pointer size). 9470 unsigned MaxVecRegSize = R.getMaxVecRegSize(); 9471 unsigned EltSize = R.getVectorElementSize(*Entry.second[0]->idx_begin()); 9472 if (MaxVecRegSize < EltSize) 9473 continue; 9474 9475 unsigned MaxElts = MaxVecRegSize / EltSize; 9476 for (unsigned BI = 0, BE = Entry.second.size(); BI < BE; BI += MaxElts) { 9477 auto Len = std::min<unsigned>(BE - BI, MaxElts); 9478 ArrayRef<GetElementPtrInst *> GEPList(&Entry.second[BI], Len); 9479 9480 // Initialize a set a candidate getelementptrs. Note that we use a 9481 // SetVector here to preserve program order. If the index computations 9482 // are vectorizable and begin with loads, we want to minimize the chance 9483 // of having to reorder them later. 9484 SetVector<Value *> Candidates(GEPList.begin(), GEPList.end()); 9485 9486 // Some of the candidates may have already been vectorized after we 9487 // initially collected them. If so, they are marked as deleted, so remove 9488 // them from the set of candidates. 9489 Candidates.remove_if( 9490 [&R](Value *I) { return R.isDeleted(cast<Instruction>(I)); }); 9491 9492 // Remove from the set of candidates all pairs of getelementptrs with 9493 // constant differences. Such getelementptrs are likely not good 9494 // candidates for vectorization in a bottom-up phase since one can be 9495 // computed from the other. We also ensure all candidate getelementptr 9496 // indices are unique. 9497 for (int I = 0, E = GEPList.size(); I < E && Candidates.size() > 1; ++I) { 9498 auto *GEPI = GEPList[I]; 9499 if (!Candidates.count(GEPI)) 9500 continue; 9501 auto *SCEVI = SE->getSCEV(GEPList[I]); 9502 for (int J = I + 1; J < E && Candidates.size() > 1; ++J) { 9503 auto *GEPJ = GEPList[J]; 9504 auto *SCEVJ = SE->getSCEV(GEPList[J]); 9505 if (isa<SCEVConstant>(SE->getMinusSCEV(SCEVI, SCEVJ))) { 9506 Candidates.remove(GEPI); 9507 Candidates.remove(GEPJ); 9508 } else if (GEPI->idx_begin()->get() == GEPJ->idx_begin()->get()) { 9509 Candidates.remove(GEPJ); 9510 } 9511 } 9512 } 9513 9514 // We break out of the above computation as soon as we know there are 9515 // fewer than two candidates remaining. 9516 if (Candidates.size() < 2) 9517 continue; 9518 9519 // Add the single, non-constant index of each candidate to the bundle. We 9520 // ensured the indices met these constraints when we originally collected 9521 // the getelementptrs. 9522 SmallVector<Value *, 16> Bundle(Candidates.size()); 9523 auto BundleIndex = 0u; 9524 for (auto *V : Candidates) { 9525 auto *GEP = cast<GetElementPtrInst>(V); 9526 auto *GEPIdx = GEP->idx_begin()->get(); 9527 assert(GEP->getNumIndices() == 1 || !isa<Constant>(GEPIdx)); 9528 Bundle[BundleIndex++] = GEPIdx; 9529 } 9530 9531 // Try and vectorize the indices. We are currently only interested in 9532 // gather-like cases of the form: 9533 // 9534 // ... = g[a[0] - b[0]] + g[a[1] - b[1]] + ... 9535 // 9536 // where the loads of "a", the loads of "b", and the subtractions can be 9537 // performed in parallel. It's likely that detecting this pattern in a 9538 // bottom-up phase will be simpler and less costly than building a 9539 // full-blown top-down phase beginning at the consecutive loads. 9540 Changed |= tryToVectorizeList(Bundle, R); 9541 } 9542 } 9543 return Changed; 9544 } 9545 9546 bool SLPVectorizerPass::vectorizeStoreChains(BoUpSLP &R) { 9547 bool Changed = false; 9548 // Sort by type, base pointers and values operand. Value operands must be 9549 // compatible (have the same opcode, same parent), otherwise it is 9550 // definitely not profitable to try to vectorize them. 9551 auto &&StoreSorter = [this](StoreInst *V, StoreInst *V2) { 9552 if (V->getPointerOperandType()->getTypeID() < 9553 V2->getPointerOperandType()->getTypeID()) 9554 return true; 9555 if (V->getPointerOperandType()->getTypeID() > 9556 V2->getPointerOperandType()->getTypeID()) 9557 return false; 9558 // UndefValues are compatible with all other values. 9559 if (isa<UndefValue>(V->getValueOperand()) || 9560 isa<UndefValue>(V2->getValueOperand())) 9561 return false; 9562 if (auto *I1 = dyn_cast<Instruction>(V->getValueOperand())) 9563 if (auto *I2 = dyn_cast<Instruction>(V2->getValueOperand())) { 9564 DomTreeNodeBase<llvm::BasicBlock> *NodeI1 = 9565 DT->getNode(I1->getParent()); 9566 DomTreeNodeBase<llvm::BasicBlock> *NodeI2 = 9567 DT->getNode(I2->getParent()); 9568 assert(NodeI1 && "Should only process reachable instructions"); 9569 assert(NodeI1 && "Should only process reachable instructions"); 9570 assert((NodeI1 == NodeI2) == 9571 (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) && 9572 "Different nodes should have different DFS numbers"); 9573 if (NodeI1 != NodeI2) 9574 return NodeI1->getDFSNumIn() < NodeI2->getDFSNumIn(); 9575 InstructionsState S = getSameOpcode({I1, I2}); 9576 if (S.getOpcode()) 9577 return false; 9578 return I1->getOpcode() < I2->getOpcode(); 9579 } 9580 if (isa<Constant>(V->getValueOperand()) && 9581 isa<Constant>(V2->getValueOperand())) 9582 return false; 9583 return V->getValueOperand()->getValueID() < 9584 V2->getValueOperand()->getValueID(); 9585 }; 9586 9587 auto &&AreCompatibleStores = [](StoreInst *V1, StoreInst *V2) { 9588 if (V1 == V2) 9589 return true; 9590 if (V1->getPointerOperandType() != V2->getPointerOperandType()) 9591 return false; 9592 // Undefs are compatible with any other value. 9593 if (isa<UndefValue>(V1->getValueOperand()) || 9594 isa<UndefValue>(V2->getValueOperand())) 9595 return true; 9596 if (auto *I1 = dyn_cast<Instruction>(V1->getValueOperand())) 9597 if (auto *I2 = dyn_cast<Instruction>(V2->getValueOperand())) { 9598 if (I1->getParent() != I2->getParent()) 9599 return false; 9600 InstructionsState S = getSameOpcode({I1, I2}); 9601 return S.getOpcode() > 0; 9602 } 9603 if (isa<Constant>(V1->getValueOperand()) && 9604 isa<Constant>(V2->getValueOperand())) 9605 return true; 9606 return V1->getValueOperand()->getValueID() == 9607 V2->getValueOperand()->getValueID(); 9608 }; 9609 auto Limit = [&R, this](StoreInst *SI) { 9610 unsigned EltSize = DL->getTypeSizeInBits(SI->getValueOperand()->getType()); 9611 return R.getMinVF(EltSize); 9612 }; 9613 9614 // Attempt to sort and vectorize each of the store-groups. 9615 for (auto &Pair : Stores) { 9616 if (Pair.second.size() < 2) 9617 continue; 9618 9619 LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length " 9620 << Pair.second.size() << ".\n"); 9621 9622 if (!isValidElementType(Pair.second.front()->getValueOperand()->getType())) 9623 continue; 9624 9625 Changed |= tryToVectorizeSequence<StoreInst>( 9626 Pair.second, Limit, StoreSorter, AreCompatibleStores, 9627 [this, &R](ArrayRef<StoreInst *> Candidates, bool) { 9628 return vectorizeStores(Candidates, R); 9629 }, 9630 /*LimitForRegisterSize=*/false); 9631 } 9632 return Changed; 9633 } 9634 9635 char SLPVectorizer::ID = 0; 9636 9637 static const char lv_name[] = "SLP Vectorizer"; 9638 9639 INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false) 9640 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass) 9641 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass) 9642 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 9643 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass) 9644 INITIALIZE_PASS_DEPENDENCY(LoopSimplify) 9645 INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass) 9646 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass) 9647 INITIALIZE_PASS_DEPENDENCY(InjectTLIMappingsLegacy) 9648 INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false) 9649 9650 Pass *llvm::createSLPVectorizerPass() { return new SLPVectorizer(); } 9651