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