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 #define SV_NAME "slp-vectorizer" 19 #define DEBUG_TYPE "SLP" 20 21 #include "llvm/Transforms/Vectorize.h" 22 #include "llvm/ADT/MapVector.h" 23 #include "llvm/ADT/PostOrderIterator.h" 24 #include "llvm/ADT/SetVector.h" 25 #include "llvm/Analysis/AliasAnalysis.h" 26 #include "llvm/Analysis/LoopInfo.h" 27 #include "llvm/Analysis/ScalarEvolution.h" 28 #include "llvm/Analysis/ScalarEvolutionExpressions.h" 29 #include "llvm/Analysis/TargetTransformInfo.h" 30 #include "llvm/Analysis/ValueTracking.h" 31 #include "llvm/IR/DataLayout.h" 32 #include "llvm/IR/Dominators.h" 33 #include "llvm/IR/IRBuilder.h" 34 #include "llvm/IR/Instructions.h" 35 #include "llvm/IR/IntrinsicInst.h" 36 #include "llvm/IR/Module.h" 37 #include "llvm/IR/Type.h" 38 #include "llvm/IR/Value.h" 39 #include "llvm/IR/Verifier.h" 40 #include "llvm/Pass.h" 41 #include "llvm/Support/CommandLine.h" 42 #include "llvm/Support/Debug.h" 43 #include "llvm/Support/raw_ostream.h" 44 #include <algorithm> 45 #include <map> 46 47 using namespace llvm; 48 49 static cl::opt<int> 50 SLPCostThreshold("slp-threshold", cl::init(0), cl::Hidden, 51 cl::desc("Only vectorize if you gain more than this " 52 "number ")); 53 54 static cl::opt<bool> 55 ShouldVectorizeHor("slp-vectorize-hor", cl::init(false), cl::Hidden, 56 cl::desc("Attempt to vectorize horizontal reductions")); 57 58 static cl::opt<bool> ShouldStartVectorizeHorAtStore( 59 "slp-vectorize-hor-store", cl::init(false), cl::Hidden, 60 cl::desc( 61 "Attempt to vectorize horizontal reductions feeding into a store")); 62 63 namespace { 64 65 static const unsigned MinVecRegSize = 128; 66 67 static const unsigned RecursionMaxDepth = 12; 68 69 /// A helper class for numbering instructions in multiple blocks. 70 /// Numbers start at zero for each basic block. 71 struct BlockNumbering { 72 73 BlockNumbering(BasicBlock *Bb) : BB(Bb), Valid(false) {} 74 75 BlockNumbering() : BB(0), Valid(false) {} 76 77 void numberInstructions() { 78 unsigned Loc = 0; 79 InstrIdx.clear(); 80 InstrVec.clear(); 81 // Number the instructions in the block. 82 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) { 83 InstrIdx[it] = Loc++; 84 InstrVec.push_back(it); 85 assert(InstrVec[InstrIdx[it]] == it && "Invalid allocation"); 86 } 87 Valid = true; 88 } 89 90 int getIndex(Instruction *I) { 91 assert(I->getParent() == BB && "Invalid instruction"); 92 if (!Valid) 93 numberInstructions(); 94 assert(InstrIdx.count(I) && "Unknown instruction"); 95 return InstrIdx[I]; 96 } 97 98 Instruction *getInstruction(unsigned loc) { 99 if (!Valid) 100 numberInstructions(); 101 assert(InstrVec.size() > loc && "Invalid Index"); 102 return InstrVec[loc]; 103 } 104 105 void forget() { Valid = false; } 106 107 private: 108 /// The block we are numbering. 109 BasicBlock *BB; 110 /// Is the block numbered. 111 bool Valid; 112 /// Maps instructions to numbers and back. 113 SmallDenseMap<Instruction *, int> InstrIdx; 114 /// Maps integers to Instructions. 115 SmallVector<Instruction *, 32> InstrVec; 116 }; 117 118 /// \returns the parent basic block if all of the instructions in \p VL 119 /// are in the same block or null otherwise. 120 static BasicBlock *getSameBlock(ArrayRef<Value *> VL) { 121 Instruction *I0 = dyn_cast<Instruction>(VL[0]); 122 if (!I0) 123 return 0; 124 BasicBlock *BB = I0->getParent(); 125 for (int i = 1, e = VL.size(); i < e; i++) { 126 Instruction *I = dyn_cast<Instruction>(VL[i]); 127 if (!I) 128 return 0; 129 130 if (BB != I->getParent()) 131 return 0; 132 } 133 return BB; 134 } 135 136 /// \returns True if all of the values in \p VL are constants. 137 static bool allConstant(ArrayRef<Value *> VL) { 138 for (unsigned i = 0, e = VL.size(); i < e; ++i) 139 if (!isa<Constant>(VL[i])) 140 return false; 141 return true; 142 } 143 144 /// \returns True if all of the values in \p VL are identical. 145 static bool isSplat(ArrayRef<Value *> VL) { 146 for (unsigned i = 1, e = VL.size(); i < e; ++i) 147 if (VL[i] != VL[0]) 148 return false; 149 return true; 150 } 151 152 /// \returns The opcode if all of the Instructions in \p VL have the same 153 /// opcode, or zero. 154 static unsigned getSameOpcode(ArrayRef<Value *> VL) { 155 Instruction *I0 = dyn_cast<Instruction>(VL[0]); 156 if (!I0) 157 return 0; 158 unsigned Opcode = I0->getOpcode(); 159 for (int i = 1, e = VL.size(); i < e; i++) { 160 Instruction *I = dyn_cast<Instruction>(VL[i]); 161 if (!I || Opcode != I->getOpcode()) 162 return 0; 163 } 164 return Opcode; 165 } 166 167 /// \returns \p I after propagating metadata from \p VL. 168 static Instruction *propagateMetadata(Instruction *I, ArrayRef<Value *> VL) { 169 Instruction *I0 = cast<Instruction>(VL[0]); 170 SmallVector<std::pair<unsigned, MDNode *>, 4> Metadata; 171 I0->getAllMetadataOtherThanDebugLoc(Metadata); 172 173 for (unsigned i = 0, n = Metadata.size(); i != n; ++i) { 174 unsigned Kind = Metadata[i].first; 175 MDNode *MD = Metadata[i].second; 176 177 for (int i = 1, e = VL.size(); MD && i != e; i++) { 178 Instruction *I = cast<Instruction>(VL[i]); 179 MDNode *IMD = I->getMetadata(Kind); 180 181 switch (Kind) { 182 default: 183 MD = 0; // Remove unknown metadata 184 break; 185 case LLVMContext::MD_tbaa: 186 MD = MDNode::getMostGenericTBAA(MD, IMD); 187 break; 188 case LLVMContext::MD_fpmath: 189 MD = MDNode::getMostGenericFPMath(MD, IMD); 190 break; 191 } 192 } 193 I->setMetadata(Kind, MD); 194 } 195 return I; 196 } 197 198 /// \returns The type that all of the values in \p VL have or null if there 199 /// are different types. 200 static Type* getSameType(ArrayRef<Value *> VL) { 201 Type *Ty = VL[0]->getType(); 202 for (int i = 1, e = VL.size(); i < e; i++) 203 if (VL[i]->getType() != Ty) 204 return 0; 205 206 return Ty; 207 } 208 209 /// \returns True if the ExtractElement instructions in VL can be vectorized 210 /// to use the original vector. 211 static bool CanReuseExtract(ArrayRef<Value *> VL) { 212 assert(Instruction::ExtractElement == getSameOpcode(VL) && "Invalid opcode"); 213 // Check if all of the extracts come from the same vector and from the 214 // correct offset. 215 Value *VL0 = VL[0]; 216 ExtractElementInst *E0 = cast<ExtractElementInst>(VL0); 217 Value *Vec = E0->getOperand(0); 218 219 // We have to extract from the same vector type. 220 unsigned NElts = Vec->getType()->getVectorNumElements(); 221 222 if (NElts != VL.size()) 223 return false; 224 225 // Check that all of the indices extract from the correct offset. 226 ConstantInt *CI = dyn_cast<ConstantInt>(E0->getOperand(1)); 227 if (!CI || CI->getZExtValue()) 228 return false; 229 230 for (unsigned i = 1, e = VL.size(); i < e; ++i) { 231 ExtractElementInst *E = cast<ExtractElementInst>(VL[i]); 232 ConstantInt *CI = dyn_cast<ConstantInt>(E->getOperand(1)); 233 234 if (!CI || CI->getZExtValue() != i || E->getOperand(0) != Vec) 235 return false; 236 } 237 238 return true; 239 } 240 241 static void reorderInputsAccordingToOpcode(ArrayRef<Value *> VL, 242 SmallVectorImpl<Value *> &Left, 243 SmallVectorImpl<Value *> &Right) { 244 245 SmallVector<Value *, 16> OrigLeft, OrigRight; 246 247 bool AllSameOpcodeLeft = true; 248 bool AllSameOpcodeRight = true; 249 for (unsigned i = 0, e = VL.size(); i != e; ++i) { 250 Instruction *I = cast<Instruction>(VL[i]); 251 Value *V0 = I->getOperand(0); 252 Value *V1 = I->getOperand(1); 253 254 OrigLeft.push_back(V0); 255 OrigRight.push_back(V1); 256 257 Instruction *I0 = dyn_cast<Instruction>(V0); 258 Instruction *I1 = dyn_cast<Instruction>(V1); 259 260 // Check whether all operands on one side have the same opcode. In this case 261 // we want to preserve the original order and not make things worse by 262 // reordering. 263 AllSameOpcodeLeft = I0; 264 AllSameOpcodeRight = I1; 265 266 if (i && AllSameOpcodeLeft) { 267 if(Instruction *P0 = dyn_cast<Instruction>(OrigLeft[i-1])) { 268 if(P0->getOpcode() != I0->getOpcode()) 269 AllSameOpcodeLeft = false; 270 } else 271 AllSameOpcodeLeft = false; 272 } 273 if (i && AllSameOpcodeRight) { 274 if(Instruction *P1 = dyn_cast<Instruction>(OrigRight[i-1])) { 275 if(P1->getOpcode() != I1->getOpcode()) 276 AllSameOpcodeRight = false; 277 } else 278 AllSameOpcodeRight = false; 279 } 280 281 // Sort two opcodes. In the code below we try to preserve the ability to use 282 // broadcast of values instead of individual inserts. 283 // vl1 = load 284 // vl2 = phi 285 // vr1 = load 286 // vr2 = vr2 287 // = vl1 x vr1 288 // = vl2 x vr2 289 // If we just sorted according to opcode we would leave the first line in 290 // tact but we would swap vl2 with vr2 because opcode(phi) > opcode(load). 291 // = vl1 x vr1 292 // = vr2 x vl2 293 // Because vr2 and vr1 are from the same load we loose the opportunity of a 294 // broadcast for the packed right side in the backend: we have [vr1, vl2] 295 // instead of [vr1, vr2=vr1]. 296 if (I0 && I1) { 297 if(!i && I0->getOpcode() > I1->getOpcode()) { 298 Left.push_back(I1); 299 Right.push_back(I0); 300 } else if (i && I0->getOpcode() > I1->getOpcode() && Right[i-1] != I1) { 301 // Try not to destroy a broad cast for no apparent benefit. 302 Left.push_back(I1); 303 Right.push_back(I0); 304 } else if (i && I0->getOpcode() == I1->getOpcode() && Right[i-1] == I0) { 305 // Try preserve broadcasts. 306 Left.push_back(I1); 307 Right.push_back(I0); 308 } else if (i && I0->getOpcode() == I1->getOpcode() && Left[i-1] == I1) { 309 // Try preserve broadcasts. 310 Left.push_back(I1); 311 Right.push_back(I0); 312 } else { 313 Left.push_back(I0); 314 Right.push_back(I1); 315 } 316 continue; 317 } 318 // One opcode, put the instruction on the right. 319 if (I0) { 320 Left.push_back(V1); 321 Right.push_back(I0); 322 continue; 323 } 324 Left.push_back(V0); 325 Right.push_back(V1); 326 } 327 328 bool LeftBroadcast = isSplat(Left); 329 bool RightBroadcast = isSplat(Right); 330 331 // Don't reorder if the operands where good to begin with. 332 if (!(LeftBroadcast || RightBroadcast) && 333 (AllSameOpcodeRight || AllSameOpcodeLeft)) { 334 Left = OrigLeft; 335 Right = OrigRight; 336 } 337 } 338 339 /// Bottom Up SLP Vectorizer. 340 class BoUpSLP { 341 public: 342 typedef SmallVector<Value *, 8> ValueList; 343 typedef SmallVector<Instruction *, 16> InstrList; 344 typedef SmallPtrSet<Value *, 16> ValueSet; 345 typedef SmallVector<StoreInst *, 8> StoreList; 346 347 BoUpSLP(Function *Func, ScalarEvolution *Se, DataLayout *Dl, 348 TargetTransformInfo *Tti, AliasAnalysis *Aa, LoopInfo *Li, 349 DominatorTree *Dt) : 350 F(Func), SE(Se), DL(Dl), TTI(Tti), AA(Aa), LI(Li), DT(Dt), 351 Builder(Se->getContext()) { 352 // Setup the block numbering utility for all of the blocks in the 353 // function. 354 for (Function::iterator it = F->begin(), e = F->end(); it != e; ++it) { 355 BasicBlock *BB = it; 356 BlocksNumbers[BB] = BlockNumbering(BB); 357 } 358 } 359 360 /// \brief Vectorize the tree that starts with the elements in \p VL. 361 /// Returns the vectorized root. 362 Value *vectorizeTree(); 363 364 /// \returns the vectorization cost of the subtree that starts at \p VL. 365 /// A negative number means that this is profitable. 366 int getTreeCost(); 367 368 /// Construct a vectorizable tree that starts at \p Roots and is possibly 369 /// used by a reduction of \p RdxOps. 370 void buildTree(ArrayRef<Value *> Roots, ValueSet *RdxOps = 0); 371 372 /// Clear the internal data structures that are created by 'buildTree'. 373 void deleteTree() { 374 RdxOps = 0; 375 VectorizableTree.clear(); 376 ScalarToTreeEntry.clear(); 377 MustGather.clear(); 378 ExternalUses.clear(); 379 MemBarrierIgnoreList.clear(); 380 } 381 382 /// \returns true if the memory operations A and B are consecutive. 383 bool isConsecutiveAccess(Value *A, Value *B); 384 385 /// \brief Perform LICM and CSE on the newly generated gather sequences. 386 void optimizeGatherSequence(); 387 private: 388 struct TreeEntry; 389 390 /// \returns the cost of the vectorizable entry. 391 int getEntryCost(TreeEntry *E); 392 393 /// This is the recursive part of buildTree. 394 void buildTree_rec(ArrayRef<Value *> Roots, unsigned Depth); 395 396 /// Vectorize a single entry in the tree. 397 Value *vectorizeTree(TreeEntry *E); 398 399 /// Vectorize a single entry in the tree, starting in \p VL. 400 Value *vectorizeTree(ArrayRef<Value *> VL); 401 402 /// \returns the pointer to the vectorized value if \p VL is already 403 /// vectorized, or NULL. They may happen in cycles. 404 Value *alreadyVectorized(ArrayRef<Value *> VL) const; 405 406 /// \brief Take the pointer operand from the Load/Store instruction. 407 /// \returns NULL if this is not a valid Load/Store instruction. 408 static Value *getPointerOperand(Value *I); 409 410 /// \brief Take the address space operand from the Load/Store instruction. 411 /// \returns -1 if this is not a valid Load/Store instruction. 412 static unsigned getAddressSpaceOperand(Value *I); 413 414 /// \returns the scalarization cost for this type. Scalarization in this 415 /// context means the creation of vectors from a group of scalars. 416 int getGatherCost(Type *Ty); 417 418 /// \returns the scalarization cost for this list of values. Assuming that 419 /// this subtree gets vectorized, we may need to extract the values from the 420 /// roots. This method calculates the cost of extracting the values. 421 int getGatherCost(ArrayRef<Value *> VL); 422 423 /// \returns the AA location that is being access by the instruction. 424 AliasAnalysis::Location getLocation(Instruction *I); 425 426 /// \brief Checks if it is possible to sink an instruction from 427 /// \p Src to \p Dst. 428 /// \returns the pointer to the barrier instruction if we can't sink. 429 Value *getSinkBarrier(Instruction *Src, Instruction *Dst); 430 431 /// \returns the index of the last instruction in the BB from \p VL. 432 int getLastIndex(ArrayRef<Value *> VL); 433 434 /// \returns the Instruction in the bundle \p VL. 435 Instruction *getLastInstruction(ArrayRef<Value *> VL); 436 437 /// \brief Set the Builder insert point to one after the last instruction in 438 /// the bundle 439 void setInsertPointAfterBundle(ArrayRef<Value *> VL); 440 441 /// \returns a vector from a collection of scalars in \p VL. 442 Value *Gather(ArrayRef<Value *> VL, VectorType *Ty); 443 444 /// \returns whether the VectorizableTree is fully vectoriable and will 445 /// be beneficial even the tree height is tiny. 446 bool isFullyVectorizableTinyTree(); 447 448 struct TreeEntry { 449 TreeEntry() : Scalars(), VectorizedValue(0), LastScalarIndex(0), 450 NeedToGather(0) {} 451 452 /// \returns true if the scalars in VL are equal to this entry. 453 bool isSame(ArrayRef<Value *> VL) const { 454 assert(VL.size() == Scalars.size() && "Invalid size"); 455 return std::equal(VL.begin(), VL.end(), Scalars.begin()); 456 } 457 458 /// A vector of scalars. 459 ValueList Scalars; 460 461 /// The Scalars are vectorized into this value. It is initialized to Null. 462 Value *VectorizedValue; 463 464 /// The index in the basic block of the last scalar. 465 int LastScalarIndex; 466 467 /// Do we need to gather this sequence ? 468 bool NeedToGather; 469 }; 470 471 /// Create a new VectorizableTree entry. 472 TreeEntry *newTreeEntry(ArrayRef<Value *> VL, bool Vectorized) { 473 VectorizableTree.push_back(TreeEntry()); 474 int idx = VectorizableTree.size() - 1; 475 TreeEntry *Last = &VectorizableTree[idx]; 476 Last->Scalars.insert(Last->Scalars.begin(), VL.begin(), VL.end()); 477 Last->NeedToGather = !Vectorized; 478 if (Vectorized) { 479 Last->LastScalarIndex = getLastIndex(VL); 480 for (int i = 0, e = VL.size(); i != e; ++i) { 481 assert(!ScalarToTreeEntry.count(VL[i]) && "Scalar already in tree!"); 482 ScalarToTreeEntry[VL[i]] = idx; 483 } 484 } else { 485 Last->LastScalarIndex = 0; 486 MustGather.insert(VL.begin(), VL.end()); 487 } 488 return Last; 489 } 490 491 /// -- Vectorization State -- 492 /// Holds all of the tree entries. 493 std::vector<TreeEntry> VectorizableTree; 494 495 /// Maps a specific scalar to its tree entry. 496 SmallDenseMap<Value*, int> ScalarToTreeEntry; 497 498 /// A list of scalars that we found that we need to keep as scalars. 499 ValueSet MustGather; 500 501 /// This POD struct describes one external user in the vectorized tree. 502 struct ExternalUser { 503 ExternalUser (Value *S, llvm::User *U, int L) : 504 Scalar(S), User(U), Lane(L){}; 505 // Which scalar in our function. 506 Value *Scalar; 507 // Which user that uses the scalar. 508 llvm::User *User; 509 // Which lane does the scalar belong to. 510 int Lane; 511 }; 512 typedef SmallVector<ExternalUser, 16> UserList; 513 514 /// A list of values that need to extracted out of the tree. 515 /// This list holds pairs of (Internal Scalar : External User). 516 UserList ExternalUses; 517 518 /// A list of instructions to ignore while sinking 519 /// memory instructions. This map must be reset between runs of getCost. 520 ValueSet MemBarrierIgnoreList; 521 522 /// Holds all of the instructions that we gathered. 523 SetVector<Instruction *> GatherSeq; 524 /// A list of blocks that we are going to CSE. 525 SetVector<BasicBlock *> CSEBlocks; 526 527 /// Numbers instructions in different blocks. 528 DenseMap<BasicBlock *, BlockNumbering> BlocksNumbers; 529 530 /// Reduction operators. 531 ValueSet *RdxOps; 532 533 // Analysis and block reference. 534 Function *F; 535 ScalarEvolution *SE; 536 DataLayout *DL; 537 TargetTransformInfo *TTI; 538 AliasAnalysis *AA; 539 LoopInfo *LI; 540 DominatorTree *DT; 541 /// Instruction builder to construct the vectorized tree. 542 IRBuilder<> Builder; 543 }; 544 545 void BoUpSLP::buildTree(ArrayRef<Value *> Roots, ValueSet *Rdx) { 546 deleteTree(); 547 RdxOps = Rdx; 548 if (!getSameType(Roots)) 549 return; 550 buildTree_rec(Roots, 0); 551 552 // Collect the values that we need to extract from the tree. 553 for (int EIdx = 0, EE = VectorizableTree.size(); EIdx < EE; ++EIdx) { 554 TreeEntry *Entry = &VectorizableTree[EIdx]; 555 556 // For each lane: 557 for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) { 558 Value *Scalar = Entry->Scalars[Lane]; 559 560 // No need to handle users of gathered values. 561 if (Entry->NeedToGather) 562 continue; 563 564 for (Value::use_iterator User = Scalar->use_begin(), 565 UE = Scalar->use_end(); User != UE; ++User) { 566 DEBUG(dbgs() << "SLP: Checking user:" << **User << ".\n"); 567 568 // Skip in-tree scalars that become vectors. 569 if (ScalarToTreeEntry.count(*User)) { 570 DEBUG(dbgs() << "SLP: \tInternal user will be removed:" << 571 **User << ".\n"); 572 int Idx = ScalarToTreeEntry[*User]; (void) Idx; 573 assert(!VectorizableTree[Idx].NeedToGather && "Bad state"); 574 continue; 575 } 576 Instruction *UserInst = dyn_cast<Instruction>(*User); 577 if (!UserInst) 578 continue; 579 580 // Ignore uses that are part of the reduction. 581 if (Rdx && std::find(Rdx->begin(), Rdx->end(), UserInst) != Rdx->end()) 582 continue; 583 584 DEBUG(dbgs() << "SLP: Need to extract:" << **User << " from lane " << 585 Lane << " from " << *Scalar << ".\n"); 586 ExternalUses.push_back(ExternalUser(Scalar, *User, Lane)); 587 } 588 } 589 } 590 } 591 592 593 void BoUpSLP::buildTree_rec(ArrayRef<Value *> VL, unsigned Depth) { 594 bool SameTy = getSameType(VL); (void)SameTy; 595 assert(SameTy && "Invalid types!"); 596 597 if (Depth == RecursionMaxDepth) { 598 DEBUG(dbgs() << "SLP: Gathering due to max recursion depth.\n"); 599 newTreeEntry(VL, false); 600 return; 601 } 602 603 // Don't handle vectors. 604 if (VL[0]->getType()->isVectorTy()) { 605 DEBUG(dbgs() << "SLP: Gathering due to vector type.\n"); 606 newTreeEntry(VL, false); 607 return; 608 } 609 610 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0])) 611 if (SI->getValueOperand()->getType()->isVectorTy()) { 612 DEBUG(dbgs() << "SLP: Gathering due to store vector type.\n"); 613 newTreeEntry(VL, false); 614 return; 615 } 616 617 // If all of the operands are identical or constant we have a simple solution. 618 if (allConstant(VL) || isSplat(VL) || !getSameBlock(VL) || 619 !getSameOpcode(VL)) { 620 DEBUG(dbgs() << "SLP: Gathering due to C,S,B,O. \n"); 621 newTreeEntry(VL, false); 622 return; 623 } 624 625 // We now know that this is a vector of instructions of the same type from 626 // the same block. 627 628 // Check if this is a duplicate of another entry. 629 if (ScalarToTreeEntry.count(VL[0])) { 630 int Idx = ScalarToTreeEntry[VL[0]]; 631 TreeEntry *E = &VectorizableTree[Idx]; 632 for (unsigned i = 0, e = VL.size(); i != e; ++i) { 633 DEBUG(dbgs() << "SLP: \tChecking bundle: " << *VL[i] << ".\n"); 634 if (E->Scalars[i] != VL[i]) { 635 DEBUG(dbgs() << "SLP: Gathering due to partial overlap.\n"); 636 newTreeEntry(VL, false); 637 return; 638 } 639 } 640 DEBUG(dbgs() << "SLP: Perfect diamond merge at " << *VL[0] << ".\n"); 641 return; 642 } 643 644 // Check that none of the instructions in the bundle are already in the tree. 645 for (unsigned i = 0, e = VL.size(); i != e; ++i) { 646 if (ScalarToTreeEntry.count(VL[i])) { 647 DEBUG(dbgs() << "SLP: The instruction (" << *VL[i] << 648 ") is already in tree.\n"); 649 newTreeEntry(VL, false); 650 return; 651 } 652 } 653 654 // If any of the scalars appears in the table OR it is marked as a value that 655 // needs to stat scalar then we need to gather the scalars. 656 for (unsigned i = 0, e = VL.size(); i != e; ++i) { 657 if (ScalarToTreeEntry.count(VL[i]) || MustGather.count(VL[i])) { 658 DEBUG(dbgs() << "SLP: Gathering due to gathered scalar. \n"); 659 newTreeEntry(VL, false); 660 return; 661 } 662 } 663 664 // Check that all of the users of the scalars that we want to vectorize are 665 // schedulable. 666 Instruction *VL0 = cast<Instruction>(VL[0]); 667 int MyLastIndex = getLastIndex(VL); 668 BasicBlock *BB = cast<Instruction>(VL0)->getParent(); 669 670 for (unsigned i = 0, e = VL.size(); i != e; ++i) { 671 Instruction *Scalar = cast<Instruction>(VL[i]); 672 DEBUG(dbgs() << "SLP: Checking users of " << *Scalar << ". \n"); 673 for (Value::use_iterator U = Scalar->use_begin(), UE = Scalar->use_end(); 674 U != UE; ++U) { 675 DEBUG(dbgs() << "SLP: \tUser " << **U << ". \n"); 676 Instruction *User = dyn_cast<Instruction>(*U); 677 if (!User) { 678 DEBUG(dbgs() << "SLP: Gathering due unknown user. \n"); 679 newTreeEntry(VL, false); 680 return; 681 } 682 683 // We don't care if the user is in a different basic block. 684 BasicBlock *UserBlock = User->getParent(); 685 if (UserBlock != BB) { 686 DEBUG(dbgs() << "SLP: User from a different basic block " 687 << *User << ". \n"); 688 continue; 689 } 690 691 // If this is a PHINode within this basic block then we can place the 692 // extract wherever we want. 693 if (isa<PHINode>(*User)) { 694 DEBUG(dbgs() << "SLP: \tWe can schedule PHIs:" << *User << ". \n"); 695 continue; 696 } 697 698 // Check if this is a safe in-tree user. 699 if (ScalarToTreeEntry.count(User)) { 700 int Idx = ScalarToTreeEntry[User]; 701 int VecLocation = VectorizableTree[Idx].LastScalarIndex; 702 if (VecLocation <= MyLastIndex) { 703 DEBUG(dbgs() << "SLP: Gathering due to unschedulable vector. \n"); 704 newTreeEntry(VL, false); 705 return; 706 } 707 DEBUG(dbgs() << "SLP: In-tree user (" << *User << ") at #" << 708 VecLocation << " vector value (" << *Scalar << ") at #" 709 << MyLastIndex << ".\n"); 710 continue; 711 } 712 713 // This user is part of the reduction. 714 if (RdxOps && RdxOps->count(User)) 715 continue; 716 717 // Make sure that we can schedule this unknown user. 718 BlockNumbering &BN = BlocksNumbers[BB]; 719 int UserIndex = BN.getIndex(User); 720 if (UserIndex < MyLastIndex) { 721 722 DEBUG(dbgs() << "SLP: Can't schedule extractelement for " 723 << *User << ". \n"); 724 newTreeEntry(VL, false); 725 return; 726 } 727 } 728 } 729 730 // Check that every instructions appears once in this bundle. 731 for (unsigned i = 0, e = VL.size(); i < e; ++i) 732 for (unsigned j = i+1; j < e; ++j) 733 if (VL[i] == VL[j]) { 734 DEBUG(dbgs() << "SLP: Scalar used twice in bundle.\n"); 735 newTreeEntry(VL, false); 736 return; 737 } 738 739 // Check that instructions in this bundle don't reference other instructions. 740 // The runtime of this check is O(N * N-1 * uses(N)) and a typical N is 4. 741 for (unsigned i = 0, e = VL.size(); i < e; ++i) { 742 for (Value::use_iterator U = VL[i]->use_begin(), UE = VL[i]->use_end(); 743 U != UE; ++U) { 744 for (unsigned j = 0; j < e; ++j) { 745 if (i != j && *U == VL[j]) { 746 DEBUG(dbgs() << "SLP: Intra-bundle dependencies!" << **U << ". \n"); 747 newTreeEntry(VL, false); 748 return; 749 } 750 } 751 } 752 } 753 754 DEBUG(dbgs() << "SLP: We are able to schedule this bundle.\n"); 755 756 unsigned Opcode = getSameOpcode(VL); 757 758 // Check if it is safe to sink the loads or the stores. 759 if (Opcode == Instruction::Load || Opcode == Instruction::Store) { 760 Instruction *Last = getLastInstruction(VL); 761 762 for (unsigned i = 0, e = VL.size(); i < e; ++i) { 763 if (VL[i] == Last) 764 continue; 765 Value *Barrier = getSinkBarrier(cast<Instruction>(VL[i]), Last); 766 if (Barrier) { 767 DEBUG(dbgs() << "SLP: Can't sink " << *VL[i] << "\n down to " << *Last 768 << "\n because of " << *Barrier << ". Gathering.\n"); 769 newTreeEntry(VL, false); 770 return; 771 } 772 } 773 } 774 775 switch (Opcode) { 776 case Instruction::PHI: { 777 PHINode *PH = dyn_cast<PHINode>(VL0); 778 779 // Check for terminator values (e.g. invoke). 780 for (unsigned j = 0; j < VL.size(); ++j) 781 for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) { 782 TerminatorInst *Term = dyn_cast<TerminatorInst>( 783 cast<PHINode>(VL[j])->getIncomingValueForBlock(PH->getIncomingBlock(i))); 784 if (Term) { 785 DEBUG(dbgs() << "SLP: Need to swizzle PHINodes (TerminatorInst use).\n"); 786 newTreeEntry(VL, false); 787 return; 788 } 789 } 790 791 newTreeEntry(VL, true); 792 DEBUG(dbgs() << "SLP: added a vector of PHINodes.\n"); 793 794 for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) { 795 ValueList Operands; 796 // Prepare the operand vector. 797 for (unsigned j = 0; j < VL.size(); ++j) 798 Operands.push_back(cast<PHINode>(VL[j])->getIncomingValueForBlock( 799 PH->getIncomingBlock(i))); 800 801 buildTree_rec(Operands, Depth + 1); 802 } 803 return; 804 } 805 case Instruction::ExtractElement: { 806 bool Reuse = CanReuseExtract(VL); 807 if (Reuse) { 808 DEBUG(dbgs() << "SLP: Reusing extract sequence.\n"); 809 } 810 newTreeEntry(VL, Reuse); 811 return; 812 } 813 case Instruction::Load: { 814 // Check if the loads are consecutive or of we need to swizzle them. 815 for (unsigned i = 0, e = VL.size() - 1; i < e; ++i) { 816 LoadInst *L = cast<LoadInst>(VL[i]); 817 if (!L->isSimple() || !isConsecutiveAccess(VL[i], VL[i + 1])) { 818 newTreeEntry(VL, false); 819 DEBUG(dbgs() << "SLP: Need to swizzle loads.\n"); 820 return; 821 } 822 } 823 newTreeEntry(VL, true); 824 DEBUG(dbgs() << "SLP: added a vector of loads.\n"); 825 return; 826 } 827 case Instruction::ZExt: 828 case Instruction::SExt: 829 case Instruction::FPToUI: 830 case Instruction::FPToSI: 831 case Instruction::FPExt: 832 case Instruction::PtrToInt: 833 case Instruction::IntToPtr: 834 case Instruction::SIToFP: 835 case Instruction::UIToFP: 836 case Instruction::Trunc: 837 case Instruction::FPTrunc: 838 case Instruction::BitCast: { 839 Type *SrcTy = VL0->getOperand(0)->getType(); 840 for (unsigned i = 0; i < VL.size(); ++i) { 841 Type *Ty = cast<Instruction>(VL[i])->getOperand(0)->getType(); 842 if (Ty != SrcTy || Ty->isAggregateType() || Ty->isVectorTy()) { 843 newTreeEntry(VL, false); 844 DEBUG(dbgs() << "SLP: Gathering casts with different src types.\n"); 845 return; 846 } 847 } 848 newTreeEntry(VL, true); 849 DEBUG(dbgs() << "SLP: added a vector of casts.\n"); 850 851 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) { 852 ValueList Operands; 853 // Prepare the operand vector. 854 for (unsigned j = 0; j < VL.size(); ++j) 855 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i)); 856 857 buildTree_rec(Operands, Depth+1); 858 } 859 return; 860 } 861 case Instruction::ICmp: 862 case Instruction::FCmp: { 863 // Check that all of the compares have the same predicate. 864 CmpInst::Predicate P0 = dyn_cast<CmpInst>(VL0)->getPredicate(); 865 Type *ComparedTy = cast<Instruction>(VL[0])->getOperand(0)->getType(); 866 for (unsigned i = 1, e = VL.size(); i < e; ++i) { 867 CmpInst *Cmp = cast<CmpInst>(VL[i]); 868 if (Cmp->getPredicate() != P0 || 869 Cmp->getOperand(0)->getType() != ComparedTy) { 870 newTreeEntry(VL, false); 871 DEBUG(dbgs() << "SLP: Gathering cmp with different predicate.\n"); 872 return; 873 } 874 } 875 876 newTreeEntry(VL, true); 877 DEBUG(dbgs() << "SLP: added a vector of compares.\n"); 878 879 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) { 880 ValueList Operands; 881 // Prepare the operand vector. 882 for (unsigned j = 0; j < VL.size(); ++j) 883 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i)); 884 885 buildTree_rec(Operands, Depth+1); 886 } 887 return; 888 } 889 case Instruction::Select: 890 case Instruction::Add: 891 case Instruction::FAdd: 892 case Instruction::Sub: 893 case Instruction::FSub: 894 case Instruction::Mul: 895 case Instruction::FMul: 896 case Instruction::UDiv: 897 case Instruction::SDiv: 898 case Instruction::FDiv: 899 case Instruction::URem: 900 case Instruction::SRem: 901 case Instruction::FRem: 902 case Instruction::Shl: 903 case Instruction::LShr: 904 case Instruction::AShr: 905 case Instruction::And: 906 case Instruction::Or: 907 case Instruction::Xor: { 908 newTreeEntry(VL, true); 909 DEBUG(dbgs() << "SLP: added a vector of bin op.\n"); 910 911 // Sort operands of the instructions so that each side is more likely to 912 // have the same opcode. 913 if (isa<BinaryOperator>(VL0) && VL0->isCommutative()) { 914 ValueList Left, Right; 915 reorderInputsAccordingToOpcode(VL, Left, Right); 916 buildTree_rec(Left, Depth + 1); 917 buildTree_rec(Right, Depth + 1); 918 return; 919 } 920 921 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) { 922 ValueList Operands; 923 // Prepare the operand vector. 924 for (unsigned j = 0; j < VL.size(); ++j) 925 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i)); 926 927 buildTree_rec(Operands, Depth+1); 928 } 929 return; 930 } 931 case Instruction::Store: { 932 // Check if the stores are consecutive or of we need to swizzle them. 933 for (unsigned i = 0, e = VL.size() - 1; i < e; ++i) 934 if (!isConsecutiveAccess(VL[i], VL[i + 1])) { 935 newTreeEntry(VL, false); 936 DEBUG(dbgs() << "SLP: Non-consecutive store.\n"); 937 return; 938 } 939 940 newTreeEntry(VL, true); 941 DEBUG(dbgs() << "SLP: added a vector of stores.\n"); 942 943 ValueList Operands; 944 for (unsigned j = 0; j < VL.size(); ++j) 945 Operands.push_back(cast<Instruction>(VL[j])->getOperand(0)); 946 947 // We can ignore these values because we are sinking them down. 948 MemBarrierIgnoreList.insert(VL.begin(), VL.end()); 949 buildTree_rec(Operands, Depth + 1); 950 return; 951 } 952 default: 953 newTreeEntry(VL, false); 954 DEBUG(dbgs() << "SLP: Gathering unknown instruction.\n"); 955 return; 956 } 957 } 958 959 int BoUpSLP::getEntryCost(TreeEntry *E) { 960 ArrayRef<Value*> VL = E->Scalars; 961 962 Type *ScalarTy = VL[0]->getType(); 963 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0])) 964 ScalarTy = SI->getValueOperand()->getType(); 965 VectorType *VecTy = VectorType::get(ScalarTy, VL.size()); 966 967 if (E->NeedToGather) { 968 if (allConstant(VL)) 969 return 0; 970 if (isSplat(VL)) { 971 return TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy, 0); 972 } 973 return getGatherCost(E->Scalars); 974 } 975 976 assert(getSameOpcode(VL) && getSameType(VL) && getSameBlock(VL) && 977 "Invalid VL"); 978 Instruction *VL0 = cast<Instruction>(VL[0]); 979 unsigned Opcode = VL0->getOpcode(); 980 switch (Opcode) { 981 case Instruction::PHI: { 982 return 0; 983 } 984 case Instruction::ExtractElement: { 985 if (CanReuseExtract(VL)) 986 return 0; 987 return getGatherCost(VecTy); 988 } 989 case Instruction::ZExt: 990 case Instruction::SExt: 991 case Instruction::FPToUI: 992 case Instruction::FPToSI: 993 case Instruction::FPExt: 994 case Instruction::PtrToInt: 995 case Instruction::IntToPtr: 996 case Instruction::SIToFP: 997 case Instruction::UIToFP: 998 case Instruction::Trunc: 999 case Instruction::FPTrunc: 1000 case Instruction::BitCast: { 1001 Type *SrcTy = VL0->getOperand(0)->getType(); 1002 1003 // Calculate the cost of this instruction. 1004 int ScalarCost = VL.size() * TTI->getCastInstrCost(VL0->getOpcode(), 1005 VL0->getType(), SrcTy); 1006 1007 VectorType *SrcVecTy = VectorType::get(SrcTy, VL.size()); 1008 int VecCost = TTI->getCastInstrCost(VL0->getOpcode(), VecTy, SrcVecTy); 1009 return VecCost - ScalarCost; 1010 } 1011 case Instruction::FCmp: 1012 case Instruction::ICmp: 1013 case Instruction::Select: 1014 case Instruction::Add: 1015 case Instruction::FAdd: 1016 case Instruction::Sub: 1017 case Instruction::FSub: 1018 case Instruction::Mul: 1019 case Instruction::FMul: 1020 case Instruction::UDiv: 1021 case Instruction::SDiv: 1022 case Instruction::FDiv: 1023 case Instruction::URem: 1024 case Instruction::SRem: 1025 case Instruction::FRem: 1026 case Instruction::Shl: 1027 case Instruction::LShr: 1028 case Instruction::AShr: 1029 case Instruction::And: 1030 case Instruction::Or: 1031 case Instruction::Xor: { 1032 // Calculate the cost of this instruction. 1033 int ScalarCost = 0; 1034 int VecCost = 0; 1035 if (Opcode == Instruction::FCmp || Opcode == Instruction::ICmp || 1036 Opcode == Instruction::Select) { 1037 VectorType *MaskTy = VectorType::get(Builder.getInt1Ty(), VL.size()); 1038 ScalarCost = VecTy->getNumElements() * 1039 TTI->getCmpSelInstrCost(Opcode, ScalarTy, Builder.getInt1Ty()); 1040 VecCost = TTI->getCmpSelInstrCost(Opcode, VecTy, MaskTy); 1041 } else { 1042 // Certain instructions can be cheaper to vectorize if they have a 1043 // constant second vector operand. 1044 TargetTransformInfo::OperandValueKind Op1VK = 1045 TargetTransformInfo::OK_AnyValue; 1046 TargetTransformInfo::OperandValueKind Op2VK = 1047 TargetTransformInfo::OK_UniformConstantValue; 1048 1049 // If all operands are exactly the same ConstantInt then set the 1050 // operand kind to OK_UniformConstantValue. 1051 // If instead not all operands are constants, then set the operand kind 1052 // to OK_AnyValue. If all operands are constants but not the same, 1053 // then set the operand kind to OK_NonUniformConstantValue. 1054 ConstantInt *CInt = NULL; 1055 for (unsigned i = 0; i < VL.size(); ++i) { 1056 const Instruction *I = cast<Instruction>(VL[i]); 1057 if (!isa<ConstantInt>(I->getOperand(1))) { 1058 Op2VK = TargetTransformInfo::OK_AnyValue; 1059 break; 1060 } 1061 if (i == 0) { 1062 CInt = cast<ConstantInt>(I->getOperand(1)); 1063 continue; 1064 } 1065 if (Op2VK == TargetTransformInfo::OK_UniformConstantValue && 1066 CInt != cast<ConstantInt>(I->getOperand(1))) 1067 Op2VK = TargetTransformInfo::OK_NonUniformConstantValue; 1068 } 1069 1070 ScalarCost = 1071 VecTy->getNumElements() * 1072 TTI->getArithmeticInstrCost(Opcode, ScalarTy, Op1VK, Op2VK); 1073 VecCost = TTI->getArithmeticInstrCost(Opcode, VecTy, Op1VK, Op2VK); 1074 } 1075 return VecCost - ScalarCost; 1076 } 1077 case Instruction::Load: { 1078 // Cost of wide load - cost of scalar loads. 1079 int ScalarLdCost = VecTy->getNumElements() * 1080 TTI->getMemoryOpCost(Instruction::Load, ScalarTy, 1, 0); 1081 int VecLdCost = TTI->getMemoryOpCost(Instruction::Load, VecTy, 1, 0); 1082 return VecLdCost - ScalarLdCost; 1083 } 1084 case Instruction::Store: { 1085 // We know that we can merge the stores. Calculate the cost. 1086 int ScalarStCost = VecTy->getNumElements() * 1087 TTI->getMemoryOpCost(Instruction::Store, ScalarTy, 1, 0); 1088 int VecStCost = TTI->getMemoryOpCost(Instruction::Store, VecTy, 1, 0); 1089 return VecStCost - ScalarStCost; 1090 } 1091 default: 1092 llvm_unreachable("Unknown instruction"); 1093 } 1094 } 1095 1096 bool BoUpSLP::isFullyVectorizableTinyTree() { 1097 DEBUG(dbgs() << "SLP: Check whether the tree with height " << 1098 VectorizableTree.size() << " is fully vectorizable .\n"); 1099 1100 // We only handle trees of height 2. 1101 if (VectorizableTree.size() != 2) 1102 return false; 1103 1104 // Gathering cost would be too much for tiny trees. 1105 if (VectorizableTree[0].NeedToGather || VectorizableTree[1].NeedToGather) 1106 return false; 1107 1108 return true; 1109 } 1110 1111 int BoUpSLP::getTreeCost() { 1112 int Cost = 0; 1113 DEBUG(dbgs() << "SLP: Calculating cost for tree of size " << 1114 VectorizableTree.size() << ".\n"); 1115 1116 // We only vectorize tiny trees if it is fully vectorizable. 1117 if (VectorizableTree.size() < 3 && !isFullyVectorizableTinyTree()) { 1118 if (!VectorizableTree.size()) { 1119 assert(!ExternalUses.size() && "We should not have any external users"); 1120 } 1121 return INT_MAX; 1122 } 1123 1124 unsigned BundleWidth = VectorizableTree[0].Scalars.size(); 1125 1126 for (unsigned i = 0, e = VectorizableTree.size(); i != e; ++i) { 1127 int C = getEntryCost(&VectorizableTree[i]); 1128 DEBUG(dbgs() << "SLP: Adding cost " << C << " for bundle that starts with " 1129 << *VectorizableTree[i].Scalars[0] << " .\n"); 1130 Cost += C; 1131 } 1132 1133 SmallSet<Value *, 16> ExtractCostCalculated; 1134 int ExtractCost = 0; 1135 for (UserList::iterator I = ExternalUses.begin(), E = ExternalUses.end(); 1136 I != E; ++I) { 1137 // We only add extract cost once for the same scalar. 1138 if (!ExtractCostCalculated.insert(I->Scalar)) 1139 continue; 1140 1141 VectorType *VecTy = VectorType::get(I->Scalar->getType(), BundleWidth); 1142 ExtractCost += TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, 1143 I->Lane); 1144 } 1145 1146 DEBUG(dbgs() << "SLP: Total Cost " << Cost + ExtractCost<< ".\n"); 1147 return Cost + ExtractCost; 1148 } 1149 1150 int BoUpSLP::getGatherCost(Type *Ty) { 1151 int Cost = 0; 1152 for (unsigned i = 0, e = cast<VectorType>(Ty)->getNumElements(); i < e; ++i) 1153 Cost += TTI->getVectorInstrCost(Instruction::InsertElement, Ty, i); 1154 return Cost; 1155 } 1156 1157 int BoUpSLP::getGatherCost(ArrayRef<Value *> VL) { 1158 // Find the type of the operands in VL. 1159 Type *ScalarTy = VL[0]->getType(); 1160 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0])) 1161 ScalarTy = SI->getValueOperand()->getType(); 1162 VectorType *VecTy = VectorType::get(ScalarTy, VL.size()); 1163 // Find the cost of inserting/extracting values from the vector. 1164 return getGatherCost(VecTy); 1165 } 1166 1167 AliasAnalysis::Location BoUpSLP::getLocation(Instruction *I) { 1168 if (StoreInst *SI = dyn_cast<StoreInst>(I)) 1169 return AA->getLocation(SI); 1170 if (LoadInst *LI = dyn_cast<LoadInst>(I)) 1171 return AA->getLocation(LI); 1172 return AliasAnalysis::Location(); 1173 } 1174 1175 Value *BoUpSLP::getPointerOperand(Value *I) { 1176 if (LoadInst *LI = dyn_cast<LoadInst>(I)) 1177 return LI->getPointerOperand(); 1178 if (StoreInst *SI = dyn_cast<StoreInst>(I)) 1179 return SI->getPointerOperand(); 1180 return 0; 1181 } 1182 1183 unsigned BoUpSLP::getAddressSpaceOperand(Value *I) { 1184 if (LoadInst *L = dyn_cast<LoadInst>(I)) 1185 return L->getPointerAddressSpace(); 1186 if (StoreInst *S = dyn_cast<StoreInst>(I)) 1187 return S->getPointerAddressSpace(); 1188 return -1; 1189 } 1190 1191 bool BoUpSLP::isConsecutiveAccess(Value *A, Value *B) { 1192 Value *PtrA = getPointerOperand(A); 1193 Value *PtrB = getPointerOperand(B); 1194 unsigned ASA = getAddressSpaceOperand(A); 1195 unsigned ASB = getAddressSpaceOperand(B); 1196 1197 // Check that the address spaces match and that the pointers are valid. 1198 if (!PtrA || !PtrB || (ASA != ASB)) 1199 return false; 1200 1201 // Make sure that A and B are different pointers of the same type. 1202 if (PtrA == PtrB || PtrA->getType() != PtrB->getType()) 1203 return false; 1204 1205 unsigned PtrBitWidth = DL->getPointerSizeInBits(ASA); 1206 Type *Ty = cast<PointerType>(PtrA->getType())->getElementType(); 1207 APInt Size(PtrBitWidth, DL->getTypeStoreSize(Ty)); 1208 1209 APInt OffsetA(PtrBitWidth, 0), OffsetB(PtrBitWidth, 0); 1210 PtrA = PtrA->stripAndAccumulateInBoundsConstantOffsets(*DL, OffsetA); 1211 PtrB = PtrB->stripAndAccumulateInBoundsConstantOffsets(*DL, OffsetB); 1212 1213 APInt OffsetDelta = OffsetB - OffsetA; 1214 1215 // Check if they are based on the same pointer. That makes the offsets 1216 // sufficient. 1217 if (PtrA == PtrB) 1218 return OffsetDelta == Size; 1219 1220 // Compute the necessary base pointer delta to have the necessary final delta 1221 // equal to the size. 1222 APInt BaseDelta = Size - OffsetDelta; 1223 1224 // Otherwise compute the distance with SCEV between the base pointers. 1225 const SCEV *PtrSCEVA = SE->getSCEV(PtrA); 1226 const SCEV *PtrSCEVB = SE->getSCEV(PtrB); 1227 const SCEV *C = SE->getConstant(BaseDelta); 1228 const SCEV *X = SE->getAddExpr(PtrSCEVA, C); 1229 return X == PtrSCEVB; 1230 } 1231 1232 Value *BoUpSLP::getSinkBarrier(Instruction *Src, Instruction *Dst) { 1233 assert(Src->getParent() == Dst->getParent() && "Not the same BB"); 1234 BasicBlock::iterator I = Src, E = Dst; 1235 /// Scan all of the instruction from SRC to DST and check if 1236 /// the source may alias. 1237 for (++I; I != E; ++I) { 1238 // Ignore store instructions that are marked as 'ignore'. 1239 if (MemBarrierIgnoreList.count(I)) 1240 continue; 1241 if (Src->mayWriteToMemory()) /* Write */ { 1242 if (!I->mayReadOrWriteMemory()) 1243 continue; 1244 } else /* Read */ { 1245 if (!I->mayWriteToMemory()) 1246 continue; 1247 } 1248 AliasAnalysis::Location A = getLocation(&*I); 1249 AliasAnalysis::Location B = getLocation(Src); 1250 1251 if (!A.Ptr || !B.Ptr || AA->alias(A, B)) 1252 return I; 1253 } 1254 return 0; 1255 } 1256 1257 int BoUpSLP::getLastIndex(ArrayRef<Value *> VL) { 1258 BasicBlock *BB = cast<Instruction>(VL[0])->getParent(); 1259 assert(BB == getSameBlock(VL) && BlocksNumbers.count(BB) && "Invalid block"); 1260 BlockNumbering &BN = BlocksNumbers[BB]; 1261 1262 int MaxIdx = BN.getIndex(BB->getFirstNonPHI()); 1263 for (unsigned i = 0, e = VL.size(); i < e; ++i) 1264 MaxIdx = std::max(MaxIdx, BN.getIndex(cast<Instruction>(VL[i]))); 1265 return MaxIdx; 1266 } 1267 1268 Instruction *BoUpSLP::getLastInstruction(ArrayRef<Value *> VL) { 1269 BasicBlock *BB = cast<Instruction>(VL[0])->getParent(); 1270 assert(BB == getSameBlock(VL) && BlocksNumbers.count(BB) && "Invalid block"); 1271 BlockNumbering &BN = BlocksNumbers[BB]; 1272 1273 int MaxIdx = BN.getIndex(cast<Instruction>(VL[0])); 1274 for (unsigned i = 1, e = VL.size(); i < e; ++i) 1275 MaxIdx = std::max(MaxIdx, BN.getIndex(cast<Instruction>(VL[i]))); 1276 Instruction *I = BN.getInstruction(MaxIdx); 1277 assert(I && "bad location"); 1278 return I; 1279 } 1280 1281 void BoUpSLP::setInsertPointAfterBundle(ArrayRef<Value *> VL) { 1282 Instruction *VL0 = cast<Instruction>(VL[0]); 1283 Instruction *LastInst = getLastInstruction(VL); 1284 BasicBlock::iterator NextInst = LastInst; 1285 ++NextInst; 1286 Builder.SetInsertPoint(VL0->getParent(), NextInst); 1287 Builder.SetCurrentDebugLocation(VL0->getDebugLoc()); 1288 } 1289 1290 Value *BoUpSLP::Gather(ArrayRef<Value *> VL, VectorType *Ty) { 1291 Value *Vec = UndefValue::get(Ty); 1292 // Generate the 'InsertElement' instruction. 1293 for (unsigned i = 0; i < Ty->getNumElements(); ++i) { 1294 Vec = Builder.CreateInsertElement(Vec, VL[i], Builder.getInt32(i)); 1295 if (Instruction *Insrt = dyn_cast<Instruction>(Vec)) { 1296 GatherSeq.insert(Insrt); 1297 CSEBlocks.insert(Insrt->getParent()); 1298 1299 // Add to our 'need-to-extract' list. 1300 if (ScalarToTreeEntry.count(VL[i])) { 1301 int Idx = ScalarToTreeEntry[VL[i]]; 1302 TreeEntry *E = &VectorizableTree[Idx]; 1303 // Find which lane we need to extract. 1304 int FoundLane = -1; 1305 for (unsigned Lane = 0, LE = VL.size(); Lane != LE; ++Lane) { 1306 // Is this the lane of the scalar that we are looking for ? 1307 if (E->Scalars[Lane] == VL[i]) { 1308 FoundLane = Lane; 1309 break; 1310 } 1311 } 1312 assert(FoundLane >= 0 && "Could not find the correct lane"); 1313 ExternalUses.push_back(ExternalUser(VL[i], Insrt, FoundLane)); 1314 } 1315 } 1316 } 1317 1318 return Vec; 1319 } 1320 1321 Value *BoUpSLP::alreadyVectorized(ArrayRef<Value *> VL) const { 1322 SmallDenseMap<Value*, int>::const_iterator Entry 1323 = ScalarToTreeEntry.find(VL[0]); 1324 if (Entry != ScalarToTreeEntry.end()) { 1325 int Idx = Entry->second; 1326 const TreeEntry *En = &VectorizableTree[Idx]; 1327 if (En->isSame(VL) && En->VectorizedValue) 1328 return En->VectorizedValue; 1329 } 1330 return 0; 1331 } 1332 1333 Value *BoUpSLP::vectorizeTree(ArrayRef<Value *> VL) { 1334 if (ScalarToTreeEntry.count(VL[0])) { 1335 int Idx = ScalarToTreeEntry[VL[0]]; 1336 TreeEntry *E = &VectorizableTree[Idx]; 1337 if (E->isSame(VL)) 1338 return vectorizeTree(E); 1339 } 1340 1341 Type *ScalarTy = VL[0]->getType(); 1342 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0])) 1343 ScalarTy = SI->getValueOperand()->getType(); 1344 VectorType *VecTy = VectorType::get(ScalarTy, VL.size()); 1345 1346 return Gather(VL, VecTy); 1347 } 1348 1349 Value *BoUpSLP::vectorizeTree(TreeEntry *E) { 1350 IRBuilder<>::InsertPointGuard Guard(Builder); 1351 1352 if (E->VectorizedValue) { 1353 DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n"); 1354 return E->VectorizedValue; 1355 } 1356 1357 Instruction *VL0 = cast<Instruction>(E->Scalars[0]); 1358 Type *ScalarTy = VL0->getType(); 1359 if (StoreInst *SI = dyn_cast<StoreInst>(VL0)) 1360 ScalarTy = SI->getValueOperand()->getType(); 1361 VectorType *VecTy = VectorType::get(ScalarTy, E->Scalars.size()); 1362 1363 if (E->NeedToGather) { 1364 setInsertPointAfterBundle(E->Scalars); 1365 return Gather(E->Scalars, VecTy); 1366 } 1367 1368 unsigned Opcode = VL0->getOpcode(); 1369 assert(Opcode == getSameOpcode(E->Scalars) && "Invalid opcode"); 1370 1371 switch (Opcode) { 1372 case Instruction::PHI: { 1373 PHINode *PH = dyn_cast<PHINode>(VL0); 1374 Builder.SetInsertPoint(PH->getParent()->getFirstNonPHI()); 1375 Builder.SetCurrentDebugLocation(PH->getDebugLoc()); 1376 PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues()); 1377 E->VectorizedValue = NewPhi; 1378 1379 // PHINodes may have multiple entries from the same block. We want to 1380 // visit every block once. 1381 SmallSet<BasicBlock*, 4> VisitedBBs; 1382 1383 for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) { 1384 ValueList Operands; 1385 BasicBlock *IBB = PH->getIncomingBlock(i); 1386 1387 if (!VisitedBBs.insert(IBB)) { 1388 NewPhi->addIncoming(NewPhi->getIncomingValueForBlock(IBB), IBB); 1389 continue; 1390 } 1391 1392 // Prepare the operand vector. 1393 for (unsigned j = 0; j < E->Scalars.size(); ++j) 1394 Operands.push_back(cast<PHINode>(E->Scalars[j])-> 1395 getIncomingValueForBlock(IBB)); 1396 1397 Builder.SetInsertPoint(IBB->getTerminator()); 1398 Builder.SetCurrentDebugLocation(PH->getDebugLoc()); 1399 Value *Vec = vectorizeTree(Operands); 1400 NewPhi->addIncoming(Vec, IBB); 1401 } 1402 1403 assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() && 1404 "Invalid number of incoming values"); 1405 return NewPhi; 1406 } 1407 1408 case Instruction::ExtractElement: { 1409 if (CanReuseExtract(E->Scalars)) { 1410 Value *V = VL0->getOperand(0); 1411 E->VectorizedValue = V; 1412 return V; 1413 } 1414 return Gather(E->Scalars, VecTy); 1415 } 1416 case Instruction::ZExt: 1417 case Instruction::SExt: 1418 case Instruction::FPToUI: 1419 case Instruction::FPToSI: 1420 case Instruction::FPExt: 1421 case Instruction::PtrToInt: 1422 case Instruction::IntToPtr: 1423 case Instruction::SIToFP: 1424 case Instruction::UIToFP: 1425 case Instruction::Trunc: 1426 case Instruction::FPTrunc: 1427 case Instruction::BitCast: { 1428 ValueList INVL; 1429 for (int i = 0, e = E->Scalars.size(); i < e; ++i) 1430 INVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0)); 1431 1432 setInsertPointAfterBundle(E->Scalars); 1433 1434 Value *InVec = vectorizeTree(INVL); 1435 1436 if (Value *V = alreadyVectorized(E->Scalars)) 1437 return V; 1438 1439 CastInst *CI = dyn_cast<CastInst>(VL0); 1440 Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy); 1441 E->VectorizedValue = V; 1442 return V; 1443 } 1444 case Instruction::FCmp: 1445 case Instruction::ICmp: { 1446 ValueList LHSV, RHSV; 1447 for (int i = 0, e = E->Scalars.size(); i < e; ++i) { 1448 LHSV.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0)); 1449 RHSV.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1)); 1450 } 1451 1452 setInsertPointAfterBundle(E->Scalars); 1453 1454 Value *L = vectorizeTree(LHSV); 1455 Value *R = vectorizeTree(RHSV); 1456 1457 if (Value *V = alreadyVectorized(E->Scalars)) 1458 return V; 1459 1460 CmpInst::Predicate P0 = dyn_cast<CmpInst>(VL0)->getPredicate(); 1461 Value *V; 1462 if (Opcode == Instruction::FCmp) 1463 V = Builder.CreateFCmp(P0, L, R); 1464 else 1465 V = Builder.CreateICmp(P0, L, R); 1466 1467 E->VectorizedValue = V; 1468 return V; 1469 } 1470 case Instruction::Select: { 1471 ValueList TrueVec, FalseVec, CondVec; 1472 for (int i = 0, e = E->Scalars.size(); i < e; ++i) { 1473 CondVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0)); 1474 TrueVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1)); 1475 FalseVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(2)); 1476 } 1477 1478 setInsertPointAfterBundle(E->Scalars); 1479 1480 Value *Cond = vectorizeTree(CondVec); 1481 Value *True = vectorizeTree(TrueVec); 1482 Value *False = vectorizeTree(FalseVec); 1483 1484 if (Value *V = alreadyVectorized(E->Scalars)) 1485 return V; 1486 1487 Value *V = Builder.CreateSelect(Cond, True, False); 1488 E->VectorizedValue = V; 1489 return V; 1490 } 1491 case Instruction::Add: 1492 case Instruction::FAdd: 1493 case Instruction::Sub: 1494 case Instruction::FSub: 1495 case Instruction::Mul: 1496 case Instruction::FMul: 1497 case Instruction::UDiv: 1498 case Instruction::SDiv: 1499 case Instruction::FDiv: 1500 case Instruction::URem: 1501 case Instruction::SRem: 1502 case Instruction::FRem: 1503 case Instruction::Shl: 1504 case Instruction::LShr: 1505 case Instruction::AShr: 1506 case Instruction::And: 1507 case Instruction::Or: 1508 case Instruction::Xor: { 1509 ValueList LHSVL, RHSVL; 1510 if (isa<BinaryOperator>(VL0) && VL0->isCommutative()) 1511 reorderInputsAccordingToOpcode(E->Scalars, LHSVL, RHSVL); 1512 else 1513 for (int i = 0, e = E->Scalars.size(); i < e; ++i) { 1514 LHSVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0)); 1515 RHSVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1)); 1516 } 1517 1518 setInsertPointAfterBundle(E->Scalars); 1519 1520 Value *LHS = vectorizeTree(LHSVL); 1521 Value *RHS = vectorizeTree(RHSVL); 1522 1523 if (LHS == RHS && isa<Instruction>(LHS)) { 1524 assert((VL0->getOperand(0) == VL0->getOperand(1)) && "Invalid order"); 1525 } 1526 1527 if (Value *V = alreadyVectorized(E->Scalars)) 1528 return V; 1529 1530 BinaryOperator *BinOp = cast<BinaryOperator>(VL0); 1531 Value *V = Builder.CreateBinOp(BinOp->getOpcode(), LHS, RHS); 1532 E->VectorizedValue = V; 1533 1534 if (Instruction *I = dyn_cast<Instruction>(V)) 1535 return propagateMetadata(I, E->Scalars); 1536 1537 return V; 1538 } 1539 case Instruction::Load: { 1540 // Loads are inserted at the head of the tree because we don't want to 1541 // sink them all the way down past store instructions. 1542 setInsertPointAfterBundle(E->Scalars); 1543 1544 LoadInst *LI = cast<LoadInst>(VL0); 1545 unsigned AS = LI->getPointerAddressSpace(); 1546 1547 Value *VecPtr = Builder.CreateBitCast(LI->getPointerOperand(), 1548 VecTy->getPointerTo(AS)); 1549 unsigned Alignment = LI->getAlignment(); 1550 LI = Builder.CreateLoad(VecPtr); 1551 LI->setAlignment(Alignment); 1552 E->VectorizedValue = LI; 1553 return propagateMetadata(LI, E->Scalars); 1554 } 1555 case Instruction::Store: { 1556 StoreInst *SI = cast<StoreInst>(VL0); 1557 unsigned Alignment = SI->getAlignment(); 1558 unsigned AS = SI->getPointerAddressSpace(); 1559 1560 ValueList ValueOp; 1561 for (int i = 0, e = E->Scalars.size(); i < e; ++i) 1562 ValueOp.push_back(cast<StoreInst>(E->Scalars[i])->getValueOperand()); 1563 1564 setInsertPointAfterBundle(E->Scalars); 1565 1566 Value *VecValue = vectorizeTree(ValueOp); 1567 Value *VecPtr = Builder.CreateBitCast(SI->getPointerOperand(), 1568 VecTy->getPointerTo(AS)); 1569 StoreInst *S = Builder.CreateStore(VecValue, VecPtr); 1570 S->setAlignment(Alignment); 1571 E->VectorizedValue = S; 1572 return propagateMetadata(S, E->Scalars); 1573 } 1574 default: 1575 llvm_unreachable("unknown inst"); 1576 } 1577 return 0; 1578 } 1579 1580 Value *BoUpSLP::vectorizeTree() { 1581 Builder.SetInsertPoint(F->getEntryBlock().begin()); 1582 vectorizeTree(&VectorizableTree[0]); 1583 1584 DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size() << " values .\n"); 1585 1586 // Extract all of the elements with the external uses. 1587 for (UserList::iterator it = ExternalUses.begin(), e = ExternalUses.end(); 1588 it != e; ++it) { 1589 Value *Scalar = it->Scalar; 1590 llvm::User *User = it->User; 1591 1592 // Skip users that we already RAUW. This happens when one instruction 1593 // has multiple uses of the same value. 1594 if (std::find(Scalar->use_begin(), Scalar->use_end(), User) == 1595 Scalar->use_end()) 1596 continue; 1597 assert(ScalarToTreeEntry.count(Scalar) && "Invalid scalar"); 1598 1599 int Idx = ScalarToTreeEntry[Scalar]; 1600 TreeEntry *E = &VectorizableTree[Idx]; 1601 assert(!E->NeedToGather && "Extracting from a gather list"); 1602 1603 Value *Vec = E->VectorizedValue; 1604 assert(Vec && "Can't find vectorizable value"); 1605 1606 Value *Lane = Builder.getInt32(it->Lane); 1607 // Generate extracts for out-of-tree users. 1608 // Find the insertion point for the extractelement lane. 1609 if (PHINode *PN = dyn_cast<PHINode>(Vec)) { 1610 Builder.SetInsertPoint(PN->getParent()->getFirstInsertionPt()); 1611 Value *Ex = Builder.CreateExtractElement(Vec, Lane); 1612 CSEBlocks.insert(PN->getParent()); 1613 User->replaceUsesOfWith(Scalar, Ex); 1614 } else if (isa<Instruction>(Vec)){ 1615 if (PHINode *PH = dyn_cast<PHINode>(User)) { 1616 for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) { 1617 if (PH->getIncomingValue(i) == Scalar) { 1618 Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator()); 1619 Value *Ex = Builder.CreateExtractElement(Vec, Lane); 1620 CSEBlocks.insert(PH->getIncomingBlock(i)); 1621 PH->setOperand(i, Ex); 1622 } 1623 } 1624 } else { 1625 Builder.SetInsertPoint(cast<Instruction>(User)); 1626 Value *Ex = Builder.CreateExtractElement(Vec, Lane); 1627 CSEBlocks.insert(cast<Instruction>(User)->getParent()); 1628 User->replaceUsesOfWith(Scalar, Ex); 1629 } 1630 } else { 1631 Builder.SetInsertPoint(F->getEntryBlock().begin()); 1632 Value *Ex = Builder.CreateExtractElement(Vec, Lane); 1633 CSEBlocks.insert(&F->getEntryBlock()); 1634 User->replaceUsesOfWith(Scalar, Ex); 1635 } 1636 1637 DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n"); 1638 } 1639 1640 // For each vectorized value: 1641 for (int EIdx = 0, EE = VectorizableTree.size(); EIdx < EE; ++EIdx) { 1642 TreeEntry *Entry = &VectorizableTree[EIdx]; 1643 1644 // For each lane: 1645 for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) { 1646 Value *Scalar = Entry->Scalars[Lane]; 1647 1648 // No need to handle users of gathered values. 1649 if (Entry->NeedToGather) 1650 continue; 1651 1652 assert(Entry->VectorizedValue && "Can't find vectorizable value"); 1653 1654 Type *Ty = Scalar->getType(); 1655 if (!Ty->isVoidTy()) { 1656 for (Value::use_iterator User = Scalar->use_begin(), 1657 UE = Scalar->use_end(); User != UE; ++User) { 1658 DEBUG(dbgs() << "SLP: \tvalidating user:" << **User << ".\n"); 1659 1660 assert((ScalarToTreeEntry.count(*User) || 1661 // It is legal to replace the reduction users by undef. 1662 (RdxOps && RdxOps->count(*User))) && 1663 "Replacing out-of-tree value with undef"); 1664 } 1665 Value *Undef = UndefValue::get(Ty); 1666 Scalar->replaceAllUsesWith(Undef); 1667 } 1668 DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n"); 1669 cast<Instruction>(Scalar)->eraseFromParent(); 1670 } 1671 } 1672 1673 for (Function::iterator it = F->begin(), e = F->end(); it != e; ++it) { 1674 BlocksNumbers[it].forget(); 1675 } 1676 Builder.ClearInsertionPoint(); 1677 1678 return VectorizableTree[0].VectorizedValue; 1679 } 1680 1681 class DTCmp { 1682 const DominatorTree *DT; 1683 1684 public: 1685 DTCmp(const DominatorTree *DT) : DT(DT) {} 1686 bool operator()(const BasicBlock *A, const BasicBlock *B) const { 1687 return DT->properlyDominates(A, B); 1688 } 1689 }; 1690 1691 void BoUpSLP::optimizeGatherSequence() { 1692 DEBUG(dbgs() << "SLP: Optimizing " << GatherSeq.size() 1693 << " gather sequences instructions.\n"); 1694 // LICM InsertElementInst sequences. 1695 for (SetVector<Instruction *>::iterator it = GatherSeq.begin(), 1696 e = GatherSeq.end(); it != e; ++it) { 1697 InsertElementInst *Insert = dyn_cast<InsertElementInst>(*it); 1698 1699 if (!Insert) 1700 continue; 1701 1702 // Check if this block is inside a loop. 1703 Loop *L = LI->getLoopFor(Insert->getParent()); 1704 if (!L) 1705 continue; 1706 1707 // Check if it has a preheader. 1708 BasicBlock *PreHeader = L->getLoopPreheader(); 1709 if (!PreHeader) 1710 continue; 1711 1712 // If the vector or the element that we insert into it are 1713 // instructions that are defined in this basic block then we can't 1714 // hoist this instruction. 1715 Instruction *CurrVec = dyn_cast<Instruction>(Insert->getOperand(0)); 1716 Instruction *NewElem = dyn_cast<Instruction>(Insert->getOperand(1)); 1717 if (CurrVec && L->contains(CurrVec)) 1718 continue; 1719 if (NewElem && L->contains(NewElem)) 1720 continue; 1721 1722 // We can hoist this instruction. Move it to the pre-header. 1723 Insert->moveBefore(PreHeader->getTerminator()); 1724 } 1725 1726 // Sort blocks by domination. This ensures we visit a block after all blocks 1727 // dominating it are visited. 1728 SmallVector<BasicBlock *, 8> CSEWorkList(CSEBlocks.begin(), CSEBlocks.end()); 1729 std::stable_sort(CSEWorkList.begin(), CSEWorkList.end(), DTCmp(DT)); 1730 1731 // Perform O(N^2) search over the gather sequences and merge identical 1732 // instructions. TODO: We can further optimize this scan if we split the 1733 // instructions into different buckets based on the insert lane. 1734 SmallVector<Instruction *, 16> Visited; 1735 for (SmallVectorImpl<BasicBlock *>::iterator I = CSEWorkList.begin(), 1736 E = CSEWorkList.end(); 1737 I != E; ++I) { 1738 assert((I == CSEWorkList.begin() || !DT->dominates(*I, *llvm::prior(I))) && 1739 "Worklist not sorted properly!"); 1740 BasicBlock *BB = *I; 1741 // For all instructions in blocks containing gather sequences: 1742 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e;) { 1743 Instruction *In = it++; 1744 if (!isa<InsertElementInst>(In) && !isa<ExtractElementInst>(In)) 1745 continue; 1746 1747 // Check if we can replace this instruction with any of the 1748 // visited instructions. 1749 for (SmallVectorImpl<Instruction *>::iterator v = Visited.begin(), 1750 ve = Visited.end(); 1751 v != ve; ++v) { 1752 if (In->isIdenticalTo(*v) && 1753 DT->dominates((*v)->getParent(), In->getParent())) { 1754 In->replaceAllUsesWith(*v); 1755 In->eraseFromParent(); 1756 In = 0; 1757 break; 1758 } 1759 } 1760 if (In) { 1761 assert(std::find(Visited.begin(), Visited.end(), In) == Visited.end()); 1762 Visited.push_back(In); 1763 } 1764 } 1765 } 1766 CSEBlocks.clear(); 1767 GatherSeq.clear(); 1768 } 1769 1770 /// The SLPVectorizer Pass. 1771 struct SLPVectorizer : public FunctionPass { 1772 typedef SmallVector<StoreInst *, 8> StoreList; 1773 typedef MapVector<Value *, StoreList> StoreListMap; 1774 1775 /// Pass identification, replacement for typeid 1776 static char ID; 1777 1778 explicit SLPVectorizer() : FunctionPass(ID) { 1779 initializeSLPVectorizerPass(*PassRegistry::getPassRegistry()); 1780 } 1781 1782 ScalarEvolution *SE; 1783 DataLayout *DL; 1784 TargetTransformInfo *TTI; 1785 AliasAnalysis *AA; 1786 LoopInfo *LI; 1787 DominatorTree *DT; 1788 1789 virtual bool runOnFunction(Function &F) { 1790 if (skipOptnoneFunction(F)) 1791 return false; 1792 1793 SE = &getAnalysis<ScalarEvolution>(); 1794 DL = getAnalysisIfAvailable<DataLayout>(); 1795 TTI = &getAnalysis<TargetTransformInfo>(); 1796 AA = &getAnalysis<AliasAnalysis>(); 1797 LI = &getAnalysis<LoopInfo>(); 1798 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 1799 1800 StoreRefs.clear(); 1801 bool Changed = false; 1802 1803 // If the target claims to have no vector registers don't attempt 1804 // vectorization. 1805 if (!TTI->getNumberOfRegisters(true)) 1806 return false; 1807 1808 // Must have DataLayout. We can't require it because some tests run w/o 1809 // triple. 1810 if (!DL) 1811 return false; 1812 1813 // Don't vectorize when the attribute NoImplicitFloat is used. 1814 if (F.hasFnAttribute(Attribute::NoImplicitFloat)) 1815 return false; 1816 1817 DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n"); 1818 1819 // Use the bottom up slp vectorizer to construct chains that start with 1820 // he store instructions. 1821 BoUpSLP R(&F, SE, DL, TTI, AA, LI, DT); 1822 1823 // Scan the blocks in the function in post order. 1824 for (po_iterator<BasicBlock*> it = po_begin(&F.getEntryBlock()), 1825 e = po_end(&F.getEntryBlock()); it != e; ++it) { 1826 BasicBlock *BB = *it; 1827 1828 // Vectorize trees that end at stores. 1829 if (unsigned count = collectStores(BB, R)) { 1830 (void)count; 1831 DEBUG(dbgs() << "SLP: Found " << count << " stores to vectorize.\n"); 1832 Changed |= vectorizeStoreChains(R); 1833 } 1834 1835 // Vectorize trees that end at reductions. 1836 Changed |= vectorizeChainsInBlock(BB, R); 1837 } 1838 1839 if (Changed) { 1840 R.optimizeGatherSequence(); 1841 DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n"); 1842 DEBUG(verifyFunction(F)); 1843 } 1844 return Changed; 1845 } 1846 1847 virtual void getAnalysisUsage(AnalysisUsage &AU) const { 1848 FunctionPass::getAnalysisUsage(AU); 1849 AU.addRequired<ScalarEvolution>(); 1850 AU.addRequired<AliasAnalysis>(); 1851 AU.addRequired<TargetTransformInfo>(); 1852 AU.addRequired<LoopInfo>(); 1853 AU.addRequired<DominatorTreeWrapperPass>(); 1854 AU.addPreserved<LoopInfo>(); 1855 AU.addPreserved<DominatorTreeWrapperPass>(); 1856 AU.setPreservesCFG(); 1857 } 1858 1859 private: 1860 1861 /// \brief Collect memory references and sort them according to their base 1862 /// object. We sort the stores to their base objects to reduce the cost of the 1863 /// quadratic search on the stores. TODO: We can further reduce this cost 1864 /// if we flush the chain creation every time we run into a memory barrier. 1865 unsigned collectStores(BasicBlock *BB, BoUpSLP &R); 1866 1867 /// \brief Try to vectorize a chain that starts at two arithmetic instrs. 1868 bool tryToVectorizePair(Value *A, Value *B, BoUpSLP &R); 1869 1870 /// \brief Try to vectorize a list of operands. 1871 /// \returns true if a value was vectorized. 1872 bool tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R); 1873 1874 /// \brief Try to vectorize a chain that may start at the operands of \V; 1875 bool tryToVectorize(BinaryOperator *V, BoUpSLP &R); 1876 1877 /// \brief Vectorize the stores that were collected in StoreRefs. 1878 bool vectorizeStoreChains(BoUpSLP &R); 1879 1880 /// \brief Scan the basic block and look for patterns that are likely to start 1881 /// a vectorization chain. 1882 bool vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R); 1883 1884 bool vectorizeStoreChain(ArrayRef<Value *> Chain, int CostThreshold, 1885 BoUpSLP &R); 1886 1887 bool vectorizeStores(ArrayRef<StoreInst *> Stores, int costThreshold, 1888 BoUpSLP &R); 1889 private: 1890 StoreListMap StoreRefs; 1891 }; 1892 1893 /// \brief Check that the Values in the slice in VL array are still existent in 1894 /// the WeakVH array. 1895 /// Vectorization of part of the VL array may cause later values in the VL array 1896 /// to become invalid. We track when this has happened in the WeakVH array. 1897 static bool hasValueBeenRAUWed(ArrayRef<Value *> &VL, 1898 SmallVectorImpl<WeakVH> &VH, 1899 unsigned SliceBegin, 1900 unsigned SliceSize) { 1901 for (unsigned i = SliceBegin; i < SliceBegin + SliceSize; ++i) 1902 if (VH[i] != VL[i]) 1903 return true; 1904 1905 return false; 1906 } 1907 1908 bool SLPVectorizer::vectorizeStoreChain(ArrayRef<Value *> Chain, 1909 int CostThreshold, BoUpSLP &R) { 1910 unsigned ChainLen = Chain.size(); 1911 DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << ChainLen 1912 << "\n"); 1913 Type *StoreTy = cast<StoreInst>(Chain[0])->getValueOperand()->getType(); 1914 unsigned Sz = DL->getTypeSizeInBits(StoreTy); 1915 unsigned VF = MinVecRegSize / Sz; 1916 1917 if (!isPowerOf2_32(Sz) || VF < 2) 1918 return false; 1919 1920 // Keep track of values that were delete by vectorizing in the loop below. 1921 SmallVector<WeakVH, 8> TrackValues(Chain.begin(), Chain.end()); 1922 1923 bool Changed = false; 1924 // Look for profitable vectorizable trees at all offsets, starting at zero. 1925 for (unsigned i = 0, e = ChainLen; i < e; ++i) { 1926 if (i + VF > e) 1927 break; 1928 1929 // Check that a previous iteration of this loop did not delete the Value. 1930 if (hasValueBeenRAUWed(Chain, TrackValues, i, VF)) 1931 continue; 1932 1933 DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << i 1934 << "\n"); 1935 ArrayRef<Value *> Operands = Chain.slice(i, VF); 1936 1937 R.buildTree(Operands); 1938 1939 int Cost = R.getTreeCost(); 1940 1941 DEBUG(dbgs() << "SLP: Found cost=" << Cost << " for VF=" << VF << "\n"); 1942 if (Cost < CostThreshold) { 1943 DEBUG(dbgs() << "SLP: Decided to vectorize cost=" << Cost << "\n"); 1944 R.vectorizeTree(); 1945 1946 // Move to the next bundle. 1947 i += VF - 1; 1948 Changed = true; 1949 } 1950 } 1951 1952 return Changed; 1953 } 1954 1955 bool SLPVectorizer::vectorizeStores(ArrayRef<StoreInst *> Stores, 1956 int costThreshold, BoUpSLP &R) { 1957 SetVector<Value *> Heads, Tails; 1958 SmallDenseMap<Value *, Value *> ConsecutiveChain; 1959 1960 // We may run into multiple chains that merge into a single chain. We mark the 1961 // stores that we vectorized so that we don't visit the same store twice. 1962 BoUpSLP::ValueSet VectorizedStores; 1963 bool Changed = false; 1964 1965 // Do a quadratic search on all of the given stores and find 1966 // all of the pairs of stores that follow each other. 1967 for (unsigned i = 0, e = Stores.size(); i < e; ++i) { 1968 for (unsigned j = 0; j < e; ++j) { 1969 if (i == j) 1970 continue; 1971 1972 if (R.isConsecutiveAccess(Stores[i], Stores[j])) { 1973 Tails.insert(Stores[j]); 1974 Heads.insert(Stores[i]); 1975 ConsecutiveChain[Stores[i]] = Stores[j]; 1976 } 1977 } 1978 } 1979 1980 // For stores that start but don't end a link in the chain: 1981 for (SetVector<Value *>::iterator it = Heads.begin(), e = Heads.end(); 1982 it != e; ++it) { 1983 if (Tails.count(*it)) 1984 continue; 1985 1986 // We found a store instr that starts a chain. Now follow the chain and try 1987 // to vectorize it. 1988 BoUpSLP::ValueList Operands; 1989 Value *I = *it; 1990 // Collect the chain into a list. 1991 while (Tails.count(I) || Heads.count(I)) { 1992 if (VectorizedStores.count(I)) 1993 break; 1994 Operands.push_back(I); 1995 // Move to the next value in the chain. 1996 I = ConsecutiveChain[I]; 1997 } 1998 1999 bool Vectorized = vectorizeStoreChain(Operands, costThreshold, R); 2000 2001 // Mark the vectorized stores so that we don't vectorize them again. 2002 if (Vectorized) 2003 VectorizedStores.insert(Operands.begin(), Operands.end()); 2004 Changed |= Vectorized; 2005 } 2006 2007 return Changed; 2008 } 2009 2010 2011 unsigned SLPVectorizer::collectStores(BasicBlock *BB, BoUpSLP &R) { 2012 unsigned count = 0; 2013 StoreRefs.clear(); 2014 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) { 2015 StoreInst *SI = dyn_cast<StoreInst>(it); 2016 if (!SI) 2017 continue; 2018 2019 // Don't touch volatile stores. 2020 if (!SI->isSimple()) 2021 continue; 2022 2023 // Check that the pointer points to scalars. 2024 Type *Ty = SI->getValueOperand()->getType(); 2025 if (Ty->isAggregateType() || Ty->isVectorTy()) 2026 return 0; 2027 2028 // Find the base pointer. 2029 Value *Ptr = GetUnderlyingObject(SI->getPointerOperand(), DL); 2030 2031 // Save the store locations. 2032 StoreRefs[Ptr].push_back(SI); 2033 count++; 2034 } 2035 return count; 2036 } 2037 2038 bool SLPVectorizer::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) { 2039 if (!A || !B) 2040 return false; 2041 Value *VL[] = { A, B }; 2042 return tryToVectorizeList(VL, R); 2043 } 2044 2045 bool SLPVectorizer::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R) { 2046 if (VL.size() < 2) 2047 return false; 2048 2049 DEBUG(dbgs() << "SLP: Vectorizing a list of length = " << VL.size() << ".\n"); 2050 2051 // Check that all of the parts are scalar instructions of the same type. 2052 Instruction *I0 = dyn_cast<Instruction>(VL[0]); 2053 if (!I0) 2054 return false; 2055 2056 unsigned Opcode0 = I0->getOpcode(); 2057 2058 Type *Ty0 = I0->getType(); 2059 unsigned Sz = DL->getTypeSizeInBits(Ty0); 2060 unsigned VF = MinVecRegSize / Sz; 2061 2062 for (int i = 0, e = VL.size(); i < e; ++i) { 2063 Type *Ty = VL[i]->getType(); 2064 if (Ty->isAggregateType() || Ty->isVectorTy()) 2065 return false; 2066 Instruction *Inst = dyn_cast<Instruction>(VL[i]); 2067 if (!Inst || Inst->getOpcode() != Opcode0) 2068 return false; 2069 } 2070 2071 bool Changed = false; 2072 2073 // Keep track of values that were delete by vectorizing in the loop below. 2074 SmallVector<WeakVH, 8> TrackValues(VL.begin(), VL.end()); 2075 2076 for (unsigned i = 0, e = VL.size(); i < e; ++i) { 2077 unsigned OpsWidth = 0; 2078 2079 if (i + VF > e) 2080 OpsWidth = e - i; 2081 else 2082 OpsWidth = VF; 2083 2084 if (!isPowerOf2_32(OpsWidth) || OpsWidth < 2) 2085 break; 2086 2087 // Check that a previous iteration of this loop did not delete the Value. 2088 if (hasValueBeenRAUWed(VL, TrackValues, i, OpsWidth)) 2089 continue; 2090 2091 DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth << " operations " 2092 << "\n"); 2093 ArrayRef<Value *> Ops = VL.slice(i, OpsWidth); 2094 2095 R.buildTree(Ops); 2096 int Cost = R.getTreeCost(); 2097 2098 if (Cost < -SLPCostThreshold) { 2099 DEBUG(dbgs() << "SLP: Vectorizing pair at cost:" << Cost << ".\n"); 2100 R.vectorizeTree(); 2101 2102 // Move to the next bundle. 2103 i += VF - 1; 2104 Changed = true; 2105 } 2106 } 2107 2108 return Changed; 2109 } 2110 2111 bool SLPVectorizer::tryToVectorize(BinaryOperator *V, BoUpSLP &R) { 2112 if (!V) 2113 return false; 2114 2115 // Try to vectorize V. 2116 if (tryToVectorizePair(V->getOperand(0), V->getOperand(1), R)) 2117 return true; 2118 2119 BinaryOperator *A = dyn_cast<BinaryOperator>(V->getOperand(0)); 2120 BinaryOperator *B = dyn_cast<BinaryOperator>(V->getOperand(1)); 2121 // Try to skip B. 2122 if (B && B->hasOneUse()) { 2123 BinaryOperator *B0 = dyn_cast<BinaryOperator>(B->getOperand(0)); 2124 BinaryOperator *B1 = dyn_cast<BinaryOperator>(B->getOperand(1)); 2125 if (tryToVectorizePair(A, B0, R)) { 2126 B->moveBefore(V); 2127 return true; 2128 } 2129 if (tryToVectorizePair(A, B1, R)) { 2130 B->moveBefore(V); 2131 return true; 2132 } 2133 } 2134 2135 // Try to skip A. 2136 if (A && A->hasOneUse()) { 2137 BinaryOperator *A0 = dyn_cast<BinaryOperator>(A->getOperand(0)); 2138 BinaryOperator *A1 = dyn_cast<BinaryOperator>(A->getOperand(1)); 2139 if (tryToVectorizePair(A0, B, R)) { 2140 A->moveBefore(V); 2141 return true; 2142 } 2143 if (tryToVectorizePair(A1, B, R)) { 2144 A->moveBefore(V); 2145 return true; 2146 } 2147 } 2148 return 0; 2149 } 2150 2151 /// \brief Generate a shuffle mask to be used in a reduction tree. 2152 /// 2153 /// \param VecLen The length of the vector to be reduced. 2154 /// \param NumEltsToRdx The number of elements that should be reduced in the 2155 /// vector. 2156 /// \param IsPairwise Whether the reduction is a pairwise or splitting 2157 /// reduction. A pairwise reduction will generate a mask of 2158 /// <0,2,...> or <1,3,..> while a splitting reduction will generate 2159 /// <2,3, undef,undef> for a vector of 4 and NumElts = 2. 2160 /// \param IsLeft True will generate a mask of even elements, odd otherwise. 2161 static Value *createRdxShuffleMask(unsigned VecLen, unsigned NumEltsToRdx, 2162 bool IsPairwise, bool IsLeft, 2163 IRBuilder<> &Builder) { 2164 assert((IsPairwise || !IsLeft) && "Don't support a <0,1,undef,...> mask"); 2165 2166 SmallVector<Constant *, 32> ShuffleMask( 2167 VecLen, UndefValue::get(Builder.getInt32Ty())); 2168 2169 if (IsPairwise) 2170 // Build a mask of 0, 2, ... (left) or 1, 3, ... (right). 2171 for (unsigned i = 0; i != NumEltsToRdx; ++i) 2172 ShuffleMask[i] = Builder.getInt32(2 * i + !IsLeft); 2173 else 2174 // Move the upper half of the vector to the lower half. 2175 for (unsigned i = 0; i != NumEltsToRdx; ++i) 2176 ShuffleMask[i] = Builder.getInt32(NumEltsToRdx + i); 2177 2178 return ConstantVector::get(ShuffleMask); 2179 } 2180 2181 2182 /// Model horizontal reductions. 2183 /// 2184 /// A horizontal reduction is a tree of reduction operations (currently add and 2185 /// fadd) that has operations that can be put into a vector as its leaf. 2186 /// For example, this tree: 2187 /// 2188 /// mul mul mul mul 2189 /// \ / \ / 2190 /// + + 2191 /// \ / 2192 /// + 2193 /// This tree has "mul" as its reduced values and "+" as its reduction 2194 /// operations. A reduction might be feeding into a store or a binary operation 2195 /// feeding a phi. 2196 /// ... 2197 /// \ / 2198 /// + 2199 /// | 2200 /// phi += 2201 /// 2202 /// Or: 2203 /// ... 2204 /// \ / 2205 /// + 2206 /// | 2207 /// *p = 2208 /// 2209 class HorizontalReduction { 2210 SmallPtrSet<Value *, 16> ReductionOps; 2211 SmallVector<Value *, 32> ReducedVals; 2212 2213 BinaryOperator *ReductionRoot; 2214 PHINode *ReductionPHI; 2215 2216 /// The opcode of the reduction. 2217 unsigned ReductionOpcode; 2218 /// The opcode of the values we perform a reduction on. 2219 unsigned ReducedValueOpcode; 2220 /// The width of one full horizontal reduction operation. 2221 unsigned ReduxWidth; 2222 /// Should we model this reduction as a pairwise reduction tree or a tree that 2223 /// splits the vector in halves and adds those halves. 2224 bool IsPairwiseReduction; 2225 2226 public: 2227 HorizontalReduction() 2228 : ReductionRoot(0), ReductionPHI(0), ReductionOpcode(0), 2229 ReducedValueOpcode(0), ReduxWidth(0), IsPairwiseReduction(false) {} 2230 2231 /// \brief Try to find a reduction tree. 2232 bool matchAssociativeReduction(PHINode *Phi, BinaryOperator *B, 2233 DataLayout *DL) { 2234 assert((!Phi || 2235 std::find(Phi->op_begin(), Phi->op_end(), B) != Phi->op_end()) && 2236 "Thi phi needs to use the binary operator"); 2237 2238 // We could have a initial reductions that is not an add. 2239 // r *= v1 + v2 + v3 + v4 2240 // In such a case start looking for a tree rooted in the first '+'. 2241 if (Phi) { 2242 if (B->getOperand(0) == Phi) { 2243 Phi = 0; 2244 B = dyn_cast<BinaryOperator>(B->getOperand(1)); 2245 } else if (B->getOperand(1) == Phi) { 2246 Phi = 0; 2247 B = dyn_cast<BinaryOperator>(B->getOperand(0)); 2248 } 2249 } 2250 2251 if (!B) 2252 return false; 2253 2254 Type *Ty = B->getType(); 2255 if (Ty->isVectorTy()) 2256 return false; 2257 2258 ReductionOpcode = B->getOpcode(); 2259 ReducedValueOpcode = 0; 2260 ReduxWidth = MinVecRegSize / DL->getTypeSizeInBits(Ty); 2261 ReductionRoot = B; 2262 ReductionPHI = Phi; 2263 2264 if (ReduxWidth < 4) 2265 return false; 2266 2267 // We currently only support adds. 2268 if (ReductionOpcode != Instruction::Add && 2269 ReductionOpcode != Instruction::FAdd) 2270 return false; 2271 2272 // Post order traverse the reduction tree starting at B. We only handle true 2273 // trees containing only binary operators. 2274 SmallVector<std::pair<BinaryOperator *, unsigned>, 32> Stack; 2275 Stack.push_back(std::make_pair(B, 0)); 2276 while (!Stack.empty()) { 2277 BinaryOperator *TreeN = Stack.back().first; 2278 unsigned EdgeToVist = Stack.back().second++; 2279 bool IsReducedValue = TreeN->getOpcode() != ReductionOpcode; 2280 2281 // Only handle trees in the current basic block. 2282 if (TreeN->getParent() != B->getParent()) 2283 return false; 2284 2285 // Each tree node needs to have one user except for the ultimate 2286 // reduction. 2287 if (!TreeN->hasOneUse() && TreeN != B) 2288 return false; 2289 2290 // Postorder vist. 2291 if (EdgeToVist == 2 || IsReducedValue) { 2292 if (IsReducedValue) { 2293 // Make sure that the opcodes of the operations that we are going to 2294 // reduce match. 2295 if (!ReducedValueOpcode) 2296 ReducedValueOpcode = TreeN->getOpcode(); 2297 else if (ReducedValueOpcode != TreeN->getOpcode()) 2298 return false; 2299 ReducedVals.push_back(TreeN); 2300 } else { 2301 // We need to be able to reassociate the adds. 2302 if (!TreeN->isAssociative()) 2303 return false; 2304 ReductionOps.insert(TreeN); 2305 } 2306 // Retract. 2307 Stack.pop_back(); 2308 continue; 2309 } 2310 2311 // Visit left or right. 2312 Value *NextV = TreeN->getOperand(EdgeToVist); 2313 BinaryOperator *Next = dyn_cast<BinaryOperator>(NextV); 2314 if (Next) 2315 Stack.push_back(std::make_pair(Next, 0)); 2316 else if (NextV != Phi) 2317 return false; 2318 } 2319 return true; 2320 } 2321 2322 /// \brief Attempt to vectorize the tree found by 2323 /// matchAssociativeReduction. 2324 bool tryToReduce(BoUpSLP &V, TargetTransformInfo *TTI) { 2325 if (ReducedVals.empty()) 2326 return false; 2327 2328 unsigned NumReducedVals = ReducedVals.size(); 2329 if (NumReducedVals < ReduxWidth) 2330 return false; 2331 2332 Value *VectorizedTree = 0; 2333 IRBuilder<> Builder(ReductionRoot); 2334 FastMathFlags Unsafe; 2335 Unsafe.setUnsafeAlgebra(); 2336 Builder.SetFastMathFlags(Unsafe); 2337 unsigned i = 0; 2338 2339 for (; i < NumReducedVals - ReduxWidth + 1; i += ReduxWidth) { 2340 ArrayRef<Value *> ValsToReduce(&ReducedVals[i], ReduxWidth); 2341 V.buildTree(ValsToReduce, &ReductionOps); 2342 2343 // Estimate cost. 2344 int Cost = V.getTreeCost() + getReductionCost(TTI, ReducedVals[i]); 2345 if (Cost >= -SLPCostThreshold) 2346 break; 2347 2348 DEBUG(dbgs() << "SLP: Vectorizing horizontal reduction at cost:" << Cost 2349 << ". (HorRdx)\n"); 2350 2351 // Vectorize a tree. 2352 DebugLoc Loc = cast<Instruction>(ReducedVals[i])->getDebugLoc(); 2353 Value *VectorizedRoot = V.vectorizeTree(); 2354 2355 // Emit a reduction. 2356 Value *ReducedSubTree = emitReduction(VectorizedRoot, Builder); 2357 if (VectorizedTree) { 2358 Builder.SetCurrentDebugLocation(Loc); 2359 VectorizedTree = createBinOp(Builder, ReductionOpcode, VectorizedTree, 2360 ReducedSubTree, "bin.rdx"); 2361 } else 2362 VectorizedTree = ReducedSubTree; 2363 } 2364 2365 if (VectorizedTree) { 2366 // Finish the reduction. 2367 for (; i < NumReducedVals; ++i) { 2368 Builder.SetCurrentDebugLocation( 2369 cast<Instruction>(ReducedVals[i])->getDebugLoc()); 2370 VectorizedTree = createBinOp(Builder, ReductionOpcode, VectorizedTree, 2371 ReducedVals[i]); 2372 } 2373 // Update users. 2374 if (ReductionPHI) { 2375 assert(ReductionRoot != NULL && "Need a reduction operation"); 2376 ReductionRoot->setOperand(0, VectorizedTree); 2377 ReductionRoot->setOperand(1, ReductionPHI); 2378 } else 2379 ReductionRoot->replaceAllUsesWith(VectorizedTree); 2380 } 2381 return VectorizedTree != 0; 2382 } 2383 2384 private: 2385 2386 /// \brief Calcuate the cost of a reduction. 2387 int getReductionCost(TargetTransformInfo *TTI, Value *FirstReducedVal) { 2388 Type *ScalarTy = FirstReducedVal->getType(); 2389 Type *VecTy = VectorType::get(ScalarTy, ReduxWidth); 2390 2391 int PairwiseRdxCost = TTI->getReductionCost(ReductionOpcode, VecTy, true); 2392 int SplittingRdxCost = TTI->getReductionCost(ReductionOpcode, VecTy, false); 2393 2394 IsPairwiseReduction = PairwiseRdxCost < SplittingRdxCost; 2395 int VecReduxCost = IsPairwiseReduction ? PairwiseRdxCost : SplittingRdxCost; 2396 2397 int ScalarReduxCost = 2398 ReduxWidth * TTI->getArithmeticInstrCost(ReductionOpcode, VecTy); 2399 2400 DEBUG(dbgs() << "SLP: Adding cost " << VecReduxCost - ScalarReduxCost 2401 << " for reduction that starts with " << *FirstReducedVal 2402 << " (It is a " 2403 << (IsPairwiseReduction ? "pairwise" : "splitting") 2404 << " reduction)\n"); 2405 2406 return VecReduxCost - ScalarReduxCost; 2407 } 2408 2409 static Value *createBinOp(IRBuilder<> &Builder, unsigned Opcode, Value *L, 2410 Value *R, const Twine &Name = "") { 2411 if (Opcode == Instruction::FAdd) 2412 return Builder.CreateFAdd(L, R, Name); 2413 return Builder.CreateBinOp((Instruction::BinaryOps)Opcode, L, R, Name); 2414 } 2415 2416 /// \brief Emit a horizontal reduction of the vectorized value. 2417 Value *emitReduction(Value *VectorizedValue, IRBuilder<> &Builder) { 2418 assert(VectorizedValue && "Need to have a vectorized tree node"); 2419 Instruction *ValToReduce = dyn_cast<Instruction>(VectorizedValue); 2420 assert(isPowerOf2_32(ReduxWidth) && 2421 "We only handle power-of-two reductions for now"); 2422 2423 Value *TmpVec = ValToReduce; 2424 for (unsigned i = ReduxWidth / 2; i != 0; i >>= 1) { 2425 if (IsPairwiseReduction) { 2426 Value *LeftMask = 2427 createRdxShuffleMask(ReduxWidth, i, true, true, Builder); 2428 Value *RightMask = 2429 createRdxShuffleMask(ReduxWidth, i, true, false, Builder); 2430 2431 Value *LeftShuf = Builder.CreateShuffleVector( 2432 TmpVec, UndefValue::get(TmpVec->getType()), LeftMask, "rdx.shuf.l"); 2433 Value *RightShuf = Builder.CreateShuffleVector( 2434 TmpVec, UndefValue::get(TmpVec->getType()), (RightMask), 2435 "rdx.shuf.r"); 2436 TmpVec = createBinOp(Builder, ReductionOpcode, LeftShuf, RightShuf, 2437 "bin.rdx"); 2438 } else { 2439 Value *UpperHalf = 2440 createRdxShuffleMask(ReduxWidth, i, false, false, Builder); 2441 Value *Shuf = Builder.CreateShuffleVector( 2442 TmpVec, UndefValue::get(TmpVec->getType()), UpperHalf, "rdx.shuf"); 2443 TmpVec = createBinOp(Builder, ReductionOpcode, TmpVec, Shuf, "bin.rdx"); 2444 } 2445 } 2446 2447 // The result is in the first element of the vector. 2448 return Builder.CreateExtractElement(TmpVec, Builder.getInt32(0)); 2449 } 2450 }; 2451 2452 /// \brief Recognize construction of vectors like 2453 /// %ra = insertelement <4 x float> undef, float %s0, i32 0 2454 /// %rb = insertelement <4 x float> %ra, float %s1, i32 1 2455 /// %rc = insertelement <4 x float> %rb, float %s2, i32 2 2456 /// %rd = insertelement <4 x float> %rc, float %s3, i32 3 2457 /// 2458 /// Returns true if it matches 2459 /// 2460 static bool findBuildVector(InsertElementInst *IE, 2461 SmallVectorImpl<Value *> &Ops) { 2462 if (!isa<UndefValue>(IE->getOperand(0))) 2463 return false; 2464 2465 while (true) { 2466 Ops.push_back(IE->getOperand(1)); 2467 2468 if (IE->use_empty()) 2469 return false; 2470 2471 InsertElementInst *NextUse = dyn_cast<InsertElementInst>(IE->use_back()); 2472 if (!NextUse) 2473 return true; 2474 2475 // If this isn't the final use, make sure the next insertelement is the only 2476 // use. It's OK if the final constructed vector is used multiple times 2477 if (!IE->hasOneUse()) 2478 return false; 2479 2480 IE = NextUse; 2481 } 2482 2483 return false; 2484 } 2485 2486 static bool PhiTypeSorterFunc(Value *V, Value *V2) { 2487 return V->getType() < V2->getType(); 2488 } 2489 2490 bool SLPVectorizer::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) { 2491 bool Changed = false; 2492 SmallVector<Value *, 4> Incoming; 2493 SmallSet<Value *, 16> VisitedInstrs; 2494 2495 bool HaveVectorizedPhiNodes = true; 2496 while (HaveVectorizedPhiNodes) { 2497 HaveVectorizedPhiNodes = false; 2498 2499 // Collect the incoming values from the PHIs. 2500 Incoming.clear(); 2501 for (BasicBlock::iterator instr = BB->begin(), ie = BB->end(); instr != ie; 2502 ++instr) { 2503 PHINode *P = dyn_cast<PHINode>(instr); 2504 if (!P) 2505 break; 2506 2507 if (!VisitedInstrs.count(P)) 2508 Incoming.push_back(P); 2509 } 2510 2511 // Sort by type. 2512 std::stable_sort(Incoming.begin(), Incoming.end(), PhiTypeSorterFunc); 2513 2514 // Try to vectorize elements base on their type. 2515 for (SmallVector<Value *, 4>::iterator IncIt = Incoming.begin(), 2516 E = Incoming.end(); 2517 IncIt != E;) { 2518 2519 // Look for the next elements with the same type. 2520 SmallVector<Value *, 4>::iterator SameTypeIt = IncIt; 2521 while (SameTypeIt != E && 2522 (*SameTypeIt)->getType() == (*IncIt)->getType()) { 2523 VisitedInstrs.insert(*SameTypeIt); 2524 ++SameTypeIt; 2525 } 2526 2527 // Try to vectorize them. 2528 unsigned NumElts = (SameTypeIt - IncIt); 2529 DEBUG(errs() << "SLP: Trying to vectorize starting at PHIs (" << NumElts << ")\n"); 2530 if (NumElts > 1 && 2531 tryToVectorizeList(ArrayRef<Value *>(IncIt, NumElts), R)) { 2532 // Success start over because instructions might have been changed. 2533 HaveVectorizedPhiNodes = true; 2534 Changed = true; 2535 break; 2536 } 2537 2538 // Start over at the next instruction of a different type (or the end). 2539 IncIt = SameTypeIt; 2540 } 2541 } 2542 2543 VisitedInstrs.clear(); 2544 2545 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; it++) { 2546 // We may go through BB multiple times so skip the one we have checked. 2547 if (!VisitedInstrs.insert(it)) 2548 continue; 2549 2550 if (isa<DbgInfoIntrinsic>(it)) 2551 continue; 2552 2553 // Try to vectorize reductions that use PHINodes. 2554 if (PHINode *P = dyn_cast<PHINode>(it)) { 2555 // Check that the PHI is a reduction PHI. 2556 if (P->getNumIncomingValues() != 2) 2557 return Changed; 2558 Value *Rdx = 2559 (P->getIncomingBlock(0) == BB 2560 ? (P->getIncomingValue(0)) 2561 : (P->getIncomingBlock(1) == BB ? P->getIncomingValue(1) : 0)); 2562 // Check if this is a Binary Operator. 2563 BinaryOperator *BI = dyn_cast_or_null<BinaryOperator>(Rdx); 2564 if (!BI) 2565 continue; 2566 2567 // Try to match and vectorize a horizontal reduction. 2568 HorizontalReduction HorRdx; 2569 if (ShouldVectorizeHor && 2570 HorRdx.matchAssociativeReduction(P, BI, DL) && 2571 HorRdx.tryToReduce(R, TTI)) { 2572 Changed = true; 2573 it = BB->begin(); 2574 e = BB->end(); 2575 continue; 2576 } 2577 2578 Value *Inst = BI->getOperand(0); 2579 if (Inst == P) 2580 Inst = BI->getOperand(1); 2581 2582 if (tryToVectorize(dyn_cast<BinaryOperator>(Inst), R)) { 2583 // We would like to start over since some instructions are deleted 2584 // and the iterator may become invalid value. 2585 Changed = true; 2586 it = BB->begin(); 2587 e = BB->end(); 2588 continue; 2589 } 2590 2591 continue; 2592 } 2593 2594 // Try to vectorize horizontal reductions feeding into a store. 2595 if (ShouldStartVectorizeHorAtStore) 2596 if (StoreInst *SI = dyn_cast<StoreInst>(it)) 2597 if (BinaryOperator *BinOp = 2598 dyn_cast<BinaryOperator>(SI->getValueOperand())) { 2599 HorizontalReduction HorRdx; 2600 if (((HorRdx.matchAssociativeReduction(0, BinOp, DL) && 2601 HorRdx.tryToReduce(R, TTI)) || 2602 tryToVectorize(BinOp, R))) { 2603 Changed = true; 2604 it = BB->begin(); 2605 e = BB->end(); 2606 continue; 2607 } 2608 } 2609 2610 // Try to vectorize trees that start at compare instructions. 2611 if (CmpInst *CI = dyn_cast<CmpInst>(it)) { 2612 if (tryToVectorizePair(CI->getOperand(0), CI->getOperand(1), R)) { 2613 Changed = true; 2614 // We would like to start over since some instructions are deleted 2615 // and the iterator may become invalid value. 2616 it = BB->begin(); 2617 e = BB->end(); 2618 continue; 2619 } 2620 2621 for (int i = 0; i < 2; ++i) { 2622 if (BinaryOperator *BI = dyn_cast<BinaryOperator>(CI->getOperand(i))) { 2623 if (tryToVectorizePair(BI->getOperand(0), BI->getOperand(1), R)) { 2624 Changed = true; 2625 // We would like to start over since some instructions are deleted 2626 // and the iterator may become invalid value. 2627 it = BB->begin(); 2628 e = BB->end(); 2629 } 2630 } 2631 } 2632 continue; 2633 } 2634 2635 // Try to vectorize trees that start at insertelement instructions. 2636 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(it)) { 2637 SmallVector<Value *, 8> Ops; 2638 if (!findBuildVector(IE, Ops)) 2639 continue; 2640 2641 if (tryToVectorizeList(Ops, R)) { 2642 Changed = true; 2643 it = BB->begin(); 2644 e = BB->end(); 2645 } 2646 2647 continue; 2648 } 2649 } 2650 2651 return Changed; 2652 } 2653 2654 bool SLPVectorizer::vectorizeStoreChains(BoUpSLP &R) { 2655 bool Changed = false; 2656 // Attempt to sort and vectorize each of the store-groups. 2657 for (StoreListMap::iterator it = StoreRefs.begin(), e = StoreRefs.end(); 2658 it != e; ++it) { 2659 if (it->second.size() < 2) 2660 continue; 2661 2662 DEBUG(dbgs() << "SLP: Analyzing a store chain of length " 2663 << it->second.size() << ".\n"); 2664 2665 // Process the stores in chunks of 16. 2666 for (unsigned CI = 0, CE = it->second.size(); CI < CE; CI+=16) { 2667 unsigned Len = std::min<unsigned>(CE - CI, 16); 2668 ArrayRef<StoreInst *> Chunk(&it->second[CI], Len); 2669 Changed |= vectorizeStores(Chunk, -SLPCostThreshold, R); 2670 } 2671 } 2672 return Changed; 2673 } 2674 2675 } // end anonymous namespace 2676 2677 char SLPVectorizer::ID = 0; 2678 static const char lv_name[] = "SLP Vectorizer"; 2679 INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false) 2680 INITIALIZE_AG_DEPENDENCY(AliasAnalysis) 2681 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo) 2682 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution) 2683 INITIALIZE_PASS_DEPENDENCY(LoopSimplify) 2684 INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false) 2685 2686 namespace llvm { 2687 Pass *createSLPVectorizerPass() { return new SLPVectorizer(); } 2688 } 2689