1 //===- SLPVectorizer.cpp - A bottom up SLP Vectorizer ---------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 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 #include "llvm/ADT/MapVector.h" 19 #include "llvm/ADT/Optional.h" 20 #include "llvm/ADT/PostOrderIterator.h" 21 #include "llvm/ADT/SetVector.h" 22 #include "llvm/ADT/Statistic.h" 23 #include "llvm/Analysis/AliasAnalysis.h" 24 #include "llvm/Analysis/AssumptionCache.h" 25 #include "llvm/Analysis/CodeMetrics.h" 26 #include "llvm/Analysis/DemandedBits.h" 27 #include "llvm/Analysis/GlobalsModRef.h" 28 #include "llvm/Analysis/LoopAccessAnalysis.h" 29 #include "llvm/Analysis/LoopInfo.h" 30 #include "llvm/Analysis/LoopAccessAnalysis.h" 31 #include "llvm/Analysis/ScalarEvolution.h" 32 #include "llvm/Analysis/ScalarEvolutionExpressions.h" 33 #include "llvm/Analysis/TargetTransformInfo.h" 34 #include "llvm/Analysis/ValueTracking.h" 35 #include "llvm/Analysis/VectorUtils.h" 36 #include "llvm/IR/DataLayout.h" 37 #include "llvm/IR/Dominators.h" 38 #include "llvm/IR/IRBuilder.h" 39 #include "llvm/IR/Instructions.h" 40 #include "llvm/IR/IntrinsicInst.h" 41 #include "llvm/IR/Module.h" 42 #include "llvm/IR/NoFolder.h" 43 #include "llvm/IR/Type.h" 44 #include "llvm/IR/Value.h" 45 #include "llvm/IR/Verifier.h" 46 #include "llvm/Pass.h" 47 #include "llvm/Support/CommandLine.h" 48 #include "llvm/Support/Debug.h" 49 #include "llvm/Support/raw_ostream.h" 50 #include "llvm/Transforms/Vectorize.h" 51 #include <algorithm> 52 #include <map> 53 #include <memory> 54 55 using namespace llvm; 56 57 #define SV_NAME "slp-vectorizer" 58 #define DEBUG_TYPE "SLP" 59 60 STATISTIC(NumVectorInstructions, "Number of vector instructions generated"); 61 62 static cl::opt<int> 63 SLPCostThreshold("slp-threshold", cl::init(0), cl::Hidden, 64 cl::desc("Only vectorize if you gain more than this " 65 "number ")); 66 67 static cl::opt<bool> 68 ShouldVectorizeHor("slp-vectorize-hor", cl::init(true), cl::Hidden, 69 cl::desc("Attempt to vectorize horizontal reductions")); 70 71 static cl::opt<bool> ShouldStartVectorizeHorAtStore( 72 "slp-vectorize-hor-store", cl::init(false), cl::Hidden, 73 cl::desc( 74 "Attempt to vectorize horizontal reductions feeding into a store")); 75 76 static cl::opt<int> 77 MaxVectorRegSizeOption("slp-max-reg-size", cl::init(128), cl::Hidden, 78 cl::desc("Attempt to vectorize for this register size in bits")); 79 80 /// Limits the size of scheduling regions in a block. 81 /// It avoid long compile times for _very_ large blocks where vector 82 /// instructions are spread over a wide range. 83 /// This limit is way higher than needed by real-world functions. 84 static cl::opt<int> 85 ScheduleRegionSizeBudget("slp-schedule-budget", cl::init(100000), cl::Hidden, 86 cl::desc("Limit the size of the SLP scheduling region per block")); 87 88 namespace { 89 90 // FIXME: Set this via cl::opt to allow overriding. 91 static const unsigned MinVecRegSize = 128; 92 93 static const unsigned RecursionMaxDepth = 12; 94 95 // Limit the number of alias checks. The limit is chosen so that 96 // it has no negative effect on the llvm benchmarks. 97 static const unsigned AliasedCheckLimit = 10; 98 99 // Another limit for the alias checks: The maximum distance between load/store 100 // instructions where alias checks are done. 101 // This limit is useful for very large basic blocks. 102 static const unsigned MaxMemDepDistance = 160; 103 104 /// If the ScheduleRegionSizeBudget is exhausted, we allow small scheduling 105 /// regions to be handled. 106 static const int MinScheduleRegionSize = 16; 107 108 /// \brief Predicate for the element types that the SLP vectorizer supports. 109 /// 110 /// The most important thing to filter here are types which are invalid in LLVM 111 /// vectors. We also filter target specific types which have absolutely no 112 /// meaningful vectorization path such as x86_fp80 and ppc_f128. This just 113 /// avoids spending time checking the cost model and realizing that they will 114 /// be inevitably scalarized. 115 static bool isValidElementType(Type *Ty) { 116 return VectorType::isValidElementType(Ty) && !Ty->isX86_FP80Ty() && 117 !Ty->isPPC_FP128Ty(); 118 } 119 120 /// \returns the parent basic block if all of the instructions in \p VL 121 /// are in the same block or null otherwise. 122 static BasicBlock *getSameBlock(ArrayRef<Value *> VL) { 123 Instruction *I0 = dyn_cast<Instruction>(VL[0]); 124 if (!I0) 125 return nullptr; 126 BasicBlock *BB = I0->getParent(); 127 for (int i = 1, e = VL.size(); i < e; i++) { 128 Instruction *I = dyn_cast<Instruction>(VL[i]); 129 if (!I) 130 return nullptr; 131 132 if (BB != I->getParent()) 133 return nullptr; 134 } 135 return BB; 136 } 137 138 /// \returns True if all of the values in \p VL are constants. 139 static bool allConstant(ArrayRef<Value *> VL) { 140 for (unsigned i = 0, e = VL.size(); i < e; ++i) 141 if (!isa<Constant>(VL[i])) 142 return false; 143 return true; 144 } 145 146 /// \returns True if all of the values in \p VL are identical. 147 static bool isSplat(ArrayRef<Value *> VL) { 148 for (unsigned i = 1, e = VL.size(); i < e; ++i) 149 if (VL[i] != VL[0]) 150 return false; 151 return true; 152 } 153 154 ///\returns Opcode that can be clubbed with \p Op to create an alternate 155 /// sequence which can later be merged as a ShuffleVector instruction. 156 static unsigned getAltOpcode(unsigned Op) { 157 switch (Op) { 158 case Instruction::FAdd: 159 return Instruction::FSub; 160 case Instruction::FSub: 161 return Instruction::FAdd; 162 case Instruction::Add: 163 return Instruction::Sub; 164 case Instruction::Sub: 165 return Instruction::Add; 166 default: 167 return 0; 168 } 169 } 170 171 ///\returns bool representing if Opcode \p Op can be part 172 /// of an alternate sequence which can later be merged as 173 /// a ShuffleVector instruction. 174 static bool canCombineAsAltInst(unsigned Op) { 175 return Op == Instruction::FAdd || Op == Instruction::FSub || 176 Op == Instruction::Sub || Op == Instruction::Add; 177 } 178 179 /// \returns ShuffleVector instruction if instructions in \p VL have 180 /// alternate fadd,fsub / fsub,fadd/add,sub/sub,add sequence. 181 /// (i.e. e.g. opcodes of fadd,fsub,fadd,fsub...) 182 static unsigned isAltInst(ArrayRef<Value *> VL) { 183 Instruction *I0 = dyn_cast<Instruction>(VL[0]); 184 unsigned Opcode = I0->getOpcode(); 185 unsigned AltOpcode = getAltOpcode(Opcode); 186 for (int i = 1, e = VL.size(); i < e; i++) { 187 Instruction *I = dyn_cast<Instruction>(VL[i]); 188 if (!I || I->getOpcode() != ((i & 1) ? AltOpcode : Opcode)) 189 return 0; 190 } 191 return Instruction::ShuffleVector; 192 } 193 194 /// \returns The opcode if all of the Instructions in \p VL have the same 195 /// opcode, or zero. 196 static unsigned getSameOpcode(ArrayRef<Value *> VL) { 197 Instruction *I0 = dyn_cast<Instruction>(VL[0]); 198 if (!I0) 199 return 0; 200 unsigned Opcode = I0->getOpcode(); 201 for (int i = 1, e = VL.size(); i < e; i++) { 202 Instruction *I = dyn_cast<Instruction>(VL[i]); 203 if (!I || Opcode != I->getOpcode()) { 204 if (canCombineAsAltInst(Opcode) && i == 1) 205 return isAltInst(VL); 206 return 0; 207 } 208 } 209 return Opcode; 210 } 211 212 /// Get the intersection (logical and) of all of the potential IR flags 213 /// of each scalar operation (VL) that will be converted into a vector (I). 214 /// Flag set: NSW, NUW, exact, and all of fast-math. 215 static void propagateIRFlags(Value *I, ArrayRef<Value *> VL) { 216 if (auto *VecOp = dyn_cast<BinaryOperator>(I)) { 217 if (auto *Intersection = dyn_cast<BinaryOperator>(VL[0])) { 218 // Intersection is initialized to the 0th scalar, 219 // so start counting from index '1'. 220 for (int i = 1, e = VL.size(); i < e; ++i) { 221 if (auto *Scalar = dyn_cast<BinaryOperator>(VL[i])) 222 Intersection->andIRFlags(Scalar); 223 } 224 VecOp->copyIRFlags(Intersection); 225 } 226 } 227 } 228 229 /// \returns \p I after propagating metadata from \p VL. 230 static Instruction *propagateMetadata(Instruction *I, ArrayRef<Value *> VL) { 231 Instruction *I0 = cast<Instruction>(VL[0]); 232 SmallVector<std::pair<unsigned, MDNode *>, 4> Metadata; 233 I0->getAllMetadataOtherThanDebugLoc(Metadata); 234 235 for (unsigned i = 0, n = Metadata.size(); i != n; ++i) { 236 unsigned Kind = Metadata[i].first; 237 MDNode *MD = Metadata[i].second; 238 239 for (int i = 1, e = VL.size(); MD && i != e; i++) { 240 Instruction *I = cast<Instruction>(VL[i]); 241 MDNode *IMD = I->getMetadata(Kind); 242 243 switch (Kind) { 244 default: 245 MD = nullptr; // Remove unknown metadata 246 break; 247 case LLVMContext::MD_tbaa: 248 MD = MDNode::getMostGenericTBAA(MD, IMD); 249 break; 250 case LLVMContext::MD_alias_scope: 251 MD = MDNode::getMostGenericAliasScope(MD, IMD); 252 break; 253 case LLVMContext::MD_noalias: 254 MD = MDNode::intersect(MD, IMD); 255 break; 256 case LLVMContext::MD_fpmath: 257 MD = MDNode::getMostGenericFPMath(MD, IMD); 258 break; 259 case LLVMContext::MD_nontemporal: 260 MD = MDNode::intersect(MD, IMD); 261 break; 262 } 263 } 264 I->setMetadata(Kind, MD); 265 } 266 return I; 267 } 268 269 /// \returns The type that all of the values in \p VL have or null if there 270 /// are different types. 271 static Type* getSameType(ArrayRef<Value *> VL) { 272 Type *Ty = VL[0]->getType(); 273 for (int i = 1, e = VL.size(); i < e; i++) 274 if (VL[i]->getType() != Ty) 275 return nullptr; 276 277 return Ty; 278 } 279 280 /// \returns True if the ExtractElement instructions in VL can be vectorized 281 /// to use the original vector. 282 static bool CanReuseExtract(ArrayRef<Value *> VL) { 283 assert(Instruction::ExtractElement == getSameOpcode(VL) && "Invalid opcode"); 284 // Check if all of the extracts come from the same vector and from the 285 // correct offset. 286 Value *VL0 = VL[0]; 287 ExtractElementInst *E0 = cast<ExtractElementInst>(VL0); 288 Value *Vec = E0->getOperand(0); 289 290 // We have to extract from the same vector type. 291 unsigned NElts = Vec->getType()->getVectorNumElements(); 292 293 if (NElts != VL.size()) 294 return false; 295 296 // Check that all of the indices extract from the correct offset. 297 ConstantInt *CI = dyn_cast<ConstantInt>(E0->getOperand(1)); 298 if (!CI || CI->getZExtValue()) 299 return false; 300 301 for (unsigned i = 1, e = VL.size(); i < e; ++i) { 302 ExtractElementInst *E = cast<ExtractElementInst>(VL[i]); 303 ConstantInt *CI = dyn_cast<ConstantInt>(E->getOperand(1)); 304 305 if (!CI || CI->getZExtValue() != i || E->getOperand(0) != Vec) 306 return false; 307 } 308 309 return true; 310 } 311 312 /// \returns True if in-tree use also needs extract. This refers to 313 /// possible scalar operand in vectorized instruction. 314 static bool InTreeUserNeedToExtract(Value *Scalar, Instruction *UserInst, 315 TargetLibraryInfo *TLI) { 316 317 unsigned Opcode = UserInst->getOpcode(); 318 switch (Opcode) { 319 case Instruction::Load: { 320 LoadInst *LI = cast<LoadInst>(UserInst); 321 return (LI->getPointerOperand() == Scalar); 322 } 323 case Instruction::Store: { 324 StoreInst *SI = cast<StoreInst>(UserInst); 325 return (SI->getPointerOperand() == Scalar); 326 } 327 case Instruction::Call: { 328 CallInst *CI = cast<CallInst>(UserInst); 329 Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI); 330 if (hasVectorInstrinsicScalarOpd(ID, 1)) { 331 return (CI->getArgOperand(1) == Scalar); 332 } 333 } 334 default: 335 return false; 336 } 337 } 338 339 /// \returns the AA location that is being access by the instruction. 340 static MemoryLocation getLocation(Instruction *I, AliasAnalysis *AA) { 341 if (StoreInst *SI = dyn_cast<StoreInst>(I)) 342 return MemoryLocation::get(SI); 343 if (LoadInst *LI = dyn_cast<LoadInst>(I)) 344 return MemoryLocation::get(LI); 345 return MemoryLocation(); 346 } 347 348 /// \returns True if the instruction is not a volatile or atomic load/store. 349 static bool isSimple(Instruction *I) { 350 if (LoadInst *LI = dyn_cast<LoadInst>(I)) 351 return LI->isSimple(); 352 if (StoreInst *SI = dyn_cast<StoreInst>(I)) 353 return SI->isSimple(); 354 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) 355 return !MI->isVolatile(); 356 return true; 357 } 358 359 /// Bottom Up SLP Vectorizer. 360 class BoUpSLP { 361 public: 362 typedef SmallVector<Value *, 8> ValueList; 363 typedef SmallVector<Instruction *, 16> InstrList; 364 typedef SmallPtrSet<Value *, 16> ValueSet; 365 typedef SmallVector<StoreInst *, 8> StoreList; 366 367 BoUpSLP(Function *Func, ScalarEvolution *Se, TargetTransformInfo *Tti, 368 TargetLibraryInfo *TLi, AliasAnalysis *Aa, LoopInfo *Li, 369 DominatorTree *Dt, AssumptionCache *AC, DemandedBits *DB) 370 : NumLoadsWantToKeepOrder(0), NumLoadsWantToChangeOrder(0), F(Func), 371 SE(Se), TTI(Tti), TLI(TLi), AA(Aa), LI(Li), DT(Dt), AC(AC), DB(DB), 372 Builder(Se->getContext()) { 373 CodeMetrics::collectEphemeralValues(F, AC, EphValues); 374 } 375 376 /// \brief Vectorize the tree that starts with the elements in \p VL. 377 /// Returns the vectorized root. 378 Value *vectorizeTree(); 379 380 /// \returns the cost incurred by unwanted spills and fills, caused by 381 /// holding live values over call sites. 382 int getSpillCost(); 383 384 /// \returns the vectorization cost of the subtree that starts at \p VL. 385 /// A negative number means that this is profitable. 386 int getTreeCost(); 387 388 /// Construct a vectorizable tree that starts at \p Roots, ignoring users for 389 /// the purpose of scheduling and extraction in the \p UserIgnoreLst. 390 void buildTree(ArrayRef<Value *> Roots, 391 ArrayRef<Value *> UserIgnoreLst = None); 392 393 /// Clear the internal data structures that are created by 'buildTree'. 394 void deleteTree() { 395 VectorizableTree.clear(); 396 ScalarToTreeEntry.clear(); 397 MustGather.clear(); 398 ExternalUses.clear(); 399 NumLoadsWantToKeepOrder = 0; 400 NumLoadsWantToChangeOrder = 0; 401 for (auto &Iter : BlocksSchedules) { 402 BlockScheduling *BS = Iter.second.get(); 403 BS->clear(); 404 } 405 MinBWs.clear(); 406 } 407 408 /// \brief Perform LICM and CSE on the newly generated gather sequences. 409 void optimizeGatherSequence(); 410 411 /// \returns true if it is beneficial to reverse the vector order. 412 bool shouldReorder() const { 413 return NumLoadsWantToChangeOrder > NumLoadsWantToKeepOrder; 414 } 415 416 /// \return The vector element size in bits to use when vectorizing the 417 /// expression tree ending at \p V. If V is a store, the size is the width of 418 /// the stored value. Otherwise, the size is the width of the largest loaded 419 /// value reaching V. This method is used by the vectorizer to calculate 420 /// vectorization factors. 421 unsigned getVectorElementSize(Value *V); 422 423 /// Compute the minimum type sizes required to represent the entries in a 424 /// vectorizable tree. 425 void computeMinimumValueSizes(); 426 427 private: 428 struct TreeEntry; 429 430 /// \returns the cost of the vectorizable entry. 431 int getEntryCost(TreeEntry *E); 432 433 /// This is the recursive part of buildTree. 434 void buildTree_rec(ArrayRef<Value *> Roots, unsigned Depth); 435 436 /// Vectorize a single entry in the tree. 437 Value *vectorizeTree(TreeEntry *E); 438 439 /// Vectorize a single entry in the tree, starting in \p VL. 440 Value *vectorizeTree(ArrayRef<Value *> VL); 441 442 /// \returns the pointer to the vectorized value if \p VL is already 443 /// vectorized, or NULL. They may happen in cycles. 444 Value *alreadyVectorized(ArrayRef<Value *> VL) const; 445 446 /// \returns the scalarization cost for this type. Scalarization in this 447 /// context means the creation of vectors from a group of scalars. 448 int getGatherCost(Type *Ty); 449 450 /// \returns the scalarization cost for this list of values. Assuming that 451 /// this subtree gets vectorized, we may need to extract the values from the 452 /// roots. This method calculates the cost of extracting the values. 453 int getGatherCost(ArrayRef<Value *> VL); 454 455 /// \brief Set the Builder insert point to one after the last instruction in 456 /// the bundle 457 void setInsertPointAfterBundle(ArrayRef<Value *> VL); 458 459 /// \returns a vector from a collection of scalars in \p VL. 460 Value *Gather(ArrayRef<Value *> VL, VectorType *Ty); 461 462 /// \returns whether the VectorizableTree is fully vectorizable and will 463 /// be beneficial even the tree height is tiny. 464 bool isFullyVectorizableTinyTree(); 465 466 /// \reorder commutative operands in alt shuffle if they result in 467 /// vectorized code. 468 void reorderAltShuffleOperands(ArrayRef<Value *> VL, 469 SmallVectorImpl<Value *> &Left, 470 SmallVectorImpl<Value *> &Right); 471 /// \reorder commutative operands to get better probability of 472 /// generating vectorized code. 473 void reorderInputsAccordingToOpcode(ArrayRef<Value *> VL, 474 SmallVectorImpl<Value *> &Left, 475 SmallVectorImpl<Value *> &Right); 476 struct TreeEntry { 477 TreeEntry() : Scalars(), VectorizedValue(nullptr), 478 NeedToGather(0) {} 479 480 /// \returns true if the scalars in VL are equal to this entry. 481 bool isSame(ArrayRef<Value *> VL) const { 482 assert(VL.size() == Scalars.size() && "Invalid size"); 483 return std::equal(VL.begin(), VL.end(), Scalars.begin()); 484 } 485 486 /// A vector of scalars. 487 ValueList Scalars; 488 489 /// The Scalars are vectorized into this value. It is initialized to Null. 490 Value *VectorizedValue; 491 492 /// Do we need to gather this sequence ? 493 bool NeedToGather; 494 }; 495 496 /// Create a new VectorizableTree entry. 497 TreeEntry *newTreeEntry(ArrayRef<Value *> VL, bool Vectorized) { 498 VectorizableTree.emplace_back(); 499 int idx = VectorizableTree.size() - 1; 500 TreeEntry *Last = &VectorizableTree[idx]; 501 Last->Scalars.insert(Last->Scalars.begin(), VL.begin(), VL.end()); 502 Last->NeedToGather = !Vectorized; 503 if (Vectorized) { 504 for (int i = 0, e = VL.size(); i != e; ++i) { 505 assert(!ScalarToTreeEntry.count(VL[i]) && "Scalar already in tree!"); 506 ScalarToTreeEntry[VL[i]] = idx; 507 } 508 } else { 509 MustGather.insert(VL.begin(), VL.end()); 510 } 511 return Last; 512 } 513 514 /// -- Vectorization State -- 515 /// Holds all of the tree entries. 516 std::vector<TreeEntry> VectorizableTree; 517 518 /// Maps a specific scalar to its tree entry. 519 SmallDenseMap<Value*, int> ScalarToTreeEntry; 520 521 /// A list of scalars that we found that we need to keep as scalars. 522 ValueSet MustGather; 523 524 /// This POD struct describes one external user in the vectorized tree. 525 struct ExternalUser { 526 ExternalUser (Value *S, llvm::User *U, int L) : 527 Scalar(S), User(U), Lane(L){} 528 // Which scalar in our function. 529 Value *Scalar; 530 // Which user that uses the scalar. 531 llvm::User *User; 532 // Which lane does the scalar belong to. 533 int Lane; 534 }; 535 typedef SmallVector<ExternalUser, 16> UserList; 536 537 /// Checks if two instructions may access the same memory. 538 /// 539 /// \p Loc1 is the location of \p Inst1. It is passed explicitly because it 540 /// is invariant in the calling loop. 541 bool isAliased(const MemoryLocation &Loc1, Instruction *Inst1, 542 Instruction *Inst2) { 543 544 // First check if the result is already in the cache. 545 AliasCacheKey key = std::make_pair(Inst1, Inst2); 546 Optional<bool> &result = AliasCache[key]; 547 if (result.hasValue()) { 548 return result.getValue(); 549 } 550 MemoryLocation Loc2 = getLocation(Inst2, AA); 551 bool aliased = true; 552 if (Loc1.Ptr && Loc2.Ptr && isSimple(Inst1) && isSimple(Inst2)) { 553 // Do the alias check. 554 aliased = AA->alias(Loc1, Loc2); 555 } 556 // Store the result in the cache. 557 result = aliased; 558 return aliased; 559 } 560 561 typedef std::pair<Instruction *, Instruction *> AliasCacheKey; 562 563 /// Cache for alias results. 564 /// TODO: consider moving this to the AliasAnalysis itself. 565 DenseMap<AliasCacheKey, Optional<bool>> AliasCache; 566 567 /// Removes an instruction from its block and eventually deletes it. 568 /// It's like Instruction::eraseFromParent() except that the actual deletion 569 /// is delayed until BoUpSLP is destructed. 570 /// This is required to ensure that there are no incorrect collisions in the 571 /// AliasCache, which can happen if a new instruction is allocated at the 572 /// same address as a previously deleted instruction. 573 void eraseInstruction(Instruction *I) { 574 I->removeFromParent(); 575 I->dropAllReferences(); 576 DeletedInstructions.push_back(std::unique_ptr<Instruction>(I)); 577 } 578 579 /// Temporary store for deleted instructions. Instructions will be deleted 580 /// eventually when the BoUpSLP is destructed. 581 SmallVector<std::unique_ptr<Instruction>, 8> DeletedInstructions; 582 583 /// A list of values that need to extracted out of the tree. 584 /// This list holds pairs of (Internal Scalar : External User). 585 UserList ExternalUses; 586 587 /// Values used only by @llvm.assume calls. 588 SmallPtrSet<const Value *, 32> EphValues; 589 590 /// Holds all of the instructions that we gathered. 591 SetVector<Instruction *> GatherSeq; 592 /// A list of blocks that we are going to CSE. 593 SetVector<BasicBlock *> CSEBlocks; 594 595 /// Contains all scheduling relevant data for an instruction. 596 /// A ScheduleData either represents a single instruction or a member of an 597 /// instruction bundle (= a group of instructions which is combined into a 598 /// vector instruction). 599 struct ScheduleData { 600 601 // The initial value for the dependency counters. It means that the 602 // dependencies are not calculated yet. 603 enum { InvalidDeps = -1 }; 604 605 ScheduleData() 606 : Inst(nullptr), FirstInBundle(nullptr), NextInBundle(nullptr), 607 NextLoadStore(nullptr), SchedulingRegionID(0), SchedulingPriority(0), 608 Dependencies(InvalidDeps), UnscheduledDeps(InvalidDeps), 609 UnscheduledDepsInBundle(InvalidDeps), IsScheduled(false) {} 610 611 void init(int BlockSchedulingRegionID) { 612 FirstInBundle = this; 613 NextInBundle = nullptr; 614 NextLoadStore = nullptr; 615 IsScheduled = false; 616 SchedulingRegionID = BlockSchedulingRegionID; 617 UnscheduledDepsInBundle = UnscheduledDeps; 618 clearDependencies(); 619 } 620 621 /// Returns true if the dependency information has been calculated. 622 bool hasValidDependencies() const { return Dependencies != InvalidDeps; } 623 624 /// Returns true for single instructions and for bundle representatives 625 /// (= the head of a bundle). 626 bool isSchedulingEntity() const { return FirstInBundle == this; } 627 628 /// Returns true if it represents an instruction bundle and not only a 629 /// single instruction. 630 bool isPartOfBundle() const { 631 return NextInBundle != nullptr || FirstInBundle != this; 632 } 633 634 /// Returns true if it is ready for scheduling, i.e. it has no more 635 /// unscheduled depending instructions/bundles. 636 bool isReady() const { 637 assert(isSchedulingEntity() && 638 "can't consider non-scheduling entity for ready list"); 639 return UnscheduledDepsInBundle == 0 && !IsScheduled; 640 } 641 642 /// Modifies the number of unscheduled dependencies, also updating it for 643 /// the whole bundle. 644 int incrementUnscheduledDeps(int Incr) { 645 UnscheduledDeps += Incr; 646 return FirstInBundle->UnscheduledDepsInBundle += Incr; 647 } 648 649 /// Sets the number of unscheduled dependencies to the number of 650 /// dependencies. 651 void resetUnscheduledDeps() { 652 incrementUnscheduledDeps(Dependencies - UnscheduledDeps); 653 } 654 655 /// Clears all dependency information. 656 void clearDependencies() { 657 Dependencies = InvalidDeps; 658 resetUnscheduledDeps(); 659 MemoryDependencies.clear(); 660 } 661 662 void dump(raw_ostream &os) const { 663 if (!isSchedulingEntity()) { 664 os << "/ " << *Inst; 665 } else if (NextInBundle) { 666 os << '[' << *Inst; 667 ScheduleData *SD = NextInBundle; 668 while (SD) { 669 os << ';' << *SD->Inst; 670 SD = SD->NextInBundle; 671 } 672 os << ']'; 673 } else { 674 os << *Inst; 675 } 676 } 677 678 Instruction *Inst; 679 680 /// Points to the head in an instruction bundle (and always to this for 681 /// single instructions). 682 ScheduleData *FirstInBundle; 683 684 /// Single linked list of all instructions in a bundle. Null if it is a 685 /// single instruction. 686 ScheduleData *NextInBundle; 687 688 /// Single linked list of all memory instructions (e.g. load, store, call) 689 /// in the block - until the end of the scheduling region. 690 ScheduleData *NextLoadStore; 691 692 /// The dependent memory instructions. 693 /// This list is derived on demand in calculateDependencies(). 694 SmallVector<ScheduleData *, 4> MemoryDependencies; 695 696 /// This ScheduleData is in the current scheduling region if this matches 697 /// the current SchedulingRegionID of BlockScheduling. 698 int SchedulingRegionID; 699 700 /// Used for getting a "good" final ordering of instructions. 701 int SchedulingPriority; 702 703 /// The number of dependencies. Constitutes of the number of users of the 704 /// instruction plus the number of dependent memory instructions (if any). 705 /// This value is calculated on demand. 706 /// If InvalidDeps, the number of dependencies is not calculated yet. 707 /// 708 int Dependencies; 709 710 /// The number of dependencies minus the number of dependencies of scheduled 711 /// instructions. As soon as this is zero, the instruction/bundle gets ready 712 /// for scheduling. 713 /// Note that this is negative as long as Dependencies is not calculated. 714 int UnscheduledDeps; 715 716 /// The sum of UnscheduledDeps in a bundle. Equals to UnscheduledDeps for 717 /// single instructions. 718 int UnscheduledDepsInBundle; 719 720 /// True if this instruction is scheduled (or considered as scheduled in the 721 /// dry-run). 722 bool IsScheduled; 723 }; 724 725 #ifndef NDEBUG 726 friend raw_ostream &operator<<(raw_ostream &os, 727 const BoUpSLP::ScheduleData &SD); 728 #endif 729 730 /// Contains all scheduling data for a basic block. 731 /// 732 struct BlockScheduling { 733 734 BlockScheduling(BasicBlock *BB) 735 : BB(BB), ChunkSize(BB->size()), ChunkPos(ChunkSize), 736 ScheduleStart(nullptr), ScheduleEnd(nullptr), 737 FirstLoadStoreInRegion(nullptr), LastLoadStoreInRegion(nullptr), 738 ScheduleRegionSize(0), 739 ScheduleRegionSizeLimit(ScheduleRegionSizeBudget), 740 // Make sure that the initial SchedulingRegionID is greater than the 741 // initial SchedulingRegionID in ScheduleData (which is 0). 742 SchedulingRegionID(1) {} 743 744 void clear() { 745 ReadyInsts.clear(); 746 ScheduleStart = nullptr; 747 ScheduleEnd = nullptr; 748 FirstLoadStoreInRegion = nullptr; 749 LastLoadStoreInRegion = nullptr; 750 751 // Reduce the maximum schedule region size by the size of the 752 // previous scheduling run. 753 ScheduleRegionSizeLimit -= ScheduleRegionSize; 754 if (ScheduleRegionSizeLimit < MinScheduleRegionSize) 755 ScheduleRegionSizeLimit = MinScheduleRegionSize; 756 ScheduleRegionSize = 0; 757 758 // Make a new scheduling region, i.e. all existing ScheduleData is not 759 // in the new region yet. 760 ++SchedulingRegionID; 761 } 762 763 ScheduleData *getScheduleData(Value *V) { 764 ScheduleData *SD = ScheduleDataMap[V]; 765 if (SD && SD->SchedulingRegionID == SchedulingRegionID) 766 return SD; 767 return nullptr; 768 } 769 770 bool isInSchedulingRegion(ScheduleData *SD) { 771 return SD->SchedulingRegionID == SchedulingRegionID; 772 } 773 774 /// Marks an instruction as scheduled and puts all dependent ready 775 /// instructions into the ready-list. 776 template <typename ReadyListType> 777 void schedule(ScheduleData *SD, ReadyListType &ReadyList) { 778 SD->IsScheduled = true; 779 DEBUG(dbgs() << "SLP: schedule " << *SD << "\n"); 780 781 ScheduleData *BundleMember = SD; 782 while (BundleMember) { 783 // Handle the def-use chain dependencies. 784 for (Use &U : BundleMember->Inst->operands()) { 785 ScheduleData *OpDef = getScheduleData(U.get()); 786 if (OpDef && OpDef->hasValidDependencies() && 787 OpDef->incrementUnscheduledDeps(-1) == 0) { 788 // There are no more unscheduled dependencies after decrementing, 789 // so we can put the dependent instruction into the ready list. 790 ScheduleData *DepBundle = OpDef->FirstInBundle; 791 assert(!DepBundle->IsScheduled && 792 "already scheduled bundle gets ready"); 793 ReadyList.insert(DepBundle); 794 DEBUG(dbgs() << "SLP: gets ready (def): " << *DepBundle << "\n"); 795 } 796 } 797 // Handle the memory dependencies. 798 for (ScheduleData *MemoryDepSD : BundleMember->MemoryDependencies) { 799 if (MemoryDepSD->incrementUnscheduledDeps(-1) == 0) { 800 // There are no more unscheduled dependencies after decrementing, 801 // so we can put the dependent instruction into the ready list. 802 ScheduleData *DepBundle = MemoryDepSD->FirstInBundle; 803 assert(!DepBundle->IsScheduled && 804 "already scheduled bundle gets ready"); 805 ReadyList.insert(DepBundle); 806 DEBUG(dbgs() << "SLP: gets ready (mem): " << *DepBundle << "\n"); 807 } 808 } 809 BundleMember = BundleMember->NextInBundle; 810 } 811 } 812 813 /// Put all instructions into the ReadyList which are ready for scheduling. 814 template <typename ReadyListType> 815 void initialFillReadyList(ReadyListType &ReadyList) { 816 for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) { 817 ScheduleData *SD = getScheduleData(I); 818 if (SD->isSchedulingEntity() && SD->isReady()) { 819 ReadyList.insert(SD); 820 DEBUG(dbgs() << "SLP: initially in ready list: " << *I << "\n"); 821 } 822 } 823 } 824 825 /// Checks if a bundle of instructions can be scheduled, i.e. has no 826 /// cyclic dependencies. This is only a dry-run, no instructions are 827 /// actually moved at this stage. 828 bool tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP); 829 830 /// Un-bundles a group of instructions. 831 void cancelScheduling(ArrayRef<Value *> VL); 832 833 /// Extends the scheduling region so that V is inside the region. 834 /// \returns true if the region size is within the limit. 835 bool extendSchedulingRegion(Value *V); 836 837 /// Initialize the ScheduleData structures for new instructions in the 838 /// scheduling region. 839 void initScheduleData(Instruction *FromI, Instruction *ToI, 840 ScheduleData *PrevLoadStore, 841 ScheduleData *NextLoadStore); 842 843 /// Updates the dependency information of a bundle and of all instructions/ 844 /// bundles which depend on the original bundle. 845 void calculateDependencies(ScheduleData *SD, bool InsertInReadyList, 846 BoUpSLP *SLP); 847 848 /// Sets all instruction in the scheduling region to un-scheduled. 849 void resetSchedule(); 850 851 BasicBlock *BB; 852 853 /// Simple memory allocation for ScheduleData. 854 std::vector<std::unique_ptr<ScheduleData[]>> ScheduleDataChunks; 855 856 /// The size of a ScheduleData array in ScheduleDataChunks. 857 int ChunkSize; 858 859 /// The allocator position in the current chunk, which is the last entry 860 /// of ScheduleDataChunks. 861 int ChunkPos; 862 863 /// Attaches ScheduleData to Instruction. 864 /// Note that the mapping survives during all vectorization iterations, i.e. 865 /// ScheduleData structures are recycled. 866 DenseMap<Value *, ScheduleData *> ScheduleDataMap; 867 868 struct ReadyList : SmallVector<ScheduleData *, 8> { 869 void insert(ScheduleData *SD) { push_back(SD); } 870 }; 871 872 /// The ready-list for scheduling (only used for the dry-run). 873 ReadyList ReadyInsts; 874 875 /// The first instruction of the scheduling region. 876 Instruction *ScheduleStart; 877 878 /// The first instruction _after_ the scheduling region. 879 Instruction *ScheduleEnd; 880 881 /// The first memory accessing instruction in the scheduling region 882 /// (can be null). 883 ScheduleData *FirstLoadStoreInRegion; 884 885 /// The last memory accessing instruction in the scheduling region 886 /// (can be null). 887 ScheduleData *LastLoadStoreInRegion; 888 889 /// The current size of the scheduling region. 890 int ScheduleRegionSize; 891 892 /// The maximum size allowed for the scheduling region. 893 int ScheduleRegionSizeLimit; 894 895 /// The ID of the scheduling region. For a new vectorization iteration this 896 /// is incremented which "removes" all ScheduleData from the region. 897 int SchedulingRegionID; 898 }; 899 900 /// Attaches the BlockScheduling structures to basic blocks. 901 MapVector<BasicBlock *, std::unique_ptr<BlockScheduling>> BlocksSchedules; 902 903 /// Performs the "real" scheduling. Done before vectorization is actually 904 /// performed in a basic block. 905 void scheduleBlock(BlockScheduling *BS); 906 907 /// List of users to ignore during scheduling and that don't need extracting. 908 ArrayRef<Value *> UserIgnoreList; 909 910 // Number of load-bundles, which contain consecutive loads. 911 int NumLoadsWantToKeepOrder; 912 913 // Number of load-bundles of size 2, which are consecutive loads if reversed. 914 int NumLoadsWantToChangeOrder; 915 916 // Analysis and block reference. 917 Function *F; 918 ScalarEvolution *SE; 919 TargetTransformInfo *TTI; 920 TargetLibraryInfo *TLI; 921 AliasAnalysis *AA; 922 LoopInfo *LI; 923 DominatorTree *DT; 924 AssumptionCache *AC; 925 DemandedBits *DB; 926 /// Instruction builder to construct the vectorized tree. 927 IRBuilder<> Builder; 928 929 /// A map of scalar integer values to the smallest bit width with which they 930 /// can legally be represented. 931 MapVector<Value *, uint64_t> MinBWs; 932 }; 933 934 #ifndef NDEBUG 935 raw_ostream &operator<<(raw_ostream &os, const BoUpSLP::ScheduleData &SD) { 936 SD.dump(os); 937 return os; 938 } 939 #endif 940 941 void BoUpSLP::buildTree(ArrayRef<Value *> Roots, 942 ArrayRef<Value *> UserIgnoreLst) { 943 deleteTree(); 944 UserIgnoreList = UserIgnoreLst; 945 if (!getSameType(Roots)) 946 return; 947 buildTree_rec(Roots, 0); 948 949 // Collect the values that we need to extract from the tree. 950 for (int EIdx = 0, EE = VectorizableTree.size(); EIdx < EE; ++EIdx) { 951 TreeEntry *Entry = &VectorizableTree[EIdx]; 952 953 // For each lane: 954 for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) { 955 Value *Scalar = Entry->Scalars[Lane]; 956 957 // No need to handle users of gathered values. 958 if (Entry->NeedToGather) 959 continue; 960 961 for (User *U : Scalar->users()) { 962 DEBUG(dbgs() << "SLP: Checking user:" << *U << ".\n"); 963 964 Instruction *UserInst = dyn_cast<Instruction>(U); 965 if (!UserInst) 966 continue; 967 968 // Skip in-tree scalars that become vectors 969 if (ScalarToTreeEntry.count(U)) { 970 int Idx = ScalarToTreeEntry[U]; 971 TreeEntry *UseEntry = &VectorizableTree[Idx]; 972 Value *UseScalar = UseEntry->Scalars[0]; 973 // Some in-tree scalars will remain as scalar in vectorized 974 // instructions. If that is the case, the one in Lane 0 will 975 // be used. 976 if (UseScalar != U || 977 !InTreeUserNeedToExtract(Scalar, UserInst, TLI)) { 978 DEBUG(dbgs() << "SLP: \tInternal user will be removed:" << *U 979 << ".\n"); 980 assert(!VectorizableTree[Idx].NeedToGather && "Bad state"); 981 continue; 982 } 983 } 984 985 // Ignore users in the user ignore list. 986 if (std::find(UserIgnoreList.begin(), UserIgnoreList.end(), UserInst) != 987 UserIgnoreList.end()) 988 continue; 989 990 DEBUG(dbgs() << "SLP: Need to extract:" << *U << " from lane " << 991 Lane << " from " << *Scalar << ".\n"); 992 ExternalUses.push_back(ExternalUser(Scalar, U, Lane)); 993 } 994 } 995 } 996 } 997 998 999 void BoUpSLP::buildTree_rec(ArrayRef<Value *> VL, unsigned Depth) { 1000 bool SameTy = getSameType(VL); (void)SameTy; 1001 bool isAltShuffle = false; 1002 assert(SameTy && "Invalid types!"); 1003 1004 if (Depth == RecursionMaxDepth) { 1005 DEBUG(dbgs() << "SLP: Gathering due to max recursion depth.\n"); 1006 newTreeEntry(VL, false); 1007 return; 1008 } 1009 1010 // Don't handle vectors. 1011 if (VL[0]->getType()->isVectorTy()) { 1012 DEBUG(dbgs() << "SLP: Gathering due to vector type.\n"); 1013 newTreeEntry(VL, false); 1014 return; 1015 } 1016 1017 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0])) 1018 if (SI->getValueOperand()->getType()->isVectorTy()) { 1019 DEBUG(dbgs() << "SLP: Gathering due to store vector type.\n"); 1020 newTreeEntry(VL, false); 1021 return; 1022 } 1023 unsigned Opcode = getSameOpcode(VL); 1024 1025 // Check that this shuffle vector refers to the alternate 1026 // sequence of opcodes. 1027 if (Opcode == Instruction::ShuffleVector) { 1028 Instruction *I0 = dyn_cast<Instruction>(VL[0]); 1029 unsigned Op = I0->getOpcode(); 1030 if (Op != Instruction::ShuffleVector) 1031 isAltShuffle = true; 1032 } 1033 1034 // If all of the operands are identical or constant we have a simple solution. 1035 if (allConstant(VL) || isSplat(VL) || !getSameBlock(VL) || !Opcode) { 1036 DEBUG(dbgs() << "SLP: Gathering due to C,S,B,O. \n"); 1037 newTreeEntry(VL, false); 1038 return; 1039 } 1040 1041 // We now know that this is a vector of instructions of the same type from 1042 // the same block. 1043 1044 // Don't vectorize ephemeral values. 1045 for (unsigned i = 0, e = VL.size(); i != e; ++i) { 1046 if (EphValues.count(VL[i])) { 1047 DEBUG(dbgs() << "SLP: The instruction (" << *VL[i] << 1048 ") is ephemeral.\n"); 1049 newTreeEntry(VL, false); 1050 return; 1051 } 1052 } 1053 1054 // Check if this is a duplicate of another entry. 1055 if (ScalarToTreeEntry.count(VL[0])) { 1056 int Idx = ScalarToTreeEntry[VL[0]]; 1057 TreeEntry *E = &VectorizableTree[Idx]; 1058 for (unsigned i = 0, e = VL.size(); i != e; ++i) { 1059 DEBUG(dbgs() << "SLP: \tChecking bundle: " << *VL[i] << ".\n"); 1060 if (E->Scalars[i] != VL[i]) { 1061 DEBUG(dbgs() << "SLP: Gathering due to partial overlap.\n"); 1062 newTreeEntry(VL, false); 1063 return; 1064 } 1065 } 1066 DEBUG(dbgs() << "SLP: Perfect diamond merge at " << *VL[0] << ".\n"); 1067 return; 1068 } 1069 1070 // Check that none of the instructions in the bundle are already in the tree. 1071 for (unsigned i = 0, e = VL.size(); i != e; ++i) { 1072 if (ScalarToTreeEntry.count(VL[i])) { 1073 DEBUG(dbgs() << "SLP: The instruction (" << *VL[i] << 1074 ") is already in tree.\n"); 1075 newTreeEntry(VL, false); 1076 return; 1077 } 1078 } 1079 1080 // If any of the scalars is marked as a value that needs to stay scalar then 1081 // we need to gather the scalars. 1082 for (unsigned i = 0, e = VL.size(); i != e; ++i) { 1083 if (MustGather.count(VL[i])) { 1084 DEBUG(dbgs() << "SLP: Gathering due to gathered scalar.\n"); 1085 newTreeEntry(VL, false); 1086 return; 1087 } 1088 } 1089 1090 // Check that all of the users of the scalars that we want to vectorize are 1091 // schedulable. 1092 Instruction *VL0 = cast<Instruction>(VL[0]); 1093 BasicBlock *BB = cast<Instruction>(VL0)->getParent(); 1094 1095 if (!DT->isReachableFromEntry(BB)) { 1096 // Don't go into unreachable blocks. They may contain instructions with 1097 // dependency cycles which confuse the final scheduling. 1098 DEBUG(dbgs() << "SLP: bundle in unreachable block.\n"); 1099 newTreeEntry(VL, false); 1100 return; 1101 } 1102 1103 // Check that every instructions appears once in this bundle. 1104 for (unsigned i = 0, e = VL.size(); i < e; ++i) 1105 for (unsigned j = i+1; j < e; ++j) 1106 if (VL[i] == VL[j]) { 1107 DEBUG(dbgs() << "SLP: Scalar used twice in bundle.\n"); 1108 newTreeEntry(VL, false); 1109 return; 1110 } 1111 1112 auto &BSRef = BlocksSchedules[BB]; 1113 if (!BSRef) { 1114 BSRef = llvm::make_unique<BlockScheduling>(BB); 1115 } 1116 BlockScheduling &BS = *BSRef.get(); 1117 1118 if (!BS.tryScheduleBundle(VL, this)) { 1119 DEBUG(dbgs() << "SLP: We are not able to schedule this bundle!\n"); 1120 assert((!BS.getScheduleData(VL[0]) || 1121 !BS.getScheduleData(VL[0])->isPartOfBundle()) && 1122 "tryScheduleBundle should cancelScheduling on failure"); 1123 newTreeEntry(VL, false); 1124 return; 1125 } 1126 DEBUG(dbgs() << "SLP: We are able to schedule this bundle.\n"); 1127 1128 switch (Opcode) { 1129 case Instruction::PHI: { 1130 PHINode *PH = dyn_cast<PHINode>(VL0); 1131 1132 // Check for terminator values (e.g. invoke). 1133 for (unsigned j = 0; j < VL.size(); ++j) 1134 for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) { 1135 TerminatorInst *Term = dyn_cast<TerminatorInst>( 1136 cast<PHINode>(VL[j])->getIncomingValueForBlock(PH->getIncomingBlock(i))); 1137 if (Term) { 1138 DEBUG(dbgs() << "SLP: Need to swizzle PHINodes (TerminatorInst use).\n"); 1139 BS.cancelScheduling(VL); 1140 newTreeEntry(VL, false); 1141 return; 1142 } 1143 } 1144 1145 newTreeEntry(VL, true); 1146 DEBUG(dbgs() << "SLP: added a vector of PHINodes.\n"); 1147 1148 for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) { 1149 ValueList Operands; 1150 // Prepare the operand vector. 1151 for (unsigned j = 0; j < VL.size(); ++j) 1152 Operands.push_back(cast<PHINode>(VL[j])->getIncomingValueForBlock( 1153 PH->getIncomingBlock(i))); 1154 1155 buildTree_rec(Operands, Depth + 1); 1156 } 1157 return; 1158 } 1159 case Instruction::ExtractElement: { 1160 bool Reuse = CanReuseExtract(VL); 1161 if (Reuse) { 1162 DEBUG(dbgs() << "SLP: Reusing extract sequence.\n"); 1163 } else { 1164 BS.cancelScheduling(VL); 1165 } 1166 newTreeEntry(VL, Reuse); 1167 return; 1168 } 1169 case Instruction::Load: { 1170 // Check that a vectorized load would load the same memory as a scalar 1171 // load. 1172 // For example we don't want vectorize loads that are smaller than 8 bit. 1173 // Even though we have a packed struct {<i2, i2, i2, i2>} LLVM treats 1174 // loading/storing it as an i8 struct. If we vectorize loads/stores from 1175 // such a struct we read/write packed bits disagreeing with the 1176 // unvectorized version. 1177 const DataLayout &DL = F->getParent()->getDataLayout(); 1178 Type *ScalarTy = VL[0]->getType(); 1179 1180 if (DL.getTypeSizeInBits(ScalarTy) != 1181 DL.getTypeAllocSizeInBits(ScalarTy)) { 1182 BS.cancelScheduling(VL); 1183 newTreeEntry(VL, false); 1184 DEBUG(dbgs() << "SLP: Gathering loads of non-packed type.\n"); 1185 return; 1186 } 1187 // Check if the loads are consecutive or of we need to swizzle them. 1188 for (unsigned i = 0, e = VL.size() - 1; i < e; ++i) { 1189 LoadInst *L = cast<LoadInst>(VL[i]); 1190 if (!L->isSimple()) { 1191 BS.cancelScheduling(VL); 1192 newTreeEntry(VL, false); 1193 DEBUG(dbgs() << "SLP: Gathering non-simple loads.\n"); 1194 return; 1195 } 1196 1197 if (!isConsecutiveAccess(VL[i], VL[i + 1], DL, *SE)) { 1198 if (VL.size() == 2 && isConsecutiveAccess(VL[1], VL[0], DL, *SE)) { 1199 ++NumLoadsWantToChangeOrder; 1200 } 1201 BS.cancelScheduling(VL); 1202 newTreeEntry(VL, false); 1203 DEBUG(dbgs() << "SLP: Gathering non-consecutive loads.\n"); 1204 return; 1205 } 1206 } 1207 ++NumLoadsWantToKeepOrder; 1208 newTreeEntry(VL, true); 1209 DEBUG(dbgs() << "SLP: added a vector of loads.\n"); 1210 return; 1211 } 1212 case Instruction::ZExt: 1213 case Instruction::SExt: 1214 case Instruction::FPToUI: 1215 case Instruction::FPToSI: 1216 case Instruction::FPExt: 1217 case Instruction::PtrToInt: 1218 case Instruction::IntToPtr: 1219 case Instruction::SIToFP: 1220 case Instruction::UIToFP: 1221 case Instruction::Trunc: 1222 case Instruction::FPTrunc: 1223 case Instruction::BitCast: { 1224 Type *SrcTy = VL0->getOperand(0)->getType(); 1225 for (unsigned i = 0; i < VL.size(); ++i) { 1226 Type *Ty = cast<Instruction>(VL[i])->getOperand(0)->getType(); 1227 if (Ty != SrcTy || !isValidElementType(Ty)) { 1228 BS.cancelScheduling(VL); 1229 newTreeEntry(VL, false); 1230 DEBUG(dbgs() << "SLP: Gathering casts with different src types.\n"); 1231 return; 1232 } 1233 } 1234 newTreeEntry(VL, true); 1235 DEBUG(dbgs() << "SLP: added a vector of casts.\n"); 1236 1237 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) { 1238 ValueList Operands; 1239 // Prepare the operand vector. 1240 for (unsigned j = 0; j < VL.size(); ++j) 1241 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i)); 1242 1243 buildTree_rec(Operands, Depth+1); 1244 } 1245 return; 1246 } 1247 case Instruction::ICmp: 1248 case Instruction::FCmp: { 1249 // Check that all of the compares have the same predicate. 1250 CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate(); 1251 Type *ComparedTy = cast<Instruction>(VL[0])->getOperand(0)->getType(); 1252 for (unsigned i = 1, e = VL.size(); i < e; ++i) { 1253 CmpInst *Cmp = cast<CmpInst>(VL[i]); 1254 if (Cmp->getPredicate() != P0 || 1255 Cmp->getOperand(0)->getType() != ComparedTy) { 1256 BS.cancelScheduling(VL); 1257 newTreeEntry(VL, false); 1258 DEBUG(dbgs() << "SLP: Gathering cmp with different predicate.\n"); 1259 return; 1260 } 1261 } 1262 1263 newTreeEntry(VL, true); 1264 DEBUG(dbgs() << "SLP: added a vector of compares.\n"); 1265 1266 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) { 1267 ValueList Operands; 1268 // Prepare the operand vector. 1269 for (unsigned j = 0; j < VL.size(); ++j) 1270 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i)); 1271 1272 buildTree_rec(Operands, Depth+1); 1273 } 1274 return; 1275 } 1276 case Instruction::Select: 1277 case Instruction::Add: 1278 case Instruction::FAdd: 1279 case Instruction::Sub: 1280 case Instruction::FSub: 1281 case Instruction::Mul: 1282 case Instruction::FMul: 1283 case Instruction::UDiv: 1284 case Instruction::SDiv: 1285 case Instruction::FDiv: 1286 case Instruction::URem: 1287 case Instruction::SRem: 1288 case Instruction::FRem: 1289 case Instruction::Shl: 1290 case Instruction::LShr: 1291 case Instruction::AShr: 1292 case Instruction::And: 1293 case Instruction::Or: 1294 case Instruction::Xor: { 1295 newTreeEntry(VL, true); 1296 DEBUG(dbgs() << "SLP: added a vector of bin op.\n"); 1297 1298 // Sort operands of the instructions so that each side is more likely to 1299 // have the same opcode. 1300 if (isa<BinaryOperator>(VL0) && VL0->isCommutative()) { 1301 ValueList Left, Right; 1302 reorderInputsAccordingToOpcode(VL, Left, Right); 1303 buildTree_rec(Left, Depth + 1); 1304 buildTree_rec(Right, Depth + 1); 1305 return; 1306 } 1307 1308 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) { 1309 ValueList Operands; 1310 // Prepare the operand vector. 1311 for (unsigned j = 0; j < VL.size(); ++j) 1312 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i)); 1313 1314 buildTree_rec(Operands, Depth+1); 1315 } 1316 return; 1317 } 1318 case Instruction::GetElementPtr: { 1319 // We don't combine GEPs with complicated (nested) indexing. 1320 for (unsigned j = 0; j < VL.size(); ++j) { 1321 if (cast<Instruction>(VL[j])->getNumOperands() != 2) { 1322 DEBUG(dbgs() << "SLP: not-vectorizable GEP (nested indexes).\n"); 1323 BS.cancelScheduling(VL); 1324 newTreeEntry(VL, false); 1325 return; 1326 } 1327 } 1328 1329 // We can't combine several GEPs into one vector if they operate on 1330 // different types. 1331 Type *Ty0 = cast<Instruction>(VL0)->getOperand(0)->getType(); 1332 for (unsigned j = 0; j < VL.size(); ++j) { 1333 Type *CurTy = cast<Instruction>(VL[j])->getOperand(0)->getType(); 1334 if (Ty0 != CurTy) { 1335 DEBUG(dbgs() << "SLP: not-vectorizable GEP (different types).\n"); 1336 BS.cancelScheduling(VL); 1337 newTreeEntry(VL, false); 1338 return; 1339 } 1340 } 1341 1342 // We don't combine GEPs with non-constant indexes. 1343 for (unsigned j = 0; j < VL.size(); ++j) { 1344 auto Op = cast<Instruction>(VL[j])->getOperand(1); 1345 if (!isa<ConstantInt>(Op)) { 1346 DEBUG( 1347 dbgs() << "SLP: not-vectorizable GEP (non-constant indexes).\n"); 1348 BS.cancelScheduling(VL); 1349 newTreeEntry(VL, false); 1350 return; 1351 } 1352 } 1353 1354 newTreeEntry(VL, true); 1355 DEBUG(dbgs() << "SLP: added a vector of GEPs.\n"); 1356 for (unsigned i = 0, e = 2; i < e; ++i) { 1357 ValueList Operands; 1358 // Prepare the operand vector. 1359 for (unsigned j = 0; j < VL.size(); ++j) 1360 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i)); 1361 1362 buildTree_rec(Operands, Depth + 1); 1363 } 1364 return; 1365 } 1366 case Instruction::Store: { 1367 const DataLayout &DL = F->getParent()->getDataLayout(); 1368 // Check if the stores are consecutive or of we need to swizzle them. 1369 for (unsigned i = 0, e = VL.size() - 1; i < e; ++i) 1370 if (!isConsecutiveAccess(VL[i], VL[i + 1], DL, *SE)) { 1371 BS.cancelScheduling(VL); 1372 newTreeEntry(VL, false); 1373 DEBUG(dbgs() << "SLP: Non-consecutive store.\n"); 1374 return; 1375 } 1376 1377 newTreeEntry(VL, true); 1378 DEBUG(dbgs() << "SLP: added a vector of stores.\n"); 1379 1380 ValueList Operands; 1381 for (unsigned j = 0; j < VL.size(); ++j) 1382 Operands.push_back(cast<Instruction>(VL[j])->getOperand(0)); 1383 1384 buildTree_rec(Operands, Depth + 1); 1385 return; 1386 } 1387 case Instruction::Call: { 1388 // Check if the calls are all to the same vectorizable intrinsic. 1389 CallInst *CI = cast<CallInst>(VL[0]); 1390 // Check if this is an Intrinsic call or something that can be 1391 // represented by an intrinsic call 1392 Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI); 1393 if (!isTriviallyVectorizable(ID)) { 1394 BS.cancelScheduling(VL); 1395 newTreeEntry(VL, false); 1396 DEBUG(dbgs() << "SLP: Non-vectorizable call.\n"); 1397 return; 1398 } 1399 Function *Int = CI->getCalledFunction(); 1400 Value *A1I = nullptr; 1401 if (hasVectorInstrinsicScalarOpd(ID, 1)) 1402 A1I = CI->getArgOperand(1); 1403 for (unsigned i = 1, e = VL.size(); i != e; ++i) { 1404 CallInst *CI2 = dyn_cast<CallInst>(VL[i]); 1405 if (!CI2 || CI2->getCalledFunction() != Int || 1406 getIntrinsicIDForCall(CI2, TLI) != ID) { 1407 BS.cancelScheduling(VL); 1408 newTreeEntry(VL, false); 1409 DEBUG(dbgs() << "SLP: mismatched calls:" << *CI << "!=" << *VL[i] 1410 << "\n"); 1411 return; 1412 } 1413 // ctlz,cttz and powi are special intrinsics whose second argument 1414 // should be same in order for them to be vectorized. 1415 if (hasVectorInstrinsicScalarOpd(ID, 1)) { 1416 Value *A1J = CI2->getArgOperand(1); 1417 if (A1I != A1J) { 1418 BS.cancelScheduling(VL); 1419 newTreeEntry(VL, false); 1420 DEBUG(dbgs() << "SLP: mismatched arguments in call:" << *CI 1421 << " argument "<< A1I<<"!=" << A1J 1422 << "\n"); 1423 return; 1424 } 1425 } 1426 } 1427 1428 newTreeEntry(VL, true); 1429 for (unsigned i = 0, e = CI->getNumArgOperands(); i != e; ++i) { 1430 ValueList Operands; 1431 // Prepare the operand vector. 1432 for (unsigned j = 0; j < VL.size(); ++j) { 1433 CallInst *CI2 = dyn_cast<CallInst>(VL[j]); 1434 Operands.push_back(CI2->getArgOperand(i)); 1435 } 1436 buildTree_rec(Operands, Depth + 1); 1437 } 1438 return; 1439 } 1440 case Instruction::ShuffleVector: { 1441 // If this is not an alternate sequence of opcode like add-sub 1442 // then do not vectorize this instruction. 1443 if (!isAltShuffle) { 1444 BS.cancelScheduling(VL); 1445 newTreeEntry(VL, false); 1446 DEBUG(dbgs() << "SLP: ShuffleVector are not vectorized.\n"); 1447 return; 1448 } 1449 newTreeEntry(VL, true); 1450 DEBUG(dbgs() << "SLP: added a ShuffleVector op.\n"); 1451 1452 // Reorder operands if reordering would enable vectorization. 1453 if (isa<BinaryOperator>(VL0)) { 1454 ValueList Left, Right; 1455 reorderAltShuffleOperands(VL, Left, Right); 1456 buildTree_rec(Left, Depth + 1); 1457 buildTree_rec(Right, Depth + 1); 1458 return; 1459 } 1460 1461 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) { 1462 ValueList Operands; 1463 // Prepare the operand vector. 1464 for (unsigned j = 0; j < VL.size(); ++j) 1465 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i)); 1466 1467 buildTree_rec(Operands, Depth + 1); 1468 } 1469 return; 1470 } 1471 default: 1472 BS.cancelScheduling(VL); 1473 newTreeEntry(VL, false); 1474 DEBUG(dbgs() << "SLP: Gathering unknown instruction.\n"); 1475 return; 1476 } 1477 } 1478 1479 int BoUpSLP::getEntryCost(TreeEntry *E) { 1480 ArrayRef<Value*> VL = E->Scalars; 1481 1482 Type *ScalarTy = VL[0]->getType(); 1483 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0])) 1484 ScalarTy = SI->getValueOperand()->getType(); 1485 VectorType *VecTy = VectorType::get(ScalarTy, VL.size()); 1486 1487 // If we have computed a smaller type for the expression, update VecTy so 1488 // that the costs will be accurate. 1489 if (MinBWs.count(VL[0])) 1490 VecTy = VectorType::get(IntegerType::get(F->getContext(), MinBWs[VL[0]]), 1491 VL.size()); 1492 1493 if (E->NeedToGather) { 1494 if (allConstant(VL)) 1495 return 0; 1496 if (isSplat(VL)) { 1497 return TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy, 0); 1498 } 1499 return getGatherCost(E->Scalars); 1500 } 1501 unsigned Opcode = getSameOpcode(VL); 1502 assert(Opcode && getSameType(VL) && getSameBlock(VL) && "Invalid VL"); 1503 Instruction *VL0 = cast<Instruction>(VL[0]); 1504 switch (Opcode) { 1505 case Instruction::PHI: { 1506 return 0; 1507 } 1508 case Instruction::ExtractElement: { 1509 if (CanReuseExtract(VL)) { 1510 int DeadCost = 0; 1511 for (unsigned i = 0, e = VL.size(); i < e; ++i) { 1512 ExtractElementInst *E = cast<ExtractElementInst>(VL[i]); 1513 if (E->hasOneUse()) 1514 // Take credit for instruction that will become dead. 1515 DeadCost += 1516 TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, i); 1517 } 1518 return -DeadCost; 1519 } 1520 return getGatherCost(VecTy); 1521 } 1522 case Instruction::ZExt: 1523 case Instruction::SExt: 1524 case Instruction::FPToUI: 1525 case Instruction::FPToSI: 1526 case Instruction::FPExt: 1527 case Instruction::PtrToInt: 1528 case Instruction::IntToPtr: 1529 case Instruction::SIToFP: 1530 case Instruction::UIToFP: 1531 case Instruction::Trunc: 1532 case Instruction::FPTrunc: 1533 case Instruction::BitCast: { 1534 Type *SrcTy = VL0->getOperand(0)->getType(); 1535 1536 // Calculate the cost of this instruction. 1537 int ScalarCost = VL.size() * TTI->getCastInstrCost(VL0->getOpcode(), 1538 VL0->getType(), SrcTy); 1539 1540 VectorType *SrcVecTy = VectorType::get(SrcTy, VL.size()); 1541 int VecCost = TTI->getCastInstrCost(VL0->getOpcode(), VecTy, SrcVecTy); 1542 return VecCost - ScalarCost; 1543 } 1544 case Instruction::FCmp: 1545 case Instruction::ICmp: 1546 case Instruction::Select: 1547 case Instruction::Add: 1548 case Instruction::FAdd: 1549 case Instruction::Sub: 1550 case Instruction::FSub: 1551 case Instruction::Mul: 1552 case Instruction::FMul: 1553 case Instruction::UDiv: 1554 case Instruction::SDiv: 1555 case Instruction::FDiv: 1556 case Instruction::URem: 1557 case Instruction::SRem: 1558 case Instruction::FRem: 1559 case Instruction::Shl: 1560 case Instruction::LShr: 1561 case Instruction::AShr: 1562 case Instruction::And: 1563 case Instruction::Or: 1564 case Instruction::Xor: { 1565 // Calculate the cost of this instruction. 1566 int ScalarCost = 0; 1567 int VecCost = 0; 1568 if (Opcode == Instruction::FCmp || Opcode == Instruction::ICmp || 1569 Opcode == Instruction::Select) { 1570 VectorType *MaskTy = VectorType::get(Builder.getInt1Ty(), VL.size()); 1571 ScalarCost = VecTy->getNumElements() * 1572 TTI->getCmpSelInstrCost(Opcode, ScalarTy, Builder.getInt1Ty()); 1573 VecCost = TTI->getCmpSelInstrCost(Opcode, VecTy, MaskTy); 1574 } else { 1575 // Certain instructions can be cheaper to vectorize if they have a 1576 // constant second vector operand. 1577 TargetTransformInfo::OperandValueKind Op1VK = 1578 TargetTransformInfo::OK_AnyValue; 1579 TargetTransformInfo::OperandValueKind Op2VK = 1580 TargetTransformInfo::OK_UniformConstantValue; 1581 TargetTransformInfo::OperandValueProperties Op1VP = 1582 TargetTransformInfo::OP_None; 1583 TargetTransformInfo::OperandValueProperties Op2VP = 1584 TargetTransformInfo::OP_None; 1585 1586 // If all operands are exactly the same ConstantInt then set the 1587 // operand kind to OK_UniformConstantValue. 1588 // If instead not all operands are constants, then set the operand kind 1589 // to OK_AnyValue. If all operands are constants but not the same, 1590 // then set the operand kind to OK_NonUniformConstantValue. 1591 ConstantInt *CInt = nullptr; 1592 for (unsigned i = 0; i < VL.size(); ++i) { 1593 const Instruction *I = cast<Instruction>(VL[i]); 1594 if (!isa<ConstantInt>(I->getOperand(1))) { 1595 Op2VK = TargetTransformInfo::OK_AnyValue; 1596 break; 1597 } 1598 if (i == 0) { 1599 CInt = cast<ConstantInt>(I->getOperand(1)); 1600 continue; 1601 } 1602 if (Op2VK == TargetTransformInfo::OK_UniformConstantValue && 1603 CInt != cast<ConstantInt>(I->getOperand(1))) 1604 Op2VK = TargetTransformInfo::OK_NonUniformConstantValue; 1605 } 1606 // FIXME: Currently cost of model modification for division by 1607 // power of 2 is handled only for X86. Add support for other targets. 1608 if (Op2VK == TargetTransformInfo::OK_UniformConstantValue && CInt && 1609 CInt->getValue().isPowerOf2()) 1610 Op2VP = TargetTransformInfo::OP_PowerOf2; 1611 1612 ScalarCost = VecTy->getNumElements() * 1613 TTI->getArithmeticInstrCost(Opcode, ScalarTy, Op1VK, Op2VK, 1614 Op1VP, Op2VP); 1615 VecCost = TTI->getArithmeticInstrCost(Opcode, VecTy, Op1VK, Op2VK, 1616 Op1VP, Op2VP); 1617 } 1618 return VecCost - ScalarCost; 1619 } 1620 case Instruction::GetElementPtr: { 1621 TargetTransformInfo::OperandValueKind Op1VK = 1622 TargetTransformInfo::OK_AnyValue; 1623 TargetTransformInfo::OperandValueKind Op2VK = 1624 TargetTransformInfo::OK_UniformConstantValue; 1625 1626 int ScalarCost = 1627 VecTy->getNumElements() * 1628 TTI->getArithmeticInstrCost(Instruction::Add, ScalarTy, Op1VK, Op2VK); 1629 int VecCost = 1630 TTI->getArithmeticInstrCost(Instruction::Add, VecTy, Op1VK, Op2VK); 1631 1632 return VecCost - ScalarCost; 1633 } 1634 case Instruction::Load: { 1635 // Cost of wide load - cost of scalar loads. 1636 int ScalarLdCost = VecTy->getNumElements() * 1637 TTI->getMemoryOpCost(Instruction::Load, ScalarTy, 1, 0); 1638 int VecLdCost = TTI->getMemoryOpCost(Instruction::Load, VecTy, 1, 0); 1639 return VecLdCost - ScalarLdCost; 1640 } 1641 case Instruction::Store: { 1642 // We know that we can merge the stores. Calculate the cost. 1643 int ScalarStCost = VecTy->getNumElements() * 1644 TTI->getMemoryOpCost(Instruction::Store, ScalarTy, 1, 0); 1645 int VecStCost = TTI->getMemoryOpCost(Instruction::Store, VecTy, 1, 0); 1646 return VecStCost - ScalarStCost; 1647 } 1648 case Instruction::Call: { 1649 CallInst *CI = cast<CallInst>(VL0); 1650 Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI); 1651 1652 // Calculate the cost of the scalar and vector calls. 1653 SmallVector<Type*, 4> ScalarTys, VecTys; 1654 for (unsigned op = 0, opc = CI->getNumArgOperands(); op!= opc; ++op) { 1655 ScalarTys.push_back(CI->getArgOperand(op)->getType()); 1656 VecTys.push_back(VectorType::get(CI->getArgOperand(op)->getType(), 1657 VecTy->getNumElements())); 1658 } 1659 1660 int ScalarCallCost = VecTy->getNumElements() * 1661 TTI->getIntrinsicInstrCost(ID, ScalarTy, ScalarTys); 1662 1663 int VecCallCost = TTI->getIntrinsicInstrCost(ID, VecTy, VecTys); 1664 1665 DEBUG(dbgs() << "SLP: Call cost "<< VecCallCost - ScalarCallCost 1666 << " (" << VecCallCost << "-" << ScalarCallCost << ")" 1667 << " for " << *CI << "\n"); 1668 1669 return VecCallCost - ScalarCallCost; 1670 } 1671 case Instruction::ShuffleVector: { 1672 TargetTransformInfo::OperandValueKind Op1VK = 1673 TargetTransformInfo::OK_AnyValue; 1674 TargetTransformInfo::OperandValueKind Op2VK = 1675 TargetTransformInfo::OK_AnyValue; 1676 int ScalarCost = 0; 1677 int VecCost = 0; 1678 for (unsigned i = 0; i < VL.size(); ++i) { 1679 Instruction *I = cast<Instruction>(VL[i]); 1680 if (!I) 1681 break; 1682 ScalarCost += 1683 TTI->getArithmeticInstrCost(I->getOpcode(), ScalarTy, Op1VK, Op2VK); 1684 } 1685 // VecCost is equal to sum of the cost of creating 2 vectors 1686 // and the cost of creating shuffle. 1687 Instruction *I0 = cast<Instruction>(VL[0]); 1688 VecCost = 1689 TTI->getArithmeticInstrCost(I0->getOpcode(), VecTy, Op1VK, Op2VK); 1690 Instruction *I1 = cast<Instruction>(VL[1]); 1691 VecCost += 1692 TTI->getArithmeticInstrCost(I1->getOpcode(), VecTy, Op1VK, Op2VK); 1693 VecCost += 1694 TTI->getShuffleCost(TargetTransformInfo::SK_Alternate, VecTy, 0); 1695 return VecCost - ScalarCost; 1696 } 1697 default: 1698 llvm_unreachable("Unknown instruction"); 1699 } 1700 } 1701 1702 bool BoUpSLP::isFullyVectorizableTinyTree() { 1703 DEBUG(dbgs() << "SLP: Check whether the tree with height " << 1704 VectorizableTree.size() << " is fully vectorizable .\n"); 1705 1706 // We only handle trees of height 2. 1707 if (VectorizableTree.size() != 2) 1708 return false; 1709 1710 // Handle splat and all-constants stores. 1711 if (!VectorizableTree[0].NeedToGather && 1712 (allConstant(VectorizableTree[1].Scalars) || 1713 isSplat(VectorizableTree[1].Scalars))) 1714 return true; 1715 1716 // Gathering cost would be too much for tiny trees. 1717 if (VectorizableTree[0].NeedToGather || VectorizableTree[1].NeedToGather) 1718 return false; 1719 1720 return true; 1721 } 1722 1723 int BoUpSLP::getSpillCost() { 1724 // Walk from the bottom of the tree to the top, tracking which values are 1725 // live. When we see a call instruction that is not part of our tree, 1726 // query TTI to see if there is a cost to keeping values live over it 1727 // (for example, if spills and fills are required). 1728 unsigned BundleWidth = VectorizableTree.front().Scalars.size(); 1729 int Cost = 0; 1730 1731 SmallPtrSet<Instruction*, 4> LiveValues; 1732 Instruction *PrevInst = nullptr; 1733 1734 for (unsigned N = 0; N < VectorizableTree.size(); ++N) { 1735 Instruction *Inst = dyn_cast<Instruction>(VectorizableTree[N].Scalars[0]); 1736 if (!Inst) 1737 continue; 1738 1739 if (!PrevInst) { 1740 PrevInst = Inst; 1741 continue; 1742 } 1743 1744 // Update LiveValues. 1745 LiveValues.erase(PrevInst); 1746 for (auto &J : PrevInst->operands()) { 1747 if (isa<Instruction>(&*J) && ScalarToTreeEntry.count(&*J)) 1748 LiveValues.insert(cast<Instruction>(&*J)); 1749 } 1750 1751 DEBUG( 1752 dbgs() << "SLP: #LV: " << LiveValues.size(); 1753 for (auto *X : LiveValues) 1754 dbgs() << " " << X->getName(); 1755 dbgs() << ", Looking at "; 1756 Inst->dump(); 1757 ); 1758 1759 // Now find the sequence of instructions between PrevInst and Inst. 1760 BasicBlock::reverse_iterator InstIt(Inst->getIterator()), 1761 PrevInstIt(PrevInst->getIterator()); 1762 --PrevInstIt; 1763 while (InstIt != PrevInstIt) { 1764 if (PrevInstIt == PrevInst->getParent()->rend()) { 1765 PrevInstIt = Inst->getParent()->rbegin(); 1766 continue; 1767 } 1768 1769 if (isa<CallInst>(&*PrevInstIt) && &*PrevInstIt != PrevInst) { 1770 SmallVector<Type*, 4> V; 1771 for (auto *II : LiveValues) 1772 V.push_back(VectorType::get(II->getType(), BundleWidth)); 1773 Cost += TTI->getCostOfKeepingLiveOverCall(V); 1774 } 1775 1776 ++PrevInstIt; 1777 } 1778 1779 PrevInst = Inst; 1780 } 1781 1782 return Cost; 1783 } 1784 1785 int BoUpSLP::getTreeCost() { 1786 int Cost = 0; 1787 DEBUG(dbgs() << "SLP: Calculating cost for tree of size " << 1788 VectorizableTree.size() << ".\n"); 1789 1790 // We only vectorize tiny trees if it is fully vectorizable. 1791 if (VectorizableTree.size() < 3 && !isFullyVectorizableTinyTree()) { 1792 if (VectorizableTree.empty()) { 1793 assert(!ExternalUses.size() && "We should not have any external users"); 1794 } 1795 return INT_MAX; 1796 } 1797 1798 unsigned BundleWidth = VectorizableTree[0].Scalars.size(); 1799 1800 for (TreeEntry &TE : VectorizableTree) { 1801 int C = getEntryCost(&TE); 1802 DEBUG(dbgs() << "SLP: Adding cost " << C << " for bundle that starts with " 1803 << *TE.Scalars[0] << ".\n"); 1804 Cost += C; 1805 } 1806 1807 SmallSet<Value *, 16> ExtractCostCalculated; 1808 int ExtractCost = 0; 1809 for (ExternalUser &EU : ExternalUses) { 1810 // We only add extract cost once for the same scalar. 1811 if (!ExtractCostCalculated.insert(EU.Scalar).second) 1812 continue; 1813 1814 // Uses by ephemeral values are free (because the ephemeral value will be 1815 // removed prior to code generation, and so the extraction will be 1816 // removed as well). 1817 if (EphValues.count(EU.User)) 1818 continue; 1819 1820 // If we plan to rewrite the tree in a smaller type, we will need to sign 1821 // extend the extracted value back to the original type. Here, we account 1822 // for the extract and the added cost of the sign extend if needed. 1823 auto *VecTy = VectorType::get(EU.Scalar->getType(), BundleWidth); 1824 auto *ScalarRoot = VectorizableTree[0].Scalars[0]; 1825 if (MinBWs.count(ScalarRoot)) { 1826 auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot]); 1827 VecTy = VectorType::get(MinTy, BundleWidth); 1828 ExtractCost += 1829 TTI->getCastInstrCost(Instruction::SExt, EU.Scalar->getType(), MinTy); 1830 } 1831 ExtractCost += 1832 TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, EU.Lane); 1833 } 1834 1835 int SpillCost = getSpillCost(); 1836 Cost += SpillCost + ExtractCost; 1837 1838 DEBUG(dbgs() << "SLP: Spill Cost = " << SpillCost << ".\n" 1839 << "SLP: Extract Cost = " << ExtractCost << ".\n" 1840 << "SLP: Total Cost = " << Cost << ".\n"); 1841 return Cost; 1842 } 1843 1844 int BoUpSLP::getGatherCost(Type *Ty) { 1845 int Cost = 0; 1846 for (unsigned i = 0, e = cast<VectorType>(Ty)->getNumElements(); i < e; ++i) 1847 Cost += TTI->getVectorInstrCost(Instruction::InsertElement, Ty, i); 1848 return Cost; 1849 } 1850 1851 int BoUpSLP::getGatherCost(ArrayRef<Value *> VL) { 1852 // Find the type of the operands in VL. 1853 Type *ScalarTy = VL[0]->getType(); 1854 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0])) 1855 ScalarTy = SI->getValueOperand()->getType(); 1856 VectorType *VecTy = VectorType::get(ScalarTy, VL.size()); 1857 // Find the cost of inserting/extracting values from the vector. 1858 return getGatherCost(VecTy); 1859 } 1860 1861 // Reorder commutative operations in alternate shuffle if the resulting vectors 1862 // are consecutive loads. This would allow us to vectorize the tree. 1863 // If we have something like- 1864 // load a[0] - load b[0] 1865 // load b[1] + load a[1] 1866 // load a[2] - load b[2] 1867 // load a[3] + load b[3] 1868 // Reordering the second load b[1] load a[1] would allow us to vectorize this 1869 // code. 1870 void BoUpSLP::reorderAltShuffleOperands(ArrayRef<Value *> VL, 1871 SmallVectorImpl<Value *> &Left, 1872 SmallVectorImpl<Value *> &Right) { 1873 const DataLayout &DL = F->getParent()->getDataLayout(); 1874 1875 // Push left and right operands of binary operation into Left and Right 1876 for (unsigned i = 0, e = VL.size(); i < e; ++i) { 1877 Left.push_back(cast<Instruction>(VL[i])->getOperand(0)); 1878 Right.push_back(cast<Instruction>(VL[i])->getOperand(1)); 1879 } 1880 1881 // Reorder if we have a commutative operation and consecutive access 1882 // are on either side of the alternate instructions. 1883 for (unsigned j = 0; j < VL.size() - 1; ++j) { 1884 if (LoadInst *L = dyn_cast<LoadInst>(Left[j])) { 1885 if (LoadInst *L1 = dyn_cast<LoadInst>(Right[j + 1])) { 1886 Instruction *VL1 = cast<Instruction>(VL[j]); 1887 Instruction *VL2 = cast<Instruction>(VL[j + 1]); 1888 if (VL1->isCommutative() && isConsecutiveAccess(L, L1, DL, *SE)) { 1889 std::swap(Left[j], Right[j]); 1890 continue; 1891 } else if (VL2->isCommutative() && isConsecutiveAccess(L, L1, DL, *SE)) { 1892 std::swap(Left[j + 1], Right[j + 1]); 1893 continue; 1894 } 1895 // else unchanged 1896 } 1897 } 1898 if (LoadInst *L = dyn_cast<LoadInst>(Right[j])) { 1899 if (LoadInst *L1 = dyn_cast<LoadInst>(Left[j + 1])) { 1900 Instruction *VL1 = cast<Instruction>(VL[j]); 1901 Instruction *VL2 = cast<Instruction>(VL[j + 1]); 1902 if (VL1->isCommutative() && isConsecutiveAccess(L, L1, DL, *SE)) { 1903 std::swap(Left[j], Right[j]); 1904 continue; 1905 } else if (VL2->isCommutative() && isConsecutiveAccess(L, L1, DL, *SE)) { 1906 std::swap(Left[j + 1], Right[j + 1]); 1907 continue; 1908 } 1909 // else unchanged 1910 } 1911 } 1912 } 1913 } 1914 1915 // Return true if I should be commuted before adding it's left and right 1916 // operands to the arrays Left and Right. 1917 // 1918 // The vectorizer is trying to either have all elements one side being 1919 // instruction with the same opcode to enable further vectorization, or having 1920 // a splat to lower the vectorizing cost. 1921 static bool shouldReorderOperands(int i, Instruction &I, 1922 SmallVectorImpl<Value *> &Left, 1923 SmallVectorImpl<Value *> &Right, 1924 bool AllSameOpcodeLeft, 1925 bool AllSameOpcodeRight, bool SplatLeft, 1926 bool SplatRight) { 1927 Value *VLeft = I.getOperand(0); 1928 Value *VRight = I.getOperand(1); 1929 // If we have "SplatRight", try to see if commuting is needed to preserve it. 1930 if (SplatRight) { 1931 if (VRight == Right[i - 1]) 1932 // Preserve SplatRight 1933 return false; 1934 if (VLeft == Right[i - 1]) { 1935 // Commuting would preserve SplatRight, but we don't want to break 1936 // SplatLeft either, i.e. preserve the original order if possible. 1937 // (FIXME: why do we care?) 1938 if (SplatLeft && VLeft == Left[i - 1]) 1939 return false; 1940 return true; 1941 } 1942 } 1943 // Symmetrically handle Right side. 1944 if (SplatLeft) { 1945 if (VLeft == Left[i - 1]) 1946 // Preserve SplatLeft 1947 return false; 1948 if (VRight == Left[i - 1]) 1949 return true; 1950 } 1951 1952 Instruction *ILeft = dyn_cast<Instruction>(VLeft); 1953 Instruction *IRight = dyn_cast<Instruction>(VRight); 1954 1955 // If we have "AllSameOpcodeRight", try to see if the left operands preserves 1956 // it and not the right, in this case we want to commute. 1957 if (AllSameOpcodeRight) { 1958 unsigned RightPrevOpcode = cast<Instruction>(Right[i - 1])->getOpcode(); 1959 if (IRight && RightPrevOpcode == IRight->getOpcode()) 1960 // Do not commute, a match on the right preserves AllSameOpcodeRight 1961 return false; 1962 if (ILeft && RightPrevOpcode == ILeft->getOpcode()) { 1963 // We have a match and may want to commute, but first check if there is 1964 // not also a match on the existing operands on the Left to preserve 1965 // AllSameOpcodeLeft, i.e. preserve the original order if possible. 1966 // (FIXME: why do we care?) 1967 if (AllSameOpcodeLeft && ILeft && 1968 cast<Instruction>(Left[i - 1])->getOpcode() == ILeft->getOpcode()) 1969 return false; 1970 return true; 1971 } 1972 } 1973 // Symmetrically handle Left side. 1974 if (AllSameOpcodeLeft) { 1975 unsigned LeftPrevOpcode = cast<Instruction>(Left[i - 1])->getOpcode(); 1976 if (ILeft && LeftPrevOpcode == ILeft->getOpcode()) 1977 return false; 1978 if (IRight && LeftPrevOpcode == IRight->getOpcode()) 1979 return true; 1980 } 1981 return false; 1982 } 1983 1984 void BoUpSLP::reorderInputsAccordingToOpcode(ArrayRef<Value *> VL, 1985 SmallVectorImpl<Value *> &Left, 1986 SmallVectorImpl<Value *> &Right) { 1987 1988 if (VL.size()) { 1989 // Peel the first iteration out of the loop since there's nothing 1990 // interesting to do anyway and it simplifies the checks in the loop. 1991 auto VLeft = cast<Instruction>(VL[0])->getOperand(0); 1992 auto VRight = cast<Instruction>(VL[0])->getOperand(1); 1993 if (!isa<Instruction>(VRight) && isa<Instruction>(VLeft)) 1994 // Favor having instruction to the right. FIXME: why? 1995 std::swap(VLeft, VRight); 1996 Left.push_back(VLeft); 1997 Right.push_back(VRight); 1998 } 1999 2000 // Keep track if we have instructions with all the same opcode on one side. 2001 bool AllSameOpcodeLeft = isa<Instruction>(Left[0]); 2002 bool AllSameOpcodeRight = isa<Instruction>(Right[0]); 2003 // Keep track if we have one side with all the same value (broadcast). 2004 bool SplatLeft = true; 2005 bool SplatRight = true; 2006 2007 for (unsigned i = 1, e = VL.size(); i != e; ++i) { 2008 Instruction *I = cast<Instruction>(VL[i]); 2009 assert(I->isCommutative() && "Can only process commutative instruction"); 2010 // Commute to favor either a splat or maximizing having the same opcodes on 2011 // one side. 2012 if (shouldReorderOperands(i, *I, Left, Right, AllSameOpcodeLeft, 2013 AllSameOpcodeRight, SplatLeft, SplatRight)) { 2014 Left.push_back(I->getOperand(1)); 2015 Right.push_back(I->getOperand(0)); 2016 } else { 2017 Left.push_back(I->getOperand(0)); 2018 Right.push_back(I->getOperand(1)); 2019 } 2020 // Update Splat* and AllSameOpcode* after the insertion. 2021 SplatRight = SplatRight && (Right[i - 1] == Right[i]); 2022 SplatLeft = SplatLeft && (Left[i - 1] == Left[i]); 2023 AllSameOpcodeLeft = AllSameOpcodeLeft && isa<Instruction>(Left[i]) && 2024 (cast<Instruction>(Left[i - 1])->getOpcode() == 2025 cast<Instruction>(Left[i])->getOpcode()); 2026 AllSameOpcodeRight = AllSameOpcodeRight && isa<Instruction>(Right[i]) && 2027 (cast<Instruction>(Right[i - 1])->getOpcode() == 2028 cast<Instruction>(Right[i])->getOpcode()); 2029 } 2030 2031 // If one operand end up being broadcast, return this operand order. 2032 if (SplatRight || SplatLeft) 2033 return; 2034 2035 const DataLayout &DL = F->getParent()->getDataLayout(); 2036 2037 // Finally check if we can get longer vectorizable chain by reordering 2038 // without breaking the good operand order detected above. 2039 // E.g. If we have something like- 2040 // load a[0] load b[0] 2041 // load b[1] load a[1] 2042 // load a[2] load b[2] 2043 // load a[3] load b[3] 2044 // Reordering the second load b[1] load a[1] would allow us to vectorize 2045 // this code and we still retain AllSameOpcode property. 2046 // FIXME: This load reordering might break AllSameOpcode in some rare cases 2047 // such as- 2048 // add a[0],c[0] load b[0] 2049 // add a[1],c[2] load b[1] 2050 // b[2] load b[2] 2051 // add a[3],c[3] load b[3] 2052 for (unsigned j = 0; j < VL.size() - 1; ++j) { 2053 if (LoadInst *L = dyn_cast<LoadInst>(Left[j])) { 2054 if (LoadInst *L1 = dyn_cast<LoadInst>(Right[j + 1])) { 2055 if (isConsecutiveAccess(L, L1, DL, *SE)) { 2056 std::swap(Left[j + 1], Right[j + 1]); 2057 continue; 2058 } 2059 } 2060 } 2061 if (LoadInst *L = dyn_cast<LoadInst>(Right[j])) { 2062 if (LoadInst *L1 = dyn_cast<LoadInst>(Left[j + 1])) { 2063 if (isConsecutiveAccess(L, L1, DL, *SE)) { 2064 std::swap(Left[j + 1], Right[j + 1]); 2065 continue; 2066 } 2067 } 2068 } 2069 // else unchanged 2070 } 2071 } 2072 2073 void BoUpSLP::setInsertPointAfterBundle(ArrayRef<Value *> VL) { 2074 Instruction *VL0 = cast<Instruction>(VL[0]); 2075 BasicBlock::iterator NextInst(VL0); 2076 ++NextInst; 2077 Builder.SetInsertPoint(VL0->getParent(), NextInst); 2078 Builder.SetCurrentDebugLocation(VL0->getDebugLoc()); 2079 } 2080 2081 Value *BoUpSLP::Gather(ArrayRef<Value *> VL, VectorType *Ty) { 2082 Value *Vec = UndefValue::get(Ty); 2083 // Generate the 'InsertElement' instruction. 2084 for (unsigned i = 0; i < Ty->getNumElements(); ++i) { 2085 Vec = Builder.CreateInsertElement(Vec, VL[i], Builder.getInt32(i)); 2086 if (Instruction *Insrt = dyn_cast<Instruction>(Vec)) { 2087 GatherSeq.insert(Insrt); 2088 CSEBlocks.insert(Insrt->getParent()); 2089 2090 // Add to our 'need-to-extract' list. 2091 if (ScalarToTreeEntry.count(VL[i])) { 2092 int Idx = ScalarToTreeEntry[VL[i]]; 2093 TreeEntry *E = &VectorizableTree[Idx]; 2094 // Find which lane we need to extract. 2095 int FoundLane = -1; 2096 for (unsigned Lane = 0, LE = VL.size(); Lane != LE; ++Lane) { 2097 // Is this the lane of the scalar that we are looking for ? 2098 if (E->Scalars[Lane] == VL[i]) { 2099 FoundLane = Lane; 2100 break; 2101 } 2102 } 2103 assert(FoundLane >= 0 && "Could not find the correct lane"); 2104 ExternalUses.push_back(ExternalUser(VL[i], Insrt, FoundLane)); 2105 } 2106 } 2107 } 2108 2109 return Vec; 2110 } 2111 2112 Value *BoUpSLP::alreadyVectorized(ArrayRef<Value *> VL) const { 2113 SmallDenseMap<Value*, int>::const_iterator Entry 2114 = ScalarToTreeEntry.find(VL[0]); 2115 if (Entry != ScalarToTreeEntry.end()) { 2116 int Idx = Entry->second; 2117 const TreeEntry *En = &VectorizableTree[Idx]; 2118 if (En->isSame(VL) && En->VectorizedValue) 2119 return En->VectorizedValue; 2120 } 2121 return nullptr; 2122 } 2123 2124 Value *BoUpSLP::vectorizeTree(ArrayRef<Value *> VL) { 2125 if (ScalarToTreeEntry.count(VL[0])) { 2126 int Idx = ScalarToTreeEntry[VL[0]]; 2127 TreeEntry *E = &VectorizableTree[Idx]; 2128 if (E->isSame(VL)) 2129 return vectorizeTree(E); 2130 } 2131 2132 Type *ScalarTy = VL[0]->getType(); 2133 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0])) 2134 ScalarTy = SI->getValueOperand()->getType(); 2135 VectorType *VecTy = VectorType::get(ScalarTy, VL.size()); 2136 2137 return Gather(VL, VecTy); 2138 } 2139 2140 Value *BoUpSLP::vectorizeTree(TreeEntry *E) { 2141 IRBuilder<>::InsertPointGuard Guard(Builder); 2142 2143 if (E->VectorizedValue) { 2144 DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n"); 2145 return E->VectorizedValue; 2146 } 2147 2148 Instruction *VL0 = cast<Instruction>(E->Scalars[0]); 2149 Type *ScalarTy = VL0->getType(); 2150 if (StoreInst *SI = dyn_cast<StoreInst>(VL0)) 2151 ScalarTy = SI->getValueOperand()->getType(); 2152 VectorType *VecTy = VectorType::get(ScalarTy, E->Scalars.size()); 2153 2154 if (E->NeedToGather) { 2155 setInsertPointAfterBundle(E->Scalars); 2156 return Gather(E->Scalars, VecTy); 2157 } 2158 2159 const DataLayout &DL = F->getParent()->getDataLayout(); 2160 unsigned Opcode = getSameOpcode(E->Scalars); 2161 2162 switch (Opcode) { 2163 case Instruction::PHI: { 2164 PHINode *PH = dyn_cast<PHINode>(VL0); 2165 Builder.SetInsertPoint(PH->getParent()->getFirstNonPHI()); 2166 Builder.SetCurrentDebugLocation(PH->getDebugLoc()); 2167 PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues()); 2168 E->VectorizedValue = NewPhi; 2169 2170 // PHINodes may have multiple entries from the same block. We want to 2171 // visit every block once. 2172 SmallSet<BasicBlock*, 4> VisitedBBs; 2173 2174 for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) { 2175 ValueList Operands; 2176 BasicBlock *IBB = PH->getIncomingBlock(i); 2177 2178 if (!VisitedBBs.insert(IBB).second) { 2179 NewPhi->addIncoming(NewPhi->getIncomingValueForBlock(IBB), IBB); 2180 continue; 2181 } 2182 2183 // Prepare the operand vector. 2184 for (Value *V : E->Scalars) 2185 Operands.push_back(cast<PHINode>(V)->getIncomingValueForBlock(IBB)); 2186 2187 Builder.SetInsertPoint(IBB->getTerminator()); 2188 Builder.SetCurrentDebugLocation(PH->getDebugLoc()); 2189 Value *Vec = vectorizeTree(Operands); 2190 NewPhi->addIncoming(Vec, IBB); 2191 } 2192 2193 assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() && 2194 "Invalid number of incoming values"); 2195 return NewPhi; 2196 } 2197 2198 case Instruction::ExtractElement: { 2199 if (CanReuseExtract(E->Scalars)) { 2200 Value *V = VL0->getOperand(0); 2201 E->VectorizedValue = V; 2202 return V; 2203 } 2204 return Gather(E->Scalars, VecTy); 2205 } 2206 case Instruction::ZExt: 2207 case Instruction::SExt: 2208 case Instruction::FPToUI: 2209 case Instruction::FPToSI: 2210 case Instruction::FPExt: 2211 case Instruction::PtrToInt: 2212 case Instruction::IntToPtr: 2213 case Instruction::SIToFP: 2214 case Instruction::UIToFP: 2215 case Instruction::Trunc: 2216 case Instruction::FPTrunc: 2217 case Instruction::BitCast: { 2218 ValueList INVL; 2219 for (Value *V : E->Scalars) 2220 INVL.push_back(cast<Instruction>(V)->getOperand(0)); 2221 2222 setInsertPointAfterBundle(E->Scalars); 2223 2224 Value *InVec = vectorizeTree(INVL); 2225 2226 if (Value *V = alreadyVectorized(E->Scalars)) 2227 return V; 2228 2229 CastInst *CI = dyn_cast<CastInst>(VL0); 2230 Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy); 2231 E->VectorizedValue = V; 2232 ++NumVectorInstructions; 2233 return V; 2234 } 2235 case Instruction::FCmp: 2236 case Instruction::ICmp: { 2237 ValueList LHSV, RHSV; 2238 for (Value *V : E->Scalars) { 2239 LHSV.push_back(cast<Instruction>(V)->getOperand(0)); 2240 RHSV.push_back(cast<Instruction>(V)->getOperand(1)); 2241 } 2242 2243 setInsertPointAfterBundle(E->Scalars); 2244 2245 Value *L = vectorizeTree(LHSV); 2246 Value *R = vectorizeTree(RHSV); 2247 2248 if (Value *V = alreadyVectorized(E->Scalars)) 2249 return V; 2250 2251 CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate(); 2252 Value *V; 2253 if (Opcode == Instruction::FCmp) 2254 V = Builder.CreateFCmp(P0, L, R); 2255 else 2256 V = Builder.CreateICmp(P0, L, R); 2257 2258 E->VectorizedValue = V; 2259 ++NumVectorInstructions; 2260 return V; 2261 } 2262 case Instruction::Select: { 2263 ValueList TrueVec, FalseVec, CondVec; 2264 for (Value *V : E->Scalars) { 2265 CondVec.push_back(cast<Instruction>(V)->getOperand(0)); 2266 TrueVec.push_back(cast<Instruction>(V)->getOperand(1)); 2267 FalseVec.push_back(cast<Instruction>(V)->getOperand(2)); 2268 } 2269 2270 setInsertPointAfterBundle(E->Scalars); 2271 2272 Value *Cond = vectorizeTree(CondVec); 2273 Value *True = vectorizeTree(TrueVec); 2274 Value *False = vectorizeTree(FalseVec); 2275 2276 if (Value *V = alreadyVectorized(E->Scalars)) 2277 return V; 2278 2279 Value *V = Builder.CreateSelect(Cond, True, False); 2280 E->VectorizedValue = V; 2281 ++NumVectorInstructions; 2282 return V; 2283 } 2284 case Instruction::Add: 2285 case Instruction::FAdd: 2286 case Instruction::Sub: 2287 case Instruction::FSub: 2288 case Instruction::Mul: 2289 case Instruction::FMul: 2290 case Instruction::UDiv: 2291 case Instruction::SDiv: 2292 case Instruction::FDiv: 2293 case Instruction::URem: 2294 case Instruction::SRem: 2295 case Instruction::FRem: 2296 case Instruction::Shl: 2297 case Instruction::LShr: 2298 case Instruction::AShr: 2299 case Instruction::And: 2300 case Instruction::Or: 2301 case Instruction::Xor: { 2302 ValueList LHSVL, RHSVL; 2303 if (isa<BinaryOperator>(VL0) && VL0->isCommutative()) 2304 reorderInputsAccordingToOpcode(E->Scalars, LHSVL, RHSVL); 2305 else 2306 for (Value *V : E->Scalars) { 2307 LHSVL.push_back(cast<Instruction>(V)->getOperand(0)); 2308 RHSVL.push_back(cast<Instruction>(V)->getOperand(1)); 2309 } 2310 2311 setInsertPointAfterBundle(E->Scalars); 2312 2313 Value *LHS = vectorizeTree(LHSVL); 2314 Value *RHS = vectorizeTree(RHSVL); 2315 2316 if (LHS == RHS && isa<Instruction>(LHS)) { 2317 assert((VL0->getOperand(0) == VL0->getOperand(1)) && "Invalid order"); 2318 } 2319 2320 if (Value *V = alreadyVectorized(E->Scalars)) 2321 return V; 2322 2323 BinaryOperator *BinOp = cast<BinaryOperator>(VL0); 2324 Value *V = Builder.CreateBinOp(BinOp->getOpcode(), LHS, RHS); 2325 E->VectorizedValue = V; 2326 propagateIRFlags(E->VectorizedValue, E->Scalars); 2327 ++NumVectorInstructions; 2328 2329 if (Instruction *I = dyn_cast<Instruction>(V)) 2330 return propagateMetadata(I, E->Scalars); 2331 2332 return V; 2333 } 2334 case Instruction::Load: { 2335 // Loads are inserted at the head of the tree because we don't want to 2336 // sink them all the way down past store instructions. 2337 setInsertPointAfterBundle(E->Scalars); 2338 2339 LoadInst *LI = cast<LoadInst>(VL0); 2340 Type *ScalarLoadTy = LI->getType(); 2341 unsigned AS = LI->getPointerAddressSpace(); 2342 2343 Value *VecPtr = Builder.CreateBitCast(LI->getPointerOperand(), 2344 VecTy->getPointerTo(AS)); 2345 2346 // The pointer operand uses an in-tree scalar so we add the new BitCast to 2347 // ExternalUses list to make sure that an extract will be generated in the 2348 // future. 2349 if (ScalarToTreeEntry.count(LI->getPointerOperand())) 2350 ExternalUses.push_back( 2351 ExternalUser(LI->getPointerOperand(), cast<User>(VecPtr), 0)); 2352 2353 unsigned Alignment = LI->getAlignment(); 2354 LI = Builder.CreateLoad(VecPtr); 2355 if (!Alignment) { 2356 Alignment = DL.getABITypeAlignment(ScalarLoadTy); 2357 } 2358 LI->setAlignment(Alignment); 2359 E->VectorizedValue = LI; 2360 ++NumVectorInstructions; 2361 return propagateMetadata(LI, E->Scalars); 2362 } 2363 case Instruction::Store: { 2364 StoreInst *SI = cast<StoreInst>(VL0); 2365 unsigned Alignment = SI->getAlignment(); 2366 unsigned AS = SI->getPointerAddressSpace(); 2367 2368 ValueList ValueOp; 2369 for (Value *V : E->Scalars) 2370 ValueOp.push_back(cast<StoreInst>(V)->getValueOperand()); 2371 2372 setInsertPointAfterBundle(E->Scalars); 2373 2374 Value *VecValue = vectorizeTree(ValueOp); 2375 Value *VecPtr = Builder.CreateBitCast(SI->getPointerOperand(), 2376 VecTy->getPointerTo(AS)); 2377 StoreInst *S = Builder.CreateStore(VecValue, VecPtr); 2378 2379 // The pointer operand uses an in-tree scalar so we add the new BitCast to 2380 // ExternalUses list to make sure that an extract will be generated in the 2381 // future. 2382 if (ScalarToTreeEntry.count(SI->getPointerOperand())) 2383 ExternalUses.push_back( 2384 ExternalUser(SI->getPointerOperand(), cast<User>(VecPtr), 0)); 2385 2386 if (!Alignment) { 2387 Alignment = DL.getABITypeAlignment(SI->getValueOperand()->getType()); 2388 } 2389 S->setAlignment(Alignment); 2390 E->VectorizedValue = S; 2391 ++NumVectorInstructions; 2392 return propagateMetadata(S, E->Scalars); 2393 } 2394 case Instruction::GetElementPtr: { 2395 setInsertPointAfterBundle(E->Scalars); 2396 2397 ValueList Op0VL; 2398 for (Value *V : E->Scalars) 2399 Op0VL.push_back(cast<GetElementPtrInst>(V)->getOperand(0)); 2400 2401 Value *Op0 = vectorizeTree(Op0VL); 2402 2403 std::vector<Value *> OpVecs; 2404 for (int j = 1, e = cast<GetElementPtrInst>(VL0)->getNumOperands(); j < e; 2405 ++j) { 2406 ValueList OpVL; 2407 for (Value *V : E->Scalars) 2408 OpVL.push_back(cast<GetElementPtrInst>(V)->getOperand(j)); 2409 2410 Value *OpVec = vectorizeTree(OpVL); 2411 OpVecs.push_back(OpVec); 2412 } 2413 2414 Value *V = Builder.CreateGEP( 2415 cast<GetElementPtrInst>(VL0)->getSourceElementType(), Op0, OpVecs); 2416 E->VectorizedValue = V; 2417 ++NumVectorInstructions; 2418 2419 if (Instruction *I = dyn_cast<Instruction>(V)) 2420 return propagateMetadata(I, E->Scalars); 2421 2422 return V; 2423 } 2424 case Instruction::Call: { 2425 CallInst *CI = cast<CallInst>(VL0); 2426 setInsertPointAfterBundle(E->Scalars); 2427 Function *FI; 2428 Intrinsic::ID IID = Intrinsic::not_intrinsic; 2429 Value *ScalarArg = nullptr; 2430 if (CI && (FI = CI->getCalledFunction())) { 2431 IID = FI->getIntrinsicID(); 2432 } 2433 std::vector<Value *> OpVecs; 2434 for (int j = 0, e = CI->getNumArgOperands(); j < e; ++j) { 2435 ValueList OpVL; 2436 // ctlz,cttz and powi are special intrinsics whose second argument is 2437 // a scalar. This argument should not be vectorized. 2438 if (hasVectorInstrinsicScalarOpd(IID, 1) && j == 1) { 2439 CallInst *CEI = cast<CallInst>(E->Scalars[0]); 2440 ScalarArg = CEI->getArgOperand(j); 2441 OpVecs.push_back(CEI->getArgOperand(j)); 2442 continue; 2443 } 2444 for (Value *V : E->Scalars) { 2445 CallInst *CEI = cast<CallInst>(V); 2446 OpVL.push_back(CEI->getArgOperand(j)); 2447 } 2448 2449 Value *OpVec = vectorizeTree(OpVL); 2450 DEBUG(dbgs() << "SLP: OpVec[" << j << "]: " << *OpVec << "\n"); 2451 OpVecs.push_back(OpVec); 2452 } 2453 2454 Module *M = F->getParent(); 2455 Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI); 2456 Type *Tys[] = { VectorType::get(CI->getType(), E->Scalars.size()) }; 2457 Function *CF = Intrinsic::getDeclaration(M, ID, Tys); 2458 Value *V = Builder.CreateCall(CF, OpVecs); 2459 2460 // The scalar argument uses an in-tree scalar so we add the new vectorized 2461 // call to ExternalUses list to make sure that an extract will be 2462 // generated in the future. 2463 if (ScalarArg && ScalarToTreeEntry.count(ScalarArg)) 2464 ExternalUses.push_back(ExternalUser(ScalarArg, cast<User>(V), 0)); 2465 2466 E->VectorizedValue = V; 2467 ++NumVectorInstructions; 2468 return V; 2469 } 2470 case Instruction::ShuffleVector: { 2471 ValueList LHSVL, RHSVL; 2472 assert(isa<BinaryOperator>(VL0) && "Invalid Shuffle Vector Operand"); 2473 reorderAltShuffleOperands(E->Scalars, LHSVL, RHSVL); 2474 setInsertPointAfterBundle(E->Scalars); 2475 2476 Value *LHS = vectorizeTree(LHSVL); 2477 Value *RHS = vectorizeTree(RHSVL); 2478 2479 if (Value *V = alreadyVectorized(E->Scalars)) 2480 return V; 2481 2482 // Create a vector of LHS op1 RHS 2483 BinaryOperator *BinOp0 = cast<BinaryOperator>(VL0); 2484 Value *V0 = Builder.CreateBinOp(BinOp0->getOpcode(), LHS, RHS); 2485 2486 // Create a vector of LHS op2 RHS 2487 Instruction *VL1 = cast<Instruction>(E->Scalars[1]); 2488 BinaryOperator *BinOp1 = cast<BinaryOperator>(VL1); 2489 Value *V1 = Builder.CreateBinOp(BinOp1->getOpcode(), LHS, RHS); 2490 2491 // Create shuffle to take alternate operations from the vector. 2492 // Also, gather up odd and even scalar ops to propagate IR flags to 2493 // each vector operation. 2494 ValueList OddScalars, EvenScalars; 2495 unsigned e = E->Scalars.size(); 2496 SmallVector<Constant *, 8> Mask(e); 2497 for (unsigned i = 0; i < e; ++i) { 2498 if (i & 1) { 2499 Mask[i] = Builder.getInt32(e + i); 2500 OddScalars.push_back(E->Scalars[i]); 2501 } else { 2502 Mask[i] = Builder.getInt32(i); 2503 EvenScalars.push_back(E->Scalars[i]); 2504 } 2505 } 2506 2507 Value *ShuffleMask = ConstantVector::get(Mask); 2508 propagateIRFlags(V0, EvenScalars); 2509 propagateIRFlags(V1, OddScalars); 2510 2511 Value *V = Builder.CreateShuffleVector(V0, V1, ShuffleMask); 2512 E->VectorizedValue = V; 2513 ++NumVectorInstructions; 2514 if (Instruction *I = dyn_cast<Instruction>(V)) 2515 return propagateMetadata(I, E->Scalars); 2516 2517 return V; 2518 } 2519 default: 2520 llvm_unreachable("unknown inst"); 2521 } 2522 return nullptr; 2523 } 2524 2525 Value *BoUpSLP::vectorizeTree() { 2526 2527 // All blocks must be scheduled before any instructions are inserted. 2528 for (auto &BSIter : BlocksSchedules) { 2529 scheduleBlock(BSIter.second.get()); 2530 } 2531 2532 Builder.SetInsertPoint(&F->getEntryBlock().front()); 2533 auto *VectorRoot = vectorizeTree(&VectorizableTree[0]); 2534 2535 // If the vectorized tree can be rewritten in a smaller type, we truncate the 2536 // vectorized root. InstCombine will then rewrite the entire expression. We 2537 // sign extend the extracted values below. 2538 auto *ScalarRoot = VectorizableTree[0].Scalars[0]; 2539 if (MinBWs.count(ScalarRoot)) { 2540 if (auto *I = dyn_cast<Instruction>(VectorRoot)) 2541 Builder.SetInsertPoint(&*++BasicBlock::iterator(I)); 2542 auto BundleWidth = VectorizableTree[0].Scalars.size(); 2543 auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot]); 2544 auto *VecTy = VectorType::get(MinTy, BundleWidth); 2545 auto *Trunc = Builder.CreateTrunc(VectorRoot, VecTy); 2546 VectorizableTree[0].VectorizedValue = Trunc; 2547 } 2548 2549 DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size() << " values .\n"); 2550 2551 // Extract all of the elements with the external uses. 2552 for (UserList::iterator it = ExternalUses.begin(), e = ExternalUses.end(); 2553 it != e; ++it) { 2554 Value *Scalar = it->Scalar; 2555 llvm::User *User = it->User; 2556 2557 // Skip users that we already RAUW. This happens when one instruction 2558 // has multiple uses of the same value. 2559 if (std::find(Scalar->user_begin(), Scalar->user_end(), User) == 2560 Scalar->user_end()) 2561 continue; 2562 assert(ScalarToTreeEntry.count(Scalar) && "Invalid scalar"); 2563 2564 int Idx = ScalarToTreeEntry[Scalar]; 2565 TreeEntry *E = &VectorizableTree[Idx]; 2566 assert(!E->NeedToGather && "Extracting from a gather list"); 2567 2568 Value *Vec = E->VectorizedValue; 2569 assert(Vec && "Can't find vectorizable value"); 2570 2571 Value *Lane = Builder.getInt32(it->Lane); 2572 // Generate extracts for out-of-tree users. 2573 // Find the insertion point for the extractelement lane. 2574 if (isa<Instruction>(Vec)){ 2575 if (PHINode *PH = dyn_cast<PHINode>(User)) { 2576 for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) { 2577 if (PH->getIncomingValue(i) == Scalar) { 2578 Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator()); 2579 Value *Ex = Builder.CreateExtractElement(Vec, Lane); 2580 if (MinBWs.count(ScalarRoot)) 2581 Ex = Builder.CreateSExt(Ex, Scalar->getType()); 2582 CSEBlocks.insert(PH->getIncomingBlock(i)); 2583 PH->setOperand(i, Ex); 2584 } 2585 } 2586 } else { 2587 Builder.SetInsertPoint(cast<Instruction>(User)); 2588 Value *Ex = Builder.CreateExtractElement(Vec, Lane); 2589 if (MinBWs.count(ScalarRoot)) 2590 Ex = Builder.CreateSExt(Ex, Scalar->getType()); 2591 CSEBlocks.insert(cast<Instruction>(User)->getParent()); 2592 User->replaceUsesOfWith(Scalar, Ex); 2593 } 2594 } else { 2595 Builder.SetInsertPoint(&F->getEntryBlock().front()); 2596 Value *Ex = Builder.CreateExtractElement(Vec, Lane); 2597 if (MinBWs.count(ScalarRoot)) 2598 Ex = Builder.CreateSExt(Ex, Scalar->getType()); 2599 CSEBlocks.insert(&F->getEntryBlock()); 2600 User->replaceUsesOfWith(Scalar, Ex); 2601 } 2602 2603 DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n"); 2604 } 2605 2606 // For each vectorized value: 2607 for (int EIdx = 0, EE = VectorizableTree.size(); EIdx < EE; ++EIdx) { 2608 TreeEntry *Entry = &VectorizableTree[EIdx]; 2609 2610 // For each lane: 2611 for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) { 2612 Value *Scalar = Entry->Scalars[Lane]; 2613 // No need to handle users of gathered values. 2614 if (Entry->NeedToGather) 2615 continue; 2616 2617 assert(Entry->VectorizedValue && "Can't find vectorizable value"); 2618 2619 Type *Ty = Scalar->getType(); 2620 if (!Ty->isVoidTy()) { 2621 #ifndef NDEBUG 2622 for (User *U : Scalar->users()) { 2623 DEBUG(dbgs() << "SLP: \tvalidating user:" << *U << ".\n"); 2624 2625 assert((ScalarToTreeEntry.count(U) || 2626 // It is legal to replace users in the ignorelist by undef. 2627 (std::find(UserIgnoreList.begin(), UserIgnoreList.end(), U) != 2628 UserIgnoreList.end())) && 2629 "Replacing out-of-tree value with undef"); 2630 } 2631 #endif 2632 Value *Undef = UndefValue::get(Ty); 2633 Scalar->replaceAllUsesWith(Undef); 2634 } 2635 DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n"); 2636 eraseInstruction(cast<Instruction>(Scalar)); 2637 } 2638 } 2639 2640 Builder.ClearInsertionPoint(); 2641 2642 return VectorizableTree[0].VectorizedValue; 2643 } 2644 2645 void BoUpSLP::optimizeGatherSequence() { 2646 DEBUG(dbgs() << "SLP: Optimizing " << GatherSeq.size() 2647 << " gather sequences instructions.\n"); 2648 // LICM InsertElementInst sequences. 2649 for (SetVector<Instruction *>::iterator it = GatherSeq.begin(), 2650 e = GatherSeq.end(); it != e; ++it) { 2651 InsertElementInst *Insert = dyn_cast<InsertElementInst>(*it); 2652 2653 if (!Insert) 2654 continue; 2655 2656 // Check if this block is inside a loop. 2657 Loop *L = LI->getLoopFor(Insert->getParent()); 2658 if (!L) 2659 continue; 2660 2661 // Check if it has a preheader. 2662 BasicBlock *PreHeader = L->getLoopPreheader(); 2663 if (!PreHeader) 2664 continue; 2665 2666 // If the vector or the element that we insert into it are 2667 // instructions that are defined in this basic block then we can't 2668 // hoist this instruction. 2669 Instruction *CurrVec = dyn_cast<Instruction>(Insert->getOperand(0)); 2670 Instruction *NewElem = dyn_cast<Instruction>(Insert->getOperand(1)); 2671 if (CurrVec && L->contains(CurrVec)) 2672 continue; 2673 if (NewElem && L->contains(NewElem)) 2674 continue; 2675 2676 // We can hoist this instruction. Move it to the pre-header. 2677 Insert->moveBefore(PreHeader->getTerminator()); 2678 } 2679 2680 // Make a list of all reachable blocks in our CSE queue. 2681 SmallVector<const DomTreeNode *, 8> CSEWorkList; 2682 CSEWorkList.reserve(CSEBlocks.size()); 2683 for (BasicBlock *BB : CSEBlocks) 2684 if (DomTreeNode *N = DT->getNode(BB)) { 2685 assert(DT->isReachableFromEntry(N)); 2686 CSEWorkList.push_back(N); 2687 } 2688 2689 // Sort blocks by domination. This ensures we visit a block after all blocks 2690 // dominating it are visited. 2691 std::stable_sort(CSEWorkList.begin(), CSEWorkList.end(), 2692 [this](const DomTreeNode *A, const DomTreeNode *B) { 2693 return DT->properlyDominates(A, B); 2694 }); 2695 2696 // Perform O(N^2) search over the gather sequences and merge identical 2697 // instructions. TODO: We can further optimize this scan if we split the 2698 // instructions into different buckets based on the insert lane. 2699 SmallVector<Instruction *, 16> Visited; 2700 for (auto I = CSEWorkList.begin(), E = CSEWorkList.end(); I != E; ++I) { 2701 assert((I == CSEWorkList.begin() || !DT->dominates(*I, *std::prev(I))) && 2702 "Worklist not sorted properly!"); 2703 BasicBlock *BB = (*I)->getBlock(); 2704 // For all instructions in blocks containing gather sequences: 2705 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e;) { 2706 Instruction *In = &*it++; 2707 if (!isa<InsertElementInst>(In) && !isa<ExtractElementInst>(In)) 2708 continue; 2709 2710 // Check if we can replace this instruction with any of the 2711 // visited instructions. 2712 for (SmallVectorImpl<Instruction *>::iterator v = Visited.begin(), 2713 ve = Visited.end(); 2714 v != ve; ++v) { 2715 if (In->isIdenticalTo(*v) && 2716 DT->dominates((*v)->getParent(), In->getParent())) { 2717 In->replaceAllUsesWith(*v); 2718 eraseInstruction(In); 2719 In = nullptr; 2720 break; 2721 } 2722 } 2723 if (In) { 2724 assert(std::find(Visited.begin(), Visited.end(), In) == Visited.end()); 2725 Visited.push_back(In); 2726 } 2727 } 2728 } 2729 CSEBlocks.clear(); 2730 GatherSeq.clear(); 2731 } 2732 2733 // Groups the instructions to a bundle (which is then a single scheduling entity) 2734 // and schedules instructions until the bundle gets ready. 2735 bool BoUpSLP::BlockScheduling::tryScheduleBundle(ArrayRef<Value *> VL, 2736 BoUpSLP *SLP) { 2737 if (isa<PHINode>(VL[0])) 2738 return true; 2739 2740 // Initialize the instruction bundle. 2741 Instruction *OldScheduleEnd = ScheduleEnd; 2742 ScheduleData *PrevInBundle = nullptr; 2743 ScheduleData *Bundle = nullptr; 2744 bool ReSchedule = false; 2745 DEBUG(dbgs() << "SLP: bundle: " << *VL[0] << "\n"); 2746 2747 // Make sure that the scheduling region contains all 2748 // instructions of the bundle. 2749 for (Value *V : VL) { 2750 if (!extendSchedulingRegion(V)) 2751 return false; 2752 } 2753 2754 for (Value *V : VL) { 2755 ScheduleData *BundleMember = getScheduleData(V); 2756 assert(BundleMember && 2757 "no ScheduleData for bundle member (maybe not in same basic block)"); 2758 if (BundleMember->IsScheduled) { 2759 // A bundle member was scheduled as single instruction before and now 2760 // needs to be scheduled as part of the bundle. We just get rid of the 2761 // existing schedule. 2762 DEBUG(dbgs() << "SLP: reset schedule because " << *BundleMember 2763 << " was already scheduled\n"); 2764 ReSchedule = true; 2765 } 2766 assert(BundleMember->isSchedulingEntity() && 2767 "bundle member already part of other bundle"); 2768 if (PrevInBundle) { 2769 PrevInBundle->NextInBundle = BundleMember; 2770 } else { 2771 Bundle = BundleMember; 2772 } 2773 BundleMember->UnscheduledDepsInBundle = 0; 2774 Bundle->UnscheduledDepsInBundle += BundleMember->UnscheduledDeps; 2775 2776 // Group the instructions to a bundle. 2777 BundleMember->FirstInBundle = Bundle; 2778 PrevInBundle = BundleMember; 2779 } 2780 if (ScheduleEnd != OldScheduleEnd) { 2781 // The scheduling region got new instructions at the lower end (or it is a 2782 // new region for the first bundle). This makes it necessary to 2783 // recalculate all dependencies. 2784 // It is seldom that this needs to be done a second time after adding the 2785 // initial bundle to the region. 2786 for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) { 2787 ScheduleData *SD = getScheduleData(I); 2788 SD->clearDependencies(); 2789 } 2790 ReSchedule = true; 2791 } 2792 if (ReSchedule) { 2793 resetSchedule(); 2794 initialFillReadyList(ReadyInsts); 2795 } 2796 2797 DEBUG(dbgs() << "SLP: try schedule bundle " << *Bundle << " in block " 2798 << BB->getName() << "\n"); 2799 2800 calculateDependencies(Bundle, true, SLP); 2801 2802 // Now try to schedule the new bundle. As soon as the bundle is "ready" it 2803 // means that there are no cyclic dependencies and we can schedule it. 2804 // Note that's important that we don't "schedule" the bundle yet (see 2805 // cancelScheduling). 2806 while (!Bundle->isReady() && !ReadyInsts.empty()) { 2807 2808 ScheduleData *pickedSD = ReadyInsts.back(); 2809 ReadyInsts.pop_back(); 2810 2811 if (pickedSD->isSchedulingEntity() && pickedSD->isReady()) { 2812 schedule(pickedSD, ReadyInsts); 2813 } 2814 } 2815 if (!Bundle->isReady()) { 2816 cancelScheduling(VL); 2817 return false; 2818 } 2819 return true; 2820 } 2821 2822 void BoUpSLP::BlockScheduling::cancelScheduling(ArrayRef<Value *> VL) { 2823 if (isa<PHINode>(VL[0])) 2824 return; 2825 2826 ScheduleData *Bundle = getScheduleData(VL[0]); 2827 DEBUG(dbgs() << "SLP: cancel scheduling of " << *Bundle << "\n"); 2828 assert(!Bundle->IsScheduled && 2829 "Can't cancel bundle which is already scheduled"); 2830 assert(Bundle->isSchedulingEntity() && Bundle->isPartOfBundle() && 2831 "tried to unbundle something which is not a bundle"); 2832 2833 // Un-bundle: make single instructions out of the bundle. 2834 ScheduleData *BundleMember = Bundle; 2835 while (BundleMember) { 2836 assert(BundleMember->FirstInBundle == Bundle && "corrupt bundle links"); 2837 BundleMember->FirstInBundle = BundleMember; 2838 ScheduleData *Next = BundleMember->NextInBundle; 2839 BundleMember->NextInBundle = nullptr; 2840 BundleMember->UnscheduledDepsInBundle = BundleMember->UnscheduledDeps; 2841 if (BundleMember->UnscheduledDepsInBundle == 0) { 2842 ReadyInsts.insert(BundleMember); 2843 } 2844 BundleMember = Next; 2845 } 2846 } 2847 2848 bool BoUpSLP::BlockScheduling::extendSchedulingRegion(Value *V) { 2849 if (getScheduleData(V)) 2850 return true; 2851 Instruction *I = dyn_cast<Instruction>(V); 2852 assert(I && "bundle member must be an instruction"); 2853 assert(!isa<PHINode>(I) && "phi nodes don't need to be scheduled"); 2854 if (!ScheduleStart) { 2855 // It's the first instruction in the new region. 2856 initScheduleData(I, I->getNextNode(), nullptr, nullptr); 2857 ScheduleStart = I; 2858 ScheduleEnd = I->getNextNode(); 2859 assert(ScheduleEnd && "tried to vectorize a TerminatorInst?"); 2860 DEBUG(dbgs() << "SLP: initialize schedule region to " << *I << "\n"); 2861 return true; 2862 } 2863 // Search up and down at the same time, because we don't know if the new 2864 // instruction is above or below the existing scheduling region. 2865 BasicBlock::reverse_iterator UpIter(ScheduleStart->getIterator()); 2866 BasicBlock::reverse_iterator UpperEnd = BB->rend(); 2867 BasicBlock::iterator DownIter(ScheduleEnd); 2868 BasicBlock::iterator LowerEnd = BB->end(); 2869 for (;;) { 2870 if (++ScheduleRegionSize > ScheduleRegionSizeLimit) { 2871 DEBUG(dbgs() << "SLP: exceeded schedule region size limit\n"); 2872 return false; 2873 } 2874 2875 if (UpIter != UpperEnd) { 2876 if (&*UpIter == I) { 2877 initScheduleData(I, ScheduleStart, nullptr, FirstLoadStoreInRegion); 2878 ScheduleStart = I; 2879 DEBUG(dbgs() << "SLP: extend schedule region start to " << *I << "\n"); 2880 return true; 2881 } 2882 UpIter++; 2883 } 2884 if (DownIter != LowerEnd) { 2885 if (&*DownIter == I) { 2886 initScheduleData(ScheduleEnd, I->getNextNode(), LastLoadStoreInRegion, 2887 nullptr); 2888 ScheduleEnd = I->getNextNode(); 2889 assert(ScheduleEnd && "tried to vectorize a TerminatorInst?"); 2890 DEBUG(dbgs() << "SLP: extend schedule region end to " << *I << "\n"); 2891 return true; 2892 } 2893 DownIter++; 2894 } 2895 assert((UpIter != UpperEnd || DownIter != LowerEnd) && 2896 "instruction not found in block"); 2897 } 2898 return true; 2899 } 2900 2901 void BoUpSLP::BlockScheduling::initScheduleData(Instruction *FromI, 2902 Instruction *ToI, 2903 ScheduleData *PrevLoadStore, 2904 ScheduleData *NextLoadStore) { 2905 ScheduleData *CurrentLoadStore = PrevLoadStore; 2906 for (Instruction *I = FromI; I != ToI; I = I->getNextNode()) { 2907 ScheduleData *SD = ScheduleDataMap[I]; 2908 if (!SD) { 2909 // Allocate a new ScheduleData for the instruction. 2910 if (ChunkPos >= ChunkSize) { 2911 ScheduleDataChunks.push_back( 2912 llvm::make_unique<ScheduleData[]>(ChunkSize)); 2913 ChunkPos = 0; 2914 } 2915 SD = &(ScheduleDataChunks.back()[ChunkPos++]); 2916 ScheduleDataMap[I] = SD; 2917 SD->Inst = I; 2918 } 2919 assert(!isInSchedulingRegion(SD) && 2920 "new ScheduleData already in scheduling region"); 2921 SD->init(SchedulingRegionID); 2922 2923 if (I->mayReadOrWriteMemory()) { 2924 // Update the linked list of memory accessing instructions. 2925 if (CurrentLoadStore) { 2926 CurrentLoadStore->NextLoadStore = SD; 2927 } else { 2928 FirstLoadStoreInRegion = SD; 2929 } 2930 CurrentLoadStore = SD; 2931 } 2932 } 2933 if (NextLoadStore) { 2934 if (CurrentLoadStore) 2935 CurrentLoadStore->NextLoadStore = NextLoadStore; 2936 } else { 2937 LastLoadStoreInRegion = CurrentLoadStore; 2938 } 2939 } 2940 2941 void BoUpSLP::BlockScheduling::calculateDependencies(ScheduleData *SD, 2942 bool InsertInReadyList, 2943 BoUpSLP *SLP) { 2944 assert(SD->isSchedulingEntity()); 2945 2946 SmallVector<ScheduleData *, 10> WorkList; 2947 WorkList.push_back(SD); 2948 2949 while (!WorkList.empty()) { 2950 ScheduleData *SD = WorkList.back(); 2951 WorkList.pop_back(); 2952 2953 ScheduleData *BundleMember = SD; 2954 while (BundleMember) { 2955 assert(isInSchedulingRegion(BundleMember)); 2956 if (!BundleMember->hasValidDependencies()) { 2957 2958 DEBUG(dbgs() << "SLP: update deps of " << *BundleMember << "\n"); 2959 BundleMember->Dependencies = 0; 2960 BundleMember->resetUnscheduledDeps(); 2961 2962 // Handle def-use chain dependencies. 2963 for (User *U : BundleMember->Inst->users()) { 2964 if (isa<Instruction>(U)) { 2965 ScheduleData *UseSD = getScheduleData(U); 2966 if (UseSD && isInSchedulingRegion(UseSD->FirstInBundle)) { 2967 BundleMember->Dependencies++; 2968 ScheduleData *DestBundle = UseSD->FirstInBundle; 2969 if (!DestBundle->IsScheduled) { 2970 BundleMember->incrementUnscheduledDeps(1); 2971 } 2972 if (!DestBundle->hasValidDependencies()) { 2973 WorkList.push_back(DestBundle); 2974 } 2975 } 2976 } else { 2977 // I'm not sure if this can ever happen. But we need to be safe. 2978 // This lets the instruction/bundle never be scheduled and 2979 // eventually disable vectorization. 2980 BundleMember->Dependencies++; 2981 BundleMember->incrementUnscheduledDeps(1); 2982 } 2983 } 2984 2985 // Handle the memory dependencies. 2986 ScheduleData *DepDest = BundleMember->NextLoadStore; 2987 if (DepDest) { 2988 Instruction *SrcInst = BundleMember->Inst; 2989 MemoryLocation SrcLoc = getLocation(SrcInst, SLP->AA); 2990 bool SrcMayWrite = BundleMember->Inst->mayWriteToMemory(); 2991 unsigned numAliased = 0; 2992 unsigned DistToSrc = 1; 2993 2994 while (DepDest) { 2995 assert(isInSchedulingRegion(DepDest)); 2996 2997 // We have two limits to reduce the complexity: 2998 // 1) AliasedCheckLimit: It's a small limit to reduce calls to 2999 // SLP->isAliased (which is the expensive part in this loop). 3000 // 2) MaxMemDepDistance: It's for very large blocks and it aborts 3001 // the whole loop (even if the loop is fast, it's quadratic). 3002 // It's important for the loop break condition (see below) to 3003 // check this limit even between two read-only instructions. 3004 if (DistToSrc >= MaxMemDepDistance || 3005 ((SrcMayWrite || DepDest->Inst->mayWriteToMemory()) && 3006 (numAliased >= AliasedCheckLimit || 3007 SLP->isAliased(SrcLoc, SrcInst, DepDest->Inst)))) { 3008 3009 // We increment the counter only if the locations are aliased 3010 // (instead of counting all alias checks). This gives a better 3011 // balance between reduced runtime and accurate dependencies. 3012 numAliased++; 3013 3014 DepDest->MemoryDependencies.push_back(BundleMember); 3015 BundleMember->Dependencies++; 3016 ScheduleData *DestBundle = DepDest->FirstInBundle; 3017 if (!DestBundle->IsScheduled) { 3018 BundleMember->incrementUnscheduledDeps(1); 3019 } 3020 if (!DestBundle->hasValidDependencies()) { 3021 WorkList.push_back(DestBundle); 3022 } 3023 } 3024 DepDest = DepDest->NextLoadStore; 3025 3026 // Example, explaining the loop break condition: Let's assume our 3027 // starting instruction is i0 and MaxMemDepDistance = 3. 3028 // 3029 // +--------v--v--v 3030 // i0,i1,i2,i3,i4,i5,i6,i7,i8 3031 // +--------^--^--^ 3032 // 3033 // MaxMemDepDistance let us stop alias-checking at i3 and we add 3034 // dependencies from i0 to i3,i4,.. (even if they are not aliased). 3035 // Previously we already added dependencies from i3 to i6,i7,i8 3036 // (because of MaxMemDepDistance). As we added a dependency from 3037 // i0 to i3, we have transitive dependencies from i0 to i6,i7,i8 3038 // and we can abort this loop at i6. 3039 if (DistToSrc >= 2 * MaxMemDepDistance) 3040 break; 3041 DistToSrc++; 3042 } 3043 } 3044 } 3045 BundleMember = BundleMember->NextInBundle; 3046 } 3047 if (InsertInReadyList && SD->isReady()) { 3048 ReadyInsts.push_back(SD); 3049 DEBUG(dbgs() << "SLP: gets ready on update: " << *SD->Inst << "\n"); 3050 } 3051 } 3052 } 3053 3054 void BoUpSLP::BlockScheduling::resetSchedule() { 3055 assert(ScheduleStart && 3056 "tried to reset schedule on block which has not been scheduled"); 3057 for (Instruction *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) { 3058 ScheduleData *SD = getScheduleData(I); 3059 assert(isInSchedulingRegion(SD)); 3060 SD->IsScheduled = false; 3061 SD->resetUnscheduledDeps(); 3062 } 3063 ReadyInsts.clear(); 3064 } 3065 3066 void BoUpSLP::scheduleBlock(BlockScheduling *BS) { 3067 3068 if (!BS->ScheduleStart) 3069 return; 3070 3071 DEBUG(dbgs() << "SLP: schedule block " << BS->BB->getName() << "\n"); 3072 3073 BS->resetSchedule(); 3074 3075 // For the real scheduling we use a more sophisticated ready-list: it is 3076 // sorted by the original instruction location. This lets the final schedule 3077 // be as close as possible to the original instruction order. 3078 struct ScheduleDataCompare { 3079 bool operator()(ScheduleData *SD1, ScheduleData *SD2) { 3080 return SD2->SchedulingPriority < SD1->SchedulingPriority; 3081 } 3082 }; 3083 std::set<ScheduleData *, ScheduleDataCompare> ReadyInsts; 3084 3085 // Ensure that all dependency data is updated and fill the ready-list with 3086 // initial instructions. 3087 int Idx = 0; 3088 int NumToSchedule = 0; 3089 for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd; 3090 I = I->getNextNode()) { 3091 ScheduleData *SD = BS->getScheduleData(I); 3092 assert( 3093 SD->isPartOfBundle() == (ScalarToTreeEntry.count(SD->Inst) != 0) && 3094 "scheduler and vectorizer have different opinion on what is a bundle"); 3095 SD->FirstInBundle->SchedulingPriority = Idx++; 3096 if (SD->isSchedulingEntity()) { 3097 BS->calculateDependencies(SD, false, this); 3098 NumToSchedule++; 3099 } 3100 } 3101 BS->initialFillReadyList(ReadyInsts); 3102 3103 Instruction *LastScheduledInst = BS->ScheduleEnd; 3104 3105 // Do the "real" scheduling. 3106 while (!ReadyInsts.empty()) { 3107 ScheduleData *picked = *ReadyInsts.begin(); 3108 ReadyInsts.erase(ReadyInsts.begin()); 3109 3110 // Move the scheduled instruction(s) to their dedicated places, if not 3111 // there yet. 3112 ScheduleData *BundleMember = picked; 3113 while (BundleMember) { 3114 Instruction *pickedInst = BundleMember->Inst; 3115 if (LastScheduledInst->getNextNode() != pickedInst) { 3116 BS->BB->getInstList().remove(pickedInst); 3117 BS->BB->getInstList().insert(LastScheduledInst->getIterator(), 3118 pickedInst); 3119 } 3120 LastScheduledInst = pickedInst; 3121 BundleMember = BundleMember->NextInBundle; 3122 } 3123 3124 BS->schedule(picked, ReadyInsts); 3125 NumToSchedule--; 3126 } 3127 assert(NumToSchedule == 0 && "could not schedule all instructions"); 3128 3129 // Avoid duplicate scheduling of the block. 3130 BS->ScheduleStart = nullptr; 3131 } 3132 3133 unsigned BoUpSLP::getVectorElementSize(Value *V) { 3134 auto &DL = F->getParent()->getDataLayout(); 3135 3136 // If V is a store, just return the width of the stored value without 3137 // traversing the expression tree. This is the common case. 3138 if (auto *Store = dyn_cast<StoreInst>(V)) 3139 return DL.getTypeSizeInBits(Store->getValueOperand()->getType()); 3140 3141 // If V is not a store, we can traverse the expression tree to find loads 3142 // that feed it. The type of the loaded value may indicate a more suitable 3143 // width than V's type. We want to base the vector element size on the width 3144 // of memory operations where possible. 3145 SmallVector<Instruction *, 16> Worklist; 3146 SmallPtrSet<Instruction *, 16> Visited; 3147 if (auto *I = dyn_cast<Instruction>(V)) 3148 Worklist.push_back(I); 3149 3150 // Traverse the expression tree in bottom-up order looking for loads. If we 3151 // encounter an instruciton we don't yet handle, we give up. 3152 auto MaxWidth = 0u; 3153 auto FoundUnknownInst = false; 3154 while (!Worklist.empty() && !FoundUnknownInst) { 3155 auto *I = Worklist.pop_back_val(); 3156 Visited.insert(I); 3157 3158 // We should only be looking at scalar instructions here. If the current 3159 // instruction has a vector type, give up. 3160 auto *Ty = I->getType(); 3161 if (isa<VectorType>(Ty)) 3162 FoundUnknownInst = true; 3163 3164 // If the current instruction is a load, update MaxWidth to reflect the 3165 // width of the loaded value. 3166 else if (isa<LoadInst>(I)) 3167 MaxWidth = std::max<unsigned>(MaxWidth, DL.getTypeSizeInBits(Ty)); 3168 3169 // Otherwise, we need to visit the operands of the instruction. We only 3170 // handle the interesting cases from buildTree here. If an operand is an 3171 // instruction we haven't yet visited, we add it to the worklist. 3172 else if (isa<PHINode>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) || 3173 isa<CmpInst>(I) || isa<SelectInst>(I) || isa<BinaryOperator>(I)) { 3174 for (Use &U : I->operands()) 3175 if (auto *J = dyn_cast<Instruction>(U.get())) 3176 if (!Visited.count(J)) 3177 Worklist.push_back(J); 3178 } 3179 3180 // If we don't yet handle the instruction, give up. 3181 else 3182 FoundUnknownInst = true; 3183 } 3184 3185 // If we didn't encounter a memory access in the expression tree, or if we 3186 // gave up for some reason, just return the width of V. 3187 if (!MaxWidth || FoundUnknownInst) 3188 return DL.getTypeSizeInBits(V->getType()); 3189 3190 // Otherwise, return the maximum width we found. 3191 return MaxWidth; 3192 } 3193 3194 // Determine if a value V in a vectorizable expression Expr can be demoted to a 3195 // smaller type with a truncation. We collect the values that will be demoted 3196 // in ToDemote and additional roots that require investigating in Roots. 3197 static bool collectValuesToDemote(Value *V, SmallPtrSetImpl<Value *> &Expr, 3198 SmallVectorImpl<Value *> &ToDemote, 3199 SmallVectorImpl<Value *> &Roots) { 3200 3201 // We can always demote constants. 3202 if (isa<Constant>(V)) { 3203 ToDemote.push_back(V); 3204 return true; 3205 } 3206 3207 // If the value is not an instruction in the expression with only one use, it 3208 // cannot be demoted. 3209 auto *I = dyn_cast<Instruction>(V); 3210 if (!I || !I->hasOneUse() || !Expr.count(I)) 3211 return false; 3212 3213 switch (I->getOpcode()) { 3214 3215 // We can always demote truncations and extensions. Since truncations can 3216 // seed additional demotion, we save the truncated value. 3217 case Instruction::Trunc: 3218 Roots.push_back(I->getOperand(0)); 3219 case Instruction::ZExt: 3220 case Instruction::SExt: 3221 break; 3222 3223 // We can demote certain binary operations if we can demote both of their 3224 // operands. 3225 case Instruction::Add: 3226 case Instruction::Sub: 3227 case Instruction::Mul: 3228 case Instruction::And: 3229 case Instruction::Or: 3230 case Instruction::Xor: 3231 if (!collectValuesToDemote(I->getOperand(0), Expr, ToDemote, Roots) || 3232 !collectValuesToDemote(I->getOperand(1), Expr, ToDemote, Roots)) 3233 return false; 3234 break; 3235 3236 // We can demote selects if we can demote their true and false values. 3237 case Instruction::Select: { 3238 SelectInst *SI = cast<SelectInst>(I); 3239 if (!collectValuesToDemote(SI->getTrueValue(), Expr, ToDemote, Roots) || 3240 !collectValuesToDemote(SI->getFalseValue(), Expr, ToDemote, Roots)) 3241 return false; 3242 break; 3243 } 3244 3245 // We can demote phis if we can demote all their incoming operands. Note that 3246 // we don't need to worry about cycles since we ensure single use above. 3247 case Instruction::PHI: { 3248 PHINode *PN = cast<PHINode>(I); 3249 for (Value *IncValue : PN->incoming_values()) 3250 if (!collectValuesToDemote(IncValue, Expr, ToDemote, Roots)) 3251 return false; 3252 break; 3253 } 3254 3255 // Otherwise, conservatively give up. 3256 default: 3257 return false; 3258 } 3259 3260 // Record the value that we can demote. 3261 ToDemote.push_back(V); 3262 return true; 3263 } 3264 3265 void BoUpSLP::computeMinimumValueSizes() { 3266 auto &DL = F->getParent()->getDataLayout(); 3267 3268 // If there are no external uses, the expression tree must be rooted by a 3269 // store. We can't demote in-memory values, so there is nothing to do here. 3270 if (ExternalUses.empty()) 3271 return; 3272 3273 // We only attempt to truncate integer expressions. 3274 auto &TreeRoot = VectorizableTree[0].Scalars; 3275 auto *TreeRootIT = dyn_cast<IntegerType>(TreeRoot[0]->getType()); 3276 if (!TreeRootIT) 3277 return; 3278 3279 // If the expression is not rooted by a store, these roots should have 3280 // external uses. We will rely on InstCombine to rewrite the expression in 3281 // the narrower type. However, InstCombine only rewrites single-use values. 3282 // This means that if a tree entry other than a root is used externally, it 3283 // must have multiple uses and InstCombine will not rewrite it. The code 3284 // below ensures that only the roots are used externally. 3285 SmallPtrSet<Value *, 16> Expr(TreeRoot.begin(), TreeRoot.end()); 3286 for (auto &EU : ExternalUses) 3287 if (!Expr.erase(EU.Scalar)) 3288 return; 3289 if (!Expr.empty()) 3290 return; 3291 3292 // Collect the scalar values in one lane of the vectorizable expression. We 3293 // will use this context to determine which values can be demoted. If we see 3294 // a truncation, we mark it as seeding another demotion. 3295 for (auto &Entry : VectorizableTree) 3296 Expr.insert(Entry.Scalars[0]); 3297 3298 // Ensure the root of the vectorizable tree doesn't form a cycle. It must 3299 // have a single external user that is not in the vectorizable tree. 3300 if (!TreeRoot[0]->hasOneUse() || Expr.count(*TreeRoot[0]->user_begin())) 3301 return; 3302 3303 // Conservatively determine if we can actually truncate the root of the 3304 // expression. Collect the values that can be demoted in ToDemote and 3305 // additional roots that require investigating in Roots. 3306 SmallVector<Value *, 32> ToDemote; 3307 SmallVector<Value *, 2> Roots; 3308 if (!collectValuesToDemote(TreeRoot[0], Expr, ToDemote, Roots)) 3309 return; 3310 3311 // The maximum bit width required to represent all the values that can be 3312 // demoted without loss of precision. It would be safe to truncate the root 3313 // of the expression to this width. 3314 auto MaxBitWidth = 8u; 3315 3316 // We first check if all the bits of the root are demanded. If they're not, 3317 // we can truncate the root to this narrower type. 3318 auto Mask = DB->getDemandedBits(cast<Instruction>(TreeRoot[0])); 3319 if (Mask.countLeadingZeros() > 0) 3320 MaxBitWidth = std::max<unsigned>( 3321 Mask.getBitWidth() - Mask.countLeadingZeros(), MaxBitWidth); 3322 3323 // If all the bits of the root are demanded, we can try a little harder to 3324 // compute a narrower type. This can happen, for example, if the roots are 3325 // getelementptr indices. InstCombine promotes these indices to the pointer 3326 // width. Thus, all their bits are technically demanded even though the 3327 // address computation might be vectorized in a smaller type. 3328 // 3329 // We start by looking at each entry that can be demoted. We compute the 3330 // maximum bit width required to store the scalar by using ValueTracking to 3331 // compute the number of high-order bits we can truncate. 3332 else 3333 for (auto *Scalar : ToDemote) { 3334 auto NumSignBits = ComputeNumSignBits(Scalar, DL, 0, AC, 0, DT); 3335 auto NumTypeBits = DL.getTypeSizeInBits(Scalar->getType()); 3336 MaxBitWidth = std::max<unsigned>(NumTypeBits - NumSignBits, MaxBitWidth); 3337 } 3338 3339 // Round MaxBitWidth up to the next power-of-two. 3340 if (!isPowerOf2_64(MaxBitWidth)) 3341 MaxBitWidth = NextPowerOf2(MaxBitWidth); 3342 3343 // If the maximum bit width we compute is less than the with of the roots' 3344 // type, we can proceed with the narrowing. Otherwise, do nothing. 3345 if (MaxBitWidth >= TreeRootIT->getBitWidth()) 3346 return; 3347 3348 // If we can truncate the root, we must collect additional values that might 3349 // be demoted as a result. That is, those seeded by truncations we will 3350 // modify. 3351 while (!Roots.empty()) 3352 collectValuesToDemote(Roots.pop_back_val(), Expr, ToDemote, Roots); 3353 3354 // Finally, map the values we can demote to the maximum bit with we computed. 3355 for (auto *Scalar : ToDemote) 3356 MinBWs[Scalar] = MaxBitWidth; 3357 } 3358 3359 /// The SLPVectorizer Pass. 3360 struct SLPVectorizer : public FunctionPass { 3361 typedef SmallVector<StoreInst *, 8> StoreList; 3362 typedef MapVector<Value *, StoreList> StoreListMap; 3363 typedef SmallVector<WeakVH, 8> WeakVHList; 3364 typedef MapVector<Value *, WeakVHList> WeakVHListMap; 3365 3366 /// Pass identification, replacement for typeid 3367 static char ID; 3368 3369 explicit SLPVectorizer() : FunctionPass(ID) { 3370 initializeSLPVectorizerPass(*PassRegistry::getPassRegistry()); 3371 } 3372 3373 ScalarEvolution *SE; 3374 TargetTransformInfo *TTI; 3375 TargetLibraryInfo *TLI; 3376 AliasAnalysis *AA; 3377 LoopInfo *LI; 3378 DominatorTree *DT; 3379 AssumptionCache *AC; 3380 DemandedBits *DB; 3381 3382 bool runOnFunction(Function &F) override { 3383 if (skipOptnoneFunction(F)) 3384 return false; 3385 3386 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE(); 3387 TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F); 3388 auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>(); 3389 TLI = TLIP ? &TLIP->getTLI() : nullptr; 3390 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults(); 3391 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 3392 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 3393 AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F); 3394 DB = &getAnalysis<DemandedBits>(); 3395 3396 Stores.clear(); 3397 GEPs.clear(); 3398 bool Changed = false; 3399 3400 // If the target claims to have no vector registers don't attempt 3401 // vectorization. 3402 if (!TTI->getNumberOfRegisters(true)) 3403 return false; 3404 3405 // Use the vector register size specified by the target unless overridden 3406 // by a command-line option. 3407 // TODO: It would be better to limit the vectorization factor based on 3408 // data type rather than just register size. For example, x86 AVX has 3409 // 256-bit registers, but it does not support integer operations 3410 // at that width (that requires AVX2). 3411 if (MaxVectorRegSizeOption.getNumOccurrences()) 3412 MaxVecRegSize = MaxVectorRegSizeOption; 3413 else 3414 MaxVecRegSize = TTI->getRegisterBitWidth(true); 3415 3416 // Don't vectorize when the attribute NoImplicitFloat is used. 3417 if (F.hasFnAttribute(Attribute::NoImplicitFloat)) 3418 return false; 3419 3420 DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n"); 3421 3422 // Use the bottom up slp vectorizer to construct chains that start with 3423 // store instructions. 3424 BoUpSLP R(&F, SE, TTI, TLI, AA, LI, DT, AC, DB); 3425 3426 // A general note: the vectorizer must use BoUpSLP::eraseInstruction() to 3427 // delete instructions. 3428 3429 // Scan the blocks in the function in post order. 3430 for (auto BB : post_order(&F.getEntryBlock())) { 3431 collectSeedInstructions(BB); 3432 3433 // Vectorize trees that end at stores. 3434 if (NumStores > 0) { 3435 DEBUG(dbgs() << "SLP: Found " << NumStores << " stores.\n"); 3436 Changed |= vectorizeStoreChains(R); 3437 } 3438 3439 // Vectorize trees that end at reductions. 3440 Changed |= vectorizeChainsInBlock(BB, R); 3441 3442 // Vectorize the index computations of getelementptr instructions. This 3443 // is primarily intended to catch gather-like idioms ending at 3444 // non-consecutive loads. 3445 if (NumGEPs > 0) { 3446 DEBUG(dbgs() << "SLP: Found " << NumGEPs << " GEPs.\n"); 3447 Changed |= vectorizeGEPIndices(BB, R); 3448 } 3449 } 3450 3451 if (Changed) { 3452 R.optimizeGatherSequence(); 3453 DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n"); 3454 DEBUG(verifyFunction(F)); 3455 } 3456 return Changed; 3457 } 3458 3459 void getAnalysisUsage(AnalysisUsage &AU) const override { 3460 FunctionPass::getAnalysisUsage(AU); 3461 AU.addRequired<AssumptionCacheTracker>(); 3462 AU.addRequired<ScalarEvolutionWrapperPass>(); 3463 AU.addRequired<AAResultsWrapperPass>(); 3464 AU.addRequired<TargetTransformInfoWrapperPass>(); 3465 AU.addRequired<LoopInfoWrapperPass>(); 3466 AU.addRequired<DominatorTreeWrapperPass>(); 3467 AU.addRequired<DemandedBits>(); 3468 AU.addPreserved<LoopInfoWrapperPass>(); 3469 AU.addPreserved<DominatorTreeWrapperPass>(); 3470 AU.addPreserved<AAResultsWrapperPass>(); 3471 AU.addPreserved<GlobalsAAWrapperPass>(); 3472 AU.setPreservesCFG(); 3473 } 3474 3475 private: 3476 /// \brief Collect store and getelementptr instructions and organize them 3477 /// according to the underlying object of their pointer operands. We sort the 3478 /// instructions by their underlying objects to reduce the cost of 3479 /// consecutive access queries. 3480 /// 3481 /// TODO: We can further reduce this cost if we flush the chain creation 3482 /// every time we run into a memory barrier. 3483 void collectSeedInstructions(BasicBlock *BB); 3484 3485 /// \brief Try to vectorize a chain that starts at two arithmetic instrs. 3486 bool tryToVectorizePair(Value *A, Value *B, BoUpSLP &R); 3487 3488 /// \brief Try to vectorize a list of operands. 3489 /// \@param BuildVector A list of users to ignore for the purpose of 3490 /// scheduling and that don't need extracting. 3491 /// \returns true if a value was vectorized. 3492 bool tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R, 3493 ArrayRef<Value *> BuildVector = None, 3494 bool allowReorder = false); 3495 3496 /// \brief Try to vectorize a chain that may start at the operands of \V; 3497 bool tryToVectorize(BinaryOperator *V, BoUpSLP &R); 3498 3499 /// \brief Vectorize the store instructions collected in Stores. 3500 bool vectorizeStoreChains(BoUpSLP &R); 3501 3502 /// \brief Vectorize the index computations of the getelementptr instructions 3503 /// collected in GEPs. 3504 bool vectorizeGEPIndices(BasicBlock *BB, BoUpSLP &R); 3505 3506 /// \brief Scan the basic block and look for patterns that are likely to start 3507 /// a vectorization chain. 3508 bool vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R); 3509 3510 bool vectorizeStoreChain(ArrayRef<Value *> Chain, int CostThreshold, 3511 BoUpSLP &R, unsigned VecRegSize); 3512 3513 bool vectorizeStores(ArrayRef<StoreInst *> Stores, int costThreshold, 3514 BoUpSLP &R); 3515 3516 /// The store instructions in a basic block organized by base pointer. 3517 StoreListMap Stores; 3518 3519 /// The getelementptr instructions in a basic block organized by base pointer. 3520 WeakVHListMap GEPs; 3521 3522 /// The number of store instructions in a basic block. 3523 unsigned NumStores; 3524 3525 /// The number of getelementptr instructions in a basic block. 3526 unsigned NumGEPs; 3527 3528 unsigned MaxVecRegSize; // This is set by TTI or overridden by cl::opt. 3529 }; 3530 3531 /// \brief Check that the Values in the slice in VL array are still existent in 3532 /// the WeakVH array. 3533 /// Vectorization of part of the VL array may cause later values in the VL array 3534 /// to become invalid. We track when this has happened in the WeakVH array. 3535 static bool hasValueBeenRAUWed(ArrayRef<Value *> VL, ArrayRef<WeakVH> VH, 3536 unsigned SliceBegin, unsigned SliceSize) { 3537 VL = VL.slice(SliceBegin, SliceSize); 3538 VH = VH.slice(SliceBegin, SliceSize); 3539 return !std::equal(VL.begin(), VL.end(), VH.begin()); 3540 } 3541 3542 bool SLPVectorizer::vectorizeStoreChain(ArrayRef<Value *> Chain, 3543 int CostThreshold, BoUpSLP &R, 3544 unsigned VecRegSize) { 3545 unsigned ChainLen = Chain.size(); 3546 DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << ChainLen 3547 << "\n"); 3548 unsigned Sz = R.getVectorElementSize(Chain[0]); 3549 unsigned VF = VecRegSize / Sz; 3550 3551 if (!isPowerOf2_32(Sz) || VF < 2) 3552 return false; 3553 3554 // Keep track of values that were deleted by vectorizing in the loop below. 3555 SmallVector<WeakVH, 8> TrackValues(Chain.begin(), Chain.end()); 3556 3557 bool Changed = false; 3558 // Look for profitable vectorizable trees at all offsets, starting at zero. 3559 for (unsigned i = 0, e = ChainLen; i < e; ++i) { 3560 if (i + VF > e) 3561 break; 3562 3563 // Check that a previous iteration of this loop did not delete the Value. 3564 if (hasValueBeenRAUWed(Chain, TrackValues, i, VF)) 3565 continue; 3566 3567 DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << i 3568 << "\n"); 3569 ArrayRef<Value *> Operands = Chain.slice(i, VF); 3570 3571 R.buildTree(Operands); 3572 R.computeMinimumValueSizes(); 3573 3574 int Cost = R.getTreeCost(); 3575 3576 DEBUG(dbgs() << "SLP: Found cost=" << Cost << " for VF=" << VF << "\n"); 3577 if (Cost < CostThreshold) { 3578 DEBUG(dbgs() << "SLP: Decided to vectorize cost=" << Cost << "\n"); 3579 R.vectorizeTree(); 3580 3581 // Move to the next bundle. 3582 i += VF - 1; 3583 Changed = true; 3584 } 3585 } 3586 3587 return Changed; 3588 } 3589 3590 bool SLPVectorizer::vectorizeStores(ArrayRef<StoreInst *> Stores, 3591 int costThreshold, BoUpSLP &R) { 3592 SetVector<StoreInst *> Heads, Tails; 3593 SmallDenseMap<StoreInst *, StoreInst *> ConsecutiveChain; 3594 3595 // We may run into multiple chains that merge into a single chain. We mark the 3596 // stores that we vectorized so that we don't visit the same store twice. 3597 BoUpSLP::ValueSet VectorizedStores; 3598 bool Changed = false; 3599 3600 // Do a quadratic search on all of the given stores and find 3601 // all of the pairs of stores that follow each other. 3602 SmallVector<unsigned, 16> IndexQueue; 3603 for (unsigned i = 0, e = Stores.size(); i < e; ++i) { 3604 const DataLayout &DL = Stores[i]->getModule()->getDataLayout(); 3605 IndexQueue.clear(); 3606 // If a store has multiple consecutive store candidates, search Stores 3607 // array according to the sequence: from i+1 to e, then from i-1 to 0. 3608 // This is because usually pairing with immediate succeeding or preceding 3609 // candidate create the best chance to find slp vectorization opportunity. 3610 unsigned j = 0; 3611 for (j = i + 1; j < e; ++j) 3612 IndexQueue.push_back(j); 3613 for (j = i; j > 0; --j) 3614 IndexQueue.push_back(j - 1); 3615 3616 for (auto &k : IndexQueue) { 3617 if (isConsecutiveAccess(Stores[i], Stores[k], DL, *SE)) { 3618 Tails.insert(Stores[k]); 3619 Heads.insert(Stores[i]); 3620 ConsecutiveChain[Stores[i]] = Stores[k]; 3621 break; 3622 } 3623 } 3624 } 3625 3626 // For stores that start but don't end a link in the chain: 3627 for (SetVector<StoreInst *>::iterator it = Heads.begin(), e = Heads.end(); 3628 it != e; ++it) { 3629 if (Tails.count(*it)) 3630 continue; 3631 3632 // We found a store instr that starts a chain. Now follow the chain and try 3633 // to vectorize it. 3634 BoUpSLP::ValueList Operands; 3635 StoreInst *I = *it; 3636 // Collect the chain into a list. 3637 while (Tails.count(I) || Heads.count(I)) { 3638 if (VectorizedStores.count(I)) 3639 break; 3640 Operands.push_back(I); 3641 // Move to the next value in the chain. 3642 I = ConsecutiveChain[I]; 3643 } 3644 3645 // FIXME: Is division-by-2 the correct step? Should we assert that the 3646 // register size is a power-of-2? 3647 for (unsigned Size = MaxVecRegSize; Size >= MinVecRegSize; Size /= 2) { 3648 if (vectorizeStoreChain(Operands, costThreshold, R, Size)) { 3649 // Mark the vectorized stores so that we don't vectorize them again. 3650 VectorizedStores.insert(Operands.begin(), Operands.end()); 3651 Changed = true; 3652 break; 3653 } 3654 } 3655 } 3656 3657 return Changed; 3658 } 3659 3660 void SLPVectorizer::collectSeedInstructions(BasicBlock *BB) { 3661 3662 // Initialize the collections. We will make a single pass over the block. 3663 Stores.clear(); 3664 GEPs.clear(); 3665 NumStores = NumGEPs = 0; 3666 const DataLayout &DL = BB->getModule()->getDataLayout(); 3667 3668 // Visit the store and getelementptr instructions in BB and organize them in 3669 // Stores and GEPs according to the underlying objects of their pointer 3670 // operands. 3671 for (Instruction &I : *BB) { 3672 3673 // Ignore store instructions that are volatile or have a pointer operand 3674 // that doesn't point to a scalar type. 3675 if (auto *SI = dyn_cast<StoreInst>(&I)) { 3676 if (!SI->isSimple()) 3677 continue; 3678 if (!isValidElementType(SI->getValueOperand()->getType())) 3679 continue; 3680 Stores[GetUnderlyingObject(SI->getPointerOperand(), DL)].push_back(SI); 3681 ++NumStores; 3682 } 3683 3684 // Ignore getelementptr instructions that have more than one index, a 3685 // constant index, or a pointer operand that doesn't point to a scalar 3686 // type. 3687 else if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) { 3688 auto Idx = GEP->idx_begin()->get(); 3689 if (GEP->getNumIndices() > 1 || isa<Constant>(Idx)) 3690 continue; 3691 if (!isValidElementType(Idx->getType())) 3692 continue; 3693 GEPs[GetUnderlyingObject(GEP->getPointerOperand(), DL)].push_back(GEP); 3694 ++NumGEPs; 3695 } 3696 } 3697 } 3698 3699 bool SLPVectorizer::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) { 3700 if (!A || !B) 3701 return false; 3702 Value *VL[] = { A, B }; 3703 return tryToVectorizeList(VL, R, None, true); 3704 } 3705 3706 bool SLPVectorizer::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R, 3707 ArrayRef<Value *> BuildVector, 3708 bool allowReorder) { 3709 if (VL.size() < 2) 3710 return false; 3711 3712 DEBUG(dbgs() << "SLP: Vectorizing a list of length = " << VL.size() << ".\n"); 3713 3714 // Check that all of the parts are scalar instructions of the same type. 3715 Instruction *I0 = dyn_cast<Instruction>(VL[0]); 3716 if (!I0) 3717 return false; 3718 3719 unsigned Opcode0 = I0->getOpcode(); 3720 3721 // FIXME: Register size should be a parameter to this function, so we can 3722 // try different vectorization factors. 3723 unsigned Sz = R.getVectorElementSize(I0); 3724 unsigned VF = MinVecRegSize / Sz; 3725 3726 for (Value *V : VL) { 3727 Type *Ty = V->getType(); 3728 if (!isValidElementType(Ty)) 3729 return false; 3730 Instruction *Inst = dyn_cast<Instruction>(V); 3731 if (!Inst || Inst->getOpcode() != Opcode0) 3732 return false; 3733 } 3734 3735 bool Changed = false; 3736 3737 // Keep track of values that were deleted by vectorizing in the loop below. 3738 SmallVector<WeakVH, 8> TrackValues(VL.begin(), VL.end()); 3739 3740 for (unsigned i = 0, e = VL.size(); i < e; ++i) { 3741 unsigned OpsWidth = 0; 3742 3743 if (i + VF > e) 3744 OpsWidth = e - i; 3745 else 3746 OpsWidth = VF; 3747 3748 if (!isPowerOf2_32(OpsWidth) || OpsWidth < 2) 3749 break; 3750 3751 // Check that a previous iteration of this loop did not delete the Value. 3752 if (hasValueBeenRAUWed(VL, TrackValues, i, OpsWidth)) 3753 continue; 3754 3755 DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth << " operations " 3756 << "\n"); 3757 ArrayRef<Value *> Ops = VL.slice(i, OpsWidth); 3758 3759 ArrayRef<Value *> BuildVectorSlice; 3760 if (!BuildVector.empty()) 3761 BuildVectorSlice = BuildVector.slice(i, OpsWidth); 3762 3763 R.buildTree(Ops, BuildVectorSlice); 3764 // TODO: check if we can allow reordering also for other cases than 3765 // tryToVectorizePair() 3766 if (allowReorder && R.shouldReorder()) { 3767 assert(Ops.size() == 2); 3768 assert(BuildVectorSlice.empty()); 3769 Value *ReorderedOps[] = { Ops[1], Ops[0] }; 3770 R.buildTree(ReorderedOps, None); 3771 } 3772 R.computeMinimumValueSizes(); 3773 int Cost = R.getTreeCost(); 3774 3775 if (Cost < -SLPCostThreshold) { 3776 DEBUG(dbgs() << "SLP: Vectorizing list at cost:" << Cost << ".\n"); 3777 Value *VectorizedRoot = R.vectorizeTree(); 3778 3779 // Reconstruct the build vector by extracting the vectorized root. This 3780 // way we handle the case where some elements of the vector are undefined. 3781 // (return (inserelt <4 xi32> (insertelt undef (opd0) 0) (opd1) 2)) 3782 if (!BuildVectorSlice.empty()) { 3783 // The insert point is the last build vector instruction. The vectorized 3784 // root will precede it. This guarantees that we get an instruction. The 3785 // vectorized tree could have been constant folded. 3786 Instruction *InsertAfter = cast<Instruction>(BuildVectorSlice.back()); 3787 unsigned VecIdx = 0; 3788 for (auto &V : BuildVectorSlice) { 3789 IRBuilder<true, NoFolder> Builder( 3790 InsertAfter->getParent(), ++BasicBlock::iterator(InsertAfter)); 3791 InsertElementInst *IE = cast<InsertElementInst>(V); 3792 Instruction *Extract = cast<Instruction>(Builder.CreateExtractElement( 3793 VectorizedRoot, Builder.getInt32(VecIdx++))); 3794 IE->setOperand(1, Extract); 3795 IE->removeFromParent(); 3796 IE->insertAfter(Extract); 3797 InsertAfter = IE; 3798 } 3799 } 3800 // Move to the next bundle. 3801 i += VF - 1; 3802 Changed = true; 3803 } 3804 } 3805 3806 return Changed; 3807 } 3808 3809 bool SLPVectorizer::tryToVectorize(BinaryOperator *V, BoUpSLP &R) { 3810 if (!V) 3811 return false; 3812 3813 // Try to vectorize V. 3814 if (tryToVectorizePair(V->getOperand(0), V->getOperand(1), R)) 3815 return true; 3816 3817 BinaryOperator *A = dyn_cast<BinaryOperator>(V->getOperand(0)); 3818 BinaryOperator *B = dyn_cast<BinaryOperator>(V->getOperand(1)); 3819 // Try to skip B. 3820 if (B && B->hasOneUse()) { 3821 BinaryOperator *B0 = dyn_cast<BinaryOperator>(B->getOperand(0)); 3822 BinaryOperator *B1 = dyn_cast<BinaryOperator>(B->getOperand(1)); 3823 if (tryToVectorizePair(A, B0, R)) { 3824 return true; 3825 } 3826 if (tryToVectorizePair(A, B1, R)) { 3827 return true; 3828 } 3829 } 3830 3831 // Try to skip A. 3832 if (A && A->hasOneUse()) { 3833 BinaryOperator *A0 = dyn_cast<BinaryOperator>(A->getOperand(0)); 3834 BinaryOperator *A1 = dyn_cast<BinaryOperator>(A->getOperand(1)); 3835 if (tryToVectorizePair(A0, B, R)) { 3836 return true; 3837 } 3838 if (tryToVectorizePair(A1, B, R)) { 3839 return true; 3840 } 3841 } 3842 return 0; 3843 } 3844 3845 /// \brief Generate a shuffle mask to be used in a reduction tree. 3846 /// 3847 /// \param VecLen The length of the vector to be reduced. 3848 /// \param NumEltsToRdx The number of elements that should be reduced in the 3849 /// vector. 3850 /// \param IsPairwise Whether the reduction is a pairwise or splitting 3851 /// reduction. A pairwise reduction will generate a mask of 3852 /// <0,2,...> or <1,3,..> while a splitting reduction will generate 3853 /// <2,3, undef,undef> for a vector of 4 and NumElts = 2. 3854 /// \param IsLeft True will generate a mask of even elements, odd otherwise. 3855 static Value *createRdxShuffleMask(unsigned VecLen, unsigned NumEltsToRdx, 3856 bool IsPairwise, bool IsLeft, 3857 IRBuilder<> &Builder) { 3858 assert((IsPairwise || !IsLeft) && "Don't support a <0,1,undef,...> mask"); 3859 3860 SmallVector<Constant *, 32> ShuffleMask( 3861 VecLen, UndefValue::get(Builder.getInt32Ty())); 3862 3863 if (IsPairwise) 3864 // Build a mask of 0, 2, ... (left) or 1, 3, ... (right). 3865 for (unsigned i = 0; i != NumEltsToRdx; ++i) 3866 ShuffleMask[i] = Builder.getInt32(2 * i + !IsLeft); 3867 else 3868 // Move the upper half of the vector to the lower half. 3869 for (unsigned i = 0; i != NumEltsToRdx; ++i) 3870 ShuffleMask[i] = Builder.getInt32(NumEltsToRdx + i); 3871 3872 return ConstantVector::get(ShuffleMask); 3873 } 3874 3875 3876 /// Model horizontal reductions. 3877 /// 3878 /// A horizontal reduction is a tree of reduction operations (currently add and 3879 /// fadd) that has operations that can be put into a vector as its leaf. 3880 /// For example, this tree: 3881 /// 3882 /// mul mul mul mul 3883 /// \ / \ / 3884 /// + + 3885 /// \ / 3886 /// + 3887 /// This tree has "mul" as its reduced values and "+" as its reduction 3888 /// operations. A reduction might be feeding into a store or a binary operation 3889 /// feeding a phi. 3890 /// ... 3891 /// \ / 3892 /// + 3893 /// | 3894 /// phi += 3895 /// 3896 /// Or: 3897 /// ... 3898 /// \ / 3899 /// + 3900 /// | 3901 /// *p = 3902 /// 3903 class HorizontalReduction { 3904 SmallVector<Value *, 16> ReductionOps; 3905 SmallVector<Value *, 32> ReducedVals; 3906 3907 BinaryOperator *ReductionRoot; 3908 PHINode *ReductionPHI; 3909 3910 /// The opcode of the reduction. 3911 unsigned ReductionOpcode; 3912 /// The opcode of the values we perform a reduction on. 3913 unsigned ReducedValueOpcode; 3914 /// Should we model this reduction as a pairwise reduction tree or a tree that 3915 /// splits the vector in halves and adds those halves. 3916 bool IsPairwiseReduction; 3917 3918 public: 3919 /// The width of one full horizontal reduction operation. 3920 unsigned ReduxWidth; 3921 3922 HorizontalReduction() 3923 : ReductionRoot(nullptr), ReductionPHI(nullptr), ReductionOpcode(0), 3924 ReducedValueOpcode(0), IsPairwiseReduction(false), ReduxWidth(0) {} 3925 3926 /// \brief Try to find a reduction tree. 3927 bool matchAssociativeReduction(PHINode *Phi, BinaryOperator *B) { 3928 assert((!Phi || 3929 std::find(Phi->op_begin(), Phi->op_end(), B) != Phi->op_end()) && 3930 "Thi phi needs to use the binary operator"); 3931 3932 // We could have a initial reductions that is not an add. 3933 // r *= v1 + v2 + v3 + v4 3934 // In such a case start looking for a tree rooted in the first '+'. 3935 if (Phi) { 3936 if (B->getOperand(0) == Phi) { 3937 Phi = nullptr; 3938 B = dyn_cast<BinaryOperator>(B->getOperand(1)); 3939 } else if (B->getOperand(1) == Phi) { 3940 Phi = nullptr; 3941 B = dyn_cast<BinaryOperator>(B->getOperand(0)); 3942 } 3943 } 3944 3945 if (!B) 3946 return false; 3947 3948 Type *Ty = B->getType(); 3949 if (!isValidElementType(Ty)) 3950 return false; 3951 3952 const DataLayout &DL = B->getModule()->getDataLayout(); 3953 ReductionOpcode = B->getOpcode(); 3954 ReducedValueOpcode = 0; 3955 // FIXME: Register size should be a parameter to this function, so we can 3956 // try different vectorization factors. 3957 ReduxWidth = MinVecRegSize / DL.getTypeSizeInBits(Ty); 3958 ReductionRoot = B; 3959 ReductionPHI = Phi; 3960 3961 if (ReduxWidth < 4) 3962 return false; 3963 3964 // We currently only support adds. 3965 if (ReductionOpcode != Instruction::Add && 3966 ReductionOpcode != Instruction::FAdd) 3967 return false; 3968 3969 // Post order traverse the reduction tree starting at B. We only handle true 3970 // trees containing only binary operators or selects. 3971 SmallVector<std::pair<Instruction *, unsigned>, 32> Stack; 3972 Stack.push_back(std::make_pair(B, 0)); 3973 while (!Stack.empty()) { 3974 Instruction *TreeN = Stack.back().first; 3975 unsigned EdgeToVist = Stack.back().second++; 3976 bool IsReducedValue = TreeN->getOpcode() != ReductionOpcode; 3977 3978 // Only handle trees in the current basic block. 3979 if (TreeN->getParent() != B->getParent()) 3980 return false; 3981 3982 // Each tree node needs to have one user except for the ultimate 3983 // reduction. 3984 if (!TreeN->hasOneUse() && TreeN != B) 3985 return false; 3986 3987 // Postorder vist. 3988 if (EdgeToVist == 2 || IsReducedValue) { 3989 if (IsReducedValue) { 3990 // Make sure that the opcodes of the operations that we are going to 3991 // reduce match. 3992 if (!ReducedValueOpcode) 3993 ReducedValueOpcode = TreeN->getOpcode(); 3994 else if (ReducedValueOpcode != TreeN->getOpcode()) 3995 return false; 3996 ReducedVals.push_back(TreeN); 3997 } else { 3998 // We need to be able to reassociate the adds. 3999 if (!TreeN->isAssociative()) 4000 return false; 4001 ReductionOps.push_back(TreeN); 4002 } 4003 // Retract. 4004 Stack.pop_back(); 4005 continue; 4006 } 4007 4008 // Visit left or right. 4009 Value *NextV = TreeN->getOperand(EdgeToVist); 4010 // We currently only allow BinaryOperator's and SelectInst's as reduction 4011 // values in our tree. 4012 if (isa<BinaryOperator>(NextV) || isa<SelectInst>(NextV)) 4013 Stack.push_back(std::make_pair(cast<Instruction>(NextV), 0)); 4014 else if (NextV != Phi) 4015 return false; 4016 } 4017 return true; 4018 } 4019 4020 /// \brief Attempt to vectorize the tree found by 4021 /// matchAssociativeReduction. 4022 bool tryToReduce(BoUpSLP &V, TargetTransformInfo *TTI) { 4023 if (ReducedVals.empty()) 4024 return false; 4025 4026 unsigned NumReducedVals = ReducedVals.size(); 4027 if (NumReducedVals < ReduxWidth) 4028 return false; 4029 4030 Value *VectorizedTree = nullptr; 4031 IRBuilder<> Builder(ReductionRoot); 4032 FastMathFlags Unsafe; 4033 Unsafe.setUnsafeAlgebra(); 4034 Builder.setFastMathFlags(Unsafe); 4035 unsigned i = 0; 4036 4037 for (; i < NumReducedVals - ReduxWidth + 1; i += ReduxWidth) { 4038 V.buildTree(makeArrayRef(&ReducedVals[i], ReduxWidth), ReductionOps); 4039 V.computeMinimumValueSizes(); 4040 4041 // Estimate cost. 4042 int Cost = V.getTreeCost() + getReductionCost(TTI, ReducedVals[i]); 4043 if (Cost >= -SLPCostThreshold) 4044 break; 4045 4046 DEBUG(dbgs() << "SLP: Vectorizing horizontal reduction at cost:" << Cost 4047 << ". (HorRdx)\n"); 4048 4049 // Vectorize a tree. 4050 DebugLoc Loc = cast<Instruction>(ReducedVals[i])->getDebugLoc(); 4051 Value *VectorizedRoot = V.vectorizeTree(); 4052 4053 // Emit a reduction. 4054 Value *ReducedSubTree = emitReduction(VectorizedRoot, Builder); 4055 if (VectorizedTree) { 4056 Builder.SetCurrentDebugLocation(Loc); 4057 VectorizedTree = createBinOp(Builder, ReductionOpcode, VectorizedTree, 4058 ReducedSubTree, "bin.rdx"); 4059 } else 4060 VectorizedTree = ReducedSubTree; 4061 } 4062 4063 if (VectorizedTree) { 4064 // Finish the reduction. 4065 for (; i < NumReducedVals; ++i) { 4066 Builder.SetCurrentDebugLocation( 4067 cast<Instruction>(ReducedVals[i])->getDebugLoc()); 4068 VectorizedTree = createBinOp(Builder, ReductionOpcode, VectorizedTree, 4069 ReducedVals[i]); 4070 } 4071 // Update users. 4072 if (ReductionPHI) { 4073 assert(ReductionRoot && "Need a reduction operation"); 4074 ReductionRoot->setOperand(0, VectorizedTree); 4075 ReductionRoot->setOperand(1, ReductionPHI); 4076 } else 4077 ReductionRoot->replaceAllUsesWith(VectorizedTree); 4078 } 4079 return VectorizedTree != nullptr; 4080 } 4081 4082 unsigned numReductionValues() const { 4083 return ReducedVals.size(); 4084 } 4085 4086 private: 4087 /// \brief Calculate the cost of a reduction. 4088 int getReductionCost(TargetTransformInfo *TTI, Value *FirstReducedVal) { 4089 Type *ScalarTy = FirstReducedVal->getType(); 4090 Type *VecTy = VectorType::get(ScalarTy, ReduxWidth); 4091 4092 int PairwiseRdxCost = TTI->getReductionCost(ReductionOpcode, VecTy, true); 4093 int SplittingRdxCost = TTI->getReductionCost(ReductionOpcode, VecTy, false); 4094 4095 IsPairwiseReduction = PairwiseRdxCost < SplittingRdxCost; 4096 int VecReduxCost = IsPairwiseReduction ? PairwiseRdxCost : SplittingRdxCost; 4097 4098 int ScalarReduxCost = 4099 ReduxWidth * TTI->getArithmeticInstrCost(ReductionOpcode, VecTy); 4100 4101 DEBUG(dbgs() << "SLP: Adding cost " << VecReduxCost - ScalarReduxCost 4102 << " for reduction that starts with " << *FirstReducedVal 4103 << " (It is a " 4104 << (IsPairwiseReduction ? "pairwise" : "splitting") 4105 << " reduction)\n"); 4106 4107 return VecReduxCost - ScalarReduxCost; 4108 } 4109 4110 static Value *createBinOp(IRBuilder<> &Builder, unsigned Opcode, Value *L, 4111 Value *R, const Twine &Name = "") { 4112 if (Opcode == Instruction::FAdd) 4113 return Builder.CreateFAdd(L, R, Name); 4114 return Builder.CreateBinOp((Instruction::BinaryOps)Opcode, L, R, Name); 4115 } 4116 4117 /// \brief Emit a horizontal reduction of the vectorized value. 4118 Value *emitReduction(Value *VectorizedValue, IRBuilder<> &Builder) { 4119 assert(VectorizedValue && "Need to have a vectorized tree node"); 4120 assert(isPowerOf2_32(ReduxWidth) && 4121 "We only handle power-of-two reductions for now"); 4122 4123 Value *TmpVec = VectorizedValue; 4124 for (unsigned i = ReduxWidth / 2; i != 0; i >>= 1) { 4125 if (IsPairwiseReduction) { 4126 Value *LeftMask = 4127 createRdxShuffleMask(ReduxWidth, i, true, true, Builder); 4128 Value *RightMask = 4129 createRdxShuffleMask(ReduxWidth, i, true, false, Builder); 4130 4131 Value *LeftShuf = Builder.CreateShuffleVector( 4132 TmpVec, UndefValue::get(TmpVec->getType()), LeftMask, "rdx.shuf.l"); 4133 Value *RightShuf = Builder.CreateShuffleVector( 4134 TmpVec, UndefValue::get(TmpVec->getType()), (RightMask), 4135 "rdx.shuf.r"); 4136 TmpVec = createBinOp(Builder, ReductionOpcode, LeftShuf, RightShuf, 4137 "bin.rdx"); 4138 } else { 4139 Value *UpperHalf = 4140 createRdxShuffleMask(ReduxWidth, i, false, false, Builder); 4141 Value *Shuf = Builder.CreateShuffleVector( 4142 TmpVec, UndefValue::get(TmpVec->getType()), UpperHalf, "rdx.shuf"); 4143 TmpVec = createBinOp(Builder, ReductionOpcode, TmpVec, Shuf, "bin.rdx"); 4144 } 4145 } 4146 4147 // The result is in the first element of the vector. 4148 return Builder.CreateExtractElement(TmpVec, Builder.getInt32(0)); 4149 } 4150 }; 4151 4152 /// \brief Recognize construction of vectors like 4153 /// %ra = insertelement <4 x float> undef, float %s0, i32 0 4154 /// %rb = insertelement <4 x float> %ra, float %s1, i32 1 4155 /// %rc = insertelement <4 x float> %rb, float %s2, i32 2 4156 /// %rd = insertelement <4 x float> %rc, float %s3, i32 3 4157 /// 4158 /// Returns true if it matches 4159 /// 4160 static bool findBuildVector(InsertElementInst *FirstInsertElem, 4161 SmallVectorImpl<Value *> &BuildVector, 4162 SmallVectorImpl<Value *> &BuildVectorOpds) { 4163 if (!isa<UndefValue>(FirstInsertElem->getOperand(0))) 4164 return false; 4165 4166 InsertElementInst *IE = FirstInsertElem; 4167 while (true) { 4168 BuildVector.push_back(IE); 4169 BuildVectorOpds.push_back(IE->getOperand(1)); 4170 4171 if (IE->use_empty()) 4172 return false; 4173 4174 InsertElementInst *NextUse = dyn_cast<InsertElementInst>(IE->user_back()); 4175 if (!NextUse) 4176 return true; 4177 4178 // If this isn't the final use, make sure the next insertelement is the only 4179 // use. It's OK if the final constructed vector is used multiple times 4180 if (!IE->hasOneUse()) 4181 return false; 4182 4183 IE = NextUse; 4184 } 4185 4186 return false; 4187 } 4188 4189 static bool PhiTypeSorterFunc(Value *V, Value *V2) { 4190 return V->getType() < V2->getType(); 4191 } 4192 4193 /// \brief Try and get a reduction value from a phi node. 4194 /// 4195 /// Given a phi node \p P in a block \p ParentBB, consider possible reductions 4196 /// if they come from either \p ParentBB or a containing loop latch. 4197 /// 4198 /// \returns A candidate reduction value if possible, or \code nullptr \endcode 4199 /// if not possible. 4200 static Value *getReductionValue(const DominatorTree *DT, PHINode *P, 4201 BasicBlock *ParentBB, LoopInfo *LI) { 4202 // There are situations where the reduction value is not dominated by the 4203 // reduction phi. Vectorizing such cases has been reported to cause 4204 // miscompiles. See PR25787. 4205 auto DominatedReduxValue = [&](Value *R) { 4206 return ( 4207 dyn_cast<Instruction>(R) && 4208 DT->dominates(P->getParent(), dyn_cast<Instruction>(R)->getParent())); 4209 }; 4210 4211 Value *Rdx = nullptr; 4212 4213 // Return the incoming value if it comes from the same BB as the phi node. 4214 if (P->getIncomingBlock(0) == ParentBB) { 4215 Rdx = P->getIncomingValue(0); 4216 } else if (P->getIncomingBlock(1) == ParentBB) { 4217 Rdx = P->getIncomingValue(1); 4218 } 4219 4220 if (Rdx && DominatedReduxValue(Rdx)) 4221 return Rdx; 4222 4223 // Otherwise, check whether we have a loop latch to look at. 4224 Loop *BBL = LI->getLoopFor(ParentBB); 4225 if (!BBL) 4226 return nullptr; 4227 BasicBlock *BBLatch = BBL->getLoopLatch(); 4228 if (!BBLatch) 4229 return nullptr; 4230 4231 // There is a loop latch, return the incoming value if it comes from 4232 // that. This reduction pattern occassionaly turns up. 4233 if (P->getIncomingBlock(0) == BBLatch) { 4234 Rdx = P->getIncomingValue(0); 4235 } else if (P->getIncomingBlock(1) == BBLatch) { 4236 Rdx = P->getIncomingValue(1); 4237 } 4238 4239 if (Rdx && DominatedReduxValue(Rdx)) 4240 return Rdx; 4241 4242 return nullptr; 4243 } 4244 4245 /// \brief Attempt to reduce a horizontal reduction. 4246 /// If it is legal to match a horizontal reduction feeding 4247 /// the phi node P with reduction operators BI, then check if it 4248 /// can be done. 4249 /// \returns true if a horizontal reduction was matched and reduced. 4250 /// \returns false if a horizontal reduction was not matched. 4251 static bool canMatchHorizontalReduction(PHINode *P, BinaryOperator *BI, 4252 BoUpSLP &R, TargetTransformInfo *TTI) { 4253 if (!ShouldVectorizeHor) 4254 return false; 4255 4256 HorizontalReduction HorRdx; 4257 if (!HorRdx.matchAssociativeReduction(P, BI)) 4258 return false; 4259 4260 // If there is a sufficient number of reduction values, reduce 4261 // to a nearby power-of-2. Can safely generate oversized 4262 // vectors and rely on the backend to split them to legal sizes. 4263 HorRdx.ReduxWidth = 4264 std::max((uint64_t)4, PowerOf2Floor(HorRdx.numReductionValues())); 4265 4266 return HorRdx.tryToReduce(R, TTI); 4267 } 4268 4269 bool SLPVectorizer::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) { 4270 bool Changed = false; 4271 SmallVector<Value *, 4> Incoming; 4272 SmallSet<Value *, 16> VisitedInstrs; 4273 4274 bool HaveVectorizedPhiNodes = true; 4275 while (HaveVectorizedPhiNodes) { 4276 HaveVectorizedPhiNodes = false; 4277 4278 // Collect the incoming values from the PHIs. 4279 Incoming.clear(); 4280 for (Instruction &I : *BB) { 4281 PHINode *P = dyn_cast<PHINode>(&I); 4282 if (!P) 4283 break; 4284 4285 if (!VisitedInstrs.count(P)) 4286 Incoming.push_back(P); 4287 } 4288 4289 // Sort by type. 4290 std::stable_sort(Incoming.begin(), Incoming.end(), PhiTypeSorterFunc); 4291 4292 // Try to vectorize elements base on their type. 4293 for (SmallVector<Value *, 4>::iterator IncIt = Incoming.begin(), 4294 E = Incoming.end(); 4295 IncIt != E;) { 4296 4297 // Look for the next elements with the same type. 4298 SmallVector<Value *, 4>::iterator SameTypeIt = IncIt; 4299 while (SameTypeIt != E && 4300 (*SameTypeIt)->getType() == (*IncIt)->getType()) { 4301 VisitedInstrs.insert(*SameTypeIt); 4302 ++SameTypeIt; 4303 } 4304 4305 // Try to vectorize them. 4306 unsigned NumElts = (SameTypeIt - IncIt); 4307 DEBUG(errs() << "SLP: Trying to vectorize starting at PHIs (" << NumElts << ")\n"); 4308 if (NumElts > 1 && tryToVectorizeList(makeArrayRef(IncIt, NumElts), R)) { 4309 // Success start over because instructions might have been changed. 4310 HaveVectorizedPhiNodes = true; 4311 Changed = true; 4312 break; 4313 } 4314 4315 // Start over at the next instruction of a different type (or the end). 4316 IncIt = SameTypeIt; 4317 } 4318 } 4319 4320 VisitedInstrs.clear(); 4321 4322 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; it++) { 4323 // We may go through BB multiple times so skip the one we have checked. 4324 if (!VisitedInstrs.insert(&*it).second) 4325 continue; 4326 4327 if (isa<DbgInfoIntrinsic>(it)) 4328 continue; 4329 4330 // Try to vectorize reductions that use PHINodes. 4331 if (PHINode *P = dyn_cast<PHINode>(it)) { 4332 // Check that the PHI is a reduction PHI. 4333 if (P->getNumIncomingValues() != 2) 4334 return Changed; 4335 4336 Value *Rdx = getReductionValue(DT, P, BB, LI); 4337 4338 // Check if this is a Binary Operator. 4339 BinaryOperator *BI = dyn_cast_or_null<BinaryOperator>(Rdx); 4340 if (!BI) 4341 continue; 4342 4343 // Try to match and vectorize a horizontal reduction. 4344 if (canMatchHorizontalReduction(P, BI, R, TTI)) { 4345 Changed = true; 4346 it = BB->begin(); 4347 e = BB->end(); 4348 continue; 4349 } 4350 4351 Value *Inst = BI->getOperand(0); 4352 if (Inst == P) 4353 Inst = BI->getOperand(1); 4354 4355 if (tryToVectorize(dyn_cast<BinaryOperator>(Inst), R)) { 4356 // We would like to start over since some instructions are deleted 4357 // and the iterator may become invalid value. 4358 Changed = true; 4359 it = BB->begin(); 4360 e = BB->end(); 4361 continue; 4362 } 4363 4364 continue; 4365 } 4366 4367 if (ShouldStartVectorizeHorAtStore) 4368 if (StoreInst *SI = dyn_cast<StoreInst>(it)) 4369 if (BinaryOperator *BinOp = 4370 dyn_cast<BinaryOperator>(SI->getValueOperand())) { 4371 if (canMatchHorizontalReduction(nullptr, BinOp, R, TTI) || 4372 tryToVectorize(BinOp, R)) { 4373 Changed = true; 4374 it = BB->begin(); 4375 e = BB->end(); 4376 continue; 4377 } 4378 } 4379 4380 // Try to vectorize horizontal reductions feeding into a return. 4381 if (ReturnInst *RI = dyn_cast<ReturnInst>(it)) 4382 if (RI->getNumOperands() != 0) 4383 if (BinaryOperator *BinOp = 4384 dyn_cast<BinaryOperator>(RI->getOperand(0))) { 4385 DEBUG(dbgs() << "SLP: Found a return to vectorize.\n"); 4386 if (tryToVectorizePair(BinOp->getOperand(0), 4387 BinOp->getOperand(1), R)) { 4388 Changed = true; 4389 it = BB->begin(); 4390 e = BB->end(); 4391 continue; 4392 } 4393 } 4394 4395 // Try to vectorize trees that start at compare instructions. 4396 if (CmpInst *CI = dyn_cast<CmpInst>(it)) { 4397 if (tryToVectorizePair(CI->getOperand(0), CI->getOperand(1), R)) { 4398 Changed = true; 4399 // We would like to start over since some instructions are deleted 4400 // and the iterator may become invalid value. 4401 it = BB->begin(); 4402 e = BB->end(); 4403 continue; 4404 } 4405 4406 for (int i = 0; i < 2; ++i) { 4407 if (BinaryOperator *BI = dyn_cast<BinaryOperator>(CI->getOperand(i))) { 4408 if (tryToVectorizePair(BI->getOperand(0), BI->getOperand(1), R)) { 4409 Changed = true; 4410 // We would like to start over since some instructions are deleted 4411 // and the iterator may become invalid value. 4412 it = BB->begin(); 4413 e = BB->end(); 4414 break; 4415 } 4416 } 4417 } 4418 continue; 4419 } 4420 4421 // Try to vectorize trees that start at insertelement instructions. 4422 if (InsertElementInst *FirstInsertElem = dyn_cast<InsertElementInst>(it)) { 4423 SmallVector<Value *, 16> BuildVector; 4424 SmallVector<Value *, 16> BuildVectorOpds; 4425 if (!findBuildVector(FirstInsertElem, BuildVector, BuildVectorOpds)) 4426 continue; 4427 4428 // Vectorize starting with the build vector operands ignoring the 4429 // BuildVector instructions for the purpose of scheduling and user 4430 // extraction. 4431 if (tryToVectorizeList(BuildVectorOpds, R, BuildVector)) { 4432 Changed = true; 4433 it = BB->begin(); 4434 e = BB->end(); 4435 } 4436 4437 continue; 4438 } 4439 } 4440 4441 return Changed; 4442 } 4443 4444 bool SLPVectorizer::vectorizeGEPIndices(BasicBlock *BB, BoUpSLP &R) { 4445 auto Changed = false; 4446 for (auto &Entry : GEPs) { 4447 4448 // If the getelementptr list has fewer than two elements, there's nothing 4449 // to do. 4450 if (Entry.second.size() < 2) 4451 continue; 4452 4453 DEBUG(dbgs() << "SLP: Analyzing a getelementptr list of length " 4454 << Entry.second.size() << ".\n"); 4455 4456 // We process the getelementptr list in chunks of 16 (like we do for 4457 // stores) to minimize compile-time. 4458 for (unsigned BI = 0, BE = Entry.second.size(); BI < BE; BI += 16) { 4459 auto Len = std::min<unsigned>(BE - BI, 16); 4460 auto GEPList = makeArrayRef(&Entry.second[BI], Len); 4461 4462 // Initialize a set a candidate getelementptrs. Note that we use a 4463 // SetVector here to preserve program order. If the index computations 4464 // are vectorizable and begin with loads, we want to minimize the chance 4465 // of having to reorder them later. 4466 SetVector<Value *> Candidates(GEPList.begin(), GEPList.end()); 4467 4468 // Some of the candidates may have already been vectorized after we 4469 // initially collected them. If so, the WeakVHs will have nullified the 4470 // values, so remove them from the set of candidates. 4471 Candidates.remove(nullptr); 4472 4473 // Remove from the set of candidates all pairs of getelementptrs with 4474 // constant differences. Such getelementptrs are likely not good 4475 // candidates for vectorization in a bottom-up phase since one can be 4476 // computed from the other. We also ensure all candidate getelementptr 4477 // indices are unique. 4478 for (int I = 0, E = GEPList.size(); I < E && Candidates.size() > 1; ++I) { 4479 auto *GEPI = cast<GetElementPtrInst>(GEPList[I]); 4480 if (!Candidates.count(GEPI)) 4481 continue; 4482 auto *SCEVI = SE->getSCEV(GEPList[I]); 4483 for (int J = I + 1; J < E && Candidates.size() > 1; ++J) { 4484 auto *GEPJ = cast<GetElementPtrInst>(GEPList[J]); 4485 auto *SCEVJ = SE->getSCEV(GEPList[J]); 4486 if (isa<SCEVConstant>(SE->getMinusSCEV(SCEVI, SCEVJ))) { 4487 Candidates.remove(GEPList[I]); 4488 Candidates.remove(GEPList[J]); 4489 } else if (GEPI->idx_begin()->get() == GEPJ->idx_begin()->get()) { 4490 Candidates.remove(GEPList[J]); 4491 } 4492 } 4493 } 4494 4495 // We break out of the above computation as soon as we know there are 4496 // fewer than two candidates remaining. 4497 if (Candidates.size() < 2) 4498 continue; 4499 4500 // Add the single, non-constant index of each candidate to the bundle. We 4501 // ensured the indices met these constraints when we originally collected 4502 // the getelementptrs. 4503 SmallVector<Value *, 16> Bundle(Candidates.size()); 4504 auto BundleIndex = 0u; 4505 for (auto *V : Candidates) { 4506 auto *GEP = cast<GetElementPtrInst>(V); 4507 auto *GEPIdx = GEP->idx_begin()->get(); 4508 assert(GEP->getNumIndices() == 1 || !isa<Constant>(GEPIdx)); 4509 Bundle[BundleIndex++] = GEPIdx; 4510 } 4511 4512 // Try and vectorize the indices. We are currently only interested in 4513 // gather-like cases of the form: 4514 // 4515 // ... = g[a[0] - b[0]] + g[a[1] - b[1]] + ... 4516 // 4517 // where the loads of "a", the loads of "b", and the subtractions can be 4518 // performed in parallel. It's likely that detecting this pattern in a 4519 // bottom-up phase will be simpler and less costly than building a 4520 // full-blown top-down phase beginning at the consecutive loads. 4521 Changed |= tryToVectorizeList(Bundle, R); 4522 } 4523 } 4524 return Changed; 4525 } 4526 4527 bool SLPVectorizer::vectorizeStoreChains(BoUpSLP &R) { 4528 bool Changed = false; 4529 // Attempt to sort and vectorize each of the store-groups. 4530 for (StoreListMap::iterator it = Stores.begin(), e = Stores.end(); it != e; 4531 ++it) { 4532 if (it->second.size() < 2) 4533 continue; 4534 4535 DEBUG(dbgs() << "SLP: Analyzing a store chain of length " 4536 << it->second.size() << ".\n"); 4537 4538 // Process the stores in chunks of 16. 4539 // TODO: The limit of 16 inhibits greater vectorization factors. 4540 // For example, AVX2 supports v32i8. Increasing this limit, however, 4541 // may cause a significant compile-time increase. 4542 for (unsigned CI = 0, CE = it->second.size(); CI < CE; CI+=16) { 4543 unsigned Len = std::min<unsigned>(CE - CI, 16); 4544 Changed |= vectorizeStores(makeArrayRef(&it->second[CI], Len), 4545 -SLPCostThreshold, R); 4546 } 4547 } 4548 return Changed; 4549 } 4550 4551 } // end anonymous namespace 4552 4553 char SLPVectorizer::ID = 0; 4554 static const char lv_name[] = "SLP Vectorizer"; 4555 INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false) 4556 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass) 4557 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass) 4558 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 4559 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass) 4560 INITIALIZE_PASS_DEPENDENCY(LoopSimplify) 4561 INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false) 4562 4563 namespace llvm { 4564 Pass *createSLPVectorizerPass() { return new SLPVectorizer(); } 4565 } 4566