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/LoopVectorize.h" 50 #include "llvm/ADT/DenseMap.h" 51 #include "llvm/ADT/Hashing.h" 52 #include "llvm/ADT/MapVector.h" 53 #include "llvm/ADT/SCCIterator.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/CodeMetrics.h" 61 #include "llvm/Analysis/GlobalsModRef.h" 62 #include "llvm/Analysis/LoopInfo.h" 63 #include "llvm/Analysis/LoopIterator.h" 64 #include "llvm/Analysis/LoopPass.h" 65 #include "llvm/Analysis/ScalarEvolutionExpander.h" 66 #include "llvm/Analysis/ScalarEvolutionExpressions.h" 67 #include "llvm/Analysis/ValueTracking.h" 68 #include "llvm/Analysis/VectorUtils.h" 69 #include "llvm/IR/Constants.h" 70 #include "llvm/IR/DataLayout.h" 71 #include "llvm/IR/DebugInfo.h" 72 #include "llvm/IR/DerivedTypes.h" 73 #include "llvm/IR/DiagnosticInfo.h" 74 #include "llvm/IR/Dominators.h" 75 #include "llvm/IR/Function.h" 76 #include "llvm/IR/IRBuilder.h" 77 #include "llvm/IR/Instructions.h" 78 #include "llvm/IR/IntrinsicInst.h" 79 #include "llvm/IR/LLVMContext.h" 80 #include "llvm/IR/Module.h" 81 #include "llvm/IR/PatternMatch.h" 82 #include "llvm/IR/Type.h" 83 #include "llvm/IR/Value.h" 84 #include "llvm/IR/ValueHandle.h" 85 #include "llvm/IR/Verifier.h" 86 #include "llvm/Pass.h" 87 #include "llvm/Support/BranchProbability.h" 88 #include "llvm/Support/CommandLine.h" 89 #include "llvm/Support/Debug.h" 90 #include "llvm/Support/raw_ostream.h" 91 #include "llvm/Transforms/Scalar.h" 92 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 93 #include "llvm/Transforms/Utils/Local.h" 94 #include "llvm/Transforms/Utils/LoopUtils.h" 95 #include "llvm/Transforms/Utils/LoopVersioning.h" 96 #include "llvm/Transforms/Vectorize.h" 97 #include <algorithm> 98 #include <map> 99 #include <tuple> 100 101 using namespace llvm; 102 using namespace llvm::PatternMatch; 103 104 #define LV_NAME "loop-vectorize" 105 #define DEBUG_TYPE LV_NAME 106 107 STATISTIC(LoopsVectorized, "Number of loops vectorized"); 108 STATISTIC(LoopsAnalyzed, "Number of loops analyzed for vectorization"); 109 110 static cl::opt<bool> 111 EnableIfConversion("enable-if-conversion", cl::init(true), cl::Hidden, 112 cl::desc("Enable if-conversion during vectorization.")); 113 114 /// We don't vectorize loops with a known constant trip count below this number. 115 static cl::opt<unsigned> TinyTripCountVectorThreshold( 116 "vectorizer-min-trip-count", cl::init(16), cl::Hidden, 117 cl::desc("Don't vectorize loops with a constant " 118 "trip count that is smaller than this " 119 "value.")); 120 121 static cl::opt<bool> MaximizeBandwidth( 122 "vectorizer-maximize-bandwidth", cl::init(false), cl::Hidden, 123 cl::desc("Maximize bandwidth when selecting vectorization factor which " 124 "will be determined by the smallest type in loop.")); 125 126 static cl::opt<bool> EnableInterleavedMemAccesses( 127 "enable-interleaved-mem-accesses", cl::init(false), cl::Hidden, 128 cl::desc("Enable vectorization on interleaved memory accesses in a loop")); 129 130 /// Maximum factor for an interleaved memory access. 131 static cl::opt<unsigned> MaxInterleaveGroupFactor( 132 "max-interleave-group-factor", cl::Hidden, 133 cl::desc("Maximum factor for an interleaved access group (default = 8)"), 134 cl::init(8)); 135 136 /// We don't interleave loops with a known constant trip count below this 137 /// number. 138 static const unsigned TinyTripCountInterleaveThreshold = 128; 139 140 static cl::opt<unsigned> ForceTargetNumScalarRegs( 141 "force-target-num-scalar-regs", cl::init(0), cl::Hidden, 142 cl::desc("A flag that overrides the target's number of scalar registers.")); 143 144 static cl::opt<unsigned> ForceTargetNumVectorRegs( 145 "force-target-num-vector-regs", cl::init(0), cl::Hidden, 146 cl::desc("A flag that overrides the target's number of vector registers.")); 147 148 /// Maximum vectorization interleave count. 149 static const unsigned MaxInterleaveFactor = 16; 150 151 static cl::opt<unsigned> ForceTargetMaxScalarInterleaveFactor( 152 "force-target-max-scalar-interleave", cl::init(0), cl::Hidden, 153 cl::desc("A flag that overrides the target's max interleave factor for " 154 "scalar loops.")); 155 156 static cl::opt<unsigned> ForceTargetMaxVectorInterleaveFactor( 157 "force-target-max-vector-interleave", cl::init(0), cl::Hidden, 158 cl::desc("A flag that overrides the target's max interleave factor for " 159 "vectorized loops.")); 160 161 static cl::opt<unsigned> ForceTargetInstructionCost( 162 "force-target-instruction-cost", cl::init(0), cl::Hidden, 163 cl::desc("A flag that overrides the target's expected cost for " 164 "an instruction to a single constant value. Mostly " 165 "useful for getting consistent testing.")); 166 167 static cl::opt<unsigned> SmallLoopCost( 168 "small-loop-cost", cl::init(20), cl::Hidden, 169 cl::desc( 170 "The cost of a loop that is considered 'small' by the interleaver.")); 171 172 static cl::opt<bool> LoopVectorizeWithBlockFrequency( 173 "loop-vectorize-with-block-frequency", cl::init(false), cl::Hidden, 174 cl::desc("Enable the use of the block frequency analysis to access PGO " 175 "heuristics minimizing code growth in cold regions and being more " 176 "aggressive in hot regions.")); 177 178 // Runtime interleave loops for load/store throughput. 179 static cl::opt<bool> EnableLoadStoreRuntimeInterleave( 180 "enable-loadstore-runtime-interleave", cl::init(true), cl::Hidden, 181 cl::desc( 182 "Enable runtime interleaving until load/store ports are saturated")); 183 184 /// The number of stores in a loop that are allowed to need predication. 185 static cl::opt<unsigned> NumberOfStoresToPredicate( 186 "vectorize-num-stores-pred", cl::init(1), cl::Hidden, 187 cl::desc("Max number of stores to be predicated behind an if.")); 188 189 static cl::opt<bool> EnableIndVarRegisterHeur( 190 "enable-ind-var-reg-heur", cl::init(true), cl::Hidden, 191 cl::desc("Count the induction variable only once when interleaving")); 192 193 static cl::opt<bool> EnableCondStoresVectorization( 194 "enable-cond-stores-vec", cl::init(false), cl::Hidden, 195 cl::desc("Enable if predication of stores during vectorization.")); 196 197 static cl::opt<unsigned> MaxNestedScalarReductionIC( 198 "max-nested-scalar-reduction-interleave", cl::init(2), cl::Hidden, 199 cl::desc("The maximum interleave count to use when interleaving a scalar " 200 "reduction in a nested loop.")); 201 202 static cl::opt<unsigned> PragmaVectorizeMemoryCheckThreshold( 203 "pragma-vectorize-memory-check-threshold", cl::init(128), cl::Hidden, 204 cl::desc("The maximum allowed number of runtime memory checks with a " 205 "vectorize(enable) pragma.")); 206 207 static cl::opt<unsigned> VectorizeSCEVCheckThreshold( 208 "vectorize-scev-check-threshold", cl::init(16), cl::Hidden, 209 cl::desc("The maximum number of SCEV checks allowed.")); 210 211 static cl::opt<unsigned> PragmaVectorizeSCEVCheckThreshold( 212 "pragma-vectorize-scev-check-threshold", cl::init(128), cl::Hidden, 213 cl::desc("The maximum number of SCEV checks allowed with a " 214 "vectorize(enable) pragma")); 215 216 namespace { 217 218 // Forward declarations. 219 class LoopVectorizeHints; 220 class LoopVectorizationLegality; 221 class LoopVectorizationCostModel; 222 class LoopVectorizationRequirements; 223 224 /// Returns true if the given loop body has a cycle, excluding the loop 225 /// itself. 226 static bool hasCyclesInLoopBody(const Loop &L) { 227 if (!L.empty()) 228 return true; 229 230 for (const auto &SCC : 231 make_range(scc_iterator<Loop, LoopBodyTraits>::begin(L), 232 scc_iterator<Loop, LoopBodyTraits>::end(L))) { 233 if (SCC.size() > 1) { 234 DEBUG(dbgs() << "LVL: Detected a cycle in the loop body:\n"); 235 DEBUG(L.dump()); 236 return true; 237 } 238 } 239 return false; 240 } 241 242 /// \brief This modifies LoopAccessReport to initialize message with 243 /// loop-vectorizer-specific part. 244 class VectorizationReport : public LoopAccessReport { 245 public: 246 VectorizationReport(Instruction *I = nullptr) 247 : LoopAccessReport("loop not vectorized: ", I) {} 248 249 /// \brief This allows promotion of the loop-access analysis report into the 250 /// loop-vectorizer report. It modifies the message to add the 251 /// loop-vectorizer-specific part of the message. 252 explicit VectorizationReport(const LoopAccessReport &R) 253 : LoopAccessReport(Twine("loop not vectorized: ") + R.str(), 254 R.getInstr()) {} 255 }; 256 257 /// A helper function for converting Scalar types to vector types. 258 /// If the incoming type is void, we return void. If the VF is 1, we return 259 /// the scalar type. 260 static Type *ToVectorTy(Type *Scalar, unsigned VF) { 261 if (Scalar->isVoidTy() || VF == 1) 262 return Scalar; 263 return VectorType::get(Scalar, VF); 264 } 265 266 /// A helper function that returns GEP instruction and knows to skip a 267 /// 'bitcast'. The 'bitcast' may be skipped if the source and the destination 268 /// pointee types of the 'bitcast' have the same size. 269 /// For example: 270 /// bitcast double** %var to i64* - can be skipped 271 /// bitcast double** %var to i8* - can not 272 static GetElementPtrInst *getGEPInstruction(Value *Ptr) { 273 274 if (isa<GetElementPtrInst>(Ptr)) 275 return cast<GetElementPtrInst>(Ptr); 276 277 if (isa<BitCastInst>(Ptr) && 278 isa<GetElementPtrInst>(cast<BitCastInst>(Ptr)->getOperand(0))) { 279 Type *BitcastTy = Ptr->getType(); 280 Type *GEPTy = cast<BitCastInst>(Ptr)->getSrcTy(); 281 if (!isa<PointerType>(BitcastTy) || !isa<PointerType>(GEPTy)) 282 return nullptr; 283 Type *Pointee1Ty = cast<PointerType>(BitcastTy)->getPointerElementType(); 284 Type *Pointee2Ty = cast<PointerType>(GEPTy)->getPointerElementType(); 285 const DataLayout &DL = cast<BitCastInst>(Ptr)->getModule()->getDataLayout(); 286 if (DL.getTypeSizeInBits(Pointee1Ty) == DL.getTypeSizeInBits(Pointee2Ty)) 287 return cast<GetElementPtrInst>(cast<BitCastInst>(Ptr)->getOperand(0)); 288 } 289 return nullptr; 290 } 291 292 /// A helper function that returns the pointer operand of a load or store 293 /// instruction. 294 static Value *getPointerOperand(Value *I) { 295 if (auto *LI = dyn_cast<LoadInst>(I)) 296 return LI->getPointerOperand(); 297 if (auto *SI = dyn_cast<StoreInst>(I)) 298 return SI->getPointerOperand(); 299 return nullptr; 300 } 301 302 /// InnerLoopVectorizer vectorizes loops which contain only one basic 303 /// block to a specified vectorization factor (VF). 304 /// This class performs the widening of scalars into vectors, or multiple 305 /// scalars. This class also implements the following features: 306 /// * It inserts an epilogue loop for handling loops that don't have iteration 307 /// counts that are known to be a multiple of the vectorization factor. 308 /// * It handles the code generation for reduction variables. 309 /// * Scalarization (implementation using scalars) of un-vectorizable 310 /// instructions. 311 /// InnerLoopVectorizer does not perform any vectorization-legality 312 /// checks, and relies on the caller to check for the different legality 313 /// aspects. The InnerLoopVectorizer relies on the 314 /// LoopVectorizationLegality class to provide information about the induction 315 /// and reduction variables that were found to a given vectorization factor. 316 class InnerLoopVectorizer { 317 public: 318 InnerLoopVectorizer(Loop *OrigLoop, PredicatedScalarEvolution &PSE, 319 LoopInfo *LI, DominatorTree *DT, 320 const TargetLibraryInfo *TLI, 321 const TargetTransformInfo *TTI, AssumptionCache *AC, 322 OptimizationRemarkEmitter *ORE, unsigned VecWidth, 323 unsigned UnrollFactor) 324 : OrigLoop(OrigLoop), PSE(PSE), LI(LI), DT(DT), TLI(TLI), TTI(TTI), 325 AC(AC), ORE(ORE), VF(VecWidth), UF(UnrollFactor), 326 Builder(PSE.getSE()->getContext()), Induction(nullptr), 327 OldInduction(nullptr), WidenMap(UnrollFactor), TripCount(nullptr), 328 VectorTripCount(nullptr), Legal(nullptr), AddedSafetyChecks(false) {} 329 330 // Perform the actual loop widening (vectorization). 331 // MinimumBitWidths maps scalar integer values to the smallest bitwidth they 332 // can be validly truncated to. The cost model has assumed this truncation 333 // will happen when vectorizing. VecValuesToIgnore contains scalar values 334 // that the cost model has chosen to ignore because they will not be 335 // vectorized. 336 void vectorize(LoopVectorizationLegality *L, 337 const MapVector<Instruction *, uint64_t> &MinimumBitWidths) { 338 MinBWs = &MinimumBitWidths; 339 Legal = L; 340 // Create a new empty loop. Unlink the old loop and connect the new one. 341 createEmptyLoop(); 342 // Widen each instruction in the old loop to a new one in the new loop. 343 // Use the Legality module to find the induction and reduction variables. 344 vectorizeLoop(); 345 } 346 347 // Return true if any runtime check is added. 348 bool areSafetyChecksAdded() { return AddedSafetyChecks; } 349 350 virtual ~InnerLoopVectorizer() {} 351 352 protected: 353 /// A small list of PHINodes. 354 typedef SmallVector<PHINode *, 4> PhiVector; 355 /// When we unroll loops we have multiple vector values for each scalar. 356 /// This data structure holds the unrolled and vectorized values that 357 /// originated from one scalar instruction. 358 typedef SmallVector<Value *, 2> VectorParts; 359 360 // When we if-convert we need to create edge masks. We have to cache values 361 // so that we don't end up with exponential recursion/IR. 362 typedef DenseMap<std::pair<BasicBlock *, BasicBlock *>, VectorParts> 363 EdgeMaskCache; 364 365 /// Create an empty loop, based on the loop ranges of the old loop. 366 void createEmptyLoop(); 367 368 /// Set up the values of the IVs correctly when exiting the vector loop. 369 void fixupIVUsers(PHINode *OrigPhi, const InductionDescriptor &II, 370 Value *CountRoundDown, Value *EndValue, 371 BasicBlock *MiddleBlock); 372 373 /// Create a new induction variable inside L. 374 PHINode *createInductionVariable(Loop *L, Value *Start, Value *End, 375 Value *Step, Instruction *DL); 376 /// Copy and widen the instructions from the old loop. 377 virtual void vectorizeLoop(); 378 379 /// Fix a first-order recurrence. This is the second phase of vectorizing 380 /// this phi node. 381 void fixFirstOrderRecurrence(PHINode *Phi); 382 383 /// \brief The Loop exit block may have single value PHI nodes where the 384 /// incoming value is 'Undef'. While vectorizing we only handled real values 385 /// that were defined inside the loop. Here we fix the 'undef case'. 386 /// See PR14725. 387 void fixLCSSAPHIs(); 388 389 /// Predicate conditional stores on their respective conditions. 390 void predicateStores(); 391 392 /// Shrinks vector element sizes based on information in "MinBWs". 393 void truncateToMinimalBitwidths(); 394 395 /// A helper function that computes the predicate of the block BB, assuming 396 /// that the header block of the loop is set to True. It returns the *entry* 397 /// mask for the block BB. 398 VectorParts createBlockInMask(BasicBlock *BB); 399 /// A helper function that computes the predicate of the edge between SRC 400 /// and DST. 401 VectorParts createEdgeMask(BasicBlock *Src, BasicBlock *Dst); 402 403 /// A helper function to vectorize a single BB within the innermost loop. 404 void vectorizeBlockInLoop(BasicBlock *BB, PhiVector *PV); 405 406 /// Vectorize a single PHINode in a block. This method handles the induction 407 /// variable canonicalization. It supports both VF = 1 for unrolled loops and 408 /// arbitrary length vectors. 409 void widenPHIInstruction(Instruction *PN, VectorParts &Entry, unsigned UF, 410 unsigned VF, PhiVector *PV); 411 412 /// Insert the new loop to the loop hierarchy and pass manager 413 /// and update the analysis passes. 414 void updateAnalysis(); 415 416 /// This instruction is un-vectorizable. Implement it as a sequence 417 /// of scalars. If \p IfPredicateStore is true we need to 'hide' each 418 /// scalarized instruction behind an if block predicated on the control 419 /// dependence of the instruction. 420 virtual void scalarizeInstruction(Instruction *Instr, 421 bool IfPredicateStore = false); 422 423 /// Vectorize Load and Store instructions, 424 virtual void vectorizeMemoryInstruction(Instruction *Instr); 425 426 /// Create a broadcast instruction. This method generates a broadcast 427 /// instruction (shuffle) for loop invariant values and for the induction 428 /// value. If this is the induction variable then we extend it to N, N+1, ... 429 /// this is needed because each iteration in the loop corresponds to a SIMD 430 /// element. 431 virtual Value *getBroadcastInstrs(Value *V); 432 433 /// This function adds (StartIdx, StartIdx + Step, StartIdx + 2*Step, ...) 434 /// to each vector element of Val. The sequence starts at StartIndex. 435 /// \p Opcode is relevant for FP induction variable. 436 virtual Value *getStepVector(Value *Val, int StartIdx, Value *Step, 437 Instruction::BinaryOps Opcode = 438 Instruction::BinaryOpsEnd); 439 440 /// Compute scalar induction steps. \p ScalarIV is the scalar induction 441 /// variable on which to base the steps, \p Step is the size of the step, and 442 /// \p EntryVal is the value from the original loop that maps to the steps. 443 /// Note that \p EntryVal doesn't have to be an induction variable (e.g., it 444 /// can be a truncate instruction). 445 void buildScalarSteps(Value *ScalarIV, Value *Step, Value *EntryVal); 446 447 /// Create a vector induction phi node based on an existing scalar one. This 448 /// currently only works for integer induction variables with a constant 449 /// step. If \p TruncType is non-null, instead of widening the original IV, 450 /// we widen a version of the IV truncated to \p TruncType. 451 void createVectorIntInductionPHI(const InductionDescriptor &II, 452 VectorParts &Entry, IntegerType *TruncType); 453 454 /// Widen an integer induction variable \p IV. If \p Trunc is provided, the 455 /// induction variable will first be truncated to the corresponding type. The 456 /// widened values are placed in \p Entry. 457 void widenIntInduction(PHINode *IV, VectorParts &Entry, 458 TruncInst *Trunc = nullptr); 459 460 /// Returns true if we should generate a scalar version of \p IV. 461 bool needsScalarInduction(Instruction *IV) const; 462 463 /// When we go over instructions in the basic block we rely on previous 464 /// values within the current basic block or on loop invariant values. 465 /// When we widen (vectorize) values we place them in the map. If the values 466 /// are not within the map, they have to be loop invariant, so we simply 467 /// broadcast them into a vector. 468 VectorParts &getVectorValue(Value *V); 469 470 /// Try to vectorize the interleaved access group that \p Instr belongs to. 471 void vectorizeInterleaveGroup(Instruction *Instr); 472 473 /// Generate a shuffle sequence that will reverse the vector Vec. 474 virtual Value *reverseVector(Value *Vec); 475 476 /// Returns (and creates if needed) the original loop trip count. 477 Value *getOrCreateTripCount(Loop *NewLoop); 478 479 /// Returns (and creates if needed) the trip count of the widened loop. 480 Value *getOrCreateVectorTripCount(Loop *NewLoop); 481 482 /// Emit a bypass check to see if the trip count would overflow, or we 483 /// wouldn't have enough iterations to execute one vector loop. 484 void emitMinimumIterationCountCheck(Loop *L, BasicBlock *Bypass); 485 /// Emit a bypass check to see if the vector trip count is nonzero. 486 void emitVectorLoopEnteredCheck(Loop *L, BasicBlock *Bypass); 487 /// Emit a bypass check to see if all of the SCEV assumptions we've 488 /// had to make are correct. 489 void emitSCEVChecks(Loop *L, BasicBlock *Bypass); 490 /// Emit bypass checks to check any memory assumptions we may have made. 491 void emitMemRuntimeChecks(Loop *L, BasicBlock *Bypass); 492 493 /// Add additional metadata to \p To that was not present on \p Orig. 494 /// 495 /// Currently this is used to add the noalias annotations based on the 496 /// inserted memchecks. Use this for instructions that are *cloned* into the 497 /// vector loop. 498 void addNewMetadata(Instruction *To, const Instruction *Orig); 499 500 /// Add metadata from one instruction to another. 501 /// 502 /// This includes both the original MDs from \p From and additional ones (\see 503 /// addNewMetadata). Use this for *newly created* instructions in the vector 504 /// loop. 505 void addMetadata(Instruction *To, Instruction *From); 506 507 /// \brief Similar to the previous function but it adds the metadata to a 508 /// vector of instructions. 509 void addMetadata(ArrayRef<Value *> To, Instruction *From); 510 511 /// This is a helper class that holds the vectorizer state. It maps scalar 512 /// instructions to vector instructions. When the code is 'unrolled' then 513 /// then a single scalar value is mapped to multiple vector parts. The parts 514 /// are stored in the VectorPart type. 515 struct ValueMap { 516 /// C'tor. UnrollFactor controls the number of vectors ('parts') that 517 /// are mapped. 518 ValueMap(unsigned UnrollFactor) : UF(UnrollFactor) {} 519 520 /// \return True if 'Key' is saved in the Value Map. 521 bool has(Value *Key) const { return MapStorage.count(Key); } 522 523 /// Initializes a new entry in the map. Sets all of the vector parts to the 524 /// save value in 'Val'. 525 /// \return A reference to a vector with splat values. 526 VectorParts &splat(Value *Key, Value *Val) { 527 VectorParts &Entry = MapStorage[Key]; 528 Entry.assign(UF, Val); 529 return Entry; 530 } 531 532 ///\return A reference to the value that is stored at 'Key'. 533 VectorParts &get(Value *Key) { 534 VectorParts &Entry = MapStorage[Key]; 535 if (Entry.empty()) 536 Entry.resize(UF); 537 assert(Entry.size() == UF); 538 return Entry; 539 } 540 541 private: 542 /// The unroll factor. Each entry in the map stores this number of vector 543 /// elements. 544 unsigned UF; 545 546 /// Map storage. We use std::map and not DenseMap because insertions to a 547 /// dense map invalidates its iterators. 548 std::map<Value *, VectorParts> MapStorage; 549 }; 550 551 /// The original loop. 552 Loop *OrigLoop; 553 /// A wrapper around ScalarEvolution used to add runtime SCEV checks. Applies 554 /// dynamic knowledge to simplify SCEV expressions and converts them to a 555 /// more usable form. 556 PredicatedScalarEvolution &PSE; 557 /// Loop Info. 558 LoopInfo *LI; 559 /// Dominator Tree. 560 DominatorTree *DT; 561 /// Alias Analysis. 562 AliasAnalysis *AA; 563 /// Target Library Info. 564 const TargetLibraryInfo *TLI; 565 /// Target Transform Info. 566 const TargetTransformInfo *TTI; 567 /// Assumption Cache. 568 AssumptionCache *AC; 569 /// Interface to emit optimization remarks. 570 OptimizationRemarkEmitter *ORE; 571 572 /// \brief LoopVersioning. It's only set up (non-null) if memchecks were 573 /// used. 574 /// 575 /// This is currently only used to add no-alias metadata based on the 576 /// memchecks. The actually versioning is performed manually. 577 std::unique_ptr<LoopVersioning> LVer; 578 579 /// The vectorization SIMD factor to use. Each vector will have this many 580 /// vector elements. 581 unsigned VF; 582 583 protected: 584 /// The vectorization unroll factor to use. Each scalar is vectorized to this 585 /// many different vector instructions. 586 unsigned UF; 587 588 /// The builder that we use 589 IRBuilder<> Builder; 590 591 // --- Vectorization state --- 592 593 /// The vector-loop preheader. 594 BasicBlock *LoopVectorPreHeader; 595 /// The scalar-loop preheader. 596 BasicBlock *LoopScalarPreHeader; 597 /// Middle Block between the vector and the scalar. 598 BasicBlock *LoopMiddleBlock; 599 /// The ExitBlock of the scalar loop. 600 BasicBlock *LoopExitBlock; 601 /// The vector loop body. 602 BasicBlock *LoopVectorBody; 603 /// The scalar loop body. 604 BasicBlock *LoopScalarBody; 605 /// A list of all bypass blocks. The first block is the entry of the loop. 606 SmallVector<BasicBlock *, 4> LoopBypassBlocks; 607 608 /// The new Induction variable which was added to the new block. 609 PHINode *Induction; 610 /// The induction variable of the old basic block. 611 PHINode *OldInduction; 612 /// Maps scalars to widened vectors. 613 ValueMap WidenMap; 614 615 /// A map of induction variables from the original loop to their 616 /// corresponding VF * UF scalarized values in the vectorized loop. The 617 /// purpose of ScalarIVMap is similar to that of WidenMap. Whereas WidenMap 618 /// maps original loop values to their vector versions in the new loop, 619 /// ScalarIVMap maps induction variables from the original loop that are not 620 /// vectorized to their scalar equivalents in the vector loop. Maintaining a 621 /// separate map for scalarized induction variables allows us to avoid 622 /// unnecessary scalar-to-vector-to-scalar conversions. 623 DenseMap<Value *, SmallVector<Value *, 8>> ScalarIVMap; 624 625 /// Store instructions that should be predicated, as a pair 626 /// <StoreInst, Predicate> 627 SmallVector<std::pair<StoreInst *, Value *>, 4> PredicatedStores; 628 EdgeMaskCache MaskCache; 629 /// Trip count of the original loop. 630 Value *TripCount; 631 /// Trip count of the widened loop (TripCount - TripCount % (VF*UF)) 632 Value *VectorTripCount; 633 634 /// Map of scalar integer values to the smallest bitwidth they can be legally 635 /// represented as. The vector equivalents of these values should be truncated 636 /// to this type. 637 const MapVector<Instruction *, uint64_t> *MinBWs; 638 639 LoopVectorizationLegality *Legal; 640 641 // Record whether runtime checks are added. 642 bool AddedSafetyChecks; 643 }; 644 645 class InnerLoopUnroller : public InnerLoopVectorizer { 646 public: 647 InnerLoopUnroller(Loop *OrigLoop, PredicatedScalarEvolution &PSE, 648 LoopInfo *LI, DominatorTree *DT, 649 const TargetLibraryInfo *TLI, 650 const TargetTransformInfo *TTI, AssumptionCache *AC, 651 OptimizationRemarkEmitter *ORE, unsigned UnrollFactor) 652 : InnerLoopVectorizer(OrigLoop, PSE, LI, DT, TLI, TTI, AC, ORE, 1, 653 UnrollFactor) {} 654 655 private: 656 void scalarizeInstruction(Instruction *Instr, 657 bool IfPredicateStore = false) override; 658 void vectorizeMemoryInstruction(Instruction *Instr) override; 659 Value *getBroadcastInstrs(Value *V) override; 660 Value *getStepVector(Value *Val, int StartIdx, Value *Step, 661 Instruction::BinaryOps Opcode = 662 Instruction::BinaryOpsEnd) override; 663 Value *reverseVector(Value *Vec) override; 664 }; 665 666 /// \brief Look for a meaningful debug location on the instruction or it's 667 /// operands. 668 static Instruction *getDebugLocFromInstOrOperands(Instruction *I) { 669 if (!I) 670 return I; 671 672 DebugLoc Empty; 673 if (I->getDebugLoc() != Empty) 674 return I; 675 676 for (User::op_iterator OI = I->op_begin(), OE = I->op_end(); OI != OE; ++OI) { 677 if (Instruction *OpInst = dyn_cast<Instruction>(*OI)) 678 if (OpInst->getDebugLoc() != Empty) 679 return OpInst; 680 } 681 682 return I; 683 } 684 685 /// \brief Set the debug location in the builder using the debug location in the 686 /// instruction. 687 static void setDebugLocFromInst(IRBuilder<> &B, const Value *Ptr) { 688 if (const Instruction *Inst = dyn_cast_or_null<Instruction>(Ptr)) 689 B.SetCurrentDebugLocation(Inst->getDebugLoc()); 690 else 691 B.SetCurrentDebugLocation(DebugLoc()); 692 } 693 694 #ifndef NDEBUG 695 /// \return string containing a file name and a line # for the given loop. 696 static std::string getDebugLocString(const Loop *L) { 697 std::string Result; 698 if (L) { 699 raw_string_ostream OS(Result); 700 if (const DebugLoc LoopDbgLoc = L->getStartLoc()) 701 LoopDbgLoc.print(OS); 702 else 703 // Just print the module name. 704 OS << L->getHeader()->getParent()->getParent()->getModuleIdentifier(); 705 OS.flush(); 706 } 707 return Result; 708 } 709 #endif 710 711 void InnerLoopVectorizer::addNewMetadata(Instruction *To, 712 const Instruction *Orig) { 713 // If the loop was versioned with memchecks, add the corresponding no-alias 714 // metadata. 715 if (LVer && (isa<LoadInst>(Orig) || isa<StoreInst>(Orig))) 716 LVer->annotateInstWithNoAlias(To, Orig); 717 } 718 719 void InnerLoopVectorizer::addMetadata(Instruction *To, 720 Instruction *From) { 721 propagateMetadata(To, From); 722 addNewMetadata(To, From); 723 } 724 725 void InnerLoopVectorizer::addMetadata(ArrayRef<Value *> To, 726 Instruction *From) { 727 for (Value *V : To) { 728 if (Instruction *I = dyn_cast<Instruction>(V)) 729 addMetadata(I, From); 730 } 731 } 732 733 /// \brief The group of interleaved loads/stores sharing the same stride and 734 /// close to each other. 735 /// 736 /// Each member in this group has an index starting from 0, and the largest 737 /// index should be less than interleaved factor, which is equal to the absolute 738 /// value of the access's stride. 739 /// 740 /// E.g. An interleaved load group of factor 4: 741 /// for (unsigned i = 0; i < 1024; i+=4) { 742 /// a = A[i]; // Member of index 0 743 /// b = A[i+1]; // Member of index 1 744 /// d = A[i+3]; // Member of index 3 745 /// ... 746 /// } 747 /// 748 /// An interleaved store group of factor 4: 749 /// for (unsigned i = 0; i < 1024; i+=4) { 750 /// ... 751 /// A[i] = a; // Member of index 0 752 /// A[i+1] = b; // Member of index 1 753 /// A[i+2] = c; // Member of index 2 754 /// A[i+3] = d; // Member of index 3 755 /// } 756 /// 757 /// Note: the interleaved load group could have gaps (missing members), but 758 /// the interleaved store group doesn't allow gaps. 759 class InterleaveGroup { 760 public: 761 InterleaveGroup(Instruction *Instr, int Stride, unsigned Align) 762 : Align(Align), SmallestKey(0), LargestKey(0), InsertPos(Instr) { 763 assert(Align && "The alignment should be non-zero"); 764 765 Factor = std::abs(Stride); 766 assert(Factor > 1 && "Invalid interleave factor"); 767 768 Reverse = Stride < 0; 769 Members[0] = Instr; 770 } 771 772 bool isReverse() const { return Reverse; } 773 unsigned getFactor() const { return Factor; } 774 unsigned getAlignment() const { return Align; } 775 unsigned getNumMembers() const { return Members.size(); } 776 777 /// \brief Try to insert a new member \p Instr with index \p Index and 778 /// alignment \p NewAlign. The index is related to the leader and it could be 779 /// negative if it is the new leader. 780 /// 781 /// \returns false if the instruction doesn't belong to the group. 782 bool insertMember(Instruction *Instr, int Index, unsigned NewAlign) { 783 assert(NewAlign && "The new member's alignment should be non-zero"); 784 785 int Key = Index + SmallestKey; 786 787 // Skip if there is already a member with the same index. 788 if (Members.count(Key)) 789 return false; 790 791 if (Key > LargestKey) { 792 // The largest index is always less than the interleave factor. 793 if (Index >= static_cast<int>(Factor)) 794 return false; 795 796 LargestKey = Key; 797 } else if (Key < SmallestKey) { 798 // The largest index is always less than the interleave factor. 799 if (LargestKey - Key >= static_cast<int>(Factor)) 800 return false; 801 802 SmallestKey = Key; 803 } 804 805 // It's always safe to select the minimum alignment. 806 Align = std::min(Align, NewAlign); 807 Members[Key] = Instr; 808 return true; 809 } 810 811 /// \brief Get the member with the given index \p Index 812 /// 813 /// \returns nullptr if contains no such member. 814 Instruction *getMember(unsigned Index) const { 815 int Key = SmallestKey + Index; 816 if (!Members.count(Key)) 817 return nullptr; 818 819 return Members.find(Key)->second; 820 } 821 822 /// \brief Get the index for the given member. Unlike the key in the member 823 /// map, the index starts from 0. 824 unsigned getIndex(Instruction *Instr) const { 825 for (auto I : Members) 826 if (I.second == Instr) 827 return I.first - SmallestKey; 828 829 llvm_unreachable("InterleaveGroup contains no such member"); 830 } 831 832 Instruction *getInsertPos() const { return InsertPos; } 833 void setInsertPos(Instruction *Inst) { InsertPos = Inst; } 834 835 private: 836 unsigned Factor; // Interleave Factor. 837 bool Reverse; 838 unsigned Align; 839 DenseMap<int, Instruction *> Members; 840 int SmallestKey; 841 int LargestKey; 842 843 // To avoid breaking dependences, vectorized instructions of an interleave 844 // group should be inserted at either the first load or the last store in 845 // program order. 846 // 847 // E.g. %even = load i32 // Insert Position 848 // %add = add i32 %even // Use of %even 849 // %odd = load i32 850 // 851 // store i32 %even 852 // %odd = add i32 // Def of %odd 853 // store i32 %odd // Insert Position 854 Instruction *InsertPos; 855 }; 856 857 /// \brief Drive the analysis of interleaved memory accesses in the loop. 858 /// 859 /// Use this class to analyze interleaved accesses only when we can vectorize 860 /// a loop. Otherwise it's meaningless to do analysis as the vectorization 861 /// on interleaved accesses is unsafe. 862 /// 863 /// The analysis collects interleave groups and records the relationships 864 /// between the member and the group in a map. 865 class InterleavedAccessInfo { 866 public: 867 InterleavedAccessInfo(PredicatedScalarEvolution &PSE, Loop *L, 868 DominatorTree *DT, LoopInfo *LI) 869 : PSE(PSE), TheLoop(L), DT(DT), LI(LI), LAI(nullptr), 870 RequiresScalarEpilogue(false) {} 871 872 ~InterleavedAccessInfo() { 873 SmallSet<InterleaveGroup *, 4> DelSet; 874 // Avoid releasing a pointer twice. 875 for (auto &I : InterleaveGroupMap) 876 DelSet.insert(I.second); 877 for (auto *Ptr : DelSet) 878 delete Ptr; 879 } 880 881 /// \brief Analyze the interleaved accesses and collect them in interleave 882 /// groups. Substitute symbolic strides using \p Strides. 883 void analyzeInterleaving(const ValueToValueMap &Strides); 884 885 /// \brief Check if \p Instr belongs to any interleave group. 886 bool isInterleaved(Instruction *Instr) const { 887 return InterleaveGroupMap.count(Instr); 888 } 889 890 /// \brief Return the maximum interleave factor of all interleaved groups. 891 unsigned getMaxInterleaveFactor() const { 892 unsigned MaxFactor = 1; 893 for (auto &Entry : InterleaveGroupMap) 894 MaxFactor = std::max(MaxFactor, Entry.second->getFactor()); 895 return MaxFactor; 896 } 897 898 /// \brief Get the interleave group that \p Instr belongs to. 899 /// 900 /// \returns nullptr if doesn't have such group. 901 InterleaveGroup *getInterleaveGroup(Instruction *Instr) const { 902 if (InterleaveGroupMap.count(Instr)) 903 return InterleaveGroupMap.find(Instr)->second; 904 return nullptr; 905 } 906 907 /// \brief Returns true if an interleaved group that may access memory 908 /// out-of-bounds requires a scalar epilogue iteration for correctness. 909 bool requiresScalarEpilogue() const { return RequiresScalarEpilogue; } 910 911 /// \brief Initialize the LoopAccessInfo used for dependence checking. 912 void setLAI(const LoopAccessInfo *Info) { LAI = Info; } 913 914 private: 915 /// A wrapper around ScalarEvolution, used to add runtime SCEV checks. 916 /// Simplifies SCEV expressions in the context of existing SCEV assumptions. 917 /// The interleaved access analysis can also add new predicates (for example 918 /// by versioning strides of pointers). 919 PredicatedScalarEvolution &PSE; 920 Loop *TheLoop; 921 DominatorTree *DT; 922 LoopInfo *LI; 923 const LoopAccessInfo *LAI; 924 925 /// True if the loop may contain non-reversed interleaved groups with 926 /// out-of-bounds accesses. We ensure we don't speculatively access memory 927 /// out-of-bounds by executing at least one scalar epilogue iteration. 928 bool RequiresScalarEpilogue; 929 930 /// Holds the relationships between the members and the interleave group. 931 DenseMap<Instruction *, InterleaveGroup *> InterleaveGroupMap; 932 933 /// Holds dependences among the memory accesses in the loop. It maps a source 934 /// access to a set of dependent sink accesses. 935 DenseMap<Instruction *, SmallPtrSet<Instruction *, 2>> Dependences; 936 937 /// \brief The descriptor for a strided memory access. 938 struct StrideDescriptor { 939 StrideDescriptor(int64_t Stride, const SCEV *Scev, uint64_t Size, 940 unsigned Align) 941 : Stride(Stride), Scev(Scev), Size(Size), Align(Align) {} 942 943 StrideDescriptor() = default; 944 945 // The access's stride. It is negative for a reverse access. 946 int64_t Stride = 0; 947 const SCEV *Scev = nullptr; // The scalar expression of this access 948 uint64_t Size = 0; // The size of the memory object. 949 unsigned Align = 0; // The alignment of this access. 950 }; 951 952 /// \brief A type for holding instructions and their stride descriptors. 953 typedef std::pair<Instruction *, StrideDescriptor> StrideEntry; 954 955 /// \brief Create a new interleave group with the given instruction \p Instr, 956 /// stride \p Stride and alignment \p Align. 957 /// 958 /// \returns the newly created interleave group. 959 InterleaveGroup *createInterleaveGroup(Instruction *Instr, int Stride, 960 unsigned Align) { 961 assert(!InterleaveGroupMap.count(Instr) && 962 "Already in an interleaved access group"); 963 InterleaveGroupMap[Instr] = new InterleaveGroup(Instr, Stride, Align); 964 return InterleaveGroupMap[Instr]; 965 } 966 967 /// \brief Release the group and remove all the relationships. 968 void releaseGroup(InterleaveGroup *Group) { 969 for (unsigned i = 0; i < Group->getFactor(); i++) 970 if (Instruction *Member = Group->getMember(i)) 971 InterleaveGroupMap.erase(Member); 972 973 delete Group; 974 } 975 976 /// \brief Collect all the accesses with a constant stride in program order. 977 void collectConstStrideAccesses( 978 MapVector<Instruction *, StrideDescriptor> &AccessStrideInfo, 979 const ValueToValueMap &Strides); 980 981 /// \brief Returns true if \p Stride is allowed in an interleaved group. 982 static bool isStrided(int Stride) { 983 unsigned Factor = std::abs(Stride); 984 return Factor >= 2 && Factor <= MaxInterleaveGroupFactor; 985 } 986 987 /// \brief Returns true if \p BB is a predicated block. 988 bool isPredicated(BasicBlock *BB) const { 989 return LoopAccessInfo::blockNeedsPredication(BB, TheLoop, DT); 990 } 991 992 /// \brief Returns true if LoopAccessInfo can be used for dependence queries. 993 bool areDependencesValid() const { 994 return LAI && LAI->getDepChecker().getDependences(); 995 } 996 997 /// \brief Returns true if memory accesses \p A and \p B can be reordered, if 998 /// necessary, when constructing interleaved groups. 999 /// 1000 /// \p A must precede \p B in program order. We return false if reordering is 1001 /// not necessary or is prevented because \p A and \p B may be dependent. 1002 bool canReorderMemAccessesForInterleavedGroups(StrideEntry *A, 1003 StrideEntry *B) const { 1004 1005 // Code motion for interleaved accesses can potentially hoist strided loads 1006 // and sink strided stores. The code below checks the legality of the 1007 // following two conditions: 1008 // 1009 // 1. Potentially moving a strided load (B) before any store (A) that 1010 // precedes B, or 1011 // 1012 // 2. Potentially moving a strided store (A) after any load or store (B) 1013 // that A precedes. 1014 // 1015 // It's legal to reorder A and B if we know there isn't a dependence from A 1016 // to B. Note that this determination is conservative since some 1017 // dependences could potentially be reordered safely. 1018 1019 // A is potentially the source of a dependence. 1020 auto *Src = A->first; 1021 auto SrcDes = A->second; 1022 1023 // B is potentially the sink of a dependence. 1024 auto *Sink = B->first; 1025 auto SinkDes = B->second; 1026 1027 // Code motion for interleaved accesses can't violate WAR dependences. 1028 // Thus, reordering is legal if the source isn't a write. 1029 if (!Src->mayWriteToMemory()) 1030 return true; 1031 1032 // At least one of the accesses must be strided. 1033 if (!isStrided(SrcDes.Stride) && !isStrided(SinkDes.Stride)) 1034 return true; 1035 1036 // If dependence information is not available from LoopAccessInfo, 1037 // conservatively assume the instructions can't be reordered. 1038 if (!areDependencesValid()) 1039 return false; 1040 1041 // If we know there is a dependence from source to sink, assume the 1042 // instructions can't be reordered. Otherwise, reordering is legal. 1043 return !Dependences.count(Src) || !Dependences.lookup(Src).count(Sink); 1044 } 1045 1046 /// \brief Collect the dependences from LoopAccessInfo. 1047 /// 1048 /// We process the dependences once during the interleaved access analysis to 1049 /// enable constant-time dependence queries. 1050 void collectDependences() { 1051 if (!areDependencesValid()) 1052 return; 1053 auto *Deps = LAI->getDepChecker().getDependences(); 1054 for (auto Dep : *Deps) 1055 Dependences[Dep.getSource(*LAI)].insert(Dep.getDestination(*LAI)); 1056 } 1057 }; 1058 1059 /// Utility class for getting and setting loop vectorizer hints in the form 1060 /// of loop metadata. 1061 /// This class keeps a number of loop annotations locally (as member variables) 1062 /// and can, upon request, write them back as metadata on the loop. It will 1063 /// initially scan the loop for existing metadata, and will update the local 1064 /// values based on information in the loop. 1065 /// We cannot write all values to metadata, as the mere presence of some info, 1066 /// for example 'force', means a decision has been made. So, we need to be 1067 /// careful NOT to add them if the user hasn't specifically asked so. 1068 class LoopVectorizeHints { 1069 enum HintKind { HK_WIDTH, HK_UNROLL, HK_FORCE }; 1070 1071 /// Hint - associates name and validation with the hint value. 1072 struct Hint { 1073 const char *Name; 1074 unsigned Value; // This may have to change for non-numeric values. 1075 HintKind Kind; 1076 1077 Hint(const char *Name, unsigned Value, HintKind Kind) 1078 : Name(Name), Value(Value), Kind(Kind) {} 1079 1080 bool validate(unsigned Val) { 1081 switch (Kind) { 1082 case HK_WIDTH: 1083 return isPowerOf2_32(Val) && Val <= VectorizerParams::MaxVectorWidth; 1084 case HK_UNROLL: 1085 return isPowerOf2_32(Val) && Val <= MaxInterleaveFactor; 1086 case HK_FORCE: 1087 return (Val <= 1); 1088 } 1089 return false; 1090 } 1091 }; 1092 1093 /// Vectorization width. 1094 Hint Width; 1095 /// Vectorization interleave factor. 1096 Hint Interleave; 1097 /// Vectorization forced 1098 Hint Force; 1099 1100 /// Return the loop metadata prefix. 1101 static StringRef Prefix() { return "llvm.loop."; } 1102 1103 /// True if there is any unsafe math in the loop. 1104 bool PotentiallyUnsafe; 1105 1106 public: 1107 enum ForceKind { 1108 FK_Undefined = -1, ///< Not selected. 1109 FK_Disabled = 0, ///< Forcing disabled. 1110 FK_Enabled = 1, ///< Forcing enabled. 1111 }; 1112 1113 LoopVectorizeHints(const Loop *L, bool DisableInterleaving, 1114 OptimizationRemarkEmitter &ORE) 1115 : Width("vectorize.width", VectorizerParams::VectorizationFactor, 1116 HK_WIDTH), 1117 Interleave("interleave.count", DisableInterleaving, HK_UNROLL), 1118 Force("vectorize.enable", FK_Undefined, HK_FORCE), 1119 PotentiallyUnsafe(false), TheLoop(L), ORE(ORE) { 1120 // Populate values with existing loop metadata. 1121 getHintsFromMetadata(); 1122 1123 // force-vector-interleave overrides DisableInterleaving. 1124 if (VectorizerParams::isInterleaveForced()) 1125 Interleave.Value = VectorizerParams::VectorizationInterleave; 1126 1127 DEBUG(if (DisableInterleaving && Interleave.Value == 1) dbgs() 1128 << "LV: Interleaving disabled by the pass manager\n"); 1129 } 1130 1131 /// Mark the loop L as already vectorized by setting the width to 1. 1132 void setAlreadyVectorized() { 1133 Width.Value = Interleave.Value = 1; 1134 Hint Hints[] = {Width, Interleave}; 1135 writeHintsToMetadata(Hints); 1136 } 1137 1138 bool allowVectorization(Function *F, Loop *L, bool AlwaysVectorize) const { 1139 if (getForce() == LoopVectorizeHints::FK_Disabled) { 1140 DEBUG(dbgs() << "LV: Not vectorizing: #pragma vectorize disable.\n"); 1141 ORE.emitOptimizationRemarkAnalysis(vectorizeAnalysisPassName(), L, 1142 emitRemark()); 1143 return false; 1144 } 1145 1146 if (!AlwaysVectorize && getForce() != LoopVectorizeHints::FK_Enabled) { 1147 DEBUG(dbgs() << "LV: Not vectorizing: No #pragma vectorize enable.\n"); 1148 ORE.emitOptimizationRemarkAnalysis(vectorizeAnalysisPassName(), L, 1149 emitRemark()); 1150 return false; 1151 } 1152 1153 if (getWidth() == 1 && getInterleave() == 1) { 1154 // FIXME: Add a separate metadata to indicate when the loop has already 1155 // been vectorized instead of setting width and count to 1. 1156 DEBUG(dbgs() << "LV: Not vectorizing: Disabled/already vectorized.\n"); 1157 // FIXME: Add interleave.disable metadata. This will allow 1158 // vectorize.disable to be used without disabling the pass and errors 1159 // to differentiate between disabled vectorization and a width of 1. 1160 ORE.emitOptimizationRemarkAnalysis( 1161 vectorizeAnalysisPassName(), L, 1162 "loop not vectorized: vectorization and interleaving are explicitly " 1163 "disabled, or vectorize width and interleave count are both set to " 1164 "1"); 1165 return false; 1166 } 1167 1168 return true; 1169 } 1170 1171 /// Dumps all the hint information. 1172 std::string emitRemark() const { 1173 VectorizationReport R; 1174 if (Force.Value == LoopVectorizeHints::FK_Disabled) 1175 R << "vectorization is explicitly disabled"; 1176 else { 1177 R << "use -Rpass-analysis=loop-vectorize for more info"; 1178 if (Force.Value == LoopVectorizeHints::FK_Enabled) { 1179 R << " (Force=true"; 1180 if (Width.Value != 0) 1181 R << ", Vector Width=" << Width.Value; 1182 if (Interleave.Value != 0) 1183 R << ", Interleave Count=" << Interleave.Value; 1184 R << ")"; 1185 } 1186 } 1187 1188 return R.str(); 1189 } 1190 1191 unsigned getWidth() const { return Width.Value; } 1192 unsigned getInterleave() const { return Interleave.Value; } 1193 enum ForceKind getForce() const { return (ForceKind)Force.Value; } 1194 1195 /// \brief If hints are provided that force vectorization, use the AlwaysPrint 1196 /// pass name to force the frontend to print the diagnostic. 1197 const char *vectorizeAnalysisPassName() const { 1198 if (getWidth() == 1) 1199 return LV_NAME; 1200 if (getForce() == LoopVectorizeHints::FK_Disabled) 1201 return LV_NAME; 1202 if (getForce() == LoopVectorizeHints::FK_Undefined && getWidth() == 0) 1203 return LV_NAME; 1204 return DiagnosticInfoOptimizationRemarkAnalysis::AlwaysPrint; 1205 } 1206 1207 bool allowReordering() const { 1208 // When enabling loop hints are provided we allow the vectorizer to change 1209 // the order of operations that is given by the scalar loop. This is not 1210 // enabled by default because can be unsafe or inefficient. For example, 1211 // reordering floating-point operations will change the way round-off 1212 // error accumulates in the loop. 1213 return getForce() == LoopVectorizeHints::FK_Enabled || getWidth() > 1; 1214 } 1215 1216 bool isPotentiallyUnsafe() const { 1217 // Avoid FP vectorization if the target is unsure about proper support. 1218 // This may be related to the SIMD unit in the target not handling 1219 // IEEE 754 FP ops properly, or bad single-to-double promotions. 1220 // Otherwise, a sequence of vectorized loops, even without reduction, 1221 // could lead to different end results on the destination vectors. 1222 return getForce() != LoopVectorizeHints::FK_Enabled && PotentiallyUnsafe; 1223 } 1224 1225 void setPotentiallyUnsafe() { PotentiallyUnsafe = true; } 1226 1227 private: 1228 /// Find hints specified in the loop metadata and update local values. 1229 void getHintsFromMetadata() { 1230 MDNode *LoopID = TheLoop->getLoopID(); 1231 if (!LoopID) 1232 return; 1233 1234 // First operand should refer to the loop id itself. 1235 assert(LoopID->getNumOperands() > 0 && "requires at least one operand"); 1236 assert(LoopID->getOperand(0) == LoopID && "invalid loop id"); 1237 1238 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) { 1239 const MDString *S = nullptr; 1240 SmallVector<Metadata *, 4> Args; 1241 1242 // The expected hint is either a MDString or a MDNode with the first 1243 // operand a MDString. 1244 if (const MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i))) { 1245 if (!MD || MD->getNumOperands() == 0) 1246 continue; 1247 S = dyn_cast<MDString>(MD->getOperand(0)); 1248 for (unsigned i = 1, ie = MD->getNumOperands(); i < ie; ++i) 1249 Args.push_back(MD->getOperand(i)); 1250 } else { 1251 S = dyn_cast<MDString>(LoopID->getOperand(i)); 1252 assert(Args.size() == 0 && "too many arguments for MDString"); 1253 } 1254 1255 if (!S) 1256 continue; 1257 1258 // Check if the hint starts with the loop metadata prefix. 1259 StringRef Name = S->getString(); 1260 if (Args.size() == 1) 1261 setHint(Name, Args[0]); 1262 } 1263 } 1264 1265 /// Checks string hint with one operand and set value if valid. 1266 void setHint(StringRef Name, Metadata *Arg) { 1267 if (!Name.startswith(Prefix())) 1268 return; 1269 Name = Name.substr(Prefix().size(), StringRef::npos); 1270 1271 const ConstantInt *C = mdconst::dyn_extract<ConstantInt>(Arg); 1272 if (!C) 1273 return; 1274 unsigned Val = C->getZExtValue(); 1275 1276 Hint *Hints[] = {&Width, &Interleave, &Force}; 1277 for (auto H : Hints) { 1278 if (Name == H->Name) { 1279 if (H->validate(Val)) 1280 H->Value = Val; 1281 else 1282 DEBUG(dbgs() << "LV: ignoring invalid hint '" << Name << "'\n"); 1283 break; 1284 } 1285 } 1286 } 1287 1288 /// Create a new hint from name / value pair. 1289 MDNode *createHintMetadata(StringRef Name, unsigned V) const { 1290 LLVMContext &Context = TheLoop->getHeader()->getContext(); 1291 Metadata *MDs[] = {MDString::get(Context, Name), 1292 ConstantAsMetadata::get( 1293 ConstantInt::get(Type::getInt32Ty(Context), V))}; 1294 return MDNode::get(Context, MDs); 1295 } 1296 1297 /// Matches metadata with hint name. 1298 bool matchesHintMetadataName(MDNode *Node, ArrayRef<Hint> HintTypes) { 1299 MDString *Name = dyn_cast<MDString>(Node->getOperand(0)); 1300 if (!Name) 1301 return false; 1302 1303 for (auto H : HintTypes) 1304 if (Name->getString().endswith(H.Name)) 1305 return true; 1306 return false; 1307 } 1308 1309 /// Sets current hints into loop metadata, keeping other values intact. 1310 void writeHintsToMetadata(ArrayRef<Hint> HintTypes) { 1311 if (HintTypes.size() == 0) 1312 return; 1313 1314 // Reserve the first element to LoopID (see below). 1315 SmallVector<Metadata *, 4> MDs(1); 1316 // If the loop already has metadata, then ignore the existing operands. 1317 MDNode *LoopID = TheLoop->getLoopID(); 1318 if (LoopID) { 1319 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) { 1320 MDNode *Node = cast<MDNode>(LoopID->getOperand(i)); 1321 // If node in update list, ignore old value. 1322 if (!matchesHintMetadataName(Node, HintTypes)) 1323 MDs.push_back(Node); 1324 } 1325 } 1326 1327 // Now, add the missing hints. 1328 for (auto H : HintTypes) 1329 MDs.push_back(createHintMetadata(Twine(Prefix(), H.Name).str(), H.Value)); 1330 1331 // Replace current metadata node with new one. 1332 LLVMContext &Context = TheLoop->getHeader()->getContext(); 1333 MDNode *NewLoopID = MDNode::get(Context, MDs); 1334 // Set operand 0 to refer to the loop id itself. 1335 NewLoopID->replaceOperandWith(0, NewLoopID); 1336 1337 TheLoop->setLoopID(NewLoopID); 1338 } 1339 1340 /// The loop these hints belong to. 1341 const Loop *TheLoop; 1342 1343 /// Interface to emit optimization remarks. 1344 OptimizationRemarkEmitter &ORE; 1345 }; 1346 1347 static void emitAnalysisDiag(const Loop *TheLoop, 1348 const LoopVectorizeHints &Hints, 1349 OptimizationRemarkEmitter &ORE, 1350 const LoopAccessReport &Message) { 1351 const char *Name = Hints.vectorizeAnalysisPassName(); 1352 LoopAccessReport::emitAnalysis(Message, TheLoop, Name, ORE); 1353 } 1354 1355 static void emitMissedWarning(Function *F, Loop *L, 1356 const LoopVectorizeHints &LH, 1357 OptimizationRemarkEmitter *ORE) { 1358 ORE->emitOptimizationRemarkMissed(LV_NAME, L, LH.emitRemark()); 1359 1360 if (LH.getForce() == LoopVectorizeHints::FK_Enabled) { 1361 if (LH.getWidth() != 1) 1362 emitLoopVectorizeWarning( 1363 F->getContext(), *F, L->getStartLoc(), 1364 "failed explicitly specified loop vectorization"); 1365 else if (LH.getInterleave() != 1) 1366 emitLoopInterleaveWarning( 1367 F->getContext(), *F, L->getStartLoc(), 1368 "failed explicitly specified loop interleaving"); 1369 } 1370 } 1371 1372 /// LoopVectorizationLegality checks if it is legal to vectorize a loop, and 1373 /// to what vectorization factor. 1374 /// This class does not look at the profitability of vectorization, only the 1375 /// legality. This class has two main kinds of checks: 1376 /// * Memory checks - The code in canVectorizeMemory checks if vectorization 1377 /// will change the order of memory accesses in a way that will change the 1378 /// correctness of the program. 1379 /// * Scalars checks - The code in canVectorizeInstrs and canVectorizeMemory 1380 /// checks for a number of different conditions, such as the availability of a 1381 /// single induction variable, that all types are supported and vectorize-able, 1382 /// etc. This code reflects the capabilities of InnerLoopVectorizer. 1383 /// This class is also used by InnerLoopVectorizer for identifying 1384 /// induction variable and the different reduction variables. 1385 class LoopVectorizationLegality { 1386 public: 1387 LoopVectorizationLegality( 1388 Loop *L, PredicatedScalarEvolution &PSE, DominatorTree *DT, 1389 TargetLibraryInfo *TLI, AliasAnalysis *AA, Function *F, 1390 const TargetTransformInfo *TTI, 1391 std::function<const LoopAccessInfo &(Loop &)> *GetLAA, LoopInfo *LI, 1392 OptimizationRemarkEmitter *ORE, LoopVectorizationRequirements *R, 1393 LoopVectorizeHints *H) 1394 : NumPredStores(0), TheLoop(L), PSE(PSE), TLI(TLI), TTI(TTI), DT(DT), 1395 GetLAA(GetLAA), LAI(nullptr), ORE(ORE), InterleaveInfo(PSE, L, DT, LI), 1396 Induction(nullptr), WidestIndTy(nullptr), HasFunNoNaNAttr(false), 1397 Requirements(R), Hints(H) {} 1398 1399 /// ReductionList contains the reduction descriptors for all 1400 /// of the reductions that were found in the loop. 1401 typedef DenseMap<PHINode *, RecurrenceDescriptor> ReductionList; 1402 1403 /// InductionList saves induction variables and maps them to the 1404 /// induction descriptor. 1405 typedef MapVector<PHINode *, InductionDescriptor> InductionList; 1406 1407 /// RecurrenceSet contains the phi nodes that are recurrences other than 1408 /// inductions and reductions. 1409 typedef SmallPtrSet<const PHINode *, 8> RecurrenceSet; 1410 1411 /// Returns true if it is legal to vectorize this loop. 1412 /// This does not mean that it is profitable to vectorize this 1413 /// loop, only that it is legal to do so. 1414 bool canVectorize(); 1415 1416 /// Returns the Induction variable. 1417 PHINode *getInduction() { return Induction; } 1418 1419 /// Returns the reduction variables found in the loop. 1420 ReductionList *getReductionVars() { return &Reductions; } 1421 1422 /// Returns the induction variables found in the loop. 1423 InductionList *getInductionVars() { return &Inductions; } 1424 1425 /// Return the first-order recurrences found in the loop. 1426 RecurrenceSet *getFirstOrderRecurrences() { return &FirstOrderRecurrences; } 1427 1428 /// Returns the widest induction type. 1429 Type *getWidestInductionType() { return WidestIndTy; } 1430 1431 /// Returns True if V is an induction variable in this loop. 1432 bool isInductionVariable(const Value *V); 1433 1434 /// Returns True if PN is a reduction variable in this loop. 1435 bool isReductionVariable(PHINode *PN) { return Reductions.count(PN); } 1436 1437 /// Returns True if Phi is a first-order recurrence in this loop. 1438 bool isFirstOrderRecurrence(const PHINode *Phi); 1439 1440 /// Return true if the block BB needs to be predicated in order for the loop 1441 /// to be vectorized. 1442 bool blockNeedsPredication(BasicBlock *BB); 1443 1444 /// Check if this pointer is consecutive when vectorizing. This happens 1445 /// when the last index of the GEP is the induction variable, or that the 1446 /// pointer itself is an induction variable. 1447 /// This check allows us to vectorize A[idx] into a wide load/store. 1448 /// Returns: 1449 /// 0 - Stride is unknown or non-consecutive. 1450 /// 1 - Address is consecutive. 1451 /// -1 - Address is consecutive, and decreasing. 1452 int isConsecutivePtr(Value *Ptr); 1453 1454 /// Returns true if the value V is uniform within the loop. 1455 bool isUniform(Value *V); 1456 1457 /// Returns true if \p I is known to be uniform after vectorization. 1458 bool isUniformAfterVectorization(Instruction *I) { return Uniforms.count(I); } 1459 1460 /// Returns true if \p I is known to be scalar after vectorization. 1461 bool isScalarAfterVectorization(Instruction *I) { return Scalars.count(I); } 1462 1463 /// Returns the information that we collected about runtime memory check. 1464 const RuntimePointerChecking *getRuntimePointerChecking() const { 1465 return LAI->getRuntimePointerChecking(); 1466 } 1467 1468 const LoopAccessInfo *getLAI() const { return LAI; } 1469 1470 /// \brief Check if \p Instr belongs to any interleaved access group. 1471 bool isAccessInterleaved(Instruction *Instr) { 1472 return InterleaveInfo.isInterleaved(Instr); 1473 } 1474 1475 /// \brief Return the maximum interleave factor of all interleaved groups. 1476 unsigned getMaxInterleaveFactor() const { 1477 return InterleaveInfo.getMaxInterleaveFactor(); 1478 } 1479 1480 /// \brief Get the interleaved access group that \p Instr belongs to. 1481 const InterleaveGroup *getInterleavedAccessGroup(Instruction *Instr) { 1482 return InterleaveInfo.getInterleaveGroup(Instr); 1483 } 1484 1485 /// \brief Returns true if an interleaved group requires a scalar iteration 1486 /// to handle accesses with gaps. 1487 bool requiresScalarEpilogue() const { 1488 return InterleaveInfo.requiresScalarEpilogue(); 1489 } 1490 1491 unsigned getMaxSafeDepDistBytes() { return LAI->getMaxSafeDepDistBytes(); } 1492 1493 bool hasStride(Value *V) { return LAI->hasStride(V); } 1494 1495 /// Returns true if the target machine supports masked store operation 1496 /// for the given \p DataType and kind of access to \p Ptr. 1497 bool isLegalMaskedStore(Type *DataType, Value *Ptr) { 1498 return isConsecutivePtr(Ptr) && TTI->isLegalMaskedStore(DataType); 1499 } 1500 /// Returns true if the target machine supports masked load operation 1501 /// for the given \p DataType and kind of access to \p Ptr. 1502 bool isLegalMaskedLoad(Type *DataType, Value *Ptr) { 1503 return isConsecutivePtr(Ptr) && TTI->isLegalMaskedLoad(DataType); 1504 } 1505 /// Returns true if the target machine supports masked scatter operation 1506 /// for the given \p DataType. 1507 bool isLegalMaskedScatter(Type *DataType) { 1508 return TTI->isLegalMaskedScatter(DataType); 1509 } 1510 /// Returns true if the target machine supports masked gather operation 1511 /// for the given \p DataType. 1512 bool isLegalMaskedGather(Type *DataType) { 1513 return TTI->isLegalMaskedGather(DataType); 1514 } 1515 /// Returns true if the target machine can represent \p V as a masked gather 1516 /// or scatter operation. 1517 bool isLegalGatherOrScatter(Value *V) { 1518 auto *LI = dyn_cast<LoadInst>(V); 1519 auto *SI = dyn_cast<StoreInst>(V); 1520 if (!LI && !SI) 1521 return false; 1522 auto *Ptr = getPointerOperand(V); 1523 auto *Ty = cast<PointerType>(Ptr->getType())->getElementType(); 1524 return (LI && isLegalMaskedGather(Ty)) || (SI && isLegalMaskedScatter(Ty)); 1525 } 1526 1527 /// Returns true if vector representation of the instruction \p I 1528 /// requires mask. 1529 bool isMaskRequired(const Instruction *I) { return (MaskedOp.count(I) != 0); } 1530 unsigned getNumStores() const { return LAI->getNumStores(); } 1531 unsigned getNumLoads() const { return LAI->getNumLoads(); } 1532 unsigned getNumPredStores() const { return NumPredStores; } 1533 1534 private: 1535 /// Check if a single basic block loop is vectorizable. 1536 /// At this point we know that this is a loop with a constant trip count 1537 /// and we only need to check individual instructions. 1538 bool canVectorizeInstrs(); 1539 1540 /// When we vectorize loops we may change the order in which 1541 /// we read and write from memory. This method checks if it is 1542 /// legal to vectorize the code, considering only memory constrains. 1543 /// Returns true if the loop is vectorizable 1544 bool canVectorizeMemory(); 1545 1546 /// Return true if we can vectorize this loop using the IF-conversion 1547 /// transformation. 1548 bool canVectorizeWithIfConvert(); 1549 1550 /// Collect the instructions that are uniform after vectorization. An 1551 /// instruction is uniform if we represent it with a single scalar value in 1552 /// the vectorized loop corresponding to each vector iteration. Examples of 1553 /// uniform instructions include pointer operands of consecutive or 1554 /// interleaved memory accesses. Note that although uniformity implies an 1555 /// instruction will be scalar, the reverse is not true. In general, a 1556 /// scalarized instruction will be represented by VF scalar values in the 1557 /// vectorized loop, each corresponding to an iteration of the original 1558 /// scalar loop. 1559 void collectLoopUniforms(); 1560 1561 /// Collect the instructions that are scalar after vectorization. An 1562 /// instruction is scalar if it is known to be uniform or will be scalarized 1563 /// during vectorization. Non-uniform scalarized instructions will be 1564 /// represented by VF values in the vectorized loop, each corresponding to an 1565 /// iteration of the original scalar loop. 1566 void collectLoopScalars(); 1567 1568 /// Return true if all of the instructions in the block can be speculatively 1569 /// executed. \p SafePtrs is a list of addresses that are known to be legal 1570 /// and we know that we can read from them without segfault. 1571 bool blockCanBePredicated(BasicBlock *BB, SmallPtrSetImpl<Value *> &SafePtrs); 1572 1573 /// Updates the vectorization state by adding \p Phi to the inductions list. 1574 /// This can set \p Phi as the main induction of the loop if \p Phi is a 1575 /// better choice for the main induction than the existing one. 1576 void addInductionPhi(PHINode *Phi, const InductionDescriptor &ID, 1577 SmallPtrSetImpl<Value *> &AllowedExit); 1578 1579 /// Report an analysis message to assist the user in diagnosing loops that are 1580 /// not vectorized. These are handled as LoopAccessReport rather than 1581 /// VectorizationReport because the << operator of VectorizationReport returns 1582 /// LoopAccessReport. 1583 void emitAnalysis(const LoopAccessReport &Message) const { 1584 emitAnalysisDiag(TheLoop, *Hints, *ORE, Message); 1585 } 1586 1587 /// \brief If an access has a symbolic strides, this maps the pointer value to 1588 /// the stride symbol. 1589 const ValueToValueMap *getSymbolicStrides() { 1590 // FIXME: Currently, the set of symbolic strides is sometimes queried before 1591 // it's collected. This happens from canVectorizeWithIfConvert, when the 1592 // pointer is checked to reference consecutive elements suitable for a 1593 // masked access. 1594 return LAI ? &LAI->getSymbolicStrides() : nullptr; 1595 } 1596 1597 unsigned NumPredStores; 1598 1599 /// The loop that we evaluate. 1600 Loop *TheLoop; 1601 /// A wrapper around ScalarEvolution used to add runtime SCEV checks. 1602 /// Applies dynamic knowledge to simplify SCEV expressions in the context 1603 /// of existing SCEV assumptions. The analysis will also add a minimal set 1604 /// of new predicates if this is required to enable vectorization and 1605 /// unrolling. 1606 PredicatedScalarEvolution &PSE; 1607 /// Target Library Info. 1608 TargetLibraryInfo *TLI; 1609 /// Target Transform Info 1610 const TargetTransformInfo *TTI; 1611 /// Dominator Tree. 1612 DominatorTree *DT; 1613 // LoopAccess analysis. 1614 std::function<const LoopAccessInfo &(Loop &)> *GetLAA; 1615 // And the loop-accesses info corresponding to this loop. This pointer is 1616 // null until canVectorizeMemory sets it up. 1617 const LoopAccessInfo *LAI; 1618 /// Interface to emit optimization remarks. 1619 OptimizationRemarkEmitter *ORE; 1620 1621 /// The interleave access information contains groups of interleaved accesses 1622 /// with the same stride and close to each other. 1623 InterleavedAccessInfo InterleaveInfo; 1624 1625 // --- vectorization state --- // 1626 1627 /// Holds the integer induction variable. This is the counter of the 1628 /// loop. 1629 PHINode *Induction; 1630 /// Holds the reduction variables. 1631 ReductionList Reductions; 1632 /// Holds all of the induction variables that we found in the loop. 1633 /// Notice that inductions don't need to start at zero and that induction 1634 /// variables can be pointers. 1635 InductionList Inductions; 1636 /// Holds the phi nodes that are first-order recurrences. 1637 RecurrenceSet FirstOrderRecurrences; 1638 /// Holds the widest induction type encountered. 1639 Type *WidestIndTy; 1640 1641 /// Allowed outside users. This holds the induction and reduction 1642 /// vars which can be accessed from outside the loop. 1643 SmallPtrSet<Value *, 4> AllowedExit; 1644 1645 /// Holds the instructions known to be uniform after vectorization. 1646 SmallPtrSet<Instruction *, 4> Uniforms; 1647 1648 /// Holds the instructions known to be scalar after vectorization. 1649 SmallPtrSet<Instruction *, 4> Scalars; 1650 1651 /// Can we assume the absence of NaNs. 1652 bool HasFunNoNaNAttr; 1653 1654 /// Vectorization requirements that will go through late-evaluation. 1655 LoopVectorizationRequirements *Requirements; 1656 1657 /// Used to emit an analysis of any legality issues. 1658 LoopVectorizeHints *Hints; 1659 1660 /// While vectorizing these instructions we have to generate a 1661 /// call to the appropriate masked intrinsic 1662 SmallPtrSet<const Instruction *, 8> MaskedOp; 1663 }; 1664 1665 /// LoopVectorizationCostModel - estimates the expected speedups due to 1666 /// vectorization. 1667 /// In many cases vectorization is not profitable. This can happen because of 1668 /// a number of reasons. In this class we mainly attempt to predict the 1669 /// expected speedup/slowdowns due to the supported instruction set. We use the 1670 /// TargetTransformInfo to query the different backends for the cost of 1671 /// different operations. 1672 class LoopVectorizationCostModel { 1673 public: 1674 LoopVectorizationCostModel(Loop *L, PredicatedScalarEvolution &PSE, 1675 LoopInfo *LI, LoopVectorizationLegality *Legal, 1676 const TargetTransformInfo &TTI, 1677 const TargetLibraryInfo *TLI, DemandedBits *DB, 1678 AssumptionCache *AC, 1679 OptimizationRemarkEmitter *ORE, const Function *F, 1680 const LoopVectorizeHints *Hints) 1681 : TheLoop(L), PSE(PSE), LI(LI), Legal(Legal), TTI(TTI), TLI(TLI), DB(DB), 1682 AC(AC), ORE(ORE), TheFunction(F), Hints(Hints) {} 1683 1684 /// Information about vectorization costs 1685 struct VectorizationFactor { 1686 unsigned Width; // Vector width with best cost 1687 unsigned Cost; // Cost of the loop with that width 1688 }; 1689 /// \return The most profitable vectorization factor and the cost of that VF. 1690 /// This method checks every power of two up to VF. If UserVF is not ZERO 1691 /// then this vectorization factor will be selected if vectorization is 1692 /// possible. 1693 VectorizationFactor selectVectorizationFactor(bool OptForSize); 1694 1695 /// \return The size (in bits) of the smallest and widest types in the code 1696 /// that needs to be vectorized. We ignore values that remain scalar such as 1697 /// 64 bit loop indices. 1698 std::pair<unsigned, unsigned> getSmallestAndWidestTypes(); 1699 1700 /// \return The desired interleave count. 1701 /// If interleave count has been specified by metadata it will be returned. 1702 /// Otherwise, the interleave count is computed and returned. VF and LoopCost 1703 /// are the selected vectorization factor and the cost of the selected VF. 1704 unsigned selectInterleaveCount(bool OptForSize, unsigned VF, 1705 unsigned LoopCost); 1706 1707 /// \return The most profitable unroll factor. 1708 /// This method finds the best unroll-factor based on register pressure and 1709 /// other parameters. VF and LoopCost are the selected vectorization factor 1710 /// and the cost of the selected VF. 1711 unsigned computeInterleaveCount(bool OptForSize, unsigned VF, 1712 unsigned LoopCost); 1713 1714 /// \brief A struct that represents some properties of the register usage 1715 /// of a loop. 1716 struct RegisterUsage { 1717 /// Holds the number of loop invariant values that are used in the loop. 1718 unsigned LoopInvariantRegs; 1719 /// Holds the maximum number of concurrent live intervals in the loop. 1720 unsigned MaxLocalUsers; 1721 /// Holds the number of instructions in the loop. 1722 unsigned NumInstructions; 1723 }; 1724 1725 /// \return Returns information about the register usages of the loop for the 1726 /// given vectorization factors. 1727 SmallVector<RegisterUsage, 8> calculateRegisterUsage(ArrayRef<unsigned> VFs); 1728 1729 /// Collect values we want to ignore in the cost model. 1730 void collectValuesToIgnore(); 1731 1732 private: 1733 /// The vectorization cost is a combination of the cost itself and a boolean 1734 /// indicating whether any of the contributing operations will actually 1735 /// operate on 1736 /// vector values after type legalization in the backend. If this latter value 1737 /// is 1738 /// false, then all operations will be scalarized (i.e. no vectorization has 1739 /// actually taken place). 1740 typedef std::pair<unsigned, bool> VectorizationCostTy; 1741 1742 /// Returns the expected execution cost. The unit of the cost does 1743 /// not matter because we use the 'cost' units to compare different 1744 /// vector widths. The cost that is returned is *not* normalized by 1745 /// the factor width. 1746 VectorizationCostTy expectedCost(unsigned VF); 1747 1748 /// Returns the execution time cost of an instruction for a given vector 1749 /// width. Vector width of one means scalar. 1750 VectorizationCostTy getInstructionCost(Instruction *I, unsigned VF); 1751 1752 /// The cost-computation logic from getInstructionCost which provides 1753 /// the vector type as an output parameter. 1754 unsigned getInstructionCost(Instruction *I, unsigned VF, Type *&VectorTy); 1755 1756 /// Returns whether the instruction is a load or store and will be a emitted 1757 /// as a vector operation. 1758 bool isConsecutiveLoadOrStore(Instruction *I); 1759 1760 /// Report an analysis message to assist the user in diagnosing loops that are 1761 /// not vectorized. These are handled as LoopAccessReport rather than 1762 /// VectorizationReport because the << operator of VectorizationReport returns 1763 /// LoopAccessReport. 1764 void emitAnalysis(const LoopAccessReport &Message) const { 1765 emitAnalysisDiag(TheLoop, *Hints, *ORE, Message); 1766 } 1767 1768 public: 1769 /// Map of scalar integer values to the smallest bitwidth they can be legally 1770 /// represented as. The vector equivalents of these values should be truncated 1771 /// to this type. 1772 MapVector<Instruction *, uint64_t> MinBWs; 1773 1774 /// The loop that we evaluate. 1775 Loop *TheLoop; 1776 /// Predicated scalar evolution analysis. 1777 PredicatedScalarEvolution &PSE; 1778 /// Loop Info analysis. 1779 LoopInfo *LI; 1780 /// Vectorization legality. 1781 LoopVectorizationLegality *Legal; 1782 /// Vector target information. 1783 const TargetTransformInfo &TTI; 1784 /// Target Library Info. 1785 const TargetLibraryInfo *TLI; 1786 /// Demanded bits analysis. 1787 DemandedBits *DB; 1788 /// Assumption cache. 1789 AssumptionCache *AC; 1790 /// Interface to emit optimization remarks. 1791 OptimizationRemarkEmitter *ORE; 1792 1793 const Function *TheFunction; 1794 /// Loop Vectorize Hint. 1795 const LoopVectorizeHints *Hints; 1796 /// Values to ignore in the cost model. 1797 SmallPtrSet<const Value *, 16> ValuesToIgnore; 1798 /// Values to ignore in the cost model when VF > 1. 1799 SmallPtrSet<const Value *, 16> VecValuesToIgnore; 1800 }; 1801 1802 /// \brief This holds vectorization requirements that must be verified late in 1803 /// the process. The requirements are set by legalize and costmodel. Once 1804 /// vectorization has been determined to be possible and profitable the 1805 /// requirements can be verified by looking for metadata or compiler options. 1806 /// For example, some loops require FP commutativity which is only allowed if 1807 /// vectorization is explicitly specified or if the fast-math compiler option 1808 /// has been provided. 1809 /// Late evaluation of these requirements allows helpful diagnostics to be 1810 /// composed that tells the user what need to be done to vectorize the loop. For 1811 /// example, by specifying #pragma clang loop vectorize or -ffast-math. Late 1812 /// evaluation should be used only when diagnostics can generated that can be 1813 /// followed by a non-expert user. 1814 class LoopVectorizationRequirements { 1815 public: 1816 LoopVectorizationRequirements(OptimizationRemarkEmitter &ORE) 1817 : NumRuntimePointerChecks(0), UnsafeAlgebraInst(nullptr), ORE(ORE) {} 1818 1819 void addUnsafeAlgebraInst(Instruction *I) { 1820 // First unsafe algebra instruction. 1821 if (!UnsafeAlgebraInst) 1822 UnsafeAlgebraInst = I; 1823 } 1824 1825 void addRuntimePointerChecks(unsigned Num) { NumRuntimePointerChecks = Num; } 1826 1827 bool doesNotMeet(Function *F, Loop *L, const LoopVectorizeHints &Hints) { 1828 const char *Name = Hints.vectorizeAnalysisPassName(); 1829 bool Failed = false; 1830 if (UnsafeAlgebraInst && !Hints.allowReordering()) { 1831 ORE.emitOptimizationRemarkAnalysisFPCommute( 1832 Name, UnsafeAlgebraInst->getDebugLoc(), 1833 UnsafeAlgebraInst->getParent(), 1834 VectorizationReport() << "cannot prove it is safe to reorder " 1835 "floating-point operations"); 1836 Failed = true; 1837 } 1838 1839 // Test if runtime memcheck thresholds are exceeded. 1840 bool PragmaThresholdReached = 1841 NumRuntimePointerChecks > PragmaVectorizeMemoryCheckThreshold; 1842 bool ThresholdReached = 1843 NumRuntimePointerChecks > VectorizerParams::RuntimeMemoryCheckThreshold; 1844 if ((ThresholdReached && !Hints.allowReordering()) || 1845 PragmaThresholdReached) { 1846 ORE.emitOptimizationRemarkAnalysisAliasing( 1847 Name, L, 1848 VectorizationReport() 1849 << "cannot prove it is safe to reorder memory operations"); 1850 DEBUG(dbgs() << "LV: Too many memory checks needed.\n"); 1851 Failed = true; 1852 } 1853 1854 return Failed; 1855 } 1856 1857 private: 1858 unsigned NumRuntimePointerChecks; 1859 Instruction *UnsafeAlgebraInst; 1860 1861 /// Interface to emit optimization remarks. 1862 OptimizationRemarkEmitter &ORE; 1863 }; 1864 1865 static void addAcyclicInnerLoop(Loop &L, SmallVectorImpl<Loop *> &V) { 1866 if (L.empty()) { 1867 if (!hasCyclesInLoopBody(L)) 1868 V.push_back(&L); 1869 return; 1870 } 1871 for (Loop *InnerL : L) 1872 addAcyclicInnerLoop(*InnerL, V); 1873 } 1874 1875 /// The LoopVectorize Pass. 1876 struct LoopVectorize : public FunctionPass { 1877 /// Pass identification, replacement for typeid 1878 static char ID; 1879 1880 explicit LoopVectorize(bool NoUnrolling = false, bool AlwaysVectorize = true) 1881 : FunctionPass(ID) { 1882 Impl.DisableUnrolling = NoUnrolling; 1883 Impl.AlwaysVectorize = AlwaysVectorize; 1884 initializeLoopVectorizePass(*PassRegistry::getPassRegistry()); 1885 } 1886 1887 LoopVectorizePass Impl; 1888 1889 bool runOnFunction(Function &F) override { 1890 if (skipFunction(F)) 1891 return false; 1892 1893 auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE(); 1894 auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 1895 auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F); 1896 auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 1897 auto *BFI = &getAnalysis<BlockFrequencyInfoWrapperPass>().getBFI(); 1898 auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>(); 1899 auto *TLI = TLIP ? &TLIP->getTLI() : nullptr; 1900 auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults(); 1901 auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F); 1902 auto *LAA = &getAnalysis<LoopAccessLegacyAnalysis>(); 1903 auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits(); 1904 auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE(); 1905 1906 std::function<const LoopAccessInfo &(Loop &)> GetLAA = 1907 [&](Loop &L) -> const LoopAccessInfo & { return LAA->getInfo(&L); }; 1908 1909 return Impl.runImpl(F, *SE, *LI, *TTI, *DT, *BFI, TLI, *DB, *AA, *AC, 1910 GetLAA, *ORE); 1911 } 1912 1913 void getAnalysisUsage(AnalysisUsage &AU) const override { 1914 AU.addRequired<AssumptionCacheTracker>(); 1915 AU.addRequiredID(LoopSimplifyID); 1916 AU.addRequiredID(LCSSAID); 1917 AU.addRequired<BlockFrequencyInfoWrapperPass>(); 1918 AU.addRequired<DominatorTreeWrapperPass>(); 1919 AU.addRequired<LoopInfoWrapperPass>(); 1920 AU.addRequired<ScalarEvolutionWrapperPass>(); 1921 AU.addRequired<TargetTransformInfoWrapperPass>(); 1922 AU.addRequired<AAResultsWrapperPass>(); 1923 AU.addRequired<LoopAccessLegacyAnalysis>(); 1924 AU.addRequired<DemandedBitsWrapperPass>(); 1925 AU.addRequired<OptimizationRemarkEmitterWrapperPass>(); 1926 AU.addPreserved<LoopInfoWrapperPass>(); 1927 AU.addPreserved<DominatorTreeWrapperPass>(); 1928 AU.addPreserved<BasicAAWrapperPass>(); 1929 AU.addPreserved<GlobalsAAWrapperPass>(); 1930 } 1931 }; 1932 1933 } // end anonymous namespace 1934 1935 //===----------------------------------------------------------------------===// 1936 // Implementation of LoopVectorizationLegality, InnerLoopVectorizer and 1937 // LoopVectorizationCostModel. 1938 //===----------------------------------------------------------------------===// 1939 1940 Value *InnerLoopVectorizer::getBroadcastInstrs(Value *V) { 1941 // We need to place the broadcast of invariant variables outside the loop. 1942 Instruction *Instr = dyn_cast<Instruction>(V); 1943 bool NewInstr = (Instr && Instr->getParent() == LoopVectorBody); 1944 bool Invariant = OrigLoop->isLoopInvariant(V) && !NewInstr; 1945 1946 // Place the code for broadcasting invariant variables in the new preheader. 1947 IRBuilder<>::InsertPointGuard Guard(Builder); 1948 if (Invariant) 1949 Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator()); 1950 1951 // Broadcast the scalar into all locations in the vector. 1952 Value *Shuf = Builder.CreateVectorSplat(VF, V, "broadcast"); 1953 1954 return Shuf; 1955 } 1956 1957 void InnerLoopVectorizer::createVectorIntInductionPHI( 1958 const InductionDescriptor &II, VectorParts &Entry, IntegerType *TruncType) { 1959 Value *Start = II.getStartValue(); 1960 ConstantInt *Step = II.getConstIntStepValue(); 1961 assert(Step && "Can not widen an IV with a non-constant step"); 1962 1963 // Construct the initial value of the vector IV in the vector loop preheader 1964 auto CurrIP = Builder.saveIP(); 1965 Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator()); 1966 if (TruncType) { 1967 Step = ConstantInt::getSigned(TruncType, Step->getSExtValue()); 1968 Start = Builder.CreateCast(Instruction::Trunc, Start, TruncType); 1969 } 1970 Value *SplatStart = Builder.CreateVectorSplat(VF, Start); 1971 Value *SteppedStart = getStepVector(SplatStart, 0, Step); 1972 Builder.restoreIP(CurrIP); 1973 1974 Value *SplatVF = 1975 ConstantVector::getSplat(VF, ConstantInt::getSigned(Start->getType(), 1976 VF * Step->getSExtValue())); 1977 // We may need to add the step a number of times, depending on the unroll 1978 // factor. The last of those goes into the PHI. 1979 PHINode *VecInd = PHINode::Create(SteppedStart->getType(), 2, "vec.ind", 1980 &*LoopVectorBody->getFirstInsertionPt()); 1981 Instruction *LastInduction = VecInd; 1982 for (unsigned Part = 0; Part < UF; ++Part) { 1983 Entry[Part] = LastInduction; 1984 LastInduction = cast<Instruction>( 1985 Builder.CreateAdd(LastInduction, SplatVF, "step.add")); 1986 } 1987 1988 // Move the last step to the end of the latch block. This ensures consistent 1989 // placement of all induction updates. 1990 auto *LoopVectorLatch = LI->getLoopFor(LoopVectorBody)->getLoopLatch(); 1991 auto *Br = cast<BranchInst>(LoopVectorLatch->getTerminator()); 1992 auto *ICmp = cast<Instruction>(Br->getCondition()); 1993 LastInduction->moveBefore(ICmp); 1994 LastInduction->setName("vec.ind.next"); 1995 1996 VecInd->addIncoming(SteppedStart, LoopVectorPreHeader); 1997 VecInd->addIncoming(LastInduction, LoopVectorLatch); 1998 } 1999 2000 bool InnerLoopVectorizer::needsScalarInduction(Instruction *IV) const { 2001 if (Legal->isScalarAfterVectorization(IV)) 2002 return true; 2003 auto isScalarInst = [&](User *U) -> bool { 2004 auto *I = cast<Instruction>(U); 2005 return (OrigLoop->contains(I) && Legal->isScalarAfterVectorization(I)); 2006 }; 2007 return any_of(IV->users(), isScalarInst); 2008 } 2009 2010 void InnerLoopVectorizer::widenIntInduction(PHINode *IV, VectorParts &Entry, 2011 TruncInst *Trunc) { 2012 2013 auto II = Legal->getInductionVars()->find(IV); 2014 assert(II != Legal->getInductionVars()->end() && "IV is not an induction"); 2015 2016 auto ID = II->second; 2017 assert(IV->getType() == ID.getStartValue()->getType() && "Types must match"); 2018 2019 // If a truncate instruction was provided, get the smaller type. 2020 auto *TruncType = Trunc ? cast<IntegerType>(Trunc->getType()) : nullptr; 2021 2022 // The scalar value to broadcast. This will be derived from the canonical 2023 // induction variable. 2024 Value *ScalarIV = nullptr; 2025 2026 // The step of the induction. 2027 Value *Step = nullptr; 2028 2029 // The value from the original loop to which we are mapping the new induction 2030 // variable. 2031 Instruction *EntryVal = Trunc ? cast<Instruction>(Trunc) : IV; 2032 2033 // True if we have vectorized the induction variable. 2034 auto VectorizedIV = false; 2035 2036 // Determine if we want a scalar version of the induction variable. This is 2037 // true if the induction variable itself is not widened, or if it has at 2038 // least one user in the loop that is not widened. 2039 auto NeedsScalarIV = VF > 1 && needsScalarInduction(EntryVal); 2040 2041 // If the induction variable has a constant integer step value, go ahead and 2042 // get it now. 2043 if (ID.getConstIntStepValue()) 2044 Step = ID.getConstIntStepValue(); 2045 2046 // Try to create a new independent vector induction variable. If we can't 2047 // create the phi node, we will splat the scalar induction variable in each 2048 // loop iteration. 2049 if (VF > 1 && IV->getType() == Induction->getType() && Step && 2050 !Legal->isScalarAfterVectorization(EntryVal)) { 2051 createVectorIntInductionPHI(ID, Entry, TruncType); 2052 VectorizedIV = true; 2053 } 2054 2055 // If we haven't yet vectorized the induction variable, or if we will create 2056 // a scalar one, we need to define the scalar induction variable and step 2057 // values. If we were given a truncation type, truncate the canonical 2058 // induction variable and constant step. Otherwise, derive these values from 2059 // the induction descriptor. 2060 if (!VectorizedIV || NeedsScalarIV) { 2061 if (TruncType) { 2062 assert(Step && "Truncation requires constant integer step"); 2063 auto StepInt = cast<ConstantInt>(Step)->getSExtValue(); 2064 ScalarIV = Builder.CreateCast(Instruction::Trunc, Induction, TruncType); 2065 Step = ConstantInt::getSigned(TruncType, StepInt); 2066 } else { 2067 ScalarIV = Induction; 2068 auto &DL = OrigLoop->getHeader()->getModule()->getDataLayout(); 2069 if (IV != OldInduction) { 2070 ScalarIV = Builder.CreateSExtOrTrunc(ScalarIV, IV->getType()); 2071 ScalarIV = ID.transform(Builder, ScalarIV, PSE.getSE(), DL); 2072 ScalarIV->setName("offset.idx"); 2073 } 2074 if (!Step) { 2075 SCEVExpander Exp(*PSE.getSE(), DL, "induction"); 2076 Step = Exp.expandCodeFor(ID.getStep(), ID.getStep()->getType(), 2077 &*Builder.GetInsertPoint()); 2078 } 2079 } 2080 } 2081 2082 // If we haven't yet vectorized the induction variable, splat the scalar 2083 // induction variable, and build the necessary step vectors. 2084 if (!VectorizedIV) { 2085 Value *Broadcasted = getBroadcastInstrs(ScalarIV); 2086 for (unsigned Part = 0; Part < UF; ++Part) 2087 Entry[Part] = getStepVector(Broadcasted, VF * Part, Step); 2088 } 2089 2090 // If an induction variable is only used for counting loop iterations or 2091 // calculating addresses, it doesn't need to be widened. Create scalar steps 2092 // that can be used by instructions we will later scalarize. Note that the 2093 // addition of the scalar steps will not increase the number of instructions 2094 // in the loop in the common case prior to InstCombine. We will be trading 2095 // one vector extract for each scalar step. 2096 if (NeedsScalarIV) 2097 buildScalarSteps(ScalarIV, Step, EntryVal); 2098 } 2099 2100 Value *InnerLoopVectorizer::getStepVector(Value *Val, int StartIdx, Value *Step, 2101 Instruction::BinaryOps BinOp) { 2102 // Create and check the types. 2103 assert(Val->getType()->isVectorTy() && "Must be a vector"); 2104 int VLen = Val->getType()->getVectorNumElements(); 2105 2106 Type *STy = Val->getType()->getScalarType(); 2107 assert((STy->isIntegerTy() || STy->isFloatingPointTy()) && 2108 "Induction Step must be an integer or FP"); 2109 assert(Step->getType() == STy && "Step has wrong type"); 2110 2111 SmallVector<Constant *, 8> Indices; 2112 2113 if (STy->isIntegerTy()) { 2114 // Create a vector of consecutive numbers from zero to VF. 2115 for (int i = 0; i < VLen; ++i) 2116 Indices.push_back(ConstantInt::get(STy, StartIdx + i)); 2117 2118 // Add the consecutive indices to the vector value. 2119 Constant *Cv = ConstantVector::get(Indices); 2120 assert(Cv->getType() == Val->getType() && "Invalid consecutive vec"); 2121 Step = Builder.CreateVectorSplat(VLen, Step); 2122 assert(Step->getType() == Val->getType() && "Invalid step vec"); 2123 // FIXME: The newly created binary instructions should contain nsw/nuw flags, 2124 // which can be found from the original scalar operations. 2125 Step = Builder.CreateMul(Cv, Step); 2126 return Builder.CreateAdd(Val, Step, "induction"); 2127 } 2128 2129 // Floating point induction. 2130 assert((BinOp == Instruction::FAdd || BinOp == Instruction::FSub) && 2131 "Binary Opcode should be specified for FP induction"); 2132 // Create a vector of consecutive numbers from zero to VF. 2133 for (int i = 0; i < VLen; ++i) 2134 Indices.push_back(ConstantFP::get(STy, (double)(StartIdx + i))); 2135 2136 // Add the consecutive indices to the vector value. 2137 Constant *Cv = ConstantVector::get(Indices); 2138 2139 Step = Builder.CreateVectorSplat(VLen, Step); 2140 2141 // Floating point operations had to be 'fast' to enable the induction. 2142 FastMathFlags Flags; 2143 Flags.setUnsafeAlgebra(); 2144 2145 Value *MulOp = Builder.CreateFMul(Cv, Step); 2146 if (isa<Instruction>(MulOp)) 2147 // Have to check, MulOp may be a constant 2148 cast<Instruction>(MulOp)->setFastMathFlags(Flags); 2149 2150 Value *BOp = Builder.CreateBinOp(BinOp, Val, MulOp, "induction"); 2151 if (isa<Instruction>(BOp)) 2152 cast<Instruction>(BOp)->setFastMathFlags(Flags); 2153 return BOp; 2154 } 2155 2156 void InnerLoopVectorizer::buildScalarSteps(Value *ScalarIV, Value *Step, 2157 Value *EntryVal) { 2158 2159 // We shouldn't have to build scalar steps if we aren't vectorizing. 2160 assert(VF > 1 && "VF should be greater than one"); 2161 2162 // Get the value type and ensure it and the step have the same integer type. 2163 Type *ScalarIVTy = ScalarIV->getType()->getScalarType(); 2164 assert(ScalarIVTy->isIntegerTy() && ScalarIVTy == Step->getType() && 2165 "Val and Step should have the same integer type"); 2166 2167 // Compute the scalar steps and save the results in ScalarIVMap. 2168 for (unsigned Part = 0; Part < UF; ++Part) 2169 for (unsigned I = 0; I < VF; ++I) { 2170 auto *StartIdx = ConstantInt::get(ScalarIVTy, VF * Part + I); 2171 auto *Mul = Builder.CreateMul(StartIdx, Step); 2172 auto *Add = Builder.CreateAdd(ScalarIV, Mul); 2173 ScalarIVMap[EntryVal].push_back(Add); 2174 } 2175 } 2176 2177 int LoopVectorizationLegality::isConsecutivePtr(Value *Ptr) { 2178 assert(Ptr->getType()->isPointerTy() && "Unexpected non-ptr"); 2179 auto *SE = PSE.getSE(); 2180 // Make sure that the pointer does not point to structs. 2181 if (Ptr->getType()->getPointerElementType()->isAggregateType()) 2182 return 0; 2183 2184 // If this value is a pointer induction variable, we know it is consecutive. 2185 PHINode *Phi = dyn_cast_or_null<PHINode>(Ptr); 2186 if (Phi && Inductions.count(Phi)) { 2187 InductionDescriptor II = Inductions[Phi]; 2188 return II.getConsecutiveDirection(); 2189 } 2190 2191 GetElementPtrInst *Gep = getGEPInstruction(Ptr); 2192 if (!Gep) 2193 return 0; 2194 2195 unsigned NumOperands = Gep->getNumOperands(); 2196 Value *GpPtr = Gep->getPointerOperand(); 2197 // If this GEP value is a consecutive pointer induction variable and all of 2198 // the indices are constant, then we know it is consecutive. 2199 Phi = dyn_cast<PHINode>(GpPtr); 2200 if (Phi && Inductions.count(Phi)) { 2201 2202 // Make sure that the pointer does not point to structs. 2203 PointerType *GepPtrType = cast<PointerType>(GpPtr->getType()); 2204 if (GepPtrType->getElementType()->isAggregateType()) 2205 return 0; 2206 2207 // Make sure that all of the index operands are loop invariant. 2208 for (unsigned i = 1; i < NumOperands; ++i) 2209 if (!SE->isLoopInvariant(PSE.getSCEV(Gep->getOperand(i)), TheLoop)) 2210 return 0; 2211 2212 InductionDescriptor II = Inductions[Phi]; 2213 return II.getConsecutiveDirection(); 2214 } 2215 2216 unsigned InductionOperand = getGEPInductionOperand(Gep); 2217 2218 // Check that all of the gep indices are uniform except for our induction 2219 // operand. 2220 for (unsigned i = 0; i != NumOperands; ++i) 2221 if (i != InductionOperand && 2222 !SE->isLoopInvariant(PSE.getSCEV(Gep->getOperand(i)), TheLoop)) 2223 return 0; 2224 2225 // We can emit wide load/stores only if the last non-zero index is the 2226 // induction variable. 2227 const SCEV *Last = nullptr; 2228 if (!getSymbolicStrides() || !getSymbolicStrides()->count(Gep)) 2229 Last = PSE.getSCEV(Gep->getOperand(InductionOperand)); 2230 else { 2231 // Because of the multiplication by a stride we can have a s/zext cast. 2232 // We are going to replace this stride by 1 so the cast is safe to ignore. 2233 // 2234 // %indvars.iv = phi i64 [ 0, %entry ], [ %indvars.iv.next, %for.body ] 2235 // %0 = trunc i64 %indvars.iv to i32 2236 // %mul = mul i32 %0, %Stride1 2237 // %idxprom = zext i32 %mul to i64 << Safe cast. 2238 // %arrayidx = getelementptr inbounds i32* %B, i64 %idxprom 2239 // 2240 Last = replaceSymbolicStrideSCEV(PSE, *getSymbolicStrides(), 2241 Gep->getOperand(InductionOperand), Gep); 2242 if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(Last)) 2243 Last = 2244 (C->getSCEVType() == scSignExtend || C->getSCEVType() == scZeroExtend) 2245 ? C->getOperand() 2246 : Last; 2247 } 2248 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Last)) { 2249 const SCEV *Step = AR->getStepRecurrence(*SE); 2250 2251 // The memory is consecutive because the last index is consecutive 2252 // and all other indices are loop invariant. 2253 if (Step->isOne()) 2254 return 1; 2255 if (Step->isAllOnesValue()) 2256 return -1; 2257 } 2258 2259 return 0; 2260 } 2261 2262 bool LoopVectorizationLegality::isUniform(Value *V) { 2263 return LAI->isUniform(V); 2264 } 2265 2266 InnerLoopVectorizer::VectorParts & 2267 InnerLoopVectorizer::getVectorValue(Value *V) { 2268 assert(V != Induction && "The new induction variable should not be used."); 2269 assert(!V->getType()->isVectorTy() && "Can't widen a vector"); 2270 2271 // If we have a stride that is replaced by one, do it here. 2272 if (Legal->hasStride(V)) 2273 V = ConstantInt::get(V->getType(), 1); 2274 2275 // If we have this scalar in the map, return it. 2276 if (WidenMap.has(V)) 2277 return WidenMap.get(V); 2278 2279 // If this scalar is unknown, assume that it is a constant or that it is 2280 // loop invariant. Broadcast V and save the value for future uses. 2281 Value *B = getBroadcastInstrs(V); 2282 return WidenMap.splat(V, B); 2283 } 2284 2285 Value *InnerLoopVectorizer::reverseVector(Value *Vec) { 2286 assert(Vec->getType()->isVectorTy() && "Invalid type"); 2287 SmallVector<Constant *, 8> ShuffleMask; 2288 for (unsigned i = 0; i < VF; ++i) 2289 ShuffleMask.push_back(Builder.getInt32(VF - i - 1)); 2290 2291 return Builder.CreateShuffleVector(Vec, UndefValue::get(Vec->getType()), 2292 ConstantVector::get(ShuffleMask), 2293 "reverse"); 2294 } 2295 2296 // Get a mask to interleave \p NumVec vectors into a wide vector. 2297 // I.e. <0, VF, VF*2, ..., VF*(NumVec-1), 1, VF+1, VF*2+1, ...> 2298 // E.g. For 2 interleaved vectors, if VF is 4, the mask is: 2299 // <0, 4, 1, 5, 2, 6, 3, 7> 2300 static Constant *getInterleavedMask(IRBuilder<> &Builder, unsigned VF, 2301 unsigned NumVec) { 2302 SmallVector<Constant *, 16> Mask; 2303 for (unsigned i = 0; i < VF; i++) 2304 for (unsigned j = 0; j < NumVec; j++) 2305 Mask.push_back(Builder.getInt32(j * VF + i)); 2306 2307 return ConstantVector::get(Mask); 2308 } 2309 2310 // Get the strided mask starting from index \p Start. 2311 // I.e. <Start, Start + Stride, ..., Start + Stride*(VF-1)> 2312 static Constant *getStridedMask(IRBuilder<> &Builder, unsigned Start, 2313 unsigned Stride, unsigned VF) { 2314 SmallVector<Constant *, 16> Mask; 2315 for (unsigned i = 0; i < VF; i++) 2316 Mask.push_back(Builder.getInt32(Start + i * Stride)); 2317 2318 return ConstantVector::get(Mask); 2319 } 2320 2321 // Get a mask of two parts: The first part consists of sequential integers 2322 // starting from 0, The second part consists of UNDEFs. 2323 // I.e. <0, 1, 2, ..., NumInt - 1, undef, ..., undef> 2324 static Constant *getSequentialMask(IRBuilder<> &Builder, unsigned NumInt, 2325 unsigned NumUndef) { 2326 SmallVector<Constant *, 16> Mask; 2327 for (unsigned i = 0; i < NumInt; i++) 2328 Mask.push_back(Builder.getInt32(i)); 2329 2330 Constant *Undef = UndefValue::get(Builder.getInt32Ty()); 2331 for (unsigned i = 0; i < NumUndef; i++) 2332 Mask.push_back(Undef); 2333 2334 return ConstantVector::get(Mask); 2335 } 2336 2337 // Concatenate two vectors with the same element type. The 2nd vector should 2338 // not have more elements than the 1st vector. If the 2nd vector has less 2339 // elements, extend it with UNDEFs. 2340 static Value *ConcatenateTwoVectors(IRBuilder<> &Builder, Value *V1, 2341 Value *V2) { 2342 VectorType *VecTy1 = dyn_cast<VectorType>(V1->getType()); 2343 VectorType *VecTy2 = dyn_cast<VectorType>(V2->getType()); 2344 assert(VecTy1 && VecTy2 && 2345 VecTy1->getScalarType() == VecTy2->getScalarType() && 2346 "Expect two vectors with the same element type"); 2347 2348 unsigned NumElts1 = VecTy1->getNumElements(); 2349 unsigned NumElts2 = VecTy2->getNumElements(); 2350 assert(NumElts1 >= NumElts2 && "Unexpect the first vector has less elements"); 2351 2352 if (NumElts1 > NumElts2) { 2353 // Extend with UNDEFs. 2354 Constant *ExtMask = 2355 getSequentialMask(Builder, NumElts2, NumElts1 - NumElts2); 2356 V2 = Builder.CreateShuffleVector(V2, UndefValue::get(VecTy2), ExtMask); 2357 } 2358 2359 Constant *Mask = getSequentialMask(Builder, NumElts1 + NumElts2, 0); 2360 return Builder.CreateShuffleVector(V1, V2, Mask); 2361 } 2362 2363 // Concatenate vectors in the given list. All vectors have the same type. 2364 static Value *ConcatenateVectors(IRBuilder<> &Builder, 2365 ArrayRef<Value *> InputList) { 2366 unsigned NumVec = InputList.size(); 2367 assert(NumVec > 1 && "Should be at least two vectors"); 2368 2369 SmallVector<Value *, 8> ResList; 2370 ResList.append(InputList.begin(), InputList.end()); 2371 do { 2372 SmallVector<Value *, 8> TmpList; 2373 for (unsigned i = 0; i < NumVec - 1; i += 2) { 2374 Value *V0 = ResList[i], *V1 = ResList[i + 1]; 2375 assert((V0->getType() == V1->getType() || i == NumVec - 2) && 2376 "Only the last vector may have a different type"); 2377 2378 TmpList.push_back(ConcatenateTwoVectors(Builder, V0, V1)); 2379 } 2380 2381 // Push the last vector if the total number of vectors is odd. 2382 if (NumVec % 2 != 0) 2383 TmpList.push_back(ResList[NumVec - 1]); 2384 2385 ResList = TmpList; 2386 NumVec = ResList.size(); 2387 } while (NumVec > 1); 2388 2389 return ResList[0]; 2390 } 2391 2392 // Try to vectorize the interleave group that \p Instr belongs to. 2393 // 2394 // E.g. Translate following interleaved load group (factor = 3): 2395 // for (i = 0; i < N; i+=3) { 2396 // R = Pic[i]; // Member of index 0 2397 // G = Pic[i+1]; // Member of index 1 2398 // B = Pic[i+2]; // Member of index 2 2399 // ... // do something to R, G, B 2400 // } 2401 // To: 2402 // %wide.vec = load <12 x i32> ; Read 4 tuples of R,G,B 2403 // %R.vec = shuffle %wide.vec, undef, <0, 3, 6, 9> ; R elements 2404 // %G.vec = shuffle %wide.vec, undef, <1, 4, 7, 10> ; G elements 2405 // %B.vec = shuffle %wide.vec, undef, <2, 5, 8, 11> ; B elements 2406 // 2407 // Or translate following interleaved store group (factor = 3): 2408 // for (i = 0; i < N; i+=3) { 2409 // ... do something to R, G, B 2410 // Pic[i] = R; // Member of index 0 2411 // Pic[i+1] = G; // Member of index 1 2412 // Pic[i+2] = B; // Member of index 2 2413 // } 2414 // To: 2415 // %R_G.vec = shuffle %R.vec, %G.vec, <0, 1, 2, ..., 7> 2416 // %B_U.vec = shuffle %B.vec, undef, <0, 1, 2, 3, u, u, u, u> 2417 // %interleaved.vec = shuffle %R_G.vec, %B_U.vec, 2418 // <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11> ; Interleave R,G,B elements 2419 // store <12 x i32> %interleaved.vec ; Write 4 tuples of R,G,B 2420 void InnerLoopVectorizer::vectorizeInterleaveGroup(Instruction *Instr) { 2421 const InterleaveGroup *Group = Legal->getInterleavedAccessGroup(Instr); 2422 assert(Group && "Fail to get an interleaved access group."); 2423 2424 // Skip if current instruction is not the insert position. 2425 if (Instr != Group->getInsertPos()) 2426 return; 2427 2428 LoadInst *LI = dyn_cast<LoadInst>(Instr); 2429 StoreInst *SI = dyn_cast<StoreInst>(Instr); 2430 Value *Ptr = getPointerOperand(Instr); 2431 2432 // Prepare for the vector type of the interleaved load/store. 2433 Type *ScalarTy = LI ? LI->getType() : SI->getValueOperand()->getType(); 2434 unsigned InterleaveFactor = Group->getFactor(); 2435 Type *VecTy = VectorType::get(ScalarTy, InterleaveFactor * VF); 2436 Type *PtrTy = VecTy->getPointerTo(Ptr->getType()->getPointerAddressSpace()); 2437 2438 // Prepare for the new pointers. 2439 setDebugLocFromInst(Builder, Ptr); 2440 VectorParts &PtrParts = getVectorValue(Ptr); 2441 SmallVector<Value *, 2> NewPtrs; 2442 unsigned Index = Group->getIndex(Instr); 2443 for (unsigned Part = 0; Part < UF; Part++) { 2444 // Extract the pointer for current instruction from the pointer vector. A 2445 // reverse access uses the pointer in the last lane. 2446 Value *NewPtr = Builder.CreateExtractElement( 2447 PtrParts[Part], 2448 Group->isReverse() ? Builder.getInt32(VF - 1) : Builder.getInt32(0)); 2449 2450 // Notice current instruction could be any index. Need to adjust the address 2451 // to the member of index 0. 2452 // 2453 // E.g. a = A[i+1]; // Member of index 1 (Current instruction) 2454 // b = A[i]; // Member of index 0 2455 // Current pointer is pointed to A[i+1], adjust it to A[i]. 2456 // 2457 // E.g. A[i+1] = a; // Member of index 1 2458 // A[i] = b; // Member of index 0 2459 // A[i+2] = c; // Member of index 2 (Current instruction) 2460 // Current pointer is pointed to A[i+2], adjust it to A[i]. 2461 NewPtr = Builder.CreateGEP(NewPtr, Builder.getInt32(-Index)); 2462 2463 // Cast to the vector pointer type. 2464 NewPtrs.push_back(Builder.CreateBitCast(NewPtr, PtrTy)); 2465 } 2466 2467 setDebugLocFromInst(Builder, Instr); 2468 Value *UndefVec = UndefValue::get(VecTy); 2469 2470 // Vectorize the interleaved load group. 2471 if (LI) { 2472 for (unsigned Part = 0; Part < UF; Part++) { 2473 Instruction *NewLoadInstr = Builder.CreateAlignedLoad( 2474 NewPtrs[Part], Group->getAlignment(), "wide.vec"); 2475 2476 for (unsigned i = 0; i < InterleaveFactor; i++) { 2477 Instruction *Member = Group->getMember(i); 2478 2479 // Skip the gaps in the group. 2480 if (!Member) 2481 continue; 2482 2483 Constant *StrideMask = getStridedMask(Builder, i, InterleaveFactor, VF); 2484 Value *StridedVec = Builder.CreateShuffleVector( 2485 NewLoadInstr, UndefVec, StrideMask, "strided.vec"); 2486 2487 // If this member has different type, cast the result type. 2488 if (Member->getType() != ScalarTy) { 2489 VectorType *OtherVTy = VectorType::get(Member->getType(), VF); 2490 StridedVec = Builder.CreateBitOrPointerCast(StridedVec, OtherVTy); 2491 } 2492 2493 VectorParts &Entry = WidenMap.get(Member); 2494 Entry[Part] = 2495 Group->isReverse() ? reverseVector(StridedVec) : StridedVec; 2496 } 2497 2498 addMetadata(NewLoadInstr, Instr); 2499 } 2500 return; 2501 } 2502 2503 // The sub vector type for current instruction. 2504 VectorType *SubVT = VectorType::get(ScalarTy, VF); 2505 2506 // Vectorize the interleaved store group. 2507 for (unsigned Part = 0; Part < UF; Part++) { 2508 // Collect the stored vector from each member. 2509 SmallVector<Value *, 4> StoredVecs; 2510 for (unsigned i = 0; i < InterleaveFactor; i++) { 2511 // Interleaved store group doesn't allow a gap, so each index has a member 2512 Instruction *Member = Group->getMember(i); 2513 assert(Member && "Fail to get a member from an interleaved store group"); 2514 2515 Value *StoredVec = 2516 getVectorValue(cast<StoreInst>(Member)->getValueOperand())[Part]; 2517 if (Group->isReverse()) 2518 StoredVec = reverseVector(StoredVec); 2519 2520 // If this member has different type, cast it to an unified type. 2521 if (StoredVec->getType() != SubVT) 2522 StoredVec = Builder.CreateBitOrPointerCast(StoredVec, SubVT); 2523 2524 StoredVecs.push_back(StoredVec); 2525 } 2526 2527 // Concatenate all vectors into a wide vector. 2528 Value *WideVec = ConcatenateVectors(Builder, StoredVecs); 2529 2530 // Interleave the elements in the wide vector. 2531 Constant *IMask = getInterleavedMask(Builder, VF, InterleaveFactor); 2532 Value *IVec = Builder.CreateShuffleVector(WideVec, UndefVec, IMask, 2533 "interleaved.vec"); 2534 2535 Instruction *NewStoreInstr = 2536 Builder.CreateAlignedStore(IVec, NewPtrs[Part], Group->getAlignment()); 2537 addMetadata(NewStoreInstr, Instr); 2538 } 2539 } 2540 2541 void InnerLoopVectorizer::vectorizeMemoryInstruction(Instruction *Instr) { 2542 // Attempt to issue a wide load. 2543 LoadInst *LI = dyn_cast<LoadInst>(Instr); 2544 StoreInst *SI = dyn_cast<StoreInst>(Instr); 2545 2546 assert((LI || SI) && "Invalid Load/Store instruction"); 2547 2548 // Try to vectorize the interleave group if this access is interleaved. 2549 if (Legal->isAccessInterleaved(Instr)) 2550 return vectorizeInterleaveGroup(Instr); 2551 2552 Type *ScalarDataTy = LI ? LI->getType() : SI->getValueOperand()->getType(); 2553 Type *DataTy = VectorType::get(ScalarDataTy, VF); 2554 Value *Ptr = getPointerOperand(Instr); 2555 unsigned Alignment = LI ? LI->getAlignment() : SI->getAlignment(); 2556 // An alignment of 0 means target abi alignment. We need to use the scalar's 2557 // target abi alignment in such a case. 2558 const DataLayout &DL = Instr->getModule()->getDataLayout(); 2559 if (!Alignment) 2560 Alignment = DL.getABITypeAlignment(ScalarDataTy); 2561 unsigned AddressSpace = Ptr->getType()->getPointerAddressSpace(); 2562 uint64_t ScalarAllocatedSize = DL.getTypeAllocSize(ScalarDataTy); 2563 uint64_t VectorElementSize = DL.getTypeStoreSize(DataTy) / VF; 2564 2565 if (SI && Legal->blockNeedsPredication(SI->getParent()) && 2566 !Legal->isMaskRequired(SI)) 2567 return scalarizeInstruction(Instr, true); 2568 2569 if (ScalarAllocatedSize != VectorElementSize) 2570 return scalarizeInstruction(Instr); 2571 2572 // If the pointer is loop invariant scalarize the load. 2573 if (LI && Legal->isUniform(Ptr)) 2574 return scalarizeInstruction(Instr); 2575 2576 // If the pointer is non-consecutive and gather/scatter is not supported 2577 // scalarize the instruction. 2578 int ConsecutiveStride = Legal->isConsecutivePtr(Ptr); 2579 bool Reverse = ConsecutiveStride < 0; 2580 bool CreateGatherScatter = 2581 !ConsecutiveStride && ((LI && Legal->isLegalMaskedGather(ScalarDataTy)) || 2582 (SI && Legal->isLegalMaskedScatter(ScalarDataTy))); 2583 2584 if (!ConsecutiveStride && !CreateGatherScatter) 2585 return scalarizeInstruction(Instr); 2586 2587 Constant *Zero = Builder.getInt32(0); 2588 VectorParts &Entry = WidenMap.get(Instr); 2589 VectorParts VectorGep; 2590 2591 // Handle consecutive loads/stores. 2592 GetElementPtrInst *Gep = getGEPInstruction(Ptr); 2593 if (ConsecutiveStride) { 2594 if (Gep && Legal->isInductionVariable(Gep->getPointerOperand())) { 2595 setDebugLocFromInst(Builder, Gep); 2596 Value *PtrOperand = Gep->getPointerOperand(); 2597 Value *FirstBasePtr = getVectorValue(PtrOperand)[0]; 2598 FirstBasePtr = Builder.CreateExtractElement(FirstBasePtr, Zero); 2599 2600 // Create the new GEP with the new induction variable. 2601 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone()); 2602 Gep2->setOperand(0, FirstBasePtr); 2603 Gep2->setName("gep.indvar.base"); 2604 Ptr = Builder.Insert(Gep2); 2605 } else if (Gep) { 2606 setDebugLocFromInst(Builder, Gep); 2607 assert(PSE.getSE()->isLoopInvariant(PSE.getSCEV(Gep->getPointerOperand()), 2608 OrigLoop) && 2609 "Base ptr must be invariant"); 2610 // The last index does not have to be the induction. It can be 2611 // consecutive and be a function of the index. For example A[I+1]; 2612 unsigned NumOperands = Gep->getNumOperands(); 2613 unsigned InductionOperand = getGEPInductionOperand(Gep); 2614 // Create the new GEP with the new induction variable. 2615 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone()); 2616 2617 for (unsigned i = 0; i < NumOperands; ++i) { 2618 Value *GepOperand = Gep->getOperand(i); 2619 Instruction *GepOperandInst = dyn_cast<Instruction>(GepOperand); 2620 2621 // Update last index or loop invariant instruction anchored in loop. 2622 if (i == InductionOperand || 2623 (GepOperandInst && OrigLoop->contains(GepOperandInst))) { 2624 assert((i == InductionOperand || 2625 PSE.getSE()->isLoopInvariant(PSE.getSCEV(GepOperandInst), 2626 OrigLoop)) && 2627 "Must be last index or loop invariant"); 2628 2629 VectorParts &GEPParts = getVectorValue(GepOperand); 2630 2631 // If GepOperand is an induction variable, and there's a scalarized 2632 // version of it available, use it. Otherwise, we will need to create 2633 // an extractelement instruction. 2634 Value *Index = ScalarIVMap.count(GepOperand) 2635 ? ScalarIVMap[GepOperand][0] 2636 : Builder.CreateExtractElement(GEPParts[0], Zero); 2637 2638 Gep2->setOperand(i, Index); 2639 Gep2->setName("gep.indvar.idx"); 2640 } 2641 } 2642 Ptr = Builder.Insert(Gep2); 2643 } else { // No GEP 2644 // Use the induction element ptr. 2645 assert(isa<PHINode>(Ptr) && "Invalid induction ptr"); 2646 setDebugLocFromInst(Builder, Ptr); 2647 VectorParts &PtrVal = getVectorValue(Ptr); 2648 Ptr = Builder.CreateExtractElement(PtrVal[0], Zero); 2649 } 2650 } else { 2651 // At this point we should vector version of GEP for Gather or Scatter 2652 assert(CreateGatherScatter && "The instruction should be scalarized"); 2653 if (Gep) { 2654 // Vectorizing GEP, across UF parts. We want to get a vector value for base 2655 // and each index that's defined inside the loop, even if it is 2656 // loop-invariant but wasn't hoisted out. Otherwise we want to keep them 2657 // scalar. 2658 SmallVector<VectorParts, 4> OpsV; 2659 for (Value *Op : Gep->operands()) { 2660 Instruction *SrcInst = dyn_cast<Instruction>(Op); 2661 if (SrcInst && OrigLoop->contains(SrcInst)) 2662 OpsV.push_back(getVectorValue(Op)); 2663 else 2664 OpsV.push_back(VectorParts(UF, Op)); 2665 } 2666 for (unsigned Part = 0; Part < UF; ++Part) { 2667 SmallVector<Value *, 4> Ops; 2668 Value *GEPBasePtr = OpsV[0][Part]; 2669 for (unsigned i = 1; i < Gep->getNumOperands(); i++) 2670 Ops.push_back(OpsV[i][Part]); 2671 Value *NewGep = Builder.CreateGEP(GEPBasePtr, Ops, "VectorGep"); 2672 cast<GetElementPtrInst>(NewGep)->setIsInBounds(Gep->isInBounds()); 2673 assert(NewGep->getType()->isVectorTy() && "Expected vector GEP"); 2674 2675 NewGep = 2676 Builder.CreateBitCast(NewGep, VectorType::get(Ptr->getType(), VF)); 2677 VectorGep.push_back(NewGep); 2678 } 2679 } else 2680 VectorGep = getVectorValue(Ptr); 2681 } 2682 2683 VectorParts Mask = createBlockInMask(Instr->getParent()); 2684 // Handle Stores: 2685 if (SI) { 2686 assert(!Legal->isUniform(SI->getPointerOperand()) && 2687 "We do not allow storing to uniform addresses"); 2688 setDebugLocFromInst(Builder, SI); 2689 // We don't want to update the value in the map as it might be used in 2690 // another expression. So don't use a reference type for "StoredVal". 2691 VectorParts StoredVal = getVectorValue(SI->getValueOperand()); 2692 2693 for (unsigned Part = 0; Part < UF; ++Part) { 2694 Instruction *NewSI = nullptr; 2695 if (CreateGatherScatter) { 2696 Value *MaskPart = Legal->isMaskRequired(SI) ? Mask[Part] : nullptr; 2697 NewSI = Builder.CreateMaskedScatter(StoredVal[Part], VectorGep[Part], 2698 Alignment, MaskPart); 2699 } else { 2700 // Calculate the pointer for the specific unroll-part. 2701 Value *PartPtr = 2702 Builder.CreateGEP(nullptr, Ptr, Builder.getInt32(Part * VF)); 2703 2704 if (Reverse) { 2705 // If we store to reverse consecutive memory locations, then we need 2706 // to reverse the order of elements in the stored value. 2707 StoredVal[Part] = reverseVector(StoredVal[Part]); 2708 // If the address is consecutive but reversed, then the 2709 // wide store needs to start at the last vector element. 2710 PartPtr = 2711 Builder.CreateGEP(nullptr, Ptr, Builder.getInt32(-Part * VF)); 2712 PartPtr = 2713 Builder.CreateGEP(nullptr, PartPtr, Builder.getInt32(1 - VF)); 2714 Mask[Part] = reverseVector(Mask[Part]); 2715 } 2716 2717 Value *VecPtr = 2718 Builder.CreateBitCast(PartPtr, DataTy->getPointerTo(AddressSpace)); 2719 2720 if (Legal->isMaskRequired(SI)) 2721 NewSI = Builder.CreateMaskedStore(StoredVal[Part], VecPtr, Alignment, 2722 Mask[Part]); 2723 else 2724 NewSI = 2725 Builder.CreateAlignedStore(StoredVal[Part], VecPtr, Alignment); 2726 } 2727 addMetadata(NewSI, SI); 2728 } 2729 return; 2730 } 2731 2732 // Handle loads. 2733 assert(LI && "Must have a load instruction"); 2734 setDebugLocFromInst(Builder, LI); 2735 for (unsigned Part = 0; Part < UF; ++Part) { 2736 Instruction *NewLI; 2737 if (CreateGatherScatter) { 2738 Value *MaskPart = Legal->isMaskRequired(LI) ? Mask[Part] : nullptr; 2739 NewLI = Builder.CreateMaskedGather(VectorGep[Part], Alignment, MaskPart, 2740 0, "wide.masked.gather"); 2741 Entry[Part] = NewLI; 2742 } else { 2743 // Calculate the pointer for the specific unroll-part. 2744 Value *PartPtr = 2745 Builder.CreateGEP(nullptr, Ptr, Builder.getInt32(Part * VF)); 2746 2747 if (Reverse) { 2748 // If the address is consecutive but reversed, then the 2749 // wide load needs to start at the last vector element. 2750 PartPtr = Builder.CreateGEP(nullptr, Ptr, Builder.getInt32(-Part * VF)); 2751 PartPtr = Builder.CreateGEP(nullptr, PartPtr, Builder.getInt32(1 - VF)); 2752 Mask[Part] = reverseVector(Mask[Part]); 2753 } 2754 2755 Value *VecPtr = 2756 Builder.CreateBitCast(PartPtr, DataTy->getPointerTo(AddressSpace)); 2757 if (Legal->isMaskRequired(LI)) 2758 NewLI = Builder.CreateMaskedLoad(VecPtr, Alignment, Mask[Part], 2759 UndefValue::get(DataTy), 2760 "wide.masked.load"); 2761 else 2762 NewLI = Builder.CreateAlignedLoad(VecPtr, Alignment, "wide.load"); 2763 Entry[Part] = Reverse ? reverseVector(NewLI) : NewLI; 2764 } 2765 addMetadata(NewLI, LI); 2766 } 2767 } 2768 2769 void InnerLoopVectorizer::scalarizeInstruction(Instruction *Instr, 2770 bool IfPredicateStore) { 2771 assert(!Instr->getType()->isAggregateType() && "Can't handle vectors"); 2772 // Holds vector parameters or scalars, in case of uniform vals. 2773 SmallVector<VectorParts, 4> Params; 2774 2775 setDebugLocFromInst(Builder, Instr); 2776 2777 // Find all of the vectorized parameters. 2778 for (Value *SrcOp : Instr->operands()) { 2779 // If we are accessing the old induction variable, use the new one. 2780 if (SrcOp == OldInduction) { 2781 Params.push_back(getVectorValue(SrcOp)); 2782 continue; 2783 } 2784 2785 // Try using previously calculated values. 2786 auto *SrcInst = dyn_cast<Instruction>(SrcOp); 2787 2788 // If the src is an instruction that appeared earlier in the basic block, 2789 // then it should already be vectorized. 2790 if (SrcInst && OrigLoop->contains(SrcInst)) { 2791 assert(WidenMap.has(SrcInst) && "Source operand is unavailable"); 2792 // The parameter is a vector value from earlier. 2793 Params.push_back(WidenMap.get(SrcInst)); 2794 } else { 2795 // The parameter is a scalar from outside the loop. Maybe even a constant. 2796 VectorParts Scalars; 2797 Scalars.append(UF, SrcOp); 2798 Params.push_back(Scalars); 2799 } 2800 } 2801 2802 assert(Params.size() == Instr->getNumOperands() && 2803 "Invalid number of operands"); 2804 2805 // Does this instruction return a value ? 2806 bool IsVoidRetTy = Instr->getType()->isVoidTy(); 2807 2808 Value *UndefVec = 2809 IsVoidRetTy ? nullptr 2810 : UndefValue::get(VectorType::get(Instr->getType(), VF)); 2811 // Create a new entry in the WidenMap and initialize it to Undef or Null. 2812 VectorParts &VecResults = WidenMap.splat(Instr, UndefVec); 2813 2814 VectorParts Cond; 2815 if (IfPredicateStore) { 2816 assert(Instr->getParent()->getSinglePredecessor() && 2817 "Only support single predecessor blocks"); 2818 Cond = createEdgeMask(Instr->getParent()->getSinglePredecessor(), 2819 Instr->getParent()); 2820 } 2821 2822 // For each vector unroll 'part': 2823 for (unsigned Part = 0; Part < UF; ++Part) { 2824 // For each scalar that we create: 2825 for (unsigned Width = 0; Width < VF; ++Width) { 2826 2827 // Start if-block. 2828 Value *Cmp = nullptr; 2829 if (IfPredicateStore) { 2830 Cmp = Builder.CreateExtractElement(Cond[Part], Builder.getInt32(Width)); 2831 Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Cmp, 2832 ConstantInt::get(Cmp->getType(), 1)); 2833 } 2834 2835 Instruction *Cloned = Instr->clone(); 2836 if (!IsVoidRetTy) 2837 Cloned->setName(Instr->getName() + ".cloned"); 2838 // Replace the operands of the cloned instructions with extracted scalars. 2839 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) { 2840 2841 // If the operand is an induction variable, and there's a scalarized 2842 // version of it available, use it. Otherwise, we will need to create 2843 // an extractelement instruction if vectorizing. 2844 auto *NewOp = Params[op][Part]; 2845 auto *ScalarOp = Instr->getOperand(op); 2846 if (ScalarIVMap.count(ScalarOp)) 2847 NewOp = ScalarIVMap[ScalarOp][VF * Part + Width]; 2848 else if (NewOp->getType()->isVectorTy()) 2849 NewOp = Builder.CreateExtractElement(NewOp, Builder.getInt32(Width)); 2850 Cloned->setOperand(op, NewOp); 2851 } 2852 addNewMetadata(Cloned, Instr); 2853 2854 // Place the cloned scalar in the new loop. 2855 Builder.Insert(Cloned); 2856 2857 // If we just cloned a new assumption, add it the assumption cache. 2858 if (auto *II = dyn_cast<IntrinsicInst>(Cloned)) 2859 if (II->getIntrinsicID() == Intrinsic::assume) 2860 AC->registerAssumption(II); 2861 2862 // If the original scalar returns a value we need to place it in a vector 2863 // so that future users will be able to use it. 2864 if (!IsVoidRetTy) 2865 VecResults[Part] = Builder.CreateInsertElement(VecResults[Part], Cloned, 2866 Builder.getInt32(Width)); 2867 // End if-block. 2868 if (IfPredicateStore) 2869 PredicatedStores.push_back( 2870 std::make_pair(cast<StoreInst>(Cloned), Cmp)); 2871 } 2872 } 2873 } 2874 2875 PHINode *InnerLoopVectorizer::createInductionVariable(Loop *L, Value *Start, 2876 Value *End, Value *Step, 2877 Instruction *DL) { 2878 BasicBlock *Header = L->getHeader(); 2879 BasicBlock *Latch = L->getLoopLatch(); 2880 // As we're just creating this loop, it's possible no latch exists 2881 // yet. If so, use the header as this will be a single block loop. 2882 if (!Latch) 2883 Latch = Header; 2884 2885 IRBuilder<> Builder(&*Header->getFirstInsertionPt()); 2886 setDebugLocFromInst(Builder, getDebugLocFromInstOrOperands(OldInduction)); 2887 auto *Induction = Builder.CreatePHI(Start->getType(), 2, "index"); 2888 2889 Builder.SetInsertPoint(Latch->getTerminator()); 2890 2891 // Create i+1 and fill the PHINode. 2892 Value *Next = Builder.CreateAdd(Induction, Step, "index.next"); 2893 Induction->addIncoming(Start, L->getLoopPreheader()); 2894 Induction->addIncoming(Next, Latch); 2895 // Create the compare. 2896 Value *ICmp = Builder.CreateICmpEQ(Next, End); 2897 Builder.CreateCondBr(ICmp, L->getExitBlock(), Header); 2898 2899 // Now we have two terminators. Remove the old one from the block. 2900 Latch->getTerminator()->eraseFromParent(); 2901 2902 return Induction; 2903 } 2904 2905 Value *InnerLoopVectorizer::getOrCreateTripCount(Loop *L) { 2906 if (TripCount) 2907 return TripCount; 2908 2909 IRBuilder<> Builder(L->getLoopPreheader()->getTerminator()); 2910 // Find the loop boundaries. 2911 ScalarEvolution *SE = PSE.getSE(); 2912 const SCEV *BackedgeTakenCount = PSE.getBackedgeTakenCount(); 2913 assert(BackedgeTakenCount != SE->getCouldNotCompute() && 2914 "Invalid loop count"); 2915 2916 Type *IdxTy = Legal->getWidestInductionType(); 2917 2918 // The exit count might have the type of i64 while the phi is i32. This can 2919 // happen if we have an induction variable that is sign extended before the 2920 // compare. The only way that we get a backedge taken count is that the 2921 // induction variable was signed and as such will not overflow. In such a case 2922 // truncation is legal. 2923 if (BackedgeTakenCount->getType()->getPrimitiveSizeInBits() > 2924 IdxTy->getPrimitiveSizeInBits()) 2925 BackedgeTakenCount = SE->getTruncateOrNoop(BackedgeTakenCount, IdxTy); 2926 BackedgeTakenCount = SE->getNoopOrZeroExtend(BackedgeTakenCount, IdxTy); 2927 2928 // Get the total trip count from the count by adding 1. 2929 const SCEV *ExitCount = SE->getAddExpr( 2930 BackedgeTakenCount, SE->getOne(BackedgeTakenCount->getType())); 2931 2932 const DataLayout &DL = L->getHeader()->getModule()->getDataLayout(); 2933 2934 // Expand the trip count and place the new instructions in the preheader. 2935 // Notice that the pre-header does not change, only the loop body. 2936 SCEVExpander Exp(*SE, DL, "induction"); 2937 2938 // Count holds the overall loop count (N). 2939 TripCount = Exp.expandCodeFor(ExitCount, ExitCount->getType(), 2940 L->getLoopPreheader()->getTerminator()); 2941 2942 if (TripCount->getType()->isPointerTy()) 2943 TripCount = 2944 CastInst::CreatePointerCast(TripCount, IdxTy, "exitcount.ptrcnt.to.int", 2945 L->getLoopPreheader()->getTerminator()); 2946 2947 return TripCount; 2948 } 2949 2950 Value *InnerLoopVectorizer::getOrCreateVectorTripCount(Loop *L) { 2951 if (VectorTripCount) 2952 return VectorTripCount; 2953 2954 Value *TC = getOrCreateTripCount(L); 2955 IRBuilder<> Builder(L->getLoopPreheader()->getTerminator()); 2956 2957 // Now we need to generate the expression for the part of the loop that the 2958 // vectorized body will execute. This is equal to N - (N % Step) if scalar 2959 // iterations are not required for correctness, or N - Step, otherwise. Step 2960 // is equal to the vectorization factor (number of SIMD elements) times the 2961 // unroll factor (number of SIMD instructions). 2962 Constant *Step = ConstantInt::get(TC->getType(), VF * UF); 2963 Value *R = Builder.CreateURem(TC, Step, "n.mod.vf"); 2964 2965 // If there is a non-reversed interleaved group that may speculatively access 2966 // memory out-of-bounds, we need to ensure that there will be at least one 2967 // iteration of the scalar epilogue loop. Thus, if the step evenly divides 2968 // the trip count, we set the remainder to be equal to the step. If the step 2969 // does not evenly divide the trip count, no adjustment is necessary since 2970 // there will already be scalar iterations. Note that the minimum iterations 2971 // check ensures that N >= Step. 2972 if (VF > 1 && Legal->requiresScalarEpilogue()) { 2973 auto *IsZero = Builder.CreateICmpEQ(R, ConstantInt::get(R->getType(), 0)); 2974 R = Builder.CreateSelect(IsZero, Step, R); 2975 } 2976 2977 VectorTripCount = Builder.CreateSub(TC, R, "n.vec"); 2978 2979 return VectorTripCount; 2980 } 2981 2982 void InnerLoopVectorizer::emitMinimumIterationCountCheck(Loop *L, 2983 BasicBlock *Bypass) { 2984 Value *Count = getOrCreateTripCount(L); 2985 BasicBlock *BB = L->getLoopPreheader(); 2986 IRBuilder<> Builder(BB->getTerminator()); 2987 2988 // Generate code to check that the loop's trip count that we computed by 2989 // adding one to the backedge-taken count will not overflow. 2990 Value *CheckMinIters = Builder.CreateICmpULT( 2991 Count, ConstantInt::get(Count->getType(), VF * UF), "min.iters.check"); 2992 2993 BasicBlock *NewBB = 2994 BB->splitBasicBlock(BB->getTerminator(), "min.iters.checked"); 2995 // Update dominator tree immediately if the generated block is a 2996 // LoopBypassBlock because SCEV expansions to generate loop bypass 2997 // checks may query it before the current function is finished. 2998 DT->addNewBlock(NewBB, BB); 2999 if (L->getParentLoop()) 3000 L->getParentLoop()->addBasicBlockToLoop(NewBB, *LI); 3001 ReplaceInstWithInst(BB->getTerminator(), 3002 BranchInst::Create(Bypass, NewBB, CheckMinIters)); 3003 LoopBypassBlocks.push_back(BB); 3004 } 3005 3006 void InnerLoopVectorizer::emitVectorLoopEnteredCheck(Loop *L, 3007 BasicBlock *Bypass) { 3008 Value *TC = getOrCreateVectorTripCount(L); 3009 BasicBlock *BB = L->getLoopPreheader(); 3010 IRBuilder<> Builder(BB->getTerminator()); 3011 3012 // Now, compare the new count to zero. If it is zero skip the vector loop and 3013 // jump to the scalar loop. 3014 Value *Cmp = Builder.CreateICmpEQ(TC, Constant::getNullValue(TC->getType()), 3015 "cmp.zero"); 3016 3017 // Generate code to check that the loop's trip count that we computed by 3018 // adding one to the backedge-taken count will not overflow. 3019 BasicBlock *NewBB = BB->splitBasicBlock(BB->getTerminator(), "vector.ph"); 3020 // Update dominator tree immediately if the generated block is a 3021 // LoopBypassBlock because SCEV expansions to generate loop bypass 3022 // checks may query it before the current function is finished. 3023 DT->addNewBlock(NewBB, BB); 3024 if (L->getParentLoop()) 3025 L->getParentLoop()->addBasicBlockToLoop(NewBB, *LI); 3026 ReplaceInstWithInst(BB->getTerminator(), 3027 BranchInst::Create(Bypass, NewBB, Cmp)); 3028 LoopBypassBlocks.push_back(BB); 3029 } 3030 3031 void InnerLoopVectorizer::emitSCEVChecks(Loop *L, BasicBlock *Bypass) { 3032 BasicBlock *BB = L->getLoopPreheader(); 3033 3034 // Generate the code to check that the SCEV assumptions that we made. 3035 // We want the new basic block to start at the first instruction in a 3036 // sequence of instructions that form a check. 3037 SCEVExpander Exp(*PSE.getSE(), Bypass->getModule()->getDataLayout(), 3038 "scev.check"); 3039 Value *SCEVCheck = 3040 Exp.expandCodeForPredicate(&PSE.getUnionPredicate(), BB->getTerminator()); 3041 3042 if (auto *C = dyn_cast<ConstantInt>(SCEVCheck)) 3043 if (C->isZero()) 3044 return; 3045 3046 // Create a new block containing the stride check. 3047 BB->setName("vector.scevcheck"); 3048 auto *NewBB = BB->splitBasicBlock(BB->getTerminator(), "vector.ph"); 3049 // Update dominator tree immediately if the generated block is a 3050 // LoopBypassBlock because SCEV expansions to generate loop bypass 3051 // checks may query it before the current function is finished. 3052 DT->addNewBlock(NewBB, BB); 3053 if (L->getParentLoop()) 3054 L->getParentLoop()->addBasicBlockToLoop(NewBB, *LI); 3055 ReplaceInstWithInst(BB->getTerminator(), 3056 BranchInst::Create(Bypass, NewBB, SCEVCheck)); 3057 LoopBypassBlocks.push_back(BB); 3058 AddedSafetyChecks = true; 3059 } 3060 3061 void InnerLoopVectorizer::emitMemRuntimeChecks(Loop *L, BasicBlock *Bypass) { 3062 BasicBlock *BB = L->getLoopPreheader(); 3063 3064 // Generate the code that checks in runtime if arrays overlap. We put the 3065 // checks into a separate block to make the more common case of few elements 3066 // faster. 3067 Instruction *FirstCheckInst; 3068 Instruction *MemRuntimeCheck; 3069 std::tie(FirstCheckInst, MemRuntimeCheck) = 3070 Legal->getLAI()->addRuntimeChecks(BB->getTerminator()); 3071 if (!MemRuntimeCheck) 3072 return; 3073 3074 // Create a new block containing the memory check. 3075 BB->setName("vector.memcheck"); 3076 auto *NewBB = BB->splitBasicBlock(BB->getTerminator(), "vector.ph"); 3077 // Update dominator tree immediately if the generated block is a 3078 // LoopBypassBlock because SCEV expansions to generate loop bypass 3079 // checks may query it before the current function is finished. 3080 DT->addNewBlock(NewBB, BB); 3081 if (L->getParentLoop()) 3082 L->getParentLoop()->addBasicBlockToLoop(NewBB, *LI); 3083 ReplaceInstWithInst(BB->getTerminator(), 3084 BranchInst::Create(Bypass, NewBB, MemRuntimeCheck)); 3085 LoopBypassBlocks.push_back(BB); 3086 AddedSafetyChecks = true; 3087 3088 // We currently don't use LoopVersioning for the actual loop cloning but we 3089 // still use it to add the noalias metadata. 3090 LVer = llvm::make_unique<LoopVersioning>(*Legal->getLAI(), OrigLoop, LI, DT, 3091 PSE.getSE()); 3092 LVer->prepareNoAliasMetadata(); 3093 } 3094 3095 void InnerLoopVectorizer::createEmptyLoop() { 3096 /* 3097 In this function we generate a new loop. The new loop will contain 3098 the vectorized instructions while the old loop will continue to run the 3099 scalar remainder. 3100 3101 [ ] <-- loop iteration number check. 3102 / | 3103 / v 3104 | [ ] <-- vector loop bypass (may consist of multiple blocks). 3105 | / | 3106 | / v 3107 || [ ] <-- vector pre header. 3108 |/ | 3109 | v 3110 | [ ] \ 3111 | [ ]_| <-- vector loop. 3112 | | 3113 | v 3114 | -[ ] <--- middle-block. 3115 | / | 3116 | / v 3117 -|- >[ ] <--- new preheader. 3118 | | 3119 | v 3120 | [ ] \ 3121 | [ ]_| <-- old scalar loop to handle remainder. 3122 \ | 3123 \ v 3124 >[ ] <-- exit block. 3125 ... 3126 */ 3127 3128 BasicBlock *OldBasicBlock = OrigLoop->getHeader(); 3129 BasicBlock *VectorPH = OrigLoop->getLoopPreheader(); 3130 BasicBlock *ExitBlock = OrigLoop->getExitBlock(); 3131 assert(VectorPH && "Invalid loop structure"); 3132 assert(ExitBlock && "Must have an exit block"); 3133 3134 // Some loops have a single integer induction variable, while other loops 3135 // don't. One example is c++ iterators that often have multiple pointer 3136 // induction variables. In the code below we also support a case where we 3137 // don't have a single induction variable. 3138 // 3139 // We try to obtain an induction variable from the original loop as hard 3140 // as possible. However if we don't find one that: 3141 // - is an integer 3142 // - counts from zero, stepping by one 3143 // - is the size of the widest induction variable type 3144 // then we create a new one. 3145 OldInduction = Legal->getInduction(); 3146 Type *IdxTy = Legal->getWidestInductionType(); 3147 3148 // Split the single block loop into the two loop structure described above. 3149 BasicBlock *VecBody = 3150 VectorPH->splitBasicBlock(VectorPH->getTerminator(), "vector.body"); 3151 BasicBlock *MiddleBlock = 3152 VecBody->splitBasicBlock(VecBody->getTerminator(), "middle.block"); 3153 BasicBlock *ScalarPH = 3154 MiddleBlock->splitBasicBlock(MiddleBlock->getTerminator(), "scalar.ph"); 3155 3156 // Create and register the new vector loop. 3157 Loop *Lp = new Loop(); 3158 Loop *ParentLoop = OrigLoop->getParentLoop(); 3159 3160 // Insert the new loop into the loop nest and register the new basic blocks 3161 // before calling any utilities such as SCEV that require valid LoopInfo. 3162 if (ParentLoop) { 3163 ParentLoop->addChildLoop(Lp); 3164 ParentLoop->addBasicBlockToLoop(ScalarPH, *LI); 3165 ParentLoop->addBasicBlockToLoop(MiddleBlock, *LI); 3166 } else { 3167 LI->addTopLevelLoop(Lp); 3168 } 3169 Lp->addBasicBlockToLoop(VecBody, *LI); 3170 3171 // Find the loop boundaries. 3172 Value *Count = getOrCreateTripCount(Lp); 3173 3174 Value *StartIdx = ConstantInt::get(IdxTy, 0); 3175 3176 // We need to test whether the backedge-taken count is uint##_max. Adding one 3177 // to it will cause overflow and an incorrect loop trip count in the vector 3178 // body. In case of overflow we want to directly jump to the scalar remainder 3179 // loop. 3180 emitMinimumIterationCountCheck(Lp, ScalarPH); 3181 // Now, compare the new count to zero. If it is zero skip the vector loop and 3182 // jump to the scalar loop. 3183 emitVectorLoopEnteredCheck(Lp, ScalarPH); 3184 // Generate the code to check any assumptions that we've made for SCEV 3185 // expressions. 3186 emitSCEVChecks(Lp, ScalarPH); 3187 3188 // Generate the code that checks in runtime if arrays overlap. We put the 3189 // checks into a separate block to make the more common case of few elements 3190 // faster. 3191 emitMemRuntimeChecks(Lp, ScalarPH); 3192 3193 // Generate the induction variable. 3194 // The loop step is equal to the vectorization factor (num of SIMD elements) 3195 // times the unroll factor (num of SIMD instructions). 3196 Value *CountRoundDown = getOrCreateVectorTripCount(Lp); 3197 Constant *Step = ConstantInt::get(IdxTy, VF * UF); 3198 Induction = 3199 createInductionVariable(Lp, StartIdx, CountRoundDown, Step, 3200 getDebugLocFromInstOrOperands(OldInduction)); 3201 3202 // We are going to resume the execution of the scalar loop. 3203 // Go over all of the induction variables that we found and fix the 3204 // PHIs that are left in the scalar version of the loop. 3205 // The starting values of PHI nodes depend on the counter of the last 3206 // iteration in the vectorized loop. 3207 // If we come from a bypass edge then we need to start from the original 3208 // start value. 3209 3210 // This variable saves the new starting index for the scalar loop. It is used 3211 // to test if there are any tail iterations left once the vector loop has 3212 // completed. 3213 LoopVectorizationLegality::InductionList *List = Legal->getInductionVars(); 3214 for (auto &InductionEntry : *List) { 3215 PHINode *OrigPhi = InductionEntry.first; 3216 InductionDescriptor II = InductionEntry.second; 3217 3218 // Create phi nodes to merge from the backedge-taken check block. 3219 PHINode *BCResumeVal = PHINode::Create( 3220 OrigPhi->getType(), 3, "bc.resume.val", ScalarPH->getTerminator()); 3221 Value *EndValue; 3222 if (OrigPhi == OldInduction) { 3223 // We know what the end value is. 3224 EndValue = CountRoundDown; 3225 } else { 3226 IRBuilder<> B(LoopBypassBlocks.back()->getTerminator()); 3227 Type *StepType = II.getStep()->getType(); 3228 Instruction::CastOps CastOp = 3229 CastInst::getCastOpcode(CountRoundDown, true, StepType, true); 3230 Value *CRD = B.CreateCast(CastOp, CountRoundDown, StepType, "cast.crd"); 3231 const DataLayout &DL = OrigLoop->getHeader()->getModule()->getDataLayout(); 3232 EndValue = II.transform(B, CRD, PSE.getSE(), DL); 3233 EndValue->setName("ind.end"); 3234 } 3235 3236 // The new PHI merges the original incoming value, in case of a bypass, 3237 // or the value at the end of the vectorized loop. 3238 BCResumeVal->addIncoming(EndValue, MiddleBlock); 3239 3240 // Fix up external users of the induction variable. 3241 fixupIVUsers(OrigPhi, II, CountRoundDown, EndValue, MiddleBlock); 3242 3243 // Fix the scalar body counter (PHI node). 3244 unsigned BlockIdx = OrigPhi->getBasicBlockIndex(ScalarPH); 3245 3246 // The old induction's phi node in the scalar body needs the truncated 3247 // value. 3248 for (BasicBlock *BB : LoopBypassBlocks) 3249 BCResumeVal->addIncoming(II.getStartValue(), BB); 3250 OrigPhi->setIncomingValue(BlockIdx, BCResumeVal); 3251 } 3252 3253 // Add a check in the middle block to see if we have completed 3254 // all of the iterations in the first vector loop. 3255 // If (N - N%VF) == N, then we *don't* need to run the remainder. 3256 Value *CmpN = 3257 CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, Count, 3258 CountRoundDown, "cmp.n", MiddleBlock->getTerminator()); 3259 ReplaceInstWithInst(MiddleBlock->getTerminator(), 3260 BranchInst::Create(ExitBlock, ScalarPH, CmpN)); 3261 3262 // Get ready to start creating new instructions into the vectorized body. 3263 Builder.SetInsertPoint(&*VecBody->getFirstInsertionPt()); 3264 3265 // Save the state. 3266 LoopVectorPreHeader = Lp->getLoopPreheader(); 3267 LoopScalarPreHeader = ScalarPH; 3268 LoopMiddleBlock = MiddleBlock; 3269 LoopExitBlock = ExitBlock; 3270 LoopVectorBody = VecBody; 3271 LoopScalarBody = OldBasicBlock; 3272 3273 // Keep all loop hints from the original loop on the vector loop (we'll 3274 // replace the vectorizer-specific hints below). 3275 if (MDNode *LID = OrigLoop->getLoopID()) 3276 Lp->setLoopID(LID); 3277 3278 LoopVectorizeHints Hints(Lp, true, *ORE); 3279 Hints.setAlreadyVectorized(); 3280 } 3281 3282 // Fix up external users of the induction variable. At this point, we are 3283 // in LCSSA form, with all external PHIs that use the IV having one input value, 3284 // coming from the remainder loop. We need those PHIs to also have a correct 3285 // value for the IV when arriving directly from the middle block. 3286 void InnerLoopVectorizer::fixupIVUsers(PHINode *OrigPhi, 3287 const InductionDescriptor &II, 3288 Value *CountRoundDown, Value *EndValue, 3289 BasicBlock *MiddleBlock) { 3290 // There are two kinds of external IV usages - those that use the value 3291 // computed in the last iteration (the PHI) and those that use the penultimate 3292 // value (the value that feeds into the phi from the loop latch). 3293 // We allow both, but they, obviously, have different values. 3294 3295 assert(OrigLoop->getExitBlock() && "Expected a single exit block"); 3296 3297 DenseMap<Value *, Value *> MissingVals; 3298 3299 // An external user of the last iteration's value should see the value that 3300 // the remainder loop uses to initialize its own IV. 3301 Value *PostInc = OrigPhi->getIncomingValueForBlock(OrigLoop->getLoopLatch()); 3302 for (User *U : PostInc->users()) { 3303 Instruction *UI = cast<Instruction>(U); 3304 if (!OrigLoop->contains(UI)) { 3305 assert(isa<PHINode>(UI) && "Expected LCSSA form"); 3306 MissingVals[UI] = EndValue; 3307 } 3308 } 3309 3310 // An external user of the penultimate value need to see EndValue - Step. 3311 // The simplest way to get this is to recompute it from the constituent SCEVs, 3312 // that is Start + (Step * (CRD - 1)). 3313 for (User *U : OrigPhi->users()) { 3314 auto *UI = cast<Instruction>(U); 3315 if (!OrigLoop->contains(UI)) { 3316 const DataLayout &DL = 3317 OrigLoop->getHeader()->getModule()->getDataLayout(); 3318 assert(isa<PHINode>(UI) && "Expected LCSSA form"); 3319 3320 IRBuilder<> B(MiddleBlock->getTerminator()); 3321 Value *CountMinusOne = B.CreateSub( 3322 CountRoundDown, ConstantInt::get(CountRoundDown->getType(), 1)); 3323 Value *CMO = B.CreateSExtOrTrunc(CountMinusOne, II.getStep()->getType(), 3324 "cast.cmo"); 3325 Value *Escape = II.transform(B, CMO, PSE.getSE(), DL); 3326 Escape->setName("ind.escape"); 3327 MissingVals[UI] = Escape; 3328 } 3329 } 3330 3331 for (auto &I : MissingVals) { 3332 PHINode *PHI = cast<PHINode>(I.first); 3333 // One corner case we have to handle is two IVs "chasing" each-other, 3334 // that is %IV2 = phi [...], [ %IV1, %latch ] 3335 // In this case, if IV1 has an external use, we need to avoid adding both 3336 // "last value of IV1" and "penultimate value of IV2". So, verify that we 3337 // don't already have an incoming value for the middle block. 3338 if (PHI->getBasicBlockIndex(MiddleBlock) == -1) 3339 PHI->addIncoming(I.second, MiddleBlock); 3340 } 3341 } 3342 3343 namespace { 3344 struct CSEDenseMapInfo { 3345 static bool canHandle(Instruction *I) { 3346 return isa<InsertElementInst>(I) || isa<ExtractElementInst>(I) || 3347 isa<ShuffleVectorInst>(I) || isa<GetElementPtrInst>(I); 3348 } 3349 static inline Instruction *getEmptyKey() { 3350 return DenseMapInfo<Instruction *>::getEmptyKey(); 3351 } 3352 static inline Instruction *getTombstoneKey() { 3353 return DenseMapInfo<Instruction *>::getTombstoneKey(); 3354 } 3355 static unsigned getHashValue(Instruction *I) { 3356 assert(canHandle(I) && "Unknown instruction!"); 3357 return hash_combine(I->getOpcode(), hash_combine_range(I->value_op_begin(), 3358 I->value_op_end())); 3359 } 3360 static bool isEqual(Instruction *LHS, Instruction *RHS) { 3361 if (LHS == getEmptyKey() || RHS == getEmptyKey() || 3362 LHS == getTombstoneKey() || RHS == getTombstoneKey()) 3363 return LHS == RHS; 3364 return LHS->isIdenticalTo(RHS); 3365 } 3366 }; 3367 } 3368 3369 ///\brief Perform cse of induction variable instructions. 3370 static void cse(BasicBlock *BB) { 3371 // Perform simple cse. 3372 SmallDenseMap<Instruction *, Instruction *, 4, CSEDenseMapInfo> CSEMap; 3373 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) { 3374 Instruction *In = &*I++; 3375 3376 if (!CSEDenseMapInfo::canHandle(In)) 3377 continue; 3378 3379 // Check if we can replace this instruction with any of the 3380 // visited instructions. 3381 if (Instruction *V = CSEMap.lookup(In)) { 3382 In->replaceAllUsesWith(V); 3383 In->eraseFromParent(); 3384 continue; 3385 } 3386 3387 CSEMap[In] = In; 3388 } 3389 } 3390 3391 /// \brief Adds a 'fast' flag to floating point operations. 3392 static Value *addFastMathFlag(Value *V) { 3393 if (isa<FPMathOperator>(V)) { 3394 FastMathFlags Flags; 3395 Flags.setUnsafeAlgebra(); 3396 cast<Instruction>(V)->setFastMathFlags(Flags); 3397 } 3398 return V; 3399 } 3400 3401 /// Estimate the overhead of scalarizing a value. Insert and Extract are set if 3402 /// the result needs to be inserted and/or extracted from vectors. 3403 static unsigned getScalarizationOverhead(Type *Ty, bool Insert, bool Extract, 3404 const TargetTransformInfo &TTI) { 3405 if (Ty->isVoidTy()) 3406 return 0; 3407 3408 assert(Ty->isVectorTy() && "Can only scalarize vectors"); 3409 unsigned Cost = 0; 3410 3411 for (unsigned I = 0, E = Ty->getVectorNumElements(); I < E; ++I) { 3412 if (Insert) 3413 Cost += TTI.getVectorInstrCost(Instruction::InsertElement, Ty, I); 3414 if (Extract) 3415 Cost += TTI.getVectorInstrCost(Instruction::ExtractElement, Ty, I); 3416 } 3417 3418 return Cost; 3419 } 3420 3421 // Estimate cost of a call instruction CI if it were vectorized with factor VF. 3422 // Return the cost of the instruction, including scalarization overhead if it's 3423 // needed. The flag NeedToScalarize shows if the call needs to be scalarized - 3424 // i.e. either vector version isn't available, or is too expensive. 3425 static unsigned getVectorCallCost(CallInst *CI, unsigned VF, 3426 const TargetTransformInfo &TTI, 3427 const TargetLibraryInfo *TLI, 3428 bool &NeedToScalarize) { 3429 Function *F = CI->getCalledFunction(); 3430 StringRef FnName = CI->getCalledFunction()->getName(); 3431 Type *ScalarRetTy = CI->getType(); 3432 SmallVector<Type *, 4> Tys, ScalarTys; 3433 for (auto &ArgOp : CI->arg_operands()) 3434 ScalarTys.push_back(ArgOp->getType()); 3435 3436 // Estimate cost of scalarized vector call. The source operands are assumed 3437 // to be vectors, so we need to extract individual elements from there, 3438 // execute VF scalar calls, and then gather the result into the vector return 3439 // value. 3440 unsigned ScalarCallCost = TTI.getCallInstrCost(F, ScalarRetTy, ScalarTys); 3441 if (VF == 1) 3442 return ScalarCallCost; 3443 3444 // Compute corresponding vector type for return value and arguments. 3445 Type *RetTy = ToVectorTy(ScalarRetTy, VF); 3446 for (Type *ScalarTy : ScalarTys) 3447 Tys.push_back(ToVectorTy(ScalarTy, VF)); 3448 3449 // Compute costs of unpacking argument values for the scalar calls and 3450 // packing the return values to a vector. 3451 unsigned ScalarizationCost = 3452 getScalarizationOverhead(RetTy, true, false, TTI); 3453 for (Type *Ty : Tys) 3454 ScalarizationCost += getScalarizationOverhead(Ty, false, true, TTI); 3455 3456 unsigned Cost = ScalarCallCost * VF + ScalarizationCost; 3457 3458 // If we can't emit a vector call for this function, then the currently found 3459 // cost is the cost we need to return. 3460 NeedToScalarize = true; 3461 if (!TLI || !TLI->isFunctionVectorizable(FnName, VF) || CI->isNoBuiltin()) 3462 return Cost; 3463 3464 // If the corresponding vector cost is cheaper, return its cost. 3465 unsigned VectorCallCost = TTI.getCallInstrCost(nullptr, RetTy, Tys); 3466 if (VectorCallCost < Cost) { 3467 NeedToScalarize = false; 3468 return VectorCallCost; 3469 } 3470 return Cost; 3471 } 3472 3473 // Estimate cost of an intrinsic call instruction CI if it were vectorized with 3474 // factor VF. Return the cost of the instruction, including scalarization 3475 // overhead if it's needed. 3476 static unsigned getVectorIntrinsicCost(CallInst *CI, unsigned VF, 3477 const TargetTransformInfo &TTI, 3478 const TargetLibraryInfo *TLI) { 3479 Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI); 3480 assert(ID && "Expected intrinsic call!"); 3481 3482 Type *RetTy = ToVectorTy(CI->getType(), VF); 3483 SmallVector<Type *, 4> Tys; 3484 for (Value *ArgOperand : CI->arg_operands()) 3485 Tys.push_back(ToVectorTy(ArgOperand->getType(), VF)); 3486 3487 FastMathFlags FMF; 3488 if (auto *FPMO = dyn_cast<FPMathOperator>(CI)) 3489 FMF = FPMO->getFastMathFlags(); 3490 3491 return TTI.getIntrinsicInstrCost(ID, RetTy, Tys, FMF); 3492 } 3493 3494 static Type *smallestIntegerVectorType(Type *T1, Type *T2) { 3495 auto *I1 = cast<IntegerType>(T1->getVectorElementType()); 3496 auto *I2 = cast<IntegerType>(T2->getVectorElementType()); 3497 return I1->getBitWidth() < I2->getBitWidth() ? T1 : T2; 3498 } 3499 static Type *largestIntegerVectorType(Type *T1, Type *T2) { 3500 auto *I1 = cast<IntegerType>(T1->getVectorElementType()); 3501 auto *I2 = cast<IntegerType>(T2->getVectorElementType()); 3502 return I1->getBitWidth() > I2->getBitWidth() ? T1 : T2; 3503 } 3504 3505 void InnerLoopVectorizer::truncateToMinimalBitwidths() { 3506 // For every instruction `I` in MinBWs, truncate the operands, create a 3507 // truncated version of `I` and reextend its result. InstCombine runs 3508 // later and will remove any ext/trunc pairs. 3509 // 3510 SmallPtrSet<Value *, 4> Erased; 3511 for (const auto &KV : *MinBWs) { 3512 VectorParts &Parts = WidenMap.get(KV.first); 3513 for (Value *&I : Parts) { 3514 if (Erased.count(I) || I->use_empty() || !isa<Instruction>(I)) 3515 continue; 3516 Type *OriginalTy = I->getType(); 3517 Type *ScalarTruncatedTy = 3518 IntegerType::get(OriginalTy->getContext(), KV.second); 3519 Type *TruncatedTy = VectorType::get(ScalarTruncatedTy, 3520 OriginalTy->getVectorNumElements()); 3521 if (TruncatedTy == OriginalTy) 3522 continue; 3523 3524 IRBuilder<> B(cast<Instruction>(I)); 3525 auto ShrinkOperand = [&](Value *V) -> Value * { 3526 if (auto *ZI = dyn_cast<ZExtInst>(V)) 3527 if (ZI->getSrcTy() == TruncatedTy) 3528 return ZI->getOperand(0); 3529 return B.CreateZExtOrTrunc(V, TruncatedTy); 3530 }; 3531 3532 // The actual instruction modification depends on the instruction type, 3533 // unfortunately. 3534 Value *NewI = nullptr; 3535 if (auto *BO = dyn_cast<BinaryOperator>(I)) { 3536 NewI = B.CreateBinOp(BO->getOpcode(), ShrinkOperand(BO->getOperand(0)), 3537 ShrinkOperand(BO->getOperand(1))); 3538 cast<BinaryOperator>(NewI)->copyIRFlags(I); 3539 } else if (auto *CI = dyn_cast<ICmpInst>(I)) { 3540 NewI = 3541 B.CreateICmp(CI->getPredicate(), ShrinkOperand(CI->getOperand(0)), 3542 ShrinkOperand(CI->getOperand(1))); 3543 } else if (auto *SI = dyn_cast<SelectInst>(I)) { 3544 NewI = B.CreateSelect(SI->getCondition(), 3545 ShrinkOperand(SI->getTrueValue()), 3546 ShrinkOperand(SI->getFalseValue())); 3547 } else if (auto *CI = dyn_cast<CastInst>(I)) { 3548 switch (CI->getOpcode()) { 3549 default: 3550 llvm_unreachable("Unhandled cast!"); 3551 case Instruction::Trunc: 3552 NewI = ShrinkOperand(CI->getOperand(0)); 3553 break; 3554 case Instruction::SExt: 3555 NewI = B.CreateSExtOrTrunc( 3556 CI->getOperand(0), 3557 smallestIntegerVectorType(OriginalTy, TruncatedTy)); 3558 break; 3559 case Instruction::ZExt: 3560 NewI = B.CreateZExtOrTrunc( 3561 CI->getOperand(0), 3562 smallestIntegerVectorType(OriginalTy, TruncatedTy)); 3563 break; 3564 } 3565 } else if (auto *SI = dyn_cast<ShuffleVectorInst>(I)) { 3566 auto Elements0 = SI->getOperand(0)->getType()->getVectorNumElements(); 3567 auto *O0 = B.CreateZExtOrTrunc( 3568 SI->getOperand(0), VectorType::get(ScalarTruncatedTy, Elements0)); 3569 auto Elements1 = SI->getOperand(1)->getType()->getVectorNumElements(); 3570 auto *O1 = B.CreateZExtOrTrunc( 3571 SI->getOperand(1), VectorType::get(ScalarTruncatedTy, Elements1)); 3572 3573 NewI = B.CreateShuffleVector(O0, O1, SI->getMask()); 3574 } else if (isa<LoadInst>(I)) { 3575 // Don't do anything with the operands, just extend the result. 3576 continue; 3577 } else if (auto *IE = dyn_cast<InsertElementInst>(I)) { 3578 auto Elements = IE->getOperand(0)->getType()->getVectorNumElements(); 3579 auto *O0 = B.CreateZExtOrTrunc( 3580 IE->getOperand(0), VectorType::get(ScalarTruncatedTy, Elements)); 3581 auto *O1 = B.CreateZExtOrTrunc(IE->getOperand(1), ScalarTruncatedTy); 3582 NewI = B.CreateInsertElement(O0, O1, IE->getOperand(2)); 3583 } else if (auto *EE = dyn_cast<ExtractElementInst>(I)) { 3584 auto Elements = EE->getOperand(0)->getType()->getVectorNumElements(); 3585 auto *O0 = B.CreateZExtOrTrunc( 3586 EE->getOperand(0), VectorType::get(ScalarTruncatedTy, Elements)); 3587 NewI = B.CreateExtractElement(O0, EE->getOperand(2)); 3588 } else { 3589 llvm_unreachable("Unhandled instruction type!"); 3590 } 3591 3592 // Lastly, extend the result. 3593 NewI->takeName(cast<Instruction>(I)); 3594 Value *Res = B.CreateZExtOrTrunc(NewI, OriginalTy); 3595 I->replaceAllUsesWith(Res); 3596 cast<Instruction>(I)->eraseFromParent(); 3597 Erased.insert(I); 3598 I = Res; 3599 } 3600 } 3601 3602 // We'll have created a bunch of ZExts that are now parentless. Clean up. 3603 for (const auto &KV : *MinBWs) { 3604 VectorParts &Parts = WidenMap.get(KV.first); 3605 for (Value *&I : Parts) { 3606 ZExtInst *Inst = dyn_cast<ZExtInst>(I); 3607 if (Inst && Inst->use_empty()) { 3608 Value *NewI = Inst->getOperand(0); 3609 Inst->eraseFromParent(); 3610 I = NewI; 3611 } 3612 } 3613 } 3614 } 3615 3616 void InnerLoopVectorizer::vectorizeLoop() { 3617 //===------------------------------------------------===// 3618 // 3619 // Notice: any optimization or new instruction that go 3620 // into the code below should be also be implemented in 3621 // the cost-model. 3622 // 3623 //===------------------------------------------------===// 3624 Constant *Zero = Builder.getInt32(0); 3625 3626 // In order to support recurrences we need to be able to vectorize Phi nodes. 3627 // Phi nodes have cycles, so we need to vectorize them in two stages. First, 3628 // we create a new vector PHI node with no incoming edges. We use this value 3629 // when we vectorize all of the instructions that use the PHI. Next, after 3630 // all of the instructions in the block are complete we add the new incoming 3631 // edges to the PHI. At this point all of the instructions in the basic block 3632 // are vectorized, so we can use them to construct the PHI. 3633 PhiVector PHIsToFix; 3634 3635 // Scan the loop in a topological order to ensure that defs are vectorized 3636 // before users. 3637 LoopBlocksDFS DFS(OrigLoop); 3638 DFS.perform(LI); 3639 3640 // Vectorize all of the blocks in the original loop. 3641 for (BasicBlock *BB : make_range(DFS.beginRPO(), DFS.endRPO())) 3642 vectorizeBlockInLoop(BB, &PHIsToFix); 3643 3644 // Insert truncates and extends for any truncated instructions as hints to 3645 // InstCombine. 3646 if (VF > 1) 3647 truncateToMinimalBitwidths(); 3648 3649 // At this point every instruction in the original loop is widened to a 3650 // vector form. Now we need to fix the recurrences in PHIsToFix. These PHI 3651 // nodes are currently empty because we did not want to introduce cycles. 3652 // This is the second stage of vectorizing recurrences. 3653 for (PHINode *Phi : PHIsToFix) { 3654 assert(Phi && "Unable to recover vectorized PHI"); 3655 3656 // Handle first-order recurrences that need to be fixed. 3657 if (Legal->isFirstOrderRecurrence(Phi)) { 3658 fixFirstOrderRecurrence(Phi); 3659 continue; 3660 } 3661 3662 // If the phi node is not a first-order recurrence, it must be a reduction. 3663 // Get it's reduction variable descriptor. 3664 assert(Legal->isReductionVariable(Phi) && 3665 "Unable to find the reduction variable"); 3666 RecurrenceDescriptor RdxDesc = (*Legal->getReductionVars())[Phi]; 3667 3668 RecurrenceDescriptor::RecurrenceKind RK = RdxDesc.getRecurrenceKind(); 3669 TrackingVH<Value> ReductionStartValue = RdxDesc.getRecurrenceStartValue(); 3670 Instruction *LoopExitInst = RdxDesc.getLoopExitInstr(); 3671 RecurrenceDescriptor::MinMaxRecurrenceKind MinMaxKind = 3672 RdxDesc.getMinMaxRecurrenceKind(); 3673 setDebugLocFromInst(Builder, ReductionStartValue); 3674 3675 // We need to generate a reduction vector from the incoming scalar. 3676 // To do so, we need to generate the 'identity' vector and override 3677 // one of the elements with the incoming scalar reduction. We need 3678 // to do it in the vector-loop preheader. 3679 Builder.SetInsertPoint(LoopBypassBlocks[1]->getTerminator()); 3680 3681 // This is the vector-clone of the value that leaves the loop. 3682 VectorParts &VectorExit = getVectorValue(LoopExitInst); 3683 Type *VecTy = VectorExit[0]->getType(); 3684 3685 // Find the reduction identity variable. Zero for addition, or, xor, 3686 // one for multiplication, -1 for And. 3687 Value *Identity; 3688 Value *VectorStart; 3689 if (RK == RecurrenceDescriptor::RK_IntegerMinMax || 3690 RK == RecurrenceDescriptor::RK_FloatMinMax) { 3691 // MinMax reduction have the start value as their identify. 3692 if (VF == 1) { 3693 VectorStart = Identity = ReductionStartValue; 3694 } else { 3695 VectorStart = Identity = 3696 Builder.CreateVectorSplat(VF, ReductionStartValue, "minmax.ident"); 3697 } 3698 } else { 3699 // Handle other reduction kinds: 3700 Constant *Iden = RecurrenceDescriptor::getRecurrenceIdentity( 3701 RK, VecTy->getScalarType()); 3702 if (VF == 1) { 3703 Identity = Iden; 3704 // This vector is the Identity vector where the first element is the 3705 // incoming scalar reduction. 3706 VectorStart = ReductionStartValue; 3707 } else { 3708 Identity = ConstantVector::getSplat(VF, Iden); 3709 3710 // This vector is the Identity vector where the first element is the 3711 // incoming scalar reduction. 3712 VectorStart = 3713 Builder.CreateInsertElement(Identity, ReductionStartValue, Zero); 3714 } 3715 } 3716 3717 // Fix the vector-loop phi. 3718 3719 // Reductions do not have to start at zero. They can start with 3720 // any loop invariant values. 3721 VectorParts &VecRdxPhi = WidenMap.get(Phi); 3722 BasicBlock *Latch = OrigLoop->getLoopLatch(); 3723 Value *LoopVal = Phi->getIncomingValueForBlock(Latch); 3724 VectorParts &Val = getVectorValue(LoopVal); 3725 for (unsigned part = 0; part < UF; ++part) { 3726 // Make sure to add the reduction stat value only to the 3727 // first unroll part. 3728 Value *StartVal = (part == 0) ? VectorStart : Identity; 3729 cast<PHINode>(VecRdxPhi[part]) 3730 ->addIncoming(StartVal, LoopVectorPreHeader); 3731 cast<PHINode>(VecRdxPhi[part]) 3732 ->addIncoming(Val[part], LoopVectorBody); 3733 } 3734 3735 // Before each round, move the insertion point right between 3736 // the PHIs and the values we are going to write. 3737 // This allows us to write both PHINodes and the extractelement 3738 // instructions. 3739 Builder.SetInsertPoint(&*LoopMiddleBlock->getFirstInsertionPt()); 3740 3741 VectorParts RdxParts = getVectorValue(LoopExitInst); 3742 setDebugLocFromInst(Builder, LoopExitInst); 3743 3744 // If the vector reduction can be performed in a smaller type, we truncate 3745 // then extend the loop exit value to enable InstCombine to evaluate the 3746 // entire expression in the smaller type. 3747 if (VF > 1 && Phi->getType() != RdxDesc.getRecurrenceType()) { 3748 Type *RdxVecTy = VectorType::get(RdxDesc.getRecurrenceType(), VF); 3749 Builder.SetInsertPoint(LoopVectorBody->getTerminator()); 3750 for (unsigned part = 0; part < UF; ++part) { 3751 Value *Trunc = Builder.CreateTrunc(RdxParts[part], RdxVecTy); 3752 Value *Extnd = RdxDesc.isSigned() ? Builder.CreateSExt(Trunc, VecTy) 3753 : Builder.CreateZExt(Trunc, VecTy); 3754 for (Value::user_iterator UI = RdxParts[part]->user_begin(); 3755 UI != RdxParts[part]->user_end();) 3756 if (*UI != Trunc) { 3757 (*UI++)->replaceUsesOfWith(RdxParts[part], Extnd); 3758 RdxParts[part] = Extnd; 3759 } else { 3760 ++UI; 3761 } 3762 } 3763 Builder.SetInsertPoint(&*LoopMiddleBlock->getFirstInsertionPt()); 3764 for (unsigned part = 0; part < UF; ++part) 3765 RdxParts[part] = Builder.CreateTrunc(RdxParts[part], RdxVecTy); 3766 } 3767 3768 // Reduce all of the unrolled parts into a single vector. 3769 Value *ReducedPartRdx = RdxParts[0]; 3770 unsigned Op = RecurrenceDescriptor::getRecurrenceBinOp(RK); 3771 setDebugLocFromInst(Builder, ReducedPartRdx); 3772 for (unsigned part = 1; part < UF; ++part) { 3773 if (Op != Instruction::ICmp && Op != Instruction::FCmp) 3774 // Floating point operations had to be 'fast' to enable the reduction. 3775 ReducedPartRdx = addFastMathFlag( 3776 Builder.CreateBinOp((Instruction::BinaryOps)Op, RdxParts[part], 3777 ReducedPartRdx, "bin.rdx")); 3778 else 3779 ReducedPartRdx = RecurrenceDescriptor::createMinMaxOp( 3780 Builder, MinMaxKind, ReducedPartRdx, RdxParts[part]); 3781 } 3782 3783 if (VF > 1) { 3784 // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles 3785 // and vector ops, reducing the set of values being computed by half each 3786 // round. 3787 assert(isPowerOf2_32(VF) && 3788 "Reduction emission only supported for pow2 vectors!"); 3789 Value *TmpVec = ReducedPartRdx; 3790 SmallVector<Constant *, 32> ShuffleMask(VF, nullptr); 3791 for (unsigned i = VF; i != 1; i >>= 1) { 3792 // Move the upper half of the vector to the lower half. 3793 for (unsigned j = 0; j != i / 2; ++j) 3794 ShuffleMask[j] = Builder.getInt32(i / 2 + j); 3795 3796 // Fill the rest of the mask with undef. 3797 std::fill(&ShuffleMask[i / 2], ShuffleMask.end(), 3798 UndefValue::get(Builder.getInt32Ty())); 3799 3800 Value *Shuf = Builder.CreateShuffleVector( 3801 TmpVec, UndefValue::get(TmpVec->getType()), 3802 ConstantVector::get(ShuffleMask), "rdx.shuf"); 3803 3804 if (Op != Instruction::ICmp && Op != Instruction::FCmp) 3805 // Floating point operations had to be 'fast' to enable the reduction. 3806 TmpVec = addFastMathFlag(Builder.CreateBinOp( 3807 (Instruction::BinaryOps)Op, TmpVec, Shuf, "bin.rdx")); 3808 else 3809 TmpVec = RecurrenceDescriptor::createMinMaxOp(Builder, MinMaxKind, 3810 TmpVec, Shuf); 3811 } 3812 3813 // The result is in the first element of the vector. 3814 ReducedPartRdx = 3815 Builder.CreateExtractElement(TmpVec, Builder.getInt32(0)); 3816 3817 // If the reduction can be performed in a smaller type, we need to extend 3818 // the reduction to the wider type before we branch to the original loop. 3819 if (Phi->getType() != RdxDesc.getRecurrenceType()) 3820 ReducedPartRdx = 3821 RdxDesc.isSigned() 3822 ? Builder.CreateSExt(ReducedPartRdx, Phi->getType()) 3823 : Builder.CreateZExt(ReducedPartRdx, Phi->getType()); 3824 } 3825 3826 // Create a phi node that merges control-flow from the backedge-taken check 3827 // block and the middle block. 3828 PHINode *BCBlockPhi = PHINode::Create(Phi->getType(), 2, "bc.merge.rdx", 3829 LoopScalarPreHeader->getTerminator()); 3830 for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I) 3831 BCBlockPhi->addIncoming(ReductionStartValue, LoopBypassBlocks[I]); 3832 BCBlockPhi->addIncoming(ReducedPartRdx, LoopMiddleBlock); 3833 3834 // Now, we need to fix the users of the reduction variable 3835 // inside and outside of the scalar remainder loop. 3836 // We know that the loop is in LCSSA form. We need to update the 3837 // PHI nodes in the exit blocks. 3838 for (BasicBlock::iterator LEI = LoopExitBlock->begin(), 3839 LEE = LoopExitBlock->end(); 3840 LEI != LEE; ++LEI) { 3841 PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI); 3842 if (!LCSSAPhi) 3843 break; 3844 3845 // All PHINodes need to have a single entry edge, or two if 3846 // we already fixed them. 3847 assert(LCSSAPhi->getNumIncomingValues() < 3 && "Invalid LCSSA PHI"); 3848 3849 // We found our reduction value exit-PHI. Update it with the 3850 // incoming bypass edge. 3851 if (LCSSAPhi->getIncomingValue(0) == LoopExitInst) { 3852 // Add an edge coming from the bypass. 3853 LCSSAPhi->addIncoming(ReducedPartRdx, LoopMiddleBlock); 3854 break; 3855 } 3856 } // end of the LCSSA phi scan. 3857 3858 // Fix the scalar loop reduction variable with the incoming reduction sum 3859 // from the vector body and from the backedge value. 3860 int IncomingEdgeBlockIdx = 3861 Phi->getBasicBlockIndex(OrigLoop->getLoopLatch()); 3862 assert(IncomingEdgeBlockIdx >= 0 && "Invalid block index"); 3863 // Pick the other block. 3864 int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1); 3865 Phi->setIncomingValue(SelfEdgeBlockIdx, BCBlockPhi); 3866 Phi->setIncomingValue(IncomingEdgeBlockIdx, LoopExitInst); 3867 } // end of for each Phi in PHIsToFix. 3868 3869 fixLCSSAPHIs(); 3870 3871 // Make sure DomTree is updated. 3872 updateAnalysis(); 3873 3874 predicateStores(); 3875 3876 // Remove redundant induction instructions. 3877 cse(LoopVectorBody); 3878 } 3879 3880 void InnerLoopVectorizer::fixFirstOrderRecurrence(PHINode *Phi) { 3881 3882 // This is the second phase of vectorizing first-order recurrences. An 3883 // overview of the transformation is described below. Suppose we have the 3884 // following loop. 3885 // 3886 // for (int i = 0; i < n; ++i) 3887 // b[i] = a[i] - a[i - 1]; 3888 // 3889 // There is a first-order recurrence on "a". For this loop, the shorthand 3890 // scalar IR looks like: 3891 // 3892 // scalar.ph: 3893 // s_init = a[-1] 3894 // br scalar.body 3895 // 3896 // scalar.body: 3897 // i = phi [0, scalar.ph], [i+1, scalar.body] 3898 // s1 = phi [s_init, scalar.ph], [s2, scalar.body] 3899 // s2 = a[i] 3900 // b[i] = s2 - s1 3901 // br cond, scalar.body, ... 3902 // 3903 // In this example, s1 is a recurrence because it's value depends on the 3904 // previous iteration. In the first phase of vectorization, we created a 3905 // temporary value for s1. We now complete the vectorization and produce the 3906 // shorthand vector IR shown below (for VF = 4, UF = 1). 3907 // 3908 // vector.ph: 3909 // v_init = vector(..., ..., ..., a[-1]) 3910 // br vector.body 3911 // 3912 // vector.body 3913 // i = phi [0, vector.ph], [i+4, vector.body] 3914 // v1 = phi [v_init, vector.ph], [v2, vector.body] 3915 // v2 = a[i, i+1, i+2, i+3]; 3916 // v3 = vector(v1(3), v2(0, 1, 2)) 3917 // b[i, i+1, i+2, i+3] = v2 - v3 3918 // br cond, vector.body, middle.block 3919 // 3920 // middle.block: 3921 // x = v2(3) 3922 // br scalar.ph 3923 // 3924 // scalar.ph: 3925 // s_init = phi [x, middle.block], [a[-1], otherwise] 3926 // br scalar.body 3927 // 3928 // After execution completes the vector loop, we extract the next value of 3929 // the recurrence (x) to use as the initial value in the scalar loop. 3930 3931 // Get the original loop preheader and single loop latch. 3932 auto *Preheader = OrigLoop->getLoopPreheader(); 3933 auto *Latch = OrigLoop->getLoopLatch(); 3934 3935 // Get the initial and previous values of the scalar recurrence. 3936 auto *ScalarInit = Phi->getIncomingValueForBlock(Preheader); 3937 auto *Previous = Phi->getIncomingValueForBlock(Latch); 3938 3939 // Create a vector from the initial value. 3940 auto *VectorInit = ScalarInit; 3941 if (VF > 1) { 3942 Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator()); 3943 VectorInit = Builder.CreateInsertElement( 3944 UndefValue::get(VectorType::get(VectorInit->getType(), VF)), VectorInit, 3945 Builder.getInt32(VF - 1), "vector.recur.init"); 3946 } 3947 3948 // We constructed a temporary phi node in the first phase of vectorization. 3949 // This phi node will eventually be deleted. 3950 auto &PhiParts = getVectorValue(Phi); 3951 Builder.SetInsertPoint(cast<Instruction>(PhiParts[0])); 3952 3953 // Create a phi node for the new recurrence. The current value will either be 3954 // the initial value inserted into a vector or loop-varying vector value. 3955 auto *VecPhi = Builder.CreatePHI(VectorInit->getType(), 2, "vector.recur"); 3956 VecPhi->addIncoming(VectorInit, LoopVectorPreHeader); 3957 3958 // Get the vectorized previous value. We ensured the previous values was an 3959 // instruction when detecting the recurrence. 3960 auto &PreviousParts = getVectorValue(Previous); 3961 3962 // Set the insertion point to be after this instruction. We ensured the 3963 // previous value dominated all uses of the phi when detecting the 3964 // recurrence. 3965 Builder.SetInsertPoint( 3966 &*++BasicBlock::iterator(cast<Instruction>(PreviousParts[UF - 1]))); 3967 3968 // We will construct a vector for the recurrence by combining the values for 3969 // the current and previous iterations. This is the required shuffle mask. 3970 SmallVector<Constant *, 8> ShuffleMask(VF); 3971 ShuffleMask[0] = Builder.getInt32(VF - 1); 3972 for (unsigned I = 1; I < VF; ++I) 3973 ShuffleMask[I] = Builder.getInt32(I + VF - 1); 3974 3975 // The vector from which to take the initial value for the current iteration 3976 // (actual or unrolled). Initially, this is the vector phi node. 3977 Value *Incoming = VecPhi; 3978 3979 // Shuffle the current and previous vector and update the vector parts. 3980 for (unsigned Part = 0; Part < UF; ++Part) { 3981 auto *Shuffle = 3982 VF > 1 3983 ? Builder.CreateShuffleVector(Incoming, PreviousParts[Part], 3984 ConstantVector::get(ShuffleMask)) 3985 : Incoming; 3986 PhiParts[Part]->replaceAllUsesWith(Shuffle); 3987 cast<Instruction>(PhiParts[Part])->eraseFromParent(); 3988 PhiParts[Part] = Shuffle; 3989 Incoming = PreviousParts[Part]; 3990 } 3991 3992 // Fix the latch value of the new recurrence in the vector loop. 3993 VecPhi->addIncoming(Incoming, LI->getLoopFor(LoopVectorBody)->getLoopLatch()); 3994 3995 // Extract the last vector element in the middle block. This will be the 3996 // initial value for the recurrence when jumping to the scalar loop. 3997 auto *Extract = Incoming; 3998 if (VF > 1) { 3999 Builder.SetInsertPoint(LoopMiddleBlock->getTerminator()); 4000 Extract = Builder.CreateExtractElement(Extract, Builder.getInt32(VF - 1), 4001 "vector.recur.extract"); 4002 } 4003 4004 // Fix the initial value of the original recurrence in the scalar loop. 4005 Builder.SetInsertPoint(&*LoopScalarPreHeader->begin()); 4006 auto *Start = Builder.CreatePHI(Phi->getType(), 2, "scalar.recur.init"); 4007 for (auto *BB : predecessors(LoopScalarPreHeader)) { 4008 auto *Incoming = BB == LoopMiddleBlock ? Extract : ScalarInit; 4009 Start->addIncoming(Incoming, BB); 4010 } 4011 4012 Phi->setIncomingValue(Phi->getBasicBlockIndex(LoopScalarPreHeader), Start); 4013 Phi->setName("scalar.recur"); 4014 4015 // Finally, fix users of the recurrence outside the loop. The users will need 4016 // either the last value of the scalar recurrence or the last value of the 4017 // vector recurrence we extracted in the middle block. Since the loop is in 4018 // LCSSA form, we just need to find the phi node for the original scalar 4019 // recurrence in the exit block, and then add an edge for the middle block. 4020 for (auto &I : *LoopExitBlock) { 4021 auto *LCSSAPhi = dyn_cast<PHINode>(&I); 4022 if (!LCSSAPhi) 4023 break; 4024 if (LCSSAPhi->getIncomingValue(0) == Phi) { 4025 LCSSAPhi->addIncoming(Extract, LoopMiddleBlock); 4026 break; 4027 } 4028 } 4029 } 4030 4031 void InnerLoopVectorizer::fixLCSSAPHIs() { 4032 for (Instruction &LEI : *LoopExitBlock) { 4033 auto *LCSSAPhi = dyn_cast<PHINode>(&LEI); 4034 if (!LCSSAPhi) 4035 break; 4036 if (LCSSAPhi->getNumIncomingValues() == 1) 4037 LCSSAPhi->addIncoming(UndefValue::get(LCSSAPhi->getType()), 4038 LoopMiddleBlock); 4039 } 4040 } 4041 4042 void InnerLoopVectorizer::predicateStores() { 4043 for (auto KV : PredicatedStores) { 4044 BasicBlock::iterator I(KV.first); 4045 auto *BB = SplitBlock(I->getParent(), &*std::next(I), DT, LI); 4046 auto *T = SplitBlockAndInsertIfThen(KV.second, &*I, /*Unreachable=*/false, 4047 /*BranchWeights=*/nullptr, DT, LI); 4048 I->moveBefore(T); 4049 I->getParent()->setName("pred.store.if"); 4050 BB->setName("pred.store.continue"); 4051 } 4052 DEBUG(DT->verifyDomTree()); 4053 } 4054 4055 InnerLoopVectorizer::VectorParts 4056 InnerLoopVectorizer::createEdgeMask(BasicBlock *Src, BasicBlock *Dst) { 4057 assert(is_contained(predecessors(Dst), Src) && "Invalid edge"); 4058 4059 // Look for cached value. 4060 std::pair<BasicBlock *, BasicBlock *> Edge(Src, Dst); 4061 EdgeMaskCache::iterator ECEntryIt = MaskCache.find(Edge); 4062 if (ECEntryIt != MaskCache.end()) 4063 return ECEntryIt->second; 4064 4065 VectorParts SrcMask = createBlockInMask(Src); 4066 4067 // The terminator has to be a branch inst! 4068 BranchInst *BI = dyn_cast<BranchInst>(Src->getTerminator()); 4069 assert(BI && "Unexpected terminator found"); 4070 4071 if (BI->isConditional()) { 4072 VectorParts EdgeMask = getVectorValue(BI->getCondition()); 4073 4074 if (BI->getSuccessor(0) != Dst) 4075 for (unsigned part = 0; part < UF; ++part) 4076 EdgeMask[part] = Builder.CreateNot(EdgeMask[part]); 4077 4078 for (unsigned part = 0; part < UF; ++part) 4079 EdgeMask[part] = Builder.CreateAnd(EdgeMask[part], SrcMask[part]); 4080 4081 MaskCache[Edge] = EdgeMask; 4082 return EdgeMask; 4083 } 4084 4085 MaskCache[Edge] = SrcMask; 4086 return SrcMask; 4087 } 4088 4089 InnerLoopVectorizer::VectorParts 4090 InnerLoopVectorizer::createBlockInMask(BasicBlock *BB) { 4091 assert(OrigLoop->contains(BB) && "Block is not a part of a loop"); 4092 4093 // Loop incoming mask is all-one. 4094 if (OrigLoop->getHeader() == BB) { 4095 Value *C = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 1); 4096 return getVectorValue(C); 4097 } 4098 4099 // This is the block mask. We OR all incoming edges, and with zero. 4100 Value *Zero = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 0); 4101 VectorParts BlockMask = getVectorValue(Zero); 4102 4103 // For each pred: 4104 for (pred_iterator it = pred_begin(BB), e = pred_end(BB); it != e; ++it) { 4105 VectorParts EM = createEdgeMask(*it, BB); 4106 for (unsigned part = 0; part < UF; ++part) 4107 BlockMask[part] = Builder.CreateOr(BlockMask[part], EM[part]); 4108 } 4109 4110 return BlockMask; 4111 } 4112 4113 void InnerLoopVectorizer::widenPHIInstruction( 4114 Instruction *PN, InnerLoopVectorizer::VectorParts &Entry, unsigned UF, 4115 unsigned VF, PhiVector *PV) { 4116 PHINode *P = cast<PHINode>(PN); 4117 // Handle recurrences. 4118 if (Legal->isReductionVariable(P) || Legal->isFirstOrderRecurrence(P)) { 4119 for (unsigned part = 0; part < UF; ++part) { 4120 // This is phase one of vectorizing PHIs. 4121 Type *VecTy = 4122 (VF == 1) ? PN->getType() : VectorType::get(PN->getType(), VF); 4123 Entry[part] = PHINode::Create( 4124 VecTy, 2, "vec.phi", &*LoopVectorBody->getFirstInsertionPt()); 4125 } 4126 PV->push_back(P); 4127 return; 4128 } 4129 4130 setDebugLocFromInst(Builder, P); 4131 // Check for PHI nodes that are lowered to vector selects. 4132 if (P->getParent() != OrigLoop->getHeader()) { 4133 // We know that all PHIs in non-header blocks are converted into 4134 // selects, so we don't have to worry about the insertion order and we 4135 // can just use the builder. 4136 // At this point we generate the predication tree. There may be 4137 // duplications since this is a simple recursive scan, but future 4138 // optimizations will clean it up. 4139 4140 unsigned NumIncoming = P->getNumIncomingValues(); 4141 4142 // Generate a sequence of selects of the form: 4143 // SELECT(Mask3, In3, 4144 // SELECT(Mask2, In2, 4145 // ( ...))) 4146 for (unsigned In = 0; In < NumIncoming; In++) { 4147 VectorParts Cond = 4148 createEdgeMask(P->getIncomingBlock(In), P->getParent()); 4149 VectorParts &In0 = getVectorValue(P->getIncomingValue(In)); 4150 4151 for (unsigned part = 0; part < UF; ++part) { 4152 // We might have single edge PHIs (blocks) - use an identity 4153 // 'select' for the first PHI operand. 4154 if (In == 0) 4155 Entry[part] = Builder.CreateSelect(Cond[part], In0[part], In0[part]); 4156 else 4157 // Select between the current value and the previous incoming edge 4158 // based on the incoming mask. 4159 Entry[part] = Builder.CreateSelect(Cond[part], In0[part], Entry[part], 4160 "predphi"); 4161 } 4162 } 4163 return; 4164 } 4165 4166 // This PHINode must be an induction variable. 4167 // Make sure that we know about it. 4168 assert(Legal->getInductionVars()->count(P) && "Not an induction variable"); 4169 4170 InductionDescriptor II = Legal->getInductionVars()->lookup(P); 4171 const DataLayout &DL = OrigLoop->getHeader()->getModule()->getDataLayout(); 4172 4173 // FIXME: The newly created binary instructions should contain nsw/nuw flags, 4174 // which can be found from the original scalar operations. 4175 switch (II.getKind()) { 4176 case InductionDescriptor::IK_NoInduction: 4177 llvm_unreachable("Unknown induction"); 4178 case InductionDescriptor::IK_IntInduction: 4179 return widenIntInduction(P, Entry); 4180 case InductionDescriptor::IK_PtrInduction: { 4181 // Handle the pointer induction variable case. 4182 assert(P->getType()->isPointerTy() && "Unexpected type."); 4183 // This is the normalized GEP that starts counting at zero. 4184 Value *PtrInd = Induction; 4185 PtrInd = Builder.CreateSExtOrTrunc(PtrInd, II.getStep()->getType()); 4186 // This is the vector of results. Notice that we don't generate 4187 // vector geps because scalar geps result in better code. 4188 for (unsigned part = 0; part < UF; ++part) { 4189 if (VF == 1) { 4190 int EltIndex = part; 4191 Constant *Idx = ConstantInt::get(PtrInd->getType(), EltIndex); 4192 Value *GlobalIdx = Builder.CreateAdd(PtrInd, Idx); 4193 Value *SclrGep = II.transform(Builder, GlobalIdx, PSE.getSE(), DL); 4194 SclrGep->setName("next.gep"); 4195 Entry[part] = SclrGep; 4196 continue; 4197 } 4198 4199 Value *VecVal = UndefValue::get(VectorType::get(P->getType(), VF)); 4200 for (unsigned int i = 0; i < VF; ++i) { 4201 int EltIndex = i + part * VF; 4202 Constant *Idx = ConstantInt::get(PtrInd->getType(), EltIndex); 4203 Value *GlobalIdx = Builder.CreateAdd(PtrInd, Idx); 4204 Value *SclrGep = II.transform(Builder, GlobalIdx, PSE.getSE(), DL); 4205 SclrGep->setName("next.gep"); 4206 VecVal = Builder.CreateInsertElement(VecVal, SclrGep, 4207 Builder.getInt32(i), "insert.gep"); 4208 } 4209 Entry[part] = VecVal; 4210 } 4211 return; 4212 } 4213 case InductionDescriptor::IK_FpInduction: { 4214 assert(P->getType() == II.getStartValue()->getType() && 4215 "Types must match"); 4216 // Handle other induction variables that are now based on the 4217 // canonical one. 4218 assert(P != OldInduction && "Primary induction can be integer only"); 4219 4220 Value *V = Builder.CreateCast(Instruction::SIToFP, Induction, P->getType()); 4221 V = II.transform(Builder, V, PSE.getSE(), DL); 4222 V->setName("fp.offset.idx"); 4223 4224 // Now we have scalar op: %fp.offset.idx = StartVal +/- Induction*StepVal 4225 4226 Value *Broadcasted = getBroadcastInstrs(V); 4227 // After broadcasting the induction variable we need to make the vector 4228 // consecutive by adding StepVal*0, StepVal*1, StepVal*2, etc. 4229 Value *StepVal = cast<SCEVUnknown>(II.getStep())->getValue(); 4230 for (unsigned part = 0; part < UF; ++part) 4231 Entry[part] = getStepVector(Broadcasted, VF * part, StepVal, 4232 II.getInductionOpcode()); 4233 return; 4234 } 4235 } 4236 } 4237 4238 void InnerLoopVectorizer::vectorizeBlockInLoop(BasicBlock *BB, PhiVector *PV) { 4239 // For each instruction in the old loop. 4240 for (Instruction &I : *BB) { 4241 VectorParts &Entry = WidenMap.get(&I); 4242 4243 switch (I.getOpcode()) { 4244 case Instruction::Br: 4245 // Nothing to do for PHIs and BR, since we already took care of the 4246 // loop control flow instructions. 4247 continue; 4248 case Instruction::PHI: { 4249 // Vectorize PHINodes. 4250 widenPHIInstruction(&I, Entry, UF, VF, PV); 4251 continue; 4252 } // End of PHI. 4253 4254 case Instruction::Add: 4255 case Instruction::FAdd: 4256 case Instruction::Sub: 4257 case Instruction::FSub: 4258 case Instruction::Mul: 4259 case Instruction::FMul: 4260 case Instruction::UDiv: 4261 case Instruction::SDiv: 4262 case Instruction::FDiv: 4263 case Instruction::URem: 4264 case Instruction::SRem: 4265 case Instruction::FRem: 4266 case Instruction::Shl: 4267 case Instruction::LShr: 4268 case Instruction::AShr: 4269 case Instruction::And: 4270 case Instruction::Or: 4271 case Instruction::Xor: { 4272 // Just widen binops. 4273 auto *BinOp = cast<BinaryOperator>(&I); 4274 setDebugLocFromInst(Builder, BinOp); 4275 VectorParts &A = getVectorValue(BinOp->getOperand(0)); 4276 VectorParts &B = getVectorValue(BinOp->getOperand(1)); 4277 4278 // Use this vector value for all users of the original instruction. 4279 for (unsigned Part = 0; Part < UF; ++Part) { 4280 Value *V = Builder.CreateBinOp(BinOp->getOpcode(), A[Part], B[Part]); 4281 4282 if (BinaryOperator *VecOp = dyn_cast<BinaryOperator>(V)) 4283 VecOp->copyIRFlags(BinOp); 4284 4285 Entry[Part] = V; 4286 } 4287 4288 addMetadata(Entry, BinOp); 4289 break; 4290 } 4291 case Instruction::Select: { 4292 // Widen selects. 4293 // If the selector is loop invariant we can create a select 4294 // instruction with a scalar condition. Otherwise, use vector-select. 4295 auto *SE = PSE.getSE(); 4296 bool InvariantCond = 4297 SE->isLoopInvariant(PSE.getSCEV(I.getOperand(0)), OrigLoop); 4298 setDebugLocFromInst(Builder, &I); 4299 4300 // The condition can be loop invariant but still defined inside the 4301 // loop. This means that we can't just use the original 'cond' value. 4302 // We have to take the 'vectorized' value and pick the first lane. 4303 // Instcombine will make this a no-op. 4304 VectorParts &Cond = getVectorValue(I.getOperand(0)); 4305 VectorParts &Op0 = getVectorValue(I.getOperand(1)); 4306 VectorParts &Op1 = getVectorValue(I.getOperand(2)); 4307 4308 Value *ScalarCond = 4309 (VF == 1) 4310 ? Cond[0] 4311 : Builder.CreateExtractElement(Cond[0], Builder.getInt32(0)); 4312 4313 for (unsigned Part = 0; Part < UF; ++Part) { 4314 Entry[Part] = Builder.CreateSelect( 4315 InvariantCond ? ScalarCond : Cond[Part], Op0[Part], Op1[Part]); 4316 } 4317 4318 addMetadata(Entry, &I); 4319 break; 4320 } 4321 4322 case Instruction::ICmp: 4323 case Instruction::FCmp: { 4324 // Widen compares. Generate vector compares. 4325 bool FCmp = (I.getOpcode() == Instruction::FCmp); 4326 auto *Cmp = dyn_cast<CmpInst>(&I); 4327 setDebugLocFromInst(Builder, Cmp); 4328 VectorParts &A = getVectorValue(Cmp->getOperand(0)); 4329 VectorParts &B = getVectorValue(Cmp->getOperand(1)); 4330 for (unsigned Part = 0; Part < UF; ++Part) { 4331 Value *C = nullptr; 4332 if (FCmp) { 4333 C = Builder.CreateFCmp(Cmp->getPredicate(), A[Part], B[Part]); 4334 cast<FCmpInst>(C)->copyFastMathFlags(Cmp); 4335 } else { 4336 C = Builder.CreateICmp(Cmp->getPredicate(), A[Part], B[Part]); 4337 } 4338 Entry[Part] = C; 4339 } 4340 4341 addMetadata(Entry, &I); 4342 break; 4343 } 4344 4345 case Instruction::Store: 4346 case Instruction::Load: 4347 vectorizeMemoryInstruction(&I); 4348 break; 4349 case Instruction::ZExt: 4350 case Instruction::SExt: 4351 case Instruction::FPToUI: 4352 case Instruction::FPToSI: 4353 case Instruction::FPExt: 4354 case Instruction::PtrToInt: 4355 case Instruction::IntToPtr: 4356 case Instruction::SIToFP: 4357 case Instruction::UIToFP: 4358 case Instruction::Trunc: 4359 case Instruction::FPTrunc: 4360 case Instruction::BitCast: { 4361 auto *CI = dyn_cast<CastInst>(&I); 4362 setDebugLocFromInst(Builder, CI); 4363 4364 // Optimize the special case where the source is a constant integer 4365 // induction variable. Notice that we can only optimize the 'trunc' case 4366 // because (a) FP conversions lose precision, (b) sext/zext may wrap, and 4367 // (c) other casts depend on pointer size. 4368 auto ID = Legal->getInductionVars()->lookup(OldInduction); 4369 if (isa<TruncInst>(CI) && CI->getOperand(0) == OldInduction && 4370 ID.getConstIntStepValue()) { 4371 widenIntInduction(OldInduction, Entry, cast<TruncInst>(CI)); 4372 addMetadata(Entry, &I); 4373 break; 4374 } 4375 4376 /// Vectorize casts. 4377 Type *DestTy = 4378 (VF == 1) ? CI->getType() : VectorType::get(CI->getType(), VF); 4379 4380 VectorParts &A = getVectorValue(CI->getOperand(0)); 4381 for (unsigned Part = 0; Part < UF; ++Part) 4382 Entry[Part] = Builder.CreateCast(CI->getOpcode(), A[Part], DestTy); 4383 addMetadata(Entry, &I); 4384 break; 4385 } 4386 4387 case Instruction::Call: { 4388 // Ignore dbg intrinsics. 4389 if (isa<DbgInfoIntrinsic>(I)) 4390 break; 4391 setDebugLocFromInst(Builder, &I); 4392 4393 Module *M = BB->getParent()->getParent(); 4394 auto *CI = cast<CallInst>(&I); 4395 4396 StringRef FnName = CI->getCalledFunction()->getName(); 4397 Function *F = CI->getCalledFunction(); 4398 Type *RetTy = ToVectorTy(CI->getType(), VF); 4399 SmallVector<Type *, 4> Tys; 4400 for (Value *ArgOperand : CI->arg_operands()) 4401 Tys.push_back(ToVectorTy(ArgOperand->getType(), VF)); 4402 4403 Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI); 4404 if (ID && (ID == Intrinsic::assume || ID == Intrinsic::lifetime_end || 4405 ID == Intrinsic::lifetime_start)) { 4406 scalarizeInstruction(&I); 4407 break; 4408 } 4409 // The flag shows whether we use Intrinsic or a usual Call for vectorized 4410 // version of the instruction. 4411 // Is it beneficial to perform intrinsic call compared to lib call? 4412 bool NeedToScalarize; 4413 unsigned CallCost = getVectorCallCost(CI, VF, *TTI, TLI, NeedToScalarize); 4414 bool UseVectorIntrinsic = 4415 ID && getVectorIntrinsicCost(CI, VF, *TTI, TLI) <= CallCost; 4416 if (!UseVectorIntrinsic && NeedToScalarize) { 4417 scalarizeInstruction(&I); 4418 break; 4419 } 4420 4421 for (unsigned Part = 0; Part < UF; ++Part) { 4422 SmallVector<Value *, 4> Args; 4423 for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i) { 4424 Value *Arg = CI->getArgOperand(i); 4425 // Some intrinsics have a scalar argument - don't replace it with a 4426 // vector. 4427 if (!UseVectorIntrinsic || !hasVectorInstrinsicScalarOpd(ID, i)) { 4428 VectorParts &VectorArg = getVectorValue(CI->getArgOperand(i)); 4429 Arg = VectorArg[Part]; 4430 } 4431 Args.push_back(Arg); 4432 } 4433 4434 Function *VectorF; 4435 if (UseVectorIntrinsic) { 4436 // Use vector version of the intrinsic. 4437 Type *TysForDecl[] = {CI->getType()}; 4438 if (VF > 1) 4439 TysForDecl[0] = VectorType::get(CI->getType()->getScalarType(), VF); 4440 VectorF = Intrinsic::getDeclaration(M, ID, TysForDecl); 4441 } else { 4442 // Use vector version of the library call. 4443 StringRef VFnName = TLI->getVectorizedFunction(FnName, VF); 4444 assert(!VFnName.empty() && "Vector function name is empty."); 4445 VectorF = M->getFunction(VFnName); 4446 if (!VectorF) { 4447 // Generate a declaration 4448 FunctionType *FTy = FunctionType::get(RetTy, Tys, false); 4449 VectorF = 4450 Function::Create(FTy, Function::ExternalLinkage, VFnName, M); 4451 VectorF->copyAttributesFrom(F); 4452 } 4453 } 4454 assert(VectorF && "Can't create vector function."); 4455 4456 SmallVector<OperandBundleDef, 1> OpBundles; 4457 CI->getOperandBundlesAsDefs(OpBundles); 4458 CallInst *V = Builder.CreateCall(VectorF, Args, OpBundles); 4459 4460 if (isa<FPMathOperator>(V)) 4461 V->copyFastMathFlags(CI); 4462 4463 Entry[Part] = V; 4464 } 4465 4466 addMetadata(Entry, &I); 4467 break; 4468 } 4469 4470 default: 4471 // All other instructions are unsupported. Scalarize them. 4472 scalarizeInstruction(&I); 4473 break; 4474 } // end of switch. 4475 } // end of for_each instr. 4476 } 4477 4478 void InnerLoopVectorizer::updateAnalysis() { 4479 // Forget the original basic block. 4480 PSE.getSE()->forgetLoop(OrigLoop); 4481 4482 // Update the dominator tree information. 4483 assert(DT->properlyDominates(LoopBypassBlocks.front(), LoopExitBlock) && 4484 "Entry does not dominate exit."); 4485 4486 // We don't predicate stores by this point, so the vector body should be a 4487 // single loop. 4488 DT->addNewBlock(LoopVectorBody, LoopVectorPreHeader); 4489 4490 DT->addNewBlock(LoopMiddleBlock, LoopVectorBody); 4491 DT->addNewBlock(LoopScalarPreHeader, LoopBypassBlocks[0]); 4492 DT->changeImmediateDominator(LoopScalarBody, LoopScalarPreHeader); 4493 DT->changeImmediateDominator(LoopExitBlock, LoopBypassBlocks[0]); 4494 4495 DEBUG(DT->verifyDomTree()); 4496 } 4497 4498 /// \brief Check whether it is safe to if-convert this phi node. 4499 /// 4500 /// Phi nodes with constant expressions that can trap are not safe to if 4501 /// convert. 4502 static bool canIfConvertPHINodes(BasicBlock *BB) { 4503 for (Instruction &I : *BB) { 4504 auto *Phi = dyn_cast<PHINode>(&I); 4505 if (!Phi) 4506 return true; 4507 for (Value *V : Phi->incoming_values()) 4508 if (auto *C = dyn_cast<Constant>(V)) 4509 if (C->canTrap()) 4510 return false; 4511 } 4512 return true; 4513 } 4514 4515 bool LoopVectorizationLegality::canVectorizeWithIfConvert() { 4516 if (!EnableIfConversion) { 4517 emitAnalysis(VectorizationReport() << "if-conversion is disabled"); 4518 return false; 4519 } 4520 4521 assert(TheLoop->getNumBlocks() > 1 && "Single block loops are vectorizable"); 4522 4523 // A list of pointers that we can safely read and write to. 4524 SmallPtrSet<Value *, 8> SafePointes; 4525 4526 // Collect safe addresses. 4527 for (BasicBlock *BB : TheLoop->blocks()) { 4528 if (blockNeedsPredication(BB)) 4529 continue; 4530 4531 for (Instruction &I : *BB) 4532 if (auto *Ptr = getPointerOperand(&I)) 4533 SafePointes.insert(Ptr); 4534 } 4535 4536 // Collect the blocks that need predication. 4537 BasicBlock *Header = TheLoop->getHeader(); 4538 for (BasicBlock *BB : TheLoop->blocks()) { 4539 // We don't support switch statements inside loops. 4540 if (!isa<BranchInst>(BB->getTerminator())) { 4541 emitAnalysis(VectorizationReport(BB->getTerminator()) 4542 << "loop contains a switch statement"); 4543 return false; 4544 } 4545 4546 // We must be able to predicate all blocks that need to be predicated. 4547 if (blockNeedsPredication(BB)) { 4548 if (!blockCanBePredicated(BB, SafePointes)) { 4549 emitAnalysis(VectorizationReport(BB->getTerminator()) 4550 << "control flow cannot be substituted for a select"); 4551 return false; 4552 } 4553 } else if (BB != Header && !canIfConvertPHINodes(BB)) { 4554 emitAnalysis(VectorizationReport(BB->getTerminator()) 4555 << "control flow cannot be substituted for a select"); 4556 return false; 4557 } 4558 } 4559 4560 // We can if-convert this loop. 4561 return true; 4562 } 4563 4564 bool LoopVectorizationLegality::canVectorize() { 4565 // We must have a loop in canonical form. Loops with indirectbr in them cannot 4566 // be canonicalized. 4567 if (!TheLoop->getLoopPreheader()) { 4568 emitAnalysis(VectorizationReport() 4569 << "loop control flow is not understood by vectorizer"); 4570 return false; 4571 } 4572 4573 // FIXME: The code is currently dead, since the loop gets sent to 4574 // LoopVectorizationLegality is already an innermost loop. 4575 // 4576 // We can only vectorize innermost loops. 4577 if (!TheLoop->empty()) { 4578 emitAnalysis(VectorizationReport() << "loop is not the innermost loop"); 4579 return false; 4580 } 4581 4582 // We must have a single backedge. 4583 if (TheLoop->getNumBackEdges() != 1) { 4584 emitAnalysis(VectorizationReport() 4585 << "loop control flow is not understood by vectorizer"); 4586 return false; 4587 } 4588 4589 // We must have a single exiting block. 4590 if (!TheLoop->getExitingBlock()) { 4591 emitAnalysis(VectorizationReport() 4592 << "loop control flow is not understood by vectorizer"); 4593 return false; 4594 } 4595 4596 // We only handle bottom-tested loops, i.e. loop in which the condition is 4597 // checked at the end of each iteration. With that we can assume that all 4598 // instructions in the loop are executed the same number of times. 4599 if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch()) { 4600 emitAnalysis(VectorizationReport() 4601 << "loop control flow is not understood by vectorizer"); 4602 return false; 4603 } 4604 4605 // We need to have a loop header. 4606 DEBUG(dbgs() << "LV: Found a loop: " << TheLoop->getHeader()->getName() 4607 << '\n'); 4608 4609 // Check if we can if-convert non-single-bb loops. 4610 unsigned NumBlocks = TheLoop->getNumBlocks(); 4611 if (NumBlocks != 1 && !canVectorizeWithIfConvert()) { 4612 DEBUG(dbgs() << "LV: Can't if-convert the loop.\n"); 4613 return false; 4614 } 4615 4616 // ScalarEvolution needs to be able to find the exit count. 4617 const SCEV *ExitCount = PSE.getBackedgeTakenCount(); 4618 if (ExitCount == PSE.getSE()->getCouldNotCompute()) { 4619 emitAnalysis(VectorizationReport() 4620 << "could not determine number of loop iterations"); 4621 DEBUG(dbgs() << "LV: SCEV could not compute the loop exit count.\n"); 4622 return false; 4623 } 4624 4625 // Check if we can vectorize the instructions and CFG in this loop. 4626 if (!canVectorizeInstrs()) { 4627 DEBUG(dbgs() << "LV: Can't vectorize the instructions or CFG\n"); 4628 return false; 4629 } 4630 4631 // Go over each instruction and look at memory deps. 4632 if (!canVectorizeMemory()) { 4633 DEBUG(dbgs() << "LV: Can't vectorize due to memory conflicts\n"); 4634 return false; 4635 } 4636 4637 DEBUG(dbgs() << "LV: We can vectorize this loop" 4638 << (LAI->getRuntimePointerChecking()->Need 4639 ? " (with a runtime bound check)" 4640 : "") 4641 << "!\n"); 4642 4643 bool UseInterleaved = TTI->enableInterleavedAccessVectorization(); 4644 4645 // If an override option has been passed in for interleaved accesses, use it. 4646 if (EnableInterleavedMemAccesses.getNumOccurrences() > 0) 4647 UseInterleaved = EnableInterleavedMemAccesses; 4648 4649 // Analyze interleaved memory accesses. 4650 if (UseInterleaved) 4651 InterleaveInfo.analyzeInterleaving(*getSymbolicStrides()); 4652 4653 // Collect all instructions that are known to be uniform after vectorization. 4654 collectLoopUniforms(); 4655 4656 // Collect all instructions that are known to be scalar after vectorization. 4657 collectLoopScalars(); 4658 4659 unsigned SCEVThreshold = VectorizeSCEVCheckThreshold; 4660 if (Hints->getForce() == LoopVectorizeHints::FK_Enabled) 4661 SCEVThreshold = PragmaVectorizeSCEVCheckThreshold; 4662 4663 if (PSE.getUnionPredicate().getComplexity() > SCEVThreshold) { 4664 emitAnalysis(VectorizationReport() 4665 << "Too many SCEV assumptions need to be made and checked " 4666 << "at runtime"); 4667 DEBUG(dbgs() << "LV: Too many SCEV checks needed.\n"); 4668 return false; 4669 } 4670 4671 // Okay! We can vectorize. At this point we don't have any other mem analysis 4672 // which may limit our maximum vectorization factor, so just return true with 4673 // no restrictions. 4674 return true; 4675 } 4676 4677 static Type *convertPointerToIntegerType(const DataLayout &DL, Type *Ty) { 4678 if (Ty->isPointerTy()) 4679 return DL.getIntPtrType(Ty); 4680 4681 // It is possible that char's or short's overflow when we ask for the loop's 4682 // trip count, work around this by changing the type size. 4683 if (Ty->getScalarSizeInBits() < 32) 4684 return Type::getInt32Ty(Ty->getContext()); 4685 4686 return Ty; 4687 } 4688 4689 static Type *getWiderType(const DataLayout &DL, Type *Ty0, Type *Ty1) { 4690 Ty0 = convertPointerToIntegerType(DL, Ty0); 4691 Ty1 = convertPointerToIntegerType(DL, Ty1); 4692 if (Ty0->getScalarSizeInBits() > Ty1->getScalarSizeInBits()) 4693 return Ty0; 4694 return Ty1; 4695 } 4696 4697 /// \brief Check that the instruction has outside loop users and is not an 4698 /// identified reduction variable. 4699 static bool hasOutsideLoopUser(const Loop *TheLoop, Instruction *Inst, 4700 SmallPtrSetImpl<Value *> &AllowedExit) { 4701 // Reduction and Induction instructions are allowed to have exit users. All 4702 // other instructions must not have external users. 4703 if (!AllowedExit.count(Inst)) 4704 // Check that all of the users of the loop are inside the BB. 4705 for (User *U : Inst->users()) { 4706 Instruction *UI = cast<Instruction>(U); 4707 // This user may be a reduction exit value. 4708 if (!TheLoop->contains(UI)) { 4709 DEBUG(dbgs() << "LV: Found an outside user for : " << *UI << '\n'); 4710 return true; 4711 } 4712 } 4713 return false; 4714 } 4715 4716 void LoopVectorizationLegality::addInductionPhi( 4717 PHINode *Phi, const InductionDescriptor &ID, 4718 SmallPtrSetImpl<Value *> &AllowedExit) { 4719 Inductions[Phi] = ID; 4720 Type *PhiTy = Phi->getType(); 4721 const DataLayout &DL = Phi->getModule()->getDataLayout(); 4722 4723 // Get the widest type. 4724 if (!PhiTy->isFloatingPointTy()) { 4725 if (!WidestIndTy) 4726 WidestIndTy = convertPointerToIntegerType(DL, PhiTy); 4727 else 4728 WidestIndTy = getWiderType(DL, PhiTy, WidestIndTy); 4729 } 4730 4731 // Int inductions are special because we only allow one IV. 4732 if (ID.getKind() == InductionDescriptor::IK_IntInduction && 4733 ID.getConstIntStepValue() && 4734 ID.getConstIntStepValue()->isOne() && 4735 isa<Constant>(ID.getStartValue()) && 4736 cast<Constant>(ID.getStartValue())->isNullValue()) { 4737 4738 // Use the phi node with the widest type as induction. Use the last 4739 // one if there are multiple (no good reason for doing this other 4740 // than it is expedient). We've checked that it begins at zero and 4741 // steps by one, so this is a canonical induction variable. 4742 if (!Induction || PhiTy == WidestIndTy) 4743 Induction = Phi; 4744 } 4745 4746 // Both the PHI node itself, and the "post-increment" value feeding 4747 // back into the PHI node may have external users. 4748 AllowedExit.insert(Phi); 4749 AllowedExit.insert(Phi->getIncomingValueForBlock(TheLoop->getLoopLatch())); 4750 4751 DEBUG(dbgs() << "LV: Found an induction variable.\n"); 4752 return; 4753 } 4754 4755 bool LoopVectorizationLegality::canVectorizeInstrs() { 4756 BasicBlock *Header = TheLoop->getHeader(); 4757 4758 // Look for the attribute signaling the absence of NaNs. 4759 Function &F = *Header->getParent(); 4760 HasFunNoNaNAttr = 4761 F.getFnAttribute("no-nans-fp-math").getValueAsString() == "true"; 4762 4763 // For each block in the loop. 4764 for (BasicBlock *BB : TheLoop->blocks()) { 4765 // Scan the instructions in the block and look for hazards. 4766 for (Instruction &I : *BB) { 4767 if (auto *Phi = dyn_cast<PHINode>(&I)) { 4768 Type *PhiTy = Phi->getType(); 4769 // Check that this PHI type is allowed. 4770 if (!PhiTy->isIntegerTy() && !PhiTy->isFloatingPointTy() && 4771 !PhiTy->isPointerTy()) { 4772 emitAnalysis(VectorizationReport(Phi) 4773 << "loop control flow is not understood by vectorizer"); 4774 DEBUG(dbgs() << "LV: Found an non-int non-pointer PHI.\n"); 4775 return false; 4776 } 4777 4778 // If this PHINode is not in the header block, then we know that we 4779 // can convert it to select during if-conversion. No need to check if 4780 // the PHIs in this block are induction or reduction variables. 4781 if (BB != Header) { 4782 // Check that this instruction has no outside users or is an 4783 // identified reduction value with an outside user. 4784 if (!hasOutsideLoopUser(TheLoop, Phi, AllowedExit)) 4785 continue; 4786 emitAnalysis(VectorizationReport(Phi) 4787 << "value could not be identified as " 4788 "an induction or reduction variable"); 4789 return false; 4790 } 4791 4792 // We only allow if-converted PHIs with exactly two incoming values. 4793 if (Phi->getNumIncomingValues() != 2) { 4794 emitAnalysis(VectorizationReport(Phi) 4795 << "control flow not understood by vectorizer"); 4796 DEBUG(dbgs() << "LV: Found an invalid PHI.\n"); 4797 return false; 4798 } 4799 4800 RecurrenceDescriptor RedDes; 4801 if (RecurrenceDescriptor::isReductionPHI(Phi, TheLoop, RedDes)) { 4802 if (RedDes.hasUnsafeAlgebra()) 4803 Requirements->addUnsafeAlgebraInst(RedDes.getUnsafeAlgebraInst()); 4804 AllowedExit.insert(RedDes.getLoopExitInstr()); 4805 Reductions[Phi] = RedDes; 4806 continue; 4807 } 4808 4809 InductionDescriptor ID; 4810 if (InductionDescriptor::isInductionPHI(Phi, TheLoop, PSE, ID)) { 4811 addInductionPhi(Phi, ID, AllowedExit); 4812 if (ID.hasUnsafeAlgebra() && !HasFunNoNaNAttr) 4813 Requirements->addUnsafeAlgebraInst(ID.getUnsafeAlgebraInst()); 4814 continue; 4815 } 4816 4817 if (RecurrenceDescriptor::isFirstOrderRecurrence(Phi, TheLoop, DT)) { 4818 FirstOrderRecurrences.insert(Phi); 4819 continue; 4820 } 4821 4822 // As a last resort, coerce the PHI to a AddRec expression 4823 // and re-try classifying it a an induction PHI. 4824 if (InductionDescriptor::isInductionPHI(Phi, TheLoop, PSE, ID, true)) { 4825 addInductionPhi(Phi, ID, AllowedExit); 4826 continue; 4827 } 4828 4829 emitAnalysis(VectorizationReport(Phi) 4830 << "value that could not be identified as " 4831 "reduction is used outside the loop"); 4832 DEBUG(dbgs() << "LV: Found an unidentified PHI." << *Phi << "\n"); 4833 return false; 4834 } // end of PHI handling 4835 4836 // We handle calls that: 4837 // * Are debug info intrinsics. 4838 // * Have a mapping to an IR intrinsic. 4839 // * Have a vector version available. 4840 auto *CI = dyn_cast<CallInst>(&I); 4841 if (CI && !getVectorIntrinsicIDForCall(CI, TLI) && 4842 !isa<DbgInfoIntrinsic>(CI) && 4843 !(CI->getCalledFunction() && TLI && 4844 TLI->isFunctionVectorizable(CI->getCalledFunction()->getName()))) { 4845 emitAnalysis(VectorizationReport(CI) 4846 << "call instruction cannot be vectorized"); 4847 DEBUG(dbgs() << "LV: Found a non-intrinsic, non-libfunc callsite.\n"); 4848 return false; 4849 } 4850 4851 // Intrinsics such as powi,cttz and ctlz are legal to vectorize if the 4852 // second argument is the same (i.e. loop invariant) 4853 if (CI && hasVectorInstrinsicScalarOpd( 4854 getVectorIntrinsicIDForCall(CI, TLI), 1)) { 4855 auto *SE = PSE.getSE(); 4856 if (!SE->isLoopInvariant(PSE.getSCEV(CI->getOperand(1)), TheLoop)) { 4857 emitAnalysis(VectorizationReport(CI) 4858 << "intrinsic instruction cannot be vectorized"); 4859 DEBUG(dbgs() << "LV: Found unvectorizable intrinsic " << *CI << "\n"); 4860 return false; 4861 } 4862 } 4863 4864 // Check that the instruction return type is vectorizable. 4865 // Also, we can't vectorize extractelement instructions. 4866 if ((!VectorType::isValidElementType(I.getType()) && 4867 !I.getType()->isVoidTy()) || 4868 isa<ExtractElementInst>(I)) { 4869 emitAnalysis(VectorizationReport(&I) 4870 << "instruction return type cannot be vectorized"); 4871 DEBUG(dbgs() << "LV: Found unvectorizable type.\n"); 4872 return false; 4873 } 4874 4875 // Check that the stored type is vectorizable. 4876 if (auto *ST = dyn_cast<StoreInst>(&I)) { 4877 Type *T = ST->getValueOperand()->getType(); 4878 if (!VectorType::isValidElementType(T)) { 4879 emitAnalysis(VectorizationReport(ST) 4880 << "store instruction cannot be vectorized"); 4881 return false; 4882 } 4883 4884 // FP instructions can allow unsafe algebra, thus vectorizable by 4885 // non-IEEE-754 compliant SIMD units. 4886 // This applies to floating-point math operations and calls, not memory 4887 // operations, shuffles, or casts, as they don't change precision or 4888 // semantics. 4889 } else if (I.getType()->isFloatingPointTy() && (CI || I.isBinaryOp()) && 4890 !I.hasUnsafeAlgebra()) { 4891 DEBUG(dbgs() << "LV: Found FP op with unsafe algebra.\n"); 4892 Hints->setPotentiallyUnsafe(); 4893 } 4894 4895 // Reduction instructions are allowed to have exit users. 4896 // All other instructions must not have external users. 4897 if (hasOutsideLoopUser(TheLoop, &I, AllowedExit)) { 4898 emitAnalysis(VectorizationReport(&I) 4899 << "value cannot be used outside the loop"); 4900 return false; 4901 } 4902 4903 } // next instr. 4904 } 4905 4906 if (!Induction) { 4907 DEBUG(dbgs() << "LV: Did not find one integer induction var.\n"); 4908 if (Inductions.empty()) { 4909 emitAnalysis(VectorizationReport() 4910 << "loop induction variable could not be identified"); 4911 return false; 4912 } 4913 } 4914 4915 // Now we know the widest induction type, check if our found induction 4916 // is the same size. If it's not, unset it here and InnerLoopVectorizer 4917 // will create another. 4918 if (Induction && WidestIndTy != Induction->getType()) 4919 Induction = nullptr; 4920 4921 return true; 4922 } 4923 4924 void LoopVectorizationLegality::collectLoopScalars() { 4925 4926 // If an instruction is uniform after vectorization, it will remain scalar. 4927 Scalars.insert(Uniforms.begin(), Uniforms.end()); 4928 4929 // Collect the getelementptr instructions that will not be vectorized. A 4930 // getelementptr instruction is only vectorized if it is used for a legal 4931 // gather or scatter operation. 4932 for (auto *BB : TheLoop->blocks()) 4933 for (auto &I : *BB) { 4934 if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) { 4935 Scalars.insert(GEP); 4936 continue; 4937 } 4938 auto *Ptr = getPointerOperand(&I); 4939 if (!Ptr) 4940 continue; 4941 auto *GEP = getGEPInstruction(Ptr); 4942 if (GEP && isLegalGatherOrScatter(&I)) 4943 Scalars.erase(GEP); 4944 } 4945 4946 // An induction variable will remain scalar if all users of the induction 4947 // variable and induction variable update remain scalar. 4948 auto *Latch = TheLoop->getLoopLatch(); 4949 for (auto &Induction : *getInductionVars()) { 4950 auto *Ind = Induction.first; 4951 auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch)); 4952 4953 // Determine if all users of the induction variable are scalar after 4954 // vectorization. 4955 auto ScalarInd = all_of(Ind->users(), [&](User *U) -> bool { 4956 auto *I = cast<Instruction>(U); 4957 return I == IndUpdate || !TheLoop->contains(I) || Scalars.count(I); 4958 }); 4959 if (!ScalarInd) 4960 continue; 4961 4962 // Determine if all users of the induction variable update instruction are 4963 // scalar after vectorization. 4964 auto ScalarIndUpdate = all_of(IndUpdate->users(), [&](User *U) -> bool { 4965 auto *I = cast<Instruction>(U); 4966 return I == Ind || !TheLoop->contains(I) || Scalars.count(I); 4967 }); 4968 if (!ScalarIndUpdate) 4969 continue; 4970 4971 // The induction variable and its update instruction will remain scalar. 4972 Scalars.insert(Ind); 4973 Scalars.insert(IndUpdate); 4974 } 4975 } 4976 4977 void LoopVectorizationLegality::collectLoopUniforms() { 4978 // We now know that the loop is vectorizable! 4979 // Collect instructions inside the loop that will remain uniform after 4980 // vectorization. 4981 4982 // Global values, params and instructions outside of current loop are out of 4983 // scope. 4984 auto isOutOfScope = [&](Value *V) -> bool { 4985 Instruction *I = dyn_cast<Instruction>(V); 4986 return (!I || !TheLoop->contains(I)); 4987 }; 4988 4989 SetVector<Instruction *> Worklist; 4990 BasicBlock *Latch = TheLoop->getLoopLatch(); 4991 // Start with the conditional branch. 4992 if (!isOutOfScope(Latch->getTerminator()->getOperand(0))) { 4993 Instruction *Cmp = cast<Instruction>(Latch->getTerminator()->getOperand(0)); 4994 Worklist.insert(Cmp); 4995 DEBUG(dbgs() << "LV: Found uniform instruction: " << *Cmp << "\n"); 4996 } 4997 4998 // Add all consecutive pointer values; these values will be uniform after 4999 // vectorization (and subsequent cleanup). Although non-consecutive, we also 5000 // add the pointer operands of interleaved accesses since they are treated 5001 // like consecutive pointers during vectorization. 5002 for (auto *BB : TheLoop->blocks()) 5003 for (auto &I : *BB) { 5004 Instruction *Ptr = nullptr; 5005 if (I.getType()->isPointerTy() && isConsecutivePtr(&I)) 5006 Ptr = &I; 5007 else if (isAccessInterleaved(&I)) 5008 Ptr = cast<Instruction>(getPointerOperand(&I)); 5009 else 5010 continue; 5011 Worklist.insert(Ptr); 5012 DEBUG(dbgs() << "LV: Found uniform instruction: " << *Ptr << "\n"); 5013 } 5014 5015 // Expand Worklist in topological order: whenever a new instruction 5016 // is added , its users should be either already inside Worklist, or 5017 // out of scope. It ensures a uniform instruction will only be used 5018 // by uniform instructions or out of scope instructions. 5019 unsigned idx = 0; 5020 while (idx != Worklist.size()) { 5021 Instruction *I = Worklist[idx++]; 5022 5023 for (auto OV : I->operand_values()) { 5024 if (isOutOfScope(OV)) 5025 continue; 5026 auto *OI = cast<Instruction>(OV); 5027 if (all_of(OI->users(), [&](User *U) -> bool { 5028 return isOutOfScope(U) || Worklist.count(cast<Instruction>(U)); 5029 })) { 5030 Worklist.insert(OI); 5031 DEBUG(dbgs() << "LV: Found uniform instruction: " << *OI << "\n"); 5032 } 5033 } 5034 } 5035 5036 // For an instruction to be added into Worklist above, all its users inside 5037 // the current loop should be already added into Worklist. This condition 5038 // cannot be true for phi instructions which is always in a dependence loop. 5039 // Because any instruction in the dependence cycle always depends on others 5040 // in the cycle to be added into Worklist first, the result is no ones in 5041 // the cycle will be added into Worklist in the end. 5042 // That is why we process PHI separately. 5043 for (auto &Induction : *getInductionVars()) { 5044 auto *PN = Induction.first; 5045 auto *UpdateV = PN->getIncomingValueForBlock(TheLoop->getLoopLatch()); 5046 if (all_of(PN->users(), 5047 [&](User *U) -> bool { 5048 return U == UpdateV || isOutOfScope(U) || 5049 Worklist.count(cast<Instruction>(U)); 5050 }) && 5051 all_of(UpdateV->users(), [&](User *U) -> bool { 5052 return U == PN || isOutOfScope(U) || 5053 Worklist.count(cast<Instruction>(U)); 5054 })) { 5055 Worklist.insert(cast<Instruction>(PN)); 5056 Worklist.insert(cast<Instruction>(UpdateV)); 5057 DEBUG(dbgs() << "LV: Found uniform instruction: " << *PN << "\n"); 5058 DEBUG(dbgs() << "LV: Found uniform instruction: " << *UpdateV << "\n"); 5059 } 5060 } 5061 5062 Uniforms.insert(Worklist.begin(), Worklist.end()); 5063 } 5064 5065 bool LoopVectorizationLegality::canVectorizeMemory() { 5066 LAI = &(*GetLAA)(*TheLoop); 5067 InterleaveInfo.setLAI(LAI); 5068 auto &OptionalReport = LAI->getReport(); 5069 if (OptionalReport) 5070 emitAnalysis(VectorizationReport(*OptionalReport)); 5071 if (!LAI->canVectorizeMemory()) 5072 return false; 5073 5074 if (LAI->hasStoreToLoopInvariantAddress()) { 5075 emitAnalysis( 5076 VectorizationReport() 5077 << "write to a loop invariant address could not be vectorized"); 5078 DEBUG(dbgs() << "LV: We don't allow storing to uniform addresses\n"); 5079 return false; 5080 } 5081 5082 Requirements->addRuntimePointerChecks(LAI->getNumRuntimePointerChecks()); 5083 PSE.addPredicate(LAI->getPSE().getUnionPredicate()); 5084 5085 return true; 5086 } 5087 5088 bool LoopVectorizationLegality::isInductionVariable(const Value *V) { 5089 Value *In0 = const_cast<Value *>(V); 5090 PHINode *PN = dyn_cast_or_null<PHINode>(In0); 5091 if (!PN) 5092 return false; 5093 5094 return Inductions.count(PN); 5095 } 5096 5097 bool LoopVectorizationLegality::isFirstOrderRecurrence(const PHINode *Phi) { 5098 return FirstOrderRecurrences.count(Phi); 5099 } 5100 5101 bool LoopVectorizationLegality::blockNeedsPredication(BasicBlock *BB) { 5102 return LoopAccessInfo::blockNeedsPredication(BB, TheLoop, DT); 5103 } 5104 5105 bool LoopVectorizationLegality::blockCanBePredicated( 5106 BasicBlock *BB, SmallPtrSetImpl<Value *> &SafePtrs) { 5107 const bool IsAnnotatedParallel = TheLoop->isAnnotatedParallel(); 5108 5109 for (Instruction &I : *BB) { 5110 // Check that we don't have a constant expression that can trap as operand. 5111 for (Value *Operand : I.operands()) { 5112 if (auto *C = dyn_cast<Constant>(Operand)) 5113 if (C->canTrap()) 5114 return false; 5115 } 5116 // We might be able to hoist the load. 5117 if (I.mayReadFromMemory()) { 5118 auto *LI = dyn_cast<LoadInst>(&I); 5119 if (!LI) 5120 return false; 5121 if (!SafePtrs.count(LI->getPointerOperand())) { 5122 if (isLegalMaskedLoad(LI->getType(), LI->getPointerOperand()) || 5123 isLegalMaskedGather(LI->getType())) { 5124 MaskedOp.insert(LI); 5125 continue; 5126 } 5127 // !llvm.mem.parallel_loop_access implies if-conversion safety. 5128 if (IsAnnotatedParallel) 5129 continue; 5130 return false; 5131 } 5132 } 5133 5134 if (I.mayWriteToMemory()) { 5135 auto *SI = dyn_cast<StoreInst>(&I); 5136 // We only support predication of stores in basic blocks with one 5137 // predecessor. 5138 if (!SI) 5139 return false; 5140 5141 // Build a masked store if it is legal for the target. 5142 if (isLegalMaskedStore(SI->getValueOperand()->getType(), 5143 SI->getPointerOperand()) || 5144 isLegalMaskedScatter(SI->getValueOperand()->getType())) { 5145 MaskedOp.insert(SI); 5146 continue; 5147 } 5148 5149 bool isSafePtr = (SafePtrs.count(SI->getPointerOperand()) != 0); 5150 bool isSinglePredecessor = SI->getParent()->getSinglePredecessor(); 5151 5152 if (++NumPredStores > NumberOfStoresToPredicate || !isSafePtr || 5153 !isSinglePredecessor) 5154 return false; 5155 } 5156 if (I.mayThrow()) 5157 return false; 5158 5159 // The instructions below can trap. 5160 switch (I.getOpcode()) { 5161 default: 5162 continue; 5163 case Instruction::UDiv: 5164 case Instruction::SDiv: 5165 case Instruction::URem: 5166 case Instruction::SRem: 5167 return false; 5168 } 5169 } 5170 5171 return true; 5172 } 5173 5174 void InterleavedAccessInfo::collectConstStrideAccesses( 5175 MapVector<Instruction *, StrideDescriptor> &AccessStrideInfo, 5176 const ValueToValueMap &Strides) { 5177 5178 auto &DL = TheLoop->getHeader()->getModule()->getDataLayout(); 5179 5180 // Since it's desired that the load/store instructions be maintained in 5181 // "program order" for the interleaved access analysis, we have to visit the 5182 // blocks in the loop in reverse postorder (i.e., in a topological order). 5183 // Such an ordering will ensure that any load/store that may be executed 5184 // before a second load/store will precede the second load/store in 5185 // AccessStrideInfo. 5186 LoopBlocksDFS DFS(TheLoop); 5187 DFS.perform(LI); 5188 for (BasicBlock *BB : make_range(DFS.beginRPO(), DFS.endRPO())) 5189 for (auto &I : *BB) { 5190 auto *LI = dyn_cast<LoadInst>(&I); 5191 auto *SI = dyn_cast<StoreInst>(&I); 5192 if (!LI && !SI) 5193 continue; 5194 5195 Value *Ptr = getPointerOperand(&I); 5196 int64_t Stride = getPtrStride(PSE, Ptr, TheLoop, Strides); 5197 5198 const SCEV *Scev = replaceSymbolicStrideSCEV(PSE, Strides, Ptr); 5199 PointerType *PtrTy = dyn_cast<PointerType>(Ptr->getType()); 5200 uint64_t Size = DL.getTypeAllocSize(PtrTy->getElementType()); 5201 5202 // An alignment of 0 means target ABI alignment. 5203 unsigned Align = LI ? LI->getAlignment() : SI->getAlignment(); 5204 if (!Align) 5205 Align = DL.getABITypeAlignment(PtrTy->getElementType()); 5206 5207 AccessStrideInfo[&I] = StrideDescriptor(Stride, Scev, Size, Align); 5208 } 5209 } 5210 5211 // Analyze interleaved accesses and collect them into interleaved load and 5212 // store groups. 5213 // 5214 // When generating code for an interleaved load group, we effectively hoist all 5215 // loads in the group to the location of the first load in program order. When 5216 // generating code for an interleaved store group, we sink all stores to the 5217 // location of the last store. This code motion can change the order of load 5218 // and store instructions and may break dependences. 5219 // 5220 // The code generation strategy mentioned above ensures that we won't violate 5221 // any write-after-read (WAR) dependences. 5222 // 5223 // E.g., for the WAR dependence: a = A[i]; // (1) 5224 // A[i] = b; // (2) 5225 // 5226 // The store group of (2) is always inserted at or below (2), and the load 5227 // group of (1) is always inserted at or above (1). Thus, the instructions will 5228 // never be reordered. All other dependences are checked to ensure the 5229 // correctness of the instruction reordering. 5230 // 5231 // The algorithm visits all memory accesses in the loop in bottom-up program 5232 // order. Program order is established by traversing the blocks in the loop in 5233 // reverse postorder when collecting the accesses. 5234 // 5235 // We visit the memory accesses in bottom-up order because it can simplify the 5236 // construction of store groups in the presence of write-after-write (WAW) 5237 // dependences. 5238 // 5239 // E.g., for the WAW dependence: A[i] = a; // (1) 5240 // A[i] = b; // (2) 5241 // A[i + 1] = c; // (3) 5242 // 5243 // We will first create a store group with (3) and (2). (1) can't be added to 5244 // this group because it and (2) are dependent. However, (1) can be grouped 5245 // with other accesses that may precede it in program order. Note that a 5246 // bottom-up order does not imply that WAW dependences should not be checked. 5247 void InterleavedAccessInfo::analyzeInterleaving( 5248 const ValueToValueMap &Strides) { 5249 DEBUG(dbgs() << "LV: Analyzing interleaved accesses...\n"); 5250 5251 // Holds all accesses with a constant stride. 5252 MapVector<Instruction *, StrideDescriptor> AccessStrideInfo; 5253 collectConstStrideAccesses(AccessStrideInfo, Strides); 5254 5255 if (AccessStrideInfo.empty()) 5256 return; 5257 5258 // Collect the dependences in the loop. 5259 collectDependences(); 5260 5261 // Holds all interleaved store groups temporarily. 5262 SmallSetVector<InterleaveGroup *, 4> StoreGroups; 5263 // Holds all interleaved load groups temporarily. 5264 SmallSetVector<InterleaveGroup *, 4> LoadGroups; 5265 5266 // Search in bottom-up program order for pairs of accesses (A and B) that can 5267 // form interleaved load or store groups. In the algorithm below, access A 5268 // precedes access B in program order. We initialize a group for B in the 5269 // outer loop of the algorithm, and then in the inner loop, we attempt to 5270 // insert each A into B's group if: 5271 // 5272 // 1. A and B have the same stride, 5273 // 2. A and B have the same memory object size, and 5274 // 3. A belongs in B's group according to its distance from B. 5275 // 5276 // Special care is taken to ensure group formation will not break any 5277 // dependences. 5278 for (auto BI = AccessStrideInfo.rbegin(), E = AccessStrideInfo.rend(); 5279 BI != E; ++BI) { 5280 Instruction *B = BI->first; 5281 StrideDescriptor DesB = BI->second; 5282 5283 // Initialize a group for B if it has an allowable stride. Even if we don't 5284 // create a group for B, we continue with the bottom-up algorithm to ensure 5285 // we don't break any of B's dependences. 5286 InterleaveGroup *Group = nullptr; 5287 if (isStrided(DesB.Stride)) { 5288 Group = getInterleaveGroup(B); 5289 if (!Group) { 5290 DEBUG(dbgs() << "LV: Creating an interleave group with:" << *B << '\n'); 5291 Group = createInterleaveGroup(B, DesB.Stride, DesB.Align); 5292 } 5293 if (B->mayWriteToMemory()) 5294 StoreGroups.insert(Group); 5295 else 5296 LoadGroups.insert(Group); 5297 } 5298 5299 for (auto AI = std::next(BI); AI != E; ++AI) { 5300 Instruction *A = AI->first; 5301 StrideDescriptor DesA = AI->second; 5302 5303 // Our code motion strategy implies that we can't have dependences 5304 // between accesses in an interleaved group and other accesses located 5305 // between the first and last member of the group. Note that this also 5306 // means that a group can't have more than one member at a given offset. 5307 // The accesses in a group can have dependences with other accesses, but 5308 // we must ensure we don't extend the boundaries of the group such that 5309 // we encompass those dependent accesses. 5310 // 5311 // For example, assume we have the sequence of accesses shown below in a 5312 // stride-2 loop: 5313 // 5314 // (1, 2) is a group | A[i] = a; // (1) 5315 // | A[i-1] = b; // (2) | 5316 // A[i-3] = c; // (3) 5317 // A[i] = d; // (4) | (2, 4) is not a group 5318 // 5319 // Because accesses (2) and (3) are dependent, we can group (2) with (1) 5320 // but not with (4). If we did, the dependent access (3) would be within 5321 // the boundaries of the (2, 4) group. 5322 if (!canReorderMemAccessesForInterleavedGroups(&*AI, &*BI)) { 5323 5324 // If a dependence exists and A is already in a group, we know that A 5325 // must be a store since A precedes B and WAR dependences are allowed. 5326 // Thus, A would be sunk below B. We release A's group to prevent this 5327 // illegal code motion. A will then be free to form another group with 5328 // instructions that precede it. 5329 if (isInterleaved(A)) { 5330 InterleaveGroup *StoreGroup = getInterleaveGroup(A); 5331 StoreGroups.remove(StoreGroup); 5332 releaseGroup(StoreGroup); 5333 } 5334 5335 // If a dependence exists and A is not already in a group (or it was 5336 // and we just released it), B might be hoisted above A (if B is a 5337 // load) or another store might be sunk below A (if B is a store). In 5338 // either case, we can't add additional instructions to B's group. B 5339 // will only form a group with instructions that it precedes. 5340 break; 5341 } 5342 5343 // At this point, we've checked for illegal code motion. If either A or B 5344 // isn't strided, there's nothing left to do. 5345 if (!isStrided(DesA.Stride) || !isStrided(DesB.Stride)) 5346 continue; 5347 5348 // Ignore A if it's already in a group or isn't the same kind of memory 5349 // operation as B. 5350 if (isInterleaved(A) || A->mayReadFromMemory() != B->mayReadFromMemory()) 5351 continue; 5352 5353 // Check rules 1 and 2. Ignore A if its stride or size is different from 5354 // that of B. 5355 if (DesA.Stride != DesB.Stride || DesA.Size != DesB.Size) 5356 continue; 5357 5358 // Calculate the distance from A to B. 5359 const SCEVConstant *DistToB = dyn_cast<SCEVConstant>( 5360 PSE.getSE()->getMinusSCEV(DesA.Scev, DesB.Scev)); 5361 if (!DistToB) 5362 continue; 5363 int64_t DistanceToB = DistToB->getAPInt().getSExtValue(); 5364 5365 // Check rule 3. Ignore A if its distance to B is not a multiple of the 5366 // size. 5367 if (DistanceToB % static_cast<int64_t>(DesB.Size)) 5368 continue; 5369 5370 // Ignore A if either A or B is in a predicated block. Although we 5371 // currently prevent group formation for predicated accesses, we may be 5372 // able to relax this limitation in the future once we handle more 5373 // complicated blocks. 5374 if (isPredicated(A->getParent()) || isPredicated(B->getParent())) 5375 continue; 5376 5377 // The index of A is the index of B plus A's distance to B in multiples 5378 // of the size. 5379 int IndexA = 5380 Group->getIndex(B) + DistanceToB / static_cast<int64_t>(DesB.Size); 5381 5382 // Try to insert A into B's group. 5383 if (Group->insertMember(A, IndexA, DesA.Align)) { 5384 DEBUG(dbgs() << "LV: Inserted:" << *A << '\n' 5385 << " into the interleave group with" << *B << '\n'); 5386 InterleaveGroupMap[A] = Group; 5387 5388 // Set the first load in program order as the insert position. 5389 if (A->mayReadFromMemory()) 5390 Group->setInsertPos(A); 5391 } 5392 } // Iteration over A accesses. 5393 } // Iteration over B accesses. 5394 5395 // Remove interleaved store groups with gaps. 5396 for (InterleaveGroup *Group : StoreGroups) 5397 if (Group->getNumMembers() != Group->getFactor()) 5398 releaseGroup(Group); 5399 5400 // If there is a non-reversed interleaved load group with gaps, we will need 5401 // to execute at least one scalar epilogue iteration. This will ensure that 5402 // we don't speculatively access memory out-of-bounds. Note that we only need 5403 // to look for a member at index factor - 1, since every group must have a 5404 // member at index zero. 5405 for (InterleaveGroup *Group : LoadGroups) 5406 if (!Group->getMember(Group->getFactor() - 1)) { 5407 if (Group->isReverse()) { 5408 releaseGroup(Group); 5409 } else { 5410 DEBUG(dbgs() << "LV: Interleaved group requires epilogue iteration.\n"); 5411 RequiresScalarEpilogue = true; 5412 } 5413 } 5414 } 5415 5416 LoopVectorizationCostModel::VectorizationFactor 5417 LoopVectorizationCostModel::selectVectorizationFactor(bool OptForSize) { 5418 // Width 1 means no vectorize 5419 VectorizationFactor Factor = {1U, 0U}; 5420 if (OptForSize && Legal->getRuntimePointerChecking()->Need) { 5421 emitAnalysis( 5422 VectorizationReport() 5423 << "runtime pointer checks needed. Enable vectorization of this " 5424 "loop with '#pragma clang loop vectorize(enable)' when " 5425 "compiling with -Os/-Oz"); 5426 DEBUG(dbgs() 5427 << "LV: Aborting. Runtime ptr check is required with -Os/-Oz.\n"); 5428 return Factor; 5429 } 5430 5431 if (!EnableCondStoresVectorization && Legal->getNumPredStores()) { 5432 emitAnalysis( 5433 VectorizationReport() 5434 << "store that is conditionally executed prevents vectorization"); 5435 DEBUG(dbgs() << "LV: No vectorization. There are conditional stores.\n"); 5436 return Factor; 5437 } 5438 5439 // Find the trip count. 5440 unsigned TC = PSE.getSE()->getSmallConstantTripCount(TheLoop); 5441 DEBUG(dbgs() << "LV: Found trip count: " << TC << '\n'); 5442 5443 MinBWs = computeMinimumValueSizes(TheLoop->getBlocks(), *DB, &TTI); 5444 unsigned SmallestType, WidestType; 5445 std::tie(SmallestType, WidestType) = getSmallestAndWidestTypes(); 5446 unsigned WidestRegister = TTI.getRegisterBitWidth(true); 5447 unsigned MaxSafeDepDist = -1U; 5448 5449 // Get the maximum safe dependence distance in bits computed by LAA. If the 5450 // loop contains any interleaved accesses, we divide the dependence distance 5451 // by the maximum interleave factor of all interleaved groups. Note that 5452 // although the division ensures correctness, this is a fairly conservative 5453 // computation because the maximum distance computed by LAA may not involve 5454 // any of the interleaved accesses. 5455 if (Legal->getMaxSafeDepDistBytes() != -1U) 5456 MaxSafeDepDist = 5457 Legal->getMaxSafeDepDistBytes() * 8 / Legal->getMaxInterleaveFactor(); 5458 5459 WidestRegister = 5460 ((WidestRegister < MaxSafeDepDist) ? WidestRegister : MaxSafeDepDist); 5461 unsigned MaxVectorSize = WidestRegister / WidestType; 5462 5463 DEBUG(dbgs() << "LV: The Smallest and Widest types: " << SmallestType << " / " 5464 << WidestType << " bits.\n"); 5465 DEBUG(dbgs() << "LV: The Widest register is: " << WidestRegister 5466 << " bits.\n"); 5467 5468 if (MaxVectorSize == 0) { 5469 DEBUG(dbgs() << "LV: The target has no vector registers.\n"); 5470 MaxVectorSize = 1; 5471 } 5472 5473 assert(MaxVectorSize <= 64 && "Did not expect to pack so many elements" 5474 " into one vector!"); 5475 5476 unsigned VF = MaxVectorSize; 5477 if (MaximizeBandwidth && !OptForSize) { 5478 // Collect all viable vectorization factors. 5479 SmallVector<unsigned, 8> VFs; 5480 unsigned NewMaxVectorSize = WidestRegister / SmallestType; 5481 for (unsigned VS = MaxVectorSize; VS <= NewMaxVectorSize; VS *= 2) 5482 VFs.push_back(VS); 5483 5484 // For each VF calculate its register usage. 5485 auto RUs = calculateRegisterUsage(VFs); 5486 5487 // Select the largest VF which doesn't require more registers than existing 5488 // ones. 5489 unsigned TargetNumRegisters = TTI.getNumberOfRegisters(true); 5490 for (int i = RUs.size() - 1; i >= 0; --i) { 5491 if (RUs[i].MaxLocalUsers <= TargetNumRegisters) { 5492 VF = VFs[i]; 5493 break; 5494 } 5495 } 5496 } 5497 5498 // If we optimize the program for size, avoid creating the tail loop. 5499 if (OptForSize) { 5500 // If we are unable to calculate the trip count then don't try to vectorize. 5501 if (TC < 2) { 5502 emitAnalysis( 5503 VectorizationReport() 5504 << "unable to calculate the loop count due to complex control flow"); 5505 DEBUG(dbgs() << "LV: Aborting. A tail loop is required with -Os/-Oz.\n"); 5506 return Factor; 5507 } 5508 5509 // Find the maximum SIMD width that can fit within the trip count. 5510 VF = TC % MaxVectorSize; 5511 5512 if (VF == 0) 5513 VF = MaxVectorSize; 5514 else { 5515 // If the trip count that we found modulo the vectorization factor is not 5516 // zero then we require a tail. 5517 emitAnalysis(VectorizationReport() 5518 << "cannot optimize for size and vectorize at the " 5519 "same time. Enable vectorization of this loop " 5520 "with '#pragma clang loop vectorize(enable)' " 5521 "when compiling with -Os/-Oz"); 5522 DEBUG(dbgs() << "LV: Aborting. A tail loop is required with -Os/-Oz.\n"); 5523 return Factor; 5524 } 5525 } 5526 5527 int UserVF = Hints->getWidth(); 5528 if (UserVF != 0) { 5529 assert(isPowerOf2_32(UserVF) && "VF needs to be a power of two"); 5530 DEBUG(dbgs() << "LV: Using user VF " << UserVF << ".\n"); 5531 5532 Factor.Width = UserVF; 5533 return Factor; 5534 } 5535 5536 float Cost = expectedCost(1).first; 5537 #ifndef NDEBUG 5538 const float ScalarCost = Cost; 5539 #endif /* NDEBUG */ 5540 unsigned Width = 1; 5541 DEBUG(dbgs() << "LV: Scalar loop costs: " << (int)ScalarCost << ".\n"); 5542 5543 bool ForceVectorization = Hints->getForce() == LoopVectorizeHints::FK_Enabled; 5544 // Ignore scalar width, because the user explicitly wants vectorization. 5545 if (ForceVectorization && VF > 1) { 5546 Width = 2; 5547 Cost = expectedCost(Width).first / (float)Width; 5548 } 5549 5550 for (unsigned i = 2; i <= VF; i *= 2) { 5551 // Notice that the vector loop needs to be executed less times, so 5552 // we need to divide the cost of the vector loops by the width of 5553 // the vector elements. 5554 VectorizationCostTy C = expectedCost(i); 5555 float VectorCost = C.first / (float)i; 5556 DEBUG(dbgs() << "LV: Vector loop of width " << i 5557 << " costs: " << (int)VectorCost << ".\n"); 5558 if (!C.second && !ForceVectorization) { 5559 DEBUG( 5560 dbgs() << "LV: Not considering vector loop of width " << i 5561 << " because it will not generate any vector instructions.\n"); 5562 continue; 5563 } 5564 if (VectorCost < Cost) { 5565 Cost = VectorCost; 5566 Width = i; 5567 } 5568 } 5569 5570 DEBUG(if (ForceVectorization && Width > 1 && Cost >= ScalarCost) dbgs() 5571 << "LV: Vectorization seems to be not beneficial, " 5572 << "but was forced by a user.\n"); 5573 DEBUG(dbgs() << "LV: Selecting VF: " << Width << ".\n"); 5574 Factor.Width = Width; 5575 Factor.Cost = Width * Cost; 5576 return Factor; 5577 } 5578 5579 std::pair<unsigned, unsigned> 5580 LoopVectorizationCostModel::getSmallestAndWidestTypes() { 5581 unsigned MinWidth = -1U; 5582 unsigned MaxWidth = 8; 5583 const DataLayout &DL = TheFunction->getParent()->getDataLayout(); 5584 5585 // For each block. 5586 for (BasicBlock *BB : TheLoop->blocks()) { 5587 // For each instruction in the loop. 5588 for (Instruction &I : *BB) { 5589 Type *T = I.getType(); 5590 5591 // Skip ignored values. 5592 if (ValuesToIgnore.count(&I)) 5593 continue; 5594 5595 // Only examine Loads, Stores and PHINodes. 5596 if (!isa<LoadInst>(I) && !isa<StoreInst>(I) && !isa<PHINode>(I)) 5597 continue; 5598 5599 // Examine PHI nodes that are reduction variables. Update the type to 5600 // account for the recurrence type. 5601 if (auto *PN = dyn_cast<PHINode>(&I)) { 5602 if (!Legal->isReductionVariable(PN)) 5603 continue; 5604 RecurrenceDescriptor RdxDesc = (*Legal->getReductionVars())[PN]; 5605 T = RdxDesc.getRecurrenceType(); 5606 } 5607 5608 // Examine the stored values. 5609 if (auto *ST = dyn_cast<StoreInst>(&I)) 5610 T = ST->getValueOperand()->getType(); 5611 5612 // Ignore loaded pointer types and stored pointer types that are not 5613 // consecutive. However, we do want to take consecutive stores/loads of 5614 // pointer vectors into account. 5615 if (T->isPointerTy() && !isConsecutiveLoadOrStore(&I)) 5616 continue; 5617 5618 MinWidth = std::min(MinWidth, 5619 (unsigned)DL.getTypeSizeInBits(T->getScalarType())); 5620 MaxWidth = std::max(MaxWidth, 5621 (unsigned)DL.getTypeSizeInBits(T->getScalarType())); 5622 } 5623 } 5624 5625 return {MinWidth, MaxWidth}; 5626 } 5627 5628 unsigned LoopVectorizationCostModel::selectInterleaveCount(bool OptForSize, 5629 unsigned VF, 5630 unsigned LoopCost) { 5631 5632 // -- The interleave heuristics -- 5633 // We interleave the loop in order to expose ILP and reduce the loop overhead. 5634 // There are many micro-architectural considerations that we can't predict 5635 // at this level. For example, frontend pressure (on decode or fetch) due to 5636 // code size, or the number and capabilities of the execution ports. 5637 // 5638 // We use the following heuristics to select the interleave count: 5639 // 1. If the code has reductions, then we interleave to break the cross 5640 // iteration dependency. 5641 // 2. If the loop is really small, then we interleave to reduce the loop 5642 // overhead. 5643 // 3. We don't interleave if we think that we will spill registers to memory 5644 // due to the increased register pressure. 5645 5646 // When we optimize for size, we don't interleave. 5647 if (OptForSize) 5648 return 1; 5649 5650 // We used the distance for the interleave count. 5651 if (Legal->getMaxSafeDepDistBytes() != -1U) 5652 return 1; 5653 5654 // Do not interleave loops with a relatively small trip count. 5655 unsigned TC = PSE.getSE()->getSmallConstantTripCount(TheLoop); 5656 if (TC > 1 && TC < TinyTripCountInterleaveThreshold) 5657 return 1; 5658 5659 unsigned TargetNumRegisters = TTI.getNumberOfRegisters(VF > 1); 5660 DEBUG(dbgs() << "LV: The target has " << TargetNumRegisters 5661 << " registers\n"); 5662 5663 if (VF == 1) { 5664 if (ForceTargetNumScalarRegs.getNumOccurrences() > 0) 5665 TargetNumRegisters = ForceTargetNumScalarRegs; 5666 } else { 5667 if (ForceTargetNumVectorRegs.getNumOccurrences() > 0) 5668 TargetNumRegisters = ForceTargetNumVectorRegs; 5669 } 5670 5671 RegisterUsage R = calculateRegisterUsage({VF})[0]; 5672 // We divide by these constants so assume that we have at least one 5673 // instruction that uses at least one register. 5674 R.MaxLocalUsers = std::max(R.MaxLocalUsers, 1U); 5675 R.NumInstructions = std::max(R.NumInstructions, 1U); 5676 5677 // We calculate the interleave count using the following formula. 5678 // Subtract the number of loop invariants from the number of available 5679 // registers. These registers are used by all of the interleaved instances. 5680 // Next, divide the remaining registers by the number of registers that is 5681 // required by the loop, in order to estimate how many parallel instances 5682 // fit without causing spills. All of this is rounded down if necessary to be 5683 // a power of two. We want power of two interleave count to simplify any 5684 // addressing operations or alignment considerations. 5685 unsigned IC = PowerOf2Floor((TargetNumRegisters - R.LoopInvariantRegs) / 5686 R.MaxLocalUsers); 5687 5688 // Don't count the induction variable as interleaved. 5689 if (EnableIndVarRegisterHeur) 5690 IC = PowerOf2Floor((TargetNumRegisters - R.LoopInvariantRegs - 1) / 5691 std::max(1U, (R.MaxLocalUsers - 1))); 5692 5693 // Clamp the interleave ranges to reasonable counts. 5694 unsigned MaxInterleaveCount = TTI.getMaxInterleaveFactor(VF); 5695 5696 // Check if the user has overridden the max. 5697 if (VF == 1) { 5698 if (ForceTargetMaxScalarInterleaveFactor.getNumOccurrences() > 0) 5699 MaxInterleaveCount = ForceTargetMaxScalarInterleaveFactor; 5700 } else { 5701 if (ForceTargetMaxVectorInterleaveFactor.getNumOccurrences() > 0) 5702 MaxInterleaveCount = ForceTargetMaxVectorInterleaveFactor; 5703 } 5704 5705 // If we did not calculate the cost for VF (because the user selected the VF) 5706 // then we calculate the cost of VF here. 5707 if (LoopCost == 0) 5708 LoopCost = expectedCost(VF).first; 5709 5710 // Clamp the calculated IC to be between the 1 and the max interleave count 5711 // that the target allows. 5712 if (IC > MaxInterleaveCount) 5713 IC = MaxInterleaveCount; 5714 else if (IC < 1) 5715 IC = 1; 5716 5717 // Interleave if we vectorized this loop and there is a reduction that could 5718 // benefit from interleaving. 5719 if (VF > 1 && Legal->getReductionVars()->size()) { 5720 DEBUG(dbgs() << "LV: Interleaving because of reductions.\n"); 5721 return IC; 5722 } 5723 5724 // Note that if we've already vectorized the loop we will have done the 5725 // runtime check and so interleaving won't require further checks. 5726 bool InterleavingRequiresRuntimePointerCheck = 5727 (VF == 1 && Legal->getRuntimePointerChecking()->Need); 5728 5729 // We want to interleave small loops in order to reduce the loop overhead and 5730 // potentially expose ILP opportunities. 5731 DEBUG(dbgs() << "LV: Loop cost is " << LoopCost << '\n'); 5732 if (!InterleavingRequiresRuntimePointerCheck && LoopCost < SmallLoopCost) { 5733 // We assume that the cost overhead is 1 and we use the cost model 5734 // to estimate the cost of the loop and interleave until the cost of the 5735 // loop overhead is about 5% of the cost of the loop. 5736 unsigned SmallIC = 5737 std::min(IC, (unsigned)PowerOf2Floor(SmallLoopCost / LoopCost)); 5738 5739 // Interleave until store/load ports (estimated by max interleave count) are 5740 // saturated. 5741 unsigned NumStores = Legal->getNumStores(); 5742 unsigned NumLoads = Legal->getNumLoads(); 5743 unsigned StoresIC = IC / (NumStores ? NumStores : 1); 5744 unsigned LoadsIC = IC / (NumLoads ? NumLoads : 1); 5745 5746 // If we have a scalar reduction (vector reductions are already dealt with 5747 // by this point), we can increase the critical path length if the loop 5748 // we're interleaving is inside another loop. Limit, by default to 2, so the 5749 // critical path only gets increased by one reduction operation. 5750 if (Legal->getReductionVars()->size() && TheLoop->getLoopDepth() > 1) { 5751 unsigned F = static_cast<unsigned>(MaxNestedScalarReductionIC); 5752 SmallIC = std::min(SmallIC, F); 5753 StoresIC = std::min(StoresIC, F); 5754 LoadsIC = std::min(LoadsIC, F); 5755 } 5756 5757 if (EnableLoadStoreRuntimeInterleave && 5758 std::max(StoresIC, LoadsIC) > SmallIC) { 5759 DEBUG(dbgs() << "LV: Interleaving to saturate store or load ports.\n"); 5760 return std::max(StoresIC, LoadsIC); 5761 } 5762 5763 DEBUG(dbgs() << "LV: Interleaving to reduce branch cost.\n"); 5764 return SmallIC; 5765 } 5766 5767 // Interleave if this is a large loop (small loops are already dealt with by 5768 // this point) that could benefit from interleaving. 5769 bool HasReductions = (Legal->getReductionVars()->size() > 0); 5770 if (TTI.enableAggressiveInterleaving(HasReductions)) { 5771 DEBUG(dbgs() << "LV: Interleaving to expose ILP.\n"); 5772 return IC; 5773 } 5774 5775 DEBUG(dbgs() << "LV: Not Interleaving.\n"); 5776 return 1; 5777 } 5778 5779 SmallVector<LoopVectorizationCostModel::RegisterUsage, 8> 5780 LoopVectorizationCostModel::calculateRegisterUsage(ArrayRef<unsigned> VFs) { 5781 // This function calculates the register usage by measuring the highest number 5782 // of values that are alive at a single location. Obviously, this is a very 5783 // rough estimation. We scan the loop in a topological order in order and 5784 // assign a number to each instruction. We use RPO to ensure that defs are 5785 // met before their users. We assume that each instruction that has in-loop 5786 // users starts an interval. We record every time that an in-loop value is 5787 // used, so we have a list of the first and last occurrences of each 5788 // instruction. Next, we transpose this data structure into a multi map that 5789 // holds the list of intervals that *end* at a specific location. This multi 5790 // map allows us to perform a linear search. We scan the instructions linearly 5791 // and record each time that a new interval starts, by placing it in a set. 5792 // If we find this value in the multi-map then we remove it from the set. 5793 // The max register usage is the maximum size of the set. 5794 // We also search for instructions that are defined outside the loop, but are 5795 // used inside the loop. We need this number separately from the max-interval 5796 // usage number because when we unroll, loop-invariant values do not take 5797 // more register. 5798 LoopBlocksDFS DFS(TheLoop); 5799 DFS.perform(LI); 5800 5801 RegisterUsage RU; 5802 RU.NumInstructions = 0; 5803 5804 // Each 'key' in the map opens a new interval. The values 5805 // of the map are the index of the 'last seen' usage of the 5806 // instruction that is the key. 5807 typedef DenseMap<Instruction *, unsigned> IntervalMap; 5808 // Maps instruction to its index. 5809 DenseMap<unsigned, Instruction *> IdxToInstr; 5810 // Marks the end of each interval. 5811 IntervalMap EndPoint; 5812 // Saves the list of instruction indices that are used in the loop. 5813 SmallSet<Instruction *, 8> Ends; 5814 // Saves the list of values that are used in the loop but are 5815 // defined outside the loop, such as arguments and constants. 5816 SmallPtrSet<Value *, 8> LoopInvariants; 5817 5818 unsigned Index = 0; 5819 for (BasicBlock *BB : make_range(DFS.beginRPO(), DFS.endRPO())) { 5820 RU.NumInstructions += BB->size(); 5821 for (Instruction &I : *BB) { 5822 IdxToInstr[Index++] = &I; 5823 5824 // Save the end location of each USE. 5825 for (Value *U : I.operands()) { 5826 auto *Instr = dyn_cast<Instruction>(U); 5827 5828 // Ignore non-instruction values such as arguments, constants, etc. 5829 if (!Instr) 5830 continue; 5831 5832 // If this instruction is outside the loop then record it and continue. 5833 if (!TheLoop->contains(Instr)) { 5834 LoopInvariants.insert(Instr); 5835 continue; 5836 } 5837 5838 // Overwrite previous end points. 5839 EndPoint[Instr] = Index; 5840 Ends.insert(Instr); 5841 } 5842 } 5843 } 5844 5845 // Saves the list of intervals that end with the index in 'key'. 5846 typedef SmallVector<Instruction *, 2> InstrList; 5847 DenseMap<unsigned, InstrList> TransposeEnds; 5848 5849 // Transpose the EndPoints to a list of values that end at each index. 5850 for (auto &Interval : EndPoint) 5851 TransposeEnds[Interval.second].push_back(Interval.first); 5852 5853 SmallSet<Instruction *, 8> OpenIntervals; 5854 5855 // Get the size of the widest register. 5856 unsigned MaxSafeDepDist = -1U; 5857 if (Legal->getMaxSafeDepDistBytes() != -1U) 5858 MaxSafeDepDist = Legal->getMaxSafeDepDistBytes() * 8; 5859 unsigned WidestRegister = 5860 std::min(TTI.getRegisterBitWidth(true), MaxSafeDepDist); 5861 const DataLayout &DL = TheFunction->getParent()->getDataLayout(); 5862 5863 SmallVector<RegisterUsage, 8> RUs(VFs.size()); 5864 SmallVector<unsigned, 8> MaxUsages(VFs.size(), 0); 5865 5866 DEBUG(dbgs() << "LV(REG): Calculating max register usage:\n"); 5867 5868 // A lambda that gets the register usage for the given type and VF. 5869 auto GetRegUsage = [&DL, WidestRegister](Type *Ty, unsigned VF) { 5870 if (Ty->isTokenTy()) 5871 return 0U; 5872 unsigned TypeSize = DL.getTypeSizeInBits(Ty->getScalarType()); 5873 return std::max<unsigned>(1, VF * TypeSize / WidestRegister); 5874 }; 5875 5876 for (unsigned int i = 0; i < Index; ++i) { 5877 Instruction *I = IdxToInstr[i]; 5878 // Ignore instructions that are never used within the loop. 5879 if (!Ends.count(I)) 5880 continue; 5881 5882 // Remove all of the instructions that end at this location. 5883 InstrList &List = TransposeEnds[i]; 5884 for (Instruction *ToRemove : List) 5885 OpenIntervals.erase(ToRemove); 5886 5887 // Skip ignored values. 5888 if (ValuesToIgnore.count(I)) 5889 continue; 5890 5891 // For each VF find the maximum usage of registers. 5892 for (unsigned j = 0, e = VFs.size(); j < e; ++j) { 5893 if (VFs[j] == 1) { 5894 MaxUsages[j] = std::max(MaxUsages[j], OpenIntervals.size()); 5895 continue; 5896 } 5897 5898 // Count the number of live intervals. 5899 unsigned RegUsage = 0; 5900 for (auto Inst : OpenIntervals) { 5901 // Skip ignored values for VF > 1. 5902 if (VecValuesToIgnore.count(Inst)) 5903 continue; 5904 RegUsage += GetRegUsage(Inst->getType(), VFs[j]); 5905 } 5906 MaxUsages[j] = std::max(MaxUsages[j], RegUsage); 5907 } 5908 5909 DEBUG(dbgs() << "LV(REG): At #" << i << " Interval # " 5910 << OpenIntervals.size() << '\n'); 5911 5912 // Add the current instruction to the list of open intervals. 5913 OpenIntervals.insert(I); 5914 } 5915 5916 for (unsigned i = 0, e = VFs.size(); i < e; ++i) { 5917 unsigned Invariant = 0; 5918 if (VFs[i] == 1) 5919 Invariant = LoopInvariants.size(); 5920 else { 5921 for (auto Inst : LoopInvariants) 5922 Invariant += GetRegUsage(Inst->getType(), VFs[i]); 5923 } 5924 5925 DEBUG(dbgs() << "LV(REG): VF = " << VFs[i] << '\n'); 5926 DEBUG(dbgs() << "LV(REG): Found max usage: " << MaxUsages[i] << '\n'); 5927 DEBUG(dbgs() << "LV(REG): Found invariant usage: " << Invariant << '\n'); 5928 DEBUG(dbgs() << "LV(REG): LoopSize: " << RU.NumInstructions << '\n'); 5929 5930 RU.LoopInvariantRegs = Invariant; 5931 RU.MaxLocalUsers = MaxUsages[i]; 5932 RUs[i] = RU; 5933 } 5934 5935 return RUs; 5936 } 5937 5938 LoopVectorizationCostModel::VectorizationCostTy 5939 LoopVectorizationCostModel::expectedCost(unsigned VF) { 5940 VectorizationCostTy Cost; 5941 5942 // For each block. 5943 for (BasicBlock *BB : TheLoop->blocks()) { 5944 VectorizationCostTy BlockCost; 5945 5946 // For each instruction in the old loop. 5947 for (Instruction &I : *BB) { 5948 // Skip dbg intrinsics. 5949 if (isa<DbgInfoIntrinsic>(I)) 5950 continue; 5951 5952 // Skip ignored values. 5953 if (ValuesToIgnore.count(&I)) 5954 continue; 5955 5956 VectorizationCostTy C = getInstructionCost(&I, VF); 5957 5958 // Check if we should override the cost. 5959 if (ForceTargetInstructionCost.getNumOccurrences() > 0) 5960 C.first = ForceTargetInstructionCost; 5961 5962 BlockCost.first += C.first; 5963 BlockCost.second |= C.second; 5964 DEBUG(dbgs() << "LV: Found an estimated cost of " << C.first << " for VF " 5965 << VF << " For instruction: " << I << '\n'); 5966 } 5967 5968 // We assume that if-converted blocks have a 50% chance of being executed. 5969 // When the code is scalar then some of the blocks are avoided due to CF. 5970 // When the code is vectorized we execute all code paths. 5971 if (VF == 1 && Legal->blockNeedsPredication(BB)) 5972 BlockCost.first /= 2; 5973 5974 Cost.first += BlockCost.first; 5975 Cost.second |= BlockCost.second; 5976 } 5977 5978 return Cost; 5979 } 5980 5981 /// \brief Check whether the address computation for a non-consecutive memory 5982 /// access looks like an unlikely candidate for being merged into the indexing 5983 /// mode. 5984 /// 5985 /// We look for a GEP which has one index that is an induction variable and all 5986 /// other indices are loop invariant. If the stride of this access is also 5987 /// within a small bound we decide that this address computation can likely be 5988 /// merged into the addressing mode. 5989 /// In all other cases, we identify the address computation as complex. 5990 static bool isLikelyComplexAddressComputation(Value *Ptr, 5991 LoopVectorizationLegality *Legal, 5992 ScalarEvolution *SE, 5993 const Loop *TheLoop) { 5994 auto *Gep = dyn_cast<GetElementPtrInst>(Ptr); 5995 if (!Gep) 5996 return true; 5997 5998 // We are looking for a gep with all loop invariant indices except for one 5999 // which should be an induction variable. 6000 unsigned NumOperands = Gep->getNumOperands(); 6001 for (unsigned i = 1; i < NumOperands; ++i) { 6002 Value *Opd = Gep->getOperand(i); 6003 if (!SE->isLoopInvariant(SE->getSCEV(Opd), TheLoop) && 6004 !Legal->isInductionVariable(Opd)) 6005 return true; 6006 } 6007 6008 // Now we know we have a GEP ptr, %inv, %ind, %inv. Make sure that the step 6009 // can likely be merged into the address computation. 6010 unsigned MaxMergeDistance = 64; 6011 6012 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Ptr)); 6013 if (!AddRec) 6014 return true; 6015 6016 // Check the step is constant. 6017 const SCEV *Step = AddRec->getStepRecurrence(*SE); 6018 // Calculate the pointer stride and check if it is consecutive. 6019 const auto *C = dyn_cast<SCEVConstant>(Step); 6020 if (!C) 6021 return true; 6022 6023 const APInt &APStepVal = C->getAPInt(); 6024 6025 // Huge step value - give up. 6026 if (APStepVal.getBitWidth() > 64) 6027 return true; 6028 6029 int64_t StepVal = APStepVal.getSExtValue(); 6030 6031 return StepVal > MaxMergeDistance; 6032 } 6033 6034 static bool isStrideMul(Instruction *I, LoopVectorizationLegality *Legal) { 6035 return Legal->hasStride(I->getOperand(0)) || 6036 Legal->hasStride(I->getOperand(1)); 6037 } 6038 6039 LoopVectorizationCostModel::VectorizationCostTy 6040 LoopVectorizationCostModel::getInstructionCost(Instruction *I, unsigned VF) { 6041 // If we know that this instruction will remain uniform, check the cost of 6042 // the scalar version. 6043 if (Legal->isUniformAfterVectorization(I)) 6044 VF = 1; 6045 6046 Type *VectorTy; 6047 unsigned C = getInstructionCost(I, VF, VectorTy); 6048 6049 bool TypeNotScalarized = 6050 VF > 1 && !VectorTy->isVoidTy() && TTI.getNumberOfParts(VectorTy) < VF; 6051 return VectorizationCostTy(C, TypeNotScalarized); 6052 } 6053 6054 unsigned LoopVectorizationCostModel::getInstructionCost(Instruction *I, 6055 unsigned VF, 6056 Type *&VectorTy) { 6057 Type *RetTy = I->getType(); 6058 if (VF > 1 && MinBWs.count(I)) 6059 RetTy = IntegerType::get(RetTy->getContext(), MinBWs[I]); 6060 VectorTy = ToVectorTy(RetTy, VF); 6061 auto SE = PSE.getSE(); 6062 6063 // TODO: We need to estimate the cost of intrinsic calls. 6064 switch (I->getOpcode()) { 6065 case Instruction::GetElementPtr: 6066 // We mark this instruction as zero-cost because the cost of GEPs in 6067 // vectorized code depends on whether the corresponding memory instruction 6068 // is scalarized or not. Therefore, we handle GEPs with the memory 6069 // instruction cost. 6070 return 0; 6071 case Instruction::Br: { 6072 return TTI.getCFInstrCost(I->getOpcode()); 6073 } 6074 case Instruction::PHI: { 6075 auto *Phi = cast<PHINode>(I); 6076 6077 // First-order recurrences are replaced by vector shuffles inside the loop. 6078 if (VF > 1 && Legal->isFirstOrderRecurrence(Phi)) 6079 return TTI.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector, 6080 VectorTy, VF - 1, VectorTy); 6081 6082 // TODO: IF-converted IFs become selects. 6083 return 0; 6084 } 6085 case Instruction::Add: 6086 case Instruction::FAdd: 6087 case Instruction::Sub: 6088 case Instruction::FSub: 6089 case Instruction::Mul: 6090 case Instruction::FMul: 6091 case Instruction::UDiv: 6092 case Instruction::SDiv: 6093 case Instruction::FDiv: 6094 case Instruction::URem: 6095 case Instruction::SRem: 6096 case Instruction::FRem: 6097 case Instruction::Shl: 6098 case Instruction::LShr: 6099 case Instruction::AShr: 6100 case Instruction::And: 6101 case Instruction::Or: 6102 case Instruction::Xor: { 6103 // Since we will replace the stride by 1 the multiplication should go away. 6104 if (I->getOpcode() == Instruction::Mul && isStrideMul(I, Legal)) 6105 return 0; 6106 // Certain instructions can be cheaper to vectorize if they have a constant 6107 // second vector operand. One example of this are shifts on x86. 6108 TargetTransformInfo::OperandValueKind Op1VK = 6109 TargetTransformInfo::OK_AnyValue; 6110 TargetTransformInfo::OperandValueKind Op2VK = 6111 TargetTransformInfo::OK_AnyValue; 6112 TargetTransformInfo::OperandValueProperties Op1VP = 6113 TargetTransformInfo::OP_None; 6114 TargetTransformInfo::OperandValueProperties Op2VP = 6115 TargetTransformInfo::OP_None; 6116 Value *Op2 = I->getOperand(1); 6117 6118 // Check for a splat or for a non uniform vector of constants. 6119 if (isa<ConstantInt>(Op2)) { 6120 ConstantInt *CInt = cast<ConstantInt>(Op2); 6121 if (CInt && CInt->getValue().isPowerOf2()) 6122 Op2VP = TargetTransformInfo::OP_PowerOf2; 6123 Op2VK = TargetTransformInfo::OK_UniformConstantValue; 6124 } else if (isa<ConstantVector>(Op2) || isa<ConstantDataVector>(Op2)) { 6125 Op2VK = TargetTransformInfo::OK_NonUniformConstantValue; 6126 Constant *SplatValue = cast<Constant>(Op2)->getSplatValue(); 6127 if (SplatValue) { 6128 ConstantInt *CInt = dyn_cast<ConstantInt>(SplatValue); 6129 if (CInt && CInt->getValue().isPowerOf2()) 6130 Op2VP = TargetTransformInfo::OP_PowerOf2; 6131 Op2VK = TargetTransformInfo::OK_UniformConstantValue; 6132 } 6133 } else if (Legal->isUniform(Op2)) { 6134 Op2VK = TargetTransformInfo::OK_UniformValue; 6135 } 6136 6137 return TTI.getArithmeticInstrCost(I->getOpcode(), VectorTy, Op1VK, Op2VK, 6138 Op1VP, Op2VP); 6139 } 6140 case Instruction::Select: { 6141 SelectInst *SI = cast<SelectInst>(I); 6142 const SCEV *CondSCEV = SE->getSCEV(SI->getCondition()); 6143 bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop)); 6144 Type *CondTy = SI->getCondition()->getType(); 6145 if (!ScalarCond) 6146 CondTy = VectorType::get(CondTy, VF); 6147 6148 return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, CondTy); 6149 } 6150 case Instruction::ICmp: 6151 case Instruction::FCmp: { 6152 Type *ValTy = I->getOperand(0)->getType(); 6153 Instruction *Op0AsInstruction = dyn_cast<Instruction>(I->getOperand(0)); 6154 auto It = MinBWs.find(Op0AsInstruction); 6155 if (VF > 1 && It != MinBWs.end()) 6156 ValTy = IntegerType::get(ValTy->getContext(), It->second); 6157 VectorTy = ToVectorTy(ValTy, VF); 6158 return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy); 6159 } 6160 case Instruction::Store: 6161 case Instruction::Load: { 6162 StoreInst *SI = dyn_cast<StoreInst>(I); 6163 LoadInst *LI = dyn_cast<LoadInst>(I); 6164 Type *ValTy = (SI ? SI->getValueOperand()->getType() : LI->getType()); 6165 VectorTy = ToVectorTy(ValTy, VF); 6166 6167 unsigned Alignment = SI ? SI->getAlignment() : LI->getAlignment(); 6168 unsigned AS = 6169 SI ? SI->getPointerAddressSpace() : LI->getPointerAddressSpace(); 6170 Value *Ptr = getPointerOperand(I); 6171 // We add the cost of address computation here instead of with the gep 6172 // instruction because only here we know whether the operation is 6173 // scalarized. 6174 if (VF == 1) 6175 return TTI.getAddressComputationCost(VectorTy) + 6176 TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS); 6177 6178 if (LI && Legal->isUniform(Ptr)) { 6179 // Scalar load + broadcast 6180 unsigned Cost = TTI.getAddressComputationCost(ValTy->getScalarType()); 6181 Cost += TTI.getMemoryOpCost(I->getOpcode(), ValTy->getScalarType(), 6182 Alignment, AS); 6183 return Cost + 6184 TTI.getShuffleCost(TargetTransformInfo::SK_Broadcast, ValTy); 6185 } 6186 6187 // For an interleaved access, calculate the total cost of the whole 6188 // interleave group. 6189 if (Legal->isAccessInterleaved(I)) { 6190 auto Group = Legal->getInterleavedAccessGroup(I); 6191 assert(Group && "Fail to get an interleaved access group."); 6192 6193 // Only calculate the cost once at the insert position. 6194 if (Group->getInsertPos() != I) 6195 return 0; 6196 6197 unsigned InterleaveFactor = Group->getFactor(); 6198 Type *WideVecTy = 6199 VectorType::get(VectorTy->getVectorElementType(), 6200 VectorTy->getVectorNumElements() * InterleaveFactor); 6201 6202 // Holds the indices of existing members in an interleaved load group. 6203 // An interleaved store group doesn't need this as it doesn't allow gaps. 6204 SmallVector<unsigned, 4> Indices; 6205 if (LI) { 6206 for (unsigned i = 0; i < InterleaveFactor; i++) 6207 if (Group->getMember(i)) 6208 Indices.push_back(i); 6209 } 6210 6211 // Calculate the cost of the whole interleaved group. 6212 unsigned Cost = TTI.getInterleavedMemoryOpCost( 6213 I->getOpcode(), WideVecTy, Group->getFactor(), Indices, 6214 Group->getAlignment(), AS); 6215 6216 if (Group->isReverse()) 6217 Cost += 6218 Group->getNumMembers() * 6219 TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, VectorTy, 0); 6220 6221 // FIXME: The interleaved load group with a huge gap could be even more 6222 // expensive than scalar operations. Then we could ignore such group and 6223 // use scalar operations instead. 6224 return Cost; 6225 } 6226 6227 // Scalarized loads/stores. 6228 int ConsecutiveStride = Legal->isConsecutivePtr(Ptr); 6229 bool UseGatherOrScatter = 6230 (ConsecutiveStride == 0) && Legal->isLegalGatherOrScatter(I); 6231 6232 bool Reverse = ConsecutiveStride < 0; 6233 const DataLayout &DL = I->getModule()->getDataLayout(); 6234 uint64_t ScalarAllocatedSize = DL.getTypeAllocSize(ValTy); 6235 uint64_t VectorElementSize = DL.getTypeStoreSize(VectorTy) / VF; 6236 if ((!ConsecutiveStride && !UseGatherOrScatter) || 6237 ScalarAllocatedSize != VectorElementSize) { 6238 bool IsComplexComputation = 6239 isLikelyComplexAddressComputation(Ptr, Legal, SE, TheLoop); 6240 unsigned Cost = 0; 6241 // The cost of extracting from the value vector and pointer vector. 6242 Type *PtrTy = ToVectorTy(Ptr->getType(), VF); 6243 for (unsigned i = 0; i < VF; ++i) { 6244 // The cost of extracting the pointer operand. 6245 Cost += TTI.getVectorInstrCost(Instruction::ExtractElement, PtrTy, i); 6246 // In case of STORE, the cost of ExtractElement from the vector. 6247 // In case of LOAD, the cost of InsertElement into the returned 6248 // vector. 6249 Cost += TTI.getVectorInstrCost(SI ? Instruction::ExtractElement 6250 : Instruction::InsertElement, 6251 VectorTy, i); 6252 } 6253 6254 // The cost of the scalar loads/stores. 6255 Cost += VF * TTI.getAddressComputationCost(PtrTy, IsComplexComputation); 6256 Cost += VF * 6257 TTI.getMemoryOpCost(I->getOpcode(), ValTy->getScalarType(), 6258 Alignment, AS); 6259 return Cost; 6260 } 6261 6262 unsigned Cost = TTI.getAddressComputationCost(VectorTy); 6263 if (UseGatherOrScatter) { 6264 assert(ConsecutiveStride == 0 && 6265 "Gather/Scatter are not used for consecutive stride"); 6266 return Cost + 6267 TTI.getGatherScatterOpCost(I->getOpcode(), VectorTy, Ptr, 6268 Legal->isMaskRequired(I), Alignment); 6269 } 6270 // Wide load/stores. 6271 if (Legal->isMaskRequired(I)) 6272 Cost += 6273 TTI.getMaskedMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS); 6274 else 6275 Cost += TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS); 6276 6277 if (Reverse) 6278 Cost += TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, VectorTy, 0); 6279 return Cost; 6280 } 6281 case Instruction::ZExt: 6282 case Instruction::SExt: 6283 case Instruction::FPToUI: 6284 case Instruction::FPToSI: 6285 case Instruction::FPExt: 6286 case Instruction::PtrToInt: 6287 case Instruction::IntToPtr: 6288 case Instruction::SIToFP: 6289 case Instruction::UIToFP: 6290 case Instruction::Trunc: 6291 case Instruction::FPTrunc: 6292 case Instruction::BitCast: { 6293 // We optimize the truncation of induction variable. 6294 // The cost of these is the same as the scalar operation. 6295 if (I->getOpcode() == Instruction::Trunc && 6296 Legal->isInductionVariable(I->getOperand(0))) 6297 return TTI.getCastInstrCost(I->getOpcode(), I->getType(), 6298 I->getOperand(0)->getType()); 6299 6300 Type *SrcScalarTy = I->getOperand(0)->getType(); 6301 Type *SrcVecTy = ToVectorTy(SrcScalarTy, VF); 6302 if (VF > 1 && MinBWs.count(I)) { 6303 // This cast is going to be shrunk. This may remove the cast or it might 6304 // turn it into slightly different cast. For example, if MinBW == 16, 6305 // "zext i8 %1 to i32" becomes "zext i8 %1 to i16". 6306 // 6307 // Calculate the modified src and dest types. 6308 Type *MinVecTy = VectorTy; 6309 if (I->getOpcode() == Instruction::Trunc) { 6310 SrcVecTy = smallestIntegerVectorType(SrcVecTy, MinVecTy); 6311 VectorTy = 6312 largestIntegerVectorType(ToVectorTy(I->getType(), VF), MinVecTy); 6313 } else if (I->getOpcode() == Instruction::ZExt || 6314 I->getOpcode() == Instruction::SExt) { 6315 SrcVecTy = largestIntegerVectorType(SrcVecTy, MinVecTy); 6316 VectorTy = 6317 smallestIntegerVectorType(ToVectorTy(I->getType(), VF), MinVecTy); 6318 } 6319 } 6320 6321 return TTI.getCastInstrCost(I->getOpcode(), VectorTy, SrcVecTy); 6322 } 6323 case Instruction::Call: { 6324 bool NeedToScalarize; 6325 CallInst *CI = cast<CallInst>(I); 6326 unsigned CallCost = getVectorCallCost(CI, VF, TTI, TLI, NeedToScalarize); 6327 if (getVectorIntrinsicIDForCall(CI, TLI)) 6328 return std::min(CallCost, getVectorIntrinsicCost(CI, VF, TTI, TLI)); 6329 return CallCost; 6330 } 6331 default: { 6332 // We are scalarizing the instruction. Return the cost of the scalar 6333 // instruction, plus the cost of insert and extract into vector 6334 // elements, times the vector width. 6335 unsigned Cost = 0; 6336 6337 if (!RetTy->isVoidTy() && VF != 1) { 6338 unsigned InsCost = 6339 TTI.getVectorInstrCost(Instruction::InsertElement, VectorTy); 6340 unsigned ExtCost = 6341 TTI.getVectorInstrCost(Instruction::ExtractElement, VectorTy); 6342 6343 // The cost of inserting the results plus extracting each one of the 6344 // operands. 6345 Cost += VF * (InsCost + ExtCost * I->getNumOperands()); 6346 } 6347 6348 // The cost of executing VF copies of the scalar instruction. This opcode 6349 // is unknown. Assume that it is the same as 'mul'. 6350 Cost += VF * TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy); 6351 return Cost; 6352 } 6353 } // end of switch. 6354 } 6355 6356 char LoopVectorize::ID = 0; 6357 static const char lv_name[] = "Loop Vectorization"; 6358 INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false) 6359 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass) 6360 INITIALIZE_PASS_DEPENDENCY(BasicAAWrapperPass) 6361 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass) 6362 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass) 6363 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 6364 INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass) 6365 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 6366 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass) 6367 INITIALIZE_PASS_DEPENDENCY(LCSSAWrapperPass) 6368 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 6369 INITIALIZE_PASS_DEPENDENCY(LoopSimplify) 6370 INITIALIZE_PASS_DEPENDENCY(LoopAccessLegacyAnalysis) 6371 INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass) 6372 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass) 6373 INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false) 6374 6375 namespace llvm { 6376 Pass *createLoopVectorizePass(bool NoUnrolling, bool AlwaysVectorize) { 6377 return new LoopVectorize(NoUnrolling, AlwaysVectorize); 6378 } 6379 } 6380 6381 bool LoopVectorizationCostModel::isConsecutiveLoadOrStore(Instruction *Inst) { 6382 6383 // Check if the pointer operand of a load or store instruction is 6384 // consecutive. 6385 if (auto *Ptr = getPointerOperand(Inst)) 6386 return Legal->isConsecutivePtr(Ptr); 6387 return false; 6388 } 6389 6390 void LoopVectorizationCostModel::collectValuesToIgnore() { 6391 // Ignore ephemeral values. 6392 CodeMetrics::collectEphemeralValues(TheLoop, AC, ValuesToIgnore); 6393 6394 // Ignore type-promoting instructions we identified during reduction 6395 // detection. 6396 for (auto &Reduction : *Legal->getReductionVars()) { 6397 RecurrenceDescriptor &RedDes = Reduction.second; 6398 SmallPtrSetImpl<Instruction *> &Casts = RedDes.getCastInsts(); 6399 VecValuesToIgnore.insert(Casts.begin(), Casts.end()); 6400 } 6401 6402 // Insert values known to be scalar into VecValuesToIgnore. 6403 for (auto *BB : TheLoop->getBlocks()) 6404 for (auto &I : *BB) 6405 if (Legal->isScalarAfterVectorization(&I)) 6406 VecValuesToIgnore.insert(&I); 6407 } 6408 6409 void InnerLoopUnroller::scalarizeInstruction(Instruction *Instr, 6410 bool IfPredicateStore) { 6411 assert(!Instr->getType()->isAggregateType() && "Can't handle vectors"); 6412 // Holds vector parameters or scalars, in case of uniform vals. 6413 SmallVector<VectorParts, 4> Params; 6414 6415 setDebugLocFromInst(Builder, Instr); 6416 6417 // Find all of the vectorized parameters. 6418 for (Value *SrcOp : Instr->operands()) { 6419 // If we are accessing the old induction variable, use the new one. 6420 if (SrcOp == OldInduction) { 6421 Params.push_back(getVectorValue(SrcOp)); 6422 continue; 6423 } 6424 6425 // Try using previously calculated values. 6426 Instruction *SrcInst = dyn_cast<Instruction>(SrcOp); 6427 6428 // If the src is an instruction that appeared earlier in the basic block 6429 // then it should already be vectorized. 6430 if (SrcInst && OrigLoop->contains(SrcInst)) { 6431 assert(WidenMap.has(SrcInst) && "Source operand is unavailable"); 6432 // The parameter is a vector value from earlier. 6433 Params.push_back(WidenMap.get(SrcInst)); 6434 } else { 6435 // The parameter is a scalar from outside the loop. Maybe even a constant. 6436 VectorParts Scalars; 6437 Scalars.append(UF, SrcOp); 6438 Params.push_back(Scalars); 6439 } 6440 } 6441 6442 assert(Params.size() == Instr->getNumOperands() && 6443 "Invalid number of operands"); 6444 6445 // Does this instruction return a value ? 6446 bool IsVoidRetTy = Instr->getType()->isVoidTy(); 6447 6448 Value *UndefVec = IsVoidRetTy ? nullptr : UndefValue::get(Instr->getType()); 6449 // Create a new entry in the WidenMap and initialize it to Undef or Null. 6450 VectorParts &VecResults = WidenMap.splat(Instr, UndefVec); 6451 6452 VectorParts Cond; 6453 if (IfPredicateStore) { 6454 assert(Instr->getParent()->getSinglePredecessor() && 6455 "Only support single predecessor blocks"); 6456 Cond = createEdgeMask(Instr->getParent()->getSinglePredecessor(), 6457 Instr->getParent()); 6458 } 6459 6460 // For each vector unroll 'part': 6461 for (unsigned Part = 0; Part < UF; ++Part) { 6462 // For each scalar that we create: 6463 6464 // Start an "if (pred) a[i] = ..." block. 6465 Value *Cmp = nullptr; 6466 if (IfPredicateStore) { 6467 if (Cond[Part]->getType()->isVectorTy()) 6468 Cond[Part] = 6469 Builder.CreateExtractElement(Cond[Part], Builder.getInt32(0)); 6470 Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Cond[Part], 6471 ConstantInt::get(Cond[Part]->getType(), 1)); 6472 } 6473 6474 Instruction *Cloned = Instr->clone(); 6475 if (!IsVoidRetTy) 6476 Cloned->setName(Instr->getName() + ".cloned"); 6477 // Replace the operands of the cloned instructions with extracted scalars. 6478 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) { 6479 Value *Op = Params[op][Part]; 6480 Cloned->setOperand(op, Op); 6481 } 6482 6483 // Place the cloned scalar in the new loop. 6484 Builder.Insert(Cloned); 6485 6486 // If we just cloned a new assumption, add it the assumption cache. 6487 if (auto *II = dyn_cast<IntrinsicInst>(Cloned)) 6488 if (II->getIntrinsicID() == Intrinsic::assume) 6489 AC->registerAssumption(II); 6490 6491 // If the original scalar returns a value we need to place it in a vector 6492 // so that future users will be able to use it. 6493 if (!IsVoidRetTy) 6494 VecResults[Part] = Cloned; 6495 6496 // End if-block. 6497 if (IfPredicateStore) 6498 PredicatedStores.push_back(std::make_pair(cast<StoreInst>(Cloned), Cmp)); 6499 } 6500 } 6501 6502 void InnerLoopUnroller::vectorizeMemoryInstruction(Instruction *Instr) { 6503 auto *SI = dyn_cast<StoreInst>(Instr); 6504 bool IfPredicateStore = (SI && Legal->blockNeedsPredication(SI->getParent())); 6505 6506 return scalarizeInstruction(Instr, IfPredicateStore); 6507 } 6508 6509 Value *InnerLoopUnroller::reverseVector(Value *Vec) { return Vec; } 6510 6511 Value *InnerLoopUnroller::getBroadcastInstrs(Value *V) { return V; } 6512 6513 Value *InnerLoopUnroller::getStepVector(Value *Val, int StartIdx, Value *Step, 6514 Instruction::BinaryOps BinOp) { 6515 // When unrolling and the VF is 1, we only need to add a simple scalar. 6516 Type *Ty = Val->getType(); 6517 assert(!Ty->isVectorTy() && "Val must be a scalar"); 6518 6519 if (Ty->isFloatingPointTy()) { 6520 Constant *C = ConstantFP::get(Ty, (double)StartIdx); 6521 6522 // Floating point operations had to be 'fast' to enable the unrolling. 6523 Value *MulOp = addFastMathFlag(Builder.CreateFMul(C, Step)); 6524 return addFastMathFlag(Builder.CreateBinOp(BinOp, Val, MulOp)); 6525 } 6526 Constant *C = ConstantInt::get(Ty, StartIdx); 6527 return Builder.CreateAdd(Val, Builder.CreateMul(C, Step), "induction"); 6528 } 6529 6530 static void AddRuntimeUnrollDisableMetaData(Loop *L) { 6531 SmallVector<Metadata *, 4> MDs; 6532 // Reserve first location for self reference to the LoopID metadata node. 6533 MDs.push_back(nullptr); 6534 bool IsUnrollMetadata = false; 6535 MDNode *LoopID = L->getLoopID(); 6536 if (LoopID) { 6537 // First find existing loop unrolling disable metadata. 6538 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) { 6539 auto *MD = dyn_cast<MDNode>(LoopID->getOperand(i)); 6540 if (MD) { 6541 const auto *S = dyn_cast<MDString>(MD->getOperand(0)); 6542 IsUnrollMetadata = 6543 S && S->getString().startswith("llvm.loop.unroll.disable"); 6544 } 6545 MDs.push_back(LoopID->getOperand(i)); 6546 } 6547 } 6548 6549 if (!IsUnrollMetadata) { 6550 // Add runtime unroll disable metadata. 6551 LLVMContext &Context = L->getHeader()->getContext(); 6552 SmallVector<Metadata *, 1> DisableOperands; 6553 DisableOperands.push_back( 6554 MDString::get(Context, "llvm.loop.unroll.runtime.disable")); 6555 MDNode *DisableNode = MDNode::get(Context, DisableOperands); 6556 MDs.push_back(DisableNode); 6557 MDNode *NewLoopID = MDNode::get(Context, MDs); 6558 // Set operand 0 to refer to the loop id itself. 6559 NewLoopID->replaceOperandWith(0, NewLoopID); 6560 L->setLoopID(NewLoopID); 6561 } 6562 } 6563 6564 bool LoopVectorizePass::processLoop(Loop *L) { 6565 assert(L->empty() && "Only process inner loops."); 6566 6567 #ifndef NDEBUG 6568 const std::string DebugLocStr = getDebugLocString(L); 6569 #endif /* NDEBUG */ 6570 6571 DEBUG(dbgs() << "\nLV: Checking a loop in \"" 6572 << L->getHeader()->getParent()->getName() << "\" from " 6573 << DebugLocStr << "\n"); 6574 6575 LoopVectorizeHints Hints(L, DisableUnrolling, *ORE); 6576 6577 DEBUG(dbgs() << "LV: Loop hints:" 6578 << " force=" 6579 << (Hints.getForce() == LoopVectorizeHints::FK_Disabled 6580 ? "disabled" 6581 : (Hints.getForce() == LoopVectorizeHints::FK_Enabled 6582 ? "enabled" 6583 : "?")) 6584 << " width=" << Hints.getWidth() 6585 << " unroll=" << Hints.getInterleave() << "\n"); 6586 6587 // Function containing loop 6588 Function *F = L->getHeader()->getParent(); 6589 6590 // Looking at the diagnostic output is the only way to determine if a loop 6591 // was vectorized (other than looking at the IR or machine code), so it 6592 // is important to generate an optimization remark for each loop. Most of 6593 // these messages are generated by emitOptimizationRemarkAnalysis. Remarks 6594 // generated by emitOptimizationRemark and emitOptimizationRemarkMissed are 6595 // less verbose reporting vectorized loops and unvectorized loops that may 6596 // benefit from vectorization, respectively. 6597 6598 if (!Hints.allowVectorization(F, L, AlwaysVectorize)) { 6599 DEBUG(dbgs() << "LV: Loop hints prevent vectorization.\n"); 6600 return false; 6601 } 6602 6603 // Check the loop for a trip count threshold: 6604 // do not vectorize loops with a tiny trip count. 6605 const unsigned TC = SE->getSmallConstantTripCount(L); 6606 if (TC > 0u && TC < TinyTripCountVectorThreshold) { 6607 DEBUG(dbgs() << "LV: Found a loop with a very small trip count. " 6608 << "This loop is not worth vectorizing."); 6609 if (Hints.getForce() == LoopVectorizeHints::FK_Enabled) 6610 DEBUG(dbgs() << " But vectorizing was explicitly forced.\n"); 6611 else { 6612 DEBUG(dbgs() << "\n"); 6613 emitAnalysisDiag(L, Hints, *ORE, VectorizationReport() 6614 << "vectorization is not beneficial " 6615 "and is not explicitly forced"); 6616 return false; 6617 } 6618 } 6619 6620 PredicatedScalarEvolution PSE(*SE, *L); 6621 6622 // Check if it is legal to vectorize the loop. 6623 LoopVectorizationRequirements Requirements(*ORE); 6624 LoopVectorizationLegality LVL(L, PSE, DT, TLI, AA, F, TTI, GetLAA, LI, ORE, 6625 &Requirements, &Hints); 6626 if (!LVL.canVectorize()) { 6627 DEBUG(dbgs() << "LV: Not vectorizing: Cannot prove legality.\n"); 6628 emitMissedWarning(F, L, Hints, ORE); 6629 return false; 6630 } 6631 6632 // Use the cost model. 6633 LoopVectorizationCostModel CM(L, PSE, LI, &LVL, *TTI, TLI, DB, AC, ORE, F, 6634 &Hints); 6635 CM.collectValuesToIgnore(); 6636 6637 // Check the function attributes to find out if this function should be 6638 // optimized for size. 6639 bool OptForSize = 6640 Hints.getForce() != LoopVectorizeHints::FK_Enabled && F->optForSize(); 6641 6642 // Compute the weighted frequency of this loop being executed and see if it 6643 // is less than 20% of the function entry baseline frequency. Note that we 6644 // always have a canonical loop here because we think we *can* vectorize. 6645 // FIXME: This is hidden behind a flag due to pervasive problems with 6646 // exactly what block frequency models. 6647 if (LoopVectorizeWithBlockFrequency) { 6648 BlockFrequency LoopEntryFreq = BFI->getBlockFreq(L->getLoopPreheader()); 6649 if (Hints.getForce() != LoopVectorizeHints::FK_Enabled && 6650 LoopEntryFreq < ColdEntryFreq) 6651 OptForSize = true; 6652 } 6653 6654 // Check the function attributes to see if implicit floats are allowed. 6655 // FIXME: This check doesn't seem possibly correct -- what if the loop is 6656 // an integer loop and the vector instructions selected are purely integer 6657 // vector instructions? 6658 if (F->hasFnAttribute(Attribute::NoImplicitFloat)) { 6659 DEBUG(dbgs() << "LV: Can't vectorize when the NoImplicitFloat" 6660 "attribute is used.\n"); 6661 emitAnalysisDiag( 6662 L, Hints, *ORE, 6663 VectorizationReport() 6664 << "loop not vectorized due to NoImplicitFloat attribute"); 6665 emitMissedWarning(F, L, Hints, ORE); 6666 return false; 6667 } 6668 6669 // Check if the target supports potentially unsafe FP vectorization. 6670 // FIXME: Add a check for the type of safety issue (denormal, signaling) 6671 // for the target we're vectorizing for, to make sure none of the 6672 // additional fp-math flags can help. 6673 if (Hints.isPotentiallyUnsafe() && 6674 TTI->isFPVectorizationPotentiallyUnsafe()) { 6675 DEBUG(dbgs() << "LV: Potentially unsafe FP op prevents vectorization.\n"); 6676 emitAnalysisDiag(L, Hints, *ORE, 6677 VectorizationReport() 6678 << "loop not vectorized due to unsafe FP support."); 6679 emitMissedWarning(F, L, Hints, ORE); 6680 return false; 6681 } 6682 6683 // Select the optimal vectorization factor. 6684 const LoopVectorizationCostModel::VectorizationFactor VF = 6685 CM.selectVectorizationFactor(OptForSize); 6686 6687 // Select the interleave count. 6688 unsigned IC = CM.selectInterleaveCount(OptForSize, VF.Width, VF.Cost); 6689 6690 // Get user interleave count. 6691 unsigned UserIC = Hints.getInterleave(); 6692 6693 // Identify the diagnostic messages that should be produced. 6694 std::string VecDiagMsg, IntDiagMsg; 6695 bool VectorizeLoop = true, InterleaveLoop = true; 6696 if (Requirements.doesNotMeet(F, L, Hints)) { 6697 DEBUG(dbgs() << "LV: Not vectorizing: loop did not meet vectorization " 6698 "requirements.\n"); 6699 emitMissedWarning(F, L, Hints, ORE); 6700 return false; 6701 } 6702 6703 if (VF.Width == 1) { 6704 DEBUG(dbgs() << "LV: Vectorization is possible but not beneficial.\n"); 6705 VecDiagMsg = 6706 "the cost-model indicates that vectorization is not beneficial"; 6707 VectorizeLoop = false; 6708 } 6709 6710 if (IC == 1 && UserIC <= 1) { 6711 // Tell the user interleaving is not beneficial. 6712 DEBUG(dbgs() << "LV: Interleaving is not beneficial.\n"); 6713 IntDiagMsg = 6714 "the cost-model indicates that interleaving is not beneficial"; 6715 InterleaveLoop = false; 6716 if (UserIC == 1) 6717 IntDiagMsg += 6718 " and is explicitly disabled or interleave count is set to 1"; 6719 } else if (IC > 1 && UserIC == 1) { 6720 // Tell the user interleaving is beneficial, but it explicitly disabled. 6721 DEBUG(dbgs() 6722 << "LV: Interleaving is beneficial but is explicitly disabled."); 6723 IntDiagMsg = "the cost-model indicates that interleaving is beneficial " 6724 "but is explicitly disabled or interleave count is set to 1"; 6725 InterleaveLoop = false; 6726 } 6727 6728 // Override IC if user provided an interleave count. 6729 IC = UserIC > 0 ? UserIC : IC; 6730 6731 // Emit diagnostic messages, if any. 6732 const char *VAPassName = Hints.vectorizeAnalysisPassName(); 6733 if (!VectorizeLoop && !InterleaveLoop) { 6734 // Do not vectorize or interleaving the loop. 6735 ORE->emitOptimizationRemarkAnalysis(VAPassName, L, VecDiagMsg); 6736 ORE->emitOptimizationRemarkAnalysis(LV_NAME, L, IntDiagMsg); 6737 return false; 6738 } else if (!VectorizeLoop && InterleaveLoop) { 6739 DEBUG(dbgs() << "LV: Interleave Count is " << IC << '\n'); 6740 ORE->emitOptimizationRemarkAnalysis(VAPassName, L, VecDiagMsg); 6741 } else if (VectorizeLoop && !InterleaveLoop) { 6742 DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width << ") in " 6743 << DebugLocStr << '\n'); 6744 ORE->emitOptimizationRemarkAnalysis(LV_NAME, L, IntDiagMsg); 6745 } else if (VectorizeLoop && InterleaveLoop) { 6746 DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width << ") in " 6747 << DebugLocStr << '\n'); 6748 DEBUG(dbgs() << "LV: Interleave Count is " << IC << '\n'); 6749 } 6750 6751 if (!VectorizeLoop) { 6752 assert(IC > 1 && "interleave count should not be 1 or 0"); 6753 // If we decided that it is not legal to vectorize the loop, then 6754 // interleave it. 6755 InnerLoopUnroller Unroller(L, PSE, LI, DT, TLI, TTI, AC, ORE, IC); 6756 Unroller.vectorize(&LVL, CM.MinBWs); 6757 6758 ORE->emitOptimizationRemark(LV_NAME, L, 6759 Twine("interleaved loop (interleaved count: ") + 6760 Twine(IC) + ")"); 6761 } else { 6762 // If we decided that it is *legal* to vectorize the loop, then do it. 6763 InnerLoopVectorizer LB(L, PSE, LI, DT, TLI, TTI, AC, ORE, VF.Width, IC); 6764 LB.vectorize(&LVL, CM.MinBWs); 6765 ++LoopsVectorized; 6766 6767 // Add metadata to disable runtime unrolling a scalar loop when there are 6768 // no runtime checks about strides and memory. A scalar loop that is 6769 // rarely used is not worth unrolling. 6770 if (!LB.areSafetyChecksAdded()) 6771 AddRuntimeUnrollDisableMetaData(L); 6772 6773 // Report the vectorization decision. 6774 ORE->emitOptimizationRemark( 6775 LV_NAME, L, Twine("vectorized loop (vectorization width: ") + 6776 Twine(VF.Width) + ", interleaved count: " + Twine(IC) + 6777 ")"); 6778 } 6779 6780 // Mark the loop as already vectorized to avoid vectorizing again. 6781 Hints.setAlreadyVectorized(); 6782 6783 DEBUG(verifyFunction(*L->getHeader()->getParent())); 6784 return true; 6785 } 6786 6787 bool LoopVectorizePass::runImpl( 6788 Function &F, ScalarEvolution &SE_, LoopInfo &LI_, TargetTransformInfo &TTI_, 6789 DominatorTree &DT_, BlockFrequencyInfo &BFI_, TargetLibraryInfo *TLI_, 6790 DemandedBits &DB_, AliasAnalysis &AA_, AssumptionCache &AC_, 6791 std::function<const LoopAccessInfo &(Loop &)> &GetLAA_, 6792 OptimizationRemarkEmitter &ORE_) { 6793 6794 SE = &SE_; 6795 LI = &LI_; 6796 TTI = &TTI_; 6797 DT = &DT_; 6798 BFI = &BFI_; 6799 TLI = TLI_; 6800 AA = &AA_; 6801 AC = &AC_; 6802 GetLAA = &GetLAA_; 6803 DB = &DB_; 6804 ORE = &ORE_; 6805 6806 // Compute some weights outside of the loop over the loops. Compute this 6807 // using a BranchProbability to re-use its scaling math. 6808 const BranchProbability ColdProb(1, 5); // 20% 6809 ColdEntryFreq = BlockFrequency(BFI->getEntryFreq()) * ColdProb; 6810 6811 // Don't attempt if 6812 // 1. the target claims to have no vector registers, and 6813 // 2. interleaving won't help ILP. 6814 // 6815 // The second condition is necessary because, even if the target has no 6816 // vector registers, loop vectorization may still enable scalar 6817 // interleaving. 6818 if (!TTI->getNumberOfRegisters(true) && TTI->getMaxInterleaveFactor(1) < 2) 6819 return false; 6820 6821 // Build up a worklist of inner-loops to vectorize. This is necessary as 6822 // the act of vectorizing or partially unrolling a loop creates new loops 6823 // and can invalidate iterators across the loops. 6824 SmallVector<Loop *, 8> Worklist; 6825 6826 for (Loop *L : *LI) 6827 addAcyclicInnerLoop(*L, Worklist); 6828 6829 LoopsAnalyzed += Worklist.size(); 6830 6831 // Now walk the identified inner loops. 6832 bool Changed = false; 6833 while (!Worklist.empty()) 6834 Changed |= processLoop(Worklist.pop_back_val()); 6835 6836 // Process each loop nest in the function. 6837 return Changed; 6838 6839 } 6840 6841 6842 PreservedAnalyses LoopVectorizePass::run(Function &F, 6843 FunctionAnalysisManager &AM) { 6844 auto &SE = AM.getResult<ScalarEvolutionAnalysis>(F); 6845 auto &LI = AM.getResult<LoopAnalysis>(F); 6846 auto &TTI = AM.getResult<TargetIRAnalysis>(F); 6847 auto &DT = AM.getResult<DominatorTreeAnalysis>(F); 6848 auto &BFI = AM.getResult<BlockFrequencyAnalysis>(F); 6849 auto *TLI = AM.getCachedResult<TargetLibraryAnalysis>(F); 6850 auto &AA = AM.getResult<AAManager>(F); 6851 auto &AC = AM.getResult<AssumptionAnalysis>(F); 6852 auto &DB = AM.getResult<DemandedBitsAnalysis>(F); 6853 auto &ORE = AM.getResult<OptimizationRemarkEmitterAnalysis>(F); 6854 6855 auto &LAM = AM.getResult<LoopAnalysisManagerFunctionProxy>(F).getManager(); 6856 std::function<const LoopAccessInfo &(Loop &)> GetLAA = 6857 [&](Loop &L) -> const LoopAccessInfo & { 6858 return LAM.getResult<LoopAccessAnalysis>(L); 6859 }; 6860 bool Changed = 6861 runImpl(F, SE, LI, TTI, DT, BFI, TLI, DB, AA, AC, GetLAA, ORE); 6862 if (!Changed) 6863 return PreservedAnalyses::all(); 6864 PreservedAnalyses PA; 6865 PA.preserve<LoopAnalysis>(); 6866 PA.preserve<DominatorTreeAnalysis>(); 6867 PA.preserve<BasicAA>(); 6868 PA.preserve<GlobalsAA>(); 6869 return PA; 6870 } 6871