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. 12 // The vectorizer uses the TargetTransformInfo analysis to estimate the costs 13 // of instructions in order to estimate the profitability of vectorization. 14 // 15 // The loop vectorizer combines consecutive loop iterations 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/EquivalenceClasses.h" 51 #include "llvm/ADT/Hashing.h" 52 #include "llvm/ADT/MapVector.h" 53 #include "llvm/ADT/SetVector.h" 54 #include "llvm/ADT/SmallPtrSet.h" 55 #include "llvm/ADT/SmallSet.h" 56 #include "llvm/ADT/SmallVector.h" 57 #include "llvm/ADT/StringExtras.h" 58 #include "llvm/Analysis/AliasAnalysis.h" 59 #include "llvm/Analysis/Dominators.h" 60 #include "llvm/Analysis/LoopInfo.h" 61 #include "llvm/Analysis/LoopIterator.h" 62 #include "llvm/Analysis/LoopPass.h" 63 #include "llvm/Analysis/ScalarEvolution.h" 64 #include "llvm/Analysis/ScalarEvolutionExpander.h" 65 #include "llvm/Analysis/ScalarEvolutionExpressions.h" 66 #include "llvm/Analysis/TargetTransformInfo.h" 67 #include "llvm/Analysis/ValueTracking.h" 68 #include "llvm/Analysis/Verifier.h" 69 #include "llvm/IR/Constants.h" 70 #include "llvm/IR/DataLayout.h" 71 #include "llvm/IR/DerivedTypes.h" 72 #include "llvm/IR/Function.h" 73 #include "llvm/IR/IRBuilder.h" 74 #include "llvm/IR/Instructions.h" 75 #include "llvm/IR/IntrinsicInst.h" 76 #include "llvm/IR/LLVMContext.h" 77 #include "llvm/IR/Module.h" 78 #include "llvm/IR/Type.h" 79 #include "llvm/IR/Value.h" 80 #include "llvm/Pass.h" 81 #include "llvm/Support/CommandLine.h" 82 #include "llvm/Support/Debug.h" 83 #include "llvm/Support/PatternMatch.h" 84 #include "llvm/Support/raw_ostream.h" 85 #include "llvm/Support/ValueHandle.h" 86 #include "llvm/Target/TargetLibraryInfo.h" 87 #include "llvm/Transforms/Scalar.h" 88 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 89 #include "llvm/Transforms/Utils/Local.h" 90 #include <algorithm> 91 #include <map> 92 93 using namespace llvm; 94 using namespace llvm::PatternMatch; 95 96 static cl::opt<unsigned> 97 VectorizationFactor("force-vector-width", cl::init(0), cl::Hidden, 98 cl::desc("Sets the SIMD width. Zero is autoselect.")); 99 100 static cl::opt<unsigned> 101 VectorizationUnroll("force-vector-unroll", cl::init(0), cl::Hidden, 102 cl::desc("Sets the vectorization unroll count. " 103 "Zero is autoselect.")); 104 105 static cl::opt<bool> 106 EnableIfConversion("enable-if-conversion", cl::init(true), cl::Hidden, 107 cl::desc("Enable if-conversion during vectorization.")); 108 109 /// We don't vectorize loops with a known constant trip count below this number. 110 static cl::opt<unsigned> 111 TinyTripCountVectorThreshold("vectorizer-min-trip-count", cl::init(16), 112 cl::Hidden, 113 cl::desc("Don't vectorize loops with a constant " 114 "trip count that is smaller than this " 115 "value.")); 116 117 /// We don't unroll loops with a known constant trip count below this number. 118 static const unsigned TinyTripCountUnrollThreshold = 128; 119 120 /// When performing memory disambiguation checks at runtime do not make more 121 /// than this number of comparisons. 122 static const unsigned RuntimeMemoryCheckThreshold = 8; 123 124 /// Maximum simd width. 125 static const unsigned MaxVectorWidth = 64; 126 127 /// Maximum vectorization unroll count. 128 static const unsigned MaxUnrollFactor = 16; 129 130 /// The cost of a loop that is considered 'small' by the unroller. 131 static const unsigned SmallLoopCost = 20; 132 133 namespace { 134 135 // Forward declarations. 136 class LoopVectorizationLegality; 137 class LoopVectorizationCostModel; 138 139 /// InnerLoopVectorizer vectorizes loops which contain only one basic 140 /// block to a specified vectorization factor (VF). 141 /// This class performs the widening of scalars into vectors, or multiple 142 /// scalars. This class also implements the following features: 143 /// * It inserts an epilogue loop for handling loops that don't have iteration 144 /// counts that are known to be a multiple of the vectorization factor. 145 /// * It handles the code generation for reduction variables. 146 /// * Scalarization (implementation using scalars) of un-vectorizable 147 /// instructions. 148 /// InnerLoopVectorizer does not perform any vectorization-legality 149 /// checks, and relies on the caller to check for the different legality 150 /// aspects. The InnerLoopVectorizer relies on the 151 /// LoopVectorizationLegality class to provide information about the induction 152 /// and reduction variables that were found to a given vectorization factor. 153 class InnerLoopVectorizer { 154 public: 155 InnerLoopVectorizer(Loop *OrigLoop, ScalarEvolution *SE, LoopInfo *LI, 156 DominatorTree *DT, DataLayout *DL, 157 const TargetLibraryInfo *TLI, unsigned VecWidth, 158 unsigned UnrollFactor) 159 : OrigLoop(OrigLoop), SE(SE), LI(LI), DT(DT), DL(DL), TLI(TLI), 160 VF(VecWidth), UF(UnrollFactor), Builder(SE->getContext()), Induction(0), 161 OldInduction(0), WidenMap(UnrollFactor) {} 162 163 // Perform the actual loop widening (vectorization). 164 void vectorize(LoopVectorizationLegality *Legal) { 165 // Create a new empty loop. Unlink the old loop and connect the new one. 166 createEmptyLoop(Legal); 167 // Widen each instruction in the old loop to a new one in the new loop. 168 // Use the Legality module to find the induction and reduction variables. 169 vectorizeLoop(Legal); 170 // Register the new loop and update the analysis passes. 171 updateAnalysis(); 172 } 173 174 virtual ~InnerLoopVectorizer() {} 175 176 protected: 177 /// A small list of PHINodes. 178 typedef SmallVector<PHINode*, 4> PhiVector; 179 /// When we unroll loops we have multiple vector values for each scalar. 180 /// This data structure holds the unrolled and vectorized values that 181 /// originated from one scalar instruction. 182 typedef SmallVector<Value*, 2> VectorParts; 183 184 // When we if-convert we need create edge masks. We have to cache values so 185 // that we don't end up with exponential recursion/IR. 186 typedef DenseMap<std::pair<BasicBlock*, BasicBlock*>, 187 VectorParts> EdgeMaskCache; 188 189 /// Add code that checks at runtime if the accessed arrays overlap. 190 /// Returns the comparator value or NULL if no check is needed. 191 Instruction *addRuntimeCheck(LoopVectorizationLegality *Legal, 192 Instruction *Loc); 193 /// Create an empty loop, based on the loop ranges of the old loop. 194 void createEmptyLoop(LoopVectorizationLegality *Legal); 195 /// Copy and widen the instructions from the old loop. 196 virtual void vectorizeLoop(LoopVectorizationLegality *Legal); 197 198 /// \brief The Loop exit block may have single value PHI nodes where the 199 /// incoming value is 'Undef'. While vectorizing we only handled real values 200 /// that were defined inside the loop. Here we fix the 'undef case'. 201 /// See PR14725. 202 void fixLCSSAPHIs(); 203 204 /// A helper function that computes the predicate of the block BB, assuming 205 /// that the header block of the loop is set to True. It returns the *entry* 206 /// mask for the block BB. 207 VectorParts createBlockInMask(BasicBlock *BB); 208 /// A helper function that computes the predicate of the edge between SRC 209 /// and DST. 210 VectorParts createEdgeMask(BasicBlock *Src, BasicBlock *Dst); 211 212 /// A helper function to vectorize a single BB within the innermost loop. 213 void vectorizeBlockInLoop(LoopVectorizationLegality *Legal, BasicBlock *BB, 214 PhiVector *PV); 215 216 /// Vectorize a single PHINode in a block. This method handles the induction 217 /// variable canonicalization. It supports both VF = 1 for unrolled loops and 218 /// arbitrary length vectors. 219 void widenPHIInstruction(Instruction *PN, VectorParts &Entry, 220 LoopVectorizationLegality *Legal, 221 unsigned UF, unsigned VF, PhiVector *PV); 222 223 /// Insert the new loop to the loop hierarchy and pass manager 224 /// and update the analysis passes. 225 void updateAnalysis(); 226 227 /// This instruction is un-vectorizable. Implement it as a sequence 228 /// of scalars. 229 virtual void scalarizeInstruction(Instruction *Instr); 230 231 /// Vectorize Load and Store instructions, 232 virtual void vectorizeMemoryInstruction(Instruction *Instr, 233 LoopVectorizationLegality *Legal); 234 235 /// Create a broadcast instruction. This method generates a broadcast 236 /// instruction (shuffle) for loop invariant values and for the induction 237 /// value. If this is the induction variable then we extend it to N, N+1, ... 238 /// this is needed because each iteration in the loop corresponds to a SIMD 239 /// element. 240 virtual Value *getBroadcastInstrs(Value *V); 241 242 /// This function adds 0, 1, 2 ... to each vector element, starting at zero. 243 /// If Negate is set then negative numbers are added e.g. (0, -1, -2, ...). 244 /// The sequence starts at StartIndex. 245 virtual Value *getConsecutiveVector(Value* Val, int StartIdx, bool Negate); 246 247 /// When we go over instructions in the basic block we rely on previous 248 /// values within the current basic block or on loop invariant values. 249 /// When we widen (vectorize) values we place them in the map. If the values 250 /// are not within the map, they have to be loop invariant, so we simply 251 /// broadcast them into a vector. 252 VectorParts &getVectorValue(Value *V); 253 254 /// Generate a shuffle sequence that will reverse the vector Vec. 255 virtual Value *reverseVector(Value *Vec); 256 257 /// This is a helper class that holds the vectorizer state. It maps scalar 258 /// instructions to vector instructions. When the code is 'unrolled' then 259 /// then a single scalar value is mapped to multiple vector parts. The parts 260 /// are stored in the VectorPart type. 261 struct ValueMap { 262 /// C'tor. UnrollFactor controls the number of vectors ('parts') that 263 /// are mapped. 264 ValueMap(unsigned UnrollFactor) : UF(UnrollFactor) {} 265 266 /// \return True if 'Key' is saved in the Value Map. 267 bool has(Value *Key) const { return MapStorage.count(Key); } 268 269 /// Initializes a new entry in the map. Sets all of the vector parts to the 270 /// save value in 'Val'. 271 /// \return A reference to a vector with splat values. 272 VectorParts &splat(Value *Key, Value *Val) { 273 VectorParts &Entry = MapStorage[Key]; 274 Entry.assign(UF, Val); 275 return Entry; 276 } 277 278 ///\return A reference to the value that is stored at 'Key'. 279 VectorParts &get(Value *Key) { 280 VectorParts &Entry = MapStorage[Key]; 281 if (Entry.empty()) 282 Entry.resize(UF); 283 assert(Entry.size() == UF); 284 return Entry; 285 } 286 287 private: 288 /// The unroll factor. Each entry in the map stores this number of vector 289 /// elements. 290 unsigned UF; 291 292 /// Map storage. We use std::map and not DenseMap because insertions to a 293 /// dense map invalidates its iterators. 294 std::map<Value *, VectorParts> MapStorage; 295 }; 296 297 /// The original loop. 298 Loop *OrigLoop; 299 /// Scev analysis to use. 300 ScalarEvolution *SE; 301 /// Loop Info. 302 LoopInfo *LI; 303 /// Dominator Tree. 304 DominatorTree *DT; 305 /// Data Layout. 306 DataLayout *DL; 307 /// Target Library Info. 308 const TargetLibraryInfo *TLI; 309 310 /// The vectorization SIMD factor to use. Each vector will have this many 311 /// vector elements. 312 unsigned VF; 313 314 protected: 315 /// The vectorization unroll factor to use. Each scalar is vectorized to this 316 /// many different vector instructions. 317 unsigned UF; 318 319 /// The builder that we use 320 IRBuilder<> Builder; 321 322 // --- Vectorization state --- 323 324 /// The vector-loop preheader. 325 BasicBlock *LoopVectorPreHeader; 326 /// The scalar-loop preheader. 327 BasicBlock *LoopScalarPreHeader; 328 /// Middle Block between the vector and the scalar. 329 BasicBlock *LoopMiddleBlock; 330 ///The ExitBlock of the scalar loop. 331 BasicBlock *LoopExitBlock; 332 ///The vector loop body. 333 BasicBlock *LoopVectorBody; 334 ///The scalar loop body. 335 BasicBlock *LoopScalarBody; 336 /// A list of all bypass blocks. The first block is the entry of the loop. 337 SmallVector<BasicBlock *, 4> LoopBypassBlocks; 338 339 /// The new Induction variable which was added to the new block. 340 PHINode *Induction; 341 /// The induction variable of the old basic block. 342 PHINode *OldInduction; 343 /// Holds the extended (to the widest induction type) start index. 344 Value *ExtendedIdx; 345 /// Maps scalars to widened vectors. 346 ValueMap WidenMap; 347 EdgeMaskCache MaskCache; 348 }; 349 350 class InnerLoopUnroller : public InnerLoopVectorizer { 351 public: 352 InnerLoopUnroller(Loop *OrigLoop, ScalarEvolution *SE, LoopInfo *LI, 353 DominatorTree *DT, DataLayout *DL, 354 const TargetLibraryInfo *TLI, unsigned UnrollFactor) : 355 InnerLoopVectorizer(OrigLoop, SE, LI, DT, DL, TLI, 1, UnrollFactor) { } 356 357 private: 358 virtual void scalarizeInstruction(Instruction *Instr); 359 virtual void vectorizeMemoryInstruction(Instruction *Instr, 360 LoopVectorizationLegality *Legal); 361 virtual Value *getBroadcastInstrs(Value *V); 362 virtual Value *getConsecutiveVector(Value* Val, int StartIdx, bool Negate); 363 virtual Value *reverseVector(Value *Vec); 364 }; 365 366 /// \brief Look for a meaningful debug location on the instruction or it's 367 /// operands. 368 static Instruction *getDebugLocFromInstOrOperands(Instruction *I) { 369 if (!I) 370 return I; 371 372 DebugLoc Empty; 373 if (I->getDebugLoc() != Empty) 374 return I; 375 376 for (User::op_iterator OI = I->op_begin(), OE = I->op_end(); OI != OE; ++OI) { 377 if (Instruction *OpInst = dyn_cast<Instruction>(*OI)) 378 if (OpInst->getDebugLoc() != Empty) 379 return OpInst; 380 } 381 382 return I; 383 } 384 385 /// \brief Set the debug location in the builder using the debug location in the 386 /// instruction. 387 static void setDebugLocFromInst(IRBuilder<> &B, const Value *Ptr) { 388 if (const Instruction *Inst = dyn_cast_or_null<Instruction>(Ptr)) 389 B.SetCurrentDebugLocation(Inst->getDebugLoc()); 390 else 391 B.SetCurrentDebugLocation(DebugLoc()); 392 } 393 394 /// LoopVectorizationLegality checks if it is legal to vectorize a loop, and 395 /// to what vectorization factor. 396 /// This class does not look at the profitability of vectorization, only the 397 /// legality. This class has two main kinds of checks: 398 /// * Memory checks - The code in canVectorizeMemory checks if vectorization 399 /// will change the order of memory accesses in a way that will change the 400 /// correctness of the program. 401 /// * Scalars checks - The code in canVectorizeInstrs and canVectorizeMemory 402 /// checks for a number of different conditions, such as the availability of a 403 /// single induction variable, that all types are supported and vectorize-able, 404 /// etc. This code reflects the capabilities of InnerLoopVectorizer. 405 /// This class is also used by InnerLoopVectorizer for identifying 406 /// induction variable and the different reduction variables. 407 class LoopVectorizationLegality { 408 public: 409 LoopVectorizationLegality(Loop *L, ScalarEvolution *SE, DataLayout *DL, 410 DominatorTree *DT, TargetLibraryInfo *TLI) 411 : TheLoop(L), SE(SE), DL(DL), DT(DT), TLI(TLI), 412 Induction(0), WidestIndTy(0), HasFunNoNaNAttr(false), 413 MaxSafeDepDistBytes(-1U) {} 414 415 /// This enum represents the kinds of reductions that we support. 416 enum ReductionKind { 417 RK_NoReduction, ///< Not a reduction. 418 RK_IntegerAdd, ///< Sum of integers. 419 RK_IntegerMult, ///< Product of integers. 420 RK_IntegerOr, ///< Bitwise or logical OR of numbers. 421 RK_IntegerAnd, ///< Bitwise or logical AND of numbers. 422 RK_IntegerXor, ///< Bitwise or logical XOR of numbers. 423 RK_IntegerMinMax, ///< Min/max implemented in terms of select(cmp()). 424 RK_FloatAdd, ///< Sum of floats. 425 RK_FloatMult, ///< Product of floats. 426 RK_FloatMinMax ///< Min/max implemented in terms of select(cmp()). 427 }; 428 429 /// This enum represents the kinds of inductions that we support. 430 enum InductionKind { 431 IK_NoInduction, ///< Not an induction variable. 432 IK_IntInduction, ///< Integer induction variable. Step = 1. 433 IK_ReverseIntInduction, ///< Reverse int induction variable. Step = -1. 434 IK_PtrInduction, ///< Pointer induction var. Step = sizeof(elem). 435 IK_ReversePtrInduction ///< Reverse ptr indvar. Step = - sizeof(elem). 436 }; 437 438 // This enum represents the kind of minmax reduction. 439 enum MinMaxReductionKind { 440 MRK_Invalid, 441 MRK_UIntMin, 442 MRK_UIntMax, 443 MRK_SIntMin, 444 MRK_SIntMax, 445 MRK_FloatMin, 446 MRK_FloatMax 447 }; 448 449 /// This struct holds information about reduction variables. 450 struct ReductionDescriptor { 451 ReductionDescriptor() : StartValue(0), LoopExitInstr(0), 452 Kind(RK_NoReduction), MinMaxKind(MRK_Invalid) {} 453 454 ReductionDescriptor(Value *Start, Instruction *Exit, ReductionKind K, 455 MinMaxReductionKind MK) 456 : StartValue(Start), LoopExitInstr(Exit), Kind(K), MinMaxKind(MK) {} 457 458 // The starting value of the reduction. 459 // It does not have to be zero! 460 TrackingVH<Value> StartValue; 461 // The instruction who's value is used outside the loop. 462 Instruction *LoopExitInstr; 463 // The kind of the reduction. 464 ReductionKind Kind; 465 // If this a min/max reduction the kind of reduction. 466 MinMaxReductionKind MinMaxKind; 467 }; 468 469 /// This POD struct holds information about a potential reduction operation. 470 struct ReductionInstDesc { 471 ReductionInstDesc(bool IsRedux, Instruction *I) : 472 IsReduction(IsRedux), PatternLastInst(I), MinMaxKind(MRK_Invalid) {} 473 474 ReductionInstDesc(Instruction *I, MinMaxReductionKind K) : 475 IsReduction(true), PatternLastInst(I), MinMaxKind(K) {} 476 477 // Is this instruction a reduction candidate. 478 bool IsReduction; 479 // The last instruction in a min/max pattern (select of the select(icmp()) 480 // pattern), or the current reduction instruction otherwise. 481 Instruction *PatternLastInst; 482 // If this is a min/max pattern the comparison predicate. 483 MinMaxReductionKind MinMaxKind; 484 }; 485 486 /// This struct holds information about the memory runtime legality 487 /// check that a group of pointers do not overlap. 488 struct RuntimePointerCheck { 489 RuntimePointerCheck() : Need(false) {} 490 491 /// Reset the state of the pointer runtime information. 492 void reset() { 493 Need = false; 494 Pointers.clear(); 495 Starts.clear(); 496 Ends.clear(); 497 IsWritePtr.clear(); 498 DependencySetId.clear(); 499 } 500 501 /// Insert a pointer and calculate the start and end SCEVs. 502 void insert(ScalarEvolution *SE, Loop *Lp, Value *Ptr, bool WritePtr, 503 unsigned DepSetId); 504 505 /// This flag indicates if we need to add the runtime check. 506 bool Need; 507 /// Holds the pointers that we need to check. 508 SmallVector<TrackingVH<Value>, 2> Pointers; 509 /// Holds the pointer value at the beginning of the loop. 510 SmallVector<const SCEV*, 2> Starts; 511 /// Holds the pointer value at the end of the loop. 512 SmallVector<const SCEV*, 2> Ends; 513 /// Holds the information if this pointer is used for writing to memory. 514 SmallVector<bool, 2> IsWritePtr; 515 /// Holds the id of the set of pointers that could be dependent because of a 516 /// shared underlying object. 517 SmallVector<unsigned, 2> DependencySetId; 518 }; 519 520 /// A struct for saving information about induction variables. 521 struct InductionInfo { 522 InductionInfo(Value *Start, InductionKind K) : StartValue(Start), IK(K) {} 523 InductionInfo() : StartValue(0), IK(IK_NoInduction) {} 524 /// Start value. 525 TrackingVH<Value> StartValue; 526 /// Induction kind. 527 InductionKind IK; 528 }; 529 530 /// ReductionList contains the reduction descriptors for all 531 /// of the reductions that were found in the loop. 532 typedef DenseMap<PHINode*, ReductionDescriptor> ReductionList; 533 534 /// InductionList saves induction variables and maps them to the 535 /// induction descriptor. 536 typedef MapVector<PHINode*, InductionInfo> InductionList; 537 538 /// Returns true if it is legal to vectorize this loop. 539 /// This does not mean that it is profitable to vectorize this 540 /// loop, only that it is legal to do so. 541 bool canVectorize(); 542 543 /// Returns the Induction variable. 544 PHINode *getInduction() { return Induction; } 545 546 /// Returns the reduction variables found in the loop. 547 ReductionList *getReductionVars() { return &Reductions; } 548 549 /// Returns the induction variables found in the loop. 550 InductionList *getInductionVars() { return &Inductions; } 551 552 /// Returns the widest induction type. 553 Type *getWidestInductionType() { return WidestIndTy; } 554 555 /// Returns True if V is an induction variable in this loop. 556 bool isInductionVariable(const Value *V); 557 558 /// Return true if the block BB needs to be predicated in order for the loop 559 /// to be vectorized. 560 bool blockNeedsPredication(BasicBlock *BB); 561 562 /// Check if this pointer is consecutive when vectorizing. This happens 563 /// when the last index of the GEP is the induction variable, or that the 564 /// pointer itself is an induction variable. 565 /// This check allows us to vectorize A[idx] into a wide load/store. 566 /// Returns: 567 /// 0 - Stride is unknown or non-consecutive. 568 /// 1 - Address is consecutive. 569 /// -1 - Address is consecutive, and decreasing. 570 int isConsecutivePtr(Value *Ptr); 571 572 /// Returns true if the value V is uniform within the loop. 573 bool isUniform(Value *V); 574 575 /// Returns true if this instruction will remain scalar after vectorization. 576 bool isUniformAfterVectorization(Instruction* I) { return Uniforms.count(I); } 577 578 /// Returns the information that we collected about runtime memory check. 579 RuntimePointerCheck *getRuntimePointerCheck() { return &PtrRtCheck; } 580 581 /// This function returns the identity element (or neutral element) for 582 /// the operation K. 583 static Constant *getReductionIdentity(ReductionKind K, Type *Tp); 584 585 unsigned getMaxSafeDepDistBytes() { return MaxSafeDepDistBytes; } 586 587 private: 588 /// Check if a single basic block loop is vectorizable. 589 /// At this point we know that this is a loop with a constant trip count 590 /// and we only need to check individual instructions. 591 bool canVectorizeInstrs(); 592 593 /// When we vectorize loops we may change the order in which 594 /// we read and write from memory. This method checks if it is 595 /// legal to vectorize the code, considering only memory constrains. 596 /// Returns true if the loop is vectorizable 597 bool canVectorizeMemory(); 598 599 /// Return true if we can vectorize this loop using the IF-conversion 600 /// transformation. 601 bool canVectorizeWithIfConvert(); 602 603 /// Collect the variables that need to stay uniform after vectorization. 604 void collectLoopUniforms(); 605 606 /// Return true if all of the instructions in the block can be speculatively 607 /// executed. \p SafePtrs is a list of addresses that are known to be legal 608 /// and we know that we can read from them without segfault. 609 bool blockCanBePredicated(BasicBlock *BB, SmallPtrSet<Value *, 8>& SafePtrs); 610 611 /// Returns True, if 'Phi' is the kind of reduction variable for type 612 /// 'Kind'. If this is a reduction variable, it adds it to ReductionList. 613 bool AddReductionVar(PHINode *Phi, ReductionKind Kind); 614 /// Returns a struct describing if the instruction 'I' can be a reduction 615 /// variable of type 'Kind'. If the reduction is a min/max pattern of 616 /// select(icmp()) this function advances the instruction pointer 'I' from the 617 /// compare instruction to the select instruction and stores this pointer in 618 /// 'PatternLastInst' member of the returned struct. 619 ReductionInstDesc isReductionInstr(Instruction *I, ReductionKind Kind, 620 ReductionInstDesc &Desc); 621 /// Returns true if the instruction is a Select(ICmp(X, Y), X, Y) instruction 622 /// pattern corresponding to a min(X, Y) or max(X, Y). 623 static ReductionInstDesc isMinMaxSelectCmpPattern(Instruction *I, 624 ReductionInstDesc &Prev); 625 /// Returns the induction kind of Phi. This function may return NoInduction 626 /// if the PHI is not an induction variable. 627 InductionKind isInductionVariable(PHINode *Phi); 628 629 /// The loop that we evaluate. 630 Loop *TheLoop; 631 /// Scev analysis. 632 ScalarEvolution *SE; 633 /// DataLayout analysis. 634 DataLayout *DL; 635 /// Dominators. 636 DominatorTree *DT; 637 /// Target Library Info. 638 TargetLibraryInfo *TLI; 639 640 // --- vectorization state --- // 641 642 /// Holds the integer induction variable. This is the counter of the 643 /// loop. 644 PHINode *Induction; 645 /// Holds the reduction variables. 646 ReductionList Reductions; 647 /// Holds all of the induction variables that we found in the loop. 648 /// Notice that inductions don't need to start at zero and that induction 649 /// variables can be pointers. 650 InductionList Inductions; 651 /// Holds the widest induction type encountered. 652 Type *WidestIndTy; 653 654 /// Allowed outside users. This holds the reduction 655 /// vars which can be accessed from outside the loop. 656 SmallPtrSet<Value*, 4> AllowedExit; 657 /// This set holds the variables which are known to be uniform after 658 /// vectorization. 659 SmallPtrSet<Instruction*, 4> Uniforms; 660 /// We need to check that all of the pointers in this list are disjoint 661 /// at runtime. 662 RuntimePointerCheck PtrRtCheck; 663 /// Can we assume the absence of NaNs. 664 bool HasFunNoNaNAttr; 665 666 unsigned MaxSafeDepDistBytes; 667 }; 668 669 /// LoopVectorizationCostModel - estimates the expected speedups due to 670 /// vectorization. 671 /// In many cases vectorization is not profitable. This can happen because of 672 /// a number of reasons. In this class we mainly attempt to predict the 673 /// expected speedup/slowdowns due to the supported instruction set. We use the 674 /// TargetTransformInfo to query the different backends for the cost of 675 /// different operations. 676 class LoopVectorizationCostModel { 677 public: 678 LoopVectorizationCostModel(Loop *L, ScalarEvolution *SE, LoopInfo *LI, 679 LoopVectorizationLegality *Legal, 680 const TargetTransformInfo &TTI, 681 DataLayout *DL, const TargetLibraryInfo *TLI) 682 : TheLoop(L), SE(SE), LI(LI), Legal(Legal), TTI(TTI), DL(DL), TLI(TLI) {} 683 684 /// Information about vectorization costs 685 struct VectorizationFactor { 686 unsigned Width; // Vector width with best cost 687 unsigned Cost; // Cost of the loop with that width 688 }; 689 /// \return The most profitable vectorization factor and the cost of that VF. 690 /// This method checks every power of two up to VF. If UserVF is not ZERO 691 /// then this vectorization factor will be selected if vectorization is 692 /// possible. 693 VectorizationFactor selectVectorizationFactor(bool OptForSize, 694 unsigned UserVF); 695 696 /// \return The size (in bits) of the widest type in the code that 697 /// needs to be vectorized. We ignore values that remain scalar such as 698 /// 64 bit loop indices. 699 unsigned getWidestType(); 700 701 /// \return The most profitable unroll factor. 702 /// If UserUF is non-zero then this method finds the best unroll-factor 703 /// based on register pressure and other parameters. 704 /// VF and LoopCost are the selected vectorization factor and the cost of the 705 /// selected VF. 706 unsigned selectUnrollFactor(bool OptForSize, unsigned UserUF, unsigned VF, 707 unsigned LoopCost); 708 709 /// \brief A struct that represents some properties of the register usage 710 /// of a loop. 711 struct RegisterUsage { 712 /// Holds the number of loop invariant values that are used in the loop. 713 unsigned LoopInvariantRegs; 714 /// Holds the maximum number of concurrent live intervals in the loop. 715 unsigned MaxLocalUsers; 716 /// Holds the number of instructions in the loop. 717 unsigned NumInstructions; 718 }; 719 720 /// \return information about the register usage of the loop. 721 RegisterUsage calculateRegisterUsage(); 722 723 private: 724 /// Returns the expected execution cost. The unit of the cost does 725 /// not matter because we use the 'cost' units to compare different 726 /// vector widths. The cost that is returned is *not* normalized by 727 /// the factor width. 728 unsigned expectedCost(unsigned VF); 729 730 /// Returns the execution time cost of an instruction for a given vector 731 /// width. Vector width of one means scalar. 732 unsigned getInstructionCost(Instruction *I, unsigned VF); 733 734 /// A helper function for converting Scalar types to vector types. 735 /// If the incoming type is void, we return void. If the VF is 1, we return 736 /// the scalar type. 737 static Type* ToVectorTy(Type *Scalar, unsigned VF); 738 739 /// Returns whether the instruction is a load or store and will be a emitted 740 /// as a vector operation. 741 bool isConsecutiveLoadOrStore(Instruction *I); 742 743 /// The loop that we evaluate. 744 Loop *TheLoop; 745 /// Scev analysis. 746 ScalarEvolution *SE; 747 /// Loop Info analysis. 748 LoopInfo *LI; 749 /// Vectorization legality. 750 LoopVectorizationLegality *Legal; 751 /// Vector target information. 752 const TargetTransformInfo &TTI; 753 /// Target data layout information. 754 DataLayout *DL; 755 /// Target Library Info. 756 const TargetLibraryInfo *TLI; 757 }; 758 759 /// Utility class for getting and setting loop vectorizer hints in the form 760 /// of loop metadata. 761 struct LoopVectorizeHints { 762 /// Vectorization width. 763 unsigned Width; 764 /// Vectorization unroll factor. 765 unsigned Unroll; 766 /// Vectorization forced (-1 not selected, 0 force disabled, 1 force enabled) 767 int Force; 768 769 LoopVectorizeHints(const Loop *L, bool DisableUnrolling) 770 : Width(VectorizationFactor) 771 , Unroll(DisableUnrolling ? 1 : VectorizationUnroll) 772 , Force(-1) 773 , LoopID(L->getLoopID()) { 774 getHints(L); 775 // The command line options override any loop metadata except for when 776 // width == 1 which is used to indicate the loop is already vectorized. 777 if (VectorizationFactor.getNumOccurrences() > 0 && Width != 1) 778 Width = VectorizationFactor; 779 if (VectorizationUnroll.getNumOccurrences() > 0) 780 Unroll = VectorizationUnroll; 781 782 DEBUG(if (DisableUnrolling && Unroll == 1) 783 dbgs() << "LV: Unrolling disabled by the pass manager\n"); 784 } 785 786 /// Return the loop vectorizer metadata prefix. 787 static StringRef Prefix() { return "llvm.vectorizer."; } 788 789 MDNode *createHint(LLVMContext &Context, StringRef Name, unsigned V) { 790 SmallVector<Value*, 2> Vals; 791 Vals.push_back(MDString::get(Context, Name)); 792 Vals.push_back(ConstantInt::get(Type::getInt32Ty(Context), V)); 793 return MDNode::get(Context, Vals); 794 } 795 796 /// Mark the loop L as already vectorized by setting the width to 1. 797 void setAlreadyVectorized(Loop *L) { 798 LLVMContext &Context = L->getHeader()->getContext(); 799 800 Width = 1; 801 802 // Create a new loop id with one more operand for the already_vectorized 803 // hint. If the loop already has a loop id then copy the existing operands. 804 SmallVector<Value*, 4> Vals(1); 805 if (LoopID) 806 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) 807 Vals.push_back(LoopID->getOperand(i)); 808 809 Vals.push_back(createHint(Context, Twine(Prefix(), "width").str(), Width)); 810 Vals.push_back(createHint(Context, Twine(Prefix(), "unroll").str(), 1)); 811 812 MDNode *NewLoopID = MDNode::get(Context, Vals); 813 // Set operand 0 to refer to the loop id itself. 814 NewLoopID->replaceOperandWith(0, NewLoopID); 815 816 L->setLoopID(NewLoopID); 817 if (LoopID) 818 LoopID->replaceAllUsesWith(NewLoopID); 819 820 LoopID = NewLoopID; 821 } 822 823 private: 824 MDNode *LoopID; 825 826 /// Find hints specified in the loop metadata. 827 void getHints(const Loop *L) { 828 if (!LoopID) 829 return; 830 831 // First operand should refer to the loop id itself. 832 assert(LoopID->getNumOperands() > 0 && "requires at least one operand"); 833 assert(LoopID->getOperand(0) == LoopID && "invalid loop id"); 834 835 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) { 836 const MDString *S = 0; 837 SmallVector<Value*, 4> Args; 838 839 // The expected hint is either a MDString or a MDNode with the first 840 // operand a MDString. 841 if (const MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i))) { 842 if (!MD || MD->getNumOperands() == 0) 843 continue; 844 S = dyn_cast<MDString>(MD->getOperand(0)); 845 for (unsigned i = 1, ie = MD->getNumOperands(); i < ie; ++i) 846 Args.push_back(MD->getOperand(i)); 847 } else { 848 S = dyn_cast<MDString>(LoopID->getOperand(i)); 849 assert(Args.size() == 0 && "too many arguments for MDString"); 850 } 851 852 if (!S) 853 continue; 854 855 // Check if the hint starts with the vectorizer prefix. 856 StringRef Hint = S->getString(); 857 if (!Hint.startswith(Prefix())) 858 continue; 859 // Remove the prefix. 860 Hint = Hint.substr(Prefix().size(), StringRef::npos); 861 862 if (Args.size() == 1) 863 getHint(Hint, Args[0]); 864 } 865 } 866 867 // Check string hint with one operand. 868 void getHint(StringRef Hint, Value *Arg) { 869 const ConstantInt *C = dyn_cast<ConstantInt>(Arg); 870 if (!C) return; 871 unsigned Val = C->getZExtValue(); 872 873 if (Hint == "width") { 874 if (isPowerOf2_32(Val) && Val <= MaxVectorWidth) 875 Width = Val; 876 else 877 DEBUG(dbgs() << "LV: ignoring invalid width hint metadata\n"); 878 } else if (Hint == "unroll") { 879 if (isPowerOf2_32(Val) && Val <= MaxUnrollFactor) 880 Unroll = Val; 881 else 882 DEBUG(dbgs() << "LV: ignoring invalid unroll hint metadata\n"); 883 } else if (Hint == "enable") { 884 if (C->getBitWidth() == 1) 885 Force = Val; 886 else 887 DEBUG(dbgs() << "LV: ignoring invalid enable hint metadata\n"); 888 } else { 889 DEBUG(dbgs() << "LV: ignoring unknown hint " << Hint << '\n'); 890 } 891 } 892 }; 893 894 /// The LoopVectorize Pass. 895 struct LoopVectorize : public LoopPass { 896 /// Pass identification, replacement for typeid 897 static char ID; 898 899 explicit LoopVectorize(bool NoUnrolling = false, bool AlwaysVectorize = true) 900 : LoopPass(ID), 901 DisableUnrolling(NoUnrolling), 902 AlwaysVectorize(AlwaysVectorize) { 903 initializeLoopVectorizePass(*PassRegistry::getPassRegistry()); 904 } 905 906 ScalarEvolution *SE; 907 DataLayout *DL; 908 LoopInfo *LI; 909 TargetTransformInfo *TTI; 910 DominatorTree *DT; 911 TargetLibraryInfo *TLI; 912 bool DisableUnrolling; 913 bool AlwaysVectorize; 914 915 virtual bool runOnLoop(Loop *L, LPPassManager &LPM) { 916 // We only vectorize innermost loops. 917 if (!L->empty()) 918 return false; 919 920 SE = &getAnalysis<ScalarEvolution>(); 921 DL = getAnalysisIfAvailable<DataLayout>(); 922 LI = &getAnalysis<LoopInfo>(); 923 TTI = &getAnalysis<TargetTransformInfo>(); 924 DT = &getAnalysis<DominatorTree>(); 925 TLI = getAnalysisIfAvailable<TargetLibraryInfo>(); 926 927 // If the target claims to have no vector registers don't attempt 928 // vectorization. 929 if (!TTI->getNumberOfRegisters(true)) 930 return false; 931 932 if (DL == NULL) { 933 DEBUG(dbgs() << "LV: Not vectorizing: Missing data layout\n"); 934 return false; 935 } 936 937 DEBUG(dbgs() << "LV: Checking a loop in \"" << 938 L->getHeader()->getParent()->getName() << "\"\n"); 939 940 LoopVectorizeHints Hints(L, DisableUnrolling); 941 942 if (Hints.Force == 0) { 943 DEBUG(dbgs() << "LV: Not vectorizing: #pragma vectorize disable.\n"); 944 return false; 945 } 946 947 if (!AlwaysVectorize && Hints.Force != 1) { 948 DEBUG(dbgs() << "LV: Not vectorizing: No #pragma vectorize enable.\n"); 949 return false; 950 } 951 952 if (Hints.Width == 1 && Hints.Unroll == 1) { 953 DEBUG(dbgs() << "LV: Not vectorizing: Disabled/already vectorized.\n"); 954 return false; 955 } 956 957 // Check if it is legal to vectorize the loop. 958 LoopVectorizationLegality LVL(L, SE, DL, DT, TLI); 959 if (!LVL.canVectorize()) { 960 DEBUG(dbgs() << "LV: Not vectorizing: Cannot prove legality.\n"); 961 return false; 962 } 963 964 // Use the cost model. 965 LoopVectorizationCostModel CM(L, SE, LI, &LVL, *TTI, DL, TLI); 966 967 // Check the function attributes to find out if this function should be 968 // optimized for size. 969 Function *F = L->getHeader()->getParent(); 970 Attribute::AttrKind SzAttr = Attribute::OptimizeForSize; 971 Attribute::AttrKind FlAttr = Attribute::NoImplicitFloat; 972 unsigned FnIndex = AttributeSet::FunctionIndex; 973 bool OptForSize = Hints.Force != 1 && 974 F->getAttributes().hasAttribute(FnIndex, SzAttr); 975 bool NoFloat = F->getAttributes().hasAttribute(FnIndex, FlAttr); 976 977 if (NoFloat) { 978 DEBUG(dbgs() << "LV: Can't vectorize when the NoImplicitFloat" 979 "attribute is used.\n"); 980 return false; 981 } 982 983 // Select the optimal vectorization factor. 984 LoopVectorizationCostModel::VectorizationFactor VF; 985 VF = CM.selectVectorizationFactor(OptForSize, Hints.Width); 986 // Select the unroll factor. 987 unsigned UF = CM.selectUnrollFactor(OptForSize, Hints.Unroll, VF.Width, 988 VF.Cost); 989 990 DEBUG(dbgs() << "LV: Found a vectorizable loop ("<< VF.Width << ") in "<< 991 F->getParent()->getModuleIdentifier() << '\n'); 992 DEBUG(dbgs() << "LV: Unroll Factor is " << UF << '\n'); 993 994 if (VF.Width == 1) { 995 DEBUG(dbgs() << "LV: Vectorization is possible but not beneficial.\n"); 996 if (UF == 1) 997 return false; 998 DEBUG(dbgs() << "LV: Trying to at least unroll the loops.\n"); 999 // We decided not to vectorize, but we may want to unroll. 1000 InnerLoopUnroller Unroller(L, SE, LI, DT, DL, TLI, UF); 1001 Unroller.vectorize(&LVL); 1002 } else { 1003 // If we decided that it is *legal* to vectorize the loop then do it. 1004 InnerLoopVectorizer LB(L, SE, LI, DT, DL, TLI, VF.Width, UF); 1005 LB.vectorize(&LVL); 1006 } 1007 1008 // Mark the loop as already vectorized to avoid vectorizing again. 1009 Hints.setAlreadyVectorized(L); 1010 1011 DEBUG(verifyFunction(*L->getHeader()->getParent())); 1012 return true; 1013 } 1014 1015 virtual void getAnalysisUsage(AnalysisUsage &AU) const { 1016 LoopPass::getAnalysisUsage(AU); 1017 AU.addRequiredID(LoopSimplifyID); 1018 AU.addRequiredID(LCSSAID); 1019 AU.addRequired<DominatorTree>(); 1020 AU.addRequired<LoopInfo>(); 1021 AU.addRequired<ScalarEvolution>(); 1022 AU.addRequired<TargetTransformInfo>(); 1023 AU.addPreserved<LoopInfo>(); 1024 AU.addPreserved<DominatorTree>(); 1025 } 1026 1027 }; 1028 1029 } // end anonymous namespace 1030 1031 //===----------------------------------------------------------------------===// 1032 // Implementation of LoopVectorizationLegality, InnerLoopVectorizer and 1033 // LoopVectorizationCostModel. 1034 //===----------------------------------------------------------------------===// 1035 1036 void 1037 LoopVectorizationLegality::RuntimePointerCheck::insert(ScalarEvolution *SE, 1038 Loop *Lp, Value *Ptr, 1039 bool WritePtr, 1040 unsigned DepSetId) { 1041 const SCEV *Sc = SE->getSCEV(Ptr); 1042 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Sc); 1043 assert(AR && "Invalid addrec expression"); 1044 const SCEV *Ex = SE->getBackedgeTakenCount(Lp); 1045 const SCEV *ScEnd = AR->evaluateAtIteration(Ex, *SE); 1046 Pointers.push_back(Ptr); 1047 Starts.push_back(AR->getStart()); 1048 Ends.push_back(ScEnd); 1049 IsWritePtr.push_back(WritePtr); 1050 DependencySetId.push_back(DepSetId); 1051 } 1052 1053 Value *InnerLoopVectorizer::getBroadcastInstrs(Value *V) { 1054 // We need to place the broadcast of invariant variables outside the loop. 1055 Instruction *Instr = dyn_cast<Instruction>(V); 1056 bool NewInstr = (Instr && Instr->getParent() == LoopVectorBody); 1057 bool Invariant = OrigLoop->isLoopInvariant(V) && !NewInstr; 1058 1059 // Place the code for broadcasting invariant variables in the new preheader. 1060 IRBuilder<>::InsertPointGuard Guard(Builder); 1061 if (Invariant) 1062 Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator()); 1063 1064 // Broadcast the scalar into all locations in the vector. 1065 Value *Shuf = Builder.CreateVectorSplat(VF, V, "broadcast"); 1066 1067 return Shuf; 1068 } 1069 1070 Value *InnerLoopVectorizer::getConsecutiveVector(Value* Val, int StartIdx, 1071 bool Negate) { 1072 assert(Val->getType()->isVectorTy() && "Must be a vector"); 1073 assert(Val->getType()->getScalarType()->isIntegerTy() && 1074 "Elem must be an integer"); 1075 // Create the types. 1076 Type *ITy = Val->getType()->getScalarType(); 1077 VectorType *Ty = cast<VectorType>(Val->getType()); 1078 int VLen = Ty->getNumElements(); 1079 SmallVector<Constant*, 8> Indices; 1080 1081 // Create a vector of consecutive numbers from zero to VF. 1082 for (int i = 0; i < VLen; ++i) { 1083 int64_t Idx = Negate ? (-i) : i; 1084 Indices.push_back(ConstantInt::get(ITy, StartIdx + Idx, Negate)); 1085 } 1086 1087 // Add the consecutive indices to the vector value. 1088 Constant *Cv = ConstantVector::get(Indices); 1089 assert(Cv->getType() == Val->getType() && "Invalid consecutive vec"); 1090 return Builder.CreateAdd(Val, Cv, "induction"); 1091 } 1092 1093 /// \brief Find the operand of the GEP that should be checked for consecutive 1094 /// stores. This ignores trailing indices that have no effect on the final 1095 /// pointer. 1096 static unsigned getGEPInductionOperand(DataLayout *DL, 1097 const GetElementPtrInst *Gep) { 1098 unsigned LastOperand = Gep->getNumOperands() - 1; 1099 unsigned GEPAllocSize = DL->getTypeAllocSize( 1100 cast<PointerType>(Gep->getType()->getScalarType())->getElementType()); 1101 1102 // Walk backwards and try to peel off zeros. 1103 while (LastOperand > 1 && match(Gep->getOperand(LastOperand), m_Zero())) { 1104 // Find the type we're currently indexing into. 1105 gep_type_iterator GEPTI = gep_type_begin(Gep); 1106 std::advance(GEPTI, LastOperand - 1); 1107 1108 // If it's a type with the same allocation size as the result of the GEP we 1109 // can peel off the zero index. 1110 if (DL->getTypeAllocSize(*GEPTI) != GEPAllocSize) 1111 break; 1112 --LastOperand; 1113 } 1114 1115 return LastOperand; 1116 } 1117 1118 int LoopVectorizationLegality::isConsecutivePtr(Value *Ptr) { 1119 assert(Ptr->getType()->isPointerTy() && "Unexpected non-ptr"); 1120 // Make sure that the pointer does not point to structs. 1121 if (Ptr->getType()->getPointerElementType()->isAggregateType()) 1122 return 0; 1123 1124 // If this value is a pointer induction variable we know it is consecutive. 1125 PHINode *Phi = dyn_cast_or_null<PHINode>(Ptr); 1126 if (Phi && Inductions.count(Phi)) { 1127 InductionInfo II = Inductions[Phi]; 1128 if (IK_PtrInduction == II.IK) 1129 return 1; 1130 else if (IK_ReversePtrInduction == II.IK) 1131 return -1; 1132 } 1133 1134 GetElementPtrInst *Gep = dyn_cast_or_null<GetElementPtrInst>(Ptr); 1135 if (!Gep) 1136 return 0; 1137 1138 unsigned NumOperands = Gep->getNumOperands(); 1139 Value *GpPtr = Gep->getPointerOperand(); 1140 // If this GEP value is a consecutive pointer induction variable and all of 1141 // the indices are constant then we know it is consecutive. We can 1142 Phi = dyn_cast<PHINode>(GpPtr); 1143 if (Phi && Inductions.count(Phi)) { 1144 1145 // Make sure that the pointer does not point to structs. 1146 PointerType *GepPtrType = cast<PointerType>(GpPtr->getType()); 1147 if (GepPtrType->getElementType()->isAggregateType()) 1148 return 0; 1149 1150 // Make sure that all of the index operands are loop invariant. 1151 for (unsigned i = 1; i < NumOperands; ++i) 1152 if (!SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop)) 1153 return 0; 1154 1155 InductionInfo II = Inductions[Phi]; 1156 if (IK_PtrInduction == II.IK) 1157 return 1; 1158 else if (IK_ReversePtrInduction == II.IK) 1159 return -1; 1160 } 1161 1162 unsigned InductionOperand = getGEPInductionOperand(DL, Gep); 1163 1164 // Check that all of the gep indices are uniform except for our induction 1165 // operand. 1166 for (unsigned i = 0; i != NumOperands; ++i) 1167 if (i != InductionOperand && 1168 !SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop)) 1169 return 0; 1170 1171 // We can emit wide load/stores only if the last non-zero index is the 1172 // induction variable. 1173 const SCEV *Last = SE->getSCEV(Gep->getOperand(InductionOperand)); 1174 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Last)) { 1175 const SCEV *Step = AR->getStepRecurrence(*SE); 1176 1177 // The memory is consecutive because the last index is consecutive 1178 // and all other indices are loop invariant. 1179 if (Step->isOne()) 1180 return 1; 1181 if (Step->isAllOnesValue()) 1182 return -1; 1183 } 1184 1185 return 0; 1186 } 1187 1188 bool LoopVectorizationLegality::isUniform(Value *V) { 1189 return (SE->isLoopInvariant(SE->getSCEV(V), TheLoop)); 1190 } 1191 1192 InnerLoopVectorizer::VectorParts& 1193 InnerLoopVectorizer::getVectorValue(Value *V) { 1194 assert(V != Induction && "The new induction variable should not be used."); 1195 assert(!V->getType()->isVectorTy() && "Can't widen a vector"); 1196 1197 // If we have this scalar in the map, return it. 1198 if (WidenMap.has(V)) 1199 return WidenMap.get(V); 1200 1201 // If this scalar is unknown, assume that it is a constant or that it is 1202 // loop invariant. Broadcast V and save the value for future uses. 1203 Value *B = getBroadcastInstrs(V); 1204 return WidenMap.splat(V, B); 1205 } 1206 1207 Value *InnerLoopVectorizer::reverseVector(Value *Vec) { 1208 assert(Vec->getType()->isVectorTy() && "Invalid type"); 1209 SmallVector<Constant*, 8> ShuffleMask; 1210 for (unsigned i = 0; i < VF; ++i) 1211 ShuffleMask.push_back(Builder.getInt32(VF - i - 1)); 1212 1213 return Builder.CreateShuffleVector(Vec, UndefValue::get(Vec->getType()), 1214 ConstantVector::get(ShuffleMask), 1215 "reverse"); 1216 } 1217 1218 1219 void InnerLoopVectorizer::vectorizeMemoryInstruction(Instruction *Instr, 1220 LoopVectorizationLegality *Legal) { 1221 // Attempt to issue a wide load. 1222 LoadInst *LI = dyn_cast<LoadInst>(Instr); 1223 StoreInst *SI = dyn_cast<StoreInst>(Instr); 1224 1225 assert((LI || SI) && "Invalid Load/Store instruction"); 1226 1227 Type *ScalarDataTy = LI ? LI->getType() : SI->getValueOperand()->getType(); 1228 Type *DataTy = VectorType::get(ScalarDataTy, VF); 1229 Value *Ptr = LI ? LI->getPointerOperand() : SI->getPointerOperand(); 1230 unsigned Alignment = LI ? LI->getAlignment() : SI->getAlignment(); 1231 // An alignment of 0 means target abi alignment. We need to use the scalar's 1232 // target abi alignment in such a case. 1233 if (!Alignment) 1234 Alignment = DL->getABITypeAlignment(ScalarDataTy); 1235 unsigned AddressSpace = Ptr->getType()->getPointerAddressSpace(); 1236 unsigned ScalarAllocatedSize = DL->getTypeAllocSize(ScalarDataTy); 1237 unsigned VectorElementSize = DL->getTypeStoreSize(DataTy)/VF; 1238 1239 if (ScalarAllocatedSize != VectorElementSize) 1240 return scalarizeInstruction(Instr); 1241 1242 // If the pointer is loop invariant or if it is non-consecutive, 1243 // scalarize the load. 1244 int ConsecutiveStride = Legal->isConsecutivePtr(Ptr); 1245 bool Reverse = ConsecutiveStride < 0; 1246 bool UniformLoad = LI && Legal->isUniform(Ptr); 1247 if (!ConsecutiveStride || UniformLoad) 1248 return scalarizeInstruction(Instr); 1249 1250 Constant *Zero = Builder.getInt32(0); 1251 VectorParts &Entry = WidenMap.get(Instr); 1252 1253 // Handle consecutive loads/stores. 1254 GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr); 1255 if (Gep && Legal->isInductionVariable(Gep->getPointerOperand())) { 1256 setDebugLocFromInst(Builder, Gep); 1257 Value *PtrOperand = Gep->getPointerOperand(); 1258 Value *FirstBasePtr = getVectorValue(PtrOperand)[0]; 1259 FirstBasePtr = Builder.CreateExtractElement(FirstBasePtr, Zero); 1260 1261 // Create the new GEP with the new induction variable. 1262 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone()); 1263 Gep2->setOperand(0, FirstBasePtr); 1264 Gep2->setName("gep.indvar.base"); 1265 Ptr = Builder.Insert(Gep2); 1266 } else if (Gep) { 1267 setDebugLocFromInst(Builder, Gep); 1268 assert(SE->isLoopInvariant(SE->getSCEV(Gep->getPointerOperand()), 1269 OrigLoop) && "Base ptr must be invariant"); 1270 1271 // The last index does not have to be the induction. It can be 1272 // consecutive and be a function of the index. For example A[I+1]; 1273 unsigned NumOperands = Gep->getNumOperands(); 1274 unsigned InductionOperand = getGEPInductionOperand(DL, Gep); 1275 // Create the new GEP with the new induction variable. 1276 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone()); 1277 1278 for (unsigned i = 0; i < NumOperands; ++i) { 1279 Value *GepOperand = Gep->getOperand(i); 1280 Instruction *GepOperandInst = dyn_cast<Instruction>(GepOperand); 1281 1282 // Update last index or loop invariant instruction anchored in loop. 1283 if (i == InductionOperand || 1284 (GepOperandInst && OrigLoop->contains(GepOperandInst))) { 1285 assert((i == InductionOperand || 1286 SE->isLoopInvariant(SE->getSCEV(GepOperandInst), OrigLoop)) && 1287 "Must be last index or loop invariant"); 1288 1289 VectorParts &GEPParts = getVectorValue(GepOperand); 1290 Value *Index = GEPParts[0]; 1291 Index = Builder.CreateExtractElement(Index, Zero); 1292 Gep2->setOperand(i, Index); 1293 Gep2->setName("gep.indvar.idx"); 1294 } 1295 } 1296 Ptr = Builder.Insert(Gep2); 1297 } else { 1298 // Use the induction element ptr. 1299 assert(isa<PHINode>(Ptr) && "Invalid induction ptr"); 1300 setDebugLocFromInst(Builder, Ptr); 1301 VectorParts &PtrVal = getVectorValue(Ptr); 1302 Ptr = Builder.CreateExtractElement(PtrVal[0], Zero); 1303 } 1304 1305 // Handle Stores: 1306 if (SI) { 1307 assert(!Legal->isUniform(SI->getPointerOperand()) && 1308 "We do not allow storing to uniform addresses"); 1309 setDebugLocFromInst(Builder, SI); 1310 // We don't want to update the value in the map as it might be used in 1311 // another expression. So don't use a reference type for "StoredVal". 1312 VectorParts StoredVal = getVectorValue(SI->getValueOperand()); 1313 1314 for (unsigned Part = 0; Part < UF; ++Part) { 1315 // Calculate the pointer for the specific unroll-part. 1316 Value *PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(Part * VF)); 1317 1318 if (Reverse) { 1319 // If we store to reverse consecutive memory locations then we need 1320 // to reverse the order of elements in the stored value. 1321 StoredVal[Part] = reverseVector(StoredVal[Part]); 1322 // If the address is consecutive but reversed, then the 1323 // wide store needs to start at the last vector element. 1324 PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(-Part * VF)); 1325 PartPtr = Builder.CreateGEP(PartPtr, Builder.getInt32(1 - VF)); 1326 } 1327 1328 Value *VecPtr = Builder.CreateBitCast(PartPtr, 1329 DataTy->getPointerTo(AddressSpace)); 1330 Builder.CreateStore(StoredVal[Part], VecPtr)->setAlignment(Alignment); 1331 } 1332 return; 1333 } 1334 1335 // Handle loads. 1336 assert(LI && "Must have a load instruction"); 1337 setDebugLocFromInst(Builder, LI); 1338 for (unsigned Part = 0; Part < UF; ++Part) { 1339 // Calculate the pointer for the specific unroll-part. 1340 Value *PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(Part * VF)); 1341 1342 if (Reverse) { 1343 // If the address is consecutive but reversed, then the 1344 // wide store needs to start at the last vector element. 1345 PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(-Part * VF)); 1346 PartPtr = Builder.CreateGEP(PartPtr, Builder.getInt32(1 - VF)); 1347 } 1348 1349 Value *VecPtr = Builder.CreateBitCast(PartPtr, 1350 DataTy->getPointerTo(AddressSpace)); 1351 Value *LI = Builder.CreateLoad(VecPtr, "wide.load"); 1352 cast<LoadInst>(LI)->setAlignment(Alignment); 1353 Entry[Part] = Reverse ? reverseVector(LI) : LI; 1354 } 1355 } 1356 1357 void InnerLoopVectorizer::scalarizeInstruction(Instruction *Instr) { 1358 assert(!Instr->getType()->isAggregateType() && "Can't handle vectors"); 1359 // Holds vector parameters or scalars, in case of uniform vals. 1360 SmallVector<VectorParts, 4> Params; 1361 1362 setDebugLocFromInst(Builder, Instr); 1363 1364 // Find all of the vectorized parameters. 1365 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) { 1366 Value *SrcOp = Instr->getOperand(op); 1367 1368 // If we are accessing the old induction variable, use the new one. 1369 if (SrcOp == OldInduction) { 1370 Params.push_back(getVectorValue(SrcOp)); 1371 continue; 1372 } 1373 1374 // Try using previously calculated values. 1375 Instruction *SrcInst = dyn_cast<Instruction>(SrcOp); 1376 1377 // If the src is an instruction that appeared earlier in the basic block 1378 // then it should already be vectorized. 1379 if (SrcInst && OrigLoop->contains(SrcInst)) { 1380 assert(WidenMap.has(SrcInst) && "Source operand is unavailable"); 1381 // The parameter is a vector value from earlier. 1382 Params.push_back(WidenMap.get(SrcInst)); 1383 } else { 1384 // The parameter is a scalar from outside the loop. Maybe even a constant. 1385 VectorParts Scalars; 1386 Scalars.append(UF, SrcOp); 1387 Params.push_back(Scalars); 1388 } 1389 } 1390 1391 assert(Params.size() == Instr->getNumOperands() && 1392 "Invalid number of operands"); 1393 1394 // Does this instruction return a value ? 1395 bool IsVoidRetTy = Instr->getType()->isVoidTy(); 1396 1397 Value *UndefVec = IsVoidRetTy ? 0 : 1398 UndefValue::get(VectorType::get(Instr->getType(), VF)); 1399 // Create a new entry in the WidenMap and initialize it to Undef or Null. 1400 VectorParts &VecResults = WidenMap.splat(Instr, UndefVec); 1401 1402 // For each vector unroll 'part': 1403 for (unsigned Part = 0; Part < UF; ++Part) { 1404 // For each scalar that we create: 1405 for (unsigned Width = 0; Width < VF; ++Width) { 1406 Instruction *Cloned = Instr->clone(); 1407 if (!IsVoidRetTy) 1408 Cloned->setName(Instr->getName() + ".cloned"); 1409 // Replace the operands of the cloned instructions with extracted scalars. 1410 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) { 1411 Value *Op = Params[op][Part]; 1412 // Param is a vector. Need to extract the right lane. 1413 if (Op->getType()->isVectorTy()) 1414 Op = Builder.CreateExtractElement(Op, Builder.getInt32(Width)); 1415 Cloned->setOperand(op, Op); 1416 } 1417 1418 // Place the cloned scalar in the new loop. 1419 Builder.Insert(Cloned); 1420 1421 // If the original scalar returns a value we need to place it in a vector 1422 // so that future users will be able to use it. 1423 if (!IsVoidRetTy) 1424 VecResults[Part] = Builder.CreateInsertElement(VecResults[Part], Cloned, 1425 Builder.getInt32(Width)); 1426 } 1427 } 1428 } 1429 1430 Instruction * 1431 InnerLoopVectorizer::addRuntimeCheck(LoopVectorizationLegality *Legal, 1432 Instruction *Loc) { 1433 LoopVectorizationLegality::RuntimePointerCheck *PtrRtCheck = 1434 Legal->getRuntimePointerCheck(); 1435 1436 if (!PtrRtCheck->Need) 1437 return NULL; 1438 1439 unsigned NumPointers = PtrRtCheck->Pointers.size(); 1440 SmallVector<TrackingVH<Value> , 2> Starts; 1441 SmallVector<TrackingVH<Value> , 2> Ends; 1442 1443 LLVMContext &Ctx = Loc->getContext(); 1444 SCEVExpander Exp(*SE, "induction"); 1445 1446 for (unsigned i = 0; i < NumPointers; ++i) { 1447 Value *Ptr = PtrRtCheck->Pointers[i]; 1448 const SCEV *Sc = SE->getSCEV(Ptr); 1449 1450 if (SE->isLoopInvariant(Sc, OrigLoop)) { 1451 DEBUG(dbgs() << "LV: Adding RT check for a loop invariant ptr:" << 1452 *Ptr <<"\n"); 1453 Starts.push_back(Ptr); 1454 Ends.push_back(Ptr); 1455 } else { 1456 DEBUG(dbgs() << "LV: Adding RT check for range:" << *Ptr << '\n'); 1457 unsigned AS = Ptr->getType()->getPointerAddressSpace(); 1458 1459 // Use this type for pointer arithmetic. 1460 Type *PtrArithTy = Type::getInt8PtrTy(Ctx, AS); 1461 1462 Value *Start = Exp.expandCodeFor(PtrRtCheck->Starts[i], PtrArithTy, Loc); 1463 Value *End = Exp.expandCodeFor(PtrRtCheck->Ends[i], PtrArithTy, Loc); 1464 Starts.push_back(Start); 1465 Ends.push_back(End); 1466 } 1467 } 1468 1469 IRBuilder<> ChkBuilder(Loc); 1470 // Our instructions might fold to a constant. 1471 Value *MemoryRuntimeCheck = 0; 1472 for (unsigned i = 0; i < NumPointers; ++i) { 1473 for (unsigned j = i+1; j < NumPointers; ++j) { 1474 // No need to check if two readonly pointers intersect. 1475 if (!PtrRtCheck->IsWritePtr[i] && !PtrRtCheck->IsWritePtr[j]) 1476 continue; 1477 1478 // Only need to check pointers between two different dependency sets. 1479 if (PtrRtCheck->DependencySetId[i] == PtrRtCheck->DependencySetId[j]) 1480 continue; 1481 1482 unsigned AS0 = Starts[i]->getType()->getPointerAddressSpace(); 1483 unsigned AS1 = Starts[j]->getType()->getPointerAddressSpace(); 1484 1485 assert((AS0 == Ends[j]->getType()->getPointerAddressSpace()) && 1486 (AS1 == Ends[i]->getType()->getPointerAddressSpace()) && 1487 "Trying to bounds check pointers with different address spaces"); 1488 1489 Type *PtrArithTy0 = Type::getInt8PtrTy(Ctx, AS0); 1490 Type *PtrArithTy1 = Type::getInt8PtrTy(Ctx, AS1); 1491 1492 Value *Start0 = ChkBuilder.CreateBitCast(Starts[i], PtrArithTy0, "bc"); 1493 Value *Start1 = ChkBuilder.CreateBitCast(Starts[j], PtrArithTy1, "bc"); 1494 Value *End0 = ChkBuilder.CreateBitCast(Ends[i], PtrArithTy1, "bc"); 1495 Value *End1 = ChkBuilder.CreateBitCast(Ends[j], PtrArithTy0, "bc"); 1496 1497 Value *Cmp0 = ChkBuilder.CreateICmpULE(Start0, End1, "bound0"); 1498 Value *Cmp1 = ChkBuilder.CreateICmpULE(Start1, End0, "bound1"); 1499 Value *IsConflict = ChkBuilder.CreateAnd(Cmp0, Cmp1, "found.conflict"); 1500 if (MemoryRuntimeCheck) 1501 IsConflict = ChkBuilder.CreateOr(MemoryRuntimeCheck, IsConflict, 1502 "conflict.rdx"); 1503 MemoryRuntimeCheck = IsConflict; 1504 } 1505 } 1506 1507 // We have to do this trickery because the IRBuilder might fold the check to a 1508 // constant expression in which case there is no Instruction anchored in a 1509 // the block. 1510 Instruction *Check = BinaryOperator::CreateAnd(MemoryRuntimeCheck, 1511 ConstantInt::getTrue(Ctx)); 1512 ChkBuilder.Insert(Check, "memcheck.conflict"); 1513 return Check; 1514 } 1515 1516 void 1517 InnerLoopVectorizer::createEmptyLoop(LoopVectorizationLegality *Legal) { 1518 /* 1519 In this function we generate a new loop. The new loop will contain 1520 the vectorized instructions while the old loop will continue to run the 1521 scalar remainder. 1522 1523 [ ] <-- vector loop bypass (may consist of multiple blocks). 1524 / | 1525 / v 1526 | [ ] <-- vector pre header. 1527 | | 1528 | v 1529 | [ ] \ 1530 | [ ]_| <-- vector loop. 1531 | | 1532 \ v 1533 >[ ] <--- middle-block. 1534 / | 1535 / v 1536 | [ ] <--- new preheader. 1537 | | 1538 | v 1539 | [ ] \ 1540 | [ ]_| <-- old scalar loop to handle remainder. 1541 \ | 1542 \ v 1543 >[ ] <-- exit block. 1544 ... 1545 */ 1546 1547 BasicBlock *OldBasicBlock = OrigLoop->getHeader(); 1548 BasicBlock *BypassBlock = OrigLoop->getLoopPreheader(); 1549 BasicBlock *ExitBlock = OrigLoop->getExitBlock(); 1550 assert(ExitBlock && "Must have an exit block"); 1551 1552 // Some loops have a single integer induction variable, while other loops 1553 // don't. One example is c++ iterators that often have multiple pointer 1554 // induction variables. In the code below we also support a case where we 1555 // don't have a single induction variable. 1556 OldInduction = Legal->getInduction(); 1557 Type *IdxTy = Legal->getWidestInductionType(); 1558 1559 // Find the loop boundaries. 1560 const SCEV *ExitCount = SE->getBackedgeTakenCount(OrigLoop); 1561 assert(ExitCount != SE->getCouldNotCompute() && "Invalid loop count"); 1562 1563 // The exit count might have the type of i64 while the phi is i32. This can 1564 // happen if we have an induction variable that is sign extended before the 1565 // compare. The only way that we get a backedge taken count is that the 1566 // induction variable was signed and as such will not overflow. In such a case 1567 // truncation is legal. 1568 if (ExitCount->getType()->getPrimitiveSizeInBits() > 1569 IdxTy->getPrimitiveSizeInBits()) 1570 ExitCount = SE->getTruncateOrNoop(ExitCount, IdxTy); 1571 1572 ExitCount = SE->getNoopOrZeroExtend(ExitCount, IdxTy); 1573 // Get the total trip count from the count by adding 1. 1574 ExitCount = SE->getAddExpr(ExitCount, 1575 SE->getConstant(ExitCount->getType(), 1)); 1576 1577 // Expand the trip count and place the new instructions in the preheader. 1578 // Notice that the pre-header does not change, only the loop body. 1579 SCEVExpander Exp(*SE, "induction"); 1580 1581 // Count holds the overall loop count (N). 1582 Value *Count = Exp.expandCodeFor(ExitCount, ExitCount->getType(), 1583 BypassBlock->getTerminator()); 1584 1585 // The loop index does not have to start at Zero. Find the original start 1586 // value from the induction PHI node. If we don't have an induction variable 1587 // then we know that it starts at zero. 1588 Builder.SetInsertPoint(BypassBlock->getTerminator()); 1589 Value *StartIdx = ExtendedIdx = OldInduction ? 1590 Builder.CreateZExt(OldInduction->getIncomingValueForBlock(BypassBlock), 1591 IdxTy): 1592 ConstantInt::get(IdxTy, 0); 1593 1594 assert(BypassBlock && "Invalid loop structure"); 1595 LoopBypassBlocks.push_back(BypassBlock); 1596 1597 // Split the single block loop into the two loop structure described above. 1598 BasicBlock *VectorPH = 1599 BypassBlock->splitBasicBlock(BypassBlock->getTerminator(), "vector.ph"); 1600 BasicBlock *VecBody = 1601 VectorPH->splitBasicBlock(VectorPH->getTerminator(), "vector.body"); 1602 BasicBlock *MiddleBlock = 1603 VecBody->splitBasicBlock(VecBody->getTerminator(), "middle.block"); 1604 BasicBlock *ScalarPH = 1605 MiddleBlock->splitBasicBlock(MiddleBlock->getTerminator(), "scalar.ph"); 1606 1607 // Create and register the new vector loop. 1608 Loop* Lp = new Loop(); 1609 Loop *ParentLoop = OrigLoop->getParentLoop(); 1610 1611 // Insert the new loop into the loop nest and register the new basic blocks 1612 // before calling any utilities such as SCEV that require valid LoopInfo. 1613 if (ParentLoop) { 1614 ParentLoop->addChildLoop(Lp); 1615 ParentLoop->addBasicBlockToLoop(ScalarPH, LI->getBase()); 1616 ParentLoop->addBasicBlockToLoop(VectorPH, LI->getBase()); 1617 ParentLoop->addBasicBlockToLoop(MiddleBlock, LI->getBase()); 1618 } else { 1619 LI->addTopLevelLoop(Lp); 1620 } 1621 Lp->addBasicBlockToLoop(VecBody, LI->getBase()); 1622 1623 // Use this IR builder to create the loop instructions (Phi, Br, Cmp) 1624 // inside the loop. 1625 Builder.SetInsertPoint(VecBody->getFirstNonPHI()); 1626 1627 // Generate the induction variable. 1628 setDebugLocFromInst(Builder, getDebugLocFromInstOrOperands(OldInduction)); 1629 Induction = Builder.CreatePHI(IdxTy, 2, "index"); 1630 // The loop step is equal to the vectorization factor (num of SIMD elements) 1631 // times the unroll factor (num of SIMD instructions). 1632 Constant *Step = ConstantInt::get(IdxTy, VF * UF); 1633 1634 // This is the IR builder that we use to add all of the logic for bypassing 1635 // the new vector loop. 1636 IRBuilder<> BypassBuilder(BypassBlock->getTerminator()); 1637 setDebugLocFromInst(BypassBuilder, 1638 getDebugLocFromInstOrOperands(OldInduction)); 1639 1640 // We may need to extend the index in case there is a type mismatch. 1641 // We know that the count starts at zero and does not overflow. 1642 if (Count->getType() != IdxTy) { 1643 // The exit count can be of pointer type. Convert it to the correct 1644 // integer type. 1645 if (ExitCount->getType()->isPointerTy()) 1646 Count = BypassBuilder.CreatePointerCast(Count, IdxTy, "ptrcnt.to.int"); 1647 else 1648 Count = BypassBuilder.CreateZExtOrTrunc(Count, IdxTy, "cnt.cast"); 1649 } 1650 1651 // Add the start index to the loop count to get the new end index. 1652 Value *IdxEnd = BypassBuilder.CreateAdd(Count, StartIdx, "end.idx"); 1653 1654 // Now we need to generate the expression for N - (N % VF), which is 1655 // the part that the vectorized body will execute. 1656 Value *R = BypassBuilder.CreateURem(Count, Step, "n.mod.vf"); 1657 Value *CountRoundDown = BypassBuilder.CreateSub(Count, R, "n.vec"); 1658 Value *IdxEndRoundDown = BypassBuilder.CreateAdd(CountRoundDown, StartIdx, 1659 "end.idx.rnd.down"); 1660 1661 // Now, compare the new count to zero. If it is zero skip the vector loop and 1662 // jump to the scalar loop. 1663 Value *Cmp = BypassBuilder.CreateICmpEQ(IdxEndRoundDown, StartIdx, 1664 "cmp.zero"); 1665 1666 BasicBlock *LastBypassBlock = BypassBlock; 1667 1668 // Generate the code that checks in runtime if arrays overlap. We put the 1669 // checks into a separate block to make the more common case of few elements 1670 // faster. 1671 Instruction *MemRuntimeCheck = addRuntimeCheck(Legal, 1672 BypassBlock->getTerminator()); 1673 if (MemRuntimeCheck) { 1674 // Create a new block containing the memory check. 1675 BasicBlock *CheckBlock = BypassBlock->splitBasicBlock(MemRuntimeCheck, 1676 "vector.memcheck"); 1677 if (ParentLoop) 1678 ParentLoop->addBasicBlockToLoop(CheckBlock, LI->getBase()); 1679 LoopBypassBlocks.push_back(CheckBlock); 1680 1681 // Replace the branch into the memory check block with a conditional branch 1682 // for the "few elements case". 1683 Instruction *OldTerm = BypassBlock->getTerminator(); 1684 BranchInst::Create(MiddleBlock, CheckBlock, Cmp, OldTerm); 1685 OldTerm->eraseFromParent(); 1686 1687 Cmp = MemRuntimeCheck; 1688 LastBypassBlock = CheckBlock; 1689 } 1690 1691 LastBypassBlock->getTerminator()->eraseFromParent(); 1692 BranchInst::Create(MiddleBlock, VectorPH, Cmp, 1693 LastBypassBlock); 1694 1695 // We are going to resume the execution of the scalar loop. 1696 // Go over all of the induction variables that we found and fix the 1697 // PHIs that are left in the scalar version of the loop. 1698 // The starting values of PHI nodes depend on the counter of the last 1699 // iteration in the vectorized loop. 1700 // If we come from a bypass edge then we need to start from the original 1701 // start value. 1702 1703 // This variable saves the new starting index for the scalar loop. 1704 PHINode *ResumeIndex = 0; 1705 LoopVectorizationLegality::InductionList::iterator I, E; 1706 LoopVectorizationLegality::InductionList *List = Legal->getInductionVars(); 1707 // Set builder to point to last bypass block. 1708 BypassBuilder.SetInsertPoint(LoopBypassBlocks.back()->getTerminator()); 1709 for (I = List->begin(), E = List->end(); I != E; ++I) { 1710 PHINode *OrigPhi = I->first; 1711 LoopVectorizationLegality::InductionInfo II = I->second; 1712 1713 Type *ResumeValTy = (OrigPhi == OldInduction) ? IdxTy : OrigPhi->getType(); 1714 PHINode *ResumeVal = PHINode::Create(ResumeValTy, 2, "resume.val", 1715 MiddleBlock->getTerminator()); 1716 // We might have extended the type of the induction variable but we need a 1717 // truncated version for the scalar loop. 1718 PHINode *TruncResumeVal = (OrigPhi == OldInduction) ? 1719 PHINode::Create(OrigPhi->getType(), 2, "trunc.resume.val", 1720 MiddleBlock->getTerminator()) : 0; 1721 1722 Value *EndValue = 0; 1723 switch (II.IK) { 1724 case LoopVectorizationLegality::IK_NoInduction: 1725 llvm_unreachable("Unknown induction"); 1726 case LoopVectorizationLegality::IK_IntInduction: { 1727 // Handle the integer induction counter. 1728 assert(OrigPhi->getType()->isIntegerTy() && "Invalid type"); 1729 1730 // We have the canonical induction variable. 1731 if (OrigPhi == OldInduction) { 1732 // Create a truncated version of the resume value for the scalar loop, 1733 // we might have promoted the type to a larger width. 1734 EndValue = 1735 BypassBuilder.CreateTrunc(IdxEndRoundDown, OrigPhi->getType()); 1736 // The new PHI merges the original incoming value, in case of a bypass, 1737 // or the value at the end of the vectorized loop. 1738 for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I) 1739 TruncResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[I]); 1740 TruncResumeVal->addIncoming(EndValue, VecBody); 1741 1742 // We know what the end value is. 1743 EndValue = IdxEndRoundDown; 1744 // We also know which PHI node holds it. 1745 ResumeIndex = ResumeVal; 1746 break; 1747 } 1748 1749 // Not the canonical induction variable - add the vector loop count to the 1750 // start value. 1751 Value *CRD = BypassBuilder.CreateSExtOrTrunc(CountRoundDown, 1752 II.StartValue->getType(), 1753 "cast.crd"); 1754 EndValue = BypassBuilder.CreateAdd(CRD, II.StartValue , "ind.end"); 1755 break; 1756 } 1757 case LoopVectorizationLegality::IK_ReverseIntInduction: { 1758 // Convert the CountRoundDown variable to the PHI size. 1759 Value *CRD = BypassBuilder.CreateSExtOrTrunc(CountRoundDown, 1760 II.StartValue->getType(), 1761 "cast.crd"); 1762 // Handle reverse integer induction counter. 1763 EndValue = BypassBuilder.CreateSub(II.StartValue, CRD, "rev.ind.end"); 1764 break; 1765 } 1766 case LoopVectorizationLegality::IK_PtrInduction: { 1767 // For pointer induction variables, calculate the offset using 1768 // the end index. 1769 EndValue = BypassBuilder.CreateGEP(II.StartValue, CountRoundDown, 1770 "ptr.ind.end"); 1771 break; 1772 } 1773 case LoopVectorizationLegality::IK_ReversePtrInduction: { 1774 // The value at the end of the loop for the reverse pointer is calculated 1775 // by creating a GEP with a negative index starting from the start value. 1776 Value *Zero = ConstantInt::get(CountRoundDown->getType(), 0); 1777 Value *NegIdx = BypassBuilder.CreateSub(Zero, CountRoundDown, 1778 "rev.ind.end"); 1779 EndValue = BypassBuilder.CreateGEP(II.StartValue, NegIdx, 1780 "rev.ptr.ind.end"); 1781 break; 1782 } 1783 }// end of case 1784 1785 // The new PHI merges the original incoming value, in case of a bypass, 1786 // or the value at the end of the vectorized loop. 1787 for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I) { 1788 if (OrigPhi == OldInduction) 1789 ResumeVal->addIncoming(StartIdx, LoopBypassBlocks[I]); 1790 else 1791 ResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[I]); 1792 } 1793 ResumeVal->addIncoming(EndValue, VecBody); 1794 1795 // Fix the scalar body counter (PHI node). 1796 unsigned BlockIdx = OrigPhi->getBasicBlockIndex(ScalarPH); 1797 // The old inductions phi node in the scalar body needs the truncated value. 1798 if (OrigPhi == OldInduction) 1799 OrigPhi->setIncomingValue(BlockIdx, TruncResumeVal); 1800 else 1801 OrigPhi->setIncomingValue(BlockIdx, ResumeVal); 1802 } 1803 1804 // If we are generating a new induction variable then we also need to 1805 // generate the code that calculates the exit value. This value is not 1806 // simply the end of the counter because we may skip the vectorized body 1807 // in case of a runtime check. 1808 if (!OldInduction){ 1809 assert(!ResumeIndex && "Unexpected resume value found"); 1810 ResumeIndex = PHINode::Create(IdxTy, 2, "new.indc.resume.val", 1811 MiddleBlock->getTerminator()); 1812 for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I) 1813 ResumeIndex->addIncoming(StartIdx, LoopBypassBlocks[I]); 1814 ResumeIndex->addIncoming(IdxEndRoundDown, VecBody); 1815 } 1816 1817 // Make sure that we found the index where scalar loop needs to continue. 1818 assert(ResumeIndex && ResumeIndex->getType()->isIntegerTy() && 1819 "Invalid resume Index"); 1820 1821 // Add a check in the middle block to see if we have completed 1822 // all of the iterations in the first vector loop. 1823 // If (N - N%VF) == N, then we *don't* need to run the remainder. 1824 Value *CmpN = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, IdxEnd, 1825 ResumeIndex, "cmp.n", 1826 MiddleBlock->getTerminator()); 1827 1828 BranchInst::Create(ExitBlock, ScalarPH, CmpN, MiddleBlock->getTerminator()); 1829 // Remove the old terminator. 1830 MiddleBlock->getTerminator()->eraseFromParent(); 1831 1832 // Create i+1 and fill the PHINode. 1833 Value *NextIdx = Builder.CreateAdd(Induction, Step, "index.next"); 1834 Induction->addIncoming(StartIdx, VectorPH); 1835 Induction->addIncoming(NextIdx, VecBody); 1836 // Create the compare. 1837 Value *ICmp = Builder.CreateICmpEQ(NextIdx, IdxEndRoundDown); 1838 Builder.CreateCondBr(ICmp, MiddleBlock, VecBody); 1839 1840 // Now we have two terminators. Remove the old one from the block. 1841 VecBody->getTerminator()->eraseFromParent(); 1842 1843 // Get ready to start creating new instructions into the vectorized body. 1844 Builder.SetInsertPoint(VecBody->getFirstInsertionPt()); 1845 1846 // Save the state. 1847 LoopVectorPreHeader = VectorPH; 1848 LoopScalarPreHeader = ScalarPH; 1849 LoopMiddleBlock = MiddleBlock; 1850 LoopExitBlock = ExitBlock; 1851 LoopVectorBody = VecBody; 1852 LoopScalarBody = OldBasicBlock; 1853 1854 LoopVectorizeHints Hints(Lp, true); 1855 Hints.setAlreadyVectorized(Lp); 1856 } 1857 1858 /// This function returns the identity element (or neutral element) for 1859 /// the operation K. 1860 Constant* 1861 LoopVectorizationLegality::getReductionIdentity(ReductionKind K, Type *Tp) { 1862 switch (K) { 1863 case RK_IntegerXor: 1864 case RK_IntegerAdd: 1865 case RK_IntegerOr: 1866 // Adding, Xoring, Oring zero to a number does not change it. 1867 return ConstantInt::get(Tp, 0); 1868 case RK_IntegerMult: 1869 // Multiplying a number by 1 does not change it. 1870 return ConstantInt::get(Tp, 1); 1871 case RK_IntegerAnd: 1872 // AND-ing a number with an all-1 value does not change it. 1873 return ConstantInt::get(Tp, -1, true); 1874 case RK_FloatMult: 1875 // Multiplying a number by 1 does not change it. 1876 return ConstantFP::get(Tp, 1.0L); 1877 case RK_FloatAdd: 1878 // Adding zero to a number does not change it. 1879 return ConstantFP::get(Tp, 0.0L); 1880 default: 1881 llvm_unreachable("Unknown reduction kind"); 1882 } 1883 } 1884 1885 static Intrinsic::ID checkUnaryFloatSignature(const CallInst &I, 1886 Intrinsic::ID ValidIntrinsicID) { 1887 if (I.getNumArgOperands() != 1 || 1888 !I.getArgOperand(0)->getType()->isFloatingPointTy() || 1889 I.getType() != I.getArgOperand(0)->getType() || 1890 !I.onlyReadsMemory()) 1891 return Intrinsic::not_intrinsic; 1892 1893 return ValidIntrinsicID; 1894 } 1895 1896 static Intrinsic::ID checkBinaryFloatSignature(const CallInst &I, 1897 Intrinsic::ID ValidIntrinsicID) { 1898 if (I.getNumArgOperands() != 2 || 1899 !I.getArgOperand(0)->getType()->isFloatingPointTy() || 1900 !I.getArgOperand(1)->getType()->isFloatingPointTy() || 1901 I.getType() != I.getArgOperand(0)->getType() || 1902 I.getType() != I.getArgOperand(1)->getType() || 1903 !I.onlyReadsMemory()) 1904 return Intrinsic::not_intrinsic; 1905 1906 return ValidIntrinsicID; 1907 } 1908 1909 1910 static Intrinsic::ID 1911 getIntrinsicIDForCall(CallInst *CI, const TargetLibraryInfo *TLI) { 1912 // If we have an intrinsic call, check if it is trivially vectorizable. 1913 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) { 1914 switch (II->getIntrinsicID()) { 1915 case Intrinsic::sqrt: 1916 case Intrinsic::sin: 1917 case Intrinsic::cos: 1918 case Intrinsic::exp: 1919 case Intrinsic::exp2: 1920 case Intrinsic::log: 1921 case Intrinsic::log10: 1922 case Intrinsic::log2: 1923 case Intrinsic::fabs: 1924 case Intrinsic::copysign: 1925 case Intrinsic::floor: 1926 case Intrinsic::ceil: 1927 case Intrinsic::trunc: 1928 case Intrinsic::rint: 1929 case Intrinsic::nearbyint: 1930 case Intrinsic::round: 1931 case Intrinsic::pow: 1932 case Intrinsic::fma: 1933 case Intrinsic::fmuladd: 1934 case Intrinsic::lifetime_start: 1935 case Intrinsic::lifetime_end: 1936 return II->getIntrinsicID(); 1937 default: 1938 return Intrinsic::not_intrinsic; 1939 } 1940 } 1941 1942 if (!TLI) 1943 return Intrinsic::not_intrinsic; 1944 1945 LibFunc::Func Func; 1946 Function *F = CI->getCalledFunction(); 1947 // We're going to make assumptions on the semantics of the functions, check 1948 // that the target knows that it's available in this environment and it does 1949 // not have local linkage. 1950 if (!F || F->hasLocalLinkage() || !TLI->getLibFunc(F->getName(), Func)) 1951 return Intrinsic::not_intrinsic; 1952 1953 // Otherwise check if we have a call to a function that can be turned into a 1954 // vector intrinsic. 1955 switch (Func) { 1956 default: 1957 break; 1958 case LibFunc::sin: 1959 case LibFunc::sinf: 1960 case LibFunc::sinl: 1961 return checkUnaryFloatSignature(*CI, Intrinsic::sin); 1962 case LibFunc::cos: 1963 case LibFunc::cosf: 1964 case LibFunc::cosl: 1965 return checkUnaryFloatSignature(*CI, Intrinsic::cos); 1966 case LibFunc::exp: 1967 case LibFunc::expf: 1968 case LibFunc::expl: 1969 return checkUnaryFloatSignature(*CI, Intrinsic::exp); 1970 case LibFunc::exp2: 1971 case LibFunc::exp2f: 1972 case LibFunc::exp2l: 1973 return checkUnaryFloatSignature(*CI, Intrinsic::exp2); 1974 case LibFunc::log: 1975 case LibFunc::logf: 1976 case LibFunc::logl: 1977 return checkUnaryFloatSignature(*CI, Intrinsic::log); 1978 case LibFunc::log10: 1979 case LibFunc::log10f: 1980 case LibFunc::log10l: 1981 return checkUnaryFloatSignature(*CI, Intrinsic::log10); 1982 case LibFunc::log2: 1983 case LibFunc::log2f: 1984 case LibFunc::log2l: 1985 return checkUnaryFloatSignature(*CI, Intrinsic::log2); 1986 case LibFunc::fabs: 1987 case LibFunc::fabsf: 1988 case LibFunc::fabsl: 1989 return checkUnaryFloatSignature(*CI, Intrinsic::fabs); 1990 case LibFunc::copysign: 1991 case LibFunc::copysignf: 1992 case LibFunc::copysignl: 1993 return checkBinaryFloatSignature(*CI, Intrinsic::copysign); 1994 case LibFunc::floor: 1995 case LibFunc::floorf: 1996 case LibFunc::floorl: 1997 return checkUnaryFloatSignature(*CI, Intrinsic::floor); 1998 case LibFunc::ceil: 1999 case LibFunc::ceilf: 2000 case LibFunc::ceill: 2001 return checkUnaryFloatSignature(*CI, Intrinsic::ceil); 2002 case LibFunc::trunc: 2003 case LibFunc::truncf: 2004 case LibFunc::truncl: 2005 return checkUnaryFloatSignature(*CI, Intrinsic::trunc); 2006 case LibFunc::rint: 2007 case LibFunc::rintf: 2008 case LibFunc::rintl: 2009 return checkUnaryFloatSignature(*CI, Intrinsic::rint); 2010 case LibFunc::nearbyint: 2011 case LibFunc::nearbyintf: 2012 case LibFunc::nearbyintl: 2013 return checkUnaryFloatSignature(*CI, Intrinsic::nearbyint); 2014 case LibFunc::round: 2015 case LibFunc::roundf: 2016 case LibFunc::roundl: 2017 return checkUnaryFloatSignature(*CI, Intrinsic::round); 2018 case LibFunc::pow: 2019 case LibFunc::powf: 2020 case LibFunc::powl: 2021 return checkBinaryFloatSignature(*CI, Intrinsic::pow); 2022 } 2023 2024 return Intrinsic::not_intrinsic; 2025 } 2026 2027 /// This function translates the reduction kind to an LLVM binary operator. 2028 static unsigned 2029 getReductionBinOp(LoopVectorizationLegality::ReductionKind Kind) { 2030 switch (Kind) { 2031 case LoopVectorizationLegality::RK_IntegerAdd: 2032 return Instruction::Add; 2033 case LoopVectorizationLegality::RK_IntegerMult: 2034 return Instruction::Mul; 2035 case LoopVectorizationLegality::RK_IntegerOr: 2036 return Instruction::Or; 2037 case LoopVectorizationLegality::RK_IntegerAnd: 2038 return Instruction::And; 2039 case LoopVectorizationLegality::RK_IntegerXor: 2040 return Instruction::Xor; 2041 case LoopVectorizationLegality::RK_FloatMult: 2042 return Instruction::FMul; 2043 case LoopVectorizationLegality::RK_FloatAdd: 2044 return Instruction::FAdd; 2045 case LoopVectorizationLegality::RK_IntegerMinMax: 2046 return Instruction::ICmp; 2047 case LoopVectorizationLegality::RK_FloatMinMax: 2048 return Instruction::FCmp; 2049 default: 2050 llvm_unreachable("Unknown reduction operation"); 2051 } 2052 } 2053 2054 Value *createMinMaxOp(IRBuilder<> &Builder, 2055 LoopVectorizationLegality::MinMaxReductionKind RK, 2056 Value *Left, 2057 Value *Right) { 2058 CmpInst::Predicate P = CmpInst::ICMP_NE; 2059 switch (RK) { 2060 default: 2061 llvm_unreachable("Unknown min/max reduction kind"); 2062 case LoopVectorizationLegality::MRK_UIntMin: 2063 P = CmpInst::ICMP_ULT; 2064 break; 2065 case LoopVectorizationLegality::MRK_UIntMax: 2066 P = CmpInst::ICMP_UGT; 2067 break; 2068 case LoopVectorizationLegality::MRK_SIntMin: 2069 P = CmpInst::ICMP_SLT; 2070 break; 2071 case LoopVectorizationLegality::MRK_SIntMax: 2072 P = CmpInst::ICMP_SGT; 2073 break; 2074 case LoopVectorizationLegality::MRK_FloatMin: 2075 P = CmpInst::FCMP_OLT; 2076 break; 2077 case LoopVectorizationLegality::MRK_FloatMax: 2078 P = CmpInst::FCMP_OGT; 2079 break; 2080 } 2081 2082 Value *Cmp; 2083 if (RK == LoopVectorizationLegality::MRK_FloatMin || 2084 RK == LoopVectorizationLegality::MRK_FloatMax) 2085 Cmp = Builder.CreateFCmp(P, Left, Right, "rdx.minmax.cmp"); 2086 else 2087 Cmp = Builder.CreateICmp(P, Left, Right, "rdx.minmax.cmp"); 2088 2089 Value *Select = Builder.CreateSelect(Cmp, Left, Right, "rdx.minmax.select"); 2090 return Select; 2091 } 2092 2093 namespace { 2094 struct CSEDenseMapInfo { 2095 static bool canHandle(Instruction *I) { 2096 return isa<InsertElementInst>(I) || isa<ExtractElementInst>(I) || 2097 isa<ShuffleVectorInst>(I) || isa<GetElementPtrInst>(I); 2098 } 2099 static inline Instruction *getEmptyKey() { 2100 return DenseMapInfo<Instruction *>::getEmptyKey(); 2101 } 2102 static inline Instruction *getTombstoneKey() { 2103 return DenseMapInfo<Instruction *>::getTombstoneKey(); 2104 } 2105 static unsigned getHashValue(Instruction *I) { 2106 assert(canHandle(I) && "Unknown instruction!"); 2107 return hash_combine(I->getOpcode(), hash_combine_range(I->value_op_begin(), 2108 I->value_op_end())); 2109 } 2110 static bool isEqual(Instruction *LHS, Instruction *RHS) { 2111 if (LHS == getEmptyKey() || RHS == getEmptyKey() || 2112 LHS == getTombstoneKey() || RHS == getTombstoneKey()) 2113 return LHS == RHS; 2114 return LHS->isIdenticalTo(RHS); 2115 } 2116 }; 2117 } 2118 2119 ///\brief Perform cse of induction variable instructions. 2120 static void cse(BasicBlock *BB) { 2121 // Perform simple cse. 2122 SmallDenseMap<Instruction *, Instruction *, 4, CSEDenseMapInfo> CSEMap; 2123 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) { 2124 Instruction *In = I++; 2125 2126 if (!CSEDenseMapInfo::canHandle(In)) 2127 continue; 2128 2129 // Check if we can replace this instruction with any of the 2130 // visited instructions. 2131 if (Instruction *V = CSEMap.lookup(In)) { 2132 In->replaceAllUsesWith(V); 2133 In->eraseFromParent(); 2134 continue; 2135 } 2136 2137 CSEMap[In] = In; 2138 } 2139 } 2140 2141 void 2142 InnerLoopVectorizer::vectorizeLoop(LoopVectorizationLegality *Legal) { 2143 //===------------------------------------------------===// 2144 // 2145 // Notice: any optimization or new instruction that go 2146 // into the code below should be also be implemented in 2147 // the cost-model. 2148 // 2149 //===------------------------------------------------===// 2150 Constant *Zero = Builder.getInt32(0); 2151 2152 // In order to support reduction variables we need to be able to vectorize 2153 // Phi nodes. Phi nodes have cycles, so we need to vectorize them in two 2154 // stages. First, we create a new vector PHI node with no incoming edges. 2155 // We use this value when we vectorize all of the instructions that use the 2156 // PHI. Next, after all of the instructions in the block are complete we 2157 // add the new incoming edges to the PHI. At this point all of the 2158 // instructions in the basic block are vectorized, so we can use them to 2159 // construct the PHI. 2160 PhiVector RdxPHIsToFix; 2161 2162 // Scan the loop in a topological order to ensure that defs are vectorized 2163 // before users. 2164 LoopBlocksDFS DFS(OrigLoop); 2165 DFS.perform(LI); 2166 2167 // Vectorize all of the blocks in the original loop. 2168 for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(), 2169 be = DFS.endRPO(); bb != be; ++bb) 2170 vectorizeBlockInLoop(Legal, *bb, &RdxPHIsToFix); 2171 2172 // At this point every instruction in the original loop is widened to 2173 // a vector form. We are almost done. Now, we need to fix the PHI nodes 2174 // that we vectorized. The PHI nodes are currently empty because we did 2175 // not want to introduce cycles. Notice that the remaining PHI nodes 2176 // that we need to fix are reduction variables. 2177 2178 // Create the 'reduced' values for each of the induction vars. 2179 // The reduced values are the vector values that we scalarize and combine 2180 // after the loop is finished. 2181 for (PhiVector::iterator it = RdxPHIsToFix.begin(), e = RdxPHIsToFix.end(); 2182 it != e; ++it) { 2183 PHINode *RdxPhi = *it; 2184 assert(RdxPhi && "Unable to recover vectorized PHI"); 2185 2186 // Find the reduction variable descriptor. 2187 assert(Legal->getReductionVars()->count(RdxPhi) && 2188 "Unable to find the reduction variable"); 2189 LoopVectorizationLegality::ReductionDescriptor RdxDesc = 2190 (*Legal->getReductionVars())[RdxPhi]; 2191 2192 setDebugLocFromInst(Builder, RdxDesc.StartValue); 2193 2194 // We need to generate a reduction vector from the incoming scalar. 2195 // To do so, we need to generate the 'identity' vector and overide 2196 // one of the elements with the incoming scalar reduction. We need 2197 // to do it in the vector-loop preheader. 2198 Builder.SetInsertPoint(LoopBypassBlocks.front()->getTerminator()); 2199 2200 // This is the vector-clone of the value that leaves the loop. 2201 VectorParts &VectorExit = getVectorValue(RdxDesc.LoopExitInstr); 2202 Type *VecTy = VectorExit[0]->getType(); 2203 2204 // Find the reduction identity variable. Zero for addition, or, xor, 2205 // one for multiplication, -1 for And. 2206 Value *Identity; 2207 Value *VectorStart; 2208 if (RdxDesc.Kind == LoopVectorizationLegality::RK_IntegerMinMax || 2209 RdxDesc.Kind == LoopVectorizationLegality::RK_FloatMinMax) { 2210 // MinMax reduction have the start value as their identify. 2211 if (VF == 1) { 2212 VectorStart = Identity = RdxDesc.StartValue; 2213 } else { 2214 VectorStart = Identity = Builder.CreateVectorSplat(VF, 2215 RdxDesc.StartValue, 2216 "minmax.ident"); 2217 } 2218 } else { 2219 // Handle other reduction kinds: 2220 Constant *Iden = 2221 LoopVectorizationLegality::getReductionIdentity(RdxDesc.Kind, 2222 VecTy->getScalarType()); 2223 if (VF == 1) { 2224 Identity = Iden; 2225 // This vector is the Identity vector where the first element is the 2226 // incoming scalar reduction. 2227 VectorStart = RdxDesc.StartValue; 2228 } else { 2229 Identity = ConstantVector::getSplat(VF, Iden); 2230 2231 // This vector is the Identity vector where the first element is the 2232 // incoming scalar reduction. 2233 VectorStart = Builder.CreateInsertElement(Identity, 2234 RdxDesc.StartValue, Zero); 2235 } 2236 } 2237 2238 // Fix the vector-loop phi. 2239 // We created the induction variable so we know that the 2240 // preheader is the first entry. 2241 BasicBlock *VecPreheader = Induction->getIncomingBlock(0); 2242 2243 // Reductions do not have to start at zero. They can start with 2244 // any loop invariant values. 2245 VectorParts &VecRdxPhi = WidenMap.get(RdxPhi); 2246 BasicBlock *Latch = OrigLoop->getLoopLatch(); 2247 Value *LoopVal = RdxPhi->getIncomingValueForBlock(Latch); 2248 VectorParts &Val = getVectorValue(LoopVal); 2249 for (unsigned part = 0; part < UF; ++part) { 2250 // Make sure to add the reduction stat value only to the 2251 // first unroll part. 2252 Value *StartVal = (part == 0) ? VectorStart : Identity; 2253 cast<PHINode>(VecRdxPhi[part])->addIncoming(StartVal, VecPreheader); 2254 cast<PHINode>(VecRdxPhi[part])->addIncoming(Val[part], LoopVectorBody); 2255 } 2256 2257 // Before each round, move the insertion point right between 2258 // the PHIs and the values we are going to write. 2259 // This allows us to write both PHINodes and the extractelement 2260 // instructions. 2261 Builder.SetInsertPoint(LoopMiddleBlock->getFirstInsertionPt()); 2262 2263 VectorParts RdxParts; 2264 setDebugLocFromInst(Builder, RdxDesc.LoopExitInstr); 2265 for (unsigned part = 0; part < UF; ++part) { 2266 // This PHINode contains the vectorized reduction variable, or 2267 // the initial value vector, if we bypass the vector loop. 2268 VectorParts &RdxExitVal = getVectorValue(RdxDesc.LoopExitInstr); 2269 PHINode *NewPhi = Builder.CreatePHI(VecTy, 2, "rdx.vec.exit.phi"); 2270 Value *StartVal = (part == 0) ? VectorStart : Identity; 2271 for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I) 2272 NewPhi->addIncoming(StartVal, LoopBypassBlocks[I]); 2273 NewPhi->addIncoming(RdxExitVal[part], LoopVectorBody); 2274 RdxParts.push_back(NewPhi); 2275 } 2276 2277 // Reduce all of the unrolled parts into a single vector. 2278 Value *ReducedPartRdx = RdxParts[0]; 2279 unsigned Op = getReductionBinOp(RdxDesc.Kind); 2280 setDebugLocFromInst(Builder, ReducedPartRdx); 2281 for (unsigned part = 1; part < UF; ++part) { 2282 if (Op != Instruction::ICmp && Op != Instruction::FCmp) 2283 ReducedPartRdx = Builder.CreateBinOp((Instruction::BinaryOps)Op, 2284 RdxParts[part], ReducedPartRdx, 2285 "bin.rdx"); 2286 else 2287 ReducedPartRdx = createMinMaxOp(Builder, RdxDesc.MinMaxKind, 2288 ReducedPartRdx, RdxParts[part]); 2289 } 2290 2291 if (VF > 1) { 2292 // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles 2293 // and vector ops, reducing the set of values being computed by half each 2294 // round. 2295 assert(isPowerOf2_32(VF) && 2296 "Reduction emission only supported for pow2 vectors!"); 2297 Value *TmpVec = ReducedPartRdx; 2298 SmallVector<Constant*, 32> ShuffleMask(VF, 0); 2299 for (unsigned i = VF; i != 1; i >>= 1) { 2300 // Move the upper half of the vector to the lower half. 2301 for (unsigned j = 0; j != i/2; ++j) 2302 ShuffleMask[j] = Builder.getInt32(i/2 + j); 2303 2304 // Fill the rest of the mask with undef. 2305 std::fill(&ShuffleMask[i/2], ShuffleMask.end(), 2306 UndefValue::get(Builder.getInt32Ty())); 2307 2308 Value *Shuf = 2309 Builder.CreateShuffleVector(TmpVec, 2310 UndefValue::get(TmpVec->getType()), 2311 ConstantVector::get(ShuffleMask), 2312 "rdx.shuf"); 2313 2314 if (Op != Instruction::ICmp && Op != Instruction::FCmp) 2315 TmpVec = Builder.CreateBinOp((Instruction::BinaryOps)Op, TmpVec, Shuf, 2316 "bin.rdx"); 2317 else 2318 TmpVec = createMinMaxOp(Builder, RdxDesc.MinMaxKind, TmpVec, Shuf); 2319 } 2320 2321 // The result is in the first element of the vector. 2322 ReducedPartRdx = Builder.CreateExtractElement(TmpVec, 2323 Builder.getInt32(0)); 2324 } 2325 2326 // Now, we need to fix the users of the reduction variable 2327 // inside and outside of the scalar remainder loop. 2328 // We know that the loop is in LCSSA form. We need to update the 2329 // PHI nodes in the exit blocks. 2330 for (BasicBlock::iterator LEI = LoopExitBlock->begin(), 2331 LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) { 2332 PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI); 2333 if (!LCSSAPhi) break; 2334 2335 // All PHINodes need to have a single entry edge, or two if 2336 // we already fixed them. 2337 assert(LCSSAPhi->getNumIncomingValues() < 3 && "Invalid LCSSA PHI"); 2338 2339 // We found our reduction value exit-PHI. Update it with the 2340 // incoming bypass edge. 2341 if (LCSSAPhi->getIncomingValue(0) == RdxDesc.LoopExitInstr) { 2342 // Add an edge coming from the bypass. 2343 LCSSAPhi->addIncoming(ReducedPartRdx, LoopMiddleBlock); 2344 break; 2345 } 2346 }// end of the LCSSA phi scan. 2347 2348 // Fix the scalar loop reduction variable with the incoming reduction sum 2349 // from the vector body and from the backedge value. 2350 int IncomingEdgeBlockIdx = 2351 (RdxPhi)->getBasicBlockIndex(OrigLoop->getLoopLatch()); 2352 assert(IncomingEdgeBlockIdx >= 0 && "Invalid block index"); 2353 // Pick the other block. 2354 int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1); 2355 (RdxPhi)->setIncomingValue(SelfEdgeBlockIdx, ReducedPartRdx); 2356 (RdxPhi)->setIncomingValue(IncomingEdgeBlockIdx, RdxDesc.LoopExitInstr); 2357 }// end of for each redux variable. 2358 2359 fixLCSSAPHIs(); 2360 2361 // Remove redundant induction instructions. 2362 cse(LoopVectorBody); 2363 } 2364 2365 void InnerLoopVectorizer::fixLCSSAPHIs() { 2366 for (BasicBlock::iterator LEI = LoopExitBlock->begin(), 2367 LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) { 2368 PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI); 2369 if (!LCSSAPhi) break; 2370 if (LCSSAPhi->getNumIncomingValues() == 1) 2371 LCSSAPhi->addIncoming(UndefValue::get(LCSSAPhi->getType()), 2372 LoopMiddleBlock); 2373 } 2374 } 2375 2376 InnerLoopVectorizer::VectorParts 2377 InnerLoopVectorizer::createEdgeMask(BasicBlock *Src, BasicBlock *Dst) { 2378 assert(std::find(pred_begin(Dst), pred_end(Dst), Src) != pred_end(Dst) && 2379 "Invalid edge"); 2380 2381 // Look for cached value. 2382 std::pair<BasicBlock*, BasicBlock*> Edge(Src, Dst); 2383 EdgeMaskCache::iterator ECEntryIt = MaskCache.find(Edge); 2384 if (ECEntryIt != MaskCache.end()) 2385 return ECEntryIt->second; 2386 2387 VectorParts SrcMask = createBlockInMask(Src); 2388 2389 // The terminator has to be a branch inst! 2390 BranchInst *BI = dyn_cast<BranchInst>(Src->getTerminator()); 2391 assert(BI && "Unexpected terminator found"); 2392 2393 if (BI->isConditional()) { 2394 VectorParts EdgeMask = getVectorValue(BI->getCondition()); 2395 2396 if (BI->getSuccessor(0) != Dst) 2397 for (unsigned part = 0; part < UF; ++part) 2398 EdgeMask[part] = Builder.CreateNot(EdgeMask[part]); 2399 2400 for (unsigned part = 0; part < UF; ++part) 2401 EdgeMask[part] = Builder.CreateAnd(EdgeMask[part], SrcMask[part]); 2402 2403 MaskCache[Edge] = EdgeMask; 2404 return EdgeMask; 2405 } 2406 2407 MaskCache[Edge] = SrcMask; 2408 return SrcMask; 2409 } 2410 2411 InnerLoopVectorizer::VectorParts 2412 InnerLoopVectorizer::createBlockInMask(BasicBlock *BB) { 2413 assert(OrigLoop->contains(BB) && "Block is not a part of a loop"); 2414 2415 // Loop incoming mask is all-one. 2416 if (OrigLoop->getHeader() == BB) { 2417 Value *C = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 1); 2418 return getVectorValue(C); 2419 } 2420 2421 // This is the block mask. We OR all incoming edges, and with zero. 2422 Value *Zero = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 0); 2423 VectorParts BlockMask = getVectorValue(Zero); 2424 2425 // For each pred: 2426 for (pred_iterator it = pred_begin(BB), e = pred_end(BB); it != e; ++it) { 2427 VectorParts EM = createEdgeMask(*it, BB); 2428 for (unsigned part = 0; part < UF; ++part) 2429 BlockMask[part] = Builder.CreateOr(BlockMask[part], EM[part]); 2430 } 2431 2432 return BlockMask; 2433 } 2434 2435 void InnerLoopVectorizer::widenPHIInstruction(Instruction *PN, 2436 InnerLoopVectorizer::VectorParts &Entry, 2437 LoopVectorizationLegality *Legal, 2438 unsigned UF, unsigned VF, PhiVector *PV) { 2439 PHINode* P = cast<PHINode>(PN); 2440 // Handle reduction variables: 2441 if (Legal->getReductionVars()->count(P)) { 2442 for (unsigned part = 0; part < UF; ++part) { 2443 // This is phase one of vectorizing PHIs. 2444 Type *VecTy = (VF == 1) ? PN->getType() : 2445 VectorType::get(PN->getType(), VF); 2446 Entry[part] = PHINode::Create(VecTy, 2, "vec.phi", 2447 LoopVectorBody-> getFirstInsertionPt()); 2448 } 2449 PV->push_back(P); 2450 return; 2451 } 2452 2453 setDebugLocFromInst(Builder, P); 2454 // Check for PHI nodes that are lowered to vector selects. 2455 if (P->getParent() != OrigLoop->getHeader()) { 2456 // We know that all PHIs in non-header blocks are converted into 2457 // selects, so we don't have to worry about the insertion order and we 2458 // can just use the builder. 2459 // At this point we generate the predication tree. There may be 2460 // duplications since this is a simple recursive scan, but future 2461 // optimizations will clean it up. 2462 2463 unsigned NumIncoming = P->getNumIncomingValues(); 2464 2465 // Generate a sequence of selects of the form: 2466 // SELECT(Mask3, In3, 2467 // SELECT(Mask2, In2, 2468 // ( ...))) 2469 for (unsigned In = 0; In < NumIncoming; In++) { 2470 VectorParts Cond = createEdgeMask(P->getIncomingBlock(In), 2471 P->getParent()); 2472 VectorParts &In0 = getVectorValue(P->getIncomingValue(In)); 2473 2474 for (unsigned part = 0; part < UF; ++part) { 2475 // We might have single edge PHIs (blocks) - use an identity 2476 // 'select' for the first PHI operand. 2477 if (In == 0) 2478 Entry[part] = Builder.CreateSelect(Cond[part], In0[part], 2479 In0[part]); 2480 else 2481 // Select between the current value and the previous incoming edge 2482 // based on the incoming mask. 2483 Entry[part] = Builder.CreateSelect(Cond[part], In0[part], 2484 Entry[part], "predphi"); 2485 } 2486 } 2487 return; 2488 } 2489 2490 // This PHINode must be an induction variable. 2491 // Make sure that we know about it. 2492 assert(Legal->getInductionVars()->count(P) && 2493 "Not an induction variable"); 2494 2495 LoopVectorizationLegality::InductionInfo II = 2496 Legal->getInductionVars()->lookup(P); 2497 2498 switch (II.IK) { 2499 case LoopVectorizationLegality::IK_NoInduction: 2500 llvm_unreachable("Unknown induction"); 2501 case LoopVectorizationLegality::IK_IntInduction: { 2502 assert(P->getType() == II.StartValue->getType() && "Types must match"); 2503 Type *PhiTy = P->getType(); 2504 Value *Broadcasted; 2505 if (P == OldInduction) { 2506 // Handle the canonical induction variable. We might have had to 2507 // extend the type. 2508 Broadcasted = Builder.CreateTrunc(Induction, PhiTy); 2509 } else { 2510 // Handle other induction variables that are now based on the 2511 // canonical one. 2512 Value *NormalizedIdx = Builder.CreateSub(Induction, ExtendedIdx, 2513 "normalized.idx"); 2514 NormalizedIdx = Builder.CreateSExtOrTrunc(NormalizedIdx, PhiTy); 2515 Broadcasted = Builder.CreateAdd(II.StartValue, NormalizedIdx, 2516 "offset.idx"); 2517 } 2518 Broadcasted = getBroadcastInstrs(Broadcasted); 2519 // After broadcasting the induction variable we need to make the vector 2520 // consecutive by adding 0, 1, 2, etc. 2521 for (unsigned part = 0; part < UF; ++part) 2522 Entry[part] = getConsecutiveVector(Broadcasted, VF * part, false); 2523 return; 2524 } 2525 case LoopVectorizationLegality::IK_ReverseIntInduction: 2526 case LoopVectorizationLegality::IK_PtrInduction: 2527 case LoopVectorizationLegality::IK_ReversePtrInduction: 2528 // Handle reverse integer and pointer inductions. 2529 Value *StartIdx = ExtendedIdx; 2530 // This is the normalized GEP that starts counting at zero. 2531 Value *NormalizedIdx = Builder.CreateSub(Induction, StartIdx, 2532 "normalized.idx"); 2533 2534 // Handle the reverse integer induction variable case. 2535 if (LoopVectorizationLegality::IK_ReverseIntInduction == II.IK) { 2536 IntegerType *DstTy = cast<IntegerType>(II.StartValue->getType()); 2537 Value *CNI = Builder.CreateSExtOrTrunc(NormalizedIdx, DstTy, 2538 "resize.norm.idx"); 2539 Value *ReverseInd = Builder.CreateSub(II.StartValue, CNI, 2540 "reverse.idx"); 2541 2542 // This is a new value so do not hoist it out. 2543 Value *Broadcasted = getBroadcastInstrs(ReverseInd); 2544 // After broadcasting the induction variable we need to make the 2545 // vector consecutive by adding ... -3, -2, -1, 0. 2546 for (unsigned part = 0; part < UF; ++part) 2547 Entry[part] = getConsecutiveVector(Broadcasted, -(int)VF * part, 2548 true); 2549 return; 2550 } 2551 2552 // Handle the pointer induction variable case. 2553 assert(P->getType()->isPointerTy() && "Unexpected type."); 2554 2555 // Is this a reverse induction ptr or a consecutive induction ptr. 2556 bool Reverse = (LoopVectorizationLegality::IK_ReversePtrInduction == 2557 II.IK); 2558 2559 // This is the vector of results. Notice that we don't generate 2560 // vector geps because scalar geps result in better code. 2561 for (unsigned part = 0; part < UF; ++part) { 2562 if (VF == 1) { 2563 int EltIndex = (part) * (Reverse ? -1 : 1); 2564 Constant *Idx = ConstantInt::get(Induction->getType(), EltIndex); 2565 Value *GlobalIdx; 2566 if (Reverse) 2567 GlobalIdx = Builder.CreateSub(Idx, NormalizedIdx, "gep.ridx"); 2568 else 2569 GlobalIdx = Builder.CreateAdd(NormalizedIdx, Idx, "gep.idx"); 2570 2571 Value *SclrGep = Builder.CreateGEP(II.StartValue, GlobalIdx, 2572 "next.gep"); 2573 Entry[part] = SclrGep; 2574 continue; 2575 } 2576 2577 Value *VecVal = UndefValue::get(VectorType::get(P->getType(), VF)); 2578 for (unsigned int i = 0; i < VF; ++i) { 2579 int EltIndex = (i + part * VF) * (Reverse ? -1 : 1); 2580 Constant *Idx = ConstantInt::get(Induction->getType(), EltIndex); 2581 Value *GlobalIdx; 2582 if (!Reverse) 2583 GlobalIdx = Builder.CreateAdd(NormalizedIdx, Idx, "gep.idx"); 2584 else 2585 GlobalIdx = Builder.CreateSub(Idx, NormalizedIdx, "gep.ridx"); 2586 2587 Value *SclrGep = Builder.CreateGEP(II.StartValue, GlobalIdx, 2588 "next.gep"); 2589 VecVal = Builder.CreateInsertElement(VecVal, SclrGep, 2590 Builder.getInt32(i), 2591 "insert.gep"); 2592 } 2593 Entry[part] = VecVal; 2594 } 2595 return; 2596 } 2597 } 2598 2599 void 2600 InnerLoopVectorizer::vectorizeBlockInLoop(LoopVectorizationLegality *Legal, 2601 BasicBlock *BB, PhiVector *PV) { 2602 // For each instruction in the old loop. 2603 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) { 2604 VectorParts &Entry = WidenMap.get(it); 2605 switch (it->getOpcode()) { 2606 case Instruction::Br: 2607 // Nothing to do for PHIs and BR, since we already took care of the 2608 // loop control flow instructions. 2609 continue; 2610 case Instruction::PHI:{ 2611 // Vectorize PHINodes. 2612 widenPHIInstruction(it, Entry, Legal, UF, VF, PV); 2613 continue; 2614 }// End of PHI. 2615 2616 case Instruction::Add: 2617 case Instruction::FAdd: 2618 case Instruction::Sub: 2619 case Instruction::FSub: 2620 case Instruction::Mul: 2621 case Instruction::FMul: 2622 case Instruction::UDiv: 2623 case Instruction::SDiv: 2624 case Instruction::FDiv: 2625 case Instruction::URem: 2626 case Instruction::SRem: 2627 case Instruction::FRem: 2628 case Instruction::Shl: 2629 case Instruction::LShr: 2630 case Instruction::AShr: 2631 case Instruction::And: 2632 case Instruction::Or: 2633 case Instruction::Xor: { 2634 // Just widen binops. 2635 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(it); 2636 setDebugLocFromInst(Builder, BinOp); 2637 VectorParts &A = getVectorValue(it->getOperand(0)); 2638 VectorParts &B = getVectorValue(it->getOperand(1)); 2639 2640 // Use this vector value for all users of the original instruction. 2641 for (unsigned Part = 0; Part < UF; ++Part) { 2642 Value *V = Builder.CreateBinOp(BinOp->getOpcode(), A[Part], B[Part]); 2643 2644 // Update the NSW, NUW and Exact flags. Notice: V can be an Undef. 2645 BinaryOperator *VecOp = dyn_cast<BinaryOperator>(V); 2646 if (VecOp && isa<OverflowingBinaryOperator>(BinOp)) { 2647 VecOp->setHasNoSignedWrap(BinOp->hasNoSignedWrap()); 2648 VecOp->setHasNoUnsignedWrap(BinOp->hasNoUnsignedWrap()); 2649 } 2650 if (VecOp && isa<PossiblyExactOperator>(VecOp)) 2651 VecOp->setIsExact(BinOp->isExact()); 2652 2653 Entry[Part] = V; 2654 } 2655 break; 2656 } 2657 case Instruction::Select: { 2658 // Widen selects. 2659 // If the selector is loop invariant we can create a select 2660 // instruction with a scalar condition. Otherwise, use vector-select. 2661 bool InvariantCond = SE->isLoopInvariant(SE->getSCEV(it->getOperand(0)), 2662 OrigLoop); 2663 setDebugLocFromInst(Builder, it); 2664 2665 // The condition can be loop invariant but still defined inside the 2666 // loop. This means that we can't just use the original 'cond' value. 2667 // We have to take the 'vectorized' value and pick the first lane. 2668 // Instcombine will make this a no-op. 2669 VectorParts &Cond = getVectorValue(it->getOperand(0)); 2670 VectorParts &Op0 = getVectorValue(it->getOperand(1)); 2671 VectorParts &Op1 = getVectorValue(it->getOperand(2)); 2672 2673 Value *ScalarCond = (VF == 1) ? Cond[0] : 2674 Builder.CreateExtractElement(Cond[0], Builder.getInt32(0)); 2675 2676 for (unsigned Part = 0; Part < UF; ++Part) { 2677 Entry[Part] = Builder.CreateSelect( 2678 InvariantCond ? ScalarCond : Cond[Part], 2679 Op0[Part], 2680 Op1[Part]); 2681 } 2682 break; 2683 } 2684 2685 case Instruction::ICmp: 2686 case Instruction::FCmp: { 2687 // Widen compares. Generate vector compares. 2688 bool FCmp = (it->getOpcode() == Instruction::FCmp); 2689 CmpInst *Cmp = dyn_cast<CmpInst>(it); 2690 setDebugLocFromInst(Builder, it); 2691 VectorParts &A = getVectorValue(it->getOperand(0)); 2692 VectorParts &B = getVectorValue(it->getOperand(1)); 2693 for (unsigned Part = 0; Part < UF; ++Part) { 2694 Value *C = 0; 2695 if (FCmp) 2696 C = Builder.CreateFCmp(Cmp->getPredicate(), A[Part], B[Part]); 2697 else 2698 C = Builder.CreateICmp(Cmp->getPredicate(), A[Part], B[Part]); 2699 Entry[Part] = C; 2700 } 2701 break; 2702 } 2703 2704 case Instruction::Store: 2705 case Instruction::Load: 2706 vectorizeMemoryInstruction(it, Legal); 2707 break; 2708 case Instruction::ZExt: 2709 case Instruction::SExt: 2710 case Instruction::FPToUI: 2711 case Instruction::FPToSI: 2712 case Instruction::FPExt: 2713 case Instruction::PtrToInt: 2714 case Instruction::IntToPtr: 2715 case Instruction::SIToFP: 2716 case Instruction::UIToFP: 2717 case Instruction::Trunc: 2718 case Instruction::FPTrunc: 2719 case Instruction::BitCast: { 2720 CastInst *CI = dyn_cast<CastInst>(it); 2721 setDebugLocFromInst(Builder, it); 2722 /// Optimize the special case where the source is the induction 2723 /// variable. Notice that we can only optimize the 'trunc' case 2724 /// because: a. FP conversions lose precision, b. sext/zext may wrap, 2725 /// c. other casts depend on pointer size. 2726 if (CI->getOperand(0) == OldInduction && 2727 it->getOpcode() == Instruction::Trunc) { 2728 Value *ScalarCast = Builder.CreateCast(CI->getOpcode(), Induction, 2729 CI->getType()); 2730 Value *Broadcasted = getBroadcastInstrs(ScalarCast); 2731 for (unsigned Part = 0; Part < UF; ++Part) 2732 Entry[Part] = getConsecutiveVector(Broadcasted, VF * Part, false); 2733 break; 2734 } 2735 /// Vectorize casts. 2736 Type *DestTy = (VF == 1) ? CI->getType() : 2737 VectorType::get(CI->getType(), VF); 2738 2739 VectorParts &A = getVectorValue(it->getOperand(0)); 2740 for (unsigned Part = 0; Part < UF; ++Part) 2741 Entry[Part] = Builder.CreateCast(CI->getOpcode(), A[Part], DestTy); 2742 break; 2743 } 2744 2745 case Instruction::Call: { 2746 // Ignore dbg intrinsics. 2747 if (isa<DbgInfoIntrinsic>(it)) 2748 break; 2749 setDebugLocFromInst(Builder, it); 2750 2751 Module *M = BB->getParent()->getParent(); 2752 CallInst *CI = cast<CallInst>(it); 2753 Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI); 2754 assert(ID && "Not an intrinsic call!"); 2755 switch (ID) { 2756 case Intrinsic::lifetime_end: 2757 case Intrinsic::lifetime_start: 2758 scalarizeInstruction(it); 2759 break; 2760 default: 2761 for (unsigned Part = 0; Part < UF; ++Part) { 2762 SmallVector<Value *, 4> Args; 2763 for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i) { 2764 VectorParts &Arg = getVectorValue(CI->getArgOperand(i)); 2765 Args.push_back(Arg[Part]); 2766 } 2767 Type *Tys[] = {CI->getType()}; 2768 if (VF > 1) 2769 Tys[0] = VectorType::get(CI->getType()->getScalarType(), VF); 2770 2771 Function *F = Intrinsic::getDeclaration(M, ID, Tys); 2772 Entry[Part] = Builder.CreateCall(F, Args); 2773 } 2774 break; 2775 } 2776 break; 2777 } 2778 2779 default: 2780 // All other instructions are unsupported. Scalarize them. 2781 scalarizeInstruction(it); 2782 break; 2783 }// end of switch. 2784 }// end of for_each instr. 2785 } 2786 2787 void InnerLoopVectorizer::updateAnalysis() { 2788 // Forget the original basic block. 2789 SE->forgetLoop(OrigLoop); 2790 2791 // Update the dominator tree information. 2792 assert(DT->properlyDominates(LoopBypassBlocks.front(), LoopExitBlock) && 2793 "Entry does not dominate exit."); 2794 2795 for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I) 2796 DT->addNewBlock(LoopBypassBlocks[I], LoopBypassBlocks[I-1]); 2797 DT->addNewBlock(LoopVectorPreHeader, LoopBypassBlocks.back()); 2798 DT->addNewBlock(LoopVectorBody, LoopVectorPreHeader); 2799 DT->addNewBlock(LoopMiddleBlock, LoopBypassBlocks.front()); 2800 DT->addNewBlock(LoopScalarPreHeader, LoopMiddleBlock); 2801 DT->changeImmediateDominator(LoopScalarBody, LoopScalarPreHeader); 2802 DT->changeImmediateDominator(LoopExitBlock, LoopMiddleBlock); 2803 2804 DEBUG(DT->verifyAnalysis()); 2805 } 2806 2807 bool LoopVectorizationLegality::canVectorizeWithIfConvert() { 2808 if (!EnableIfConversion) 2809 return false; 2810 2811 assert(TheLoop->getNumBlocks() > 1 && "Single block loops are vectorizable"); 2812 2813 // A list of pointers that we can safely read and write to. 2814 SmallPtrSet<Value *, 8> SafePointes; 2815 2816 // Collect safe addresses. 2817 for (Loop::block_iterator BI = TheLoop->block_begin(), 2818 BE = TheLoop->block_end(); BI != BE; ++BI) { 2819 BasicBlock *BB = *BI; 2820 2821 if (blockNeedsPredication(BB)) 2822 continue; 2823 2824 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) { 2825 if (LoadInst *LI = dyn_cast<LoadInst>(I)) 2826 SafePointes.insert(LI->getPointerOperand()); 2827 else if (StoreInst *SI = dyn_cast<StoreInst>(I)) 2828 SafePointes.insert(SI->getPointerOperand()); 2829 } 2830 } 2831 2832 // Collect the blocks that need predication. 2833 for (Loop::block_iterator BI = TheLoop->block_begin(), 2834 BE = TheLoop->block_end(); BI != BE; ++BI) { 2835 BasicBlock *BB = *BI; 2836 2837 // We don't support switch statements inside loops. 2838 if (!isa<BranchInst>(BB->getTerminator())) 2839 return false; 2840 2841 // We must be able to predicate all blocks that need to be predicated. 2842 if (blockNeedsPredication(BB) && !blockCanBePredicated(BB, SafePointes)) 2843 return false; 2844 } 2845 2846 // We can if-convert this loop. 2847 return true; 2848 } 2849 2850 bool LoopVectorizationLegality::canVectorize() { 2851 // We must have a loop in canonical form. Loops with indirectbr in them cannot 2852 // be canonicalized. 2853 if (!TheLoop->getLoopPreheader()) 2854 return false; 2855 2856 // We can only vectorize innermost loops. 2857 if (TheLoop->getSubLoopsVector().size()) 2858 return false; 2859 2860 // We must have a single backedge. 2861 if (TheLoop->getNumBackEdges() != 1) 2862 return false; 2863 2864 // We must have a single exiting block. 2865 if (!TheLoop->getExitingBlock()) 2866 return false; 2867 2868 // We need to have a loop header. 2869 DEBUG(dbgs() << "LV: Found a loop: " << 2870 TheLoop->getHeader()->getName() << '\n'); 2871 2872 // Check if we can if-convert non-single-bb loops. 2873 unsigned NumBlocks = TheLoop->getNumBlocks(); 2874 if (NumBlocks != 1 && !canVectorizeWithIfConvert()) { 2875 DEBUG(dbgs() << "LV: Can't if-convert the loop.\n"); 2876 return false; 2877 } 2878 2879 // ScalarEvolution needs to be able to find the exit count. 2880 const SCEV *ExitCount = SE->getBackedgeTakenCount(TheLoop); 2881 if (ExitCount == SE->getCouldNotCompute()) { 2882 DEBUG(dbgs() << "LV: SCEV could not compute the loop exit count.\n"); 2883 return false; 2884 } 2885 2886 // Do not loop-vectorize loops with a tiny trip count. 2887 BasicBlock *Latch = TheLoop->getLoopLatch(); 2888 unsigned TC = SE->getSmallConstantTripCount(TheLoop, Latch); 2889 if (TC > 0u && TC < TinyTripCountVectorThreshold) { 2890 DEBUG(dbgs() << "LV: Found a loop with a very small trip count. " << 2891 "This loop is not worth vectorizing.\n"); 2892 return false; 2893 } 2894 2895 // Check if we can vectorize the instructions and CFG in this loop. 2896 if (!canVectorizeInstrs()) { 2897 DEBUG(dbgs() << "LV: Can't vectorize the instructions or CFG\n"); 2898 return false; 2899 } 2900 2901 // Go over each instruction and look at memory deps. 2902 if (!canVectorizeMemory()) { 2903 DEBUG(dbgs() << "LV: Can't vectorize due to memory conflicts\n"); 2904 return false; 2905 } 2906 2907 // Collect all of the variables that remain uniform after vectorization. 2908 collectLoopUniforms(); 2909 2910 DEBUG(dbgs() << "LV: We can vectorize this loop" << 2911 (PtrRtCheck.Need ? " (with a runtime bound check)" : "") 2912 <<"!\n"); 2913 2914 // Okay! We can vectorize. At this point we don't have any other mem analysis 2915 // which may limit our maximum vectorization factor, so just return true with 2916 // no restrictions. 2917 return true; 2918 } 2919 2920 static Type *convertPointerToIntegerType(DataLayout &DL, Type *Ty) { 2921 if (Ty->isPointerTy()) 2922 return DL.getIntPtrType(Ty); 2923 2924 // It is possible that char's or short's overflow when we ask for the loop's 2925 // trip count, work around this by changing the type size. 2926 if (Ty->getScalarSizeInBits() < 32) 2927 return Type::getInt32Ty(Ty->getContext()); 2928 2929 return Ty; 2930 } 2931 2932 static Type* getWiderType(DataLayout &DL, Type *Ty0, Type *Ty1) { 2933 Ty0 = convertPointerToIntegerType(DL, Ty0); 2934 Ty1 = convertPointerToIntegerType(DL, Ty1); 2935 if (Ty0->getScalarSizeInBits() > Ty1->getScalarSizeInBits()) 2936 return Ty0; 2937 return Ty1; 2938 } 2939 2940 /// \brief Check that the instruction has outside loop users and is not an 2941 /// identified reduction variable. 2942 static bool hasOutsideLoopUser(const Loop *TheLoop, Instruction *Inst, 2943 SmallPtrSet<Value *, 4> &Reductions) { 2944 // Reduction instructions are allowed to have exit users. All other 2945 // instructions must not have external users. 2946 if (!Reductions.count(Inst)) 2947 //Check that all of the users of the loop are inside the BB. 2948 for (Value::use_iterator I = Inst->use_begin(), E = Inst->use_end(); 2949 I != E; ++I) { 2950 Instruction *U = cast<Instruction>(*I); 2951 // This user may be a reduction exit value. 2952 if (!TheLoop->contains(U)) { 2953 DEBUG(dbgs() << "LV: Found an outside user for : " << *U << '\n'); 2954 return true; 2955 } 2956 } 2957 return false; 2958 } 2959 2960 bool LoopVectorizationLegality::canVectorizeInstrs() { 2961 BasicBlock *PreHeader = TheLoop->getLoopPreheader(); 2962 BasicBlock *Header = TheLoop->getHeader(); 2963 2964 // Look for the attribute signaling the absence of NaNs. 2965 Function &F = *Header->getParent(); 2966 if (F.hasFnAttribute("no-nans-fp-math")) 2967 HasFunNoNaNAttr = F.getAttributes().getAttribute( 2968 AttributeSet::FunctionIndex, 2969 "no-nans-fp-math").getValueAsString() == "true"; 2970 2971 // For each block in the loop. 2972 for (Loop::block_iterator bb = TheLoop->block_begin(), 2973 be = TheLoop->block_end(); bb != be; ++bb) { 2974 2975 // Scan the instructions in the block and look for hazards. 2976 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e; 2977 ++it) { 2978 2979 if (PHINode *Phi = dyn_cast<PHINode>(it)) { 2980 Type *PhiTy = Phi->getType(); 2981 // Check that this PHI type is allowed. 2982 if (!PhiTy->isIntegerTy() && 2983 !PhiTy->isFloatingPointTy() && 2984 !PhiTy->isPointerTy()) { 2985 DEBUG(dbgs() << "LV: Found an non-int non-pointer PHI.\n"); 2986 return false; 2987 } 2988 2989 // If this PHINode is not in the header block, then we know that we 2990 // can convert it to select during if-conversion. No need to check if 2991 // the PHIs in this block are induction or reduction variables. 2992 if (*bb != Header) { 2993 // Check that this instruction has no outside users or is an 2994 // identified reduction value with an outside user. 2995 if(!hasOutsideLoopUser(TheLoop, it, AllowedExit)) 2996 continue; 2997 return false; 2998 } 2999 3000 // We only allow if-converted PHIs with more than two incoming values. 3001 if (Phi->getNumIncomingValues() != 2) { 3002 DEBUG(dbgs() << "LV: Found an invalid PHI.\n"); 3003 return false; 3004 } 3005 3006 // This is the value coming from the preheader. 3007 Value *StartValue = Phi->getIncomingValueForBlock(PreHeader); 3008 // Check if this is an induction variable. 3009 InductionKind IK = isInductionVariable(Phi); 3010 3011 if (IK_NoInduction != IK) { 3012 // Get the widest type. 3013 if (!WidestIndTy) 3014 WidestIndTy = convertPointerToIntegerType(*DL, PhiTy); 3015 else 3016 WidestIndTy = getWiderType(*DL, PhiTy, WidestIndTy); 3017 3018 // Int inductions are special because we only allow one IV. 3019 if (IK == IK_IntInduction) { 3020 // Use the phi node with the widest type as induction. Use the last 3021 // one if there are multiple (no good reason for doing this other 3022 // than it is expedient). 3023 if (!Induction || PhiTy == WidestIndTy) 3024 Induction = Phi; 3025 } 3026 3027 DEBUG(dbgs() << "LV: Found an induction variable.\n"); 3028 Inductions[Phi] = InductionInfo(StartValue, IK); 3029 3030 // Until we explicitly handle the case of an induction variable with 3031 // an outside loop user we have to give up vectorizing this loop. 3032 if (hasOutsideLoopUser(TheLoop, it, AllowedExit)) 3033 return false; 3034 3035 continue; 3036 } 3037 3038 if (AddReductionVar(Phi, RK_IntegerAdd)) { 3039 DEBUG(dbgs() << "LV: Found an ADD reduction PHI."<< *Phi <<"\n"); 3040 continue; 3041 } 3042 if (AddReductionVar(Phi, RK_IntegerMult)) { 3043 DEBUG(dbgs() << "LV: Found a MUL reduction PHI."<< *Phi <<"\n"); 3044 continue; 3045 } 3046 if (AddReductionVar(Phi, RK_IntegerOr)) { 3047 DEBUG(dbgs() << "LV: Found an OR reduction PHI."<< *Phi <<"\n"); 3048 continue; 3049 } 3050 if (AddReductionVar(Phi, RK_IntegerAnd)) { 3051 DEBUG(dbgs() << "LV: Found an AND reduction PHI."<< *Phi <<"\n"); 3052 continue; 3053 } 3054 if (AddReductionVar(Phi, RK_IntegerXor)) { 3055 DEBUG(dbgs() << "LV: Found a XOR reduction PHI."<< *Phi <<"\n"); 3056 continue; 3057 } 3058 if (AddReductionVar(Phi, RK_IntegerMinMax)) { 3059 DEBUG(dbgs() << "LV: Found a MINMAX reduction PHI."<< *Phi <<"\n"); 3060 continue; 3061 } 3062 if (AddReductionVar(Phi, RK_FloatMult)) { 3063 DEBUG(dbgs() << "LV: Found an FMult reduction PHI."<< *Phi <<"\n"); 3064 continue; 3065 } 3066 if (AddReductionVar(Phi, RK_FloatAdd)) { 3067 DEBUG(dbgs() << "LV: Found an FAdd reduction PHI."<< *Phi <<"\n"); 3068 continue; 3069 } 3070 if (AddReductionVar(Phi, RK_FloatMinMax)) { 3071 DEBUG(dbgs() << "LV: Found an float MINMAX reduction PHI."<< *Phi << 3072 "\n"); 3073 continue; 3074 } 3075 3076 DEBUG(dbgs() << "LV: Found an unidentified PHI."<< *Phi <<"\n"); 3077 return false; 3078 }// end of PHI handling 3079 3080 // We still don't handle functions. However, we can ignore dbg intrinsic 3081 // calls and we do handle certain intrinsic and libm functions. 3082 CallInst *CI = dyn_cast<CallInst>(it); 3083 if (CI && !getIntrinsicIDForCall(CI, TLI) && !isa<DbgInfoIntrinsic>(CI)) { 3084 DEBUG(dbgs() << "LV: Found a call site.\n"); 3085 return false; 3086 } 3087 3088 // Check that the instruction return type is vectorizable. 3089 // Also, we can't vectorize extractelement instructions. 3090 if ((!VectorType::isValidElementType(it->getType()) && 3091 !it->getType()->isVoidTy()) || isa<ExtractElementInst>(it)) { 3092 DEBUG(dbgs() << "LV: Found unvectorizable type.\n"); 3093 return false; 3094 } 3095 3096 // Check that the stored type is vectorizable. 3097 if (StoreInst *ST = dyn_cast<StoreInst>(it)) { 3098 Type *T = ST->getValueOperand()->getType(); 3099 if (!VectorType::isValidElementType(T)) 3100 return false; 3101 } 3102 3103 // Reduction instructions are allowed to have exit users. 3104 // All other instructions must not have external users. 3105 if (hasOutsideLoopUser(TheLoop, it, AllowedExit)) 3106 return false; 3107 3108 } // next instr. 3109 3110 } 3111 3112 if (!Induction) { 3113 DEBUG(dbgs() << "LV: Did not find one integer induction var.\n"); 3114 if (Inductions.empty()) 3115 return false; 3116 } 3117 3118 return true; 3119 } 3120 3121 void LoopVectorizationLegality::collectLoopUniforms() { 3122 // We now know that the loop is vectorizable! 3123 // Collect variables that will remain uniform after vectorization. 3124 std::vector<Value*> Worklist; 3125 BasicBlock *Latch = TheLoop->getLoopLatch(); 3126 3127 // Start with the conditional branch and walk up the block. 3128 Worklist.push_back(Latch->getTerminator()->getOperand(0)); 3129 3130 while (Worklist.size()) { 3131 Instruction *I = dyn_cast<Instruction>(Worklist.back()); 3132 Worklist.pop_back(); 3133 3134 // Look at instructions inside this loop. 3135 // Stop when reaching PHI nodes. 3136 // TODO: we need to follow values all over the loop, not only in this block. 3137 if (!I || !TheLoop->contains(I) || isa<PHINode>(I)) 3138 continue; 3139 3140 // This is a known uniform. 3141 Uniforms.insert(I); 3142 3143 // Insert all operands. 3144 Worklist.insert(Worklist.end(), I->op_begin(), I->op_end()); 3145 } 3146 } 3147 3148 namespace { 3149 /// \brief Analyses memory accesses in a loop. 3150 /// 3151 /// Checks whether run time pointer checks are needed and builds sets for data 3152 /// dependence checking. 3153 class AccessAnalysis { 3154 public: 3155 /// \brief Read or write access location. 3156 typedef PointerIntPair<Value *, 1, bool> MemAccessInfo; 3157 typedef SmallPtrSet<MemAccessInfo, 8> MemAccessInfoSet; 3158 3159 /// \brief Set of potential dependent memory accesses. 3160 typedef EquivalenceClasses<MemAccessInfo> DepCandidates; 3161 3162 AccessAnalysis(DataLayout *Dl, DepCandidates &DA) : 3163 DL(Dl), DepCands(DA), AreAllWritesIdentified(true), 3164 AreAllReadsIdentified(true), IsRTCheckNeeded(false) {} 3165 3166 /// \brief Register a load and whether it is only read from. 3167 void addLoad(Value *Ptr, bool IsReadOnly) { 3168 Accesses.insert(MemAccessInfo(Ptr, false)); 3169 if (IsReadOnly) 3170 ReadOnlyPtr.insert(Ptr); 3171 } 3172 3173 /// \brief Register a store. 3174 void addStore(Value *Ptr) { 3175 Accesses.insert(MemAccessInfo(Ptr, true)); 3176 } 3177 3178 /// \brief Check whether we can check the pointers at runtime for 3179 /// non-intersection. 3180 bool canCheckPtrAtRT(LoopVectorizationLegality::RuntimePointerCheck &RtCheck, 3181 unsigned &NumComparisons, ScalarEvolution *SE, 3182 Loop *TheLoop, bool ShouldCheckStride = false); 3183 3184 /// \brief Goes over all memory accesses, checks whether a RT check is needed 3185 /// and builds sets of dependent accesses. 3186 void buildDependenceSets() { 3187 // Process read-write pointers first. 3188 processMemAccesses(false); 3189 // Next, process read pointers. 3190 processMemAccesses(true); 3191 } 3192 3193 bool isRTCheckNeeded() { return IsRTCheckNeeded; } 3194 3195 bool isDependencyCheckNeeded() { return !CheckDeps.empty(); } 3196 void resetDepChecks() { CheckDeps.clear(); } 3197 3198 MemAccessInfoSet &getDependenciesToCheck() { return CheckDeps; } 3199 3200 private: 3201 typedef SetVector<MemAccessInfo> PtrAccessSet; 3202 typedef DenseMap<Value*, MemAccessInfo> UnderlyingObjToAccessMap; 3203 3204 /// \brief Go over all memory access or only the deferred ones if 3205 /// \p UseDeferred is true and check whether runtime pointer checks are needed 3206 /// and build sets of dependency check candidates. 3207 void processMemAccesses(bool UseDeferred); 3208 3209 /// Set of all accesses. 3210 PtrAccessSet Accesses; 3211 3212 /// Set of access to check after all writes have been processed. 3213 PtrAccessSet DeferredAccesses; 3214 3215 /// Map of pointers to last access encountered. 3216 UnderlyingObjToAccessMap ObjToLastAccess; 3217 3218 /// Set of accesses that need a further dependence check. 3219 MemAccessInfoSet CheckDeps; 3220 3221 /// Set of pointers that are read only. 3222 SmallPtrSet<Value*, 16> ReadOnlyPtr; 3223 3224 /// Set of underlying objects already written to. 3225 SmallPtrSet<Value*, 16> WriteObjects; 3226 3227 DataLayout *DL; 3228 3229 /// Sets of potentially dependent accesses - members of one set share an 3230 /// underlying pointer. The set "CheckDeps" identfies which sets really need a 3231 /// dependence check. 3232 DepCandidates &DepCands; 3233 3234 bool AreAllWritesIdentified; 3235 bool AreAllReadsIdentified; 3236 bool IsRTCheckNeeded; 3237 }; 3238 3239 } // end anonymous namespace 3240 3241 /// \brief Check whether a pointer can participate in a runtime bounds check. 3242 static bool hasComputableBounds(ScalarEvolution *SE, Value *Ptr) { 3243 const SCEV *PtrScev = SE->getSCEV(Ptr); 3244 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev); 3245 if (!AR) 3246 return false; 3247 3248 return AR->isAffine(); 3249 } 3250 3251 /// \brief Check the stride of the pointer and ensure that it does not wrap in 3252 /// the address space. 3253 static int isStridedPtr(ScalarEvolution *SE, DataLayout *DL, Value *Ptr, 3254 const Loop *Lp); 3255 3256 bool AccessAnalysis::canCheckPtrAtRT( 3257 LoopVectorizationLegality::RuntimePointerCheck &RtCheck, 3258 unsigned &NumComparisons, ScalarEvolution *SE, 3259 Loop *TheLoop, bool ShouldCheckStride) { 3260 // Find pointers with computable bounds. We are going to use this information 3261 // to place a runtime bound check. 3262 unsigned NumReadPtrChecks = 0; 3263 unsigned NumWritePtrChecks = 0; 3264 bool CanDoRT = true; 3265 3266 bool IsDepCheckNeeded = isDependencyCheckNeeded(); 3267 // We assign consecutive id to access from different dependence sets. 3268 // Accesses within the same set don't need a runtime check. 3269 unsigned RunningDepId = 1; 3270 DenseMap<Value *, unsigned> DepSetId; 3271 3272 for (PtrAccessSet::iterator AI = Accesses.begin(), AE = Accesses.end(); 3273 AI != AE; ++AI) { 3274 const MemAccessInfo &Access = *AI; 3275 Value *Ptr = Access.getPointer(); 3276 bool IsWrite = Access.getInt(); 3277 3278 // Just add write checks if we have both. 3279 if (!IsWrite && Accesses.count(MemAccessInfo(Ptr, true))) 3280 continue; 3281 3282 if (IsWrite) 3283 ++NumWritePtrChecks; 3284 else 3285 ++NumReadPtrChecks; 3286 3287 if (hasComputableBounds(SE, Ptr) && 3288 // When we run after a failing dependency check we have to make sure we 3289 // don't have wrapping pointers. 3290 (!ShouldCheckStride || isStridedPtr(SE, DL, Ptr, TheLoop) == 1)) { 3291 // The id of the dependence set. 3292 unsigned DepId; 3293 3294 if (IsDepCheckNeeded) { 3295 Value *Leader = DepCands.getLeaderValue(Access).getPointer(); 3296 unsigned &LeaderId = DepSetId[Leader]; 3297 if (!LeaderId) 3298 LeaderId = RunningDepId++; 3299 DepId = LeaderId; 3300 } else 3301 // Each access has its own dependence set. 3302 DepId = RunningDepId++; 3303 3304 RtCheck.insert(SE, TheLoop, Ptr, IsWrite, DepId); 3305 3306 DEBUG(dbgs() << "LV: Found a runtime check ptr:" << *Ptr << '\n'); 3307 } else { 3308 CanDoRT = false; 3309 } 3310 } 3311 3312 if (IsDepCheckNeeded && CanDoRT && RunningDepId == 2) 3313 NumComparisons = 0; // Only one dependence set. 3314 else { 3315 NumComparisons = (NumWritePtrChecks * (NumReadPtrChecks + 3316 NumWritePtrChecks - 1)); 3317 } 3318 3319 // If the pointers that we would use for the bounds comparison have different 3320 // address spaces, assume the values aren't directly comparable, so we can't 3321 // use them for the runtime check. We also have to assume they could 3322 // overlap. In the future there should be metadata for whether address spaces 3323 // are disjoint. 3324 unsigned NumPointers = RtCheck.Pointers.size(); 3325 for (unsigned i = 0; i < NumPointers; ++i) { 3326 for (unsigned j = i + 1; j < NumPointers; ++j) { 3327 // Only need to check pointers between two different dependency sets. 3328 if (RtCheck.DependencySetId[i] == RtCheck.DependencySetId[j]) 3329 continue; 3330 3331 Value *PtrI = RtCheck.Pointers[i]; 3332 Value *PtrJ = RtCheck.Pointers[j]; 3333 3334 unsigned ASi = PtrI->getType()->getPointerAddressSpace(); 3335 unsigned ASj = PtrJ->getType()->getPointerAddressSpace(); 3336 if (ASi != ASj) { 3337 DEBUG(dbgs() << "LV: Runtime check would require comparison between" 3338 " different address spaces\n"); 3339 return false; 3340 } 3341 } 3342 } 3343 3344 return CanDoRT; 3345 } 3346 3347 static bool isFunctionScopeIdentifiedObject(Value *Ptr) { 3348 return isNoAliasArgument(Ptr) || isNoAliasCall(Ptr) || isa<AllocaInst>(Ptr); 3349 } 3350 3351 void AccessAnalysis::processMemAccesses(bool UseDeferred) { 3352 // We process the set twice: first we process read-write pointers, last we 3353 // process read-only pointers. This allows us to skip dependence tests for 3354 // read-only pointers. 3355 3356 PtrAccessSet &S = UseDeferred ? DeferredAccesses : Accesses; 3357 for (PtrAccessSet::iterator AI = S.begin(), AE = S.end(); AI != AE; ++AI) { 3358 const MemAccessInfo &Access = *AI; 3359 Value *Ptr = Access.getPointer(); 3360 bool IsWrite = Access.getInt(); 3361 3362 DepCands.insert(Access); 3363 3364 // Memorize read-only pointers for later processing and skip them in the 3365 // first round (they need to be checked after we have seen all write 3366 // pointers). Note: we also mark pointer that are not consecutive as 3367 // "read-only" pointers (so that we check "a[b[i]] +="). Hence, we need the 3368 // second check for "!IsWrite". 3369 bool IsReadOnlyPtr = ReadOnlyPtr.count(Ptr) && !IsWrite; 3370 if (!UseDeferred && IsReadOnlyPtr) { 3371 DeferredAccesses.insert(Access); 3372 continue; 3373 } 3374 3375 bool NeedDepCheck = false; 3376 // Check whether there is the possiblity of dependency because of underlying 3377 // objects being the same. 3378 typedef SmallVector<Value*, 16> ValueVector; 3379 ValueVector TempObjects; 3380 GetUnderlyingObjects(Ptr, TempObjects, DL); 3381 for (ValueVector::iterator UI = TempObjects.begin(), UE = TempObjects.end(); 3382 UI != UE; ++UI) { 3383 Value *UnderlyingObj = *UI; 3384 3385 // If this is a write then it needs to be an identified object. If this a 3386 // read and all writes (so far) are identified function scope objects we 3387 // don't need an identified underlying object but only an Argument (the 3388 // next write is going to invalidate this assumption if it is 3389 // unidentified). 3390 // This is a micro-optimization for the case where all writes are 3391 // identified and we have one argument pointer. 3392 // Otherwise, we do need a runtime check. 3393 if ((IsWrite && !isFunctionScopeIdentifiedObject(UnderlyingObj)) || 3394 (!IsWrite && (!AreAllWritesIdentified || 3395 !isa<Argument>(UnderlyingObj)) && 3396 !isIdentifiedObject(UnderlyingObj))) { 3397 DEBUG(dbgs() << "LV: Found an unidentified " << 3398 (IsWrite ? "write" : "read" ) << " ptr: " << *UnderlyingObj << 3399 "\n"); 3400 IsRTCheckNeeded = (IsRTCheckNeeded || 3401 !isIdentifiedObject(UnderlyingObj) || 3402 !AreAllReadsIdentified); 3403 3404 if (IsWrite) 3405 AreAllWritesIdentified = false; 3406 if (!IsWrite) 3407 AreAllReadsIdentified = false; 3408 } 3409 3410 // If this is a write - check other reads and writes for conflicts. If 3411 // this is a read only check other writes for conflicts (but only if there 3412 // is no other write to the ptr - this is an optimization to catch "a[i] = 3413 // a[i] + " without having to do a dependence check). 3414 if ((IsWrite || IsReadOnlyPtr) && WriteObjects.count(UnderlyingObj)) 3415 NeedDepCheck = true; 3416 3417 if (IsWrite) 3418 WriteObjects.insert(UnderlyingObj); 3419 3420 // Create sets of pointers connected by shared underlying objects. 3421 UnderlyingObjToAccessMap::iterator Prev = 3422 ObjToLastAccess.find(UnderlyingObj); 3423 if (Prev != ObjToLastAccess.end()) 3424 DepCands.unionSets(Access, Prev->second); 3425 3426 ObjToLastAccess[UnderlyingObj] = Access; 3427 } 3428 3429 if (NeedDepCheck) 3430 CheckDeps.insert(Access); 3431 } 3432 } 3433 3434 namespace { 3435 /// \brief Checks memory dependences among accesses to the same underlying 3436 /// object to determine whether there vectorization is legal or not (and at 3437 /// which vectorization factor). 3438 /// 3439 /// This class works under the assumption that we already checked that memory 3440 /// locations with different underlying pointers are "must-not alias". 3441 /// We use the ScalarEvolution framework to symbolically evalutate access 3442 /// functions pairs. Since we currently don't restructure the loop we can rely 3443 /// on the program order of memory accesses to determine their safety. 3444 /// At the moment we will only deem accesses as safe for: 3445 /// * A negative constant distance assuming program order. 3446 /// 3447 /// Safe: tmp = a[i + 1]; OR a[i + 1] = x; 3448 /// a[i] = tmp; y = a[i]; 3449 /// 3450 /// The latter case is safe because later checks guarantuee that there can't 3451 /// be a cycle through a phi node (that is, we check that "x" and "y" is not 3452 /// the same variable: a header phi can only be an induction or a reduction, a 3453 /// reduction can't have a memory sink, an induction can't have a memory 3454 /// source). This is important and must not be violated (or we have to 3455 /// resort to checking for cycles through memory). 3456 /// 3457 /// * A positive constant distance assuming program order that is bigger 3458 /// than the biggest memory access. 3459 /// 3460 /// tmp = a[i] OR b[i] = x 3461 /// a[i+2] = tmp y = b[i+2]; 3462 /// 3463 /// Safe distance: 2 x sizeof(a[0]), and 2 x sizeof(b[0]), respectively. 3464 /// 3465 /// * Zero distances and all accesses have the same size. 3466 /// 3467 class MemoryDepChecker { 3468 public: 3469 typedef PointerIntPair<Value *, 1, bool> MemAccessInfo; 3470 typedef SmallPtrSet<MemAccessInfo, 8> MemAccessInfoSet; 3471 3472 MemoryDepChecker(ScalarEvolution *Se, DataLayout *Dl, const Loop *L) 3473 : SE(Se), DL(Dl), InnermostLoop(L), AccessIdx(0), 3474 ShouldRetryWithRuntimeCheck(false) {} 3475 3476 /// \brief Register the location (instructions are given increasing numbers) 3477 /// of a write access. 3478 void addAccess(StoreInst *SI) { 3479 Value *Ptr = SI->getPointerOperand(); 3480 Accesses[MemAccessInfo(Ptr, true)].push_back(AccessIdx); 3481 InstMap.push_back(SI); 3482 ++AccessIdx; 3483 } 3484 3485 /// \brief Register the location (instructions are given increasing numbers) 3486 /// of a write access. 3487 void addAccess(LoadInst *LI) { 3488 Value *Ptr = LI->getPointerOperand(); 3489 Accesses[MemAccessInfo(Ptr, false)].push_back(AccessIdx); 3490 InstMap.push_back(LI); 3491 ++AccessIdx; 3492 } 3493 3494 /// \brief Check whether the dependencies between the accesses are safe. 3495 /// 3496 /// Only checks sets with elements in \p CheckDeps. 3497 bool areDepsSafe(AccessAnalysis::DepCandidates &AccessSets, 3498 MemAccessInfoSet &CheckDeps); 3499 3500 /// \brief The maximum number of bytes of a vector register we can vectorize 3501 /// the accesses safely with. 3502 unsigned getMaxSafeDepDistBytes() { return MaxSafeDepDistBytes; } 3503 3504 /// \brief In same cases when the dependency check fails we can still 3505 /// vectorize the loop with a dynamic array access check. 3506 bool shouldRetryWithRuntimeCheck() { return ShouldRetryWithRuntimeCheck; } 3507 3508 private: 3509 ScalarEvolution *SE; 3510 DataLayout *DL; 3511 const Loop *InnermostLoop; 3512 3513 /// \brief Maps access locations (ptr, read/write) to program order. 3514 DenseMap<MemAccessInfo, std::vector<unsigned> > Accesses; 3515 3516 /// \brief Memory access instructions in program order. 3517 SmallVector<Instruction *, 16> InstMap; 3518 3519 /// \brief The program order index to be used for the next instruction. 3520 unsigned AccessIdx; 3521 3522 // We can access this many bytes in parallel safely. 3523 unsigned MaxSafeDepDistBytes; 3524 3525 /// \brief If we see a non-constant dependence distance we can still try to 3526 /// vectorize this loop with runtime checks. 3527 bool ShouldRetryWithRuntimeCheck; 3528 3529 /// \brief Check whether there is a plausible dependence between the two 3530 /// accesses. 3531 /// 3532 /// Access \p A must happen before \p B in program order. The two indices 3533 /// identify the index into the program order map. 3534 /// 3535 /// This function checks whether there is a plausible dependence (or the 3536 /// absence of such can't be proved) between the two accesses. If there is a 3537 /// plausible dependence but the dependence distance is bigger than one 3538 /// element access it records this distance in \p MaxSafeDepDistBytes (if this 3539 /// distance is smaller than any other distance encountered so far). 3540 /// Otherwise, this function returns true signaling a possible dependence. 3541 bool isDependent(const MemAccessInfo &A, unsigned AIdx, 3542 const MemAccessInfo &B, unsigned BIdx); 3543 3544 /// \brief Check whether the data dependence could prevent store-load 3545 /// forwarding. 3546 bool couldPreventStoreLoadForward(unsigned Distance, unsigned TypeByteSize); 3547 }; 3548 3549 } // end anonymous namespace 3550 3551 static bool isInBoundsGep(Value *Ptr) { 3552 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) 3553 return GEP->isInBounds(); 3554 return false; 3555 } 3556 3557 /// \brief Check whether the access through \p Ptr has a constant stride. 3558 static int isStridedPtr(ScalarEvolution *SE, DataLayout *DL, Value *Ptr, 3559 const Loop *Lp) { 3560 const Type *Ty = Ptr->getType(); 3561 assert(Ty->isPointerTy() && "Unexpected non-ptr"); 3562 3563 // Make sure that the pointer does not point to aggregate types. 3564 const PointerType *PtrTy = cast<PointerType>(Ty); 3565 if (PtrTy->getElementType()->isAggregateType()) { 3566 DEBUG(dbgs() << "LV: Bad stride - Not a pointer to a scalar type" << *Ptr << 3567 "\n"); 3568 return 0; 3569 } 3570 3571 const SCEV *PtrScev = SE->getSCEV(Ptr); 3572 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev); 3573 if (!AR) { 3574 DEBUG(dbgs() << "LV: Bad stride - Not an AddRecExpr pointer " 3575 << *Ptr << " SCEV: " << *PtrScev << "\n"); 3576 return 0; 3577 } 3578 3579 // The accesss function must stride over the innermost loop. 3580 if (Lp != AR->getLoop()) { 3581 DEBUG(dbgs() << "LV: Bad stride - Not striding over innermost loop " << 3582 *Ptr << " SCEV: " << *PtrScev << "\n"); 3583 } 3584 3585 // The address calculation must not wrap. Otherwise, a dependence could be 3586 // inverted. 3587 // An inbounds getelementptr that is a AddRec with a unit stride 3588 // cannot wrap per definition. The unit stride requirement is checked later. 3589 // An getelementptr without an inbounds attribute and unit stride would have 3590 // to access the pointer value "0" which is undefined behavior in address 3591 // space 0, therefore we can also vectorize this case. 3592 bool IsInBoundsGEP = isInBoundsGep(Ptr); 3593 bool IsNoWrapAddRec = AR->getNoWrapFlags(SCEV::NoWrapMask); 3594 bool IsInAddressSpaceZero = PtrTy->getAddressSpace() == 0; 3595 if (!IsNoWrapAddRec && !IsInBoundsGEP && !IsInAddressSpaceZero) { 3596 DEBUG(dbgs() << "LV: Bad stride - Pointer may wrap in the address space " 3597 << *Ptr << " SCEV: " << *PtrScev << "\n"); 3598 return 0; 3599 } 3600 3601 // Check the step is constant. 3602 const SCEV *Step = AR->getStepRecurrence(*SE); 3603 3604 // Calculate the pointer stride and check if it is consecutive. 3605 const SCEVConstant *C = dyn_cast<SCEVConstant>(Step); 3606 if (!C) { 3607 DEBUG(dbgs() << "LV: Bad stride - Not a constant strided " << *Ptr << 3608 " SCEV: " << *PtrScev << "\n"); 3609 return 0; 3610 } 3611 3612 int64_t Size = DL->getTypeAllocSize(PtrTy->getElementType()); 3613 const APInt &APStepVal = C->getValue()->getValue(); 3614 3615 // Huge step value - give up. 3616 if (APStepVal.getBitWidth() > 64) 3617 return 0; 3618 3619 int64_t StepVal = APStepVal.getSExtValue(); 3620 3621 // Strided access. 3622 int64_t Stride = StepVal / Size; 3623 int64_t Rem = StepVal % Size; 3624 if (Rem) 3625 return 0; 3626 3627 // If the SCEV could wrap but we have an inbounds gep with a unit stride we 3628 // know we can't "wrap around the address space". In case of address space 3629 // zero we know that this won't happen without triggering undefined behavior. 3630 if (!IsNoWrapAddRec && (IsInBoundsGEP || IsInAddressSpaceZero) && 3631 Stride != 1 && Stride != -1) 3632 return 0; 3633 3634 return Stride; 3635 } 3636 3637 bool MemoryDepChecker::couldPreventStoreLoadForward(unsigned Distance, 3638 unsigned TypeByteSize) { 3639 // If loads occur at a distance that is not a multiple of a feasible vector 3640 // factor store-load forwarding does not take place. 3641 // Positive dependences might cause troubles because vectorizing them might 3642 // prevent store-load forwarding making vectorized code run a lot slower. 3643 // a[i] = a[i-3] ^ a[i-8]; 3644 // The stores to a[i:i+1] don't align with the stores to a[i-3:i-2] and 3645 // hence on your typical architecture store-load forwarding does not take 3646 // place. Vectorizing in such cases does not make sense. 3647 // Store-load forwarding distance. 3648 const unsigned NumCyclesForStoreLoadThroughMemory = 8*TypeByteSize; 3649 // Maximum vector factor. 3650 unsigned MaxVFWithoutSLForwardIssues = MaxVectorWidth*TypeByteSize; 3651 if(MaxSafeDepDistBytes < MaxVFWithoutSLForwardIssues) 3652 MaxVFWithoutSLForwardIssues = MaxSafeDepDistBytes; 3653 3654 for (unsigned vf = 2*TypeByteSize; vf <= MaxVFWithoutSLForwardIssues; 3655 vf *= 2) { 3656 if (Distance % vf && Distance / vf < NumCyclesForStoreLoadThroughMemory) { 3657 MaxVFWithoutSLForwardIssues = (vf >>=1); 3658 break; 3659 } 3660 } 3661 3662 if (MaxVFWithoutSLForwardIssues< 2*TypeByteSize) { 3663 DEBUG(dbgs() << "LV: Distance " << Distance << 3664 " that could cause a store-load forwarding conflict\n"); 3665 return true; 3666 } 3667 3668 if (MaxVFWithoutSLForwardIssues < MaxSafeDepDistBytes && 3669 MaxVFWithoutSLForwardIssues != MaxVectorWidth*TypeByteSize) 3670 MaxSafeDepDistBytes = MaxVFWithoutSLForwardIssues; 3671 return false; 3672 } 3673 3674 bool MemoryDepChecker::isDependent(const MemAccessInfo &A, unsigned AIdx, 3675 const MemAccessInfo &B, unsigned BIdx) { 3676 assert (AIdx < BIdx && "Must pass arguments in program order"); 3677 3678 Value *APtr = A.getPointer(); 3679 Value *BPtr = B.getPointer(); 3680 bool AIsWrite = A.getInt(); 3681 bool BIsWrite = B.getInt(); 3682 3683 // Two reads are independent. 3684 if (!AIsWrite && !BIsWrite) 3685 return false; 3686 3687 const SCEV *AScev = SE->getSCEV(APtr); 3688 const SCEV *BScev = SE->getSCEV(BPtr); 3689 3690 int StrideAPtr = isStridedPtr(SE, DL, APtr, InnermostLoop); 3691 int StrideBPtr = isStridedPtr(SE, DL, BPtr, InnermostLoop); 3692 3693 const SCEV *Src = AScev; 3694 const SCEV *Sink = BScev; 3695 3696 // If the induction step is negative we have to invert source and sink of the 3697 // dependence. 3698 if (StrideAPtr < 0) { 3699 //Src = BScev; 3700 //Sink = AScev; 3701 std::swap(APtr, BPtr); 3702 std::swap(Src, Sink); 3703 std::swap(AIsWrite, BIsWrite); 3704 std::swap(AIdx, BIdx); 3705 std::swap(StrideAPtr, StrideBPtr); 3706 } 3707 3708 const SCEV *Dist = SE->getMinusSCEV(Sink, Src); 3709 3710 DEBUG(dbgs() << "LV: Src Scev: " << *Src << "Sink Scev: " << *Sink 3711 << "(Induction step: " << StrideAPtr << ")\n"); 3712 DEBUG(dbgs() << "LV: Distance for " << *InstMap[AIdx] << " to " 3713 << *InstMap[BIdx] << ": " << *Dist << "\n"); 3714 3715 // Need consecutive accesses. We don't want to vectorize 3716 // "A[B[i]] += ..." and similar code or pointer arithmetic that could wrap in 3717 // the address space. 3718 if (!StrideAPtr || !StrideBPtr || StrideAPtr != StrideBPtr){ 3719 DEBUG(dbgs() << "Non-consecutive pointer access\n"); 3720 return true; 3721 } 3722 3723 const SCEVConstant *C = dyn_cast<SCEVConstant>(Dist); 3724 if (!C) { 3725 DEBUG(dbgs() << "LV: Dependence because of non-constant distance\n"); 3726 ShouldRetryWithRuntimeCheck = true; 3727 return true; 3728 } 3729 3730 Type *ATy = APtr->getType()->getPointerElementType(); 3731 Type *BTy = BPtr->getType()->getPointerElementType(); 3732 unsigned TypeByteSize = DL->getTypeAllocSize(ATy); 3733 3734 // Negative distances are not plausible dependencies. 3735 const APInt &Val = C->getValue()->getValue(); 3736 if (Val.isNegative()) { 3737 bool IsTrueDataDependence = (AIsWrite && !BIsWrite); 3738 if (IsTrueDataDependence && 3739 (couldPreventStoreLoadForward(Val.abs().getZExtValue(), TypeByteSize) || 3740 ATy != BTy)) 3741 return true; 3742 3743 DEBUG(dbgs() << "LV: Dependence is negative: NoDep\n"); 3744 return false; 3745 } 3746 3747 // Write to the same location with the same size. 3748 // Could be improved to assert type sizes are the same (i32 == float, etc). 3749 if (Val == 0) { 3750 if (ATy == BTy) 3751 return false; 3752 DEBUG(dbgs() << "LV: Zero dependence difference but different types\n"); 3753 return true; 3754 } 3755 3756 assert(Val.isStrictlyPositive() && "Expect a positive value"); 3757 3758 // Positive distance bigger than max vectorization factor. 3759 if (ATy != BTy) { 3760 DEBUG(dbgs() << 3761 "LV: ReadWrite-Write positive dependency with different types\n"); 3762 return false; 3763 } 3764 3765 unsigned Distance = (unsigned) Val.getZExtValue(); 3766 3767 // Bail out early if passed-in parameters make vectorization not feasible. 3768 unsigned ForcedFactor = VectorizationFactor ? VectorizationFactor : 1; 3769 unsigned ForcedUnroll = VectorizationUnroll ? VectorizationUnroll : 1; 3770 3771 // The distance must be bigger than the size needed for a vectorized version 3772 // of the operation and the size of the vectorized operation must not be 3773 // bigger than the currrent maximum size. 3774 if (Distance < 2*TypeByteSize || 3775 2*TypeByteSize > MaxSafeDepDistBytes || 3776 Distance < TypeByteSize * ForcedUnroll * ForcedFactor) { 3777 DEBUG(dbgs() << "LV: Failure because of Positive distance " 3778 << Val.getSExtValue() << '\n'); 3779 return true; 3780 } 3781 3782 MaxSafeDepDistBytes = Distance < MaxSafeDepDistBytes ? 3783 Distance : MaxSafeDepDistBytes; 3784 3785 bool IsTrueDataDependence = (!AIsWrite && BIsWrite); 3786 if (IsTrueDataDependence && 3787 couldPreventStoreLoadForward(Distance, TypeByteSize)) 3788 return true; 3789 3790 DEBUG(dbgs() << "LV: Positive distance " << Val.getSExtValue() << 3791 " with max VF = " << MaxSafeDepDistBytes / TypeByteSize << '\n'); 3792 3793 return false; 3794 } 3795 3796 bool 3797 MemoryDepChecker::areDepsSafe(AccessAnalysis::DepCandidates &AccessSets, 3798 MemAccessInfoSet &CheckDeps) { 3799 3800 MaxSafeDepDistBytes = -1U; 3801 while (!CheckDeps.empty()) { 3802 MemAccessInfo CurAccess = *CheckDeps.begin(); 3803 3804 // Get the relevant memory access set. 3805 EquivalenceClasses<MemAccessInfo>::iterator I = 3806 AccessSets.findValue(AccessSets.getLeaderValue(CurAccess)); 3807 3808 // Check accesses within this set. 3809 EquivalenceClasses<MemAccessInfo>::member_iterator AI, AE; 3810 AI = AccessSets.member_begin(I), AE = AccessSets.member_end(); 3811 3812 // Check every access pair. 3813 while (AI != AE) { 3814 CheckDeps.erase(*AI); 3815 EquivalenceClasses<MemAccessInfo>::member_iterator OI = llvm::next(AI); 3816 while (OI != AE) { 3817 // Check every accessing instruction pair in program order. 3818 for (std::vector<unsigned>::iterator I1 = Accesses[*AI].begin(), 3819 I1E = Accesses[*AI].end(); I1 != I1E; ++I1) 3820 for (std::vector<unsigned>::iterator I2 = Accesses[*OI].begin(), 3821 I2E = Accesses[*OI].end(); I2 != I2E; ++I2) { 3822 if (*I1 < *I2 && isDependent(*AI, *I1, *OI, *I2)) 3823 return false; 3824 if (*I2 < *I1 && isDependent(*OI, *I2, *AI, *I1)) 3825 return false; 3826 } 3827 ++OI; 3828 } 3829 AI++; 3830 } 3831 } 3832 return true; 3833 } 3834 3835 bool LoopVectorizationLegality::canVectorizeMemory() { 3836 3837 typedef SmallVector<Value*, 16> ValueVector; 3838 typedef SmallPtrSet<Value*, 16> ValueSet; 3839 3840 // Holds the Load and Store *instructions*. 3841 ValueVector Loads; 3842 ValueVector Stores; 3843 3844 // Holds all the different accesses in the loop. 3845 unsigned NumReads = 0; 3846 unsigned NumReadWrites = 0; 3847 3848 PtrRtCheck.Pointers.clear(); 3849 PtrRtCheck.Need = false; 3850 3851 const bool IsAnnotatedParallel = TheLoop->isAnnotatedParallel(); 3852 MemoryDepChecker DepChecker(SE, DL, TheLoop); 3853 3854 // For each block. 3855 for (Loop::block_iterator bb = TheLoop->block_begin(), 3856 be = TheLoop->block_end(); bb != be; ++bb) { 3857 3858 // Scan the BB and collect legal loads and stores. 3859 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e; 3860 ++it) { 3861 3862 // If this is a load, save it. If this instruction can read from memory 3863 // but is not a load, then we quit. Notice that we don't handle function 3864 // calls that read or write. 3865 if (it->mayReadFromMemory()) { 3866 // Many math library functions read the rounding mode. We will only 3867 // vectorize a loop if it contains known function calls that don't set 3868 // the flag. Therefore, it is safe to ignore this read from memory. 3869 CallInst *Call = dyn_cast<CallInst>(it); 3870 if (Call && getIntrinsicIDForCall(Call, TLI)) 3871 continue; 3872 3873 LoadInst *Ld = dyn_cast<LoadInst>(it); 3874 if (!Ld) return false; 3875 if (!Ld->isSimple() && !IsAnnotatedParallel) { 3876 DEBUG(dbgs() << "LV: Found a non-simple load.\n"); 3877 return false; 3878 } 3879 Loads.push_back(Ld); 3880 DepChecker.addAccess(Ld); 3881 continue; 3882 } 3883 3884 // Save 'store' instructions. Abort if other instructions write to memory. 3885 if (it->mayWriteToMemory()) { 3886 StoreInst *St = dyn_cast<StoreInst>(it); 3887 if (!St) return false; 3888 if (!St->isSimple() && !IsAnnotatedParallel) { 3889 DEBUG(dbgs() << "LV: Found a non-simple store.\n"); 3890 return false; 3891 } 3892 Stores.push_back(St); 3893 DepChecker.addAccess(St); 3894 } 3895 } // Next instr. 3896 } // Next block. 3897 3898 // Now we have two lists that hold the loads and the stores. 3899 // Next, we find the pointers that they use. 3900 3901 // Check if we see any stores. If there are no stores, then we don't 3902 // care if the pointers are *restrict*. 3903 if (!Stores.size()) { 3904 DEBUG(dbgs() << "LV: Found a read-only loop!\n"); 3905 return true; 3906 } 3907 3908 AccessAnalysis::DepCandidates DependentAccesses; 3909 AccessAnalysis Accesses(DL, DependentAccesses); 3910 3911 // Holds the analyzed pointers. We don't want to call GetUnderlyingObjects 3912 // multiple times on the same object. If the ptr is accessed twice, once 3913 // for read and once for write, it will only appear once (on the write 3914 // list). This is okay, since we are going to check for conflicts between 3915 // writes and between reads and writes, but not between reads and reads. 3916 ValueSet Seen; 3917 3918 ValueVector::iterator I, IE; 3919 for (I = Stores.begin(), IE = Stores.end(); I != IE; ++I) { 3920 StoreInst *ST = cast<StoreInst>(*I); 3921 Value* Ptr = ST->getPointerOperand(); 3922 3923 if (isUniform(Ptr)) { 3924 DEBUG(dbgs() << "LV: We don't allow storing to uniform addresses\n"); 3925 return false; 3926 } 3927 3928 // If we did *not* see this pointer before, insert it to the read-write 3929 // list. At this phase it is only a 'write' list. 3930 if (Seen.insert(Ptr)) { 3931 ++NumReadWrites; 3932 Accesses.addStore(Ptr); 3933 } 3934 } 3935 3936 if (IsAnnotatedParallel) { 3937 DEBUG(dbgs() 3938 << "LV: A loop annotated parallel, ignore memory dependency " 3939 << "checks.\n"); 3940 return true; 3941 } 3942 3943 for (I = Loads.begin(), IE = Loads.end(); I != IE; ++I) { 3944 LoadInst *LD = cast<LoadInst>(*I); 3945 Value* Ptr = LD->getPointerOperand(); 3946 // If we did *not* see this pointer before, insert it to the 3947 // read list. If we *did* see it before, then it is already in 3948 // the read-write list. This allows us to vectorize expressions 3949 // such as A[i] += x; Because the address of A[i] is a read-write 3950 // pointer. This only works if the index of A[i] is consecutive. 3951 // If the address of i is unknown (for example A[B[i]]) then we may 3952 // read a few words, modify, and write a few words, and some of the 3953 // words may be written to the same address. 3954 bool IsReadOnlyPtr = false; 3955 if (Seen.insert(Ptr) || !isStridedPtr(SE, DL, Ptr, TheLoop)) { 3956 ++NumReads; 3957 IsReadOnlyPtr = true; 3958 } 3959 Accesses.addLoad(Ptr, IsReadOnlyPtr); 3960 } 3961 3962 // If we write (or read-write) to a single destination and there are no 3963 // other reads in this loop then is it safe to vectorize. 3964 if (NumReadWrites == 1 && NumReads == 0) { 3965 DEBUG(dbgs() << "LV: Found a write-only loop!\n"); 3966 return true; 3967 } 3968 3969 // Build dependence sets and check whether we need a runtime pointer bounds 3970 // check. 3971 Accesses.buildDependenceSets(); 3972 bool NeedRTCheck = Accesses.isRTCheckNeeded(); 3973 3974 // Find pointers with computable bounds. We are going to use this information 3975 // to place a runtime bound check. 3976 unsigned NumComparisons = 0; 3977 bool CanDoRT = false; 3978 if (NeedRTCheck) 3979 CanDoRT = Accesses.canCheckPtrAtRT(PtrRtCheck, NumComparisons, SE, TheLoop); 3980 3981 3982 DEBUG(dbgs() << "LV: We need to do " << NumComparisons << 3983 " pointer comparisons.\n"); 3984 3985 // If we only have one set of dependences to check pointers among we don't 3986 // need a runtime check. 3987 if (NumComparisons == 0 && NeedRTCheck) 3988 NeedRTCheck = false; 3989 3990 // Check that we did not collect too many pointers or found an unsizeable 3991 // pointer. 3992 if (!CanDoRT || NumComparisons > RuntimeMemoryCheckThreshold) { 3993 PtrRtCheck.reset(); 3994 CanDoRT = false; 3995 } 3996 3997 if (CanDoRT) { 3998 DEBUG(dbgs() << "LV: We can perform a memory runtime check if needed.\n"); 3999 } 4000 4001 if (NeedRTCheck && !CanDoRT) { 4002 DEBUG(dbgs() << "LV: We can't vectorize because we can't find " << 4003 "the array bounds.\n"); 4004 PtrRtCheck.reset(); 4005 return false; 4006 } 4007 4008 PtrRtCheck.Need = NeedRTCheck; 4009 4010 bool CanVecMem = true; 4011 if (Accesses.isDependencyCheckNeeded()) { 4012 DEBUG(dbgs() << "LV: Checking memory dependencies\n"); 4013 CanVecMem = DepChecker.areDepsSafe(DependentAccesses, 4014 Accesses.getDependenciesToCheck()); 4015 MaxSafeDepDistBytes = DepChecker.getMaxSafeDepDistBytes(); 4016 4017 if (!CanVecMem && DepChecker.shouldRetryWithRuntimeCheck()) { 4018 DEBUG(dbgs() << "LV: Retrying with memory checks\n"); 4019 NeedRTCheck = true; 4020 4021 // Clear the dependency checks. We assume they are not needed. 4022 Accesses.resetDepChecks(); 4023 4024 PtrRtCheck.reset(); 4025 PtrRtCheck.Need = true; 4026 4027 CanDoRT = Accesses.canCheckPtrAtRT(PtrRtCheck, NumComparisons, SE, 4028 TheLoop, true); 4029 // Check that we did not collect too many pointers or found an unsizeable 4030 // pointer. 4031 if (!CanDoRT || NumComparisons > RuntimeMemoryCheckThreshold) { 4032 DEBUG(dbgs() << "LV: Can't vectorize with memory checks\n"); 4033 PtrRtCheck.reset(); 4034 return false; 4035 } 4036 4037 CanVecMem = true; 4038 } 4039 } 4040 4041 DEBUG(dbgs() << "LV: We" << (NeedRTCheck ? "" : " don't") << 4042 " need a runtime memory check.\n"); 4043 4044 return CanVecMem; 4045 } 4046 4047 static bool hasMultipleUsesOf(Instruction *I, 4048 SmallPtrSet<Instruction *, 8> &Insts) { 4049 unsigned NumUses = 0; 4050 for(User::op_iterator Use = I->op_begin(), E = I->op_end(); Use != E; ++Use) { 4051 if (Insts.count(dyn_cast<Instruction>(*Use))) 4052 ++NumUses; 4053 if (NumUses > 1) 4054 return true; 4055 } 4056 4057 return false; 4058 } 4059 4060 static bool areAllUsesIn(Instruction *I, SmallPtrSet<Instruction *, 8> &Set) { 4061 for(User::op_iterator Use = I->op_begin(), E = I->op_end(); Use != E; ++Use) 4062 if (!Set.count(dyn_cast<Instruction>(*Use))) 4063 return false; 4064 return true; 4065 } 4066 4067 bool LoopVectorizationLegality::AddReductionVar(PHINode *Phi, 4068 ReductionKind Kind) { 4069 if (Phi->getNumIncomingValues() != 2) 4070 return false; 4071 4072 // Reduction variables are only found in the loop header block. 4073 if (Phi->getParent() != TheLoop->getHeader()) 4074 return false; 4075 4076 // Obtain the reduction start value from the value that comes from the loop 4077 // preheader. 4078 Value *RdxStart = Phi->getIncomingValueForBlock(TheLoop->getLoopPreheader()); 4079 4080 // ExitInstruction is the single value which is used outside the loop. 4081 // We only allow for a single reduction value to be used outside the loop. 4082 // This includes users of the reduction, variables (which form a cycle 4083 // which ends in the phi node). 4084 Instruction *ExitInstruction = 0; 4085 // Indicates that we found a reduction operation in our scan. 4086 bool FoundReduxOp = false; 4087 4088 // We start with the PHI node and scan for all of the users of this 4089 // instruction. All users must be instructions that can be used as reduction 4090 // variables (such as ADD). We must have a single out-of-block user. The cycle 4091 // must include the original PHI. 4092 bool FoundStartPHI = false; 4093 4094 // To recognize min/max patterns formed by a icmp select sequence, we store 4095 // the number of instruction we saw from the recognized min/max pattern, 4096 // to make sure we only see exactly the two instructions. 4097 unsigned NumCmpSelectPatternInst = 0; 4098 ReductionInstDesc ReduxDesc(false, 0); 4099 4100 SmallPtrSet<Instruction *, 8> VisitedInsts; 4101 SmallVector<Instruction *, 8> Worklist; 4102 Worklist.push_back(Phi); 4103 VisitedInsts.insert(Phi); 4104 4105 // A value in the reduction can be used: 4106 // - By the reduction: 4107 // - Reduction operation: 4108 // - One use of reduction value (safe). 4109 // - Multiple use of reduction value (not safe). 4110 // - PHI: 4111 // - All uses of the PHI must be the reduction (safe). 4112 // - Otherwise, not safe. 4113 // - By one instruction outside of the loop (safe). 4114 // - By further instructions outside of the loop (not safe). 4115 // - By an instruction that is not part of the reduction (not safe). 4116 // This is either: 4117 // * An instruction type other than PHI or the reduction operation. 4118 // * A PHI in the header other than the initial PHI. 4119 while (!Worklist.empty()) { 4120 Instruction *Cur = Worklist.back(); 4121 Worklist.pop_back(); 4122 4123 // No Users. 4124 // If the instruction has no users then this is a broken chain and can't be 4125 // a reduction variable. 4126 if (Cur->use_empty()) 4127 return false; 4128 4129 bool IsAPhi = isa<PHINode>(Cur); 4130 4131 // A header PHI use other than the original PHI. 4132 if (Cur != Phi && IsAPhi && Cur->getParent() == Phi->getParent()) 4133 return false; 4134 4135 // Reductions of instructions such as Div, and Sub is only possible if the 4136 // LHS is the reduction variable. 4137 if (!Cur->isCommutative() && !IsAPhi && !isa<SelectInst>(Cur) && 4138 !isa<ICmpInst>(Cur) && !isa<FCmpInst>(Cur) && 4139 !VisitedInsts.count(dyn_cast<Instruction>(Cur->getOperand(0)))) 4140 return false; 4141 4142 // Any reduction instruction must be of one of the allowed kinds. 4143 ReduxDesc = isReductionInstr(Cur, Kind, ReduxDesc); 4144 if (!ReduxDesc.IsReduction) 4145 return false; 4146 4147 // A reduction operation must only have one use of the reduction value. 4148 if (!IsAPhi && Kind != RK_IntegerMinMax && Kind != RK_FloatMinMax && 4149 hasMultipleUsesOf(Cur, VisitedInsts)) 4150 return false; 4151 4152 // All inputs to a PHI node must be a reduction value. 4153 if(IsAPhi && Cur != Phi && !areAllUsesIn(Cur, VisitedInsts)) 4154 return false; 4155 4156 if (Kind == RK_IntegerMinMax && (isa<ICmpInst>(Cur) || 4157 isa<SelectInst>(Cur))) 4158 ++NumCmpSelectPatternInst; 4159 if (Kind == RK_FloatMinMax && (isa<FCmpInst>(Cur) || 4160 isa<SelectInst>(Cur))) 4161 ++NumCmpSelectPatternInst; 4162 4163 // Check whether we found a reduction operator. 4164 FoundReduxOp |= !IsAPhi; 4165 4166 // Process users of current instruction. Push non-PHI nodes after PHI nodes 4167 // onto the stack. This way we are going to have seen all inputs to PHI 4168 // nodes once we get to them. 4169 SmallVector<Instruction *, 8> NonPHIs; 4170 SmallVector<Instruction *, 8> PHIs; 4171 for (Value::use_iterator UI = Cur->use_begin(), E = Cur->use_end(); UI != E; 4172 ++UI) { 4173 Instruction *Usr = cast<Instruction>(*UI); 4174 4175 // Check if we found the exit user. 4176 BasicBlock *Parent = Usr->getParent(); 4177 if (!TheLoop->contains(Parent)) { 4178 // Exit if you find multiple outside users or if the header phi node is 4179 // being used. In this case the user uses the value of the previous 4180 // iteration, in which case we would loose "VF-1" iterations of the 4181 // reduction operation if we vectorize. 4182 if (ExitInstruction != 0 || Cur == Phi) 4183 return false; 4184 4185 // The instruction used by an outside user must be the last instruction 4186 // before we feed back to the reduction phi. Otherwise, we loose VF-1 4187 // operations on the value. 4188 if (std::find(Phi->op_begin(), Phi->op_end(), Cur) == Phi->op_end()) 4189 return false; 4190 4191 ExitInstruction = Cur; 4192 continue; 4193 } 4194 4195 // Process instructions only once (termination). 4196 if (VisitedInsts.insert(Usr)) { 4197 if (isa<PHINode>(Usr)) 4198 PHIs.push_back(Usr); 4199 else 4200 NonPHIs.push_back(Usr); 4201 } 4202 // Remember that we completed the cycle. 4203 if (Usr == Phi) 4204 FoundStartPHI = true; 4205 } 4206 Worklist.append(PHIs.begin(), PHIs.end()); 4207 Worklist.append(NonPHIs.begin(), NonPHIs.end()); 4208 } 4209 4210 // This means we have seen one but not the other instruction of the 4211 // pattern or more than just a select and cmp. 4212 if ((Kind == RK_IntegerMinMax || Kind == RK_FloatMinMax) && 4213 NumCmpSelectPatternInst != 2) 4214 return false; 4215 4216 if (!FoundStartPHI || !FoundReduxOp || !ExitInstruction) 4217 return false; 4218 4219 // We found a reduction var if we have reached the original phi node and we 4220 // only have a single instruction with out-of-loop users. 4221 4222 // This instruction is allowed to have out-of-loop users. 4223 AllowedExit.insert(ExitInstruction); 4224 4225 // Save the description of this reduction variable. 4226 ReductionDescriptor RD(RdxStart, ExitInstruction, Kind, 4227 ReduxDesc.MinMaxKind); 4228 Reductions[Phi] = RD; 4229 // We've ended the cycle. This is a reduction variable if we have an 4230 // outside user and it has a binary op. 4231 4232 return true; 4233 } 4234 4235 /// Returns true if the instruction is a Select(ICmp(X, Y), X, Y) instruction 4236 /// pattern corresponding to a min(X, Y) or max(X, Y). 4237 LoopVectorizationLegality::ReductionInstDesc 4238 LoopVectorizationLegality::isMinMaxSelectCmpPattern(Instruction *I, 4239 ReductionInstDesc &Prev) { 4240 4241 assert((isa<ICmpInst>(I) || isa<FCmpInst>(I) || isa<SelectInst>(I)) && 4242 "Expect a select instruction"); 4243 Instruction *Cmp = 0; 4244 SelectInst *Select = 0; 4245 4246 // We must handle the select(cmp()) as a single instruction. Advance to the 4247 // select. 4248 if ((Cmp = dyn_cast<ICmpInst>(I)) || (Cmp = dyn_cast<FCmpInst>(I))) { 4249 if (!Cmp->hasOneUse() || !(Select = dyn_cast<SelectInst>(*I->use_begin()))) 4250 return ReductionInstDesc(false, I); 4251 return ReductionInstDesc(Select, Prev.MinMaxKind); 4252 } 4253 4254 // Only handle single use cases for now. 4255 if (!(Select = dyn_cast<SelectInst>(I))) 4256 return ReductionInstDesc(false, I); 4257 if (!(Cmp = dyn_cast<ICmpInst>(I->getOperand(0))) && 4258 !(Cmp = dyn_cast<FCmpInst>(I->getOperand(0)))) 4259 return ReductionInstDesc(false, I); 4260 if (!Cmp->hasOneUse()) 4261 return ReductionInstDesc(false, I); 4262 4263 Value *CmpLeft; 4264 Value *CmpRight; 4265 4266 // Look for a min/max pattern. 4267 if (m_UMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select)) 4268 return ReductionInstDesc(Select, MRK_UIntMin); 4269 else if (m_UMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select)) 4270 return ReductionInstDesc(Select, MRK_UIntMax); 4271 else if (m_SMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select)) 4272 return ReductionInstDesc(Select, MRK_SIntMax); 4273 else if (m_SMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select)) 4274 return ReductionInstDesc(Select, MRK_SIntMin); 4275 else if (m_OrdFMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select)) 4276 return ReductionInstDesc(Select, MRK_FloatMin); 4277 else if (m_OrdFMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select)) 4278 return ReductionInstDesc(Select, MRK_FloatMax); 4279 else if (m_UnordFMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select)) 4280 return ReductionInstDesc(Select, MRK_FloatMin); 4281 else if (m_UnordFMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select)) 4282 return ReductionInstDesc(Select, MRK_FloatMax); 4283 4284 return ReductionInstDesc(false, I); 4285 } 4286 4287 LoopVectorizationLegality::ReductionInstDesc 4288 LoopVectorizationLegality::isReductionInstr(Instruction *I, 4289 ReductionKind Kind, 4290 ReductionInstDesc &Prev) { 4291 bool FP = I->getType()->isFloatingPointTy(); 4292 bool FastMath = (FP && I->isCommutative() && I->isAssociative()); 4293 switch (I->getOpcode()) { 4294 default: 4295 return ReductionInstDesc(false, I); 4296 case Instruction::PHI: 4297 if (FP && (Kind != RK_FloatMult && Kind != RK_FloatAdd && 4298 Kind != RK_FloatMinMax)) 4299 return ReductionInstDesc(false, I); 4300 return ReductionInstDesc(I, Prev.MinMaxKind); 4301 case Instruction::Sub: 4302 case Instruction::Add: 4303 return ReductionInstDesc(Kind == RK_IntegerAdd, I); 4304 case Instruction::Mul: 4305 return ReductionInstDesc(Kind == RK_IntegerMult, I); 4306 case Instruction::And: 4307 return ReductionInstDesc(Kind == RK_IntegerAnd, I); 4308 case Instruction::Or: 4309 return ReductionInstDesc(Kind == RK_IntegerOr, I); 4310 case Instruction::Xor: 4311 return ReductionInstDesc(Kind == RK_IntegerXor, I); 4312 case Instruction::FMul: 4313 return ReductionInstDesc(Kind == RK_FloatMult && FastMath, I); 4314 case Instruction::FAdd: 4315 return ReductionInstDesc(Kind == RK_FloatAdd && FastMath, I); 4316 case Instruction::FCmp: 4317 case Instruction::ICmp: 4318 case Instruction::Select: 4319 if (Kind != RK_IntegerMinMax && 4320 (!HasFunNoNaNAttr || Kind != RK_FloatMinMax)) 4321 return ReductionInstDesc(false, I); 4322 return isMinMaxSelectCmpPattern(I, Prev); 4323 } 4324 } 4325 4326 LoopVectorizationLegality::InductionKind 4327 LoopVectorizationLegality::isInductionVariable(PHINode *Phi) { 4328 Type *PhiTy = Phi->getType(); 4329 // We only handle integer and pointer inductions variables. 4330 if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy()) 4331 return IK_NoInduction; 4332 4333 // Check that the PHI is consecutive. 4334 const SCEV *PhiScev = SE->getSCEV(Phi); 4335 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev); 4336 if (!AR) { 4337 DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n"); 4338 return IK_NoInduction; 4339 } 4340 const SCEV *Step = AR->getStepRecurrence(*SE); 4341 4342 // Integer inductions need to have a stride of one. 4343 if (PhiTy->isIntegerTy()) { 4344 if (Step->isOne()) 4345 return IK_IntInduction; 4346 if (Step->isAllOnesValue()) 4347 return IK_ReverseIntInduction; 4348 return IK_NoInduction; 4349 } 4350 4351 // Calculate the pointer stride and check if it is consecutive. 4352 const SCEVConstant *C = dyn_cast<SCEVConstant>(Step); 4353 if (!C) 4354 return IK_NoInduction; 4355 4356 assert(PhiTy->isPointerTy() && "The PHI must be a pointer"); 4357 uint64_t Size = DL->getTypeAllocSize(PhiTy->getPointerElementType()); 4358 if (C->getValue()->equalsInt(Size)) 4359 return IK_PtrInduction; 4360 else if (C->getValue()->equalsInt(0 - Size)) 4361 return IK_ReversePtrInduction; 4362 4363 return IK_NoInduction; 4364 } 4365 4366 bool LoopVectorizationLegality::isInductionVariable(const Value *V) { 4367 Value *In0 = const_cast<Value*>(V); 4368 PHINode *PN = dyn_cast_or_null<PHINode>(In0); 4369 if (!PN) 4370 return false; 4371 4372 return Inductions.count(PN); 4373 } 4374 4375 bool LoopVectorizationLegality::blockNeedsPredication(BasicBlock *BB) { 4376 assert(TheLoop->contains(BB) && "Unknown block used"); 4377 4378 // Blocks that do not dominate the latch need predication. 4379 BasicBlock* Latch = TheLoop->getLoopLatch(); 4380 return !DT->dominates(BB, Latch); 4381 } 4382 4383 bool LoopVectorizationLegality::blockCanBePredicated(BasicBlock *BB, 4384 SmallPtrSet<Value *, 8>& SafePtrs) { 4385 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) { 4386 // We might be able to hoist the load. 4387 if (it->mayReadFromMemory()) { 4388 LoadInst *LI = dyn_cast<LoadInst>(it); 4389 if (!LI || !SafePtrs.count(LI->getPointerOperand())) 4390 return false; 4391 } 4392 4393 // We don't predicate stores at the moment. 4394 if (it->mayWriteToMemory() || it->mayThrow()) 4395 return false; 4396 4397 // The instructions below can trap. 4398 switch (it->getOpcode()) { 4399 default: continue; 4400 case Instruction::UDiv: 4401 case Instruction::SDiv: 4402 case Instruction::URem: 4403 case Instruction::SRem: 4404 return false; 4405 } 4406 } 4407 4408 return true; 4409 } 4410 4411 LoopVectorizationCostModel::VectorizationFactor 4412 LoopVectorizationCostModel::selectVectorizationFactor(bool OptForSize, 4413 unsigned UserVF) { 4414 // Width 1 means no vectorize 4415 VectorizationFactor Factor = { 1U, 0U }; 4416 if (OptForSize && Legal->getRuntimePointerCheck()->Need) { 4417 DEBUG(dbgs() << "LV: Aborting. Runtime ptr check is required in Os.\n"); 4418 return Factor; 4419 } 4420 4421 // Find the trip count. 4422 unsigned TC = SE->getSmallConstantTripCount(TheLoop, TheLoop->getLoopLatch()); 4423 DEBUG(dbgs() << "LV: Found trip count: " << TC << '\n'); 4424 4425 unsigned WidestType = getWidestType(); 4426 unsigned WidestRegister = TTI.getRegisterBitWidth(true); 4427 unsigned MaxSafeDepDist = -1U; 4428 if (Legal->getMaxSafeDepDistBytes() != -1U) 4429 MaxSafeDepDist = Legal->getMaxSafeDepDistBytes() * 8; 4430 WidestRegister = ((WidestRegister < MaxSafeDepDist) ? 4431 WidestRegister : MaxSafeDepDist); 4432 unsigned MaxVectorSize = WidestRegister / WidestType; 4433 DEBUG(dbgs() << "LV: The Widest type: " << WidestType << " bits.\n"); 4434 DEBUG(dbgs() << "LV: The Widest register is: " 4435 << WidestRegister << " bits.\n"); 4436 4437 if (MaxVectorSize == 0) { 4438 DEBUG(dbgs() << "LV: The target has no vector registers.\n"); 4439 MaxVectorSize = 1; 4440 } 4441 4442 assert(MaxVectorSize <= 32 && "Did not expect to pack so many elements" 4443 " into one vector!"); 4444 4445 unsigned VF = MaxVectorSize; 4446 4447 // If we optimize the program for size, avoid creating the tail loop. 4448 if (OptForSize) { 4449 // If we are unable to calculate the trip count then don't try to vectorize. 4450 if (TC < 2) { 4451 DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n"); 4452 return Factor; 4453 } 4454 4455 // Find the maximum SIMD width that can fit within the trip count. 4456 VF = TC % MaxVectorSize; 4457 4458 if (VF == 0) 4459 VF = MaxVectorSize; 4460 4461 // If the trip count that we found modulo the vectorization factor is not 4462 // zero then we require a tail. 4463 if (VF < 2) { 4464 DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n"); 4465 return Factor; 4466 } 4467 } 4468 4469 if (UserVF != 0) { 4470 assert(isPowerOf2_32(UserVF) && "VF needs to be a power of two"); 4471 DEBUG(dbgs() << "LV: Using user VF " << UserVF << ".\n"); 4472 4473 Factor.Width = UserVF; 4474 return Factor; 4475 } 4476 4477 float Cost = expectedCost(1); 4478 unsigned Width = 1; 4479 DEBUG(dbgs() << "LV: Scalar loop costs: " << (int)Cost << ".\n"); 4480 for (unsigned i=2; i <= VF; i*=2) { 4481 // Notice that the vector loop needs to be executed less times, so 4482 // we need to divide the cost of the vector loops by the width of 4483 // the vector elements. 4484 float VectorCost = expectedCost(i) / (float)i; 4485 DEBUG(dbgs() << "LV: Vector loop of width " << i << " costs: " << 4486 (int)VectorCost << ".\n"); 4487 if (VectorCost < Cost) { 4488 Cost = VectorCost; 4489 Width = i; 4490 } 4491 } 4492 4493 DEBUG(dbgs() << "LV: Selecting VF = : "<< Width << ".\n"); 4494 Factor.Width = Width; 4495 Factor.Cost = Width * Cost; 4496 return Factor; 4497 } 4498 4499 unsigned LoopVectorizationCostModel::getWidestType() { 4500 unsigned MaxWidth = 8; 4501 4502 // For each block. 4503 for (Loop::block_iterator bb = TheLoop->block_begin(), 4504 be = TheLoop->block_end(); bb != be; ++bb) { 4505 BasicBlock *BB = *bb; 4506 4507 // For each instruction in the loop. 4508 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) { 4509 Type *T = it->getType(); 4510 4511 // Only examine Loads, Stores and PHINodes. 4512 if (!isa<LoadInst>(it) && !isa<StoreInst>(it) && !isa<PHINode>(it)) 4513 continue; 4514 4515 // Examine PHI nodes that are reduction variables. 4516 if (PHINode *PN = dyn_cast<PHINode>(it)) 4517 if (!Legal->getReductionVars()->count(PN)) 4518 continue; 4519 4520 // Examine the stored values. 4521 if (StoreInst *ST = dyn_cast<StoreInst>(it)) 4522 T = ST->getValueOperand()->getType(); 4523 4524 // Ignore loaded pointer types and stored pointer types that are not 4525 // consecutive. However, we do want to take consecutive stores/loads of 4526 // pointer vectors into account. 4527 if (T->isPointerTy() && !isConsecutiveLoadOrStore(it)) 4528 continue; 4529 4530 MaxWidth = std::max(MaxWidth, 4531 (unsigned)DL->getTypeSizeInBits(T->getScalarType())); 4532 } 4533 } 4534 4535 return MaxWidth; 4536 } 4537 4538 unsigned 4539 LoopVectorizationCostModel::selectUnrollFactor(bool OptForSize, 4540 unsigned UserUF, 4541 unsigned VF, 4542 unsigned LoopCost) { 4543 4544 // -- The unroll heuristics -- 4545 // We unroll the loop in order to expose ILP and reduce the loop overhead. 4546 // There are many micro-architectural considerations that we can't predict 4547 // at this level. For example frontend pressure (on decode or fetch) due to 4548 // code size, or the number and capabilities of the execution ports. 4549 // 4550 // We use the following heuristics to select the unroll factor: 4551 // 1. If the code has reductions the we unroll in order to break the cross 4552 // iteration dependency. 4553 // 2. If the loop is really small then we unroll in order to reduce the loop 4554 // overhead. 4555 // 3. We don't unroll if we think that we will spill registers to memory due 4556 // to the increased register pressure. 4557 4558 // Use the user preference, unless 'auto' is selected. 4559 if (UserUF != 0) 4560 return UserUF; 4561 4562 // When we optimize for size we don't unroll. 4563 if (OptForSize) 4564 return 1; 4565 4566 // We used the distance for the unroll factor. 4567 if (Legal->getMaxSafeDepDistBytes() != -1U) 4568 return 1; 4569 4570 // Do not unroll loops with a relatively small trip count. 4571 unsigned TC = SE->getSmallConstantTripCount(TheLoop, 4572 TheLoop->getLoopLatch()); 4573 if (TC > 1 && TC < TinyTripCountUnrollThreshold) 4574 return 1; 4575 4576 unsigned TargetVectorRegisters = TTI.getNumberOfRegisters(true); 4577 DEBUG(dbgs() << "LV: The target has " << TargetVectorRegisters << 4578 " vector registers\n"); 4579 4580 LoopVectorizationCostModel::RegisterUsage R = calculateRegisterUsage(); 4581 // We divide by these constants so assume that we have at least one 4582 // instruction that uses at least one register. 4583 R.MaxLocalUsers = std::max(R.MaxLocalUsers, 1U); 4584 R.NumInstructions = std::max(R.NumInstructions, 1U); 4585 4586 // We calculate the unroll factor using the following formula. 4587 // Subtract the number of loop invariants from the number of available 4588 // registers. These registers are used by all of the unrolled instances. 4589 // Next, divide the remaining registers by the number of registers that is 4590 // required by the loop, in order to estimate how many parallel instances 4591 // fit without causing spills. 4592 unsigned UF = (TargetVectorRegisters - R.LoopInvariantRegs) / R.MaxLocalUsers; 4593 4594 // Clamp the unroll factor ranges to reasonable factors. 4595 unsigned MaxUnrollSize = TTI.getMaximumUnrollFactor(); 4596 4597 // If we did not calculate the cost for VF (because the user selected the VF) 4598 // then we calculate the cost of VF here. 4599 if (LoopCost == 0) 4600 LoopCost = expectedCost(VF); 4601 4602 // Clamp the calculated UF to be between the 1 and the max unroll factor 4603 // that the target allows. 4604 if (UF > MaxUnrollSize) 4605 UF = MaxUnrollSize; 4606 else if (UF < 1) 4607 UF = 1; 4608 4609 bool HasReductions = Legal->getReductionVars()->size(); 4610 4611 // Decide if we want to unroll if we decided that it is legal to vectorize 4612 // but not profitable. 4613 if (VF == 1) { 4614 if (TheLoop->getNumBlocks() > 1 || !HasReductions || 4615 LoopCost > SmallLoopCost) 4616 return 1; 4617 4618 return UF; 4619 } 4620 4621 if (HasReductions) { 4622 DEBUG(dbgs() << "LV: Unrolling because of reductions.\n"); 4623 return UF; 4624 } 4625 4626 // We want to unroll tiny loops in order to reduce the loop overhead. 4627 // We assume that the cost overhead is 1 and we use the cost model 4628 // to estimate the cost of the loop and unroll until the cost of the 4629 // loop overhead is about 5% of the cost of the loop. 4630 DEBUG(dbgs() << "LV: Loop cost is " << LoopCost << '\n'); 4631 if (LoopCost < SmallLoopCost) { 4632 DEBUG(dbgs() << "LV: Unrolling to reduce branch cost.\n"); 4633 unsigned NewUF = SmallLoopCost / (LoopCost + 1); 4634 return std::min(NewUF, UF); 4635 } 4636 4637 DEBUG(dbgs() << "LV: Not Unrolling.\n"); 4638 return 1; 4639 } 4640 4641 LoopVectorizationCostModel::RegisterUsage 4642 LoopVectorizationCostModel::calculateRegisterUsage() { 4643 // This function calculates the register usage by measuring the highest number 4644 // of values that are alive at a single location. Obviously, this is a very 4645 // rough estimation. We scan the loop in a topological order in order and 4646 // assign a number to each instruction. We use RPO to ensure that defs are 4647 // met before their users. We assume that each instruction that has in-loop 4648 // users starts an interval. We record every time that an in-loop value is 4649 // used, so we have a list of the first and last occurrences of each 4650 // instruction. Next, we transpose this data structure into a multi map that 4651 // holds the list of intervals that *end* at a specific location. This multi 4652 // map allows us to perform a linear search. We scan the instructions linearly 4653 // and record each time that a new interval starts, by placing it in a set. 4654 // If we find this value in the multi-map then we remove it from the set. 4655 // The max register usage is the maximum size of the set. 4656 // We also search for instructions that are defined outside the loop, but are 4657 // used inside the loop. We need this number separately from the max-interval 4658 // usage number because when we unroll, loop-invariant values do not take 4659 // more register. 4660 LoopBlocksDFS DFS(TheLoop); 4661 DFS.perform(LI); 4662 4663 RegisterUsage R; 4664 R.NumInstructions = 0; 4665 4666 // Each 'key' in the map opens a new interval. The values 4667 // of the map are the index of the 'last seen' usage of the 4668 // instruction that is the key. 4669 typedef DenseMap<Instruction*, unsigned> IntervalMap; 4670 // Maps instruction to its index. 4671 DenseMap<unsigned, Instruction*> IdxToInstr; 4672 // Marks the end of each interval. 4673 IntervalMap EndPoint; 4674 // Saves the list of instruction indices that are used in the loop. 4675 SmallSet<Instruction*, 8> Ends; 4676 // Saves the list of values that are used in the loop but are 4677 // defined outside the loop, such as arguments and constants. 4678 SmallPtrSet<Value*, 8> LoopInvariants; 4679 4680 unsigned Index = 0; 4681 for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(), 4682 be = DFS.endRPO(); bb != be; ++bb) { 4683 R.NumInstructions += (*bb)->size(); 4684 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e; 4685 ++it) { 4686 Instruction *I = it; 4687 IdxToInstr[Index++] = I; 4688 4689 // Save the end location of each USE. 4690 for (unsigned i = 0; i < I->getNumOperands(); ++i) { 4691 Value *U = I->getOperand(i); 4692 Instruction *Instr = dyn_cast<Instruction>(U); 4693 4694 // Ignore non-instruction values such as arguments, constants, etc. 4695 if (!Instr) continue; 4696 4697 // If this instruction is outside the loop then record it and continue. 4698 if (!TheLoop->contains(Instr)) { 4699 LoopInvariants.insert(Instr); 4700 continue; 4701 } 4702 4703 // Overwrite previous end points. 4704 EndPoint[Instr] = Index; 4705 Ends.insert(Instr); 4706 } 4707 } 4708 } 4709 4710 // Saves the list of intervals that end with the index in 'key'. 4711 typedef SmallVector<Instruction*, 2> InstrList; 4712 DenseMap<unsigned, InstrList> TransposeEnds; 4713 4714 // Transpose the EndPoints to a list of values that end at each index. 4715 for (IntervalMap::iterator it = EndPoint.begin(), e = EndPoint.end(); 4716 it != e; ++it) 4717 TransposeEnds[it->second].push_back(it->first); 4718 4719 SmallSet<Instruction*, 8> OpenIntervals; 4720 unsigned MaxUsage = 0; 4721 4722 4723 DEBUG(dbgs() << "LV(REG): Calculating max register usage:\n"); 4724 for (unsigned int i = 0; i < Index; ++i) { 4725 Instruction *I = IdxToInstr[i]; 4726 // Ignore instructions that are never used within the loop. 4727 if (!Ends.count(I)) continue; 4728 4729 // Remove all of the instructions that end at this location. 4730 InstrList &List = TransposeEnds[i]; 4731 for (unsigned int j=0, e = List.size(); j < e; ++j) 4732 OpenIntervals.erase(List[j]); 4733 4734 // Count the number of live interals. 4735 MaxUsage = std::max(MaxUsage, OpenIntervals.size()); 4736 4737 DEBUG(dbgs() << "LV(REG): At #" << i << " Interval # " << 4738 OpenIntervals.size() << '\n'); 4739 4740 // Add the current instruction to the list of open intervals. 4741 OpenIntervals.insert(I); 4742 } 4743 4744 unsigned Invariant = LoopInvariants.size(); 4745 DEBUG(dbgs() << "LV(REG): Found max usage: " << MaxUsage << '\n'); 4746 DEBUG(dbgs() << "LV(REG): Found invariant usage: " << Invariant << '\n'); 4747 DEBUG(dbgs() << "LV(REG): LoopSize: " << R.NumInstructions << '\n'); 4748 4749 R.LoopInvariantRegs = Invariant; 4750 R.MaxLocalUsers = MaxUsage; 4751 return R; 4752 } 4753 4754 unsigned LoopVectorizationCostModel::expectedCost(unsigned VF) { 4755 unsigned Cost = 0; 4756 4757 // For each block. 4758 for (Loop::block_iterator bb = TheLoop->block_begin(), 4759 be = TheLoop->block_end(); bb != be; ++bb) { 4760 unsigned BlockCost = 0; 4761 BasicBlock *BB = *bb; 4762 4763 // For each instruction in the old loop. 4764 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) { 4765 // Skip dbg intrinsics. 4766 if (isa<DbgInfoIntrinsic>(it)) 4767 continue; 4768 4769 unsigned C = getInstructionCost(it, VF); 4770 BlockCost += C; 4771 DEBUG(dbgs() << "LV: Found an estimated cost of " << C << " for VF " << 4772 VF << " For instruction: " << *it << '\n'); 4773 } 4774 4775 // We assume that if-converted blocks have a 50% chance of being executed. 4776 // When the code is scalar then some of the blocks are avoided due to CF. 4777 // When the code is vectorized we execute all code paths. 4778 if (VF == 1 && Legal->blockNeedsPredication(*bb)) 4779 BlockCost /= 2; 4780 4781 Cost += BlockCost; 4782 } 4783 4784 return Cost; 4785 } 4786 4787 /// \brief Check whether the address computation for a non-consecutive memory 4788 /// access looks like an unlikely candidate for being merged into the indexing 4789 /// mode. 4790 /// 4791 /// We look for a GEP which has one index that is an induction variable and all 4792 /// other indices are loop invariant. If the stride of this access is also 4793 /// within a small bound we decide that this address computation can likely be 4794 /// merged into the addressing mode. 4795 /// In all other cases, we identify the address computation as complex. 4796 static bool isLikelyComplexAddressComputation(Value *Ptr, 4797 LoopVectorizationLegality *Legal, 4798 ScalarEvolution *SE, 4799 const Loop *TheLoop) { 4800 GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr); 4801 if (!Gep) 4802 return true; 4803 4804 // We are looking for a gep with all loop invariant indices except for one 4805 // which should be an induction variable. 4806 unsigned NumOperands = Gep->getNumOperands(); 4807 for (unsigned i = 1; i < NumOperands; ++i) { 4808 Value *Opd = Gep->getOperand(i); 4809 if (!SE->isLoopInvariant(SE->getSCEV(Opd), TheLoop) && 4810 !Legal->isInductionVariable(Opd)) 4811 return true; 4812 } 4813 4814 // Now we know we have a GEP ptr, %inv, %ind, %inv. Make sure that the step 4815 // can likely be merged into the address computation. 4816 unsigned MaxMergeDistance = 64; 4817 4818 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Ptr)); 4819 if (!AddRec) 4820 return true; 4821 4822 // Check the step is constant. 4823 const SCEV *Step = AddRec->getStepRecurrence(*SE); 4824 // Calculate the pointer stride and check if it is consecutive. 4825 const SCEVConstant *C = dyn_cast<SCEVConstant>(Step); 4826 if (!C) 4827 return true; 4828 4829 const APInt &APStepVal = C->getValue()->getValue(); 4830 4831 // Huge step value - give up. 4832 if (APStepVal.getBitWidth() > 64) 4833 return true; 4834 4835 int64_t StepVal = APStepVal.getSExtValue(); 4836 4837 return StepVal > MaxMergeDistance; 4838 } 4839 4840 unsigned 4841 LoopVectorizationCostModel::getInstructionCost(Instruction *I, unsigned VF) { 4842 // If we know that this instruction will remain uniform, check the cost of 4843 // the scalar version. 4844 if (Legal->isUniformAfterVectorization(I)) 4845 VF = 1; 4846 4847 Type *RetTy = I->getType(); 4848 Type *VectorTy = ToVectorTy(RetTy, VF); 4849 4850 // TODO: We need to estimate the cost of intrinsic calls. 4851 switch (I->getOpcode()) { 4852 case Instruction::GetElementPtr: 4853 // We mark this instruction as zero-cost because the cost of GEPs in 4854 // vectorized code depends on whether the corresponding memory instruction 4855 // is scalarized or not. Therefore, we handle GEPs with the memory 4856 // instruction cost. 4857 return 0; 4858 case Instruction::Br: { 4859 return TTI.getCFInstrCost(I->getOpcode()); 4860 } 4861 case Instruction::PHI: 4862 //TODO: IF-converted IFs become selects. 4863 return 0; 4864 case Instruction::Add: 4865 case Instruction::FAdd: 4866 case Instruction::Sub: 4867 case Instruction::FSub: 4868 case Instruction::Mul: 4869 case Instruction::FMul: 4870 case Instruction::UDiv: 4871 case Instruction::SDiv: 4872 case Instruction::FDiv: 4873 case Instruction::URem: 4874 case Instruction::SRem: 4875 case Instruction::FRem: 4876 case Instruction::Shl: 4877 case Instruction::LShr: 4878 case Instruction::AShr: 4879 case Instruction::And: 4880 case Instruction::Or: 4881 case Instruction::Xor: { 4882 // Certain instructions can be cheaper to vectorize if they have a constant 4883 // second vector operand. One example of this are shifts on x86. 4884 TargetTransformInfo::OperandValueKind Op1VK = 4885 TargetTransformInfo::OK_AnyValue; 4886 TargetTransformInfo::OperandValueKind Op2VK = 4887 TargetTransformInfo::OK_AnyValue; 4888 4889 if (isa<ConstantInt>(I->getOperand(1))) 4890 Op2VK = TargetTransformInfo::OK_UniformConstantValue; 4891 4892 return TTI.getArithmeticInstrCost(I->getOpcode(), VectorTy, Op1VK, Op2VK); 4893 } 4894 case Instruction::Select: { 4895 SelectInst *SI = cast<SelectInst>(I); 4896 const SCEV *CondSCEV = SE->getSCEV(SI->getCondition()); 4897 bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop)); 4898 Type *CondTy = SI->getCondition()->getType(); 4899 if (!ScalarCond) 4900 CondTy = VectorType::get(CondTy, VF); 4901 4902 return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, CondTy); 4903 } 4904 case Instruction::ICmp: 4905 case Instruction::FCmp: { 4906 Type *ValTy = I->getOperand(0)->getType(); 4907 VectorTy = ToVectorTy(ValTy, VF); 4908 return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy); 4909 } 4910 case Instruction::Store: 4911 case Instruction::Load: { 4912 StoreInst *SI = dyn_cast<StoreInst>(I); 4913 LoadInst *LI = dyn_cast<LoadInst>(I); 4914 Type *ValTy = (SI ? SI->getValueOperand()->getType() : 4915 LI->getType()); 4916 VectorTy = ToVectorTy(ValTy, VF); 4917 4918 unsigned Alignment = SI ? SI->getAlignment() : LI->getAlignment(); 4919 unsigned AS = SI ? SI->getPointerAddressSpace() : 4920 LI->getPointerAddressSpace(); 4921 Value *Ptr = SI ? SI->getPointerOperand() : LI->getPointerOperand(); 4922 // We add the cost of address computation here instead of with the gep 4923 // instruction because only here we know whether the operation is 4924 // scalarized. 4925 if (VF == 1) 4926 return TTI.getAddressComputationCost(VectorTy) + 4927 TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS); 4928 4929 // Scalarized loads/stores. 4930 int ConsecutiveStride = Legal->isConsecutivePtr(Ptr); 4931 bool Reverse = ConsecutiveStride < 0; 4932 unsigned ScalarAllocatedSize = DL->getTypeAllocSize(ValTy); 4933 unsigned VectorElementSize = DL->getTypeStoreSize(VectorTy)/VF; 4934 if (!ConsecutiveStride || ScalarAllocatedSize != VectorElementSize) { 4935 bool IsComplexComputation = 4936 isLikelyComplexAddressComputation(Ptr, Legal, SE, TheLoop); 4937 unsigned Cost = 0; 4938 // The cost of extracting from the value vector and pointer vector. 4939 Type *PtrTy = ToVectorTy(Ptr->getType(), VF); 4940 for (unsigned i = 0; i < VF; ++i) { 4941 // The cost of extracting the pointer operand. 4942 Cost += TTI.getVectorInstrCost(Instruction::ExtractElement, PtrTy, i); 4943 // In case of STORE, the cost of ExtractElement from the vector. 4944 // In case of LOAD, the cost of InsertElement into the returned 4945 // vector. 4946 Cost += TTI.getVectorInstrCost(SI ? Instruction::ExtractElement : 4947 Instruction::InsertElement, 4948 VectorTy, i); 4949 } 4950 4951 // The cost of the scalar loads/stores. 4952 Cost += VF * TTI.getAddressComputationCost(PtrTy, IsComplexComputation); 4953 Cost += VF * TTI.getMemoryOpCost(I->getOpcode(), ValTy->getScalarType(), 4954 Alignment, AS); 4955 return Cost; 4956 } 4957 4958 // Wide load/stores. 4959 unsigned Cost = TTI.getAddressComputationCost(VectorTy); 4960 Cost += TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS); 4961 4962 if (Reverse) 4963 Cost += TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, 4964 VectorTy, 0); 4965 return Cost; 4966 } 4967 case Instruction::ZExt: 4968 case Instruction::SExt: 4969 case Instruction::FPToUI: 4970 case Instruction::FPToSI: 4971 case Instruction::FPExt: 4972 case Instruction::PtrToInt: 4973 case Instruction::IntToPtr: 4974 case Instruction::SIToFP: 4975 case Instruction::UIToFP: 4976 case Instruction::Trunc: 4977 case Instruction::FPTrunc: 4978 case Instruction::BitCast: { 4979 // We optimize the truncation of induction variable. 4980 // The cost of these is the same as the scalar operation. 4981 if (I->getOpcode() == Instruction::Trunc && 4982 Legal->isInductionVariable(I->getOperand(0))) 4983 return TTI.getCastInstrCost(I->getOpcode(), I->getType(), 4984 I->getOperand(0)->getType()); 4985 4986 Type *SrcVecTy = ToVectorTy(I->getOperand(0)->getType(), VF); 4987 return TTI.getCastInstrCost(I->getOpcode(), VectorTy, SrcVecTy); 4988 } 4989 case Instruction::Call: { 4990 CallInst *CI = cast<CallInst>(I); 4991 Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI); 4992 assert(ID && "Not an intrinsic call!"); 4993 Type *RetTy = ToVectorTy(CI->getType(), VF); 4994 SmallVector<Type*, 4> Tys; 4995 for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i) 4996 Tys.push_back(ToVectorTy(CI->getArgOperand(i)->getType(), VF)); 4997 return TTI.getIntrinsicInstrCost(ID, RetTy, Tys); 4998 } 4999 default: { 5000 // We are scalarizing the instruction. Return the cost of the scalar 5001 // instruction, plus the cost of insert and extract into vector 5002 // elements, times the vector width. 5003 unsigned Cost = 0; 5004 5005 if (!RetTy->isVoidTy() && VF != 1) { 5006 unsigned InsCost = TTI.getVectorInstrCost(Instruction::InsertElement, 5007 VectorTy); 5008 unsigned ExtCost = TTI.getVectorInstrCost(Instruction::ExtractElement, 5009 VectorTy); 5010 5011 // The cost of inserting the results plus extracting each one of the 5012 // operands. 5013 Cost += VF * (InsCost + ExtCost * I->getNumOperands()); 5014 } 5015 5016 // The cost of executing VF copies of the scalar instruction. This opcode 5017 // is unknown. Assume that it is the same as 'mul'. 5018 Cost += VF * TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy); 5019 return Cost; 5020 } 5021 }// end of switch. 5022 } 5023 5024 Type* LoopVectorizationCostModel::ToVectorTy(Type *Scalar, unsigned VF) { 5025 if (Scalar->isVoidTy() || VF == 1) 5026 return Scalar; 5027 return VectorType::get(Scalar, VF); 5028 } 5029 5030 char LoopVectorize::ID = 0; 5031 static const char lv_name[] = "Loop Vectorization"; 5032 INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false) 5033 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo) 5034 INITIALIZE_PASS_DEPENDENCY(DominatorTree) 5035 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution) 5036 INITIALIZE_PASS_DEPENDENCY(LCSSA) 5037 INITIALIZE_PASS_DEPENDENCY(LoopInfo) 5038 INITIALIZE_PASS_DEPENDENCY(LoopSimplify) 5039 INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false) 5040 5041 namespace llvm { 5042 Pass *createLoopVectorizePass(bool NoUnrolling, bool AlwaysVectorize) { 5043 return new LoopVectorize(NoUnrolling, AlwaysVectorize); 5044 } 5045 } 5046 5047 bool LoopVectorizationCostModel::isConsecutiveLoadOrStore(Instruction *Inst) { 5048 // Check for a store. 5049 if (StoreInst *ST = dyn_cast<StoreInst>(Inst)) 5050 return Legal->isConsecutivePtr(ST->getPointerOperand()) != 0; 5051 5052 // Check for a load. 5053 if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) 5054 return Legal->isConsecutivePtr(LI->getPointerOperand()) != 0; 5055 5056 return false; 5057 } 5058 5059 5060 void InnerLoopUnroller::scalarizeInstruction(Instruction *Instr) { 5061 assert(!Instr->getType()->isAggregateType() && "Can't handle vectors"); 5062 // Holds vector parameters or scalars, in case of uniform vals. 5063 SmallVector<VectorParts, 4> Params; 5064 5065 setDebugLocFromInst(Builder, Instr); 5066 5067 // Find all of the vectorized parameters. 5068 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) { 5069 Value *SrcOp = Instr->getOperand(op); 5070 5071 // If we are accessing the old induction variable, use the new one. 5072 if (SrcOp == OldInduction) { 5073 Params.push_back(getVectorValue(SrcOp)); 5074 continue; 5075 } 5076 5077 // Try using previously calculated values. 5078 Instruction *SrcInst = dyn_cast<Instruction>(SrcOp); 5079 5080 // If the src is an instruction that appeared earlier in the basic block 5081 // then it should already be vectorized. 5082 if (SrcInst && OrigLoop->contains(SrcInst)) { 5083 assert(WidenMap.has(SrcInst) && "Source operand is unavailable"); 5084 // The parameter is a vector value from earlier. 5085 Params.push_back(WidenMap.get(SrcInst)); 5086 } else { 5087 // The parameter is a scalar from outside the loop. Maybe even a constant. 5088 VectorParts Scalars; 5089 Scalars.append(UF, SrcOp); 5090 Params.push_back(Scalars); 5091 } 5092 } 5093 5094 assert(Params.size() == Instr->getNumOperands() && 5095 "Invalid number of operands"); 5096 5097 // Does this instruction return a value ? 5098 bool IsVoidRetTy = Instr->getType()->isVoidTy(); 5099 5100 Value *UndefVec = IsVoidRetTy ? 0 : 5101 UndefValue::get(Instr->getType()); 5102 // Create a new entry in the WidenMap and initialize it to Undef or Null. 5103 VectorParts &VecResults = WidenMap.splat(Instr, UndefVec); 5104 5105 // For each vector unroll 'part': 5106 for (unsigned Part = 0; Part < UF; ++Part) { 5107 // For each scalar that we create: 5108 5109 Instruction *Cloned = Instr->clone(); 5110 if (!IsVoidRetTy) 5111 Cloned->setName(Instr->getName() + ".cloned"); 5112 // Replace the operands of the cloned instructions with extracted scalars. 5113 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) { 5114 Value *Op = Params[op][Part]; 5115 Cloned->setOperand(op, Op); 5116 } 5117 5118 // Place the cloned scalar in the new loop. 5119 Builder.Insert(Cloned); 5120 5121 // If the original scalar returns a value we need to place it in a vector 5122 // so that future users will be able to use it. 5123 if (!IsVoidRetTy) 5124 VecResults[Part] = Cloned; 5125 } 5126 } 5127 5128 void 5129 InnerLoopUnroller::vectorizeMemoryInstruction(Instruction *Instr, 5130 LoopVectorizationLegality*) { 5131 return scalarizeInstruction(Instr); 5132 } 5133 5134 Value *InnerLoopUnroller::reverseVector(Value *Vec) { 5135 return Vec; 5136 } 5137 5138 Value *InnerLoopUnroller::getBroadcastInstrs(Value *V) { 5139 return V; 5140 } 5141 5142 Value *InnerLoopUnroller::getConsecutiveVector(Value* Val, int StartIdx, 5143 bool Negate) { 5144 // When unrolling and the VF is 1, we only need to add a simple scalar. 5145 Type *ITy = Val->getType(); 5146 assert(!ITy->isVectorTy() && "Val must be a scalar"); 5147 Constant *C = ConstantInt::get(ITy, StartIdx, Negate); 5148 return Builder.CreateAdd(Val, C, "induction"); 5149 } 5150 5151