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