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