1 //===- LoopVectorize.cpp - A Loop 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 // 10 // This is the LLVM loop vectorizer. This pass modifies 'vectorizable' loops 11 // and generates target-independent LLVM-IR. Legalization of the IR is done 12 // in the codegen. However, the vectorizes uses (will use) the codegen 13 // interfaces to generate IR that is likely to result in an optimal binary. 14 // 15 // The loop vectorizer combines consecutive loop iteration into a single 16 // 'wide' iteration. After this transformation the index is incremented 17 // by the SIMD vector width, and not by one. 18 // 19 // This pass has three parts: 20 // 1. The main loop pass that drives the different parts. 21 // 2. LoopVectorizationLegality - A unit that checks for the legality 22 // of the vectorization. 23 // 3. InnerLoopVectorizer - A unit that performs the actual 24 // widening of instructions. 25 // 4. LoopVectorizationCostModel - A unit that checks for the profitability 26 // of vectorization. It decides on the optimal vector width, which 27 // can be one, if vectorization is not profitable. 28 // 29 //===----------------------------------------------------------------------===// 30 // 31 // The reduction-variable vectorization is based on the paper: 32 // D. Nuzman and R. Henderson. Multi-platform Auto-vectorization. 33 // 34 // Variable uniformity checks are inspired by: 35 // Karrenberg, R. and Hack, S. Whole Function Vectorization. 36 // 37 // Other ideas/concepts are from: 38 // A. Zaks and D. Nuzman. Autovectorization in GCC-two years later. 39 // 40 // S. Maleki, Y. Gao, M. Garzaran, T. Wong and D. Padua. An Evaluation of 41 // Vectorizing Compilers. 42 // 43 //===----------------------------------------------------------------------===// 44 45 #define LV_NAME "loop-vectorize" 46 #define DEBUG_TYPE LV_NAME 47 48 #include "llvm/Transforms/Vectorize.h" 49 #include "llvm/ADT/DenseMap.h" 50 #include "llvm/ADT/MapVector.h" 51 #include "llvm/ADT/SmallPtrSet.h" 52 #include "llvm/ADT/SmallSet.h" 53 #include "llvm/ADT/SmallVector.h" 54 #include "llvm/ADT/StringExtras.h" 55 #include "llvm/Analysis/AliasAnalysis.h" 56 #include "llvm/Analysis/AliasSetTracker.h" 57 #include "llvm/Analysis/Dominators.h" 58 #include "llvm/Analysis/LoopInfo.h" 59 #include "llvm/Analysis/LoopIterator.h" 60 #include "llvm/Analysis/LoopPass.h" 61 #include "llvm/Analysis/ScalarEvolution.h" 62 #include "llvm/Analysis/ScalarEvolutionExpander.h" 63 #include "llvm/Analysis/ScalarEvolutionExpressions.h" 64 #include "llvm/Analysis/TargetTransformInfo.h" 65 #include "llvm/Analysis/ValueTracking.h" 66 #include "llvm/Analysis/Verifier.h" 67 #include "llvm/IR/Constants.h" 68 #include "llvm/IR/DataLayout.h" 69 #include "llvm/IR/DerivedTypes.h" 70 #include "llvm/IR/Function.h" 71 #include "llvm/IR/IRBuilder.h" 72 #include "llvm/IR/Instructions.h" 73 #include "llvm/IR/IntrinsicInst.h" 74 #include "llvm/IR/LLVMContext.h" 75 #include "llvm/IR/Module.h" 76 #include "llvm/IR/Type.h" 77 #include "llvm/IR/Value.h" 78 #include "llvm/Pass.h" 79 #include "llvm/Support/CommandLine.h" 80 #include "llvm/Support/Debug.h" 81 #include "llvm/Support/raw_ostream.h" 82 #include "llvm/Transforms/Scalar.h" 83 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 84 #include "llvm/Transforms/Utils/Local.h" 85 #include <algorithm> 86 #include <map> 87 88 using namespace llvm; 89 90 static cl::opt<unsigned> 91 VectorizationFactor("force-vector-width", cl::init(0), cl::Hidden, 92 cl::desc("Sets the SIMD width. Zero is autoselect.")); 93 94 static cl::opt<unsigned> 95 VectorizationUnroll("force-vector-unroll", cl::init(0), cl::Hidden, 96 cl::desc("Sets the vectorization unroll count. " 97 "Zero is autoselect.")); 98 99 static cl::opt<bool> 100 EnableIfConversion("enable-if-conversion", cl::init(true), cl::Hidden, 101 cl::desc("Enable if-conversion during vectorization.")); 102 103 /// We don't vectorize loops with a known constant trip count below this number. 104 static const unsigned TinyTripCountVectorThreshold = 16; 105 106 /// We don't unroll loops with a known constant trip count below this number. 107 static const unsigned TinyTripCountUnrollThreshold = 128; 108 109 /// When performing a runtime memory check, do not check more than this 110 /// number of pointers. Notice that the check is quadratic! 111 static const unsigned RuntimeMemoryCheckThreshold = 4; 112 113 namespace { 114 115 // Forward declarations. 116 class LoopVectorizationLegality; 117 class LoopVectorizationCostModel; 118 119 /// InnerLoopVectorizer vectorizes loops which contain only one basic 120 /// block to a specified vectorization factor (VF). 121 /// This class performs the widening of scalars into vectors, or multiple 122 /// scalars. This class also implements the following features: 123 /// * It inserts an epilogue loop for handling loops that don't have iteration 124 /// counts that are known to be a multiple of the vectorization factor. 125 /// * It handles the code generation for reduction variables. 126 /// * Scalarization (implementation using scalars) of un-vectorizable 127 /// instructions. 128 /// InnerLoopVectorizer does not perform any vectorization-legality 129 /// checks, and relies on the caller to check for the different legality 130 /// aspects. The InnerLoopVectorizer relies on the 131 /// LoopVectorizationLegality class to provide information about the induction 132 /// and reduction variables that were found to a given vectorization factor. 133 class InnerLoopVectorizer { 134 public: 135 InnerLoopVectorizer(Loop *OrigLoop, ScalarEvolution *SE, LoopInfo *LI, 136 DominatorTree *DT, DataLayout *DL, unsigned VecWidth, 137 unsigned UnrollFactor) 138 : OrigLoop(OrigLoop), SE(SE), LI(LI), DT(DT), DL(DL), VF(VecWidth), 139 UF(UnrollFactor), Builder(SE->getContext()), Induction(0), 140 OldInduction(0), WidenMap(UnrollFactor) {} 141 142 // Perform the actual loop widening (vectorization). 143 void vectorize(LoopVectorizationLegality *Legal) { 144 // Create a new empty loop. Unlink the old loop and connect the new one. 145 createEmptyLoop(Legal); 146 // Widen each instruction in the old loop to a new one in the new loop. 147 // Use the Legality module to find the induction and reduction variables. 148 vectorizeLoop(Legal); 149 // Register the new loop and update the analysis passes. 150 updateAnalysis(); 151 } 152 153 private: 154 /// A small list of PHINodes. 155 typedef SmallVector<PHINode*, 4> PhiVector; 156 /// When we unroll loops we have multiple vector values for each scalar. 157 /// This data structure holds the unrolled and vectorized values that 158 /// originated from one scalar instruction. 159 typedef SmallVector<Value*, 2> VectorParts; 160 161 /// Add code that checks at runtime if the accessed arrays overlap. 162 /// Returns the comparator value or NULL if no check is needed. 163 Instruction *addRuntimeCheck(LoopVectorizationLegality *Legal, 164 Instruction *Loc); 165 /// Create an empty loop, based on the loop ranges of the old loop. 166 void createEmptyLoop(LoopVectorizationLegality *Legal); 167 /// Copy and widen the instructions from the old loop. 168 void vectorizeLoop(LoopVectorizationLegality *Legal); 169 170 /// A helper function that computes the predicate of the block BB, assuming 171 /// that the header block of the loop is set to True. It returns the *entry* 172 /// mask for the block BB. 173 VectorParts createBlockInMask(BasicBlock *BB); 174 /// A helper function that computes the predicate of the edge between SRC 175 /// and DST. 176 VectorParts createEdgeMask(BasicBlock *Src, BasicBlock *Dst); 177 178 /// A helper function to vectorize a single BB within the innermost loop. 179 void vectorizeBlockInLoop(LoopVectorizationLegality *Legal, BasicBlock *BB, 180 PhiVector *PV); 181 182 /// Insert the new loop to the loop hierarchy and pass manager 183 /// and update the analysis passes. 184 void updateAnalysis(); 185 186 /// This instruction is un-vectorizable. Implement it as a sequence 187 /// of scalars. 188 void scalarizeInstruction(Instruction *Instr); 189 190 /// Vectorize Load and Store instructions, 191 void vectorizeMemoryInstruction(Instruction *Instr, 192 LoopVectorizationLegality *Legal); 193 194 /// Create a broadcast instruction. This method generates a broadcast 195 /// instruction (shuffle) for loop invariant values and for the induction 196 /// value. If this is the induction variable then we extend it to N, N+1, ... 197 /// this is needed because each iteration in the loop corresponds to a SIMD 198 /// element. 199 Value *getBroadcastInstrs(Value *V); 200 201 /// This function adds 0, 1, 2 ... to each vector element, starting at zero. 202 /// If Negate is set then negative numbers are added e.g. (0, -1, -2, ...). 203 /// The sequence starts at StartIndex. 204 Value *getConsecutiveVector(Value* Val, unsigned StartIdx, bool Negate); 205 206 /// When we go over instructions in the basic block we rely on previous 207 /// values within the current basic block or on loop invariant values. 208 /// When we widen (vectorize) values we place them in the map. If the values 209 /// are not within the map, they have to be loop invariant, so we simply 210 /// broadcast them into a vector. 211 VectorParts &getVectorValue(Value *V); 212 213 /// Generate a shuffle sequence that will reverse the vector Vec. 214 Value *reverseVector(Value *Vec); 215 216 /// This is a helper class that holds the vectorizer state. It maps scalar 217 /// instructions to vector instructions. When the code is 'unrolled' then 218 /// then a single scalar value is mapped to multiple vector parts. The parts 219 /// are stored in the VectorPart type. 220 struct ValueMap { 221 /// C'tor. UnrollFactor controls the number of vectors ('parts') that 222 /// are mapped. 223 ValueMap(unsigned UnrollFactor) : UF(UnrollFactor) {} 224 225 /// \return True if 'Key' is saved in the Value Map. 226 bool has(Value *Key) { return MapStoreage.count(Key); } 227 228 /// Initializes a new entry in the map. Sets all of the vector parts to the 229 /// save value in 'Val'. 230 /// \return A reference to a vector with splat values. 231 VectorParts &splat(Value *Key, Value *Val) { 232 MapStoreage[Key].clear(); 233 MapStoreage[Key].append(UF, Val); 234 return MapStoreage[Key]; 235 } 236 237 ///\return A reference to the value that is stored at 'Key'. 238 VectorParts &get(Value *Key) { 239 if (!has(Key)) 240 MapStoreage[Key].resize(UF); 241 return MapStoreage[Key]; 242 } 243 244 /// The unroll factor. Each entry in the map stores this number of vector 245 /// elements. 246 unsigned UF; 247 248 /// Map storage. We use std::map and not DenseMap because insertions to a 249 /// dense map invalidates its iterators. 250 std::map<Value*, VectorParts> MapStoreage; 251 }; 252 253 /// The original loop. 254 Loop *OrigLoop; 255 /// Scev analysis to use. 256 ScalarEvolution *SE; 257 /// Loop Info. 258 LoopInfo *LI; 259 /// Dominator Tree. 260 DominatorTree *DT; 261 /// Data Layout. 262 DataLayout *DL; 263 /// The vectorization SIMD factor to use. Each vector will have this many 264 /// vector elements. 265 unsigned VF; 266 /// The vectorization unroll factor to use. Each scalar is vectorized to this 267 /// many different vector instructions. 268 unsigned UF; 269 270 /// The builder that we use 271 IRBuilder<> Builder; 272 273 // --- Vectorization state --- 274 275 /// The vector-loop preheader. 276 BasicBlock *LoopVectorPreHeader; 277 /// The scalar-loop preheader. 278 BasicBlock *LoopScalarPreHeader; 279 /// Middle Block between the vector and the scalar. 280 BasicBlock *LoopMiddleBlock; 281 ///The ExitBlock of the scalar loop. 282 BasicBlock *LoopExitBlock; 283 ///The vector loop body. 284 BasicBlock *LoopVectorBody; 285 ///The scalar loop body. 286 BasicBlock *LoopScalarBody; 287 /// A list of all bypass blocks. The first block is the entry of the loop. 288 SmallVector<BasicBlock *, 4> LoopBypassBlocks; 289 290 /// The new Induction variable which was added to the new block. 291 PHINode *Induction; 292 /// The induction variable of the old basic block. 293 PHINode *OldInduction; 294 /// Maps scalars to widened vectors. 295 ValueMap WidenMap; 296 }; 297 298 /// LoopVectorizationLegality checks if it is legal to vectorize a loop, and 299 /// to what vectorization factor. 300 /// This class does not look at the profitability of vectorization, only the 301 /// legality. This class has two main kinds of checks: 302 /// * Memory checks - The code in canVectorizeMemory checks if vectorization 303 /// will change the order of memory accesses in a way that will change the 304 /// correctness of the program. 305 /// * Scalars checks - The code in canVectorizeInstrs and canVectorizeMemory 306 /// checks for a number of different conditions, such as the availability of a 307 /// single induction variable, that all types are supported and vectorize-able, 308 /// etc. This code reflects the capabilities of InnerLoopVectorizer. 309 /// This class is also used by InnerLoopVectorizer for identifying 310 /// induction variable and the different reduction variables. 311 class LoopVectorizationLegality { 312 public: 313 LoopVectorizationLegality(Loop *L, ScalarEvolution *SE, DataLayout *DL, 314 DominatorTree *DT) 315 : TheLoop(L), SE(SE), DL(DL), DT(DT), Induction(0) {} 316 317 /// This enum represents the kinds of reductions that we support. 318 enum ReductionKind { 319 RK_NoReduction, ///< Not a reduction. 320 RK_IntegerAdd, ///< Sum of integers. 321 RK_IntegerMult, ///< Product of integers. 322 RK_IntegerOr, ///< Bitwise or logical OR of numbers. 323 RK_IntegerAnd, ///< Bitwise or logical AND of numbers. 324 RK_IntegerXor, ///< Bitwise or logical XOR of numbers. 325 RK_FloatAdd, ///< Sum of floats. 326 RK_FloatMult ///< Product of floats. 327 }; 328 329 /// This enum represents the kinds of inductions that we support. 330 enum InductionKind { 331 IK_NoInduction, ///< Not an induction variable. 332 IK_IntInduction, ///< Integer induction variable. Step = 1. 333 IK_ReverseIntInduction, ///< Reverse int induction variable. Step = -1. 334 IK_PtrInduction, ///< Pointer induction var. Step = sizeof(elem). 335 IK_ReversePtrInduction ///< Reverse ptr indvar. Step = - sizeof(elem). 336 }; 337 338 /// This POD struct holds information about reduction variables. 339 struct ReductionDescriptor { 340 ReductionDescriptor() : StartValue(0), LoopExitInstr(0), 341 Kind(RK_NoReduction) {} 342 343 ReductionDescriptor(Value *Start, Instruction *Exit, ReductionKind K) 344 : StartValue(Start), LoopExitInstr(Exit), Kind(K) {} 345 346 // The starting value of the reduction. 347 // It does not have to be zero! 348 Value *StartValue; 349 // The instruction who's value is used outside the loop. 350 Instruction *LoopExitInstr; 351 // The kind of the reduction. 352 ReductionKind Kind; 353 }; 354 355 // This POD struct holds information about the memory runtime legality 356 // check that a group of pointers do not overlap. 357 struct RuntimePointerCheck { 358 RuntimePointerCheck() : Need(false) {} 359 360 /// Reset the state of the pointer runtime information. 361 void reset() { 362 Need = false; 363 Pointers.clear(); 364 Starts.clear(); 365 Ends.clear(); 366 } 367 368 /// Insert a pointer and calculate the start and end SCEVs. 369 void insert(ScalarEvolution *SE, Loop *Lp, Value *Ptr); 370 371 /// This flag indicates if we need to add the runtime check. 372 bool Need; 373 /// Holds the pointers that we need to check. 374 SmallVector<Value*, 2> Pointers; 375 /// Holds the pointer value at the beginning of the loop. 376 SmallVector<const SCEV*, 2> Starts; 377 /// Holds the pointer value at the end of the loop. 378 SmallVector<const SCEV*, 2> Ends; 379 }; 380 381 /// A POD for saving information about induction variables. 382 struct InductionInfo { 383 InductionInfo(Value *Start, InductionKind K) : StartValue(Start), IK(K) {} 384 InductionInfo() : StartValue(0), IK(IK_NoInduction) {} 385 /// Start value. 386 Value *StartValue; 387 /// Induction kind. 388 InductionKind IK; 389 }; 390 391 /// ReductionList contains the reduction descriptors for all 392 /// of the reductions that were found in the loop. 393 typedef DenseMap<PHINode*, ReductionDescriptor> ReductionList; 394 395 /// InductionList saves induction variables and maps them to the 396 /// induction descriptor. 397 typedef MapVector<PHINode*, InductionInfo> InductionList; 398 399 /// Returns true if it is legal to vectorize this loop. 400 /// This does not mean that it is profitable to vectorize this 401 /// loop, only that it is legal to do so. 402 bool canVectorize(); 403 404 /// Returns the Induction variable. 405 PHINode *getInduction() { return Induction; } 406 407 /// Returns the reduction variables found in the loop. 408 ReductionList *getReductionVars() { return &Reductions; } 409 410 /// Returns the induction variables found in the loop. 411 InductionList *getInductionVars() { return &Inductions; } 412 413 /// Returns True if V is an induction variable in this loop. 414 bool isInductionVariable(const Value *V); 415 416 /// Return true if the block BB needs to be predicated in order for the loop 417 /// to be vectorized. 418 bool blockNeedsPredication(BasicBlock *BB); 419 420 /// Check if this pointer is consecutive when vectorizing. This happens 421 /// when the last index of the GEP is the induction variable, or that the 422 /// pointer itself is an induction variable. 423 /// This check allows us to vectorize A[idx] into a wide load/store. 424 /// Returns: 425 /// 0 - Stride is unknown or non consecutive. 426 /// 1 - Address is consecutive. 427 /// -1 - Address is consecutive, and decreasing. 428 int isConsecutivePtr(Value *Ptr); 429 430 /// Returns true if the value V is uniform within the loop. 431 bool isUniform(Value *V); 432 433 /// Returns true if this instruction will remain scalar after vectorization. 434 bool isUniformAfterVectorization(Instruction* I) { return Uniforms.count(I); } 435 436 /// Returns the information that we collected about runtime memory check. 437 RuntimePointerCheck *getRuntimePointerCheck() { return &PtrRtCheck; } 438 private: 439 /// Check if a single basic block loop is vectorizable. 440 /// At this point we know that this is a loop with a constant trip count 441 /// and we only need to check individual instructions. 442 bool canVectorizeInstrs(); 443 444 /// When we vectorize loops we may change the order in which 445 /// we read and write from memory. This method checks if it is 446 /// legal to vectorize the code, considering only memory constrains. 447 /// Returns true if the loop is vectorizable 448 bool canVectorizeMemory(); 449 450 /// Return true if we can vectorize this loop using the IF-conversion 451 /// transformation. 452 bool canVectorizeWithIfConvert(); 453 454 /// Collect the variables that need to stay uniform after vectorization. 455 void collectLoopUniforms(); 456 457 /// Return true if all of the instructions in the block can be speculatively 458 /// executed. 459 bool blockCanBePredicated(BasicBlock *BB); 460 461 /// Returns True, if 'Phi' is the kind of reduction variable for type 462 /// 'Kind'. If this is a reduction variable, it adds it to ReductionList. 463 bool AddReductionVar(PHINode *Phi, ReductionKind Kind); 464 /// Returns true if the instruction I can be a reduction variable of type 465 /// 'Kind'. 466 bool isReductionInstr(Instruction *I, ReductionKind Kind); 467 /// Returns the induction kind of Phi. This function may return NoInduction 468 /// if the PHI is not an induction variable. 469 InductionKind isInductionVariable(PHINode *Phi); 470 /// Return true if can compute the address bounds of Ptr within the loop. 471 bool hasComputableBounds(Value *Ptr); 472 473 /// The loop that we evaluate. 474 Loop *TheLoop; 475 /// Scev analysis. 476 ScalarEvolution *SE; 477 /// DataLayout analysis. 478 DataLayout *DL; 479 // Dominators. 480 DominatorTree *DT; 481 482 // --- vectorization state --- // 483 484 /// Holds the integer induction variable. This is the counter of the 485 /// loop. 486 PHINode *Induction; 487 /// Holds the reduction variables. 488 ReductionList Reductions; 489 /// Holds all of the induction variables that we found in the loop. 490 /// Notice that inductions don't need to start at zero and that induction 491 /// variables can be pointers. 492 InductionList Inductions; 493 494 /// Allowed outside users. This holds the reduction 495 /// vars which can be accessed from outside the loop. 496 SmallPtrSet<Value*, 4> AllowedExit; 497 /// This set holds the variables which are known to be uniform after 498 /// vectorization. 499 SmallPtrSet<Instruction*, 4> Uniforms; 500 /// We need to check that all of the pointers in this list are disjoint 501 /// at runtime. 502 RuntimePointerCheck PtrRtCheck; 503 }; 504 505 /// LoopVectorizationCostModel - estimates the expected speedups due to 506 /// vectorization. 507 /// In many cases vectorization is not profitable. This can happen because of 508 /// a number of reasons. In this class we mainly attempt to predict the 509 /// expected speedup/slowdowns due to the supported instruction set. We use the 510 /// TargetTransformInfo to query the different backends for the cost of 511 /// different operations. 512 class LoopVectorizationCostModel { 513 public: 514 LoopVectorizationCostModel(Loop *L, ScalarEvolution *SE, LoopInfo *LI, 515 LoopVectorizationLegality *Legal, 516 const TargetTransformInfo &TTI) 517 : TheLoop(L), SE(SE), LI(LI), Legal(Legal), TTI(TTI) {} 518 519 /// Information about vectorization costs 520 struct VectorizationFactor { 521 unsigned Width; // Vector width with best cost 522 unsigned Cost; // Cost of the loop with that width 523 }; 524 /// \return The most profitable vectorization factor and the cost of that VF. 525 /// This method checks every power of two up to VF. If UserVF is not ZERO 526 /// then this vectorization factor will be selected if vectorization is 527 /// possible. 528 VectorizationFactor selectVectorizationFactor(bool OptForSize, unsigned UserVF); 529 530 /// \return The size (in bits) of the widest type in the code that 531 /// needs to be vectorized. We ignore values that remain scalar such as 532 /// 64 bit loop indices. 533 unsigned getWidestType(); 534 535 /// \return The most profitable unroll factor. 536 /// If UserUF is non-zero then this method finds the best unroll-factor 537 /// based on register pressure and other parameters. 538 /// VF and LoopCost are the selected vectorization factor and the cost of the 539 /// selected VF. 540 unsigned selectUnrollFactor(bool OptForSize, unsigned UserUF, unsigned VF, 541 unsigned LoopCost); 542 543 /// \brief A struct that represents some properties of the register usage 544 /// of a loop. 545 struct RegisterUsage { 546 /// Holds the number of loop invariant values that are used in the loop. 547 unsigned LoopInvariantRegs; 548 /// Holds the maximum number of concurrent live intervals in the loop. 549 unsigned MaxLocalUsers; 550 /// Holds the number of instructions in the loop. 551 unsigned NumInstructions; 552 }; 553 554 /// \return information about the register usage of the loop. 555 RegisterUsage calculateRegisterUsage(); 556 557 private: 558 /// Returns the expected execution cost. The unit of the cost does 559 /// not matter because we use the 'cost' units to compare different 560 /// vector widths. The cost that is returned is *not* normalized by 561 /// the factor width. 562 unsigned expectedCost(unsigned VF); 563 564 /// Returns the execution time cost of an instruction for a given vector 565 /// width. Vector width of one means scalar. 566 unsigned getInstructionCost(Instruction *I, unsigned VF); 567 568 /// A helper function for converting Scalar types to vector types. 569 /// If the incoming type is void, we return void. If the VF is 1, we return 570 /// the scalar type. 571 static Type* ToVectorTy(Type *Scalar, unsigned VF); 572 573 /// The loop that we evaluate. 574 Loop *TheLoop; 575 /// Scev analysis. 576 ScalarEvolution *SE; 577 /// Loop Info analysis. 578 LoopInfo *LI; 579 /// Vectorization legality. 580 LoopVectorizationLegality *Legal; 581 /// Vector target information. 582 const TargetTransformInfo &TTI; 583 }; 584 585 /// The LoopVectorize Pass. 586 struct LoopVectorize : public LoopPass { 587 /// Pass identification, replacement for typeid 588 static char ID; 589 590 explicit LoopVectorize() : LoopPass(ID) { 591 initializeLoopVectorizePass(*PassRegistry::getPassRegistry()); 592 } 593 594 ScalarEvolution *SE; 595 DataLayout *DL; 596 LoopInfo *LI; 597 TargetTransformInfo *TTI; 598 DominatorTree *DT; 599 600 virtual bool runOnLoop(Loop *L, LPPassManager &LPM) { 601 // We only vectorize innermost loops. 602 if (!L->empty()) 603 return false; 604 605 SE = &getAnalysis<ScalarEvolution>(); 606 DL = getAnalysisIfAvailable<DataLayout>(); 607 LI = &getAnalysis<LoopInfo>(); 608 TTI = &getAnalysis<TargetTransformInfo>(); 609 DT = &getAnalysis<DominatorTree>(); 610 611 DEBUG(dbgs() << "LV: Checking a loop in \"" << 612 L->getHeader()->getParent()->getName() << "\"\n"); 613 614 // Check if it is legal to vectorize the loop. 615 LoopVectorizationLegality LVL(L, SE, DL, DT); 616 if (!LVL.canVectorize()) { 617 DEBUG(dbgs() << "LV: Not vectorizing.\n"); 618 return false; 619 } 620 621 // Use the cost model. 622 LoopVectorizationCostModel CM(L, SE, LI, &LVL, *TTI); 623 624 // Check the function attribues to find out if this function should be 625 // optimized for size. 626 Function *F = L->getHeader()->getParent(); 627 Attribute::AttrKind SzAttr = Attribute::OptimizeForSize; 628 Attribute::AttrKind FlAttr = Attribute::NoImplicitFloat; 629 unsigned FnIndex = AttributeSet::FunctionIndex; 630 bool OptForSize = F->getAttributes().hasAttribute(FnIndex, SzAttr); 631 bool NoFloat = F->getAttributes().hasAttribute(FnIndex, FlAttr); 632 633 if (NoFloat) { 634 DEBUG(dbgs() << "LV: Can't vectorize when the NoImplicitFloat" 635 "attribute is used.\n"); 636 return false; 637 } 638 639 // Select the optimal vectorization factor. 640 LoopVectorizationCostModel::VectorizationFactor VF; 641 VF = CM.selectVectorizationFactor(OptForSize, VectorizationFactor); 642 // Select the unroll factor. 643 unsigned UF = CM.selectUnrollFactor(OptForSize, VectorizationUnroll, 644 VF.Width, VF.Cost); 645 646 if (VF.Width == 1) { 647 DEBUG(dbgs() << "LV: Vectorization is possible but not beneficial.\n"); 648 return false; 649 } 650 651 DEBUG(dbgs() << "LV: Found a vectorizable loop ("<< VF.Width << ") in "<< 652 F->getParent()->getModuleIdentifier()<<"\n"); 653 DEBUG(dbgs() << "LV: Unroll Factor is " << UF << "\n"); 654 655 // If we decided that it is *legal* to vectorizer the loop then do it. 656 InnerLoopVectorizer LB(L, SE, LI, DT, DL, VF.Width, UF); 657 LB.vectorize(&LVL); 658 659 DEBUG(verifyFunction(*L->getHeader()->getParent())); 660 return true; 661 } 662 663 virtual void getAnalysisUsage(AnalysisUsage &AU) const { 664 LoopPass::getAnalysisUsage(AU); 665 AU.addRequiredID(LoopSimplifyID); 666 AU.addRequiredID(LCSSAID); 667 AU.addRequired<DominatorTree>(); 668 AU.addRequired<LoopInfo>(); 669 AU.addRequired<ScalarEvolution>(); 670 AU.addRequired<TargetTransformInfo>(); 671 AU.addPreserved<LoopInfo>(); 672 AU.addPreserved<DominatorTree>(); 673 } 674 675 }; 676 677 } // end anonymous namespace 678 679 //===----------------------------------------------------------------------===// 680 // Implementation of LoopVectorizationLegality, InnerLoopVectorizer and 681 // LoopVectorizationCostModel. 682 //===----------------------------------------------------------------------===// 683 684 void 685 LoopVectorizationLegality::RuntimePointerCheck::insert(ScalarEvolution *SE, 686 Loop *Lp, Value *Ptr) { 687 const SCEV *Sc = SE->getSCEV(Ptr); 688 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Sc); 689 assert(AR && "Invalid addrec expression"); 690 const SCEV *Ex = SE->getExitCount(Lp, Lp->getLoopLatch()); 691 const SCEV *ScEnd = AR->evaluateAtIteration(Ex, *SE); 692 Pointers.push_back(Ptr); 693 Starts.push_back(AR->getStart()); 694 Ends.push_back(ScEnd); 695 } 696 697 Value *InnerLoopVectorizer::getBroadcastInstrs(Value *V) { 698 // Save the current insertion location. 699 Instruction *Loc = Builder.GetInsertPoint(); 700 701 // We need to place the broadcast of invariant variables outside the loop. 702 Instruction *Instr = dyn_cast<Instruction>(V); 703 bool NewInstr = (Instr && Instr->getParent() == LoopVectorBody); 704 bool Invariant = OrigLoop->isLoopInvariant(V) && !NewInstr; 705 706 // Place the code for broadcasting invariant variables in the new preheader. 707 if (Invariant) 708 Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator()); 709 710 // Broadcast the scalar into all locations in the vector. 711 Value *Shuf = Builder.CreateVectorSplat(VF, V, "broadcast"); 712 713 // Restore the builder insertion point. 714 if (Invariant) 715 Builder.SetInsertPoint(Loc); 716 717 return Shuf; 718 } 719 720 Value *InnerLoopVectorizer::getConsecutiveVector(Value* Val, unsigned StartIdx, 721 bool Negate) { 722 assert(Val->getType()->isVectorTy() && "Must be a vector"); 723 assert(Val->getType()->getScalarType()->isIntegerTy() && 724 "Elem must be an integer"); 725 // Create the types. 726 Type *ITy = Val->getType()->getScalarType(); 727 VectorType *Ty = cast<VectorType>(Val->getType()); 728 int VLen = Ty->getNumElements(); 729 SmallVector<Constant*, 8> Indices; 730 731 // Create a vector of consecutive numbers from zero to VF. 732 for (int i = 0; i < VLen; ++i) { 733 int Idx = Negate ? (-i): i; 734 Indices.push_back(ConstantInt::get(ITy, StartIdx + Idx)); 735 } 736 737 // Add the consecutive indices to the vector value. 738 Constant *Cv = ConstantVector::get(Indices); 739 assert(Cv->getType() == Val->getType() && "Invalid consecutive vec"); 740 return Builder.CreateAdd(Val, Cv, "induction"); 741 } 742 743 int LoopVectorizationLegality::isConsecutivePtr(Value *Ptr) { 744 assert(Ptr->getType()->isPointerTy() && "Unexpected non ptr"); 745 // Make sure that the pointer does not point to structs. 746 if (cast<PointerType>(Ptr->getType())->getElementType()->isAggregateType()) 747 return 0; 748 749 // If this value is a pointer induction variable we know it is consecutive. 750 PHINode *Phi = dyn_cast_or_null<PHINode>(Ptr); 751 if (Phi && Inductions.count(Phi)) { 752 InductionInfo II = Inductions[Phi]; 753 if (IK_PtrInduction == II.IK) 754 return 1; 755 else if (IK_ReversePtrInduction == II.IK) 756 return -1; 757 } 758 759 GetElementPtrInst *Gep = dyn_cast_or_null<GetElementPtrInst>(Ptr); 760 if (!Gep) 761 return 0; 762 763 unsigned NumOperands = Gep->getNumOperands(); 764 Value *LastIndex = Gep->getOperand(NumOperands - 1); 765 766 Value *GpPtr = Gep->getPointerOperand(); 767 // If this GEP value is a consecutive pointer induction variable and all of 768 // the indices are constant then we know it is consecutive. We can 769 Phi = dyn_cast<PHINode>(GpPtr); 770 if (Phi && Inductions.count(Phi)) { 771 772 // Make sure that the pointer does not point to structs. 773 PointerType *GepPtrType = cast<PointerType>(GpPtr->getType()); 774 if (GepPtrType->getElementType()->isAggregateType()) 775 return 0; 776 777 // Make sure that all of the index operands are loop invariant. 778 for (unsigned i = 1; i < NumOperands; ++i) 779 if (!SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop)) 780 return 0; 781 782 InductionInfo II = Inductions[Phi]; 783 if (IK_PtrInduction == II.IK) 784 return 1; 785 else if (IK_ReversePtrInduction == II.IK) 786 return -1; 787 } 788 789 // Check that all of the gep indices are uniform except for the last. 790 for (unsigned i = 0; i < NumOperands - 1; ++i) 791 if (!SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop)) 792 return 0; 793 794 // We can emit wide load/stores only if the last index is the induction 795 // variable. 796 const SCEV *Last = SE->getSCEV(LastIndex); 797 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Last)) { 798 const SCEV *Step = AR->getStepRecurrence(*SE); 799 800 // The memory is consecutive because the last index is consecutive 801 // and all other indices are loop invariant. 802 if (Step->isOne()) 803 return 1; 804 if (Step->isAllOnesValue()) 805 return -1; 806 } 807 808 return 0; 809 } 810 811 bool LoopVectorizationLegality::isUniform(Value *V) { 812 return (SE->isLoopInvariant(SE->getSCEV(V), TheLoop)); 813 } 814 815 InnerLoopVectorizer::VectorParts& 816 InnerLoopVectorizer::getVectorValue(Value *V) { 817 assert(V != Induction && "The new induction variable should not be used."); 818 assert(!V->getType()->isVectorTy() && "Can't widen a vector"); 819 820 // If we have this scalar in the map, return it. 821 if (WidenMap.has(V)) 822 return WidenMap.get(V); 823 824 // If this scalar is unknown, assume that it is a constant or that it is 825 // loop invariant. Broadcast V and save the value for future uses. 826 Value *B = getBroadcastInstrs(V); 827 WidenMap.splat(V, B); 828 return WidenMap.get(V); 829 } 830 831 Value *InnerLoopVectorizer::reverseVector(Value *Vec) { 832 assert(Vec->getType()->isVectorTy() && "Invalid type"); 833 SmallVector<Constant*, 8> ShuffleMask; 834 for (unsigned i = 0; i < VF; ++i) 835 ShuffleMask.push_back(Builder.getInt32(VF - i - 1)); 836 837 return Builder.CreateShuffleVector(Vec, UndefValue::get(Vec->getType()), 838 ConstantVector::get(ShuffleMask), 839 "reverse"); 840 } 841 842 843 void InnerLoopVectorizer::vectorizeMemoryInstruction(Instruction *Instr, 844 LoopVectorizationLegality *Legal) { 845 // Attempt to issue a wide load. 846 LoadInst *LI = dyn_cast<LoadInst>(Instr); 847 StoreInst *SI = dyn_cast<StoreInst>(Instr); 848 849 assert((LI || SI) && "Invalid Load/Store instruction"); 850 851 Type *ScalarDataTy = LI ? LI->getType() : SI->getValueOperand()->getType(); 852 Type *DataTy = VectorType::get(ScalarDataTy, VF); 853 Value *Ptr = LI ? LI->getPointerOperand() : SI->getPointerOperand(); 854 unsigned Alignment = LI ? LI->getAlignment() : SI->getAlignment(); 855 856 // If the pointer is loop invariant or if it is non consecutive, 857 // scalarize the load. 858 int Stride = Legal->isConsecutivePtr(Ptr); 859 bool Reverse = Stride < 0; 860 bool UniformLoad = LI && Legal->isUniform(Ptr); 861 if (Stride == 0 || UniformLoad) 862 return scalarizeInstruction(Instr); 863 864 Constant *Zero = Builder.getInt32(0); 865 VectorParts &Entry = WidenMap.get(Instr); 866 867 // Handle consecutive loads/stores. 868 GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr); 869 if (Gep && Legal->isInductionVariable(Gep->getPointerOperand())) { 870 Value *PtrOperand = Gep->getPointerOperand(); 871 Value *FirstBasePtr = getVectorValue(PtrOperand)[0]; 872 FirstBasePtr = Builder.CreateExtractElement(FirstBasePtr, Zero); 873 874 // Create the new GEP with the new induction variable. 875 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone()); 876 Gep2->setOperand(0, FirstBasePtr); 877 Gep2->setName("gep.indvar.base"); 878 Ptr = Builder.Insert(Gep2); 879 } else if (Gep) { 880 assert(SE->isLoopInvariant(SE->getSCEV(Gep->getPointerOperand()), 881 OrigLoop) && "Base ptr must be invariant"); 882 883 // The last index does not have to be the induction. It can be 884 // consecutive and be a function of the index. For example A[I+1]; 885 unsigned NumOperands = Gep->getNumOperands(); 886 887 Value *LastGepOperand = Gep->getOperand(NumOperands - 1); 888 VectorParts &GEPParts = getVectorValue(LastGepOperand); 889 Value *LastIndex = GEPParts[0]; 890 LastIndex = Builder.CreateExtractElement(LastIndex, Zero); 891 892 // Create the new GEP with the new induction variable. 893 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone()); 894 Gep2->setOperand(NumOperands - 1, LastIndex); 895 Gep2->setName("gep.indvar.idx"); 896 Ptr = Builder.Insert(Gep2); 897 } else { 898 // Use the induction element ptr. 899 assert(isa<PHINode>(Ptr) && "Invalid induction ptr"); 900 VectorParts &PtrVal = getVectorValue(Ptr); 901 Ptr = Builder.CreateExtractElement(PtrVal[0], Zero); 902 } 903 904 // Handle Stores: 905 if (SI) { 906 assert(!Legal->isUniform(SI->getPointerOperand()) && 907 "We do not allow storing to uniform addresses"); 908 909 VectorParts &StoredVal = getVectorValue(SI->getValueOperand()); 910 for (unsigned Part = 0; Part < UF; ++Part) { 911 // Calculate the pointer for the specific unroll-part. 912 Value *PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(Part * VF)); 913 914 if (Reverse) { 915 // If we store to reverse consecutive memory locations then we need 916 // to reverse the order of elements in the stored value. 917 StoredVal[Part] = reverseVector(StoredVal[Part]); 918 // If the address is consecutive but reversed, then the 919 // wide store needs to start at the last vector element. 920 PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(-Part * VF)); 921 PartPtr = Builder.CreateGEP(PartPtr, Builder.getInt32(1 - VF)); 922 } 923 924 Value *VecPtr = Builder.CreateBitCast(PartPtr, DataTy->getPointerTo()); 925 Builder.CreateStore(StoredVal[Part], VecPtr)->setAlignment(Alignment); 926 } 927 } 928 929 for (unsigned Part = 0; Part < UF; ++Part) { 930 // Calculate the pointer for the specific unroll-part. 931 Value *PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(Part * VF)); 932 933 if (Reverse) { 934 // If the address is consecutive but reversed, then the 935 // wide store needs to start at the last vector element. 936 PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(-Part * VF)); 937 PartPtr = Builder.CreateGEP(PartPtr, Builder.getInt32(1 - VF)); 938 } 939 940 Value *VecPtr = Builder.CreateBitCast(PartPtr, DataTy->getPointerTo()); 941 Value *LI = Builder.CreateLoad(VecPtr, "wide.load"); 942 cast<LoadInst>(LI)->setAlignment(Alignment); 943 Entry[Part] = Reverse ? reverseVector(LI) : LI; 944 } 945 } 946 947 void InnerLoopVectorizer::scalarizeInstruction(Instruction *Instr) { 948 assert(!Instr->getType()->isAggregateType() && "Can't handle vectors"); 949 // Holds vector parameters or scalars, in case of uniform vals. 950 SmallVector<VectorParts, 4> Params; 951 952 // Find all of the vectorized parameters. 953 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) { 954 Value *SrcOp = Instr->getOperand(op); 955 956 // If we are accessing the old induction variable, use the new one. 957 if (SrcOp == OldInduction) { 958 Params.push_back(getVectorValue(SrcOp)); 959 continue; 960 } 961 962 // Try using previously calculated values. 963 Instruction *SrcInst = dyn_cast<Instruction>(SrcOp); 964 965 // If the src is an instruction that appeared earlier in the basic block 966 // then it should already be vectorized. 967 if (SrcInst && OrigLoop->contains(SrcInst)) { 968 assert(WidenMap.has(SrcInst) && "Source operand is unavailable"); 969 // The parameter is a vector value from earlier. 970 Params.push_back(WidenMap.get(SrcInst)); 971 } else { 972 // The parameter is a scalar from outside the loop. Maybe even a constant. 973 VectorParts Scalars; 974 Scalars.append(UF, SrcOp); 975 Params.push_back(Scalars); 976 } 977 } 978 979 assert(Params.size() == Instr->getNumOperands() && 980 "Invalid number of operands"); 981 982 // Does this instruction return a value ? 983 bool IsVoidRetTy = Instr->getType()->isVoidTy(); 984 985 Value *UndefVec = IsVoidRetTy ? 0 : 986 UndefValue::get(VectorType::get(Instr->getType(), VF)); 987 // Create a new entry in the WidenMap and initialize it to Undef or Null. 988 VectorParts &VecResults = WidenMap.splat(Instr, UndefVec); 989 990 // For each scalar that we create: 991 for (unsigned Width = 0; Width < VF; ++Width) { 992 // For each vector unroll 'part': 993 for (unsigned Part = 0; Part < UF; ++Part) { 994 Instruction *Cloned = Instr->clone(); 995 if (!IsVoidRetTy) 996 Cloned->setName(Instr->getName() + ".cloned"); 997 // Replace the operands of the cloned instrucions with extracted scalars. 998 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) { 999 Value *Op = Params[op][Part]; 1000 // Param is a vector. Need to extract the right lane. 1001 if (Op->getType()->isVectorTy()) 1002 Op = Builder.CreateExtractElement(Op, Builder.getInt32(Width)); 1003 Cloned->setOperand(op, Op); 1004 } 1005 1006 // Place the cloned scalar in the new loop. 1007 Builder.Insert(Cloned); 1008 1009 // If the original scalar returns a value we need to place it in a vector 1010 // so that future users will be able to use it. 1011 if (!IsVoidRetTy) 1012 VecResults[Part] = Builder.CreateInsertElement(VecResults[Part], Cloned, 1013 Builder.getInt32(Width)); 1014 } 1015 } 1016 } 1017 1018 Instruction * 1019 InnerLoopVectorizer::addRuntimeCheck(LoopVectorizationLegality *Legal, 1020 Instruction *Loc) { 1021 LoopVectorizationLegality::RuntimePointerCheck *PtrRtCheck = 1022 Legal->getRuntimePointerCheck(); 1023 1024 if (!PtrRtCheck->Need) 1025 return NULL; 1026 1027 Instruction *MemoryRuntimeCheck = 0; 1028 unsigned NumPointers = PtrRtCheck->Pointers.size(); 1029 SmallVector<Value* , 2> Starts; 1030 SmallVector<Value* , 2> Ends; 1031 1032 SCEVExpander Exp(*SE, "induction"); 1033 1034 // Use this type for pointer arithmetic. 1035 Type* PtrArithTy = Type::getInt8PtrTy(Loc->getContext(), 0); 1036 1037 for (unsigned i = 0; i < NumPointers; ++i) { 1038 Value *Ptr = PtrRtCheck->Pointers[i]; 1039 const SCEV *Sc = SE->getSCEV(Ptr); 1040 1041 if (SE->isLoopInvariant(Sc, OrigLoop)) { 1042 DEBUG(dbgs() << "LV: Adding RT check for a loop invariant ptr:" << 1043 *Ptr <<"\n"); 1044 Starts.push_back(Ptr); 1045 Ends.push_back(Ptr); 1046 } else { 1047 DEBUG(dbgs() << "LV: Adding RT check for range:" << *Ptr <<"\n"); 1048 1049 Value *Start = Exp.expandCodeFor(PtrRtCheck->Starts[i], PtrArithTy, Loc); 1050 Value *End = Exp.expandCodeFor(PtrRtCheck->Ends[i], PtrArithTy, Loc); 1051 Starts.push_back(Start); 1052 Ends.push_back(End); 1053 } 1054 } 1055 1056 IRBuilder<> ChkBuilder(Loc); 1057 1058 for (unsigned i = 0; i < NumPointers; ++i) { 1059 for (unsigned j = i+1; j < NumPointers; ++j) { 1060 Value *Start0 = ChkBuilder.CreateBitCast(Starts[i], PtrArithTy, "bc"); 1061 Value *Start1 = ChkBuilder.CreateBitCast(Starts[j], PtrArithTy, "bc"); 1062 Value *End0 = ChkBuilder.CreateBitCast(Ends[i], PtrArithTy, "bc"); 1063 Value *End1 = ChkBuilder.CreateBitCast(Ends[j], PtrArithTy, "bc"); 1064 1065 Value *Cmp0 = ChkBuilder.CreateICmpULE(Start0, End1, "bound0"); 1066 Value *Cmp1 = ChkBuilder.CreateICmpULE(Start1, End0, "bound1"); 1067 Value *IsConflict = ChkBuilder.CreateAnd(Cmp0, Cmp1, "found.conflict"); 1068 if (MemoryRuntimeCheck) 1069 IsConflict = ChkBuilder.CreateOr(MemoryRuntimeCheck, IsConflict, 1070 "conflict.rdx"); 1071 1072 MemoryRuntimeCheck = cast<Instruction>(IsConflict); 1073 } 1074 } 1075 1076 return MemoryRuntimeCheck; 1077 } 1078 1079 void 1080 InnerLoopVectorizer::createEmptyLoop(LoopVectorizationLegality *Legal) { 1081 /* 1082 In this function we generate a new loop. The new loop will contain 1083 the vectorized instructions while the old loop will continue to run the 1084 scalar remainder. 1085 1086 [ ] <-- vector loop bypass (may consist of multiple blocks). 1087 / | 1088 / v 1089 | [ ] <-- vector pre header. 1090 | | 1091 | v 1092 | [ ] \ 1093 | [ ]_| <-- vector loop. 1094 | | 1095 \ v 1096 >[ ] <--- middle-block. 1097 / | 1098 / v 1099 | [ ] <--- new preheader. 1100 | | 1101 | v 1102 | [ ] \ 1103 | [ ]_| <-- old scalar loop to handle remainder. 1104 \ | 1105 \ v 1106 >[ ] <-- exit block. 1107 ... 1108 */ 1109 1110 BasicBlock *OldBasicBlock = OrigLoop->getHeader(); 1111 BasicBlock *BypassBlock = OrigLoop->getLoopPreheader(); 1112 BasicBlock *ExitBlock = OrigLoop->getExitBlock(); 1113 assert(ExitBlock && "Must have an exit block"); 1114 1115 // Some loops have a single integer induction variable, while other loops 1116 // don't. One example is c++ iterators that often have multiple pointer 1117 // induction variables. In the code below we also support a case where we 1118 // don't have a single induction variable. 1119 OldInduction = Legal->getInduction(); 1120 Type *IdxTy = OldInduction ? OldInduction->getType() : 1121 DL->getIntPtrType(SE->getContext()); 1122 1123 // Find the loop boundaries. 1124 const SCEV *ExitCount = SE->getExitCount(OrigLoop, OrigLoop->getLoopLatch()); 1125 assert(ExitCount != SE->getCouldNotCompute() && "Invalid loop count"); 1126 1127 // Get the total trip count from the count by adding 1. 1128 ExitCount = SE->getAddExpr(ExitCount, 1129 SE->getConstant(ExitCount->getType(), 1)); 1130 1131 // Expand the trip count and place the new instructions in the preheader. 1132 // Notice that the pre-header does not change, only the loop body. 1133 SCEVExpander Exp(*SE, "induction"); 1134 1135 // Count holds the overall loop count (N). 1136 Value *Count = Exp.expandCodeFor(ExitCount, ExitCount->getType(), 1137 BypassBlock->getTerminator()); 1138 1139 // The loop index does not have to start at Zero. Find the original start 1140 // value from the induction PHI node. If we don't have an induction variable 1141 // then we know that it starts at zero. 1142 Value *StartIdx = OldInduction ? 1143 OldInduction->getIncomingValueForBlock(BypassBlock): 1144 ConstantInt::get(IdxTy, 0); 1145 1146 assert(BypassBlock && "Invalid loop structure"); 1147 LoopBypassBlocks.push_back(BypassBlock); 1148 1149 // Split the single block loop into the two loop structure described above. 1150 BasicBlock *VectorPH = 1151 BypassBlock->splitBasicBlock(BypassBlock->getTerminator(), "vector.ph"); 1152 BasicBlock *VecBody = 1153 VectorPH->splitBasicBlock(VectorPH->getTerminator(), "vector.body"); 1154 BasicBlock *MiddleBlock = 1155 VecBody->splitBasicBlock(VecBody->getTerminator(), "middle.block"); 1156 BasicBlock *ScalarPH = 1157 MiddleBlock->splitBasicBlock(MiddleBlock->getTerminator(), "scalar.ph"); 1158 1159 // Use this IR builder to create the loop instructions (Phi, Br, Cmp) 1160 // inside the loop. 1161 Builder.SetInsertPoint(VecBody->getFirstInsertionPt()); 1162 1163 // Generate the induction variable. 1164 Induction = Builder.CreatePHI(IdxTy, 2, "index"); 1165 // The loop step is equal to the vectorization factor (num of SIMD elements) 1166 // times the unroll factor (num of SIMD instructions). 1167 Constant *Step = ConstantInt::get(IdxTy, VF * UF); 1168 1169 // This is the IR builder that we use to add all of the logic for bypassing 1170 // the new vector loop. 1171 IRBuilder<> BypassBuilder(BypassBlock->getTerminator()); 1172 1173 // We may need to extend the index in case there is a type mismatch. 1174 // We know that the count starts at zero and does not overflow. 1175 if (Count->getType() != IdxTy) { 1176 // The exit count can be of pointer type. Convert it to the correct 1177 // integer type. 1178 if (ExitCount->getType()->isPointerTy()) 1179 Count = BypassBuilder.CreatePointerCast(Count, IdxTy, "ptrcnt.to.int"); 1180 else 1181 Count = BypassBuilder.CreateZExtOrTrunc(Count, IdxTy, "cnt.cast"); 1182 } 1183 1184 // Add the start index to the loop count to get the new end index. 1185 Value *IdxEnd = BypassBuilder.CreateAdd(Count, StartIdx, "end.idx"); 1186 1187 // Now we need to generate the expression for N - (N % VF), which is 1188 // the part that the vectorized body will execute. 1189 Value *R = BypassBuilder.CreateURem(Count, Step, "n.mod.vf"); 1190 Value *CountRoundDown = BypassBuilder.CreateSub(Count, R, "n.vec"); 1191 Value *IdxEndRoundDown = BypassBuilder.CreateAdd(CountRoundDown, StartIdx, 1192 "end.idx.rnd.down"); 1193 1194 // Now, compare the new count to zero. If it is zero skip the vector loop and 1195 // jump to the scalar loop. 1196 Value *Cmp = BypassBuilder.CreateICmpEQ(IdxEndRoundDown, StartIdx, 1197 "cmp.zero"); 1198 1199 BasicBlock *LastBypassBlock = BypassBlock; 1200 1201 // Generate the code that checks in runtime if arrays overlap. We put the 1202 // checks into a separate block to make the more common case of few elements 1203 // faster. 1204 Instruction *MemRuntimeCheck = addRuntimeCheck(Legal, 1205 BypassBlock->getTerminator()); 1206 if (MemRuntimeCheck) { 1207 // Create a new block containing the memory check. 1208 BasicBlock *CheckBlock = BypassBlock->splitBasicBlock(MemRuntimeCheck, 1209 "vector.memcheck"); 1210 LoopBypassBlocks.push_back(CheckBlock); 1211 1212 // Replace the branch into the memory check block with a conditional branch 1213 // for the "few elements case". 1214 Instruction *OldTerm = BypassBlock->getTerminator(); 1215 BranchInst::Create(MiddleBlock, CheckBlock, Cmp, OldTerm); 1216 OldTerm->eraseFromParent(); 1217 1218 Cmp = MemRuntimeCheck; 1219 LastBypassBlock = CheckBlock; 1220 } 1221 1222 LastBypassBlock->getTerminator()->eraseFromParent(); 1223 BranchInst::Create(MiddleBlock, VectorPH, Cmp, 1224 LastBypassBlock); 1225 1226 // We are going to resume the execution of the scalar loop. 1227 // Go over all of the induction variables that we found and fix the 1228 // PHIs that are left in the scalar version of the loop. 1229 // The starting values of PHI nodes depend on the counter of the last 1230 // iteration in the vectorized loop. 1231 // If we come from a bypass edge then we need to start from the original 1232 // start value. 1233 1234 // This variable saves the new starting index for the scalar loop. 1235 PHINode *ResumeIndex = 0; 1236 LoopVectorizationLegality::InductionList::iterator I, E; 1237 LoopVectorizationLegality::InductionList *List = Legal->getInductionVars(); 1238 for (I = List->begin(), E = List->end(); I != E; ++I) { 1239 PHINode *OrigPhi = I->first; 1240 LoopVectorizationLegality::InductionInfo II = I->second; 1241 PHINode *ResumeVal = PHINode::Create(OrigPhi->getType(), 2, "resume.val", 1242 MiddleBlock->getTerminator()); 1243 Value *EndValue = 0; 1244 switch (II.IK) { 1245 case LoopVectorizationLegality::IK_NoInduction: 1246 llvm_unreachable("Unknown induction"); 1247 case LoopVectorizationLegality::IK_IntInduction: { 1248 // Handle the integer induction counter: 1249 assert(OrigPhi->getType()->isIntegerTy() && "Invalid type"); 1250 assert(OrigPhi == OldInduction && "Unknown integer PHI"); 1251 // We know what the end value is. 1252 EndValue = IdxEndRoundDown; 1253 // We also know which PHI node holds it. 1254 ResumeIndex = ResumeVal; 1255 break; 1256 } 1257 case LoopVectorizationLegality::IK_ReverseIntInduction: { 1258 // Convert the CountRoundDown variable to the PHI size. 1259 unsigned CRDSize = CountRoundDown->getType()->getScalarSizeInBits(); 1260 unsigned IISize = II.StartValue->getType()->getScalarSizeInBits(); 1261 Value *CRD = CountRoundDown; 1262 if (CRDSize > IISize) 1263 CRD = CastInst::Create(Instruction::Trunc, CountRoundDown, 1264 II.StartValue->getType(), "tr.crd", 1265 LoopBypassBlocks.back()->getTerminator()); 1266 else if (CRDSize < IISize) 1267 CRD = CastInst::Create(Instruction::SExt, CountRoundDown, 1268 II.StartValue->getType(), 1269 "sext.crd", 1270 LoopBypassBlocks.back()->getTerminator()); 1271 // Handle reverse integer induction counter: 1272 EndValue = 1273 BinaryOperator::CreateSub(II.StartValue, CRD, "rev.ind.end", 1274 LoopBypassBlocks.back()->getTerminator()); 1275 break; 1276 } 1277 case LoopVectorizationLegality::IK_PtrInduction: { 1278 // For pointer induction variables, calculate the offset using 1279 // the end index. 1280 EndValue = 1281 GetElementPtrInst::Create(II.StartValue, CountRoundDown, "ptr.ind.end", 1282 LoopBypassBlocks.back()->getTerminator()); 1283 break; 1284 } 1285 case LoopVectorizationLegality::IK_ReversePtrInduction: { 1286 // The value at the end of the loop for the reverse pointer is calculated 1287 // by creating a GEP with a negative index starting from the start value. 1288 Value *Zero = ConstantInt::get(CountRoundDown->getType(), 0); 1289 Value *NegIdx = BinaryOperator::CreateSub(Zero, CountRoundDown, 1290 "rev.ind.end", 1291 LoopBypassBlocks.back()->getTerminator()); 1292 EndValue = GetElementPtrInst::Create(II.StartValue, NegIdx, 1293 "rev.ptr.ind.end", 1294 LoopBypassBlocks.back()->getTerminator()); 1295 break; 1296 } 1297 }// end of case 1298 1299 // The new PHI merges the original incoming value, in case of a bypass, 1300 // or the value at the end of the vectorized loop. 1301 for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I) 1302 ResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[I]); 1303 ResumeVal->addIncoming(EndValue, VecBody); 1304 1305 // Fix the scalar body counter (PHI node). 1306 unsigned BlockIdx = OrigPhi->getBasicBlockIndex(ScalarPH); 1307 OrigPhi->setIncomingValue(BlockIdx, ResumeVal); 1308 } 1309 1310 // If we are generating a new induction variable then we also need to 1311 // generate the code that calculates the exit value. This value is not 1312 // simply the end of the counter because we may skip the vectorized body 1313 // in case of a runtime check. 1314 if (!OldInduction){ 1315 assert(!ResumeIndex && "Unexpected resume value found"); 1316 ResumeIndex = PHINode::Create(IdxTy, 2, "new.indc.resume.val", 1317 MiddleBlock->getTerminator()); 1318 for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I) 1319 ResumeIndex->addIncoming(StartIdx, LoopBypassBlocks[I]); 1320 ResumeIndex->addIncoming(IdxEndRoundDown, VecBody); 1321 } 1322 1323 // Make sure that we found the index where scalar loop needs to continue. 1324 assert(ResumeIndex && ResumeIndex->getType()->isIntegerTy() && 1325 "Invalid resume Index"); 1326 1327 // Add a check in the middle block to see if we have completed 1328 // all of the iterations in the first vector loop. 1329 // If (N - N%VF) == N, then we *don't* need to run the remainder. 1330 Value *CmpN = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, IdxEnd, 1331 ResumeIndex, "cmp.n", 1332 MiddleBlock->getTerminator()); 1333 1334 BranchInst::Create(ExitBlock, ScalarPH, CmpN, MiddleBlock->getTerminator()); 1335 // Remove the old terminator. 1336 MiddleBlock->getTerminator()->eraseFromParent(); 1337 1338 // Create i+1 and fill the PHINode. 1339 Value *NextIdx = Builder.CreateAdd(Induction, Step, "index.next"); 1340 Induction->addIncoming(StartIdx, VectorPH); 1341 Induction->addIncoming(NextIdx, VecBody); 1342 // Create the compare. 1343 Value *ICmp = Builder.CreateICmpEQ(NextIdx, IdxEndRoundDown); 1344 Builder.CreateCondBr(ICmp, MiddleBlock, VecBody); 1345 1346 // Now we have two terminators. Remove the old one from the block. 1347 VecBody->getTerminator()->eraseFromParent(); 1348 1349 // Get ready to start creating new instructions into the vectorized body. 1350 Builder.SetInsertPoint(VecBody->getFirstInsertionPt()); 1351 1352 // Create and register the new vector loop. 1353 Loop* Lp = new Loop(); 1354 Loop *ParentLoop = OrigLoop->getParentLoop(); 1355 1356 // Insert the new loop into the loop nest and register the new basic blocks. 1357 if (ParentLoop) { 1358 ParentLoop->addChildLoop(Lp); 1359 for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I) 1360 ParentLoop->addBasicBlockToLoop(LoopBypassBlocks[I], LI->getBase()); 1361 ParentLoop->addBasicBlockToLoop(ScalarPH, LI->getBase()); 1362 ParentLoop->addBasicBlockToLoop(VectorPH, LI->getBase()); 1363 ParentLoop->addBasicBlockToLoop(MiddleBlock, LI->getBase()); 1364 } else { 1365 LI->addTopLevelLoop(Lp); 1366 } 1367 1368 Lp->addBasicBlockToLoop(VecBody, LI->getBase()); 1369 1370 // Save the state. 1371 LoopVectorPreHeader = VectorPH; 1372 LoopScalarPreHeader = ScalarPH; 1373 LoopMiddleBlock = MiddleBlock; 1374 LoopExitBlock = ExitBlock; 1375 LoopVectorBody = VecBody; 1376 LoopScalarBody = OldBasicBlock; 1377 } 1378 1379 /// This function returns the identity element (or neutral element) for 1380 /// the operation K. 1381 static Constant* 1382 getReductionIdentity(LoopVectorizationLegality::ReductionKind K, Type *Tp) { 1383 switch (K) { 1384 case LoopVectorizationLegality:: RK_IntegerXor: 1385 case LoopVectorizationLegality:: RK_IntegerAdd: 1386 case LoopVectorizationLegality:: RK_IntegerOr: 1387 // Adding, Xoring, Oring zero to a number does not change it. 1388 return ConstantInt::get(Tp, 0); 1389 case LoopVectorizationLegality:: RK_IntegerMult: 1390 // Multiplying a number by 1 does not change it. 1391 return ConstantInt::get(Tp, 1); 1392 case LoopVectorizationLegality:: RK_IntegerAnd: 1393 // AND-ing a number with an all-1 value does not change it. 1394 return ConstantInt::get(Tp, -1, true); 1395 case LoopVectorizationLegality:: RK_FloatMult: 1396 // Multiplying a number by 1 does not change it. 1397 return ConstantFP::get(Tp, 1.0L); 1398 case LoopVectorizationLegality:: RK_FloatAdd: 1399 // Adding zero to a number does not change it. 1400 return ConstantFP::get(Tp, 0.0L); 1401 default: 1402 llvm_unreachable("Unknown reduction kind"); 1403 } 1404 } 1405 1406 static bool 1407 isTriviallyVectorizableIntrinsic(Instruction *Inst) { 1408 IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst); 1409 if (!II) 1410 return false; 1411 switch (II->getIntrinsicID()) { 1412 case Intrinsic::sqrt: 1413 case Intrinsic::sin: 1414 case Intrinsic::cos: 1415 case Intrinsic::exp: 1416 case Intrinsic::exp2: 1417 case Intrinsic::log: 1418 case Intrinsic::log10: 1419 case Intrinsic::log2: 1420 case Intrinsic::fabs: 1421 case Intrinsic::floor: 1422 case Intrinsic::ceil: 1423 case Intrinsic::trunc: 1424 case Intrinsic::rint: 1425 case Intrinsic::nearbyint: 1426 case Intrinsic::pow: 1427 case Intrinsic::fma: 1428 case Intrinsic::fmuladd: 1429 return true; 1430 default: 1431 return false; 1432 } 1433 return false; 1434 } 1435 1436 /// This function translates the reduction kind to an LLVM binary operator. 1437 static Instruction::BinaryOps 1438 getReductionBinOp(LoopVectorizationLegality::ReductionKind Kind) { 1439 switch (Kind) { 1440 case LoopVectorizationLegality::RK_IntegerAdd: 1441 return Instruction::Add; 1442 case LoopVectorizationLegality::RK_IntegerMult: 1443 return Instruction::Mul; 1444 case LoopVectorizationLegality::RK_IntegerOr: 1445 return Instruction::Or; 1446 case LoopVectorizationLegality::RK_IntegerAnd: 1447 return Instruction::And; 1448 case LoopVectorizationLegality::RK_IntegerXor: 1449 return Instruction::Xor; 1450 case LoopVectorizationLegality::RK_FloatMult: 1451 return Instruction::FMul; 1452 case LoopVectorizationLegality::RK_FloatAdd: 1453 return Instruction::FAdd; 1454 default: 1455 llvm_unreachable("Unknown reduction operation"); 1456 } 1457 } 1458 1459 void 1460 InnerLoopVectorizer::vectorizeLoop(LoopVectorizationLegality *Legal) { 1461 //===------------------------------------------------===// 1462 // 1463 // Notice: any optimization or new instruction that go 1464 // into the code below should be also be implemented in 1465 // the cost-model. 1466 // 1467 //===------------------------------------------------===// 1468 Constant *Zero = Builder.getInt32(0); 1469 1470 // In order to support reduction variables we need to be able to vectorize 1471 // Phi nodes. Phi nodes have cycles, so we need to vectorize them in two 1472 // stages. First, we create a new vector PHI node with no incoming edges. 1473 // We use this value when we vectorize all of the instructions that use the 1474 // PHI. Next, after all of the instructions in the block are complete we 1475 // add the new incoming edges to the PHI. At this point all of the 1476 // instructions in the basic block are vectorized, so we can use them to 1477 // construct the PHI. 1478 PhiVector RdxPHIsToFix; 1479 1480 // Scan the loop in a topological order to ensure that defs are vectorized 1481 // before users. 1482 LoopBlocksDFS DFS(OrigLoop); 1483 DFS.perform(LI); 1484 1485 // Vectorize all of the blocks in the original loop. 1486 for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(), 1487 be = DFS.endRPO(); bb != be; ++bb) 1488 vectorizeBlockInLoop(Legal, *bb, &RdxPHIsToFix); 1489 1490 // At this point every instruction in the original loop is widened to 1491 // a vector form. We are almost done. Now, we need to fix the PHI nodes 1492 // that we vectorized. The PHI nodes are currently empty because we did 1493 // not want to introduce cycles. Notice that the remaining PHI nodes 1494 // that we need to fix are reduction variables. 1495 1496 // Create the 'reduced' values for each of the induction vars. 1497 // The reduced values are the vector values that we scalarize and combine 1498 // after the loop is finished. 1499 for (PhiVector::iterator it = RdxPHIsToFix.begin(), e = RdxPHIsToFix.end(); 1500 it != e; ++it) { 1501 PHINode *RdxPhi = *it; 1502 assert(RdxPhi && "Unable to recover vectorized PHI"); 1503 1504 // Find the reduction variable descriptor. 1505 assert(Legal->getReductionVars()->count(RdxPhi) && 1506 "Unable to find the reduction variable"); 1507 LoopVectorizationLegality::ReductionDescriptor RdxDesc = 1508 (*Legal->getReductionVars())[RdxPhi]; 1509 1510 // We need to generate a reduction vector from the incoming scalar. 1511 // To do so, we need to generate the 'identity' vector and overide 1512 // one of the elements with the incoming scalar reduction. We need 1513 // to do it in the vector-loop preheader. 1514 Builder.SetInsertPoint(LoopBypassBlocks.back()->getTerminator()); 1515 1516 // This is the vector-clone of the value that leaves the loop. 1517 VectorParts &VectorExit = getVectorValue(RdxDesc.LoopExitInstr); 1518 Type *VecTy = VectorExit[0]->getType(); 1519 1520 // Find the reduction identity variable. Zero for addition, or, xor, 1521 // one for multiplication, -1 for And. 1522 Constant *Iden = getReductionIdentity(RdxDesc.Kind, VecTy->getScalarType()); 1523 Constant *Identity = ConstantVector::getSplat(VF, Iden); 1524 1525 // This vector is the Identity vector where the first element is the 1526 // incoming scalar reduction. 1527 Value *VectorStart = Builder.CreateInsertElement(Identity, 1528 RdxDesc.StartValue, Zero); 1529 1530 // Fix the vector-loop phi. 1531 // We created the induction variable so we know that the 1532 // preheader is the first entry. 1533 BasicBlock *VecPreheader = Induction->getIncomingBlock(0); 1534 1535 // Reductions do not have to start at zero. They can start with 1536 // any loop invariant values. 1537 VectorParts &VecRdxPhi = WidenMap.get(RdxPhi); 1538 BasicBlock *Latch = OrigLoop->getLoopLatch(); 1539 Value *LoopVal = RdxPhi->getIncomingValueForBlock(Latch); 1540 VectorParts &Val = getVectorValue(LoopVal); 1541 for (unsigned part = 0; part < UF; ++part) { 1542 // Make sure to add the reduction stat value only to the 1543 // first unroll part. 1544 Value *StartVal = (part == 0) ? VectorStart : Identity; 1545 cast<PHINode>(VecRdxPhi[part])->addIncoming(StartVal, VecPreheader); 1546 cast<PHINode>(VecRdxPhi[part])->addIncoming(Val[part], LoopVectorBody); 1547 } 1548 1549 // Before each round, move the insertion point right between 1550 // the PHIs and the values we are going to write. 1551 // This allows us to write both PHINodes and the extractelement 1552 // instructions. 1553 Builder.SetInsertPoint(LoopMiddleBlock->getFirstInsertionPt()); 1554 1555 VectorParts RdxParts; 1556 for (unsigned part = 0; part < UF; ++part) { 1557 // This PHINode contains the vectorized reduction variable, or 1558 // the initial value vector, if we bypass the vector loop. 1559 VectorParts &RdxExitVal = getVectorValue(RdxDesc.LoopExitInstr); 1560 PHINode *NewPhi = Builder.CreatePHI(VecTy, 2, "rdx.vec.exit.phi"); 1561 Value *StartVal = (part == 0) ? VectorStart : Identity; 1562 for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I) 1563 NewPhi->addIncoming(StartVal, LoopBypassBlocks[I]); 1564 NewPhi->addIncoming(RdxExitVal[part], LoopVectorBody); 1565 RdxParts.push_back(NewPhi); 1566 } 1567 1568 // Reduce all of the unrolled parts into a single vector. 1569 Value *ReducedPartRdx = RdxParts[0]; 1570 for (unsigned part = 1; part < UF; ++part) { 1571 Instruction::BinaryOps Op = getReductionBinOp(RdxDesc.Kind); 1572 ReducedPartRdx = Builder.CreateBinOp(Op, RdxParts[part], ReducedPartRdx, 1573 "bin.rdx"); 1574 } 1575 1576 // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles 1577 // and vector ops, reducing the set of values being computed by half each 1578 // round. 1579 assert(isPowerOf2_32(VF) && 1580 "Reduction emission only supported for pow2 vectors!"); 1581 Value *TmpVec = ReducedPartRdx; 1582 SmallVector<Constant*, 32> ShuffleMask(VF, 0); 1583 for (unsigned i = VF; i != 1; i >>= 1) { 1584 // Move the upper half of the vector to the lower half. 1585 for (unsigned j = 0; j != i/2; ++j) 1586 ShuffleMask[j] = Builder.getInt32(i/2 + j); 1587 1588 // Fill the rest of the mask with undef. 1589 std::fill(&ShuffleMask[i/2], ShuffleMask.end(), 1590 UndefValue::get(Builder.getInt32Ty())); 1591 1592 Value *Shuf = 1593 Builder.CreateShuffleVector(TmpVec, 1594 UndefValue::get(TmpVec->getType()), 1595 ConstantVector::get(ShuffleMask), 1596 "rdx.shuf"); 1597 1598 Instruction::BinaryOps Op = getReductionBinOp(RdxDesc.Kind); 1599 TmpVec = Builder.CreateBinOp(Op, TmpVec, Shuf, "bin.rdx"); 1600 } 1601 1602 // The result is in the first element of the vector. 1603 Value *Scalar0 = Builder.CreateExtractElement(TmpVec, Builder.getInt32(0)); 1604 1605 // Now, we need to fix the users of the reduction variable 1606 // inside and outside of the scalar remainder loop. 1607 // We know that the loop is in LCSSA form. We need to update the 1608 // PHI nodes in the exit blocks. 1609 for (BasicBlock::iterator LEI = LoopExitBlock->begin(), 1610 LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) { 1611 PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI); 1612 if (!LCSSAPhi) continue; 1613 1614 // All PHINodes need to have a single entry edge, or two if 1615 // we already fixed them. 1616 assert(LCSSAPhi->getNumIncomingValues() < 3 && "Invalid LCSSA PHI"); 1617 1618 // We found our reduction value exit-PHI. Update it with the 1619 // incoming bypass edge. 1620 if (LCSSAPhi->getIncomingValue(0) == RdxDesc.LoopExitInstr) { 1621 // Add an edge coming from the bypass. 1622 LCSSAPhi->addIncoming(Scalar0, LoopMiddleBlock); 1623 break; 1624 } 1625 }// end of the LCSSA phi scan. 1626 1627 // Fix the scalar loop reduction variable with the incoming reduction sum 1628 // from the vector body and from the backedge value. 1629 int IncomingEdgeBlockIdx = 1630 (RdxPhi)->getBasicBlockIndex(OrigLoop->getLoopLatch()); 1631 assert(IncomingEdgeBlockIdx >= 0 && "Invalid block index"); 1632 // Pick the other block. 1633 int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1); 1634 (RdxPhi)->setIncomingValue(SelfEdgeBlockIdx, Scalar0); 1635 (RdxPhi)->setIncomingValue(IncomingEdgeBlockIdx, RdxDesc.LoopExitInstr); 1636 }// end of for each redux variable. 1637 1638 // The Loop exit block may have single value PHI nodes where the incoming 1639 // value is 'undef'. While vectorizing we only handled real values that 1640 // were defined inside the loop. Here we handle the 'undef case'. 1641 // See PR14725. 1642 for (BasicBlock::iterator LEI = LoopExitBlock->begin(), 1643 LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) { 1644 PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI); 1645 if (!LCSSAPhi) continue; 1646 if (LCSSAPhi->getNumIncomingValues() == 1) 1647 LCSSAPhi->addIncoming(UndefValue::get(LCSSAPhi->getType()), 1648 LoopMiddleBlock); 1649 } 1650 } 1651 1652 InnerLoopVectorizer::VectorParts 1653 InnerLoopVectorizer::createEdgeMask(BasicBlock *Src, BasicBlock *Dst) { 1654 assert(std::find(pred_begin(Dst), pred_end(Dst), Src) != pred_end(Dst) && 1655 "Invalid edge"); 1656 1657 VectorParts SrcMask = createBlockInMask(Src); 1658 1659 // The terminator has to be a branch inst! 1660 BranchInst *BI = dyn_cast<BranchInst>(Src->getTerminator()); 1661 assert(BI && "Unexpected terminator found"); 1662 1663 if (BI->isConditional()) { 1664 VectorParts EdgeMask = getVectorValue(BI->getCondition()); 1665 1666 if (BI->getSuccessor(0) != Dst) 1667 for (unsigned part = 0; part < UF; ++part) 1668 EdgeMask[part] = Builder.CreateNot(EdgeMask[part]); 1669 1670 for (unsigned part = 0; part < UF; ++part) 1671 EdgeMask[part] = Builder.CreateAnd(EdgeMask[part], SrcMask[part]); 1672 return EdgeMask; 1673 } 1674 1675 return SrcMask; 1676 } 1677 1678 InnerLoopVectorizer::VectorParts 1679 InnerLoopVectorizer::createBlockInMask(BasicBlock *BB) { 1680 assert(OrigLoop->contains(BB) && "Block is not a part of a loop"); 1681 1682 // Loop incoming mask is all-one. 1683 if (OrigLoop->getHeader() == BB) { 1684 Value *C = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 1); 1685 return getVectorValue(C); 1686 } 1687 1688 // This is the block mask. We OR all incoming edges, and with zero. 1689 Value *Zero = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 0); 1690 VectorParts BlockMask = getVectorValue(Zero); 1691 1692 // For each pred: 1693 for (pred_iterator it = pred_begin(BB), e = pred_end(BB); it != e; ++it) { 1694 VectorParts EM = createEdgeMask(*it, BB); 1695 for (unsigned part = 0; part < UF; ++part) 1696 BlockMask[part] = Builder.CreateOr(BlockMask[part], EM[part]); 1697 } 1698 1699 return BlockMask; 1700 } 1701 1702 void 1703 InnerLoopVectorizer::vectorizeBlockInLoop(LoopVectorizationLegality *Legal, 1704 BasicBlock *BB, PhiVector *PV) { 1705 // For each instruction in the old loop. 1706 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) { 1707 VectorParts &Entry = WidenMap.get(it); 1708 switch (it->getOpcode()) { 1709 case Instruction::Br: 1710 // Nothing to do for PHIs and BR, since we already took care of the 1711 // loop control flow instructions. 1712 continue; 1713 case Instruction::PHI:{ 1714 PHINode* P = cast<PHINode>(it); 1715 // Handle reduction variables: 1716 if (Legal->getReductionVars()->count(P)) { 1717 for (unsigned part = 0; part < UF; ++part) { 1718 // This is phase one of vectorizing PHIs. 1719 Type *VecTy = VectorType::get(it->getType(), VF); 1720 Entry[part] = PHINode::Create(VecTy, 2, "vec.phi", 1721 LoopVectorBody-> getFirstInsertionPt()); 1722 } 1723 PV->push_back(P); 1724 continue; 1725 } 1726 1727 // Check for PHI nodes that are lowered to vector selects. 1728 if (P->getParent() != OrigLoop->getHeader()) { 1729 // We know that all PHIs in non header blocks are converted into 1730 // selects, so we don't have to worry about the insertion order and we 1731 // can just use the builder. 1732 1733 // At this point we generate the predication tree. There may be 1734 // duplications since this is a simple recursive scan, but future 1735 // optimizations will clean it up. 1736 VectorParts Cond = createEdgeMask(P->getIncomingBlock(0), 1737 P->getParent()); 1738 1739 for (unsigned part = 0; part < UF; ++part) { 1740 VectorParts &In0 = getVectorValue(P->getIncomingValue(0)); 1741 VectorParts &In1 = getVectorValue(P->getIncomingValue(1)); 1742 Entry[part] = Builder.CreateSelect(Cond[part], In0[part], In1[part], 1743 "predphi"); 1744 } 1745 continue; 1746 } 1747 1748 // This PHINode must be an induction variable. 1749 // Make sure that we know about it. 1750 assert(Legal->getInductionVars()->count(P) && 1751 "Not an induction variable"); 1752 1753 LoopVectorizationLegality::InductionInfo II = 1754 Legal->getInductionVars()->lookup(P); 1755 1756 switch (II.IK) { 1757 case LoopVectorizationLegality::IK_NoInduction: 1758 llvm_unreachable("Unknown induction"); 1759 case LoopVectorizationLegality::IK_IntInduction: { 1760 assert(P == OldInduction && "Unexpected PHI"); 1761 Value *Broadcasted = getBroadcastInstrs(Induction); 1762 // After broadcasting the induction variable we need to make the 1763 // vector consecutive by adding 0, 1, 2 ... 1764 for (unsigned part = 0; part < UF; ++part) 1765 Entry[part] = getConsecutiveVector(Broadcasted, VF * part, false); 1766 continue; 1767 } 1768 case LoopVectorizationLegality::IK_ReverseIntInduction: 1769 case LoopVectorizationLegality::IK_PtrInduction: 1770 case LoopVectorizationLegality::IK_ReversePtrInduction: 1771 // Handle reverse integer and pointer inductions. 1772 Value *StartIdx = 0; 1773 // If we have a single integer induction variable then use it. 1774 // Otherwise, start counting at zero. 1775 if (OldInduction) { 1776 LoopVectorizationLegality::InductionInfo OldII = 1777 Legal->getInductionVars()->lookup(OldInduction); 1778 StartIdx = OldII.StartValue; 1779 } else { 1780 StartIdx = ConstantInt::get(Induction->getType(), 0); 1781 } 1782 // This is the normalized GEP that starts counting at zero. 1783 Value *NormalizedIdx = Builder.CreateSub(Induction, StartIdx, 1784 "normalized.idx"); 1785 1786 // Handle the reverse integer induction variable case. 1787 if (LoopVectorizationLegality::IK_ReverseIntInduction == II.IK) { 1788 IntegerType *DstTy = cast<IntegerType>(II.StartValue->getType()); 1789 Value *CNI = Builder.CreateSExtOrTrunc(NormalizedIdx, DstTy, 1790 "resize.norm.idx"); 1791 Value *ReverseInd = Builder.CreateSub(II.StartValue, CNI, 1792 "reverse.idx"); 1793 1794 // This is a new value so do not hoist it out. 1795 Value *Broadcasted = getBroadcastInstrs(ReverseInd); 1796 // After broadcasting the induction variable we need to make the 1797 // vector consecutive by adding ... -3, -2, -1, 0. 1798 for (unsigned part = 0; part < UF; ++part) 1799 Entry[part] = getConsecutiveVector(Broadcasted, -VF * part, true); 1800 continue; 1801 } 1802 1803 // Handle the pointer induction variable case. 1804 assert(P->getType()->isPointerTy() && "Unexpected type."); 1805 1806 // Is this a reverse induction ptr or a consecutive induction ptr. 1807 bool Reverse = (LoopVectorizationLegality::IK_ReversePtrInduction == 1808 II.IK); 1809 1810 // This is the vector of results. Notice that we don't generate 1811 // vector geps because scalar geps result in better code. 1812 for (unsigned part = 0; part < UF; ++part) { 1813 Value *VecVal = UndefValue::get(VectorType::get(P->getType(), VF)); 1814 for (unsigned int i = 0; i < VF; ++i) { 1815 int EltIndex = (i + part * VF) * (Reverse ? -1 : 1); 1816 Constant *Idx = ConstantInt::get(Induction->getType(), EltIndex); 1817 Value *GlobalIdx; 1818 if (!Reverse) 1819 GlobalIdx = Builder.CreateAdd(NormalizedIdx, Idx, "gep.idx"); 1820 else 1821 GlobalIdx = Builder.CreateSub(Idx, NormalizedIdx, "gep.ridx"); 1822 1823 Value *SclrGep = Builder.CreateGEP(II.StartValue, GlobalIdx, 1824 "next.gep"); 1825 VecVal = Builder.CreateInsertElement(VecVal, SclrGep, 1826 Builder.getInt32(i), 1827 "insert.gep"); 1828 } 1829 Entry[part] = VecVal; 1830 } 1831 continue; 1832 } 1833 1834 }// End of PHI. 1835 1836 case Instruction::Add: 1837 case Instruction::FAdd: 1838 case Instruction::Sub: 1839 case Instruction::FSub: 1840 case Instruction::Mul: 1841 case Instruction::FMul: 1842 case Instruction::UDiv: 1843 case Instruction::SDiv: 1844 case Instruction::FDiv: 1845 case Instruction::URem: 1846 case Instruction::SRem: 1847 case Instruction::FRem: 1848 case Instruction::Shl: 1849 case Instruction::LShr: 1850 case Instruction::AShr: 1851 case Instruction::And: 1852 case Instruction::Or: 1853 case Instruction::Xor: { 1854 // Just widen binops. 1855 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(it); 1856 VectorParts &A = getVectorValue(it->getOperand(0)); 1857 VectorParts &B = getVectorValue(it->getOperand(1)); 1858 1859 // Use this vector value for all users of the original instruction. 1860 for (unsigned Part = 0; Part < UF; ++Part) { 1861 Value *V = Builder.CreateBinOp(BinOp->getOpcode(), A[Part], B[Part]); 1862 1863 // Update the NSW, NUW and Exact flags. Notice: V can be an Undef. 1864 BinaryOperator *VecOp = dyn_cast<BinaryOperator>(V); 1865 if (VecOp && isa<OverflowingBinaryOperator>(BinOp)) { 1866 VecOp->setHasNoSignedWrap(BinOp->hasNoSignedWrap()); 1867 VecOp->setHasNoUnsignedWrap(BinOp->hasNoUnsignedWrap()); 1868 } 1869 if (VecOp && isa<PossiblyExactOperator>(VecOp)) 1870 VecOp->setIsExact(BinOp->isExact()); 1871 1872 Entry[Part] = V; 1873 } 1874 break; 1875 } 1876 case Instruction::Select: { 1877 // Widen selects. 1878 // If the selector is loop invariant we can create a select 1879 // instruction with a scalar condition. Otherwise, use vector-select. 1880 bool InvariantCond = SE->isLoopInvariant(SE->getSCEV(it->getOperand(0)), 1881 OrigLoop); 1882 1883 // The condition can be loop invariant but still defined inside the 1884 // loop. This means that we can't just use the original 'cond' value. 1885 // We have to take the 'vectorized' value and pick the first lane. 1886 // Instcombine will make this a no-op. 1887 VectorParts &Cond = getVectorValue(it->getOperand(0)); 1888 VectorParts &Op0 = getVectorValue(it->getOperand(1)); 1889 VectorParts &Op1 = getVectorValue(it->getOperand(2)); 1890 Value *ScalarCond = Builder.CreateExtractElement(Cond[0], 1891 Builder.getInt32(0)); 1892 for (unsigned Part = 0; Part < UF; ++Part) { 1893 Entry[Part] = Builder.CreateSelect( 1894 InvariantCond ? ScalarCond : Cond[Part], 1895 Op0[Part], 1896 Op1[Part]); 1897 } 1898 break; 1899 } 1900 1901 case Instruction::ICmp: 1902 case Instruction::FCmp: { 1903 // Widen compares. Generate vector compares. 1904 bool FCmp = (it->getOpcode() == Instruction::FCmp); 1905 CmpInst *Cmp = dyn_cast<CmpInst>(it); 1906 VectorParts &A = getVectorValue(it->getOperand(0)); 1907 VectorParts &B = getVectorValue(it->getOperand(1)); 1908 for (unsigned Part = 0; Part < UF; ++Part) { 1909 Value *C = 0; 1910 if (FCmp) 1911 C = Builder.CreateFCmp(Cmp->getPredicate(), A[Part], B[Part]); 1912 else 1913 C = Builder.CreateICmp(Cmp->getPredicate(), A[Part], B[Part]); 1914 Entry[Part] = C; 1915 } 1916 break; 1917 } 1918 1919 case Instruction::Store: 1920 case Instruction::Load: 1921 vectorizeMemoryInstruction(it, Legal); 1922 break; 1923 case Instruction::ZExt: 1924 case Instruction::SExt: 1925 case Instruction::FPToUI: 1926 case Instruction::FPToSI: 1927 case Instruction::FPExt: 1928 case Instruction::PtrToInt: 1929 case Instruction::IntToPtr: 1930 case Instruction::SIToFP: 1931 case Instruction::UIToFP: 1932 case Instruction::Trunc: 1933 case Instruction::FPTrunc: 1934 case Instruction::BitCast: { 1935 CastInst *CI = dyn_cast<CastInst>(it); 1936 /// Optimize the special case where the source is the induction 1937 /// variable. Notice that we can only optimize the 'trunc' case 1938 /// because: a. FP conversions lose precision, b. sext/zext may wrap, 1939 /// c. other casts depend on pointer size. 1940 if (CI->getOperand(0) == OldInduction && 1941 it->getOpcode() == Instruction::Trunc) { 1942 Value *ScalarCast = Builder.CreateCast(CI->getOpcode(), Induction, 1943 CI->getType()); 1944 Value *Broadcasted = getBroadcastInstrs(ScalarCast); 1945 for (unsigned Part = 0; Part < UF; ++Part) 1946 Entry[Part] = getConsecutiveVector(Broadcasted, VF * Part, false); 1947 break; 1948 } 1949 /// Vectorize casts. 1950 Type *DestTy = VectorType::get(CI->getType()->getScalarType(), VF); 1951 1952 VectorParts &A = getVectorValue(it->getOperand(0)); 1953 for (unsigned Part = 0; Part < UF; ++Part) 1954 Entry[Part] = Builder.CreateCast(CI->getOpcode(), A[Part], DestTy); 1955 break; 1956 } 1957 1958 case Instruction::Call: { 1959 assert(isTriviallyVectorizableIntrinsic(it)); 1960 Module *M = BB->getParent()->getParent(); 1961 IntrinsicInst *II = cast<IntrinsicInst>(it); 1962 Intrinsic::ID ID = II->getIntrinsicID(); 1963 for (unsigned Part = 0; Part < UF; ++Part) { 1964 SmallVector<Value*, 4> Args; 1965 for (unsigned i = 0, ie = II->getNumArgOperands(); i != ie; ++i) { 1966 VectorParts &Arg = getVectorValue(II->getArgOperand(i)); 1967 Args.push_back(Arg[Part]); 1968 } 1969 Type *Tys[] = { VectorType::get(II->getType()->getScalarType(), VF) }; 1970 Function *F = Intrinsic::getDeclaration(M, ID, Tys); 1971 Entry[Part] = Builder.CreateCall(F, Args); 1972 } 1973 break; 1974 } 1975 1976 default: 1977 // All other instructions are unsupported. Scalarize them. 1978 scalarizeInstruction(it); 1979 break; 1980 }// end of switch. 1981 }// end of for_each instr. 1982 } 1983 1984 void InnerLoopVectorizer::updateAnalysis() { 1985 // Forget the original basic block. 1986 SE->forgetLoop(OrigLoop); 1987 1988 // Update the dominator tree information. 1989 assert(DT->properlyDominates(LoopBypassBlocks.front(), LoopExitBlock) && 1990 "Entry does not dominate exit."); 1991 1992 for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I) 1993 DT->addNewBlock(LoopBypassBlocks[I], LoopBypassBlocks[I-1]); 1994 DT->addNewBlock(LoopVectorPreHeader, LoopBypassBlocks.back()); 1995 DT->addNewBlock(LoopVectorBody, LoopVectorPreHeader); 1996 DT->addNewBlock(LoopMiddleBlock, LoopBypassBlocks.front()); 1997 DT->addNewBlock(LoopScalarPreHeader, LoopMiddleBlock); 1998 DT->changeImmediateDominator(LoopScalarBody, LoopScalarPreHeader); 1999 DT->changeImmediateDominator(LoopExitBlock, LoopMiddleBlock); 2000 2001 DEBUG(DT->verifyAnalysis()); 2002 } 2003 2004 bool LoopVectorizationLegality::canVectorizeWithIfConvert() { 2005 if (!EnableIfConversion) 2006 return false; 2007 2008 assert(TheLoop->getNumBlocks() > 1 && "Single block loops are vectorizable"); 2009 std::vector<BasicBlock*> &LoopBlocks = TheLoop->getBlocksVector(); 2010 2011 // Collect the blocks that need predication. 2012 for (unsigned i = 0, e = LoopBlocks.size(); i < e; ++i) { 2013 BasicBlock *BB = LoopBlocks[i]; 2014 2015 // We don't support switch statements inside loops. 2016 if (!isa<BranchInst>(BB->getTerminator())) 2017 return false; 2018 2019 // We must have at most two predecessors because we need to convert 2020 // all PHIs to selects. 2021 unsigned Preds = std::distance(pred_begin(BB), pred_end(BB)); 2022 if (Preds > 2) 2023 return false; 2024 2025 // We must be able to predicate all blocks that need to be predicated. 2026 if (blockNeedsPredication(BB) && !blockCanBePredicated(BB)) 2027 return false; 2028 } 2029 2030 // We can if-convert this loop. 2031 return true; 2032 } 2033 2034 bool LoopVectorizationLegality::canVectorize() { 2035 assert(TheLoop->getLoopPreheader() && "No preheader!!"); 2036 2037 // We can only vectorize innermost loops. 2038 if (TheLoop->getSubLoopsVector().size()) 2039 return false; 2040 2041 // We must have a single backedge. 2042 if (TheLoop->getNumBackEdges() != 1) 2043 return false; 2044 2045 // We must have a single exiting block. 2046 if (!TheLoop->getExitingBlock()) 2047 return false; 2048 2049 unsigned NumBlocks = TheLoop->getNumBlocks(); 2050 2051 // Check if we can if-convert non single-bb loops. 2052 if (NumBlocks != 1 && !canVectorizeWithIfConvert()) { 2053 DEBUG(dbgs() << "LV: Can't if-convert the loop.\n"); 2054 return false; 2055 } 2056 2057 // We need to have a loop header. 2058 BasicBlock *Latch = TheLoop->getLoopLatch(); 2059 DEBUG(dbgs() << "LV: Found a loop: " << 2060 TheLoop->getHeader()->getName() << "\n"); 2061 2062 // ScalarEvolution needs to be able to find the exit count. 2063 const SCEV *ExitCount = SE->getExitCount(TheLoop, Latch); 2064 if (ExitCount == SE->getCouldNotCompute()) { 2065 DEBUG(dbgs() << "LV: SCEV could not compute the loop exit count.\n"); 2066 return false; 2067 } 2068 2069 // Do not loop-vectorize loops with a tiny trip count. 2070 unsigned TC = SE->getSmallConstantTripCount(TheLoop, Latch); 2071 if (TC > 0u && TC < TinyTripCountVectorThreshold) { 2072 DEBUG(dbgs() << "LV: Found a loop with a very small trip count. " << 2073 "This loop is not worth vectorizing.\n"); 2074 return false; 2075 } 2076 2077 // Check if we can vectorize the instructions and CFG in this loop. 2078 if (!canVectorizeInstrs()) { 2079 DEBUG(dbgs() << "LV: Can't vectorize the instructions or CFG\n"); 2080 return false; 2081 } 2082 2083 // Go over each instruction and look at memory deps. 2084 if (!canVectorizeMemory()) { 2085 DEBUG(dbgs() << "LV: Can't vectorize due to memory conflicts\n"); 2086 return false; 2087 } 2088 2089 // Collect all of the variables that remain uniform after vectorization. 2090 collectLoopUniforms(); 2091 2092 DEBUG(dbgs() << "LV: We can vectorize this loop" << 2093 (PtrRtCheck.Need ? " (with a runtime bound check)" : "") 2094 <<"!\n"); 2095 2096 // Okay! We can vectorize. At this point we don't have any other mem analysis 2097 // which may limit our maximum vectorization factor, so just return true with 2098 // no restrictions. 2099 return true; 2100 } 2101 2102 bool LoopVectorizationLegality::canVectorizeInstrs() { 2103 BasicBlock *PreHeader = TheLoop->getLoopPreheader(); 2104 BasicBlock *Header = TheLoop->getHeader(); 2105 2106 // For each block in the loop. 2107 for (Loop::block_iterator bb = TheLoop->block_begin(), 2108 be = TheLoop->block_end(); bb != be; ++bb) { 2109 2110 // Scan the instructions in the block and look for hazards. 2111 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e; 2112 ++it) { 2113 2114 if (PHINode *Phi = dyn_cast<PHINode>(it)) { 2115 // This should not happen because the loop should be normalized. 2116 if (Phi->getNumIncomingValues() != 2) { 2117 DEBUG(dbgs() << "LV: Found an invalid PHI.\n"); 2118 return false; 2119 } 2120 2121 // Check that this PHI type is allowed. 2122 if (!Phi->getType()->isIntegerTy() && 2123 !Phi->getType()->isFloatingPointTy() && 2124 !Phi->getType()->isPointerTy()) { 2125 DEBUG(dbgs() << "LV: Found an non-int non-pointer PHI.\n"); 2126 return false; 2127 } 2128 2129 // If this PHINode is not in the header block, then we know that we 2130 // can convert it to select during if-conversion. No need to check if 2131 // the PHIs in this block are induction or reduction variables. 2132 if (*bb != Header) 2133 continue; 2134 2135 // This is the value coming from the preheader. 2136 Value *StartValue = Phi->getIncomingValueForBlock(PreHeader); 2137 // Check if this is an induction variable. 2138 InductionKind IK = isInductionVariable(Phi); 2139 2140 if (IK_NoInduction != IK) { 2141 // Int inductions are special because we only allow one IV. 2142 if (IK == IK_IntInduction) { 2143 if (Induction) { 2144 DEBUG(dbgs() << "LV: Found too many inductions."<< *Phi <<"\n"); 2145 return false; 2146 } 2147 Induction = Phi; 2148 } 2149 2150 DEBUG(dbgs() << "LV: Found an induction variable.\n"); 2151 Inductions[Phi] = InductionInfo(StartValue, IK); 2152 continue; 2153 } 2154 2155 if (AddReductionVar(Phi, RK_IntegerAdd)) { 2156 DEBUG(dbgs() << "LV: Found an ADD reduction PHI."<< *Phi <<"\n"); 2157 continue; 2158 } 2159 if (AddReductionVar(Phi, RK_IntegerMult)) { 2160 DEBUG(dbgs() << "LV: Found a MUL reduction PHI."<< *Phi <<"\n"); 2161 continue; 2162 } 2163 if (AddReductionVar(Phi, RK_IntegerOr)) { 2164 DEBUG(dbgs() << "LV: Found an OR reduction PHI."<< *Phi <<"\n"); 2165 continue; 2166 } 2167 if (AddReductionVar(Phi, RK_IntegerAnd)) { 2168 DEBUG(dbgs() << "LV: Found an AND reduction PHI."<< *Phi <<"\n"); 2169 continue; 2170 } 2171 if (AddReductionVar(Phi, RK_IntegerXor)) { 2172 DEBUG(dbgs() << "LV: Found a XOR reduction PHI."<< *Phi <<"\n"); 2173 continue; 2174 } 2175 if (AddReductionVar(Phi, RK_FloatMult)) { 2176 DEBUG(dbgs() << "LV: Found an FMult reduction PHI."<< *Phi <<"\n"); 2177 continue; 2178 } 2179 if (AddReductionVar(Phi, RK_FloatAdd)) { 2180 DEBUG(dbgs() << "LV: Found an FAdd reduction PHI."<< *Phi <<"\n"); 2181 continue; 2182 } 2183 2184 DEBUG(dbgs() << "LV: Found an unidentified PHI."<< *Phi <<"\n"); 2185 return false; 2186 }// end of PHI handling 2187 2188 // We still don't handle functions. 2189 CallInst *CI = dyn_cast<CallInst>(it); 2190 if (CI && !isTriviallyVectorizableIntrinsic(it)) { 2191 DEBUG(dbgs() << "LV: Found a call site.\n"); 2192 return false; 2193 } 2194 2195 // Check that the instruction return type is vectorizable. 2196 if (!VectorType::isValidElementType(it->getType()) && 2197 !it->getType()->isVoidTy()) { 2198 DEBUG(dbgs() << "LV: Found unvectorizable type." << "\n"); 2199 return false; 2200 } 2201 2202 // Check that the stored type is vectorizable. 2203 if (StoreInst *ST = dyn_cast<StoreInst>(it)) { 2204 Type *T = ST->getValueOperand()->getType(); 2205 if (!VectorType::isValidElementType(T)) 2206 return false; 2207 } 2208 2209 // Reduction instructions are allowed to have exit users. 2210 // All other instructions must not have external users. 2211 if (!AllowedExit.count(it)) 2212 //Check that all of the users of the loop are inside the BB. 2213 for (Value::use_iterator I = it->use_begin(), E = it->use_end(); 2214 I != E; ++I) { 2215 Instruction *U = cast<Instruction>(*I); 2216 // This user may be a reduction exit value. 2217 if (!TheLoop->contains(U)) { 2218 DEBUG(dbgs() << "LV: Found an outside user for : "<< *U << "\n"); 2219 return false; 2220 } 2221 } 2222 } // next instr. 2223 2224 } 2225 2226 if (!Induction) { 2227 DEBUG(dbgs() << "LV: Did not find one integer induction var.\n"); 2228 assert(getInductionVars()->size() && "No induction variables"); 2229 } 2230 2231 return true; 2232 } 2233 2234 void LoopVectorizationLegality::collectLoopUniforms() { 2235 // We now know that the loop is vectorizable! 2236 // Collect variables that will remain uniform after vectorization. 2237 std::vector<Value*> Worklist; 2238 BasicBlock *Latch = TheLoop->getLoopLatch(); 2239 2240 // Start with the conditional branch and walk up the block. 2241 Worklist.push_back(Latch->getTerminator()->getOperand(0)); 2242 2243 while (Worklist.size()) { 2244 Instruction *I = dyn_cast<Instruction>(Worklist.back()); 2245 Worklist.pop_back(); 2246 2247 // Look at instructions inside this loop. 2248 // Stop when reaching PHI nodes. 2249 // TODO: we need to follow values all over the loop, not only in this block. 2250 if (!I || !TheLoop->contains(I) || isa<PHINode>(I)) 2251 continue; 2252 2253 // This is a known uniform. 2254 Uniforms.insert(I); 2255 2256 // Insert all operands. 2257 for (int i = 0, Op = I->getNumOperands(); i < Op; ++i) { 2258 Worklist.push_back(I->getOperand(i)); 2259 } 2260 } 2261 } 2262 2263 bool LoopVectorizationLegality::canVectorizeMemory() { 2264 typedef SmallVector<Value*, 16> ValueVector; 2265 typedef SmallPtrSet<Value*, 16> ValueSet; 2266 // Holds the Load and Store *instructions*. 2267 ValueVector Loads; 2268 ValueVector Stores; 2269 PtrRtCheck.Pointers.clear(); 2270 PtrRtCheck.Need = false; 2271 2272 // For each block. 2273 for (Loop::block_iterator bb = TheLoop->block_begin(), 2274 be = TheLoop->block_end(); bb != be; ++bb) { 2275 2276 // Scan the BB and collect legal loads and stores. 2277 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e; 2278 ++it) { 2279 2280 // If this is a load, save it. If this instruction can read from memory 2281 // but is not a load, then we quit. Notice that we don't handle function 2282 // calls that read or write. 2283 if (it->mayReadFromMemory()) { 2284 LoadInst *Ld = dyn_cast<LoadInst>(it); 2285 if (!Ld) return false; 2286 if (!Ld->isSimple()) { 2287 DEBUG(dbgs() << "LV: Found a non-simple load.\n"); 2288 return false; 2289 } 2290 Loads.push_back(Ld); 2291 continue; 2292 } 2293 2294 // Save 'store' instructions. Abort if other instructions write to memory. 2295 if (it->mayWriteToMemory()) { 2296 StoreInst *St = dyn_cast<StoreInst>(it); 2297 if (!St) return false; 2298 if (!St->isSimple()) { 2299 DEBUG(dbgs() << "LV: Found a non-simple store.\n"); 2300 return false; 2301 } 2302 Stores.push_back(St); 2303 } 2304 } // next instr. 2305 } // next block. 2306 2307 // Now we have two lists that hold the loads and the stores. 2308 // Next, we find the pointers that they use. 2309 2310 // Check if we see any stores. If there are no stores, then we don't 2311 // care if the pointers are *restrict*. 2312 if (!Stores.size()) { 2313 DEBUG(dbgs() << "LV: Found a read-only loop!\n"); 2314 return true; 2315 } 2316 2317 // Holds the read and read-write *pointers* that we find. 2318 ValueVector Reads; 2319 ValueVector ReadWrites; 2320 2321 // Holds the analyzed pointers. We don't want to call GetUnderlyingObjects 2322 // multiple times on the same object. If the ptr is accessed twice, once 2323 // for read and once for write, it will only appear once (on the write 2324 // list). This is okay, since we are going to check for conflicts between 2325 // writes and between reads and writes, but not between reads and reads. 2326 ValueSet Seen; 2327 2328 ValueVector::iterator I, IE; 2329 for (I = Stores.begin(), IE = Stores.end(); I != IE; ++I) { 2330 StoreInst *ST = cast<StoreInst>(*I); 2331 Value* Ptr = ST->getPointerOperand(); 2332 2333 if (isUniform(Ptr)) { 2334 DEBUG(dbgs() << "LV: We don't allow storing to uniform addresses\n"); 2335 return false; 2336 } 2337 2338 // If we did *not* see this pointer before, insert it to 2339 // the read-write list. At this phase it is only a 'write' list. 2340 if (Seen.insert(Ptr)) 2341 ReadWrites.push_back(Ptr); 2342 } 2343 2344 for (I = Loads.begin(), IE = Loads.end(); I != IE; ++I) { 2345 LoadInst *LD = cast<LoadInst>(*I); 2346 Value* Ptr = LD->getPointerOperand(); 2347 // If we did *not* see this pointer before, insert it to the 2348 // read list. If we *did* see it before, then it is already in 2349 // the read-write list. This allows us to vectorize expressions 2350 // such as A[i] += x; Because the address of A[i] is a read-write 2351 // pointer. This only works if the index of A[i] is consecutive. 2352 // If the address of i is unknown (for example A[B[i]]) then we may 2353 // read a few words, modify, and write a few words, and some of the 2354 // words may be written to the same address. 2355 if (Seen.insert(Ptr) || 0 == isConsecutivePtr(Ptr)) 2356 Reads.push_back(Ptr); 2357 } 2358 2359 // If we write (or read-write) to a single destination and there are no 2360 // other reads in this loop then is it safe to vectorize. 2361 if (ReadWrites.size() == 1 && Reads.size() == 0) { 2362 DEBUG(dbgs() << "LV: Found a write-only loop!\n"); 2363 return true; 2364 } 2365 2366 // Find pointers with computable bounds. We are going to use this information 2367 // to place a runtime bound check. 2368 bool CanDoRT = true; 2369 for (I = ReadWrites.begin(), IE = ReadWrites.end(); I != IE; ++I) 2370 if (hasComputableBounds(*I)) { 2371 PtrRtCheck.insert(SE, TheLoop, *I); 2372 DEBUG(dbgs() << "LV: Found a runtime check ptr:" << **I <<"\n"); 2373 } else { 2374 CanDoRT = false; 2375 break; 2376 } 2377 for (I = Reads.begin(), IE = Reads.end(); I != IE; ++I) 2378 if (hasComputableBounds(*I)) { 2379 PtrRtCheck.insert(SE, TheLoop, *I); 2380 DEBUG(dbgs() << "LV: Found a runtime check ptr:" << **I <<"\n"); 2381 } else { 2382 CanDoRT = false; 2383 break; 2384 } 2385 2386 // Check that we did not collect too many pointers or found a 2387 // unsizeable pointer. 2388 if (!CanDoRT || PtrRtCheck.Pointers.size() > RuntimeMemoryCheckThreshold) { 2389 PtrRtCheck.reset(); 2390 CanDoRT = false; 2391 } 2392 2393 if (CanDoRT) { 2394 DEBUG(dbgs() << "LV: We can perform a memory runtime check if needed.\n"); 2395 } 2396 2397 bool NeedRTCheck = false; 2398 2399 // Now that the pointers are in two lists (Reads and ReadWrites), we 2400 // can check that there are no conflicts between each of the writes and 2401 // between the writes to the reads. 2402 ValueSet WriteObjects; 2403 ValueVector TempObjects; 2404 2405 // Check that the read-writes do not conflict with other read-write 2406 // pointers. 2407 bool AllWritesIdentified = true; 2408 for (I = ReadWrites.begin(), IE = ReadWrites.end(); I != IE; ++I) { 2409 GetUnderlyingObjects(*I, TempObjects, DL); 2410 for (ValueVector::iterator it=TempObjects.begin(), e=TempObjects.end(); 2411 it != e; ++it) { 2412 if (!isIdentifiedObject(*it)) { 2413 DEBUG(dbgs() << "LV: Found an unidentified write ptr:"<< **it <<"\n"); 2414 NeedRTCheck = true; 2415 AllWritesIdentified = false; 2416 } 2417 if (!WriteObjects.insert(*it)) { 2418 DEBUG(dbgs() << "LV: Found a possible write-write reorder:" 2419 << **it <<"\n"); 2420 return false; 2421 } 2422 } 2423 TempObjects.clear(); 2424 } 2425 2426 /// Check that the reads don't conflict with the read-writes. 2427 for (I = Reads.begin(), IE = Reads.end(); I != IE; ++I) { 2428 GetUnderlyingObjects(*I, TempObjects, DL); 2429 for (ValueVector::iterator it=TempObjects.begin(), e=TempObjects.end(); 2430 it != e; ++it) { 2431 // If all of the writes are identified then we don't care if the read 2432 // pointer is identified or not. 2433 if (!AllWritesIdentified && !isIdentifiedObject(*it)) { 2434 DEBUG(dbgs() << "LV: Found an unidentified read ptr:"<< **it <<"\n"); 2435 NeedRTCheck = true; 2436 } 2437 if (WriteObjects.count(*it)) { 2438 DEBUG(dbgs() << "LV: Found a possible read/write reorder:" 2439 << **it <<"\n"); 2440 return false; 2441 } 2442 } 2443 TempObjects.clear(); 2444 } 2445 2446 PtrRtCheck.Need = NeedRTCheck; 2447 if (NeedRTCheck && !CanDoRT) { 2448 DEBUG(dbgs() << "LV: We can't vectorize because we can't find " << 2449 "the array bounds.\n"); 2450 PtrRtCheck.reset(); 2451 return false; 2452 } 2453 2454 DEBUG(dbgs() << "LV: We "<< (NeedRTCheck ? "" : "don't") << 2455 " need a runtime memory check.\n"); 2456 return true; 2457 } 2458 2459 bool LoopVectorizationLegality::AddReductionVar(PHINode *Phi, 2460 ReductionKind Kind) { 2461 if (Phi->getNumIncomingValues() != 2) 2462 return false; 2463 2464 // Reduction variables are only found in the loop header block. 2465 if (Phi->getParent() != TheLoop->getHeader()) 2466 return false; 2467 2468 // Obtain the reduction start value from the value that comes from the loop 2469 // preheader. 2470 Value *RdxStart = Phi->getIncomingValueForBlock(TheLoop->getLoopPreheader()); 2471 2472 // ExitInstruction is the single value which is used outside the loop. 2473 // We only allow for a single reduction value to be used outside the loop. 2474 // This includes users of the reduction, variables (which form a cycle 2475 // which ends in the phi node). 2476 Instruction *ExitInstruction = 0; 2477 // Indicates that we found a binary operation in our scan. 2478 bool FoundBinOp = false; 2479 2480 // Iter is our iterator. We start with the PHI node and scan for all of the 2481 // users of this instruction. All users must be instructions that can be 2482 // used as reduction variables (such as ADD). We may have a single 2483 // out-of-block user. The cycle must end with the original PHI. 2484 Instruction *Iter = Phi; 2485 while (true) { 2486 // If the instruction has no users then this is a broken 2487 // chain and can't be a reduction variable. 2488 if (Iter->use_empty()) 2489 return false; 2490 2491 // Did we find a user inside this loop already ? 2492 bool FoundInBlockUser = false; 2493 // Did we reach the initial PHI node already ? 2494 bool FoundStartPHI = false; 2495 2496 // Is this a bin op ? 2497 FoundBinOp |= !isa<PHINode>(Iter); 2498 2499 // For each of the *users* of iter. 2500 for (Value::use_iterator it = Iter->use_begin(), e = Iter->use_end(); 2501 it != e; ++it) { 2502 Instruction *U = cast<Instruction>(*it); 2503 // We already know that the PHI is a user. 2504 if (U == Phi) { 2505 FoundStartPHI = true; 2506 continue; 2507 } 2508 2509 // Check if we found the exit user. 2510 BasicBlock *Parent = U->getParent(); 2511 if (!TheLoop->contains(Parent)) { 2512 // Exit if you find multiple outside users. 2513 if (ExitInstruction != 0) 2514 return false; 2515 ExitInstruction = Iter; 2516 } 2517 2518 // We allow in-loop PHINodes which are not the original reduction PHI 2519 // node. If this PHI is the only user of Iter (happens in IF w/ no ELSE 2520 // structure) then don't skip this PHI. 2521 if (isa<PHINode>(Iter) && isa<PHINode>(U) && 2522 U->getParent() != TheLoop->getHeader() && 2523 TheLoop->contains(U) && 2524 Iter->getNumUses() > 1) 2525 continue; 2526 2527 // We can't have multiple inside users. 2528 if (FoundInBlockUser) 2529 return false; 2530 FoundInBlockUser = true; 2531 2532 // Any reduction instr must be of one of the allowed kinds. 2533 if (!isReductionInstr(U, Kind)) 2534 return false; 2535 2536 // Reductions of instructions such as Div, and Sub is only 2537 // possible if the LHS is the reduction variable. 2538 if (!U->isCommutative() && !isa<PHINode>(U) && U->getOperand(0) != Iter) 2539 return false; 2540 2541 Iter = U; 2542 } 2543 2544 // We found a reduction var if we have reached the original 2545 // phi node and we only have a single instruction with out-of-loop 2546 // users. 2547 if (FoundStartPHI) { 2548 // This instruction is allowed to have out-of-loop users. 2549 AllowedExit.insert(ExitInstruction); 2550 2551 // Save the description of this reduction variable. 2552 ReductionDescriptor RD(RdxStart, ExitInstruction, Kind); 2553 Reductions[Phi] = RD; 2554 // We've ended the cycle. This is a reduction variable if we have an 2555 // outside user and it has a binary op. 2556 return FoundBinOp && ExitInstruction; 2557 } 2558 } 2559 } 2560 2561 bool 2562 LoopVectorizationLegality::isReductionInstr(Instruction *I, 2563 ReductionKind Kind) { 2564 bool FP = I->getType()->isFloatingPointTy(); 2565 bool FastMath = (FP && I->isCommutative() && I->isAssociative()); 2566 2567 switch (I->getOpcode()) { 2568 default: 2569 return false; 2570 case Instruction::PHI: 2571 if (FP && (Kind != RK_FloatMult && Kind != RK_FloatAdd)) 2572 return false; 2573 // possibly. 2574 return true; 2575 case Instruction::Sub: 2576 case Instruction::Add: 2577 return Kind == RK_IntegerAdd; 2578 case Instruction::SDiv: 2579 case Instruction::UDiv: 2580 case Instruction::Mul: 2581 return Kind == RK_IntegerMult; 2582 case Instruction::And: 2583 return Kind == RK_IntegerAnd; 2584 case Instruction::Or: 2585 return Kind == RK_IntegerOr; 2586 case Instruction::Xor: 2587 return Kind == RK_IntegerXor; 2588 case Instruction::FMul: 2589 return Kind == RK_FloatMult && FastMath; 2590 case Instruction::FAdd: 2591 return Kind == RK_FloatAdd && FastMath; 2592 } 2593 } 2594 2595 LoopVectorizationLegality::InductionKind 2596 LoopVectorizationLegality::isInductionVariable(PHINode *Phi) { 2597 Type *PhiTy = Phi->getType(); 2598 // We only handle integer and pointer inductions variables. 2599 if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy()) 2600 return IK_NoInduction; 2601 2602 // Check that the PHI is consecutive. 2603 const SCEV *PhiScev = SE->getSCEV(Phi); 2604 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev); 2605 if (!AR) { 2606 DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n"); 2607 return IK_NoInduction; 2608 } 2609 const SCEV *Step = AR->getStepRecurrence(*SE); 2610 2611 // Integer inductions need to have a stride of one. 2612 if (PhiTy->isIntegerTy()) { 2613 if (Step->isOne()) 2614 return IK_IntInduction; 2615 if (Step->isAllOnesValue()) 2616 return IK_ReverseIntInduction; 2617 return IK_NoInduction; 2618 } 2619 2620 // Calculate the pointer stride and check if it is consecutive. 2621 const SCEVConstant *C = dyn_cast<SCEVConstant>(Step); 2622 if (!C) 2623 return IK_NoInduction; 2624 2625 assert(PhiTy->isPointerTy() && "The PHI must be a pointer"); 2626 uint64_t Size = DL->getTypeAllocSize(PhiTy->getPointerElementType()); 2627 if (C->getValue()->equalsInt(Size)) 2628 return IK_PtrInduction; 2629 else if (C->getValue()->equalsInt(0 - Size)) 2630 return IK_ReversePtrInduction; 2631 2632 return IK_NoInduction; 2633 } 2634 2635 bool LoopVectorizationLegality::isInductionVariable(const Value *V) { 2636 Value *In0 = const_cast<Value*>(V); 2637 PHINode *PN = dyn_cast_or_null<PHINode>(In0); 2638 if (!PN) 2639 return false; 2640 2641 return Inductions.count(PN); 2642 } 2643 2644 bool LoopVectorizationLegality::blockNeedsPredication(BasicBlock *BB) { 2645 assert(TheLoop->contains(BB) && "Unknown block used"); 2646 2647 // Blocks that do not dominate the latch need predication. 2648 BasicBlock* Latch = TheLoop->getLoopLatch(); 2649 return !DT->dominates(BB, Latch); 2650 } 2651 2652 bool LoopVectorizationLegality::blockCanBePredicated(BasicBlock *BB) { 2653 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) { 2654 // We don't predicate loads/stores at the moment. 2655 if (it->mayReadFromMemory() || it->mayWriteToMemory() || it->mayThrow()) 2656 return false; 2657 2658 // The instructions below can trap. 2659 switch (it->getOpcode()) { 2660 default: continue; 2661 case Instruction::UDiv: 2662 case Instruction::SDiv: 2663 case Instruction::URem: 2664 case Instruction::SRem: 2665 return false; 2666 } 2667 } 2668 2669 return true; 2670 } 2671 2672 bool LoopVectorizationLegality::hasComputableBounds(Value *Ptr) { 2673 const SCEV *PhiScev = SE->getSCEV(Ptr); 2674 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev); 2675 if (!AR) 2676 return false; 2677 2678 return AR->isAffine(); 2679 } 2680 2681 LoopVectorizationCostModel::VectorizationFactor 2682 LoopVectorizationCostModel::selectVectorizationFactor(bool OptForSize, 2683 unsigned UserVF) { 2684 // Width 1 means no vectorize 2685 VectorizationFactor Factor = { 1U, 0U }; 2686 if (OptForSize && Legal->getRuntimePointerCheck()->Need) { 2687 DEBUG(dbgs() << "LV: Aborting. Runtime ptr check is required in Os.\n"); 2688 return Factor; 2689 } 2690 2691 // Find the trip count. 2692 unsigned TC = SE->getSmallConstantTripCount(TheLoop, TheLoop->getLoopLatch()); 2693 DEBUG(dbgs() << "LV: Found trip count:"<<TC<<"\n"); 2694 2695 unsigned WidestType = getWidestType(); 2696 unsigned WidestRegister = TTI.getRegisterBitWidth(true); 2697 unsigned MaxVectorSize = WidestRegister / WidestType; 2698 DEBUG(dbgs() << "LV: The Widest type: " << WidestType << " bits.\n"); 2699 DEBUG(dbgs() << "LV: The Widest register is:" << WidestRegister << "bits.\n"); 2700 2701 if (MaxVectorSize == 0) { 2702 DEBUG(dbgs() << "LV: The target has no vector registers.\n"); 2703 MaxVectorSize = 1; 2704 } 2705 2706 assert(MaxVectorSize <= 32 && "Did not expect to pack so many elements" 2707 " into one vector!"); 2708 2709 unsigned VF = MaxVectorSize; 2710 2711 // If we optimize the program for size, avoid creating the tail loop. 2712 if (OptForSize) { 2713 // If we are unable to calculate the trip count then don't try to vectorize. 2714 if (TC < 2) { 2715 DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n"); 2716 return Factor; 2717 } 2718 2719 // Find the maximum SIMD width that can fit within the trip count. 2720 VF = TC % MaxVectorSize; 2721 2722 if (VF == 0) 2723 VF = MaxVectorSize; 2724 2725 // If the trip count that we found modulo the vectorization factor is not 2726 // zero then we require a tail. 2727 if (VF < 2) { 2728 DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n"); 2729 return Factor; 2730 } 2731 } 2732 2733 if (UserVF != 0) { 2734 assert(isPowerOf2_32(UserVF) && "VF needs to be a power of two"); 2735 DEBUG(dbgs() << "LV: Using user VF "<<UserVF<<".\n"); 2736 2737 Factor.Width = UserVF; 2738 return Factor; 2739 } 2740 2741 float Cost = expectedCost(1); 2742 unsigned Width = 1; 2743 DEBUG(dbgs() << "LV: Scalar loop costs: "<< (int)Cost << ".\n"); 2744 for (unsigned i=2; i <= VF; i*=2) { 2745 // Notice that the vector loop needs to be executed less times, so 2746 // we need to divide the cost of the vector loops by the width of 2747 // the vector elements. 2748 float VectorCost = expectedCost(i) / (float)i; 2749 DEBUG(dbgs() << "LV: Vector loop of width "<< i << " costs: " << 2750 (int)VectorCost << ".\n"); 2751 if (VectorCost < Cost) { 2752 Cost = VectorCost; 2753 Width = i; 2754 } 2755 } 2756 2757 DEBUG(dbgs() << "LV: Selecting VF = : "<< Width << ".\n"); 2758 Factor.Width = Width; 2759 Factor.Cost = Width * Cost; 2760 return Factor; 2761 } 2762 2763 unsigned LoopVectorizationCostModel::getWidestType() { 2764 unsigned MaxWidth = 8; 2765 2766 // For each block. 2767 for (Loop::block_iterator bb = TheLoop->block_begin(), 2768 be = TheLoop->block_end(); bb != be; ++bb) { 2769 BasicBlock *BB = *bb; 2770 2771 // For each instruction in the loop. 2772 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) { 2773 Type *T = it->getType(); 2774 2775 // Only examine Loads, Stores and PHINodes. 2776 if (!isa<LoadInst>(it) && !isa<StoreInst>(it) && !isa<PHINode>(it)) 2777 continue; 2778 2779 // Examine PHI nodes that are reduction variables. 2780 if (PHINode *PN = dyn_cast<PHINode>(it)) 2781 if (!Legal->getReductionVars()->count(PN)) 2782 continue; 2783 2784 // Examine the stored values. 2785 if (StoreInst *ST = dyn_cast<StoreInst>(it)) 2786 T = ST->getValueOperand()->getType(); 2787 2788 // Ignore stored/loaded pointer types. 2789 if (T->isPointerTy()) 2790 continue; 2791 2792 MaxWidth = std::max(MaxWidth, T->getScalarSizeInBits()); 2793 } 2794 } 2795 2796 return MaxWidth; 2797 } 2798 2799 unsigned 2800 LoopVectorizationCostModel::selectUnrollFactor(bool OptForSize, 2801 unsigned UserUF, 2802 unsigned VF, 2803 unsigned LoopCost) { 2804 2805 // -- The unroll heuristics -- 2806 // We unroll the loop in order to expose ILP and reduce the loop overhead. 2807 // There are many micro-architectural considerations that we can't predict 2808 // at this level. For example frontend pressure (on decode or fetch) due to 2809 // code size, or the number and capabilities of the execution ports. 2810 // 2811 // We use the following heuristics to select the unroll factor: 2812 // 1. If the code has reductions the we unroll in order to break the cross 2813 // iteration dependency. 2814 // 2. If the loop is really small then we unroll in order to reduce the loop 2815 // overhead. 2816 // 3. We don't unroll if we think that we will spill registers to memory due 2817 // to the increased register pressure. 2818 2819 // Use the user preference, unless 'auto' is selected. 2820 if (UserUF != 0) 2821 return UserUF; 2822 2823 // When we optimize for size we don't unroll. 2824 if (OptForSize) 2825 return 1; 2826 2827 // Do not unroll loops with a relatively small trip count. 2828 unsigned TC = SE->getSmallConstantTripCount(TheLoop, 2829 TheLoop->getLoopLatch()); 2830 if (TC > 1 && TC < TinyTripCountUnrollThreshold) 2831 return 1; 2832 2833 unsigned TargetVectorRegisters = TTI.getNumberOfRegisters(true); 2834 DEBUG(dbgs() << "LV: The target has " << TargetVectorRegisters << 2835 " vector registers\n"); 2836 2837 LoopVectorizationCostModel::RegisterUsage R = calculateRegisterUsage(); 2838 // We divide by these constants so assume that we have at least one 2839 // instruction that uses at least one register. 2840 R.MaxLocalUsers = std::max(R.MaxLocalUsers, 1U); 2841 R.NumInstructions = std::max(R.NumInstructions, 1U); 2842 2843 // We calculate the unroll factor using the following formula. 2844 // Subtract the number of loop invariants from the number of available 2845 // registers. These registers are used by all of the unrolled instances. 2846 // Next, divide the remaining registers by the number of registers that is 2847 // required by the loop, in order to estimate how many parallel instances 2848 // fit without causing spills. 2849 unsigned UF = (TargetVectorRegisters - R.LoopInvariantRegs) / R.MaxLocalUsers; 2850 2851 // Clamp the unroll factor ranges to reasonable factors. 2852 unsigned MaxUnrollSize = TTI.getMaximumUnrollFactor(); 2853 2854 // If we did not calculate the cost for VF (because the user selected the VF) 2855 // then we calculate the cost of VF here. 2856 if (LoopCost == 0) 2857 LoopCost = expectedCost(VF); 2858 2859 // Clamp the calculated UF to be between the 1 and the max unroll factor 2860 // that the target allows. 2861 if (UF > MaxUnrollSize) 2862 UF = MaxUnrollSize; 2863 else if (UF < 1) 2864 UF = 1; 2865 2866 if (Legal->getReductionVars()->size()) { 2867 DEBUG(dbgs() << "LV: Unrolling because of reductions. \n"); 2868 return UF; 2869 } 2870 2871 // We want to unroll tiny loops in order to reduce the loop overhead. 2872 // We assume that the cost overhead is 1 and we use the cost model 2873 // to estimate the cost of the loop and unroll until the cost of the 2874 // loop overhead is about 5% of the cost of the loop. 2875 DEBUG(dbgs() << "LV: Loop cost is "<< LoopCost <<" \n"); 2876 if (LoopCost < 20) { 2877 DEBUG(dbgs() << "LV: Unrolling to reduce branch cost. \n"); 2878 unsigned NewUF = 20/LoopCost + 1; 2879 return std::min(NewUF, UF); 2880 } 2881 2882 DEBUG(dbgs() << "LV: Not Unrolling. \n"); 2883 return 1; 2884 } 2885 2886 LoopVectorizationCostModel::RegisterUsage 2887 LoopVectorizationCostModel::calculateRegisterUsage() { 2888 // This function calculates the register usage by measuring the highest number 2889 // of values that are alive at a single location. Obviously, this is a very 2890 // rough estimation. We scan the loop in a topological order in order and 2891 // assign a number to each instruction. We use RPO to ensure that defs are 2892 // met before their users. We assume that each instruction that has in-loop 2893 // users starts an interval. We record every time that an in-loop value is 2894 // used, so we have a list of the first and last occurrences of each 2895 // instruction. Next, we transpose this data structure into a multi map that 2896 // holds the list of intervals that *end* at a specific location. This multi 2897 // map allows us to perform a linear search. We scan the instructions linearly 2898 // and record each time that a new interval starts, by placing it in a set. 2899 // If we find this value in the multi-map then we remove it from the set. 2900 // The max register usage is the maximum size of the set. 2901 // We also search for instructions that are defined outside the loop, but are 2902 // used inside the loop. We need this number separately from the max-interval 2903 // usage number because when we unroll, loop-invariant values do not take 2904 // more register. 2905 LoopBlocksDFS DFS(TheLoop); 2906 DFS.perform(LI); 2907 2908 RegisterUsage R; 2909 R.NumInstructions = 0; 2910 2911 // Each 'key' in the map opens a new interval. The values 2912 // of the map are the index of the 'last seen' usage of the 2913 // instruction that is the key. 2914 typedef DenseMap<Instruction*, unsigned> IntervalMap; 2915 // Maps instruction to its index. 2916 DenseMap<unsigned, Instruction*> IdxToInstr; 2917 // Marks the end of each interval. 2918 IntervalMap EndPoint; 2919 // Saves the list of instruction indices that are used in the loop. 2920 SmallSet<Instruction*, 8> Ends; 2921 // Saves the list of values that are used in the loop but are 2922 // defined outside the loop, such as arguments and constants. 2923 SmallPtrSet<Value*, 8> LoopInvariants; 2924 2925 unsigned Index = 0; 2926 for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(), 2927 be = DFS.endRPO(); bb != be; ++bb) { 2928 R.NumInstructions += (*bb)->size(); 2929 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e; 2930 ++it) { 2931 Instruction *I = it; 2932 IdxToInstr[Index++] = I; 2933 2934 // Save the end location of each USE. 2935 for (unsigned i = 0; i < I->getNumOperands(); ++i) { 2936 Value *U = I->getOperand(i); 2937 Instruction *Instr = dyn_cast<Instruction>(U); 2938 2939 // Ignore non-instruction values such as arguments, constants, etc. 2940 if (!Instr) continue; 2941 2942 // If this instruction is outside the loop then record it and continue. 2943 if (!TheLoop->contains(Instr)) { 2944 LoopInvariants.insert(Instr); 2945 continue; 2946 } 2947 2948 // Overwrite previous end points. 2949 EndPoint[Instr] = Index; 2950 Ends.insert(Instr); 2951 } 2952 } 2953 } 2954 2955 // Saves the list of intervals that end with the index in 'key'. 2956 typedef SmallVector<Instruction*, 2> InstrList; 2957 DenseMap<unsigned, InstrList> TransposeEnds; 2958 2959 // Transpose the EndPoints to a list of values that end at each index. 2960 for (IntervalMap::iterator it = EndPoint.begin(), e = EndPoint.end(); 2961 it != e; ++it) 2962 TransposeEnds[it->second].push_back(it->first); 2963 2964 SmallSet<Instruction*, 8> OpenIntervals; 2965 unsigned MaxUsage = 0; 2966 2967 2968 DEBUG(dbgs() << "LV(REG): Calculating max register usage:\n"); 2969 for (unsigned int i = 0; i < Index; ++i) { 2970 Instruction *I = IdxToInstr[i]; 2971 // Ignore instructions that are never used within the loop. 2972 if (!Ends.count(I)) continue; 2973 2974 // Remove all of the instructions that end at this location. 2975 InstrList &List = TransposeEnds[i]; 2976 for (unsigned int j=0, e = List.size(); j < e; ++j) 2977 OpenIntervals.erase(List[j]); 2978 2979 // Count the number of live interals. 2980 MaxUsage = std::max(MaxUsage, OpenIntervals.size()); 2981 2982 DEBUG(dbgs() << "LV(REG): At #" << i << " Interval # " << 2983 OpenIntervals.size() <<"\n"); 2984 2985 // Add the current instruction to the list of open intervals. 2986 OpenIntervals.insert(I); 2987 } 2988 2989 unsigned Invariant = LoopInvariants.size(); 2990 DEBUG(dbgs() << "LV(REG): Found max usage: " << MaxUsage << " \n"); 2991 DEBUG(dbgs() << "LV(REG): Found invariant usage: " << Invariant << " \n"); 2992 DEBUG(dbgs() << "LV(REG): LoopSize: " << R.NumInstructions << " \n"); 2993 2994 R.LoopInvariantRegs = Invariant; 2995 R.MaxLocalUsers = MaxUsage; 2996 return R; 2997 } 2998 2999 unsigned LoopVectorizationCostModel::expectedCost(unsigned VF) { 3000 unsigned Cost = 0; 3001 3002 // For each block. 3003 for (Loop::block_iterator bb = TheLoop->block_begin(), 3004 be = TheLoop->block_end(); bb != be; ++bb) { 3005 unsigned BlockCost = 0; 3006 BasicBlock *BB = *bb; 3007 3008 // For each instruction in the old loop. 3009 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) { 3010 unsigned C = getInstructionCost(it, VF); 3011 Cost += C; 3012 DEBUG(dbgs() << "LV: Found an estimated cost of "<< C <<" for VF " << 3013 VF << " For instruction: "<< *it << "\n"); 3014 } 3015 3016 // We assume that if-converted blocks have a 50% chance of being executed. 3017 // When the code is scalar then some of the blocks are avoided due to CF. 3018 // When the code is vectorized we execute all code paths. 3019 if (Legal->blockNeedsPredication(*bb) && VF == 1) 3020 BlockCost /= 2; 3021 3022 Cost += BlockCost; 3023 } 3024 3025 return Cost; 3026 } 3027 3028 unsigned 3029 LoopVectorizationCostModel::getInstructionCost(Instruction *I, unsigned VF) { 3030 // If we know that this instruction will remain uniform, check the cost of 3031 // the scalar version. 3032 if (Legal->isUniformAfterVectorization(I)) 3033 VF = 1; 3034 3035 Type *RetTy = I->getType(); 3036 Type *VectorTy = ToVectorTy(RetTy, VF); 3037 3038 // TODO: We need to estimate the cost of intrinsic calls. 3039 switch (I->getOpcode()) { 3040 case Instruction::GetElementPtr: 3041 // We mark this instruction as zero-cost because scalar GEPs are usually 3042 // lowered to the intruction addressing mode. At the moment we don't 3043 // generate vector geps. 3044 return 0; 3045 case Instruction::Br: { 3046 return TTI.getCFInstrCost(I->getOpcode()); 3047 } 3048 case Instruction::PHI: 3049 //TODO: IF-converted IFs become selects. 3050 return 0; 3051 case Instruction::Add: 3052 case Instruction::FAdd: 3053 case Instruction::Sub: 3054 case Instruction::FSub: 3055 case Instruction::Mul: 3056 case Instruction::FMul: 3057 case Instruction::UDiv: 3058 case Instruction::SDiv: 3059 case Instruction::FDiv: 3060 case Instruction::URem: 3061 case Instruction::SRem: 3062 case Instruction::FRem: 3063 case Instruction::Shl: 3064 case Instruction::LShr: 3065 case Instruction::AShr: 3066 case Instruction::And: 3067 case Instruction::Or: 3068 case Instruction::Xor: 3069 return TTI.getArithmeticInstrCost(I->getOpcode(), VectorTy); 3070 case Instruction::Select: { 3071 SelectInst *SI = cast<SelectInst>(I); 3072 const SCEV *CondSCEV = SE->getSCEV(SI->getCondition()); 3073 bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop)); 3074 Type *CondTy = SI->getCondition()->getType(); 3075 if (ScalarCond) 3076 CondTy = VectorType::get(CondTy, VF); 3077 3078 return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, CondTy); 3079 } 3080 case Instruction::ICmp: 3081 case Instruction::FCmp: { 3082 Type *ValTy = I->getOperand(0)->getType(); 3083 VectorTy = ToVectorTy(ValTy, VF); 3084 return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy); 3085 } 3086 case Instruction::Store: { 3087 StoreInst *SI = cast<StoreInst>(I); 3088 Type *ValTy = SI->getValueOperand()->getType(); 3089 VectorTy = ToVectorTy(ValTy, VF); 3090 3091 if (VF == 1) 3092 return TTI.getMemoryOpCost(I->getOpcode(), VectorTy, 3093 SI->getAlignment(), 3094 SI->getPointerAddressSpace()); 3095 3096 // Scalarized stores. 3097 int Stride = Legal->isConsecutivePtr(SI->getPointerOperand()); 3098 bool Reverse = Stride < 0; 3099 if (0 == Stride) { 3100 unsigned Cost = 0; 3101 3102 // The cost of extracting from the value vector and pointer vector. 3103 Type *PtrTy = ToVectorTy(I->getOperand(0)->getType(), VF); 3104 for (unsigned i = 0; i < VF; ++i) { 3105 Cost += TTI.getVectorInstrCost(Instruction::ExtractElement, VectorTy, 3106 i); 3107 Cost += TTI.getVectorInstrCost(Instruction::ExtractElement, PtrTy, i); 3108 } 3109 3110 // The cost of the scalar stores. 3111 Cost += VF * TTI.getMemoryOpCost(I->getOpcode(), ValTy->getScalarType(), 3112 SI->getAlignment(), 3113 SI->getPointerAddressSpace()); 3114 return Cost; 3115 } 3116 3117 // Wide stores. 3118 unsigned Cost = TTI.getMemoryOpCost(I->getOpcode(), VectorTy, 3119 SI->getAlignment(), 3120 SI->getPointerAddressSpace()); 3121 if (Reverse) 3122 Cost += TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, 3123 VectorTy, 0); 3124 return Cost; 3125 } 3126 case Instruction::Load: { 3127 LoadInst *LI = cast<LoadInst>(I); 3128 3129 if (VF == 1) 3130 return TTI.getMemoryOpCost(I->getOpcode(), VectorTy, LI->getAlignment(), 3131 LI->getPointerAddressSpace()); 3132 3133 // Scalarized loads. 3134 int Stride = Legal->isConsecutivePtr(LI->getPointerOperand()); 3135 bool Reverse = Stride < 0; 3136 if (0 == Stride) { 3137 unsigned Cost = 0; 3138 Type *PtrTy = ToVectorTy(I->getOperand(0)->getType(), VF); 3139 3140 // The cost of extracting from the pointer vector. 3141 for (unsigned i = 0; i < VF; ++i) 3142 Cost += TTI.getVectorInstrCost(Instruction::ExtractElement, PtrTy, i); 3143 3144 // The cost of inserting data to the result vector. 3145 for (unsigned i = 0; i < VF; ++i) 3146 Cost += TTI.getVectorInstrCost(Instruction::InsertElement, VectorTy, i); 3147 3148 // The cost of the scalar stores. 3149 Cost += VF * TTI.getMemoryOpCost(I->getOpcode(), RetTy->getScalarType(), 3150 LI->getAlignment(), 3151 LI->getPointerAddressSpace()); 3152 return Cost; 3153 } 3154 3155 // Wide loads. 3156 unsigned Cost = TTI.getMemoryOpCost(I->getOpcode(), VectorTy, 3157 LI->getAlignment(), 3158 LI->getPointerAddressSpace()); 3159 if (Reverse) 3160 Cost += TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, VectorTy, 0); 3161 return Cost; 3162 } 3163 case Instruction::ZExt: 3164 case Instruction::SExt: 3165 case Instruction::FPToUI: 3166 case Instruction::FPToSI: 3167 case Instruction::FPExt: 3168 case Instruction::PtrToInt: 3169 case Instruction::IntToPtr: 3170 case Instruction::SIToFP: 3171 case Instruction::UIToFP: 3172 case Instruction::Trunc: 3173 case Instruction::FPTrunc: 3174 case Instruction::BitCast: { 3175 // We optimize the truncation of induction variable. 3176 // The cost of these is the same as the scalar operation. 3177 if (I->getOpcode() == Instruction::Trunc && 3178 Legal->isInductionVariable(I->getOperand(0))) 3179 return TTI.getCastInstrCost(I->getOpcode(), I->getType(), 3180 I->getOperand(0)->getType()); 3181 3182 Type *SrcVecTy = ToVectorTy(I->getOperand(0)->getType(), VF); 3183 return TTI.getCastInstrCost(I->getOpcode(), VectorTy, SrcVecTy); 3184 } 3185 case Instruction::Call: { 3186 assert(isTriviallyVectorizableIntrinsic(I)); 3187 IntrinsicInst *II = cast<IntrinsicInst>(I); 3188 Type *RetTy = ToVectorTy(II->getType(), VF); 3189 SmallVector<Type*, 4> Tys; 3190 for (unsigned i = 0, ie = II->getNumArgOperands(); i != ie; ++i) 3191 Tys.push_back(ToVectorTy(II->getArgOperand(i)->getType(), VF)); 3192 return TTI.getIntrinsicInstrCost(II->getIntrinsicID(), RetTy, Tys); 3193 } 3194 default: { 3195 // We are scalarizing the instruction. Return the cost of the scalar 3196 // instruction, plus the cost of insert and extract into vector 3197 // elements, times the vector width. 3198 unsigned Cost = 0; 3199 3200 if (!RetTy->isVoidTy() && VF != 1) { 3201 unsigned InsCost = TTI.getVectorInstrCost(Instruction::InsertElement, 3202 VectorTy); 3203 unsigned ExtCost = TTI.getVectorInstrCost(Instruction::ExtractElement, 3204 VectorTy); 3205 3206 // The cost of inserting the results plus extracting each one of the 3207 // operands. 3208 Cost += VF * (InsCost + ExtCost * I->getNumOperands()); 3209 } 3210 3211 // The cost of executing VF copies of the scalar instruction. This opcode 3212 // is unknown. Assume that it is the same as 'mul'. 3213 Cost += VF * TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy); 3214 return Cost; 3215 } 3216 }// end of switch. 3217 } 3218 3219 Type* LoopVectorizationCostModel::ToVectorTy(Type *Scalar, unsigned VF) { 3220 if (Scalar->isVoidTy() || VF == 1) 3221 return Scalar; 3222 return VectorType::get(Scalar, VF); 3223 } 3224 3225 char LoopVectorize::ID = 0; 3226 static const char lv_name[] = "Loop Vectorization"; 3227 INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false) 3228 INITIALIZE_AG_DEPENDENCY(AliasAnalysis) 3229 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo) 3230 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution) 3231 INITIALIZE_PASS_DEPENDENCY(LoopSimplify) 3232 INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false) 3233 3234 namespace llvm { 3235 Pass *createLoopVectorizePass() { 3236 return new LoopVectorize(); 3237 } 3238 } 3239 3240 3241