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