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 if (Trunc) { 2525 auto *TruncType = cast<IntegerType>(Trunc->getType()); 2526 assert(Step->getType()->isIntegerTy() && 2527 "Truncation requires an integer step"); 2528 ScalarIV = Builder.CreateCast(Instruction::Trunc, Induction, TruncType); 2529 Step = Builder.CreateTrunc(Step, TruncType); 2530 } else { 2531 ScalarIV = Induction; 2532 if (IV != OldInduction) { 2533 ScalarIV = IV->getType()->isIntegerTy() 2534 ? Builder.CreateSExtOrTrunc(ScalarIV, IV->getType()) 2535 : Builder.CreateCast(Instruction::SIToFP, Induction, 2536 IV->getType()); 2537 ScalarIV = ID.transform(Builder, ScalarIV, PSE.getSE(), DL); 2538 ScalarIV->setName("offset.idx"); 2539 } 2540 } 2541 } 2542 2543 // If we haven't yet vectorized the induction variable, splat the scalar 2544 // induction variable, and build the necessary step vectors. 2545 if (!VectorizedIV) { 2546 Value *Broadcasted = getBroadcastInstrs(ScalarIV); 2547 VectorParts Entry(UF); 2548 for (unsigned Part = 0; Part < UF; ++Part) 2549 Entry[Part] = 2550 getStepVector(Broadcasted, VF * Part, Step, ID.getInductionOpcode()); 2551 VectorLoopValueMap.initVector(EntryVal, Entry); 2552 if (Trunc) 2553 addMetadata(Entry, Trunc); 2554 } 2555 2556 // If an induction variable is only used for counting loop iterations or 2557 // calculating addresses, it doesn't need to be widened. Create scalar steps 2558 // that can be used by instructions we will later scalarize. Note that the 2559 // addition of the scalar steps will not increase the number of instructions 2560 // in the loop in the common case prior to InstCombine. We will be trading 2561 // one vector extract for each scalar step. 2562 if (NeedsScalarIV) 2563 buildScalarSteps(ScalarIV, Step, EntryVal, ID); 2564 } 2565 2566 Value *InnerLoopVectorizer::getStepVector(Value *Val, int StartIdx, Value *Step, 2567 Instruction::BinaryOps BinOp) { 2568 // Create and check the types. 2569 assert(Val->getType()->isVectorTy() && "Must be a vector"); 2570 int VLen = Val->getType()->getVectorNumElements(); 2571 2572 Type *STy = Val->getType()->getScalarType(); 2573 assert((STy->isIntegerTy() || STy->isFloatingPointTy()) && 2574 "Induction Step must be an integer or FP"); 2575 assert(Step->getType() == STy && "Step has wrong type"); 2576 2577 SmallVector<Constant *, 8> Indices; 2578 2579 if (STy->isIntegerTy()) { 2580 // Create a vector of consecutive numbers from zero to VF. 2581 for (int i = 0; i < VLen; ++i) 2582 Indices.push_back(ConstantInt::get(STy, StartIdx + i)); 2583 2584 // Add the consecutive indices to the vector value. 2585 Constant *Cv = ConstantVector::get(Indices); 2586 assert(Cv->getType() == Val->getType() && "Invalid consecutive vec"); 2587 Step = Builder.CreateVectorSplat(VLen, Step); 2588 assert(Step->getType() == Val->getType() && "Invalid step vec"); 2589 // FIXME: The newly created binary instructions should contain nsw/nuw flags, 2590 // which can be found from the original scalar operations. 2591 Step = Builder.CreateMul(Cv, Step); 2592 return Builder.CreateAdd(Val, Step, "induction"); 2593 } 2594 2595 // Floating point induction. 2596 assert((BinOp == Instruction::FAdd || BinOp == Instruction::FSub) && 2597 "Binary Opcode should be specified for FP induction"); 2598 // Create a vector of consecutive numbers from zero to VF. 2599 for (int i = 0; i < VLen; ++i) 2600 Indices.push_back(ConstantFP::get(STy, (double)(StartIdx + i))); 2601 2602 // Add the consecutive indices to the vector value. 2603 Constant *Cv = ConstantVector::get(Indices); 2604 2605 Step = Builder.CreateVectorSplat(VLen, Step); 2606 2607 // Floating point operations had to be 'fast' to enable the induction. 2608 FastMathFlags Flags; 2609 Flags.setUnsafeAlgebra(); 2610 2611 Value *MulOp = Builder.CreateFMul(Cv, Step); 2612 if (isa<Instruction>(MulOp)) 2613 // Have to check, MulOp may be a constant 2614 cast<Instruction>(MulOp)->setFastMathFlags(Flags); 2615 2616 Value *BOp = Builder.CreateBinOp(BinOp, Val, MulOp, "induction"); 2617 if (isa<Instruction>(BOp)) 2618 cast<Instruction>(BOp)->setFastMathFlags(Flags); 2619 return BOp; 2620 } 2621 2622 void InnerLoopVectorizer::buildScalarSteps(Value *ScalarIV, Value *Step, 2623 Value *EntryVal, 2624 const InductionDescriptor &ID) { 2625 2626 // We shouldn't have to build scalar steps if we aren't vectorizing. 2627 assert(VF > 1 && "VF should be greater than one"); 2628 2629 // Get the value type and ensure it and the step have the same integer type. 2630 Type *ScalarIVTy = ScalarIV->getType()->getScalarType(); 2631 assert(ScalarIVTy == Step->getType() && 2632 "Val and Step should have the same type"); 2633 2634 // We build scalar steps for both integer and floating-point induction 2635 // variables. Here, we determine the kind of arithmetic we will perform. 2636 Instruction::BinaryOps AddOp; 2637 Instruction::BinaryOps MulOp; 2638 if (ScalarIVTy->isIntegerTy()) { 2639 AddOp = Instruction::Add; 2640 MulOp = Instruction::Mul; 2641 } else { 2642 AddOp = ID.getInductionOpcode(); 2643 MulOp = Instruction::FMul; 2644 } 2645 2646 // Determine the number of scalars we need to generate for each unroll 2647 // iteration. If EntryVal is uniform, we only need to generate the first 2648 // lane. Otherwise, we generate all VF values. 2649 unsigned Lanes = 2650 Cost->isUniformAfterVectorization(cast<Instruction>(EntryVal), VF) ? 1 : VF; 2651 2652 // Compute the scalar steps and save the results in VectorLoopValueMap. 2653 ScalarParts Entry(UF); 2654 for (unsigned Part = 0; Part < UF; ++Part) { 2655 Entry[Part].resize(VF); 2656 for (unsigned Lane = 0; Lane < Lanes; ++Lane) { 2657 auto *StartIdx = getSignedIntOrFpConstant(ScalarIVTy, VF * Part + Lane); 2658 auto *Mul = addFastMathFlag(Builder.CreateBinOp(MulOp, StartIdx, Step)); 2659 auto *Add = addFastMathFlag(Builder.CreateBinOp(AddOp, ScalarIV, Mul)); 2660 Entry[Part][Lane] = Add; 2661 } 2662 } 2663 VectorLoopValueMap.initScalar(EntryVal, Entry); 2664 } 2665 2666 int LoopVectorizationLegality::isConsecutivePtr(Value *Ptr) { 2667 2668 const ValueToValueMap &Strides = getSymbolicStrides() ? *getSymbolicStrides() : 2669 ValueToValueMap(); 2670 2671 int Stride = getPtrStride(PSE, Ptr, TheLoop, Strides, true, false); 2672 if (Stride == 1 || Stride == -1) 2673 return Stride; 2674 return 0; 2675 } 2676 2677 bool LoopVectorizationLegality::isUniform(Value *V) { 2678 return LAI->isUniform(V); 2679 } 2680 2681 const InnerLoopVectorizer::VectorParts & 2682 InnerLoopVectorizer::getVectorValue(Value *V) { 2683 assert(V != Induction && "The new induction variable should not be used."); 2684 assert(!V->getType()->isVectorTy() && "Can't widen a vector"); 2685 assert(!V->getType()->isVoidTy() && "Type does not produce a value"); 2686 2687 // If we have a stride that is replaced by one, do it here. 2688 if (Legal->hasStride(V)) 2689 V = ConstantInt::get(V->getType(), 1); 2690 2691 // If we have this scalar in the map, return it. 2692 if (VectorLoopValueMap.hasVector(V)) 2693 return VectorLoopValueMap.VectorMapStorage[V]; 2694 2695 // If the value has not been vectorized, check if it has been scalarized 2696 // instead. If it has been scalarized, and we actually need the value in 2697 // vector form, we will construct the vector values on demand. 2698 if (VectorLoopValueMap.hasScalar(V)) { 2699 2700 // Initialize a new vector map entry. 2701 VectorParts Entry(UF); 2702 2703 // If we've scalarized a value, that value should be an instruction. 2704 auto *I = cast<Instruction>(V); 2705 2706 // If we aren't vectorizing, we can just copy the scalar map values over to 2707 // the vector map. 2708 if (VF == 1) { 2709 for (unsigned Part = 0; Part < UF; ++Part) 2710 Entry[Part] = getScalarValue(V, Part, 0); 2711 return VectorLoopValueMap.initVector(V, Entry); 2712 } 2713 2714 // Get the last scalar instruction we generated for V. If the value is 2715 // known to be uniform after vectorization, this corresponds to lane zero 2716 // of the last unroll iteration. Otherwise, the last instruction is the one 2717 // we created for the last vector lane of the last unroll iteration. 2718 unsigned LastLane = Cost->isUniformAfterVectorization(I, VF) ? 0 : VF - 1; 2719 auto *LastInst = cast<Instruction>(getScalarValue(V, UF - 1, LastLane)); 2720 2721 // Set the insert point after the last scalarized instruction. This ensures 2722 // the insertelement sequence will directly follow the scalar definitions. 2723 auto OldIP = Builder.saveIP(); 2724 auto NewIP = std::next(BasicBlock::iterator(LastInst)); 2725 Builder.SetInsertPoint(&*NewIP); 2726 2727 // However, if we are vectorizing, we need to construct the vector values. 2728 // If the value is known to be uniform after vectorization, we can just 2729 // broadcast the scalar value corresponding to lane zero for each unroll 2730 // iteration. Otherwise, we construct the vector values using insertelement 2731 // instructions. Since the resulting vectors are stored in 2732 // VectorLoopValueMap, we will only generate the insertelements once. 2733 for (unsigned Part = 0; Part < UF; ++Part) { 2734 Value *VectorValue = nullptr; 2735 if (Cost->isUniformAfterVectorization(I, VF)) { 2736 VectorValue = getBroadcastInstrs(getScalarValue(V, Part, 0)); 2737 } else { 2738 VectorValue = UndefValue::get(VectorType::get(V->getType(), VF)); 2739 for (unsigned Lane = 0; Lane < VF; ++Lane) 2740 VectorValue = Builder.CreateInsertElement( 2741 VectorValue, getScalarValue(V, Part, Lane), 2742 Builder.getInt32(Lane)); 2743 } 2744 Entry[Part] = VectorValue; 2745 } 2746 Builder.restoreIP(OldIP); 2747 return VectorLoopValueMap.initVector(V, Entry); 2748 } 2749 2750 // If this scalar is unknown, assume that it is a constant or that it is 2751 // loop invariant. Broadcast V and save the value for future uses. 2752 Value *B = getBroadcastInstrs(V); 2753 return VectorLoopValueMap.initVector(V, VectorParts(UF, B)); 2754 } 2755 2756 Value *InnerLoopVectorizer::getScalarValue(Value *V, unsigned Part, 2757 unsigned Lane) { 2758 2759 // If the value is not an instruction contained in the loop, it should 2760 // already be scalar. 2761 if (OrigLoop->isLoopInvariant(V)) 2762 return V; 2763 2764 assert(Lane > 0 ? 2765 !Cost->isUniformAfterVectorization(cast<Instruction>(V), VF) 2766 : true && "Uniform values only have lane zero"); 2767 2768 // If the value from the original loop has not been vectorized, it is 2769 // represented by UF x VF scalar values in the new loop. Return the requested 2770 // scalar value. 2771 if (VectorLoopValueMap.hasScalar(V)) 2772 return VectorLoopValueMap.ScalarMapStorage[V][Part][Lane]; 2773 2774 // If the value has not been scalarized, get its entry in VectorLoopValueMap 2775 // for the given unroll part. If this entry is not a vector type (i.e., the 2776 // vectorization factor is one), there is no need to generate an 2777 // extractelement instruction. 2778 auto *U = getVectorValue(V)[Part]; 2779 if (!U->getType()->isVectorTy()) { 2780 assert(VF == 1 && "Value not scalarized has non-vector type"); 2781 return U; 2782 } 2783 2784 // Otherwise, the value from the original loop has been vectorized and is 2785 // represented by UF vector values. Extract and return the requested scalar 2786 // value from the appropriate vector lane. 2787 return Builder.CreateExtractElement(U, Builder.getInt32(Lane)); 2788 } 2789 2790 Value *InnerLoopVectorizer::reverseVector(Value *Vec) { 2791 assert(Vec->getType()->isVectorTy() && "Invalid type"); 2792 SmallVector<Constant *, 8> ShuffleMask; 2793 for (unsigned i = 0; i < VF; ++i) 2794 ShuffleMask.push_back(Builder.getInt32(VF - i - 1)); 2795 2796 return Builder.CreateShuffleVector(Vec, UndefValue::get(Vec->getType()), 2797 ConstantVector::get(ShuffleMask), 2798 "reverse"); 2799 } 2800 2801 // Try to vectorize the interleave group that \p Instr belongs to. 2802 // 2803 // E.g. Translate following interleaved load group (factor = 3): 2804 // for (i = 0; i < N; i+=3) { 2805 // R = Pic[i]; // Member of index 0 2806 // G = Pic[i+1]; // Member of index 1 2807 // B = Pic[i+2]; // Member of index 2 2808 // ... // do something to R, G, B 2809 // } 2810 // To: 2811 // %wide.vec = load <12 x i32> ; Read 4 tuples of R,G,B 2812 // %R.vec = shuffle %wide.vec, undef, <0, 3, 6, 9> ; R elements 2813 // %G.vec = shuffle %wide.vec, undef, <1, 4, 7, 10> ; G elements 2814 // %B.vec = shuffle %wide.vec, undef, <2, 5, 8, 11> ; B elements 2815 // 2816 // Or translate following interleaved store group (factor = 3): 2817 // for (i = 0; i < N; i+=3) { 2818 // ... do something to R, G, B 2819 // Pic[i] = R; // Member of index 0 2820 // Pic[i+1] = G; // Member of index 1 2821 // Pic[i+2] = B; // Member of index 2 2822 // } 2823 // To: 2824 // %R_G.vec = shuffle %R.vec, %G.vec, <0, 1, 2, ..., 7> 2825 // %B_U.vec = shuffle %B.vec, undef, <0, 1, 2, 3, u, u, u, u> 2826 // %interleaved.vec = shuffle %R_G.vec, %B_U.vec, 2827 // <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11> ; Interleave R,G,B elements 2828 // store <12 x i32> %interleaved.vec ; Write 4 tuples of R,G,B 2829 void InnerLoopVectorizer::vectorizeInterleaveGroup(Instruction *Instr) { 2830 const InterleaveGroup *Group = Legal->getInterleavedAccessGroup(Instr); 2831 assert(Group && "Fail to get an interleaved access group."); 2832 2833 // Skip if current instruction is not the insert position. 2834 if (Instr != Group->getInsertPos()) 2835 return; 2836 2837 Value *Ptr = getPointerOperand(Instr); 2838 2839 // Prepare for the vector type of the interleaved load/store. 2840 Type *ScalarTy = getMemInstValueType(Instr); 2841 unsigned InterleaveFactor = Group->getFactor(); 2842 Type *VecTy = VectorType::get(ScalarTy, InterleaveFactor * VF); 2843 Type *PtrTy = VecTy->getPointerTo(getMemInstAddressSpace(Instr)); 2844 2845 // Prepare for the new pointers. 2846 setDebugLocFromInst(Builder, Ptr); 2847 SmallVector<Value *, 2> NewPtrs; 2848 unsigned Index = Group->getIndex(Instr); 2849 2850 // If the group is reverse, adjust the index to refer to the last vector lane 2851 // instead of the first. We adjust the index from the first vector lane, 2852 // rather than directly getting the pointer for lane VF - 1, because the 2853 // pointer operand of the interleaved access is supposed to be uniform. For 2854 // uniform instructions, we're only required to generate a value for the 2855 // first vector lane in each unroll iteration. 2856 if (Group->isReverse()) 2857 Index += (VF - 1) * Group->getFactor(); 2858 2859 for (unsigned Part = 0; Part < UF; Part++) { 2860 Value *NewPtr = getScalarValue(Ptr, Part, 0); 2861 2862 // Notice current instruction could be any index. Need to adjust the address 2863 // to the member of index 0. 2864 // 2865 // E.g. a = A[i+1]; // Member of index 1 (Current instruction) 2866 // b = A[i]; // Member of index 0 2867 // Current pointer is pointed to A[i+1], adjust it to A[i]. 2868 // 2869 // E.g. A[i+1] = a; // Member of index 1 2870 // A[i] = b; // Member of index 0 2871 // A[i+2] = c; // Member of index 2 (Current instruction) 2872 // Current pointer is pointed to A[i+2], adjust it to A[i]. 2873 NewPtr = Builder.CreateGEP(NewPtr, Builder.getInt32(-Index)); 2874 2875 // Cast to the vector pointer type. 2876 NewPtrs.push_back(Builder.CreateBitCast(NewPtr, PtrTy)); 2877 } 2878 2879 setDebugLocFromInst(Builder, Instr); 2880 Value *UndefVec = UndefValue::get(VecTy); 2881 2882 // Vectorize the interleaved load group. 2883 if (isa<LoadInst>(Instr)) { 2884 2885 // For each unroll part, create a wide load for the group. 2886 SmallVector<Value *, 2> NewLoads; 2887 for (unsigned Part = 0; Part < UF; Part++) { 2888 auto *NewLoad = Builder.CreateAlignedLoad( 2889 NewPtrs[Part], Group->getAlignment(), "wide.vec"); 2890 addMetadata(NewLoad, Instr); 2891 NewLoads.push_back(NewLoad); 2892 } 2893 2894 // For each member in the group, shuffle out the appropriate data from the 2895 // wide loads. 2896 for (unsigned I = 0; I < InterleaveFactor; ++I) { 2897 Instruction *Member = Group->getMember(I); 2898 2899 // Skip the gaps in the group. 2900 if (!Member) 2901 continue; 2902 2903 VectorParts Entry(UF); 2904 Constant *StrideMask = createStrideMask(Builder, I, InterleaveFactor, VF); 2905 for (unsigned Part = 0; Part < UF; Part++) { 2906 Value *StridedVec = Builder.CreateShuffleVector( 2907 NewLoads[Part], UndefVec, StrideMask, "strided.vec"); 2908 2909 // If this member has different type, cast the result type. 2910 if (Member->getType() != ScalarTy) { 2911 VectorType *OtherVTy = VectorType::get(Member->getType(), VF); 2912 StridedVec = Builder.CreateBitOrPointerCast(StridedVec, OtherVTy); 2913 } 2914 2915 Entry[Part] = 2916 Group->isReverse() ? reverseVector(StridedVec) : StridedVec; 2917 } 2918 VectorLoopValueMap.initVector(Member, Entry); 2919 } 2920 return; 2921 } 2922 2923 // The sub vector type for current instruction. 2924 VectorType *SubVT = VectorType::get(ScalarTy, VF); 2925 2926 // Vectorize the interleaved store group. 2927 for (unsigned Part = 0; Part < UF; Part++) { 2928 // Collect the stored vector from each member. 2929 SmallVector<Value *, 4> StoredVecs; 2930 for (unsigned i = 0; i < InterleaveFactor; i++) { 2931 // Interleaved store group doesn't allow a gap, so each index has a member 2932 Instruction *Member = Group->getMember(i); 2933 assert(Member && "Fail to get a member from an interleaved store group"); 2934 2935 Value *StoredVec = 2936 getVectorValue(cast<StoreInst>(Member)->getValueOperand())[Part]; 2937 if (Group->isReverse()) 2938 StoredVec = reverseVector(StoredVec); 2939 2940 // If this member has different type, cast it to an unified type. 2941 if (StoredVec->getType() != SubVT) 2942 StoredVec = Builder.CreateBitOrPointerCast(StoredVec, SubVT); 2943 2944 StoredVecs.push_back(StoredVec); 2945 } 2946 2947 // Concatenate all vectors into a wide vector. 2948 Value *WideVec = concatenateVectors(Builder, StoredVecs); 2949 2950 // Interleave the elements in the wide vector. 2951 Constant *IMask = createInterleaveMask(Builder, VF, InterleaveFactor); 2952 Value *IVec = Builder.CreateShuffleVector(WideVec, UndefVec, IMask, 2953 "interleaved.vec"); 2954 2955 Instruction *NewStoreInstr = 2956 Builder.CreateAlignedStore(IVec, NewPtrs[Part], Group->getAlignment()); 2957 addMetadata(NewStoreInstr, Instr); 2958 } 2959 } 2960 2961 void InnerLoopVectorizer::vectorizeMemoryInstruction(Instruction *Instr) { 2962 // Attempt to issue a wide load. 2963 LoadInst *LI = dyn_cast<LoadInst>(Instr); 2964 StoreInst *SI = dyn_cast<StoreInst>(Instr); 2965 2966 assert((LI || SI) && "Invalid Load/Store instruction"); 2967 2968 LoopVectorizationCostModel::InstWidening Decision = 2969 Cost->getWideningDecision(Instr, VF); 2970 assert(Decision != LoopVectorizationCostModel::CM_Unknown && 2971 "CM decision should be taken at this point"); 2972 if (Decision == LoopVectorizationCostModel::CM_Interleave) 2973 return vectorizeInterleaveGroup(Instr); 2974 2975 Type *ScalarDataTy = getMemInstValueType(Instr); 2976 Type *DataTy = VectorType::get(ScalarDataTy, VF); 2977 Value *Ptr = getPointerOperand(Instr); 2978 unsigned Alignment = getMemInstAlignment(Instr); 2979 // An alignment of 0 means target abi alignment. We need to use the scalar's 2980 // target abi alignment in such a case. 2981 const DataLayout &DL = Instr->getModule()->getDataLayout(); 2982 if (!Alignment) 2983 Alignment = DL.getABITypeAlignment(ScalarDataTy); 2984 unsigned AddressSpace = getMemInstAddressSpace(Instr); 2985 2986 // Scalarize the memory instruction if necessary. 2987 if (Decision == LoopVectorizationCostModel::CM_Scalarize) 2988 return scalarizeInstruction(Instr, Legal->isScalarWithPredication(Instr)); 2989 2990 // Determine if the pointer operand of the access is either consecutive or 2991 // reverse consecutive. 2992 int ConsecutiveStride = Legal->isConsecutivePtr(Ptr); 2993 bool Reverse = ConsecutiveStride < 0; 2994 bool CreateGatherScatter = 2995 (Decision == LoopVectorizationCostModel::CM_GatherScatter); 2996 2997 VectorParts VectorGep; 2998 2999 // Handle consecutive loads/stores. 3000 GetElementPtrInst *Gep = getGEPInstruction(Ptr); 3001 if (ConsecutiveStride) { 3002 Ptr = getScalarValue(Ptr, 0, 0); 3003 } else { 3004 // At this point we should vector version of GEP for Gather or Scatter 3005 assert(CreateGatherScatter && "The instruction should be scalarized"); 3006 if (Gep) { 3007 // Vectorizing GEP, across UF parts. We want to get a vector value for base 3008 // and each index that's defined inside the loop, even if it is 3009 // loop-invariant but wasn't hoisted out. Otherwise we want to keep them 3010 // scalar. 3011 SmallVector<VectorParts, 4> OpsV; 3012 for (Value *Op : Gep->operands()) { 3013 Instruction *SrcInst = dyn_cast<Instruction>(Op); 3014 if (SrcInst && OrigLoop->contains(SrcInst)) 3015 OpsV.push_back(getVectorValue(Op)); 3016 else 3017 OpsV.push_back(VectorParts(UF, Op)); 3018 } 3019 for (unsigned Part = 0; Part < UF; ++Part) { 3020 SmallVector<Value *, 4> Ops; 3021 Value *GEPBasePtr = OpsV[0][Part]; 3022 for (unsigned i = 1; i < Gep->getNumOperands(); i++) 3023 Ops.push_back(OpsV[i][Part]); 3024 Value *NewGep = Builder.CreateGEP(GEPBasePtr, Ops, "VectorGep"); 3025 cast<GetElementPtrInst>(NewGep)->setIsInBounds(Gep->isInBounds()); 3026 assert(NewGep->getType()->isVectorTy() && "Expected vector GEP"); 3027 3028 NewGep = 3029 Builder.CreateBitCast(NewGep, VectorType::get(Ptr->getType(), VF)); 3030 VectorGep.push_back(NewGep); 3031 } 3032 } else 3033 VectorGep = getVectorValue(Ptr); 3034 } 3035 3036 VectorParts Mask = createBlockInMask(Instr->getParent()); 3037 // Handle Stores: 3038 if (SI) { 3039 assert(!Legal->isUniform(SI->getPointerOperand()) && 3040 "We do not allow storing to uniform addresses"); 3041 setDebugLocFromInst(Builder, SI); 3042 // We don't want to update the value in the map as it might be used in 3043 // another expression. So don't use a reference type for "StoredVal". 3044 VectorParts StoredVal = getVectorValue(SI->getValueOperand()); 3045 3046 for (unsigned Part = 0; Part < UF; ++Part) { 3047 Instruction *NewSI = nullptr; 3048 if (CreateGatherScatter) { 3049 Value *MaskPart = Legal->isMaskRequired(SI) ? Mask[Part] : nullptr; 3050 NewSI = Builder.CreateMaskedScatter(StoredVal[Part], VectorGep[Part], 3051 Alignment, MaskPart); 3052 } else { 3053 // Calculate the pointer for the specific unroll-part. 3054 Value *PartPtr = 3055 Builder.CreateGEP(nullptr, Ptr, Builder.getInt32(Part * VF)); 3056 3057 if (Reverse) { 3058 // If we store to reverse consecutive memory locations, then we need 3059 // to reverse the order of elements in the stored value. 3060 StoredVal[Part] = reverseVector(StoredVal[Part]); 3061 // If the address is consecutive but reversed, then the 3062 // wide store needs to start at the last vector element. 3063 PartPtr = 3064 Builder.CreateGEP(nullptr, Ptr, Builder.getInt32(-Part * VF)); 3065 PartPtr = 3066 Builder.CreateGEP(nullptr, PartPtr, Builder.getInt32(1 - VF)); 3067 Mask[Part] = reverseVector(Mask[Part]); 3068 } 3069 3070 Value *VecPtr = 3071 Builder.CreateBitCast(PartPtr, DataTy->getPointerTo(AddressSpace)); 3072 3073 if (Legal->isMaskRequired(SI)) 3074 NewSI = Builder.CreateMaskedStore(StoredVal[Part], VecPtr, Alignment, 3075 Mask[Part]); 3076 else 3077 NewSI = 3078 Builder.CreateAlignedStore(StoredVal[Part], VecPtr, Alignment); 3079 } 3080 addMetadata(NewSI, SI); 3081 } 3082 return; 3083 } 3084 3085 // Handle loads. 3086 assert(LI && "Must have a load instruction"); 3087 setDebugLocFromInst(Builder, LI); 3088 VectorParts Entry(UF); 3089 for (unsigned Part = 0; Part < UF; ++Part) { 3090 Instruction *NewLI; 3091 if (CreateGatherScatter) { 3092 Value *MaskPart = Legal->isMaskRequired(LI) ? Mask[Part] : nullptr; 3093 NewLI = Builder.CreateMaskedGather(VectorGep[Part], Alignment, MaskPart, 3094 0, "wide.masked.gather"); 3095 Entry[Part] = NewLI; 3096 } else { 3097 // Calculate the pointer for the specific unroll-part. 3098 Value *PartPtr = 3099 Builder.CreateGEP(nullptr, Ptr, Builder.getInt32(Part * VF)); 3100 3101 if (Reverse) { 3102 // If the address is consecutive but reversed, then the 3103 // wide load needs to start at the last vector element. 3104 PartPtr = Builder.CreateGEP(nullptr, Ptr, Builder.getInt32(-Part * VF)); 3105 PartPtr = Builder.CreateGEP(nullptr, PartPtr, Builder.getInt32(1 - VF)); 3106 Mask[Part] = reverseVector(Mask[Part]); 3107 } 3108 3109 Value *VecPtr = 3110 Builder.CreateBitCast(PartPtr, DataTy->getPointerTo(AddressSpace)); 3111 if (Legal->isMaskRequired(LI)) 3112 NewLI = Builder.CreateMaskedLoad(VecPtr, Alignment, Mask[Part], 3113 UndefValue::get(DataTy), 3114 "wide.masked.load"); 3115 else 3116 NewLI = Builder.CreateAlignedLoad(VecPtr, Alignment, "wide.load"); 3117 Entry[Part] = Reverse ? reverseVector(NewLI) : NewLI; 3118 } 3119 addMetadata(NewLI, LI); 3120 } 3121 VectorLoopValueMap.initVector(Instr, Entry); 3122 } 3123 3124 void InnerLoopVectorizer::scalarizeInstruction(Instruction *Instr, 3125 bool IfPredicateInstr) { 3126 assert(!Instr->getType()->isAggregateType() && "Can't handle vectors"); 3127 DEBUG(dbgs() << "LV: Scalarizing" 3128 << (IfPredicateInstr ? " and predicating:" : ":") << *Instr 3129 << '\n'); 3130 // Holds vector parameters or scalars, in case of uniform vals. 3131 SmallVector<VectorParts, 4> Params; 3132 3133 setDebugLocFromInst(Builder, Instr); 3134 3135 // Does this instruction return a value ? 3136 bool IsVoidRetTy = Instr->getType()->isVoidTy(); 3137 3138 // Initialize a new scalar map entry. 3139 ScalarParts Entry(UF); 3140 3141 VectorParts Cond; 3142 if (IfPredicateInstr) 3143 Cond = createBlockInMask(Instr->getParent()); 3144 3145 // Determine the number of scalars we need to generate for each unroll 3146 // iteration. If the instruction is uniform, we only need to generate the 3147 // first lane. Otherwise, we generate all VF values. 3148 unsigned Lanes = Cost->isUniformAfterVectorization(Instr, VF) ? 1 : VF; 3149 3150 // For each vector unroll 'part': 3151 for (unsigned Part = 0; Part < UF; ++Part) { 3152 Entry[Part].resize(VF); 3153 // For each scalar that we create: 3154 for (unsigned Lane = 0; Lane < Lanes; ++Lane) { 3155 3156 // Start if-block. 3157 Value *Cmp = nullptr; 3158 if (IfPredicateInstr) { 3159 Cmp = Cond[Part]; 3160 if (Cmp->getType()->isVectorTy()) 3161 Cmp = Builder.CreateExtractElement(Cmp, Builder.getInt32(Lane)); 3162 Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Cmp, 3163 ConstantInt::get(Cmp->getType(), 1)); 3164 } 3165 3166 Instruction *Cloned = Instr->clone(); 3167 if (!IsVoidRetTy) 3168 Cloned->setName(Instr->getName() + ".cloned"); 3169 3170 // Replace the operands of the cloned instructions with their scalar 3171 // equivalents in the new loop. 3172 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) { 3173 auto *NewOp = getScalarValue(Instr->getOperand(op), Part, Lane); 3174 Cloned->setOperand(op, NewOp); 3175 } 3176 addNewMetadata(Cloned, Instr); 3177 3178 // Place the cloned scalar in the new loop. 3179 Builder.Insert(Cloned); 3180 3181 // Add the cloned scalar to the scalar map entry. 3182 Entry[Part][Lane] = Cloned; 3183 3184 // If we just cloned a new assumption, add it the assumption cache. 3185 if (auto *II = dyn_cast<IntrinsicInst>(Cloned)) 3186 if (II->getIntrinsicID() == Intrinsic::assume) 3187 AC->registerAssumption(II); 3188 3189 // End if-block. 3190 if (IfPredicateInstr) 3191 PredicatedInstructions.push_back(std::make_pair(Cloned, Cmp)); 3192 } 3193 } 3194 VectorLoopValueMap.initScalar(Instr, Entry); 3195 } 3196 3197 PHINode *InnerLoopVectorizer::createInductionVariable(Loop *L, Value *Start, 3198 Value *End, Value *Step, 3199 Instruction *DL) { 3200 BasicBlock *Header = L->getHeader(); 3201 BasicBlock *Latch = L->getLoopLatch(); 3202 // As we're just creating this loop, it's possible no latch exists 3203 // yet. If so, use the header as this will be a single block loop. 3204 if (!Latch) 3205 Latch = Header; 3206 3207 IRBuilder<> Builder(&*Header->getFirstInsertionPt()); 3208 Instruction *OldInst = getDebugLocFromInstOrOperands(OldInduction); 3209 setDebugLocFromInst(Builder, OldInst); 3210 auto *Induction = Builder.CreatePHI(Start->getType(), 2, "index"); 3211 3212 Builder.SetInsertPoint(Latch->getTerminator()); 3213 setDebugLocFromInst(Builder, OldInst); 3214 3215 // Create i+1 and fill the PHINode. 3216 Value *Next = Builder.CreateAdd(Induction, Step, "index.next"); 3217 Induction->addIncoming(Start, L->getLoopPreheader()); 3218 Induction->addIncoming(Next, Latch); 3219 // Create the compare. 3220 Value *ICmp = Builder.CreateICmpEQ(Next, End); 3221 Builder.CreateCondBr(ICmp, L->getExitBlock(), Header); 3222 3223 // Now we have two terminators. Remove the old one from the block. 3224 Latch->getTerminator()->eraseFromParent(); 3225 3226 return Induction; 3227 } 3228 3229 Value *InnerLoopVectorizer::getOrCreateTripCount(Loop *L) { 3230 if (TripCount) 3231 return TripCount; 3232 3233 IRBuilder<> Builder(L->getLoopPreheader()->getTerminator()); 3234 // Find the loop boundaries. 3235 ScalarEvolution *SE = PSE.getSE(); 3236 const SCEV *BackedgeTakenCount = PSE.getBackedgeTakenCount(); 3237 assert(BackedgeTakenCount != SE->getCouldNotCompute() && 3238 "Invalid loop count"); 3239 3240 Type *IdxTy = Legal->getWidestInductionType(); 3241 3242 // The exit count might have the type of i64 while the phi is i32. This can 3243 // happen if we have an induction variable that is sign extended before the 3244 // compare. The only way that we get a backedge taken count is that the 3245 // induction variable was signed and as such will not overflow. In such a case 3246 // truncation is legal. 3247 if (BackedgeTakenCount->getType()->getPrimitiveSizeInBits() > 3248 IdxTy->getPrimitiveSizeInBits()) 3249 BackedgeTakenCount = SE->getTruncateOrNoop(BackedgeTakenCount, IdxTy); 3250 BackedgeTakenCount = SE->getNoopOrZeroExtend(BackedgeTakenCount, IdxTy); 3251 3252 // Get the total trip count from the count by adding 1. 3253 const SCEV *ExitCount = SE->getAddExpr( 3254 BackedgeTakenCount, SE->getOne(BackedgeTakenCount->getType())); 3255 3256 const DataLayout &DL = L->getHeader()->getModule()->getDataLayout(); 3257 3258 // Expand the trip count and place the new instructions in the preheader. 3259 // Notice that the pre-header does not change, only the loop body. 3260 SCEVExpander Exp(*SE, DL, "induction"); 3261 3262 // Count holds the overall loop count (N). 3263 TripCount = Exp.expandCodeFor(ExitCount, ExitCount->getType(), 3264 L->getLoopPreheader()->getTerminator()); 3265 3266 if (TripCount->getType()->isPointerTy()) 3267 TripCount = 3268 CastInst::CreatePointerCast(TripCount, IdxTy, "exitcount.ptrcnt.to.int", 3269 L->getLoopPreheader()->getTerminator()); 3270 3271 return TripCount; 3272 } 3273 3274 Value *InnerLoopVectorizer::getOrCreateVectorTripCount(Loop *L) { 3275 if (VectorTripCount) 3276 return VectorTripCount; 3277 3278 Value *TC = getOrCreateTripCount(L); 3279 IRBuilder<> Builder(L->getLoopPreheader()->getTerminator()); 3280 3281 // Now we need to generate the expression for the part of the loop that the 3282 // vectorized body will execute. This is equal to N - (N % Step) if scalar 3283 // iterations are not required for correctness, or N - Step, otherwise. Step 3284 // is equal to the vectorization factor (number of SIMD elements) times the 3285 // unroll factor (number of SIMD instructions). 3286 Constant *Step = ConstantInt::get(TC->getType(), VF * UF); 3287 Value *R = Builder.CreateURem(TC, Step, "n.mod.vf"); 3288 3289 // If there is a non-reversed interleaved group that may speculatively access 3290 // memory out-of-bounds, we need to ensure that there will be at least one 3291 // iteration of the scalar epilogue loop. Thus, if the step evenly divides 3292 // the trip count, we set the remainder to be equal to the step. If the step 3293 // does not evenly divide the trip count, no adjustment is necessary since 3294 // there will already be scalar iterations. Note that the minimum iterations 3295 // check ensures that N >= Step. 3296 if (VF > 1 && Legal->requiresScalarEpilogue()) { 3297 auto *IsZero = Builder.CreateICmpEQ(R, ConstantInt::get(R->getType(), 0)); 3298 R = Builder.CreateSelect(IsZero, Step, R); 3299 } 3300 3301 VectorTripCount = Builder.CreateSub(TC, R, "n.vec"); 3302 3303 return VectorTripCount; 3304 } 3305 3306 void InnerLoopVectorizer::emitMinimumIterationCountCheck(Loop *L, 3307 BasicBlock *Bypass) { 3308 Value *Count = getOrCreateTripCount(L); 3309 BasicBlock *BB = L->getLoopPreheader(); 3310 IRBuilder<> Builder(BB->getTerminator()); 3311 3312 // Generate code to check that the loop's trip count that we computed by 3313 // adding one to the backedge-taken count will not overflow. 3314 Value *CheckMinIters = Builder.CreateICmpULT( 3315 Count, ConstantInt::get(Count->getType(), VF * UF), "min.iters.check"); 3316 3317 BasicBlock *NewBB = 3318 BB->splitBasicBlock(BB->getTerminator(), "min.iters.checked"); 3319 // Update dominator tree immediately if the generated block is a 3320 // LoopBypassBlock because SCEV expansions to generate loop bypass 3321 // checks may query it before the current function is finished. 3322 DT->addNewBlock(NewBB, BB); 3323 if (L->getParentLoop()) 3324 L->getParentLoop()->addBasicBlockToLoop(NewBB, *LI); 3325 ReplaceInstWithInst(BB->getTerminator(), 3326 BranchInst::Create(Bypass, NewBB, CheckMinIters)); 3327 LoopBypassBlocks.push_back(BB); 3328 } 3329 3330 void InnerLoopVectorizer::emitVectorLoopEnteredCheck(Loop *L, 3331 BasicBlock *Bypass) { 3332 Value *TC = getOrCreateVectorTripCount(L); 3333 BasicBlock *BB = L->getLoopPreheader(); 3334 IRBuilder<> Builder(BB->getTerminator()); 3335 3336 // Now, compare the new count to zero. If it is zero skip the vector loop and 3337 // jump to the scalar loop. 3338 Value *Cmp = Builder.CreateICmpEQ(TC, Constant::getNullValue(TC->getType()), 3339 "cmp.zero"); 3340 3341 // Generate code to check that the loop's trip count that we computed by 3342 // adding one to the backedge-taken count will not overflow. 3343 BasicBlock *NewBB = BB->splitBasicBlock(BB->getTerminator(), "vector.ph"); 3344 // Update dominator tree immediately if the generated block is a 3345 // LoopBypassBlock because SCEV expansions to generate loop bypass 3346 // checks may query it before the current function is finished. 3347 DT->addNewBlock(NewBB, BB); 3348 if (L->getParentLoop()) 3349 L->getParentLoop()->addBasicBlockToLoop(NewBB, *LI); 3350 ReplaceInstWithInst(BB->getTerminator(), 3351 BranchInst::Create(Bypass, NewBB, Cmp)); 3352 LoopBypassBlocks.push_back(BB); 3353 } 3354 3355 void InnerLoopVectorizer::emitSCEVChecks(Loop *L, BasicBlock *Bypass) { 3356 BasicBlock *BB = L->getLoopPreheader(); 3357 3358 // Generate the code to check that the SCEV assumptions that we made. 3359 // We want the new basic block to start at the first instruction in a 3360 // sequence of instructions that form a check. 3361 SCEVExpander Exp(*PSE.getSE(), Bypass->getModule()->getDataLayout(), 3362 "scev.check"); 3363 Value *SCEVCheck = 3364 Exp.expandCodeForPredicate(&PSE.getUnionPredicate(), BB->getTerminator()); 3365 3366 if (auto *C = dyn_cast<ConstantInt>(SCEVCheck)) 3367 if (C->isZero()) 3368 return; 3369 3370 // Create a new block containing the stride check. 3371 BB->setName("vector.scevcheck"); 3372 auto *NewBB = BB->splitBasicBlock(BB->getTerminator(), "vector.ph"); 3373 // Update dominator tree immediately if the generated block is a 3374 // LoopBypassBlock because SCEV expansions to generate loop bypass 3375 // checks may query it before the current function is finished. 3376 DT->addNewBlock(NewBB, BB); 3377 if (L->getParentLoop()) 3378 L->getParentLoop()->addBasicBlockToLoop(NewBB, *LI); 3379 ReplaceInstWithInst(BB->getTerminator(), 3380 BranchInst::Create(Bypass, NewBB, SCEVCheck)); 3381 LoopBypassBlocks.push_back(BB); 3382 AddedSafetyChecks = true; 3383 } 3384 3385 void InnerLoopVectorizer::emitMemRuntimeChecks(Loop *L, BasicBlock *Bypass) { 3386 BasicBlock *BB = L->getLoopPreheader(); 3387 3388 // Generate the code that checks in runtime if arrays overlap. We put the 3389 // checks into a separate block to make the more common case of few elements 3390 // faster. 3391 Instruction *FirstCheckInst; 3392 Instruction *MemRuntimeCheck; 3393 std::tie(FirstCheckInst, MemRuntimeCheck) = 3394 Legal->getLAI()->addRuntimeChecks(BB->getTerminator()); 3395 if (!MemRuntimeCheck) 3396 return; 3397 3398 // Create a new block containing the memory check. 3399 BB->setName("vector.memcheck"); 3400 auto *NewBB = BB->splitBasicBlock(BB->getTerminator(), "vector.ph"); 3401 // Update dominator tree immediately if the generated block is a 3402 // LoopBypassBlock because SCEV expansions to generate loop bypass 3403 // checks may query it before the current function is finished. 3404 DT->addNewBlock(NewBB, BB); 3405 if (L->getParentLoop()) 3406 L->getParentLoop()->addBasicBlockToLoop(NewBB, *LI); 3407 ReplaceInstWithInst(BB->getTerminator(), 3408 BranchInst::Create(Bypass, NewBB, MemRuntimeCheck)); 3409 LoopBypassBlocks.push_back(BB); 3410 AddedSafetyChecks = true; 3411 3412 // We currently don't use LoopVersioning for the actual loop cloning but we 3413 // still use it to add the noalias metadata. 3414 LVer = llvm::make_unique<LoopVersioning>(*Legal->getLAI(), OrigLoop, LI, DT, 3415 PSE.getSE()); 3416 LVer->prepareNoAliasMetadata(); 3417 } 3418 3419 void InnerLoopVectorizer::createEmptyLoop() { 3420 /* 3421 In this function we generate a new loop. The new loop will contain 3422 the vectorized instructions while the old loop will continue to run the 3423 scalar remainder. 3424 3425 [ ] <-- loop iteration number check. 3426 / | 3427 / v 3428 | [ ] <-- vector loop bypass (may consist of multiple blocks). 3429 | / | 3430 | / v 3431 || [ ] <-- vector pre header. 3432 |/ | 3433 | v 3434 | [ ] \ 3435 | [ ]_| <-- vector loop. 3436 | | 3437 | v 3438 | -[ ] <--- middle-block. 3439 | / | 3440 | / v 3441 -|- >[ ] <--- new preheader. 3442 | | 3443 | v 3444 | [ ] \ 3445 | [ ]_| <-- old scalar loop to handle remainder. 3446 \ | 3447 \ v 3448 >[ ] <-- exit block. 3449 ... 3450 */ 3451 3452 BasicBlock *OldBasicBlock = OrigLoop->getHeader(); 3453 BasicBlock *VectorPH = OrigLoop->getLoopPreheader(); 3454 BasicBlock *ExitBlock = OrigLoop->getExitBlock(); 3455 assert(VectorPH && "Invalid loop structure"); 3456 assert(ExitBlock && "Must have an exit block"); 3457 3458 // Some loops have a single integer induction variable, while other loops 3459 // don't. One example is c++ iterators that often have multiple pointer 3460 // induction variables. In the code below we also support a case where we 3461 // don't have a single induction variable. 3462 // 3463 // We try to obtain an induction variable from the original loop as hard 3464 // as possible. However if we don't find one that: 3465 // - is an integer 3466 // - counts from zero, stepping by one 3467 // - is the size of the widest induction variable type 3468 // then we create a new one. 3469 OldInduction = Legal->getPrimaryInduction(); 3470 Type *IdxTy = Legal->getWidestInductionType(); 3471 3472 // Split the single block loop into the two loop structure described above. 3473 BasicBlock *VecBody = 3474 VectorPH->splitBasicBlock(VectorPH->getTerminator(), "vector.body"); 3475 BasicBlock *MiddleBlock = 3476 VecBody->splitBasicBlock(VecBody->getTerminator(), "middle.block"); 3477 BasicBlock *ScalarPH = 3478 MiddleBlock->splitBasicBlock(MiddleBlock->getTerminator(), "scalar.ph"); 3479 3480 // Create and register the new vector loop. 3481 Loop *Lp = new Loop(); 3482 Loop *ParentLoop = OrigLoop->getParentLoop(); 3483 3484 // Insert the new loop into the loop nest and register the new basic blocks 3485 // before calling any utilities such as SCEV that require valid LoopInfo. 3486 if (ParentLoop) { 3487 ParentLoop->addChildLoop(Lp); 3488 ParentLoop->addBasicBlockToLoop(ScalarPH, *LI); 3489 ParentLoop->addBasicBlockToLoop(MiddleBlock, *LI); 3490 } else { 3491 LI->addTopLevelLoop(Lp); 3492 } 3493 Lp->addBasicBlockToLoop(VecBody, *LI); 3494 3495 // Find the loop boundaries. 3496 Value *Count = getOrCreateTripCount(Lp); 3497 3498 Value *StartIdx = ConstantInt::get(IdxTy, 0); 3499 3500 // We need to test whether the backedge-taken count is uint##_max. Adding one 3501 // to it will cause overflow and an incorrect loop trip count in the vector 3502 // body. In case of overflow we want to directly jump to the scalar remainder 3503 // loop. 3504 emitMinimumIterationCountCheck(Lp, ScalarPH); 3505 // Now, compare the new count to zero. If it is zero skip the vector loop and 3506 // jump to the scalar loop. 3507 emitVectorLoopEnteredCheck(Lp, ScalarPH); 3508 // Generate the code to check any assumptions that we've made for SCEV 3509 // expressions. 3510 emitSCEVChecks(Lp, ScalarPH); 3511 3512 // Generate the code that checks in runtime if arrays overlap. We put the 3513 // checks into a separate block to make the more common case of few elements 3514 // faster. 3515 emitMemRuntimeChecks(Lp, ScalarPH); 3516 3517 // Generate the induction variable. 3518 // The loop step is equal to the vectorization factor (num of SIMD elements) 3519 // times the unroll factor (num of SIMD instructions). 3520 Value *CountRoundDown = getOrCreateVectorTripCount(Lp); 3521 Constant *Step = ConstantInt::get(IdxTy, VF * UF); 3522 Induction = 3523 createInductionVariable(Lp, StartIdx, CountRoundDown, Step, 3524 getDebugLocFromInstOrOperands(OldInduction)); 3525 3526 // We are going to resume the execution of the scalar loop. 3527 // Go over all of the induction variables that we found and fix the 3528 // PHIs that are left in the scalar version of the loop. 3529 // The starting values of PHI nodes depend on the counter of the last 3530 // iteration in the vectorized loop. 3531 // If we come from a bypass edge then we need to start from the original 3532 // start value. 3533 3534 // This variable saves the new starting index for the scalar loop. It is used 3535 // to test if there are any tail iterations left once the vector loop has 3536 // completed. 3537 LoopVectorizationLegality::InductionList *List = Legal->getInductionVars(); 3538 for (auto &InductionEntry : *List) { 3539 PHINode *OrigPhi = InductionEntry.first; 3540 InductionDescriptor II = InductionEntry.second; 3541 3542 // Create phi nodes to merge from the backedge-taken check block. 3543 PHINode *BCResumeVal = PHINode::Create( 3544 OrigPhi->getType(), 3, "bc.resume.val", ScalarPH->getTerminator()); 3545 Value *&EndValue = IVEndValues[OrigPhi]; 3546 if (OrigPhi == OldInduction) { 3547 // We know what the end value is. 3548 EndValue = CountRoundDown; 3549 } else { 3550 IRBuilder<> B(LoopBypassBlocks.back()->getTerminator()); 3551 Type *StepType = II.getStep()->getType(); 3552 Instruction::CastOps CastOp = 3553 CastInst::getCastOpcode(CountRoundDown, true, StepType, true); 3554 Value *CRD = B.CreateCast(CastOp, CountRoundDown, StepType, "cast.crd"); 3555 const DataLayout &DL = OrigLoop->getHeader()->getModule()->getDataLayout(); 3556 EndValue = II.transform(B, CRD, PSE.getSE(), DL); 3557 EndValue->setName("ind.end"); 3558 } 3559 3560 // The new PHI merges the original incoming value, in case of a bypass, 3561 // or the value at the end of the vectorized loop. 3562 BCResumeVal->addIncoming(EndValue, MiddleBlock); 3563 3564 // Fix the scalar body counter (PHI node). 3565 unsigned BlockIdx = OrigPhi->getBasicBlockIndex(ScalarPH); 3566 3567 // The old induction's phi node in the scalar body needs the truncated 3568 // value. 3569 for (BasicBlock *BB : LoopBypassBlocks) 3570 BCResumeVal->addIncoming(II.getStartValue(), BB); 3571 OrigPhi->setIncomingValue(BlockIdx, BCResumeVal); 3572 } 3573 3574 // Add a check in the middle block to see if we have completed 3575 // all of the iterations in the first vector loop. 3576 // If (N - N%VF) == N, then we *don't* need to run the remainder. 3577 Value *CmpN = 3578 CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, Count, 3579 CountRoundDown, "cmp.n", MiddleBlock->getTerminator()); 3580 ReplaceInstWithInst(MiddleBlock->getTerminator(), 3581 BranchInst::Create(ExitBlock, ScalarPH, CmpN)); 3582 3583 // Get ready to start creating new instructions into the vectorized body. 3584 Builder.SetInsertPoint(&*VecBody->getFirstInsertionPt()); 3585 3586 // Save the state. 3587 LoopVectorPreHeader = Lp->getLoopPreheader(); 3588 LoopScalarPreHeader = ScalarPH; 3589 LoopMiddleBlock = MiddleBlock; 3590 LoopExitBlock = ExitBlock; 3591 LoopVectorBody = VecBody; 3592 LoopScalarBody = OldBasicBlock; 3593 3594 // Keep all loop hints from the original loop on the vector loop (we'll 3595 // replace the vectorizer-specific hints below). 3596 if (MDNode *LID = OrigLoop->getLoopID()) 3597 Lp->setLoopID(LID); 3598 3599 LoopVectorizeHints Hints(Lp, true, *ORE); 3600 Hints.setAlreadyVectorized(); 3601 } 3602 3603 // Fix up external users of the induction variable. At this point, we are 3604 // in LCSSA form, with all external PHIs that use the IV having one input value, 3605 // coming from the remainder loop. We need those PHIs to also have a correct 3606 // value for the IV when arriving directly from the middle block. 3607 void InnerLoopVectorizer::fixupIVUsers(PHINode *OrigPhi, 3608 const InductionDescriptor &II, 3609 Value *CountRoundDown, Value *EndValue, 3610 BasicBlock *MiddleBlock) { 3611 // There are two kinds of external IV usages - those that use the value 3612 // computed in the last iteration (the PHI) and those that use the penultimate 3613 // value (the value that feeds into the phi from the loop latch). 3614 // We allow both, but they, obviously, have different values. 3615 3616 assert(OrigLoop->getExitBlock() && "Expected a single exit block"); 3617 3618 DenseMap<Value *, Value *> MissingVals; 3619 3620 // An external user of the last iteration's value should see the value that 3621 // the remainder loop uses to initialize its own IV. 3622 Value *PostInc = OrigPhi->getIncomingValueForBlock(OrigLoop->getLoopLatch()); 3623 for (User *U : PostInc->users()) { 3624 Instruction *UI = cast<Instruction>(U); 3625 if (!OrigLoop->contains(UI)) { 3626 assert(isa<PHINode>(UI) && "Expected LCSSA form"); 3627 MissingVals[UI] = EndValue; 3628 } 3629 } 3630 3631 // An external user of the penultimate value need to see EndValue - Step. 3632 // The simplest way to get this is to recompute it from the constituent SCEVs, 3633 // that is Start + (Step * (CRD - 1)). 3634 for (User *U : OrigPhi->users()) { 3635 auto *UI = cast<Instruction>(U); 3636 if (!OrigLoop->contains(UI)) { 3637 const DataLayout &DL = 3638 OrigLoop->getHeader()->getModule()->getDataLayout(); 3639 assert(isa<PHINode>(UI) && "Expected LCSSA form"); 3640 3641 IRBuilder<> B(MiddleBlock->getTerminator()); 3642 Value *CountMinusOne = B.CreateSub( 3643 CountRoundDown, ConstantInt::get(CountRoundDown->getType(), 1)); 3644 Value *CMO = B.CreateSExtOrTrunc(CountMinusOne, II.getStep()->getType(), 3645 "cast.cmo"); 3646 Value *Escape = II.transform(B, CMO, PSE.getSE(), DL); 3647 Escape->setName("ind.escape"); 3648 MissingVals[UI] = Escape; 3649 } 3650 } 3651 3652 for (auto &I : MissingVals) { 3653 PHINode *PHI = cast<PHINode>(I.first); 3654 // One corner case we have to handle is two IVs "chasing" each-other, 3655 // that is %IV2 = phi [...], [ %IV1, %latch ] 3656 // In this case, if IV1 has an external use, we need to avoid adding both 3657 // "last value of IV1" and "penultimate value of IV2". So, verify that we 3658 // don't already have an incoming value for the middle block. 3659 if (PHI->getBasicBlockIndex(MiddleBlock) == -1) 3660 PHI->addIncoming(I.second, MiddleBlock); 3661 } 3662 } 3663 3664 namespace { 3665 struct CSEDenseMapInfo { 3666 static bool canHandle(const Instruction *I) { 3667 return isa<InsertElementInst>(I) || isa<ExtractElementInst>(I) || 3668 isa<ShuffleVectorInst>(I) || isa<GetElementPtrInst>(I); 3669 } 3670 static inline Instruction *getEmptyKey() { 3671 return DenseMapInfo<Instruction *>::getEmptyKey(); 3672 } 3673 static inline Instruction *getTombstoneKey() { 3674 return DenseMapInfo<Instruction *>::getTombstoneKey(); 3675 } 3676 static unsigned getHashValue(const Instruction *I) { 3677 assert(canHandle(I) && "Unknown instruction!"); 3678 return hash_combine(I->getOpcode(), hash_combine_range(I->value_op_begin(), 3679 I->value_op_end())); 3680 } 3681 static bool isEqual(const Instruction *LHS, const Instruction *RHS) { 3682 if (LHS == getEmptyKey() || RHS == getEmptyKey() || 3683 LHS == getTombstoneKey() || RHS == getTombstoneKey()) 3684 return LHS == RHS; 3685 return LHS->isIdenticalTo(RHS); 3686 } 3687 }; 3688 } 3689 3690 ///\brief Perform cse of induction variable instructions. 3691 static void cse(BasicBlock *BB) { 3692 // Perform simple cse. 3693 SmallDenseMap<Instruction *, Instruction *, 4, CSEDenseMapInfo> CSEMap; 3694 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) { 3695 Instruction *In = &*I++; 3696 3697 if (!CSEDenseMapInfo::canHandle(In)) 3698 continue; 3699 3700 // Check if we can replace this instruction with any of the 3701 // visited instructions. 3702 if (Instruction *V = CSEMap.lookup(In)) { 3703 In->replaceAllUsesWith(V); 3704 In->eraseFromParent(); 3705 continue; 3706 } 3707 3708 CSEMap[In] = In; 3709 } 3710 } 3711 3712 /// \brief Estimate the overhead of scalarizing an instruction. This is a 3713 /// convenience wrapper for the type-based getScalarizationOverhead API. 3714 static unsigned getScalarizationOverhead(Instruction *I, unsigned VF, 3715 const TargetTransformInfo &TTI) { 3716 if (VF == 1) 3717 return 0; 3718 3719 unsigned Cost = 0; 3720 Type *RetTy = ToVectorTy(I->getType(), VF); 3721 if (!RetTy->isVoidTy()) 3722 Cost += TTI.getScalarizationOverhead(RetTy, true, false); 3723 3724 if (CallInst *CI = dyn_cast<CallInst>(I)) { 3725 SmallVector<const Value *, 4> Operands(CI->arg_operands()); 3726 Cost += TTI.getOperandsScalarizationOverhead(Operands, VF); 3727 } else { 3728 SmallVector<const Value *, 4> Operands(I->operand_values()); 3729 Cost += TTI.getOperandsScalarizationOverhead(Operands, VF); 3730 } 3731 3732 return Cost; 3733 } 3734 3735 // Estimate cost of a call instruction CI if it were vectorized with factor VF. 3736 // Return the cost of the instruction, including scalarization overhead if it's 3737 // needed. The flag NeedToScalarize shows if the call needs to be scalarized - 3738 // i.e. either vector version isn't available, or is too expensive. 3739 static unsigned getVectorCallCost(CallInst *CI, unsigned VF, 3740 const TargetTransformInfo &TTI, 3741 const TargetLibraryInfo *TLI, 3742 bool &NeedToScalarize) { 3743 Function *F = CI->getCalledFunction(); 3744 StringRef FnName = CI->getCalledFunction()->getName(); 3745 Type *ScalarRetTy = CI->getType(); 3746 SmallVector<Type *, 4> Tys, ScalarTys; 3747 for (auto &ArgOp : CI->arg_operands()) 3748 ScalarTys.push_back(ArgOp->getType()); 3749 3750 // Estimate cost of scalarized vector call. The source operands are assumed 3751 // to be vectors, so we need to extract individual elements from there, 3752 // execute VF scalar calls, and then gather the result into the vector return 3753 // value. 3754 unsigned ScalarCallCost = TTI.getCallInstrCost(F, ScalarRetTy, ScalarTys); 3755 if (VF == 1) 3756 return ScalarCallCost; 3757 3758 // Compute corresponding vector type for return value and arguments. 3759 Type *RetTy = ToVectorTy(ScalarRetTy, VF); 3760 for (Type *ScalarTy : ScalarTys) 3761 Tys.push_back(ToVectorTy(ScalarTy, VF)); 3762 3763 // Compute costs of unpacking argument values for the scalar calls and 3764 // packing the return values to a vector. 3765 unsigned ScalarizationCost = getScalarizationOverhead(CI, VF, TTI); 3766 3767 unsigned Cost = ScalarCallCost * VF + ScalarizationCost; 3768 3769 // If we can't emit a vector call for this function, then the currently found 3770 // cost is the cost we need to return. 3771 NeedToScalarize = true; 3772 if (!TLI || !TLI->isFunctionVectorizable(FnName, VF) || CI->isNoBuiltin()) 3773 return Cost; 3774 3775 // If the corresponding vector cost is cheaper, return its cost. 3776 unsigned VectorCallCost = TTI.getCallInstrCost(nullptr, RetTy, Tys); 3777 if (VectorCallCost < Cost) { 3778 NeedToScalarize = false; 3779 return VectorCallCost; 3780 } 3781 return Cost; 3782 } 3783 3784 // Estimate cost of an intrinsic call instruction CI if it were vectorized with 3785 // factor VF. Return the cost of the instruction, including scalarization 3786 // overhead if it's needed. 3787 static unsigned getVectorIntrinsicCost(CallInst *CI, unsigned VF, 3788 const TargetTransformInfo &TTI, 3789 const TargetLibraryInfo *TLI) { 3790 Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI); 3791 assert(ID && "Expected intrinsic call!"); 3792 3793 FastMathFlags FMF; 3794 if (auto *FPMO = dyn_cast<FPMathOperator>(CI)) 3795 FMF = FPMO->getFastMathFlags(); 3796 3797 SmallVector<Value *, 4> Operands(CI->arg_operands()); 3798 return TTI.getIntrinsicInstrCost(ID, CI->getType(), Operands, FMF, VF); 3799 } 3800 3801 static Type *smallestIntegerVectorType(Type *T1, Type *T2) { 3802 auto *I1 = cast<IntegerType>(T1->getVectorElementType()); 3803 auto *I2 = cast<IntegerType>(T2->getVectorElementType()); 3804 return I1->getBitWidth() < I2->getBitWidth() ? T1 : T2; 3805 } 3806 static Type *largestIntegerVectorType(Type *T1, Type *T2) { 3807 auto *I1 = cast<IntegerType>(T1->getVectorElementType()); 3808 auto *I2 = cast<IntegerType>(T2->getVectorElementType()); 3809 return I1->getBitWidth() > I2->getBitWidth() ? T1 : T2; 3810 } 3811 3812 void InnerLoopVectorizer::truncateToMinimalBitwidths() { 3813 // For every instruction `I` in MinBWs, truncate the operands, create a 3814 // truncated version of `I` and reextend its result. InstCombine runs 3815 // later and will remove any ext/trunc pairs. 3816 // 3817 SmallPtrSet<Value *, 4> Erased; 3818 for (const auto &KV : Cost->getMinimalBitwidths()) { 3819 // If the value wasn't vectorized, we must maintain the original scalar 3820 // type. The absence of the value from VectorLoopValueMap indicates that it 3821 // wasn't vectorized. 3822 if (!VectorLoopValueMap.hasVector(KV.first)) 3823 continue; 3824 VectorParts &Parts = VectorLoopValueMap.getVector(KV.first); 3825 for (Value *&I : Parts) { 3826 if (Erased.count(I) || I->use_empty() || !isa<Instruction>(I)) 3827 continue; 3828 Type *OriginalTy = I->getType(); 3829 Type *ScalarTruncatedTy = 3830 IntegerType::get(OriginalTy->getContext(), KV.second); 3831 Type *TruncatedTy = VectorType::get(ScalarTruncatedTy, 3832 OriginalTy->getVectorNumElements()); 3833 if (TruncatedTy == OriginalTy) 3834 continue; 3835 3836 IRBuilder<> B(cast<Instruction>(I)); 3837 auto ShrinkOperand = [&](Value *V) -> Value * { 3838 if (auto *ZI = dyn_cast<ZExtInst>(V)) 3839 if (ZI->getSrcTy() == TruncatedTy) 3840 return ZI->getOperand(0); 3841 return B.CreateZExtOrTrunc(V, TruncatedTy); 3842 }; 3843 3844 // The actual instruction modification depends on the instruction type, 3845 // unfortunately. 3846 Value *NewI = nullptr; 3847 if (auto *BO = dyn_cast<BinaryOperator>(I)) { 3848 NewI = B.CreateBinOp(BO->getOpcode(), ShrinkOperand(BO->getOperand(0)), 3849 ShrinkOperand(BO->getOperand(1))); 3850 cast<BinaryOperator>(NewI)->copyIRFlags(I); 3851 } else if (auto *CI = dyn_cast<ICmpInst>(I)) { 3852 NewI = 3853 B.CreateICmp(CI->getPredicate(), ShrinkOperand(CI->getOperand(0)), 3854 ShrinkOperand(CI->getOperand(1))); 3855 } else if (auto *SI = dyn_cast<SelectInst>(I)) { 3856 NewI = B.CreateSelect(SI->getCondition(), 3857 ShrinkOperand(SI->getTrueValue()), 3858 ShrinkOperand(SI->getFalseValue())); 3859 } else if (auto *CI = dyn_cast<CastInst>(I)) { 3860 switch (CI->getOpcode()) { 3861 default: 3862 llvm_unreachable("Unhandled cast!"); 3863 case Instruction::Trunc: 3864 NewI = ShrinkOperand(CI->getOperand(0)); 3865 break; 3866 case Instruction::SExt: 3867 NewI = B.CreateSExtOrTrunc( 3868 CI->getOperand(0), 3869 smallestIntegerVectorType(OriginalTy, TruncatedTy)); 3870 break; 3871 case Instruction::ZExt: 3872 NewI = B.CreateZExtOrTrunc( 3873 CI->getOperand(0), 3874 smallestIntegerVectorType(OriginalTy, TruncatedTy)); 3875 break; 3876 } 3877 } else if (auto *SI = dyn_cast<ShuffleVectorInst>(I)) { 3878 auto Elements0 = SI->getOperand(0)->getType()->getVectorNumElements(); 3879 auto *O0 = B.CreateZExtOrTrunc( 3880 SI->getOperand(0), VectorType::get(ScalarTruncatedTy, Elements0)); 3881 auto Elements1 = SI->getOperand(1)->getType()->getVectorNumElements(); 3882 auto *O1 = B.CreateZExtOrTrunc( 3883 SI->getOperand(1), VectorType::get(ScalarTruncatedTy, Elements1)); 3884 3885 NewI = B.CreateShuffleVector(O0, O1, SI->getMask()); 3886 } else if (isa<LoadInst>(I)) { 3887 // Don't do anything with the operands, just extend the result. 3888 continue; 3889 } else if (auto *IE = dyn_cast<InsertElementInst>(I)) { 3890 auto Elements = IE->getOperand(0)->getType()->getVectorNumElements(); 3891 auto *O0 = B.CreateZExtOrTrunc( 3892 IE->getOperand(0), VectorType::get(ScalarTruncatedTy, Elements)); 3893 auto *O1 = B.CreateZExtOrTrunc(IE->getOperand(1), ScalarTruncatedTy); 3894 NewI = B.CreateInsertElement(O0, O1, IE->getOperand(2)); 3895 } else if (auto *EE = dyn_cast<ExtractElementInst>(I)) { 3896 auto Elements = EE->getOperand(0)->getType()->getVectorNumElements(); 3897 auto *O0 = B.CreateZExtOrTrunc( 3898 EE->getOperand(0), VectorType::get(ScalarTruncatedTy, Elements)); 3899 NewI = B.CreateExtractElement(O0, EE->getOperand(2)); 3900 } else { 3901 llvm_unreachable("Unhandled instruction type!"); 3902 } 3903 3904 // Lastly, extend the result. 3905 NewI->takeName(cast<Instruction>(I)); 3906 Value *Res = B.CreateZExtOrTrunc(NewI, OriginalTy); 3907 I->replaceAllUsesWith(Res); 3908 cast<Instruction>(I)->eraseFromParent(); 3909 Erased.insert(I); 3910 I = Res; 3911 } 3912 } 3913 3914 // We'll have created a bunch of ZExts that are now parentless. Clean up. 3915 for (const auto &KV : Cost->getMinimalBitwidths()) { 3916 // If the value wasn't vectorized, we must maintain the original scalar 3917 // type. The absence of the value from VectorLoopValueMap indicates that it 3918 // wasn't vectorized. 3919 if (!VectorLoopValueMap.hasVector(KV.first)) 3920 continue; 3921 VectorParts &Parts = VectorLoopValueMap.getVector(KV.first); 3922 for (Value *&I : Parts) { 3923 ZExtInst *Inst = dyn_cast<ZExtInst>(I); 3924 if (Inst && Inst->use_empty()) { 3925 Value *NewI = Inst->getOperand(0); 3926 Inst->eraseFromParent(); 3927 I = NewI; 3928 } 3929 } 3930 } 3931 } 3932 3933 void InnerLoopVectorizer::vectorizeLoop() { 3934 //===------------------------------------------------===// 3935 // 3936 // Notice: any optimization or new instruction that go 3937 // into the code below should be also be implemented in 3938 // the cost-model. 3939 // 3940 //===------------------------------------------------===// 3941 3942 // Collect instructions from the original loop that will become trivially 3943 // dead in the vectorized loop. We don't need to vectorize these 3944 // instructions. 3945 collectTriviallyDeadInstructions(); 3946 3947 // Scan the loop in a topological order to ensure that defs are vectorized 3948 // before users. 3949 LoopBlocksDFS DFS(OrigLoop); 3950 DFS.perform(LI); 3951 3952 // Vectorize all of the blocks in the original loop. 3953 for (BasicBlock *BB : make_range(DFS.beginRPO(), DFS.endRPO())) 3954 vectorizeBlockInLoop(BB); 3955 3956 // Insert truncates and extends for any truncated instructions as hints to 3957 // InstCombine. 3958 if (VF > 1) 3959 truncateToMinimalBitwidths(); 3960 3961 // At this point every instruction in the original loop is widened to a 3962 // vector form. Now we need to fix the recurrences in the loop. These PHI 3963 // nodes are currently empty because we did not want to introduce cycles. 3964 // This is the second stage of vectorizing recurrences. 3965 fixCrossIterationPHIs(); 3966 3967 // Update the dominator tree. 3968 // 3969 // FIXME: After creating the structure of the new loop, the dominator tree is 3970 // no longer up-to-date, and it remains that way until we update it 3971 // here. An out-of-date dominator tree is problematic for SCEV, 3972 // because SCEVExpander uses it to guide code generation. The 3973 // vectorizer use SCEVExpanders in several places. Instead, we should 3974 // keep the dominator tree up-to-date as we go. 3975 updateAnalysis(); 3976 3977 // Fix-up external users of the induction variables. 3978 for (auto &Entry : *Legal->getInductionVars()) 3979 fixupIVUsers(Entry.first, Entry.second, 3980 getOrCreateVectorTripCount(LI->getLoopFor(LoopVectorBody)), 3981 IVEndValues[Entry.first], LoopMiddleBlock); 3982 3983 fixLCSSAPHIs(); 3984 predicateInstructions(); 3985 3986 // Remove redundant induction instructions. 3987 cse(LoopVectorBody); 3988 } 3989 3990 void InnerLoopVectorizer::fixCrossIterationPHIs() { 3991 // In order to support recurrences we need to be able to vectorize Phi nodes. 3992 // Phi nodes have cycles, so we need to vectorize them in two stages. This is 3993 // stage #2: We now need to fix the recurrences by adding incoming edges to 3994 // the currently empty PHI nodes. At this point every instruction in the 3995 // original loop is widened to a vector form so we can use them to construct 3996 // the incoming edges. 3997 for (Instruction &I : *OrigLoop->getHeader()) { 3998 PHINode *Phi = dyn_cast<PHINode>(&I); 3999 if (!Phi) 4000 break; 4001 // Handle first-order recurrences and reductions that need to be fixed. 4002 if (Legal->isFirstOrderRecurrence(Phi)) 4003 fixFirstOrderRecurrence(Phi); 4004 else if (Legal->isReductionVariable(Phi)) 4005 fixReduction(Phi); 4006 } 4007 } 4008 4009 void InnerLoopVectorizer::fixFirstOrderRecurrence(PHINode *Phi) { 4010 4011 // This is the second phase of vectorizing first-order recurrences. An 4012 // overview of the transformation is described below. Suppose we have the 4013 // following loop. 4014 // 4015 // for (int i = 0; i < n; ++i) 4016 // b[i] = a[i] - a[i - 1]; 4017 // 4018 // There is a first-order recurrence on "a". For this loop, the shorthand 4019 // scalar IR looks like: 4020 // 4021 // scalar.ph: 4022 // s_init = a[-1] 4023 // br scalar.body 4024 // 4025 // scalar.body: 4026 // i = phi [0, scalar.ph], [i+1, scalar.body] 4027 // s1 = phi [s_init, scalar.ph], [s2, scalar.body] 4028 // s2 = a[i] 4029 // b[i] = s2 - s1 4030 // br cond, scalar.body, ... 4031 // 4032 // In this example, s1 is a recurrence because it's value depends on the 4033 // previous iteration. In the first phase of vectorization, we created a 4034 // temporary value for s1. We now complete the vectorization and produce the 4035 // shorthand vector IR shown below (for VF = 4, UF = 1). 4036 // 4037 // vector.ph: 4038 // v_init = vector(..., ..., ..., a[-1]) 4039 // br vector.body 4040 // 4041 // vector.body 4042 // i = phi [0, vector.ph], [i+4, vector.body] 4043 // v1 = phi [v_init, vector.ph], [v2, vector.body] 4044 // v2 = a[i, i+1, i+2, i+3]; 4045 // v3 = vector(v1(3), v2(0, 1, 2)) 4046 // b[i, i+1, i+2, i+3] = v2 - v3 4047 // br cond, vector.body, middle.block 4048 // 4049 // middle.block: 4050 // x = v2(3) 4051 // br scalar.ph 4052 // 4053 // scalar.ph: 4054 // s_init = phi [x, middle.block], [a[-1], otherwise] 4055 // br scalar.body 4056 // 4057 // After execution completes the vector loop, we extract the next value of 4058 // the recurrence (x) to use as the initial value in the scalar loop. 4059 4060 // Get the original loop preheader and single loop latch. 4061 auto *Preheader = OrigLoop->getLoopPreheader(); 4062 auto *Latch = OrigLoop->getLoopLatch(); 4063 4064 // Get the initial and previous values of the scalar recurrence. 4065 auto *ScalarInit = Phi->getIncomingValueForBlock(Preheader); 4066 auto *Previous = Phi->getIncomingValueForBlock(Latch); 4067 4068 // Create a vector from the initial value. 4069 auto *VectorInit = ScalarInit; 4070 if (VF > 1) { 4071 Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator()); 4072 VectorInit = Builder.CreateInsertElement( 4073 UndefValue::get(VectorType::get(VectorInit->getType(), VF)), VectorInit, 4074 Builder.getInt32(VF - 1), "vector.recur.init"); 4075 } 4076 4077 // We constructed a temporary phi node in the first phase of vectorization. 4078 // This phi node will eventually be deleted. 4079 VectorParts &PhiParts = VectorLoopValueMap.getVector(Phi); 4080 Builder.SetInsertPoint(cast<Instruction>(PhiParts[0])); 4081 4082 // Create a phi node for the new recurrence. The current value will either be 4083 // the initial value inserted into a vector or loop-varying vector value. 4084 auto *VecPhi = Builder.CreatePHI(VectorInit->getType(), 2, "vector.recur"); 4085 VecPhi->addIncoming(VectorInit, LoopVectorPreHeader); 4086 4087 // Get the vectorized previous value. 4088 auto &PreviousParts = getVectorValue(Previous); 4089 4090 // Set the insertion point after the previous value if it is an instruction. 4091 // Note that the previous value may have been constant-folded so it is not 4092 // guaranteed to be an instruction in the vector loop. 4093 if (LI->getLoopFor(LoopVectorBody)->isLoopInvariant(PreviousParts[UF - 1])) 4094 Builder.SetInsertPoint(&*LoopVectorBody->getFirstInsertionPt()); 4095 else 4096 Builder.SetInsertPoint( 4097 &*++BasicBlock::iterator(cast<Instruction>(PreviousParts[UF - 1]))); 4098 4099 // We will construct a vector for the recurrence by combining the values for 4100 // the current and previous iterations. This is the required shuffle mask. 4101 SmallVector<Constant *, 8> ShuffleMask(VF); 4102 ShuffleMask[0] = Builder.getInt32(VF - 1); 4103 for (unsigned I = 1; I < VF; ++I) 4104 ShuffleMask[I] = Builder.getInt32(I + VF - 1); 4105 4106 // The vector from which to take the initial value for the current iteration 4107 // (actual or unrolled). Initially, this is the vector phi node. 4108 Value *Incoming = VecPhi; 4109 4110 // Shuffle the current and previous vector and update the vector parts. 4111 for (unsigned Part = 0; Part < UF; ++Part) { 4112 auto *Shuffle = 4113 VF > 1 4114 ? Builder.CreateShuffleVector(Incoming, PreviousParts[Part], 4115 ConstantVector::get(ShuffleMask)) 4116 : Incoming; 4117 PhiParts[Part]->replaceAllUsesWith(Shuffle); 4118 cast<Instruction>(PhiParts[Part])->eraseFromParent(); 4119 PhiParts[Part] = Shuffle; 4120 Incoming = PreviousParts[Part]; 4121 } 4122 4123 // Fix the latch value of the new recurrence in the vector loop. 4124 VecPhi->addIncoming(Incoming, LI->getLoopFor(LoopVectorBody)->getLoopLatch()); 4125 4126 // Extract the last vector element in the middle block. This will be the 4127 // initial value for the recurrence when jumping to the scalar loop. 4128 auto *Extract = Incoming; 4129 if (VF > 1) { 4130 Builder.SetInsertPoint(LoopMiddleBlock->getTerminator()); 4131 Extract = Builder.CreateExtractElement(Extract, Builder.getInt32(VF - 1), 4132 "vector.recur.extract"); 4133 } 4134 4135 // Fix the initial value of the original recurrence in the scalar loop. 4136 Builder.SetInsertPoint(&*LoopScalarPreHeader->begin()); 4137 auto *Start = Builder.CreatePHI(Phi->getType(), 2, "scalar.recur.init"); 4138 for (auto *BB : predecessors(LoopScalarPreHeader)) { 4139 auto *Incoming = BB == LoopMiddleBlock ? Extract : ScalarInit; 4140 Start->addIncoming(Incoming, BB); 4141 } 4142 4143 Phi->setIncomingValue(Phi->getBasicBlockIndex(LoopScalarPreHeader), Start); 4144 Phi->setName("scalar.recur"); 4145 4146 // Finally, fix users of the recurrence outside the loop. The users will need 4147 // either the last value of the scalar recurrence or the last value of the 4148 // vector recurrence we extracted in the middle block. Since the loop is in 4149 // LCSSA form, we just need to find the phi node for the original scalar 4150 // recurrence in the exit block, and then add an edge for the middle block. 4151 for (auto &I : *LoopExitBlock) { 4152 auto *LCSSAPhi = dyn_cast<PHINode>(&I); 4153 if (!LCSSAPhi) 4154 break; 4155 if (LCSSAPhi->getIncomingValue(0) == Phi) { 4156 LCSSAPhi->addIncoming(Extract, LoopMiddleBlock); 4157 break; 4158 } 4159 } 4160 } 4161 4162 void InnerLoopVectorizer::fixReduction(PHINode *Phi) { 4163 Constant *Zero = Builder.getInt32(0); 4164 4165 // Get it's reduction variable descriptor. 4166 assert(Legal->isReductionVariable(Phi) && 4167 "Unable to find the reduction variable"); 4168 RecurrenceDescriptor RdxDesc = (*Legal->getReductionVars())[Phi]; 4169 4170 RecurrenceDescriptor::RecurrenceKind RK = RdxDesc.getRecurrenceKind(); 4171 TrackingVH<Value> ReductionStartValue = RdxDesc.getRecurrenceStartValue(); 4172 Instruction *LoopExitInst = RdxDesc.getLoopExitInstr(); 4173 RecurrenceDescriptor::MinMaxRecurrenceKind MinMaxKind = 4174 RdxDesc.getMinMaxRecurrenceKind(); 4175 setDebugLocFromInst(Builder, ReductionStartValue); 4176 4177 // We need to generate a reduction vector from the incoming scalar. 4178 // To do so, we need to generate the 'identity' vector and override 4179 // one of the elements with the incoming scalar reduction. We need 4180 // to do it in the vector-loop preheader. 4181 Builder.SetInsertPoint(LoopBypassBlocks[1]->getTerminator()); 4182 4183 // This is the vector-clone of the value that leaves the loop. 4184 const VectorParts &VectorExit = getVectorValue(LoopExitInst); 4185 Type *VecTy = VectorExit[0]->getType(); 4186 4187 // Find the reduction identity variable. Zero for addition, or, xor, 4188 // one for multiplication, -1 for And. 4189 Value *Identity; 4190 Value *VectorStart; 4191 if (RK == RecurrenceDescriptor::RK_IntegerMinMax || 4192 RK == RecurrenceDescriptor::RK_FloatMinMax) { 4193 // MinMax reduction have the start value as their identify. 4194 if (VF == 1) { 4195 VectorStart = Identity = ReductionStartValue; 4196 } else { 4197 VectorStart = Identity = 4198 Builder.CreateVectorSplat(VF, ReductionStartValue, "minmax.ident"); 4199 } 4200 } else { 4201 // Handle other reduction kinds: 4202 Constant *Iden = RecurrenceDescriptor::getRecurrenceIdentity( 4203 RK, VecTy->getScalarType()); 4204 if (VF == 1) { 4205 Identity = Iden; 4206 // This vector is the Identity vector where the first element is the 4207 // incoming scalar reduction. 4208 VectorStart = ReductionStartValue; 4209 } else { 4210 Identity = ConstantVector::getSplat(VF, Iden); 4211 4212 // This vector is the Identity vector where the first element is the 4213 // incoming scalar reduction. 4214 VectorStart = 4215 Builder.CreateInsertElement(Identity, ReductionStartValue, Zero); 4216 } 4217 } 4218 4219 // Fix the vector-loop phi. 4220 4221 // Reductions do not have to start at zero. They can start with 4222 // any loop invariant values. 4223 const VectorParts &VecRdxPhi = getVectorValue(Phi); 4224 BasicBlock *Latch = OrigLoop->getLoopLatch(); 4225 Value *LoopVal = Phi->getIncomingValueForBlock(Latch); 4226 const VectorParts &Val = getVectorValue(LoopVal); 4227 for (unsigned part = 0; part < UF; ++part) { 4228 // Make sure to add the reduction stat value only to the 4229 // first unroll part. 4230 Value *StartVal = (part == 0) ? VectorStart : Identity; 4231 cast<PHINode>(VecRdxPhi[part]) 4232 ->addIncoming(StartVal, LoopVectorPreHeader); 4233 cast<PHINode>(VecRdxPhi[part]) 4234 ->addIncoming(Val[part], LoopVectorBody); 4235 } 4236 4237 // Before each round, move the insertion point right between 4238 // the PHIs and the values we are going to write. 4239 // This allows us to write both PHINodes and the extractelement 4240 // instructions. 4241 Builder.SetInsertPoint(&*LoopMiddleBlock->getFirstInsertionPt()); 4242 4243 VectorParts &RdxParts = VectorLoopValueMap.getVector(LoopExitInst); 4244 setDebugLocFromInst(Builder, LoopExitInst); 4245 4246 // If the vector reduction can be performed in a smaller type, we truncate 4247 // then extend the loop exit value to enable InstCombine to evaluate the 4248 // entire expression in the smaller type. 4249 if (VF > 1 && Phi->getType() != RdxDesc.getRecurrenceType()) { 4250 Type *RdxVecTy = VectorType::get(RdxDesc.getRecurrenceType(), VF); 4251 Builder.SetInsertPoint(LoopVectorBody->getTerminator()); 4252 for (unsigned part = 0; part < UF; ++part) { 4253 Value *Trunc = Builder.CreateTrunc(RdxParts[part], RdxVecTy); 4254 Value *Extnd = RdxDesc.isSigned() ? Builder.CreateSExt(Trunc, VecTy) 4255 : Builder.CreateZExt(Trunc, VecTy); 4256 for (Value::user_iterator UI = RdxParts[part]->user_begin(); 4257 UI != RdxParts[part]->user_end();) 4258 if (*UI != Trunc) { 4259 (*UI++)->replaceUsesOfWith(RdxParts[part], Extnd); 4260 RdxParts[part] = Extnd; 4261 } else { 4262 ++UI; 4263 } 4264 } 4265 Builder.SetInsertPoint(&*LoopMiddleBlock->getFirstInsertionPt()); 4266 for (unsigned part = 0; part < UF; ++part) 4267 RdxParts[part] = Builder.CreateTrunc(RdxParts[part], RdxVecTy); 4268 } 4269 4270 // Reduce all of the unrolled parts into a single vector. 4271 Value *ReducedPartRdx = RdxParts[0]; 4272 unsigned Op = RecurrenceDescriptor::getRecurrenceBinOp(RK); 4273 setDebugLocFromInst(Builder, ReducedPartRdx); 4274 for (unsigned part = 1; part < UF; ++part) { 4275 if (Op != Instruction::ICmp && Op != Instruction::FCmp) 4276 // Floating point operations had to be 'fast' to enable the reduction. 4277 ReducedPartRdx = addFastMathFlag( 4278 Builder.CreateBinOp((Instruction::BinaryOps)Op, RdxParts[part], 4279 ReducedPartRdx, "bin.rdx")); 4280 else 4281 ReducedPartRdx = RecurrenceDescriptor::createMinMaxOp( 4282 Builder, MinMaxKind, ReducedPartRdx, RdxParts[part]); 4283 } 4284 4285 if (VF > 1) { 4286 // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles 4287 // and vector ops, reducing the set of values being computed by half each 4288 // round. 4289 assert(isPowerOf2_32(VF) && 4290 "Reduction emission only supported for pow2 vectors!"); 4291 Value *TmpVec = ReducedPartRdx; 4292 SmallVector<Constant *, 32> ShuffleMask(VF, nullptr); 4293 for (unsigned i = VF; i != 1; i >>= 1) { 4294 // Move the upper half of the vector to the lower half. 4295 for (unsigned j = 0; j != i / 2; ++j) 4296 ShuffleMask[j] = Builder.getInt32(i / 2 + j); 4297 4298 // Fill the rest of the mask with undef. 4299 std::fill(&ShuffleMask[i / 2], ShuffleMask.end(), 4300 UndefValue::get(Builder.getInt32Ty())); 4301 4302 Value *Shuf = Builder.CreateShuffleVector( 4303 TmpVec, UndefValue::get(TmpVec->getType()), 4304 ConstantVector::get(ShuffleMask), "rdx.shuf"); 4305 4306 if (Op != Instruction::ICmp && Op != Instruction::FCmp) 4307 // Floating point operations had to be 'fast' to enable the reduction. 4308 TmpVec = addFastMathFlag(Builder.CreateBinOp( 4309 (Instruction::BinaryOps)Op, TmpVec, Shuf, "bin.rdx")); 4310 else 4311 TmpVec = RecurrenceDescriptor::createMinMaxOp(Builder, MinMaxKind, 4312 TmpVec, Shuf); 4313 } 4314 4315 // The result is in the first element of the vector. 4316 ReducedPartRdx = 4317 Builder.CreateExtractElement(TmpVec, Builder.getInt32(0)); 4318 4319 // If the reduction can be performed in a smaller type, we need to extend 4320 // the reduction to the wider type before we branch to the original loop. 4321 if (Phi->getType() != RdxDesc.getRecurrenceType()) 4322 ReducedPartRdx = 4323 RdxDesc.isSigned() 4324 ? Builder.CreateSExt(ReducedPartRdx, Phi->getType()) 4325 : Builder.CreateZExt(ReducedPartRdx, Phi->getType()); 4326 } 4327 4328 // Create a phi node that merges control-flow from the backedge-taken check 4329 // block and the middle block. 4330 PHINode *BCBlockPhi = PHINode::Create(Phi->getType(), 2, "bc.merge.rdx", 4331 LoopScalarPreHeader->getTerminator()); 4332 for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I) 4333 BCBlockPhi->addIncoming(ReductionStartValue, LoopBypassBlocks[I]); 4334 BCBlockPhi->addIncoming(ReducedPartRdx, LoopMiddleBlock); 4335 4336 // Now, we need to fix the users of the reduction variable 4337 // inside and outside of the scalar remainder loop. 4338 // We know that the loop is in LCSSA form. We need to update the 4339 // PHI nodes in the exit blocks. 4340 for (BasicBlock::iterator LEI = LoopExitBlock->begin(), 4341 LEE = LoopExitBlock->end(); 4342 LEI != LEE; ++LEI) { 4343 PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI); 4344 if (!LCSSAPhi) 4345 break; 4346 4347 // All PHINodes need to have a single entry edge, or two if 4348 // we already fixed them. 4349 assert(LCSSAPhi->getNumIncomingValues() < 3 && "Invalid LCSSA PHI"); 4350 4351 // We found a reduction value exit-PHI. Update it with the 4352 // incoming bypass edge. 4353 if (LCSSAPhi->getIncomingValue(0) == LoopExitInst) 4354 LCSSAPhi->addIncoming(ReducedPartRdx, LoopMiddleBlock); 4355 } // end of the LCSSA phi scan. 4356 4357 // Fix the scalar loop reduction variable with the incoming reduction sum 4358 // from the vector body and from the backedge value. 4359 int IncomingEdgeBlockIdx = 4360 Phi->getBasicBlockIndex(OrigLoop->getLoopLatch()); 4361 assert(IncomingEdgeBlockIdx >= 0 && "Invalid block index"); 4362 // Pick the other block. 4363 int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1); 4364 Phi->setIncomingValue(SelfEdgeBlockIdx, BCBlockPhi); 4365 Phi->setIncomingValue(IncomingEdgeBlockIdx, LoopExitInst); 4366 } 4367 4368 void InnerLoopVectorizer::fixLCSSAPHIs() { 4369 for (Instruction &LEI : *LoopExitBlock) { 4370 auto *LCSSAPhi = dyn_cast<PHINode>(&LEI); 4371 if (!LCSSAPhi) 4372 break; 4373 if (LCSSAPhi->getNumIncomingValues() == 1) 4374 LCSSAPhi->addIncoming(UndefValue::get(LCSSAPhi->getType()), 4375 LoopMiddleBlock); 4376 } 4377 } 4378 4379 void InnerLoopVectorizer::collectTriviallyDeadInstructions() { 4380 BasicBlock *Latch = OrigLoop->getLoopLatch(); 4381 4382 // We create new control-flow for the vectorized loop, so the original 4383 // condition will be dead after vectorization if it's only used by the 4384 // branch. 4385 auto *Cmp = dyn_cast<Instruction>(Latch->getTerminator()->getOperand(0)); 4386 if (Cmp && Cmp->hasOneUse()) 4387 DeadInstructions.insert(Cmp); 4388 4389 // We create new "steps" for induction variable updates to which the original 4390 // induction variables map. An original update instruction will be dead if 4391 // all its users except the induction variable are dead. 4392 for (auto &Induction : *Legal->getInductionVars()) { 4393 PHINode *Ind = Induction.first; 4394 auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch)); 4395 if (all_of(IndUpdate->users(), [&](User *U) -> bool { 4396 return U == Ind || DeadInstructions.count(cast<Instruction>(U)); 4397 })) 4398 DeadInstructions.insert(IndUpdate); 4399 } 4400 } 4401 4402 void InnerLoopVectorizer::sinkScalarOperands(Instruction *PredInst) { 4403 4404 // The basic block and loop containing the predicated instruction. 4405 auto *PredBB = PredInst->getParent(); 4406 auto *VectorLoop = LI->getLoopFor(PredBB); 4407 4408 // Initialize a worklist with the operands of the predicated instruction. 4409 SetVector<Value *> Worklist(PredInst->op_begin(), PredInst->op_end()); 4410 4411 // Holds instructions that we need to analyze again. An instruction may be 4412 // reanalyzed if we don't yet know if we can sink it or not. 4413 SmallVector<Instruction *, 8> InstsToReanalyze; 4414 4415 // Returns true if a given use occurs in the predicated block. Phi nodes use 4416 // their operands in their corresponding predecessor blocks. 4417 auto isBlockOfUsePredicated = [&](Use &U) -> bool { 4418 auto *I = cast<Instruction>(U.getUser()); 4419 BasicBlock *BB = I->getParent(); 4420 if (auto *Phi = dyn_cast<PHINode>(I)) 4421 BB = Phi->getIncomingBlock( 4422 PHINode::getIncomingValueNumForOperand(U.getOperandNo())); 4423 return BB == PredBB; 4424 }; 4425 4426 // Iteratively sink the scalarized operands of the predicated instruction 4427 // into the block we created for it. When an instruction is sunk, it's 4428 // operands are then added to the worklist. The algorithm ends after one pass 4429 // through the worklist doesn't sink a single instruction. 4430 bool Changed; 4431 do { 4432 4433 // Add the instructions that need to be reanalyzed to the worklist, and 4434 // reset the changed indicator. 4435 Worklist.insert(InstsToReanalyze.begin(), InstsToReanalyze.end()); 4436 InstsToReanalyze.clear(); 4437 Changed = false; 4438 4439 while (!Worklist.empty()) { 4440 auto *I = dyn_cast<Instruction>(Worklist.pop_back_val()); 4441 4442 // We can't sink an instruction if it is a phi node, is already in the 4443 // predicated block, is not in the loop, or may have side effects. 4444 if (!I || isa<PHINode>(I) || I->getParent() == PredBB || 4445 !VectorLoop->contains(I) || I->mayHaveSideEffects()) 4446 continue; 4447 4448 // It's legal to sink the instruction if all its uses occur in the 4449 // predicated block. Otherwise, there's nothing to do yet, and we may 4450 // need to reanalyze the instruction. 4451 if (!all_of(I->uses(), isBlockOfUsePredicated)) { 4452 InstsToReanalyze.push_back(I); 4453 continue; 4454 } 4455 4456 // Move the instruction to the beginning of the predicated block, and add 4457 // it's operands to the worklist. 4458 I->moveBefore(&*PredBB->getFirstInsertionPt()); 4459 Worklist.insert(I->op_begin(), I->op_end()); 4460 4461 // The sinking may have enabled other instructions to be sunk, so we will 4462 // need to iterate. 4463 Changed = true; 4464 } 4465 } while (Changed); 4466 } 4467 4468 void InnerLoopVectorizer::predicateInstructions() { 4469 4470 // For each instruction I marked for predication on value C, split I into its 4471 // own basic block to form an if-then construct over C. Since I may be fed by 4472 // an extractelement instruction or other scalar operand, we try to 4473 // iteratively sink its scalar operands into the predicated block. If I feeds 4474 // an insertelement instruction, we try to move this instruction into the 4475 // predicated block as well. For non-void types, a phi node will be created 4476 // for the resulting value (either vector or scalar). 4477 // 4478 // So for some predicated instruction, e.g. the conditional sdiv in: 4479 // 4480 // for.body: 4481 // ... 4482 // %add = add nsw i32 %mul, %0 4483 // %cmp5 = icmp sgt i32 %2, 7 4484 // br i1 %cmp5, label %if.then, label %if.end 4485 // 4486 // if.then: 4487 // %div = sdiv i32 %0, %1 4488 // br label %if.end 4489 // 4490 // if.end: 4491 // %x.0 = phi i32 [ %div, %if.then ], [ %add, %for.body ] 4492 // 4493 // the sdiv at this point is scalarized and if-converted using a select. 4494 // The inactive elements in the vector are not used, but the predicated 4495 // instruction is still executed for all vector elements, essentially: 4496 // 4497 // vector.body: 4498 // ... 4499 // %17 = add nsw <2 x i32> %16, %wide.load 4500 // %29 = extractelement <2 x i32> %wide.load, i32 0 4501 // %30 = extractelement <2 x i32> %wide.load51, i32 0 4502 // %31 = sdiv i32 %29, %30 4503 // %32 = insertelement <2 x i32> undef, i32 %31, i32 0 4504 // %35 = extractelement <2 x i32> %wide.load, i32 1 4505 // %36 = extractelement <2 x i32> %wide.load51, i32 1 4506 // %37 = sdiv i32 %35, %36 4507 // %38 = insertelement <2 x i32> %32, i32 %37, i32 1 4508 // %predphi = select <2 x i1> %26, <2 x i32> %38, <2 x i32> %17 4509 // 4510 // Predication will now re-introduce the original control flow to avoid false 4511 // side-effects by the sdiv instructions on the inactive elements, yielding 4512 // (after cleanup): 4513 // 4514 // vector.body: 4515 // ... 4516 // %5 = add nsw <2 x i32> %4, %wide.load 4517 // %8 = icmp sgt <2 x i32> %wide.load52, <i32 7, i32 7> 4518 // %9 = extractelement <2 x i1> %8, i32 0 4519 // br i1 %9, label %pred.sdiv.if, label %pred.sdiv.continue 4520 // 4521 // pred.sdiv.if: 4522 // %10 = extractelement <2 x i32> %wide.load, i32 0 4523 // %11 = extractelement <2 x i32> %wide.load51, i32 0 4524 // %12 = sdiv i32 %10, %11 4525 // %13 = insertelement <2 x i32> undef, i32 %12, i32 0 4526 // br label %pred.sdiv.continue 4527 // 4528 // pred.sdiv.continue: 4529 // %14 = phi <2 x i32> [ undef, %vector.body ], [ %13, %pred.sdiv.if ] 4530 // %15 = extractelement <2 x i1> %8, i32 1 4531 // br i1 %15, label %pred.sdiv.if54, label %pred.sdiv.continue55 4532 // 4533 // pred.sdiv.if54: 4534 // %16 = extractelement <2 x i32> %wide.load, i32 1 4535 // %17 = extractelement <2 x i32> %wide.load51, i32 1 4536 // %18 = sdiv i32 %16, %17 4537 // %19 = insertelement <2 x i32> %14, i32 %18, i32 1 4538 // br label %pred.sdiv.continue55 4539 // 4540 // pred.sdiv.continue55: 4541 // %20 = phi <2 x i32> [ %14, %pred.sdiv.continue ], [ %19, %pred.sdiv.if54 ] 4542 // %predphi = select <2 x i1> %8, <2 x i32> %20, <2 x i32> %5 4543 4544 for (auto KV : PredicatedInstructions) { 4545 BasicBlock::iterator I(KV.first); 4546 BasicBlock *Head = I->getParent(); 4547 auto *BB = SplitBlock(Head, &*std::next(I), DT, LI); 4548 auto *T = SplitBlockAndInsertIfThen(KV.second, &*I, /*Unreachable=*/false, 4549 /*BranchWeights=*/nullptr, DT, LI); 4550 I->moveBefore(T); 4551 sinkScalarOperands(&*I); 4552 4553 I->getParent()->setName(Twine("pred.") + I->getOpcodeName() + ".if"); 4554 BB->setName(Twine("pred.") + I->getOpcodeName() + ".continue"); 4555 4556 // If the instruction is non-void create a Phi node at reconvergence point. 4557 if (!I->getType()->isVoidTy()) { 4558 Value *IncomingTrue = nullptr; 4559 Value *IncomingFalse = nullptr; 4560 4561 if (I->hasOneUse() && isa<InsertElementInst>(*I->user_begin())) { 4562 // If the predicated instruction is feeding an insert-element, move it 4563 // into the Then block; Phi node will be created for the vector. 4564 InsertElementInst *IEI = cast<InsertElementInst>(*I->user_begin()); 4565 IEI->moveBefore(T); 4566 IncomingTrue = IEI; // the new vector with the inserted element. 4567 IncomingFalse = IEI->getOperand(0); // the unmodified vector 4568 } else { 4569 // Phi node will be created for the scalar predicated instruction. 4570 IncomingTrue = &*I; 4571 IncomingFalse = UndefValue::get(I->getType()); 4572 } 4573 4574 BasicBlock *PostDom = I->getParent()->getSingleSuccessor(); 4575 assert(PostDom && "Then block has multiple successors"); 4576 PHINode *Phi = 4577 PHINode::Create(IncomingTrue->getType(), 2, "", &PostDom->front()); 4578 IncomingTrue->replaceAllUsesWith(Phi); 4579 Phi->addIncoming(IncomingFalse, Head); 4580 Phi->addIncoming(IncomingTrue, I->getParent()); 4581 } 4582 } 4583 4584 DEBUG(DT->verifyDomTree()); 4585 } 4586 4587 InnerLoopVectorizer::VectorParts 4588 InnerLoopVectorizer::createEdgeMask(BasicBlock *Src, BasicBlock *Dst) { 4589 assert(is_contained(predecessors(Dst), Src) && "Invalid edge"); 4590 4591 // Look for cached value. 4592 std::pair<BasicBlock *, BasicBlock *> Edge(Src, Dst); 4593 EdgeMaskCache::iterator ECEntryIt = MaskCache.find(Edge); 4594 if (ECEntryIt != MaskCache.end()) 4595 return ECEntryIt->second; 4596 4597 VectorParts SrcMask = createBlockInMask(Src); 4598 4599 // The terminator has to be a branch inst! 4600 BranchInst *BI = dyn_cast<BranchInst>(Src->getTerminator()); 4601 assert(BI && "Unexpected terminator found"); 4602 4603 if (BI->isConditional()) { 4604 VectorParts EdgeMask = getVectorValue(BI->getCondition()); 4605 4606 if (BI->getSuccessor(0) != Dst) 4607 for (unsigned part = 0; part < UF; ++part) 4608 EdgeMask[part] = Builder.CreateNot(EdgeMask[part]); 4609 4610 for (unsigned part = 0; part < UF; ++part) 4611 EdgeMask[part] = Builder.CreateAnd(EdgeMask[part], SrcMask[part]); 4612 4613 MaskCache[Edge] = EdgeMask; 4614 return EdgeMask; 4615 } 4616 4617 MaskCache[Edge] = SrcMask; 4618 return SrcMask; 4619 } 4620 4621 InnerLoopVectorizer::VectorParts 4622 InnerLoopVectorizer::createBlockInMask(BasicBlock *BB) { 4623 assert(OrigLoop->contains(BB) && "Block is not a part of a loop"); 4624 4625 // Loop incoming mask is all-one. 4626 if (OrigLoop->getHeader() == BB) { 4627 Value *C = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 1); 4628 return getVectorValue(C); 4629 } 4630 4631 // This is the block mask. We OR all incoming edges, and with zero. 4632 Value *Zero = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 0); 4633 VectorParts BlockMask = getVectorValue(Zero); 4634 4635 // For each pred: 4636 for (pred_iterator it = pred_begin(BB), e = pred_end(BB); it != e; ++it) { 4637 VectorParts EM = createEdgeMask(*it, BB); 4638 for (unsigned part = 0; part < UF; ++part) 4639 BlockMask[part] = Builder.CreateOr(BlockMask[part], EM[part]); 4640 } 4641 4642 return BlockMask; 4643 } 4644 4645 void InnerLoopVectorizer::widenPHIInstruction(Instruction *PN, unsigned UF, 4646 unsigned VF) { 4647 PHINode *P = cast<PHINode>(PN); 4648 // In order to support recurrences we need to be able to vectorize Phi nodes. 4649 // Phi nodes have cycles, so we need to vectorize them in two stages. This is 4650 // stage #1: We create a new vector PHI node with no incoming edges. We'll use 4651 // this value when we vectorize all of the instructions that use the PHI. 4652 if (Legal->isReductionVariable(P) || Legal->isFirstOrderRecurrence(P)) { 4653 VectorParts Entry(UF); 4654 for (unsigned part = 0; part < UF; ++part) { 4655 // This is phase one of vectorizing PHIs. 4656 Type *VecTy = 4657 (VF == 1) ? PN->getType() : VectorType::get(PN->getType(), VF); 4658 Entry[part] = PHINode::Create( 4659 VecTy, 2, "vec.phi", &*LoopVectorBody->getFirstInsertionPt()); 4660 } 4661 VectorLoopValueMap.initVector(P, Entry); 4662 return; 4663 } 4664 4665 setDebugLocFromInst(Builder, P); 4666 // Check for PHI nodes that are lowered to vector selects. 4667 if (P->getParent() != OrigLoop->getHeader()) { 4668 // We know that all PHIs in non-header blocks are converted into 4669 // selects, so we don't have to worry about the insertion order and we 4670 // can just use the builder. 4671 // At this point we generate the predication tree. There may be 4672 // duplications since this is a simple recursive scan, but future 4673 // optimizations will clean it up. 4674 4675 unsigned NumIncoming = P->getNumIncomingValues(); 4676 4677 // Generate a sequence of selects of the form: 4678 // SELECT(Mask3, In3, 4679 // SELECT(Mask2, In2, 4680 // ( ...))) 4681 VectorParts Entry(UF); 4682 for (unsigned In = 0; In < NumIncoming; In++) { 4683 VectorParts Cond = 4684 createEdgeMask(P->getIncomingBlock(In), P->getParent()); 4685 const VectorParts &In0 = getVectorValue(P->getIncomingValue(In)); 4686 4687 for (unsigned part = 0; part < UF; ++part) { 4688 // We might have single edge PHIs (blocks) - use an identity 4689 // 'select' for the first PHI operand. 4690 if (In == 0) 4691 Entry[part] = Builder.CreateSelect(Cond[part], In0[part], In0[part]); 4692 else 4693 // Select between the current value and the previous incoming edge 4694 // based on the incoming mask. 4695 Entry[part] = Builder.CreateSelect(Cond[part], In0[part], Entry[part], 4696 "predphi"); 4697 } 4698 } 4699 VectorLoopValueMap.initVector(P, Entry); 4700 return; 4701 } 4702 4703 // This PHINode must be an induction variable. 4704 // Make sure that we know about it. 4705 assert(Legal->getInductionVars()->count(P) && "Not an induction variable"); 4706 4707 InductionDescriptor II = Legal->getInductionVars()->lookup(P); 4708 const DataLayout &DL = OrigLoop->getHeader()->getModule()->getDataLayout(); 4709 4710 // FIXME: The newly created binary instructions should contain nsw/nuw flags, 4711 // which can be found from the original scalar operations. 4712 switch (II.getKind()) { 4713 case InductionDescriptor::IK_NoInduction: 4714 llvm_unreachable("Unknown induction"); 4715 case InductionDescriptor::IK_IntInduction: 4716 case InductionDescriptor::IK_FpInduction: 4717 return widenIntOrFpInduction(P); 4718 case InductionDescriptor::IK_PtrInduction: { 4719 // Handle the pointer induction variable case. 4720 assert(P->getType()->isPointerTy() && "Unexpected type."); 4721 // This is the normalized GEP that starts counting at zero. 4722 Value *PtrInd = Induction; 4723 PtrInd = Builder.CreateSExtOrTrunc(PtrInd, II.getStep()->getType()); 4724 // Determine the number of scalars we need to generate for each unroll 4725 // iteration. If the instruction is uniform, we only need to generate the 4726 // first lane. Otherwise, we generate all VF values. 4727 unsigned Lanes = Cost->isUniformAfterVectorization(P, VF) ? 1 : VF; 4728 // These are the scalar results. Notice that we don't generate vector GEPs 4729 // because scalar GEPs result in better code. 4730 ScalarParts Entry(UF); 4731 for (unsigned Part = 0; Part < UF; ++Part) { 4732 Entry[Part].resize(VF); 4733 for (unsigned Lane = 0; Lane < Lanes; ++Lane) { 4734 Constant *Idx = ConstantInt::get(PtrInd->getType(), Lane + Part * VF); 4735 Value *GlobalIdx = Builder.CreateAdd(PtrInd, Idx); 4736 Value *SclrGep = II.transform(Builder, GlobalIdx, PSE.getSE(), DL); 4737 SclrGep->setName("next.gep"); 4738 Entry[Part][Lane] = SclrGep; 4739 } 4740 } 4741 VectorLoopValueMap.initScalar(P, Entry); 4742 return; 4743 } 4744 } 4745 } 4746 4747 /// A helper function for checking whether an integer division-related 4748 /// instruction may divide by zero (in which case it must be predicated if 4749 /// executed conditionally in the scalar code). 4750 /// TODO: It may be worthwhile to generalize and check isKnownNonZero(). 4751 /// Non-zero divisors that are non compile-time constants will not be 4752 /// converted into multiplication, so we will still end up scalarizing 4753 /// the division, but can do so w/o predication. 4754 static bool mayDivideByZero(Instruction &I) { 4755 assert((I.getOpcode() == Instruction::UDiv || 4756 I.getOpcode() == Instruction::SDiv || 4757 I.getOpcode() == Instruction::URem || 4758 I.getOpcode() == Instruction::SRem) && 4759 "Unexpected instruction"); 4760 Value *Divisor = I.getOperand(1); 4761 auto *CInt = dyn_cast<ConstantInt>(Divisor); 4762 return !CInt || CInt->isZero(); 4763 } 4764 4765 void InnerLoopVectorizer::vectorizeBlockInLoop(BasicBlock *BB) { 4766 // For each instruction in the old loop. 4767 for (Instruction &I : *BB) { 4768 4769 // If the instruction will become trivially dead when vectorized, we don't 4770 // need to generate it. 4771 if (DeadInstructions.count(&I)) 4772 continue; 4773 4774 // Scalarize instructions that should remain scalar after vectorization. 4775 if (VF > 1 && 4776 !(isa<BranchInst>(&I) || isa<PHINode>(&I) || 4777 isa<DbgInfoIntrinsic>(&I)) && 4778 shouldScalarizeInstruction(&I)) { 4779 scalarizeInstruction(&I, Legal->isScalarWithPredication(&I)); 4780 continue; 4781 } 4782 4783 switch (I.getOpcode()) { 4784 case Instruction::Br: 4785 // Nothing to do for PHIs and BR, since we already took care of the 4786 // loop control flow instructions. 4787 continue; 4788 case Instruction::PHI: { 4789 // Vectorize PHINodes. 4790 widenPHIInstruction(&I, UF, VF); 4791 continue; 4792 } // End of PHI. 4793 4794 case Instruction::UDiv: 4795 case Instruction::SDiv: 4796 case Instruction::SRem: 4797 case Instruction::URem: 4798 // Scalarize with predication if this instruction may divide by zero and 4799 // block execution is conditional, otherwise fallthrough. 4800 if (Legal->isScalarWithPredication(&I)) { 4801 scalarizeInstruction(&I, true); 4802 continue; 4803 } 4804 case Instruction::Add: 4805 case Instruction::FAdd: 4806 case Instruction::Sub: 4807 case Instruction::FSub: 4808 case Instruction::Mul: 4809 case Instruction::FMul: 4810 case Instruction::FDiv: 4811 case Instruction::FRem: 4812 case Instruction::Shl: 4813 case Instruction::LShr: 4814 case Instruction::AShr: 4815 case Instruction::And: 4816 case Instruction::Or: 4817 case Instruction::Xor: { 4818 // Just widen binops. 4819 auto *BinOp = cast<BinaryOperator>(&I); 4820 setDebugLocFromInst(Builder, BinOp); 4821 const VectorParts &A = getVectorValue(BinOp->getOperand(0)); 4822 const VectorParts &B = getVectorValue(BinOp->getOperand(1)); 4823 4824 // Use this vector value for all users of the original instruction. 4825 VectorParts Entry(UF); 4826 for (unsigned Part = 0; Part < UF; ++Part) { 4827 Value *V = Builder.CreateBinOp(BinOp->getOpcode(), A[Part], B[Part]); 4828 4829 if (BinaryOperator *VecOp = dyn_cast<BinaryOperator>(V)) 4830 VecOp->copyIRFlags(BinOp); 4831 4832 Entry[Part] = V; 4833 } 4834 4835 VectorLoopValueMap.initVector(&I, Entry); 4836 addMetadata(Entry, BinOp); 4837 break; 4838 } 4839 case Instruction::Select: { 4840 // Widen selects. 4841 // If the selector is loop invariant we can create a select 4842 // instruction with a scalar condition. Otherwise, use vector-select. 4843 auto *SE = PSE.getSE(); 4844 bool InvariantCond = 4845 SE->isLoopInvariant(PSE.getSCEV(I.getOperand(0)), OrigLoop); 4846 setDebugLocFromInst(Builder, &I); 4847 4848 // The condition can be loop invariant but still defined inside the 4849 // loop. This means that we can't just use the original 'cond' value. 4850 // We have to take the 'vectorized' value and pick the first lane. 4851 // Instcombine will make this a no-op. 4852 const VectorParts &Cond = getVectorValue(I.getOperand(0)); 4853 const VectorParts &Op0 = getVectorValue(I.getOperand(1)); 4854 const VectorParts &Op1 = getVectorValue(I.getOperand(2)); 4855 4856 auto *ScalarCond = getScalarValue(I.getOperand(0), 0, 0); 4857 4858 VectorParts Entry(UF); 4859 for (unsigned Part = 0; Part < UF; ++Part) { 4860 Entry[Part] = Builder.CreateSelect( 4861 InvariantCond ? ScalarCond : Cond[Part], Op0[Part], Op1[Part]); 4862 } 4863 4864 VectorLoopValueMap.initVector(&I, Entry); 4865 addMetadata(Entry, &I); 4866 break; 4867 } 4868 4869 case Instruction::ICmp: 4870 case Instruction::FCmp: { 4871 // Widen compares. Generate vector compares. 4872 bool FCmp = (I.getOpcode() == Instruction::FCmp); 4873 auto *Cmp = dyn_cast<CmpInst>(&I); 4874 setDebugLocFromInst(Builder, Cmp); 4875 const VectorParts &A = getVectorValue(Cmp->getOperand(0)); 4876 const VectorParts &B = getVectorValue(Cmp->getOperand(1)); 4877 VectorParts Entry(UF); 4878 for (unsigned Part = 0; Part < UF; ++Part) { 4879 Value *C = nullptr; 4880 if (FCmp) { 4881 C = Builder.CreateFCmp(Cmp->getPredicate(), A[Part], B[Part]); 4882 cast<FCmpInst>(C)->copyFastMathFlags(Cmp); 4883 } else { 4884 C = Builder.CreateICmp(Cmp->getPredicate(), A[Part], B[Part]); 4885 } 4886 Entry[Part] = C; 4887 } 4888 4889 VectorLoopValueMap.initVector(&I, Entry); 4890 addMetadata(Entry, &I); 4891 break; 4892 } 4893 4894 case Instruction::Store: 4895 case Instruction::Load: 4896 vectorizeMemoryInstruction(&I); 4897 break; 4898 case Instruction::ZExt: 4899 case Instruction::SExt: 4900 case Instruction::FPToUI: 4901 case Instruction::FPToSI: 4902 case Instruction::FPExt: 4903 case Instruction::PtrToInt: 4904 case Instruction::IntToPtr: 4905 case Instruction::SIToFP: 4906 case Instruction::UIToFP: 4907 case Instruction::Trunc: 4908 case Instruction::FPTrunc: 4909 case Instruction::BitCast: { 4910 auto *CI = dyn_cast<CastInst>(&I); 4911 setDebugLocFromInst(Builder, CI); 4912 4913 // Optimize the special case where the source is a constant integer 4914 // induction variable. Notice that we can only optimize the 'trunc' case 4915 // because (a) FP conversions lose precision, (b) sext/zext may wrap, and 4916 // (c) other casts depend on pointer size. 4917 if (Cost->isOptimizableIVTruncate(CI, VF)) { 4918 widenIntOrFpInduction(cast<PHINode>(CI->getOperand(0)), 4919 cast<TruncInst>(CI)); 4920 break; 4921 } 4922 4923 /// Vectorize casts. 4924 Type *DestTy = 4925 (VF == 1) ? CI->getType() : VectorType::get(CI->getType(), VF); 4926 4927 const VectorParts &A = getVectorValue(CI->getOperand(0)); 4928 VectorParts Entry(UF); 4929 for (unsigned Part = 0; Part < UF; ++Part) 4930 Entry[Part] = Builder.CreateCast(CI->getOpcode(), A[Part], DestTy); 4931 VectorLoopValueMap.initVector(&I, Entry); 4932 addMetadata(Entry, &I); 4933 break; 4934 } 4935 4936 case Instruction::Call: { 4937 // Ignore dbg intrinsics. 4938 if (isa<DbgInfoIntrinsic>(I)) 4939 break; 4940 setDebugLocFromInst(Builder, &I); 4941 4942 Module *M = BB->getParent()->getParent(); 4943 auto *CI = cast<CallInst>(&I); 4944 4945 StringRef FnName = CI->getCalledFunction()->getName(); 4946 Function *F = CI->getCalledFunction(); 4947 Type *RetTy = ToVectorTy(CI->getType(), VF); 4948 SmallVector<Type *, 4> Tys; 4949 for (Value *ArgOperand : CI->arg_operands()) 4950 Tys.push_back(ToVectorTy(ArgOperand->getType(), VF)); 4951 4952 Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI); 4953 if (ID && (ID == Intrinsic::assume || ID == Intrinsic::lifetime_end || 4954 ID == Intrinsic::lifetime_start)) { 4955 scalarizeInstruction(&I); 4956 break; 4957 } 4958 // The flag shows whether we use Intrinsic or a usual Call for vectorized 4959 // version of the instruction. 4960 // Is it beneficial to perform intrinsic call compared to lib call? 4961 bool NeedToScalarize; 4962 unsigned CallCost = getVectorCallCost(CI, VF, *TTI, TLI, NeedToScalarize); 4963 bool UseVectorIntrinsic = 4964 ID && getVectorIntrinsicCost(CI, VF, *TTI, TLI) <= CallCost; 4965 if (!UseVectorIntrinsic && NeedToScalarize) { 4966 scalarizeInstruction(&I); 4967 break; 4968 } 4969 4970 VectorParts Entry(UF); 4971 for (unsigned Part = 0; Part < UF; ++Part) { 4972 SmallVector<Value *, 4> Args; 4973 for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i) { 4974 Value *Arg = CI->getArgOperand(i); 4975 // Some intrinsics have a scalar argument - don't replace it with a 4976 // vector. 4977 if (!UseVectorIntrinsic || !hasVectorInstrinsicScalarOpd(ID, i)) { 4978 const VectorParts &VectorArg = getVectorValue(CI->getArgOperand(i)); 4979 Arg = VectorArg[Part]; 4980 } 4981 Args.push_back(Arg); 4982 } 4983 4984 Function *VectorF; 4985 if (UseVectorIntrinsic) { 4986 // Use vector version of the intrinsic. 4987 Type *TysForDecl[] = {CI->getType()}; 4988 if (VF > 1) 4989 TysForDecl[0] = VectorType::get(CI->getType()->getScalarType(), VF); 4990 VectorF = Intrinsic::getDeclaration(M, ID, TysForDecl); 4991 } else { 4992 // Use vector version of the library call. 4993 StringRef VFnName = TLI->getVectorizedFunction(FnName, VF); 4994 assert(!VFnName.empty() && "Vector function name is empty."); 4995 VectorF = M->getFunction(VFnName); 4996 if (!VectorF) { 4997 // Generate a declaration 4998 FunctionType *FTy = FunctionType::get(RetTy, Tys, false); 4999 VectorF = 5000 Function::Create(FTy, Function::ExternalLinkage, VFnName, M); 5001 VectorF->copyAttributesFrom(F); 5002 } 5003 } 5004 assert(VectorF && "Can't create vector function."); 5005 5006 SmallVector<OperandBundleDef, 1> OpBundles; 5007 CI->getOperandBundlesAsDefs(OpBundles); 5008 CallInst *V = Builder.CreateCall(VectorF, Args, OpBundles); 5009 5010 if (isa<FPMathOperator>(V)) 5011 V->copyFastMathFlags(CI); 5012 5013 Entry[Part] = V; 5014 } 5015 5016 VectorLoopValueMap.initVector(&I, Entry); 5017 addMetadata(Entry, &I); 5018 break; 5019 } 5020 5021 default: 5022 // All other instructions are unsupported. Scalarize them. 5023 scalarizeInstruction(&I); 5024 break; 5025 } // end of switch. 5026 } // end of for_each instr. 5027 } 5028 5029 void InnerLoopVectorizer::updateAnalysis() { 5030 // Forget the original basic block. 5031 PSE.getSE()->forgetLoop(OrigLoop); 5032 5033 // Update the dominator tree information. 5034 assert(DT->properlyDominates(LoopBypassBlocks.front(), LoopExitBlock) && 5035 "Entry does not dominate exit."); 5036 5037 // We don't predicate stores by this point, so the vector body should be a 5038 // single loop. 5039 DT->addNewBlock(LoopVectorBody, LoopVectorPreHeader); 5040 5041 DT->addNewBlock(LoopMiddleBlock, LoopVectorBody); 5042 DT->addNewBlock(LoopScalarPreHeader, LoopBypassBlocks[0]); 5043 DT->changeImmediateDominator(LoopScalarBody, LoopScalarPreHeader); 5044 DT->changeImmediateDominator(LoopExitBlock, LoopBypassBlocks[0]); 5045 5046 DEBUG(DT->verifyDomTree()); 5047 } 5048 5049 /// \brief Check whether it is safe to if-convert this phi node. 5050 /// 5051 /// Phi nodes with constant expressions that can trap are not safe to if 5052 /// convert. 5053 static bool canIfConvertPHINodes(BasicBlock *BB) { 5054 for (Instruction &I : *BB) { 5055 auto *Phi = dyn_cast<PHINode>(&I); 5056 if (!Phi) 5057 return true; 5058 for (Value *V : Phi->incoming_values()) 5059 if (auto *C = dyn_cast<Constant>(V)) 5060 if (C->canTrap()) 5061 return false; 5062 } 5063 return true; 5064 } 5065 5066 bool LoopVectorizationLegality::canVectorizeWithIfConvert() { 5067 if (!EnableIfConversion) { 5068 ORE->emit(createMissedAnalysis("IfConversionDisabled") 5069 << "if-conversion is disabled"); 5070 return false; 5071 } 5072 5073 assert(TheLoop->getNumBlocks() > 1 && "Single block loops are vectorizable"); 5074 5075 // A list of pointers that we can safely read and write to. 5076 SmallPtrSet<Value *, 8> SafePointes; 5077 5078 // Collect safe addresses. 5079 for (BasicBlock *BB : TheLoop->blocks()) { 5080 if (blockNeedsPredication(BB)) 5081 continue; 5082 5083 for (Instruction &I : *BB) 5084 if (auto *Ptr = getPointerOperand(&I)) 5085 SafePointes.insert(Ptr); 5086 } 5087 5088 // Collect the blocks that need predication. 5089 BasicBlock *Header = TheLoop->getHeader(); 5090 for (BasicBlock *BB : TheLoop->blocks()) { 5091 // We don't support switch statements inside loops. 5092 if (!isa<BranchInst>(BB->getTerminator())) { 5093 ORE->emit(createMissedAnalysis("LoopContainsSwitch", BB->getTerminator()) 5094 << "loop contains a switch statement"); 5095 return false; 5096 } 5097 5098 // We must be able to predicate all blocks that need to be predicated. 5099 if (blockNeedsPredication(BB)) { 5100 if (!blockCanBePredicated(BB, SafePointes)) { 5101 ORE->emit(createMissedAnalysis("NoCFGForSelect", BB->getTerminator()) 5102 << "control flow cannot be substituted for a select"); 5103 return false; 5104 } 5105 } else if (BB != Header && !canIfConvertPHINodes(BB)) { 5106 ORE->emit(createMissedAnalysis("NoCFGForSelect", BB->getTerminator()) 5107 << "control flow cannot be substituted for a select"); 5108 return false; 5109 } 5110 } 5111 5112 // We can if-convert this loop. 5113 return true; 5114 } 5115 5116 bool LoopVectorizationLegality::canVectorize() { 5117 // We must have a loop in canonical form. Loops with indirectbr in them cannot 5118 // be canonicalized. 5119 if (!TheLoop->getLoopPreheader()) { 5120 ORE->emit(createMissedAnalysis("CFGNotUnderstood") 5121 << "loop control flow is not understood by vectorizer"); 5122 return false; 5123 } 5124 5125 // FIXME: The code is currently dead, since the loop gets sent to 5126 // LoopVectorizationLegality is already an innermost loop. 5127 // 5128 // We can only vectorize innermost loops. 5129 if (!TheLoop->empty()) { 5130 ORE->emit(createMissedAnalysis("NotInnermostLoop") 5131 << "loop is not the innermost loop"); 5132 return false; 5133 } 5134 5135 // We must have a single backedge. 5136 if (TheLoop->getNumBackEdges() != 1) { 5137 ORE->emit(createMissedAnalysis("CFGNotUnderstood") 5138 << "loop control flow is not understood by vectorizer"); 5139 return false; 5140 } 5141 5142 // We must have a single exiting block. 5143 if (!TheLoop->getExitingBlock()) { 5144 ORE->emit(createMissedAnalysis("CFGNotUnderstood") 5145 << "loop control flow is not understood by vectorizer"); 5146 return false; 5147 } 5148 5149 // We only handle bottom-tested loops, i.e. loop in which the condition is 5150 // checked at the end of each iteration. With that we can assume that all 5151 // instructions in the loop are executed the same number of times. 5152 if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch()) { 5153 ORE->emit(createMissedAnalysis("CFGNotUnderstood") 5154 << "loop control flow is not understood by vectorizer"); 5155 return false; 5156 } 5157 5158 // We need to have a loop header. 5159 DEBUG(dbgs() << "LV: Found a loop: " << TheLoop->getHeader()->getName() 5160 << '\n'); 5161 5162 // Check if we can if-convert non-single-bb loops. 5163 unsigned NumBlocks = TheLoop->getNumBlocks(); 5164 if (NumBlocks != 1 && !canVectorizeWithIfConvert()) { 5165 DEBUG(dbgs() << "LV: Can't if-convert the loop.\n"); 5166 return false; 5167 } 5168 5169 // ScalarEvolution needs to be able to find the exit count. 5170 const SCEV *ExitCount = PSE.getBackedgeTakenCount(); 5171 if (ExitCount == PSE.getSE()->getCouldNotCompute()) { 5172 ORE->emit(createMissedAnalysis("CantComputeNumberOfIterations") 5173 << "could not determine number of loop iterations"); 5174 DEBUG(dbgs() << "LV: SCEV could not compute the loop exit count.\n"); 5175 return false; 5176 } 5177 5178 // Check if we can vectorize the instructions and CFG in this loop. 5179 if (!canVectorizeInstrs()) { 5180 DEBUG(dbgs() << "LV: Can't vectorize the instructions or CFG\n"); 5181 return false; 5182 } 5183 5184 // Go over each instruction and look at memory deps. 5185 if (!canVectorizeMemory()) { 5186 DEBUG(dbgs() << "LV: Can't vectorize due to memory conflicts\n"); 5187 return false; 5188 } 5189 5190 DEBUG(dbgs() << "LV: We can vectorize this loop" 5191 << (LAI->getRuntimePointerChecking()->Need 5192 ? " (with a runtime bound check)" 5193 : "") 5194 << "!\n"); 5195 5196 bool UseInterleaved = TTI->enableInterleavedAccessVectorization(); 5197 5198 // If an override option has been passed in for interleaved accesses, use it. 5199 if (EnableInterleavedMemAccesses.getNumOccurrences() > 0) 5200 UseInterleaved = EnableInterleavedMemAccesses; 5201 5202 // Analyze interleaved memory accesses. 5203 if (UseInterleaved) 5204 InterleaveInfo.analyzeInterleaving(*getSymbolicStrides()); 5205 5206 unsigned SCEVThreshold = VectorizeSCEVCheckThreshold; 5207 if (Hints->getForce() == LoopVectorizeHints::FK_Enabled) 5208 SCEVThreshold = PragmaVectorizeSCEVCheckThreshold; 5209 5210 if (PSE.getUnionPredicate().getComplexity() > SCEVThreshold) { 5211 ORE->emit(createMissedAnalysis("TooManySCEVRunTimeChecks") 5212 << "Too many SCEV assumptions need to be made and checked " 5213 << "at runtime"); 5214 DEBUG(dbgs() << "LV: Too many SCEV checks needed.\n"); 5215 return false; 5216 } 5217 5218 // Okay! We can vectorize. At this point we don't have any other mem analysis 5219 // which may limit our maximum vectorization factor, so just return true with 5220 // no restrictions. 5221 return true; 5222 } 5223 5224 static Type *convertPointerToIntegerType(const DataLayout &DL, Type *Ty) { 5225 if (Ty->isPointerTy()) 5226 return DL.getIntPtrType(Ty); 5227 5228 // It is possible that char's or short's overflow when we ask for the loop's 5229 // trip count, work around this by changing the type size. 5230 if (Ty->getScalarSizeInBits() < 32) 5231 return Type::getInt32Ty(Ty->getContext()); 5232 5233 return Ty; 5234 } 5235 5236 static Type *getWiderType(const DataLayout &DL, Type *Ty0, Type *Ty1) { 5237 Ty0 = convertPointerToIntegerType(DL, Ty0); 5238 Ty1 = convertPointerToIntegerType(DL, Ty1); 5239 if (Ty0->getScalarSizeInBits() > Ty1->getScalarSizeInBits()) 5240 return Ty0; 5241 return Ty1; 5242 } 5243 5244 /// \brief Check that the instruction has outside loop users and is not an 5245 /// identified reduction variable. 5246 static bool hasOutsideLoopUser(const Loop *TheLoop, Instruction *Inst, 5247 SmallPtrSetImpl<Value *> &AllowedExit) { 5248 // Reduction and Induction instructions are allowed to have exit users. All 5249 // other instructions must not have external users. 5250 if (!AllowedExit.count(Inst)) 5251 // Check that all of the users of the loop are inside the BB. 5252 for (User *U : Inst->users()) { 5253 Instruction *UI = cast<Instruction>(U); 5254 // This user may be a reduction exit value. 5255 if (!TheLoop->contains(UI)) { 5256 DEBUG(dbgs() << "LV: Found an outside user for : " << *UI << '\n'); 5257 return true; 5258 } 5259 } 5260 return false; 5261 } 5262 5263 void LoopVectorizationLegality::addInductionPhi( 5264 PHINode *Phi, const InductionDescriptor &ID, 5265 SmallPtrSetImpl<Value *> &AllowedExit) { 5266 Inductions[Phi] = ID; 5267 Type *PhiTy = Phi->getType(); 5268 const DataLayout &DL = Phi->getModule()->getDataLayout(); 5269 5270 // Get the widest type. 5271 if (!PhiTy->isFloatingPointTy()) { 5272 if (!WidestIndTy) 5273 WidestIndTy = convertPointerToIntegerType(DL, PhiTy); 5274 else 5275 WidestIndTy = getWiderType(DL, PhiTy, WidestIndTy); 5276 } 5277 5278 // Int inductions are special because we only allow one IV. 5279 if (ID.getKind() == InductionDescriptor::IK_IntInduction && 5280 ID.getConstIntStepValue() && 5281 ID.getConstIntStepValue()->isOne() && 5282 isa<Constant>(ID.getStartValue()) && 5283 cast<Constant>(ID.getStartValue())->isNullValue()) { 5284 5285 // Use the phi node with the widest type as induction. Use the last 5286 // one if there are multiple (no good reason for doing this other 5287 // than it is expedient). We've checked that it begins at zero and 5288 // steps by one, so this is a canonical induction variable. 5289 if (!PrimaryInduction || PhiTy == WidestIndTy) 5290 PrimaryInduction = Phi; 5291 } 5292 5293 // Both the PHI node itself, and the "post-increment" value feeding 5294 // back into the PHI node may have external users. 5295 AllowedExit.insert(Phi); 5296 AllowedExit.insert(Phi->getIncomingValueForBlock(TheLoop->getLoopLatch())); 5297 5298 DEBUG(dbgs() << "LV: Found an induction variable.\n"); 5299 return; 5300 } 5301 5302 bool LoopVectorizationLegality::canVectorizeInstrs() { 5303 BasicBlock *Header = TheLoop->getHeader(); 5304 5305 // Look for the attribute signaling the absence of NaNs. 5306 Function &F = *Header->getParent(); 5307 HasFunNoNaNAttr = 5308 F.getFnAttribute("no-nans-fp-math").getValueAsString() == "true"; 5309 5310 // For each block in the loop. 5311 for (BasicBlock *BB : TheLoop->blocks()) { 5312 // Scan the instructions in the block and look for hazards. 5313 for (Instruction &I : *BB) { 5314 if (auto *Phi = dyn_cast<PHINode>(&I)) { 5315 Type *PhiTy = Phi->getType(); 5316 // Check that this PHI type is allowed. 5317 if (!PhiTy->isIntegerTy() && !PhiTy->isFloatingPointTy() && 5318 !PhiTy->isPointerTy()) { 5319 ORE->emit(createMissedAnalysis("CFGNotUnderstood", Phi) 5320 << "loop control flow is not understood by vectorizer"); 5321 DEBUG(dbgs() << "LV: Found an non-int non-pointer PHI.\n"); 5322 return false; 5323 } 5324 5325 // If this PHINode is not in the header block, then we know that we 5326 // can convert it to select during if-conversion. No need to check if 5327 // the PHIs in this block are induction or reduction variables. 5328 if (BB != Header) { 5329 // Check that this instruction has no outside users or is an 5330 // identified reduction value with an outside user. 5331 if (!hasOutsideLoopUser(TheLoop, Phi, AllowedExit)) 5332 continue; 5333 ORE->emit(createMissedAnalysis("NeitherInductionNorReduction", Phi) 5334 << "value could not be identified as " 5335 "an induction or reduction variable"); 5336 return false; 5337 } 5338 5339 // We only allow if-converted PHIs with exactly two incoming values. 5340 if (Phi->getNumIncomingValues() != 2) { 5341 ORE->emit(createMissedAnalysis("CFGNotUnderstood", Phi) 5342 << "control flow not understood by vectorizer"); 5343 DEBUG(dbgs() << "LV: Found an invalid PHI.\n"); 5344 return false; 5345 } 5346 5347 RecurrenceDescriptor RedDes; 5348 if (RecurrenceDescriptor::isReductionPHI(Phi, TheLoop, RedDes)) { 5349 if (RedDes.hasUnsafeAlgebra()) 5350 Requirements->addUnsafeAlgebraInst(RedDes.getUnsafeAlgebraInst()); 5351 AllowedExit.insert(RedDes.getLoopExitInstr()); 5352 Reductions[Phi] = RedDes; 5353 continue; 5354 } 5355 5356 InductionDescriptor ID; 5357 if (InductionDescriptor::isInductionPHI(Phi, TheLoop, PSE, ID)) { 5358 addInductionPhi(Phi, ID, AllowedExit); 5359 if (ID.hasUnsafeAlgebra() && !HasFunNoNaNAttr) 5360 Requirements->addUnsafeAlgebraInst(ID.getUnsafeAlgebraInst()); 5361 continue; 5362 } 5363 5364 if (RecurrenceDescriptor::isFirstOrderRecurrence(Phi, TheLoop, DT)) { 5365 FirstOrderRecurrences.insert(Phi); 5366 continue; 5367 } 5368 5369 // As a last resort, coerce the PHI to a AddRec expression 5370 // and re-try classifying it a an induction PHI. 5371 if (InductionDescriptor::isInductionPHI(Phi, TheLoop, PSE, ID, true)) { 5372 addInductionPhi(Phi, ID, AllowedExit); 5373 continue; 5374 } 5375 5376 ORE->emit(createMissedAnalysis("NonReductionValueUsedOutsideLoop", Phi) 5377 << "value that could not be identified as " 5378 "reduction is used outside the loop"); 5379 DEBUG(dbgs() << "LV: Found an unidentified PHI." << *Phi << "\n"); 5380 return false; 5381 } // end of PHI handling 5382 5383 // We handle calls that: 5384 // * Are debug info intrinsics. 5385 // * Have a mapping to an IR intrinsic. 5386 // * Have a vector version available. 5387 auto *CI = dyn_cast<CallInst>(&I); 5388 if (CI && !getVectorIntrinsicIDForCall(CI, TLI) && 5389 !isa<DbgInfoIntrinsic>(CI) && 5390 !(CI->getCalledFunction() && TLI && 5391 TLI->isFunctionVectorizable(CI->getCalledFunction()->getName()))) { 5392 ORE->emit(createMissedAnalysis("CantVectorizeCall", CI) 5393 << "call instruction cannot be vectorized"); 5394 DEBUG(dbgs() << "LV: Found a non-intrinsic, non-libfunc callsite.\n"); 5395 return false; 5396 } 5397 5398 // Intrinsics such as powi,cttz and ctlz are legal to vectorize if the 5399 // second argument is the same (i.e. loop invariant) 5400 if (CI && hasVectorInstrinsicScalarOpd( 5401 getVectorIntrinsicIDForCall(CI, TLI), 1)) { 5402 auto *SE = PSE.getSE(); 5403 if (!SE->isLoopInvariant(PSE.getSCEV(CI->getOperand(1)), TheLoop)) { 5404 ORE->emit(createMissedAnalysis("CantVectorizeIntrinsic", CI) 5405 << "intrinsic instruction cannot be vectorized"); 5406 DEBUG(dbgs() << "LV: Found unvectorizable intrinsic " << *CI << "\n"); 5407 return false; 5408 } 5409 } 5410 5411 // Check that the instruction return type is vectorizable. 5412 // Also, we can't vectorize extractelement instructions. 5413 if ((!VectorType::isValidElementType(I.getType()) && 5414 !I.getType()->isVoidTy()) || 5415 isa<ExtractElementInst>(I)) { 5416 ORE->emit(createMissedAnalysis("CantVectorizeInstructionReturnType", &I) 5417 << "instruction return type cannot be vectorized"); 5418 DEBUG(dbgs() << "LV: Found unvectorizable type.\n"); 5419 return false; 5420 } 5421 5422 // Check that the stored type is vectorizable. 5423 if (auto *ST = dyn_cast<StoreInst>(&I)) { 5424 Type *T = ST->getValueOperand()->getType(); 5425 if (!VectorType::isValidElementType(T)) { 5426 ORE->emit(createMissedAnalysis("CantVectorizeStore", ST) 5427 << "store instruction cannot be vectorized"); 5428 return false; 5429 } 5430 5431 // FP instructions can allow unsafe algebra, thus vectorizable by 5432 // non-IEEE-754 compliant SIMD units. 5433 // This applies to floating-point math operations and calls, not memory 5434 // operations, shuffles, or casts, as they don't change precision or 5435 // semantics. 5436 } else if (I.getType()->isFloatingPointTy() && (CI || I.isBinaryOp()) && 5437 !I.hasUnsafeAlgebra()) { 5438 DEBUG(dbgs() << "LV: Found FP op with unsafe algebra.\n"); 5439 Hints->setPotentiallyUnsafe(); 5440 } 5441 5442 // Reduction instructions are allowed to have exit users. 5443 // All other instructions must not have external users. 5444 if (hasOutsideLoopUser(TheLoop, &I, AllowedExit)) { 5445 ORE->emit(createMissedAnalysis("ValueUsedOutsideLoop", &I) 5446 << "value cannot be used outside the loop"); 5447 return false; 5448 } 5449 5450 } // next instr. 5451 } 5452 5453 if (!PrimaryInduction) { 5454 DEBUG(dbgs() << "LV: Did not find one integer induction var.\n"); 5455 if (Inductions.empty()) { 5456 ORE->emit(createMissedAnalysis("NoInductionVariable") 5457 << "loop induction variable could not be identified"); 5458 return false; 5459 } 5460 } 5461 5462 // Now we know the widest induction type, check if our found induction 5463 // is the same size. If it's not, unset it here and InnerLoopVectorizer 5464 // will create another. 5465 if (PrimaryInduction && WidestIndTy != PrimaryInduction->getType()) 5466 PrimaryInduction = nullptr; 5467 5468 return true; 5469 } 5470 5471 void LoopVectorizationCostModel::collectLoopScalars(unsigned VF) { 5472 5473 // We should not collect Scalars more than once per VF. Right now, 5474 // this function is called from collectUniformsAndScalars(), which 5475 // already does this check. Collecting Scalars for VF=1 does not make any 5476 // sense. 5477 5478 assert(VF >= 2 && !Scalars.count(VF) && 5479 "This function should not be visited twice for the same VF"); 5480 5481 // If an instruction is uniform after vectorization, it will remain scalar. 5482 Scalars[VF].insert(Uniforms[VF].begin(), Uniforms[VF].end()); 5483 5484 // Collect the getelementptr instructions that will not be vectorized. A 5485 // getelementptr instruction is only vectorized if it is used for a legal 5486 // gather or scatter operation. 5487 for (auto *BB : TheLoop->blocks()) 5488 for (auto &I : *BB) { 5489 if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) { 5490 Scalars[VF].insert(GEP); 5491 continue; 5492 } 5493 auto *Ptr = getPointerOperand(&I); 5494 if (!Ptr) 5495 continue; 5496 auto *GEP = getGEPInstruction(Ptr); 5497 if (GEP && getWideningDecision(&I, VF) == CM_GatherScatter) 5498 Scalars[VF].erase(GEP); 5499 } 5500 5501 // An induction variable will remain scalar if all users of the induction 5502 // variable and induction variable update remain scalar. 5503 auto *Latch = TheLoop->getLoopLatch(); 5504 for (auto &Induction : *Legal->getInductionVars()) { 5505 auto *Ind = Induction.first; 5506 auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch)); 5507 5508 // Determine if all users of the induction variable are scalar after 5509 // vectorization. 5510 auto ScalarInd = all_of(Ind->users(), [&](User *U) -> bool { 5511 auto *I = cast<Instruction>(U); 5512 return I == IndUpdate || !TheLoop->contains(I) || Scalars[VF].count(I); 5513 }); 5514 if (!ScalarInd) 5515 continue; 5516 5517 // Determine if all users of the induction variable update instruction are 5518 // scalar after vectorization. 5519 auto ScalarIndUpdate = all_of(IndUpdate->users(), [&](User *U) -> bool { 5520 auto *I = cast<Instruction>(U); 5521 return I == Ind || !TheLoop->contains(I) || Scalars[VF].count(I); 5522 }); 5523 if (!ScalarIndUpdate) 5524 continue; 5525 5526 // The induction variable and its update instruction will remain scalar. 5527 Scalars[VF].insert(Ind); 5528 Scalars[VF].insert(IndUpdate); 5529 } 5530 } 5531 5532 bool LoopVectorizationLegality::isScalarWithPredication(Instruction *I) { 5533 if (!blockNeedsPredication(I->getParent())) 5534 return false; 5535 switch(I->getOpcode()) { 5536 default: 5537 break; 5538 case Instruction::Store: 5539 return !isMaskRequired(I); 5540 case Instruction::UDiv: 5541 case Instruction::SDiv: 5542 case Instruction::SRem: 5543 case Instruction::URem: 5544 return mayDivideByZero(*I); 5545 } 5546 return false; 5547 } 5548 5549 bool LoopVectorizationLegality::memoryInstructionCanBeWidened(Instruction *I, 5550 unsigned VF) { 5551 // Get and ensure we have a valid memory instruction. 5552 LoadInst *LI = dyn_cast<LoadInst>(I); 5553 StoreInst *SI = dyn_cast<StoreInst>(I); 5554 assert((LI || SI) && "Invalid memory instruction"); 5555 5556 auto *Ptr = getPointerOperand(I); 5557 5558 // In order to be widened, the pointer should be consecutive, first of all. 5559 if (!isConsecutivePtr(Ptr)) 5560 return false; 5561 5562 // If the instruction is a store located in a predicated block, it will be 5563 // scalarized. 5564 if (isScalarWithPredication(I)) 5565 return false; 5566 5567 // If the instruction's allocated size doesn't equal it's type size, it 5568 // requires padding and will be scalarized. 5569 auto &DL = I->getModule()->getDataLayout(); 5570 auto *ScalarTy = LI ? LI->getType() : SI->getValueOperand()->getType(); 5571 if (hasIrregularType(ScalarTy, DL, VF)) 5572 return false; 5573 5574 return true; 5575 } 5576 5577 void LoopVectorizationCostModel::collectLoopUniforms(unsigned VF) { 5578 5579 // We should not collect Uniforms more than once per VF. Right now, 5580 // this function is called from collectUniformsAndScalars(), which 5581 // already does this check. Collecting Uniforms for VF=1 does not make any 5582 // sense. 5583 5584 assert(VF >= 2 && !Uniforms.count(VF) && 5585 "This function should not be visited twice for the same VF"); 5586 5587 // Visit the list of Uniforms. If we'll not find any uniform value, we'll 5588 // not analyze again. Uniforms.count(VF) will return 1. 5589 Uniforms[VF].clear(); 5590 5591 // We now know that the loop is vectorizable! 5592 // Collect instructions inside the loop that will remain uniform after 5593 // vectorization. 5594 5595 // Global values, params and instructions outside of current loop are out of 5596 // scope. 5597 auto isOutOfScope = [&](Value *V) -> bool { 5598 Instruction *I = dyn_cast<Instruction>(V); 5599 return (!I || !TheLoop->contains(I)); 5600 }; 5601 5602 SetVector<Instruction *> Worklist; 5603 BasicBlock *Latch = TheLoop->getLoopLatch(); 5604 5605 // Start with the conditional branch. If the branch condition is an 5606 // instruction contained in the loop that is only used by the branch, it is 5607 // uniform. 5608 auto *Cmp = dyn_cast<Instruction>(Latch->getTerminator()->getOperand(0)); 5609 if (Cmp && TheLoop->contains(Cmp) && Cmp->hasOneUse()) { 5610 Worklist.insert(Cmp); 5611 DEBUG(dbgs() << "LV: Found uniform instruction: " << *Cmp << "\n"); 5612 } 5613 5614 // Holds consecutive and consecutive-like pointers. Consecutive-like pointers 5615 // are pointers that are treated like consecutive pointers during 5616 // vectorization. The pointer operands of interleaved accesses are an 5617 // example. 5618 SmallSetVector<Instruction *, 8> ConsecutiveLikePtrs; 5619 5620 // Holds pointer operands of instructions that are possibly non-uniform. 5621 SmallPtrSet<Instruction *, 8> PossibleNonUniformPtrs; 5622 5623 auto isUniformDecision = [&](Instruction *I, unsigned VF) { 5624 InstWidening WideningDecision = getWideningDecision(I, VF); 5625 assert(WideningDecision != CM_Unknown && 5626 "Widening decision should be ready at this moment"); 5627 5628 return (WideningDecision == CM_Widen || 5629 WideningDecision == CM_Interleave); 5630 }; 5631 // Iterate over the instructions in the loop, and collect all 5632 // consecutive-like pointer operands in ConsecutiveLikePtrs. If it's possible 5633 // that a consecutive-like pointer operand will be scalarized, we collect it 5634 // in PossibleNonUniformPtrs instead. We use two sets here because a single 5635 // getelementptr instruction can be used by both vectorized and scalarized 5636 // memory instructions. For example, if a loop loads and stores from the same 5637 // location, but the store is conditional, the store will be scalarized, and 5638 // the getelementptr won't remain uniform. 5639 for (auto *BB : TheLoop->blocks()) 5640 for (auto &I : *BB) { 5641 5642 // If there's no pointer operand, there's nothing to do. 5643 auto *Ptr = dyn_cast_or_null<Instruction>(getPointerOperand(&I)); 5644 if (!Ptr) 5645 continue; 5646 5647 // True if all users of Ptr are memory accesses that have Ptr as their 5648 // pointer operand. 5649 auto UsersAreMemAccesses = all_of(Ptr->users(), [&](User *U) -> bool { 5650 return getPointerOperand(U) == Ptr; 5651 }); 5652 5653 // Ensure the memory instruction will not be scalarized or used by 5654 // gather/scatter, making its pointer operand non-uniform. If the pointer 5655 // operand is used by any instruction other than a memory access, we 5656 // conservatively assume the pointer operand may be non-uniform. 5657 if (!UsersAreMemAccesses || !isUniformDecision(&I, VF)) 5658 PossibleNonUniformPtrs.insert(Ptr); 5659 5660 // If the memory instruction will be vectorized and its pointer operand 5661 // is consecutive-like, or interleaving - the pointer operand should 5662 // remain uniform. 5663 else 5664 ConsecutiveLikePtrs.insert(Ptr); 5665 } 5666 5667 // Add to the Worklist all consecutive and consecutive-like pointers that 5668 // aren't also identified as possibly non-uniform. 5669 for (auto *V : ConsecutiveLikePtrs) 5670 if (!PossibleNonUniformPtrs.count(V)) { 5671 DEBUG(dbgs() << "LV: Found uniform instruction: " << *V << "\n"); 5672 Worklist.insert(V); 5673 } 5674 5675 // Expand Worklist in topological order: whenever a new instruction 5676 // is added , its users should be either already inside Worklist, or 5677 // out of scope. It ensures a uniform instruction will only be used 5678 // by uniform instructions or out of scope instructions. 5679 unsigned idx = 0; 5680 while (idx != Worklist.size()) { 5681 Instruction *I = Worklist[idx++]; 5682 5683 for (auto OV : I->operand_values()) { 5684 if (isOutOfScope(OV)) 5685 continue; 5686 auto *OI = cast<Instruction>(OV); 5687 if (all_of(OI->users(), [&](User *U) -> bool { 5688 auto *J = cast<Instruction>(U); 5689 return !TheLoop->contains(J) || Worklist.count(J) || 5690 (OI == getPointerOperand(J) && isUniformDecision(J, VF)); 5691 })) { 5692 Worklist.insert(OI); 5693 DEBUG(dbgs() << "LV: Found uniform instruction: " << *OI << "\n"); 5694 } 5695 } 5696 } 5697 5698 // Returns true if Ptr is the pointer operand of a memory access instruction 5699 // I, and I is known to not require scalarization. 5700 auto isVectorizedMemAccessUse = [&](Instruction *I, Value *Ptr) -> bool { 5701 return getPointerOperand(I) == Ptr && isUniformDecision(I, VF); 5702 }; 5703 5704 // For an instruction to be added into Worklist above, all its users inside 5705 // the loop should also be in Worklist. However, this condition cannot be 5706 // true for phi nodes that form a cyclic dependence. We must process phi 5707 // nodes separately. An induction variable will remain uniform if all users 5708 // of the induction variable and induction variable update remain uniform. 5709 // The code below handles both pointer and non-pointer induction variables. 5710 for (auto &Induction : *Legal->getInductionVars()) { 5711 auto *Ind = Induction.first; 5712 auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch)); 5713 5714 // Determine if all users of the induction variable are uniform after 5715 // vectorization. 5716 auto UniformInd = all_of(Ind->users(), [&](User *U) -> bool { 5717 auto *I = cast<Instruction>(U); 5718 return I == IndUpdate || !TheLoop->contains(I) || Worklist.count(I) || 5719 isVectorizedMemAccessUse(I, Ind); 5720 }); 5721 if (!UniformInd) 5722 continue; 5723 5724 // Determine if all users of the induction variable update instruction are 5725 // uniform after vectorization. 5726 auto UniformIndUpdate = all_of(IndUpdate->users(), [&](User *U) -> bool { 5727 auto *I = cast<Instruction>(U); 5728 return I == Ind || !TheLoop->contains(I) || Worklist.count(I) || 5729 isVectorizedMemAccessUse(I, IndUpdate); 5730 }); 5731 if (!UniformIndUpdate) 5732 continue; 5733 5734 // The induction variable and its update instruction will remain uniform. 5735 Worklist.insert(Ind); 5736 Worklist.insert(IndUpdate); 5737 DEBUG(dbgs() << "LV: Found uniform instruction: " << *Ind << "\n"); 5738 DEBUG(dbgs() << "LV: Found uniform instruction: " << *IndUpdate << "\n"); 5739 } 5740 5741 Uniforms[VF].insert(Worklist.begin(), Worklist.end()); 5742 } 5743 5744 bool LoopVectorizationLegality::canVectorizeMemory() { 5745 LAI = &(*GetLAA)(*TheLoop); 5746 InterleaveInfo.setLAI(LAI); 5747 const OptimizationRemarkAnalysis *LAR = LAI->getReport(); 5748 if (LAR) { 5749 OptimizationRemarkAnalysis VR(Hints->vectorizeAnalysisPassName(), 5750 "loop not vectorized: ", *LAR); 5751 ORE->emit(VR); 5752 } 5753 if (!LAI->canVectorizeMemory()) 5754 return false; 5755 5756 if (LAI->hasStoreToLoopInvariantAddress()) { 5757 ORE->emit(createMissedAnalysis("CantVectorizeStoreToLoopInvariantAddress") 5758 << "write to a loop invariant address could not be vectorized"); 5759 DEBUG(dbgs() << "LV: We don't allow storing to uniform addresses\n"); 5760 return false; 5761 } 5762 5763 Requirements->addRuntimePointerChecks(LAI->getNumRuntimePointerChecks()); 5764 PSE.addPredicate(LAI->getPSE().getUnionPredicate()); 5765 5766 return true; 5767 } 5768 5769 bool LoopVectorizationLegality::isInductionVariable(const Value *V) { 5770 Value *In0 = const_cast<Value *>(V); 5771 PHINode *PN = dyn_cast_or_null<PHINode>(In0); 5772 if (!PN) 5773 return false; 5774 5775 return Inductions.count(PN); 5776 } 5777 5778 bool LoopVectorizationLegality::isFirstOrderRecurrence(const PHINode *Phi) { 5779 return FirstOrderRecurrences.count(Phi); 5780 } 5781 5782 bool LoopVectorizationLegality::blockNeedsPredication(BasicBlock *BB) { 5783 return LoopAccessInfo::blockNeedsPredication(BB, TheLoop, DT); 5784 } 5785 5786 bool LoopVectorizationLegality::blockCanBePredicated( 5787 BasicBlock *BB, SmallPtrSetImpl<Value *> &SafePtrs) { 5788 const bool IsAnnotatedParallel = TheLoop->isAnnotatedParallel(); 5789 5790 for (Instruction &I : *BB) { 5791 // Check that we don't have a constant expression that can trap as operand. 5792 for (Value *Operand : I.operands()) { 5793 if (auto *C = dyn_cast<Constant>(Operand)) 5794 if (C->canTrap()) 5795 return false; 5796 } 5797 // We might be able to hoist the load. 5798 if (I.mayReadFromMemory()) { 5799 auto *LI = dyn_cast<LoadInst>(&I); 5800 if (!LI) 5801 return false; 5802 if (!SafePtrs.count(LI->getPointerOperand())) { 5803 if (isLegalMaskedLoad(LI->getType(), LI->getPointerOperand()) || 5804 isLegalMaskedGather(LI->getType())) { 5805 MaskedOp.insert(LI); 5806 continue; 5807 } 5808 // !llvm.mem.parallel_loop_access implies if-conversion safety. 5809 if (IsAnnotatedParallel) 5810 continue; 5811 return false; 5812 } 5813 } 5814 5815 if (I.mayWriteToMemory()) { 5816 auto *SI = dyn_cast<StoreInst>(&I); 5817 // We only support predication of stores in basic blocks with one 5818 // predecessor. 5819 if (!SI) 5820 return false; 5821 5822 // Build a masked store if it is legal for the target. 5823 if (isLegalMaskedStore(SI->getValueOperand()->getType(), 5824 SI->getPointerOperand()) || 5825 isLegalMaskedScatter(SI->getValueOperand()->getType())) { 5826 MaskedOp.insert(SI); 5827 continue; 5828 } 5829 5830 bool isSafePtr = (SafePtrs.count(SI->getPointerOperand()) != 0); 5831 bool isSinglePredecessor = SI->getParent()->getSinglePredecessor(); 5832 5833 if (++NumPredStores > NumberOfStoresToPredicate || !isSafePtr || 5834 !isSinglePredecessor) 5835 return false; 5836 } 5837 if (I.mayThrow()) 5838 return false; 5839 } 5840 5841 return true; 5842 } 5843 5844 void InterleavedAccessInfo::collectConstStrideAccesses( 5845 MapVector<Instruction *, StrideDescriptor> &AccessStrideInfo, 5846 const ValueToValueMap &Strides) { 5847 5848 auto &DL = TheLoop->getHeader()->getModule()->getDataLayout(); 5849 5850 // Since it's desired that the load/store instructions be maintained in 5851 // "program order" for the interleaved access analysis, we have to visit the 5852 // blocks in the loop in reverse postorder (i.e., in a topological order). 5853 // Such an ordering will ensure that any load/store that may be executed 5854 // before a second load/store will precede the second load/store in 5855 // AccessStrideInfo. 5856 LoopBlocksDFS DFS(TheLoop); 5857 DFS.perform(LI); 5858 for (BasicBlock *BB : make_range(DFS.beginRPO(), DFS.endRPO())) 5859 for (auto &I : *BB) { 5860 auto *LI = dyn_cast<LoadInst>(&I); 5861 auto *SI = dyn_cast<StoreInst>(&I); 5862 if (!LI && !SI) 5863 continue; 5864 5865 Value *Ptr = getPointerOperand(&I); 5866 // We don't check wrapping here because we don't know yet if Ptr will be 5867 // part of a full group or a group with gaps. Checking wrapping for all 5868 // pointers (even those that end up in groups with no gaps) will be overly 5869 // conservative. For full groups, wrapping should be ok since if we would 5870 // wrap around the address space we would do a memory access at nullptr 5871 // even without the transformation. The wrapping checks are therefore 5872 // deferred until after we've formed the interleaved groups. 5873 int64_t Stride = getPtrStride(PSE, Ptr, TheLoop, Strides, 5874 /*Assume=*/true, /*ShouldCheckWrap=*/false); 5875 5876 const SCEV *Scev = replaceSymbolicStrideSCEV(PSE, Strides, Ptr); 5877 PointerType *PtrTy = dyn_cast<PointerType>(Ptr->getType()); 5878 uint64_t Size = DL.getTypeAllocSize(PtrTy->getElementType()); 5879 5880 // An alignment of 0 means target ABI alignment. 5881 unsigned Align = getMemInstAlignment(&I); 5882 if (!Align) 5883 Align = DL.getABITypeAlignment(PtrTy->getElementType()); 5884 5885 AccessStrideInfo[&I] = StrideDescriptor(Stride, Scev, Size, Align); 5886 } 5887 } 5888 5889 // Analyze interleaved accesses and collect them into interleaved load and 5890 // store groups. 5891 // 5892 // When generating code for an interleaved load group, we effectively hoist all 5893 // loads in the group to the location of the first load in program order. When 5894 // generating code for an interleaved store group, we sink all stores to the 5895 // location of the last store. This code motion can change the order of load 5896 // and store instructions and may break dependences. 5897 // 5898 // The code generation strategy mentioned above ensures that we won't violate 5899 // any write-after-read (WAR) dependences. 5900 // 5901 // E.g., for the WAR dependence: a = A[i]; // (1) 5902 // A[i] = b; // (2) 5903 // 5904 // The store group of (2) is always inserted at or below (2), and the load 5905 // group of (1) is always inserted at or above (1). Thus, the instructions will 5906 // never be reordered. All other dependences are checked to ensure the 5907 // correctness of the instruction reordering. 5908 // 5909 // The algorithm visits all memory accesses in the loop in bottom-up program 5910 // order. Program order is established by traversing the blocks in the loop in 5911 // reverse postorder when collecting the accesses. 5912 // 5913 // We visit the memory accesses in bottom-up order because it can simplify the 5914 // construction of store groups in the presence of write-after-write (WAW) 5915 // dependences. 5916 // 5917 // E.g., for the WAW dependence: A[i] = a; // (1) 5918 // A[i] = b; // (2) 5919 // A[i + 1] = c; // (3) 5920 // 5921 // We will first create a store group with (3) and (2). (1) can't be added to 5922 // this group because it and (2) are dependent. However, (1) can be grouped 5923 // with other accesses that may precede it in program order. Note that a 5924 // bottom-up order does not imply that WAW dependences should not be checked. 5925 void InterleavedAccessInfo::analyzeInterleaving( 5926 const ValueToValueMap &Strides) { 5927 DEBUG(dbgs() << "LV: Analyzing interleaved accesses...\n"); 5928 5929 // Holds all accesses with a constant stride. 5930 MapVector<Instruction *, StrideDescriptor> AccessStrideInfo; 5931 collectConstStrideAccesses(AccessStrideInfo, Strides); 5932 5933 if (AccessStrideInfo.empty()) 5934 return; 5935 5936 // Collect the dependences in the loop. 5937 collectDependences(); 5938 5939 // Holds all interleaved store groups temporarily. 5940 SmallSetVector<InterleaveGroup *, 4> StoreGroups; 5941 // Holds all interleaved load groups temporarily. 5942 SmallSetVector<InterleaveGroup *, 4> LoadGroups; 5943 5944 // Search in bottom-up program order for pairs of accesses (A and B) that can 5945 // form interleaved load or store groups. In the algorithm below, access A 5946 // precedes access B in program order. We initialize a group for B in the 5947 // outer loop of the algorithm, and then in the inner loop, we attempt to 5948 // insert each A into B's group if: 5949 // 5950 // 1. A and B have the same stride, 5951 // 2. A and B have the same memory object size, and 5952 // 3. A belongs in B's group according to its distance from B. 5953 // 5954 // Special care is taken to ensure group formation will not break any 5955 // dependences. 5956 for (auto BI = AccessStrideInfo.rbegin(), E = AccessStrideInfo.rend(); 5957 BI != E; ++BI) { 5958 Instruction *B = BI->first; 5959 StrideDescriptor DesB = BI->second; 5960 5961 // Initialize a group for B if it has an allowable stride. Even if we don't 5962 // create a group for B, we continue with the bottom-up algorithm to ensure 5963 // we don't break any of B's dependences. 5964 InterleaveGroup *Group = nullptr; 5965 if (isStrided(DesB.Stride)) { 5966 Group = getInterleaveGroup(B); 5967 if (!Group) { 5968 DEBUG(dbgs() << "LV: Creating an interleave group with:" << *B << '\n'); 5969 Group = createInterleaveGroup(B, DesB.Stride, DesB.Align); 5970 } 5971 if (B->mayWriteToMemory()) 5972 StoreGroups.insert(Group); 5973 else 5974 LoadGroups.insert(Group); 5975 } 5976 5977 for (auto AI = std::next(BI); AI != E; ++AI) { 5978 Instruction *A = AI->first; 5979 StrideDescriptor DesA = AI->second; 5980 5981 // Our code motion strategy implies that we can't have dependences 5982 // between accesses in an interleaved group and other accesses located 5983 // between the first and last member of the group. Note that this also 5984 // means that a group can't have more than one member at a given offset. 5985 // The accesses in a group can have dependences with other accesses, but 5986 // we must ensure we don't extend the boundaries of the group such that 5987 // we encompass those dependent accesses. 5988 // 5989 // For example, assume we have the sequence of accesses shown below in a 5990 // stride-2 loop: 5991 // 5992 // (1, 2) is a group | A[i] = a; // (1) 5993 // | A[i-1] = b; // (2) | 5994 // A[i-3] = c; // (3) 5995 // A[i] = d; // (4) | (2, 4) is not a group 5996 // 5997 // Because accesses (2) and (3) are dependent, we can group (2) with (1) 5998 // but not with (4). If we did, the dependent access (3) would be within 5999 // the boundaries of the (2, 4) group. 6000 if (!canReorderMemAccessesForInterleavedGroups(&*AI, &*BI)) { 6001 6002 // If a dependence exists and A is already in a group, we know that A 6003 // must be a store since A precedes B and WAR dependences are allowed. 6004 // Thus, A would be sunk below B. We release A's group to prevent this 6005 // illegal code motion. A will then be free to form another group with 6006 // instructions that precede it. 6007 if (isInterleaved(A)) { 6008 InterleaveGroup *StoreGroup = getInterleaveGroup(A); 6009 StoreGroups.remove(StoreGroup); 6010 releaseGroup(StoreGroup); 6011 } 6012 6013 // If a dependence exists and A is not already in a group (or it was 6014 // and we just released it), B might be hoisted above A (if B is a 6015 // load) or another store might be sunk below A (if B is a store). In 6016 // either case, we can't add additional instructions to B's group. B 6017 // will only form a group with instructions that it precedes. 6018 break; 6019 } 6020 6021 // At this point, we've checked for illegal code motion. If either A or B 6022 // isn't strided, there's nothing left to do. 6023 if (!isStrided(DesA.Stride) || !isStrided(DesB.Stride)) 6024 continue; 6025 6026 // Ignore A if it's already in a group or isn't the same kind of memory 6027 // operation as B. 6028 if (isInterleaved(A) || A->mayReadFromMemory() != B->mayReadFromMemory()) 6029 continue; 6030 6031 // Check rules 1 and 2. Ignore A if its stride or size is different from 6032 // that of B. 6033 if (DesA.Stride != DesB.Stride || DesA.Size != DesB.Size) 6034 continue; 6035 6036 // Ignore A if the memory object of A and B don't belong to the same 6037 // address space 6038 if (getMemInstAddressSpace(A) != getMemInstAddressSpace(B)) 6039 continue; 6040 6041 // Calculate the distance from A to B. 6042 const SCEVConstant *DistToB = dyn_cast<SCEVConstant>( 6043 PSE.getSE()->getMinusSCEV(DesA.Scev, DesB.Scev)); 6044 if (!DistToB) 6045 continue; 6046 int64_t DistanceToB = DistToB->getAPInt().getSExtValue(); 6047 6048 // Check rule 3. Ignore A if its distance to B is not a multiple of the 6049 // size. 6050 if (DistanceToB % static_cast<int64_t>(DesB.Size)) 6051 continue; 6052 6053 // Ignore A if either A or B is in a predicated block. Although we 6054 // currently prevent group formation for predicated accesses, we may be 6055 // able to relax this limitation in the future once we handle more 6056 // complicated blocks. 6057 if (isPredicated(A->getParent()) || isPredicated(B->getParent())) 6058 continue; 6059 6060 // The index of A is the index of B plus A's distance to B in multiples 6061 // of the size. 6062 int IndexA = 6063 Group->getIndex(B) + DistanceToB / static_cast<int64_t>(DesB.Size); 6064 6065 // Try to insert A into B's group. 6066 if (Group->insertMember(A, IndexA, DesA.Align)) { 6067 DEBUG(dbgs() << "LV: Inserted:" << *A << '\n' 6068 << " into the interleave group with" << *B << '\n'); 6069 InterleaveGroupMap[A] = Group; 6070 6071 // Set the first load in program order as the insert position. 6072 if (A->mayReadFromMemory()) 6073 Group->setInsertPos(A); 6074 } 6075 } // Iteration over A accesses. 6076 } // Iteration over B accesses. 6077 6078 // Remove interleaved store groups with gaps. 6079 for (InterleaveGroup *Group : StoreGroups) 6080 if (Group->getNumMembers() != Group->getFactor()) 6081 releaseGroup(Group); 6082 6083 // Remove interleaved groups with gaps (currently only loads) whose memory 6084 // accesses may wrap around. We have to revisit the getPtrStride analysis, 6085 // this time with ShouldCheckWrap=true, since collectConstStrideAccesses does 6086 // not check wrapping (see documentation there). 6087 // FORNOW we use Assume=false; 6088 // TODO: Change to Assume=true but making sure we don't exceed the threshold 6089 // of runtime SCEV assumptions checks (thereby potentially failing to 6090 // vectorize altogether). 6091 // Additional optional optimizations: 6092 // TODO: If we are peeling the loop and we know that the first pointer doesn't 6093 // wrap then we can deduce that all pointers in the group don't wrap. 6094 // This means that we can forcefully peel the loop in order to only have to 6095 // check the first pointer for no-wrap. When we'll change to use Assume=true 6096 // we'll only need at most one runtime check per interleaved group. 6097 // 6098 for (InterleaveGroup *Group : LoadGroups) { 6099 6100 // Case 1: A full group. Can Skip the checks; For full groups, if the wide 6101 // load would wrap around the address space we would do a memory access at 6102 // nullptr even without the transformation. 6103 if (Group->getNumMembers() == Group->getFactor()) 6104 continue; 6105 6106 // Case 2: If first and last members of the group don't wrap this implies 6107 // that all the pointers in the group don't wrap. 6108 // So we check only group member 0 (which is always guaranteed to exist), 6109 // and group member Factor - 1; If the latter doesn't exist we rely on 6110 // peeling (if it is a non-reveresed accsess -- see Case 3). 6111 Value *FirstMemberPtr = getPointerOperand(Group->getMember(0)); 6112 if (!getPtrStride(PSE, FirstMemberPtr, TheLoop, Strides, /*Assume=*/false, 6113 /*ShouldCheckWrap=*/true)) { 6114 DEBUG(dbgs() << "LV: Invalidate candidate interleaved group due to " 6115 "first group member potentially pointer-wrapping.\n"); 6116 releaseGroup(Group); 6117 continue; 6118 } 6119 Instruction *LastMember = Group->getMember(Group->getFactor() - 1); 6120 if (LastMember) { 6121 Value *LastMemberPtr = getPointerOperand(LastMember); 6122 if (!getPtrStride(PSE, LastMemberPtr, TheLoop, Strides, /*Assume=*/false, 6123 /*ShouldCheckWrap=*/true)) { 6124 DEBUG(dbgs() << "LV: Invalidate candidate interleaved group due to " 6125 "last group member potentially pointer-wrapping.\n"); 6126 releaseGroup(Group); 6127 } 6128 } else { 6129 // Case 3: A non-reversed interleaved load group with gaps: We need 6130 // to execute at least one scalar epilogue iteration. This will ensure 6131 // we don't speculatively access memory out-of-bounds. We only need 6132 // to look for a member at index factor - 1, since every group must have 6133 // a member at index zero. 6134 if (Group->isReverse()) { 6135 releaseGroup(Group); 6136 continue; 6137 } 6138 DEBUG(dbgs() << "LV: Interleaved group requires epilogue iteration.\n"); 6139 RequiresScalarEpilogue = true; 6140 } 6141 } 6142 } 6143 6144 Optional<unsigned> LoopVectorizationCostModel::computeMaxVF(bool OptForSize) { 6145 if (!EnableCondStoresVectorization && Legal->getNumPredStores()) { 6146 ORE->emit(createMissedAnalysis("ConditionalStore") 6147 << "store that is conditionally executed prevents vectorization"); 6148 DEBUG(dbgs() << "LV: No vectorization. There are conditional stores.\n"); 6149 return None; 6150 } 6151 6152 if (!OptForSize) // Remaining checks deal with scalar loop when OptForSize. 6153 return computeFeasibleMaxVF(OptForSize); 6154 6155 if (Legal->getRuntimePointerChecking()->Need) { 6156 ORE->emit(createMissedAnalysis("CantVersionLoopWithOptForSize") 6157 << "runtime pointer checks needed. Enable vectorization of this " 6158 "loop with '#pragma clang loop vectorize(enable)' when " 6159 "compiling with -Os/-Oz"); 6160 DEBUG(dbgs() 6161 << "LV: Aborting. Runtime ptr check is required with -Os/-Oz.\n"); 6162 return None; 6163 } 6164 6165 // If we optimize the program for size, avoid creating the tail loop. 6166 unsigned TC = PSE.getSE()->getSmallConstantTripCount(TheLoop); 6167 DEBUG(dbgs() << "LV: Found trip count: " << TC << '\n'); 6168 6169 // If we don't know the precise trip count, don't try to vectorize. 6170 if (TC < 2) { 6171 ORE->emit( 6172 createMissedAnalysis("UnknownLoopCountComplexCFG") 6173 << "unable to calculate the loop count due to complex control flow"); 6174 DEBUG(dbgs() << "LV: Aborting. A tail loop is required with -Os/-Oz.\n"); 6175 return None; 6176 } 6177 6178 unsigned MaxVF = computeFeasibleMaxVF(OptForSize); 6179 6180 if (TC % MaxVF != 0) { 6181 // If the trip count that we found modulo the vectorization factor is not 6182 // zero then we require a tail. 6183 // FIXME: look for a smaller MaxVF that does divide TC rather than give up. 6184 // FIXME: return None if loop requiresScalarEpilog(<MaxVF>), or look for a 6185 // smaller MaxVF that does not require a scalar epilog. 6186 6187 ORE->emit(createMissedAnalysis("NoTailLoopWithOptForSize") 6188 << "cannot optimize for size and vectorize at the " 6189 "same time. Enable vectorization of this loop " 6190 "with '#pragma clang loop vectorize(enable)' " 6191 "when compiling with -Os/-Oz"); 6192 DEBUG(dbgs() << "LV: Aborting. A tail loop is required with -Os/-Oz.\n"); 6193 return None; 6194 } 6195 6196 return MaxVF; 6197 } 6198 6199 unsigned LoopVectorizationCostModel::computeFeasibleMaxVF(bool OptForSize) { 6200 MinBWs = computeMinimumValueSizes(TheLoop->getBlocks(), *DB, &TTI); 6201 unsigned SmallestType, WidestType; 6202 std::tie(SmallestType, WidestType) = getSmallestAndWidestTypes(); 6203 unsigned WidestRegister = TTI.getRegisterBitWidth(true); 6204 unsigned MaxSafeDepDist = -1U; 6205 6206 // Get the maximum safe dependence distance in bits computed by LAA. If the 6207 // loop contains any interleaved accesses, we divide the dependence distance 6208 // by the maximum interleave factor of all interleaved groups. Note that 6209 // although the division ensures correctness, this is a fairly conservative 6210 // computation because the maximum distance computed by LAA may not involve 6211 // any of the interleaved accesses. 6212 if (Legal->getMaxSafeDepDistBytes() != -1U) 6213 MaxSafeDepDist = 6214 Legal->getMaxSafeDepDistBytes() * 8 / Legal->getMaxInterleaveFactor(); 6215 6216 WidestRegister = 6217 ((WidestRegister < MaxSafeDepDist) ? WidestRegister : MaxSafeDepDist); 6218 unsigned MaxVectorSize = WidestRegister / WidestType; 6219 6220 DEBUG(dbgs() << "LV: The Smallest and Widest types: " << SmallestType << " / " 6221 << WidestType << " bits.\n"); 6222 DEBUG(dbgs() << "LV: The Widest register is: " << WidestRegister 6223 << " bits.\n"); 6224 6225 if (MaxVectorSize == 0) { 6226 DEBUG(dbgs() << "LV: The target has no vector registers.\n"); 6227 MaxVectorSize = 1; 6228 } 6229 6230 assert(MaxVectorSize <= 64 && "Did not expect to pack so many elements" 6231 " into one vector!"); 6232 6233 unsigned MaxVF = MaxVectorSize; 6234 if (MaximizeBandwidth && !OptForSize) { 6235 // Collect all viable vectorization factors. 6236 SmallVector<unsigned, 8> VFs; 6237 unsigned NewMaxVectorSize = WidestRegister / SmallestType; 6238 for (unsigned VS = MaxVectorSize; VS <= NewMaxVectorSize; VS *= 2) 6239 VFs.push_back(VS); 6240 6241 // For each VF calculate its register usage. 6242 auto RUs = calculateRegisterUsage(VFs); 6243 6244 // Select the largest VF which doesn't require more registers than existing 6245 // ones. 6246 unsigned TargetNumRegisters = TTI.getNumberOfRegisters(true); 6247 for (int i = RUs.size() - 1; i >= 0; --i) { 6248 if (RUs[i].MaxLocalUsers <= TargetNumRegisters) { 6249 MaxVF = VFs[i]; 6250 break; 6251 } 6252 } 6253 } 6254 return MaxVF; 6255 } 6256 6257 LoopVectorizationCostModel::VectorizationFactor 6258 LoopVectorizationCostModel::selectVectorizationFactor(unsigned MaxVF) { 6259 float Cost = expectedCost(1).first; 6260 #ifndef NDEBUG 6261 const float ScalarCost = Cost; 6262 #endif /* NDEBUG */ 6263 unsigned Width = 1; 6264 DEBUG(dbgs() << "LV: Scalar loop costs: " << (int)ScalarCost << ".\n"); 6265 6266 bool ForceVectorization = Hints->getForce() == LoopVectorizeHints::FK_Enabled; 6267 // Ignore scalar width, because the user explicitly wants vectorization. 6268 if (ForceVectorization && MaxVF > 1) { 6269 Width = 2; 6270 Cost = expectedCost(Width).first / (float)Width; 6271 } 6272 6273 for (unsigned i = 2; i <= MaxVF; i *= 2) { 6274 // Notice that the vector loop needs to be executed less times, so 6275 // we need to divide the cost of the vector loops by the width of 6276 // the vector elements. 6277 VectorizationCostTy C = expectedCost(i); 6278 float VectorCost = C.first / (float)i; 6279 DEBUG(dbgs() << "LV: Vector loop of width " << i 6280 << " costs: " << (int)VectorCost << ".\n"); 6281 if (!C.second && !ForceVectorization) { 6282 DEBUG( 6283 dbgs() << "LV: Not considering vector loop of width " << i 6284 << " because it will not generate any vector instructions.\n"); 6285 continue; 6286 } 6287 if (VectorCost < Cost) { 6288 Cost = VectorCost; 6289 Width = i; 6290 } 6291 } 6292 6293 DEBUG(if (ForceVectorization && Width > 1 && Cost >= ScalarCost) dbgs() 6294 << "LV: Vectorization seems to be not beneficial, " 6295 << "but was forced by a user.\n"); 6296 DEBUG(dbgs() << "LV: Selecting VF: " << Width << ".\n"); 6297 VectorizationFactor Factor = {Width, (unsigned)(Width * Cost)}; 6298 return Factor; 6299 } 6300 6301 std::pair<unsigned, unsigned> 6302 LoopVectorizationCostModel::getSmallestAndWidestTypes() { 6303 unsigned MinWidth = -1U; 6304 unsigned MaxWidth = 8; 6305 const DataLayout &DL = TheFunction->getParent()->getDataLayout(); 6306 6307 // For each block. 6308 for (BasicBlock *BB : TheLoop->blocks()) { 6309 // For each instruction in the loop. 6310 for (Instruction &I : *BB) { 6311 Type *T = I.getType(); 6312 6313 // Skip ignored values. 6314 if (ValuesToIgnore.count(&I)) 6315 continue; 6316 6317 // Only examine Loads, Stores and PHINodes. 6318 if (!isa<LoadInst>(I) && !isa<StoreInst>(I) && !isa<PHINode>(I)) 6319 continue; 6320 6321 // Examine PHI nodes that are reduction variables. Update the type to 6322 // account for the recurrence type. 6323 if (auto *PN = dyn_cast<PHINode>(&I)) { 6324 if (!Legal->isReductionVariable(PN)) 6325 continue; 6326 RecurrenceDescriptor RdxDesc = (*Legal->getReductionVars())[PN]; 6327 T = RdxDesc.getRecurrenceType(); 6328 } 6329 6330 // Examine the stored values. 6331 if (auto *ST = dyn_cast<StoreInst>(&I)) 6332 T = ST->getValueOperand()->getType(); 6333 6334 // Ignore loaded pointer types and stored pointer types that are not 6335 // vectorizable. 6336 // 6337 // FIXME: The check here attempts to predict whether a load or store will 6338 // be vectorized. We only know this for certain after a VF has 6339 // been selected. Here, we assume that if an access can be 6340 // vectorized, it will be. We should also look at extending this 6341 // optimization to non-pointer types. 6342 // 6343 if (T->isPointerTy() && !isConsecutiveLoadOrStore(&I) && 6344 !Legal->isAccessInterleaved(&I) && !Legal->isLegalGatherOrScatter(&I)) 6345 continue; 6346 6347 MinWidth = std::min(MinWidth, 6348 (unsigned)DL.getTypeSizeInBits(T->getScalarType())); 6349 MaxWidth = std::max(MaxWidth, 6350 (unsigned)DL.getTypeSizeInBits(T->getScalarType())); 6351 } 6352 } 6353 6354 return {MinWidth, MaxWidth}; 6355 } 6356 6357 unsigned LoopVectorizationCostModel::selectInterleaveCount(bool OptForSize, 6358 unsigned VF, 6359 unsigned LoopCost) { 6360 6361 // -- The interleave heuristics -- 6362 // We interleave the loop in order to expose ILP and reduce the loop overhead. 6363 // There are many micro-architectural considerations that we can't predict 6364 // at this level. For example, frontend pressure (on decode or fetch) due to 6365 // code size, or the number and capabilities of the execution ports. 6366 // 6367 // We use the following heuristics to select the interleave count: 6368 // 1. If the code has reductions, then we interleave to break the cross 6369 // iteration dependency. 6370 // 2. If the loop is really small, then we interleave to reduce the loop 6371 // overhead. 6372 // 3. We don't interleave if we think that we will spill registers to memory 6373 // due to the increased register pressure. 6374 6375 // When we optimize for size, we don't interleave. 6376 if (OptForSize) 6377 return 1; 6378 6379 // We used the distance for the interleave count. 6380 if (Legal->getMaxSafeDepDistBytes() != -1U) 6381 return 1; 6382 6383 // Do not interleave loops with a relatively small trip count. 6384 unsigned TC = PSE.getSE()->getSmallConstantTripCount(TheLoop); 6385 if (TC > 1 && TC < TinyTripCountInterleaveThreshold) 6386 return 1; 6387 6388 unsigned TargetNumRegisters = TTI.getNumberOfRegisters(VF > 1); 6389 DEBUG(dbgs() << "LV: The target has " << TargetNumRegisters 6390 << " registers\n"); 6391 6392 if (VF == 1) { 6393 if (ForceTargetNumScalarRegs.getNumOccurrences() > 0) 6394 TargetNumRegisters = ForceTargetNumScalarRegs; 6395 } else { 6396 if (ForceTargetNumVectorRegs.getNumOccurrences() > 0) 6397 TargetNumRegisters = ForceTargetNumVectorRegs; 6398 } 6399 6400 RegisterUsage R = calculateRegisterUsage({VF})[0]; 6401 // We divide by these constants so assume that we have at least one 6402 // instruction that uses at least one register. 6403 R.MaxLocalUsers = std::max(R.MaxLocalUsers, 1U); 6404 R.NumInstructions = std::max(R.NumInstructions, 1U); 6405 6406 // We calculate the interleave count using the following formula. 6407 // Subtract the number of loop invariants from the number of available 6408 // registers. These registers are used by all of the interleaved instances. 6409 // Next, divide the remaining registers by the number of registers that is 6410 // required by the loop, in order to estimate how many parallel instances 6411 // fit without causing spills. All of this is rounded down if necessary to be 6412 // a power of two. We want power of two interleave count to simplify any 6413 // addressing operations or alignment considerations. 6414 unsigned IC = PowerOf2Floor((TargetNumRegisters - R.LoopInvariantRegs) / 6415 R.MaxLocalUsers); 6416 6417 // Don't count the induction variable as interleaved. 6418 if (EnableIndVarRegisterHeur) 6419 IC = PowerOf2Floor((TargetNumRegisters - R.LoopInvariantRegs - 1) / 6420 std::max(1U, (R.MaxLocalUsers - 1))); 6421 6422 // Clamp the interleave ranges to reasonable counts. 6423 unsigned MaxInterleaveCount = TTI.getMaxInterleaveFactor(VF); 6424 6425 // Check if the user has overridden the max. 6426 if (VF == 1) { 6427 if (ForceTargetMaxScalarInterleaveFactor.getNumOccurrences() > 0) 6428 MaxInterleaveCount = ForceTargetMaxScalarInterleaveFactor; 6429 } else { 6430 if (ForceTargetMaxVectorInterleaveFactor.getNumOccurrences() > 0) 6431 MaxInterleaveCount = ForceTargetMaxVectorInterleaveFactor; 6432 } 6433 6434 // If we did not calculate the cost for VF (because the user selected the VF) 6435 // then we calculate the cost of VF here. 6436 if (LoopCost == 0) 6437 LoopCost = expectedCost(VF).first; 6438 6439 // Clamp the calculated IC to be between the 1 and the max interleave count 6440 // that the target allows. 6441 if (IC > MaxInterleaveCount) 6442 IC = MaxInterleaveCount; 6443 else if (IC < 1) 6444 IC = 1; 6445 6446 // Interleave if we vectorized this loop and there is a reduction that could 6447 // benefit from interleaving. 6448 if (VF > 1 && Legal->getReductionVars()->size()) { 6449 DEBUG(dbgs() << "LV: Interleaving because of reductions.\n"); 6450 return IC; 6451 } 6452 6453 // Note that if we've already vectorized the loop we will have done the 6454 // runtime check and so interleaving won't require further checks. 6455 bool InterleavingRequiresRuntimePointerCheck = 6456 (VF == 1 && Legal->getRuntimePointerChecking()->Need); 6457 6458 // We want to interleave small loops in order to reduce the loop overhead and 6459 // potentially expose ILP opportunities. 6460 DEBUG(dbgs() << "LV: Loop cost is " << LoopCost << '\n'); 6461 if (!InterleavingRequiresRuntimePointerCheck && LoopCost < SmallLoopCost) { 6462 // We assume that the cost overhead is 1 and we use the cost model 6463 // to estimate the cost of the loop and interleave until the cost of the 6464 // loop overhead is about 5% of the cost of the loop. 6465 unsigned SmallIC = 6466 std::min(IC, (unsigned)PowerOf2Floor(SmallLoopCost / LoopCost)); 6467 6468 // Interleave until store/load ports (estimated by max interleave count) are 6469 // saturated. 6470 unsigned NumStores = Legal->getNumStores(); 6471 unsigned NumLoads = Legal->getNumLoads(); 6472 unsigned StoresIC = IC / (NumStores ? NumStores : 1); 6473 unsigned LoadsIC = IC / (NumLoads ? NumLoads : 1); 6474 6475 // If we have a scalar reduction (vector reductions are already dealt with 6476 // by this point), we can increase the critical path length if the loop 6477 // we're interleaving is inside another loop. Limit, by default to 2, so the 6478 // critical path only gets increased by one reduction operation. 6479 if (Legal->getReductionVars()->size() && TheLoop->getLoopDepth() > 1) { 6480 unsigned F = static_cast<unsigned>(MaxNestedScalarReductionIC); 6481 SmallIC = std::min(SmallIC, F); 6482 StoresIC = std::min(StoresIC, F); 6483 LoadsIC = std::min(LoadsIC, F); 6484 } 6485 6486 if (EnableLoadStoreRuntimeInterleave && 6487 std::max(StoresIC, LoadsIC) > SmallIC) { 6488 DEBUG(dbgs() << "LV: Interleaving to saturate store or load ports.\n"); 6489 return std::max(StoresIC, LoadsIC); 6490 } 6491 6492 DEBUG(dbgs() << "LV: Interleaving to reduce branch cost.\n"); 6493 return SmallIC; 6494 } 6495 6496 // Interleave if this is a large loop (small loops are already dealt with by 6497 // this point) that could benefit from interleaving. 6498 bool HasReductions = (Legal->getReductionVars()->size() > 0); 6499 if (TTI.enableAggressiveInterleaving(HasReductions)) { 6500 DEBUG(dbgs() << "LV: Interleaving to expose ILP.\n"); 6501 return IC; 6502 } 6503 6504 DEBUG(dbgs() << "LV: Not Interleaving.\n"); 6505 return 1; 6506 } 6507 6508 SmallVector<LoopVectorizationCostModel::RegisterUsage, 8> 6509 LoopVectorizationCostModel::calculateRegisterUsage(ArrayRef<unsigned> VFs) { 6510 // This function calculates the register usage by measuring the highest number 6511 // of values that are alive at a single location. Obviously, this is a very 6512 // rough estimation. We scan the loop in a topological order in order and 6513 // assign a number to each instruction. We use RPO to ensure that defs are 6514 // met before their users. We assume that each instruction that has in-loop 6515 // users starts an interval. We record every time that an in-loop value is 6516 // used, so we have a list of the first and last occurrences of each 6517 // instruction. Next, we transpose this data structure into a multi map that 6518 // holds the list of intervals that *end* at a specific location. This multi 6519 // map allows us to perform a linear search. We scan the instructions linearly 6520 // and record each time that a new interval starts, by placing it in a set. 6521 // If we find this value in the multi-map then we remove it from the set. 6522 // The max register usage is the maximum size of the set. 6523 // We also search for instructions that are defined outside the loop, but are 6524 // used inside the loop. We need this number separately from the max-interval 6525 // usage number because when we unroll, loop-invariant values do not take 6526 // more register. 6527 LoopBlocksDFS DFS(TheLoop); 6528 DFS.perform(LI); 6529 6530 RegisterUsage RU; 6531 RU.NumInstructions = 0; 6532 6533 // Each 'key' in the map opens a new interval. The values 6534 // of the map are the index of the 'last seen' usage of the 6535 // instruction that is the key. 6536 typedef DenseMap<Instruction *, unsigned> IntervalMap; 6537 // Maps instruction to its index. 6538 DenseMap<unsigned, Instruction *> IdxToInstr; 6539 // Marks the end of each interval. 6540 IntervalMap EndPoint; 6541 // Saves the list of instruction indices that are used in the loop. 6542 SmallSet<Instruction *, 8> Ends; 6543 // Saves the list of values that are used in the loop but are 6544 // defined outside the loop, such as arguments and constants. 6545 SmallPtrSet<Value *, 8> LoopInvariants; 6546 6547 unsigned Index = 0; 6548 for (BasicBlock *BB : make_range(DFS.beginRPO(), DFS.endRPO())) { 6549 RU.NumInstructions += BB->size(); 6550 for (Instruction &I : *BB) { 6551 IdxToInstr[Index++] = &I; 6552 6553 // Save the end location of each USE. 6554 for (Value *U : I.operands()) { 6555 auto *Instr = dyn_cast<Instruction>(U); 6556 6557 // Ignore non-instruction values such as arguments, constants, etc. 6558 if (!Instr) 6559 continue; 6560 6561 // If this instruction is outside the loop then record it and continue. 6562 if (!TheLoop->contains(Instr)) { 6563 LoopInvariants.insert(Instr); 6564 continue; 6565 } 6566 6567 // Overwrite previous end points. 6568 EndPoint[Instr] = Index; 6569 Ends.insert(Instr); 6570 } 6571 } 6572 } 6573 6574 // Saves the list of intervals that end with the index in 'key'. 6575 typedef SmallVector<Instruction *, 2> InstrList; 6576 DenseMap<unsigned, InstrList> TransposeEnds; 6577 6578 // Transpose the EndPoints to a list of values that end at each index. 6579 for (auto &Interval : EndPoint) 6580 TransposeEnds[Interval.second].push_back(Interval.first); 6581 6582 SmallSet<Instruction *, 8> OpenIntervals; 6583 6584 // Get the size of the widest register. 6585 unsigned MaxSafeDepDist = -1U; 6586 if (Legal->getMaxSafeDepDistBytes() != -1U) 6587 MaxSafeDepDist = Legal->getMaxSafeDepDistBytes() * 8; 6588 unsigned WidestRegister = 6589 std::min(TTI.getRegisterBitWidth(true), MaxSafeDepDist); 6590 const DataLayout &DL = TheFunction->getParent()->getDataLayout(); 6591 6592 SmallVector<RegisterUsage, 8> RUs(VFs.size()); 6593 SmallVector<unsigned, 8> MaxUsages(VFs.size(), 0); 6594 6595 DEBUG(dbgs() << "LV(REG): Calculating max register usage:\n"); 6596 6597 // A lambda that gets the register usage for the given type and VF. 6598 auto GetRegUsage = [&DL, WidestRegister](Type *Ty, unsigned VF) { 6599 if (Ty->isTokenTy()) 6600 return 0U; 6601 unsigned TypeSize = DL.getTypeSizeInBits(Ty->getScalarType()); 6602 return std::max<unsigned>(1, VF * TypeSize / WidestRegister); 6603 }; 6604 6605 for (unsigned int i = 0; i < Index; ++i) { 6606 Instruction *I = IdxToInstr[i]; 6607 6608 // Remove all of the instructions that end at this location. 6609 InstrList &List = TransposeEnds[i]; 6610 for (Instruction *ToRemove : List) 6611 OpenIntervals.erase(ToRemove); 6612 6613 // Ignore instructions that are never used within the loop. 6614 if (!Ends.count(I)) 6615 continue; 6616 6617 // Skip ignored values. 6618 if (ValuesToIgnore.count(I)) 6619 continue; 6620 6621 // For each VF find the maximum usage of registers. 6622 for (unsigned j = 0, e = VFs.size(); j < e; ++j) { 6623 if (VFs[j] == 1) { 6624 MaxUsages[j] = std::max(MaxUsages[j], OpenIntervals.size()); 6625 continue; 6626 } 6627 collectUniformsAndScalars(VFs[j]); 6628 // Count the number of live intervals. 6629 unsigned RegUsage = 0; 6630 for (auto Inst : OpenIntervals) { 6631 // Skip ignored values for VF > 1. 6632 if (VecValuesToIgnore.count(Inst) || 6633 isScalarAfterVectorization(Inst, VFs[j])) 6634 continue; 6635 RegUsage += GetRegUsage(Inst->getType(), VFs[j]); 6636 } 6637 MaxUsages[j] = std::max(MaxUsages[j], RegUsage); 6638 } 6639 6640 DEBUG(dbgs() << "LV(REG): At #" << i << " Interval # " 6641 << OpenIntervals.size() << '\n'); 6642 6643 // Add the current instruction to the list of open intervals. 6644 OpenIntervals.insert(I); 6645 } 6646 6647 for (unsigned i = 0, e = VFs.size(); i < e; ++i) { 6648 unsigned Invariant = 0; 6649 if (VFs[i] == 1) 6650 Invariant = LoopInvariants.size(); 6651 else { 6652 for (auto Inst : LoopInvariants) 6653 Invariant += GetRegUsage(Inst->getType(), VFs[i]); 6654 } 6655 6656 DEBUG(dbgs() << "LV(REG): VF = " << VFs[i] << '\n'); 6657 DEBUG(dbgs() << "LV(REG): Found max usage: " << MaxUsages[i] << '\n'); 6658 DEBUG(dbgs() << "LV(REG): Found invariant usage: " << Invariant << '\n'); 6659 DEBUG(dbgs() << "LV(REG): LoopSize: " << RU.NumInstructions << '\n'); 6660 6661 RU.LoopInvariantRegs = Invariant; 6662 RU.MaxLocalUsers = MaxUsages[i]; 6663 RUs[i] = RU; 6664 } 6665 6666 return RUs; 6667 } 6668 6669 void LoopVectorizationCostModel::collectInstsToScalarize(unsigned VF) { 6670 6671 // If we aren't vectorizing the loop, or if we've already collected the 6672 // instructions to scalarize, there's nothing to do. Collection may already 6673 // have occurred if we have a user-selected VF and are now computing the 6674 // expected cost for interleaving. 6675 if (VF < 2 || InstsToScalarize.count(VF)) 6676 return; 6677 6678 // Initialize a mapping for VF in InstsToScalalarize. If we find that it's 6679 // not profitable to scalarize any instructions, the presence of VF in the 6680 // map will indicate that we've analyzed it already. 6681 ScalarCostsTy &ScalarCostsVF = InstsToScalarize[VF]; 6682 6683 // Find all the instructions that are scalar with predication in the loop and 6684 // determine if it would be better to not if-convert the blocks they are in. 6685 // If so, we also record the instructions to scalarize. 6686 for (BasicBlock *BB : TheLoop->blocks()) { 6687 if (!Legal->blockNeedsPredication(BB)) 6688 continue; 6689 for (Instruction &I : *BB) 6690 if (Legal->isScalarWithPredication(&I)) { 6691 ScalarCostsTy ScalarCosts; 6692 if (computePredInstDiscount(&I, ScalarCosts, VF) >= 0) 6693 ScalarCostsVF.insert(ScalarCosts.begin(), ScalarCosts.end()); 6694 } 6695 } 6696 } 6697 6698 int LoopVectorizationCostModel::computePredInstDiscount( 6699 Instruction *PredInst, DenseMap<Instruction *, unsigned> &ScalarCosts, 6700 unsigned VF) { 6701 6702 assert(!isUniformAfterVectorization(PredInst, VF) && 6703 "Instruction marked uniform-after-vectorization will be predicated"); 6704 6705 // Initialize the discount to zero, meaning that the scalar version and the 6706 // vector version cost the same. 6707 int Discount = 0; 6708 6709 // Holds instructions to analyze. The instructions we visit are mapped in 6710 // ScalarCosts. Those instructions are the ones that would be scalarized if 6711 // we find that the scalar version costs less. 6712 SmallVector<Instruction *, 8> Worklist; 6713 6714 // Returns true if the given instruction can be scalarized. 6715 auto canBeScalarized = [&](Instruction *I) -> bool { 6716 6717 // We only attempt to scalarize instructions forming a single-use chain 6718 // from the original predicated block that would otherwise be vectorized. 6719 // Although not strictly necessary, we give up on instructions we know will 6720 // already be scalar to avoid traversing chains that are unlikely to be 6721 // beneficial. 6722 if (!I->hasOneUse() || PredInst->getParent() != I->getParent() || 6723 isScalarAfterVectorization(I, VF)) 6724 return false; 6725 6726 // If the instruction is scalar with predication, it will be analyzed 6727 // separately. We ignore it within the context of PredInst. 6728 if (Legal->isScalarWithPredication(I)) 6729 return false; 6730 6731 // If any of the instruction's operands are uniform after vectorization, 6732 // the instruction cannot be scalarized. This prevents, for example, a 6733 // masked load from being scalarized. 6734 // 6735 // We assume we will only emit a value for lane zero of an instruction 6736 // marked uniform after vectorization, rather than VF identical values. 6737 // Thus, if we scalarize an instruction that uses a uniform, we would 6738 // create uses of values corresponding to the lanes we aren't emitting code 6739 // for. This behavior can be changed by allowing getScalarValue to clone 6740 // the lane zero values for uniforms rather than asserting. 6741 for (Use &U : I->operands()) 6742 if (auto *J = dyn_cast<Instruction>(U.get())) 6743 if (isUniformAfterVectorization(J, VF)) 6744 return false; 6745 6746 // Otherwise, we can scalarize the instruction. 6747 return true; 6748 }; 6749 6750 // Returns true if an operand that cannot be scalarized must be extracted 6751 // from a vector. We will account for this scalarization overhead below. Note 6752 // that the non-void predicated instructions are placed in their own blocks, 6753 // and their return values are inserted into vectors. Thus, an extract would 6754 // still be required. 6755 auto needsExtract = [&](Instruction *I) -> bool { 6756 return TheLoop->contains(I) && !isScalarAfterVectorization(I, VF); 6757 }; 6758 6759 // Compute the expected cost discount from scalarizing the entire expression 6760 // feeding the predicated instruction. We currently only consider expressions 6761 // that are single-use instruction chains. 6762 Worklist.push_back(PredInst); 6763 while (!Worklist.empty()) { 6764 Instruction *I = Worklist.pop_back_val(); 6765 6766 // If we've already analyzed the instruction, there's nothing to do. 6767 if (ScalarCosts.count(I)) 6768 continue; 6769 6770 // Compute the cost of the vector instruction. Note that this cost already 6771 // includes the scalarization overhead of the predicated instruction. 6772 unsigned VectorCost = getInstructionCost(I, VF).first; 6773 6774 // Compute the cost of the scalarized instruction. This cost is the cost of 6775 // the instruction as if it wasn't if-converted and instead remained in the 6776 // predicated block. We will scale this cost by block probability after 6777 // computing the scalarization overhead. 6778 unsigned ScalarCost = VF * getInstructionCost(I, 1).first; 6779 6780 // Compute the scalarization overhead of needed insertelement instructions 6781 // and phi nodes. 6782 if (Legal->isScalarWithPredication(I) && !I->getType()->isVoidTy()) { 6783 ScalarCost += TTI.getScalarizationOverhead(ToVectorTy(I->getType(), VF), 6784 true, false); 6785 ScalarCost += VF * TTI.getCFInstrCost(Instruction::PHI); 6786 } 6787 6788 // Compute the scalarization overhead of needed extractelement 6789 // instructions. For each of the instruction's operands, if the operand can 6790 // be scalarized, add it to the worklist; otherwise, account for the 6791 // overhead. 6792 for (Use &U : I->operands()) 6793 if (auto *J = dyn_cast<Instruction>(U.get())) { 6794 assert(VectorType::isValidElementType(J->getType()) && 6795 "Instruction has non-scalar type"); 6796 if (canBeScalarized(J)) 6797 Worklist.push_back(J); 6798 else if (needsExtract(J)) 6799 ScalarCost += TTI.getScalarizationOverhead( 6800 ToVectorTy(J->getType(),VF), false, true); 6801 } 6802 6803 // Scale the total scalar cost by block probability. 6804 ScalarCost /= getReciprocalPredBlockProb(); 6805 6806 // Compute the discount. A non-negative discount means the vector version 6807 // of the instruction costs more, and scalarizing would be beneficial. 6808 Discount += VectorCost - ScalarCost; 6809 ScalarCosts[I] = ScalarCost; 6810 } 6811 6812 return Discount; 6813 } 6814 6815 LoopVectorizationCostModel::VectorizationCostTy 6816 LoopVectorizationCostModel::expectedCost(unsigned VF) { 6817 VectorizationCostTy Cost; 6818 6819 // Collect Uniform and Scalar instructions after vectorization with VF. 6820 collectUniformsAndScalars(VF); 6821 6822 // Collect the instructions (and their associated costs) that will be more 6823 // profitable to scalarize. 6824 collectInstsToScalarize(VF); 6825 6826 // For each block. 6827 for (BasicBlock *BB : TheLoop->blocks()) { 6828 VectorizationCostTy BlockCost; 6829 6830 // For each instruction in the old loop. 6831 for (Instruction &I : *BB) { 6832 // Skip dbg intrinsics. 6833 if (isa<DbgInfoIntrinsic>(I)) 6834 continue; 6835 6836 // Skip ignored values. 6837 if (ValuesToIgnore.count(&I)) 6838 continue; 6839 6840 VectorizationCostTy C = getInstructionCost(&I, VF); 6841 6842 // Check if we should override the cost. 6843 if (ForceTargetInstructionCost.getNumOccurrences() > 0) 6844 C.first = ForceTargetInstructionCost; 6845 6846 BlockCost.first += C.first; 6847 BlockCost.second |= C.second; 6848 DEBUG(dbgs() << "LV: Found an estimated cost of " << C.first << " for VF " 6849 << VF << " For instruction: " << I << '\n'); 6850 } 6851 6852 // If we are vectorizing a predicated block, it will have been 6853 // if-converted. This means that the block's instructions (aside from 6854 // stores and instructions that may divide by zero) will now be 6855 // unconditionally executed. For the scalar case, we may not always execute 6856 // the predicated block. Thus, scale the block's cost by the probability of 6857 // executing it. 6858 if (VF == 1 && Legal->blockNeedsPredication(BB)) 6859 BlockCost.first /= getReciprocalPredBlockProb(); 6860 6861 Cost.first += BlockCost.first; 6862 Cost.second |= BlockCost.second; 6863 } 6864 6865 return Cost; 6866 } 6867 6868 /// \brief Gets Address Access SCEV after verifying that the access pattern 6869 /// is loop invariant except the induction variable dependence. 6870 /// 6871 /// This SCEV can be sent to the Target in order to estimate the address 6872 /// calculation cost. 6873 static const SCEV *getAddressAccessSCEV( 6874 Value *Ptr, 6875 LoopVectorizationLegality *Legal, 6876 ScalarEvolution *SE, 6877 const Loop *TheLoop) { 6878 auto *Gep = dyn_cast<GetElementPtrInst>(Ptr); 6879 if (!Gep) 6880 return nullptr; 6881 6882 // We are looking for a gep with all loop invariant indices except for one 6883 // which should be an induction variable. 6884 unsigned NumOperands = Gep->getNumOperands(); 6885 for (unsigned i = 1; i < NumOperands; ++i) { 6886 Value *Opd = Gep->getOperand(i); 6887 if (!SE->isLoopInvariant(SE->getSCEV(Opd), TheLoop) && 6888 !Legal->isInductionVariable(Opd)) 6889 return nullptr; 6890 } 6891 6892 // Now we know we have a GEP ptr, %inv, %ind, %inv. return the Ptr SCEV. 6893 return SE->getSCEV(Ptr); 6894 } 6895 6896 static bool isStrideMul(Instruction *I, LoopVectorizationLegality *Legal) { 6897 return Legal->hasStride(I->getOperand(0)) || 6898 Legal->hasStride(I->getOperand(1)); 6899 } 6900 6901 unsigned LoopVectorizationCostModel::getMemInstScalarizationCost(Instruction *I, 6902 unsigned VF) { 6903 Type *ValTy = getMemInstValueType(I); 6904 auto SE = PSE.getSE(); 6905 6906 unsigned Alignment = getMemInstAlignment(I); 6907 unsigned AS = getMemInstAddressSpace(I); 6908 Value *Ptr = getPointerOperand(I); 6909 Type *PtrTy = ToVectorTy(Ptr->getType(), VF); 6910 6911 // Figure out whether the access is strided and get the stride value 6912 // if it's known in compile time 6913 const SCEV *PtrSCEV = getAddressAccessSCEV(Ptr, Legal, SE, TheLoop); 6914 6915 // Get the cost of the scalar memory instruction and address computation. 6916 unsigned Cost = VF * TTI.getAddressComputationCost(PtrTy, SE, PtrSCEV); 6917 6918 Cost += VF * 6919 TTI.getMemoryOpCost(I->getOpcode(), ValTy->getScalarType(), Alignment, 6920 AS); 6921 6922 // Get the overhead of the extractelement and insertelement instructions 6923 // we might create due to scalarization. 6924 Cost += getScalarizationOverhead(I, VF, TTI); 6925 6926 // If we have a predicated store, it may not be executed for each vector 6927 // lane. Scale the cost by the probability of executing the predicated 6928 // block. 6929 if (Legal->isScalarWithPredication(I)) 6930 Cost /= getReciprocalPredBlockProb(); 6931 6932 return Cost; 6933 } 6934 6935 unsigned LoopVectorizationCostModel::getConsecutiveMemOpCost(Instruction *I, 6936 unsigned VF) { 6937 Type *ValTy = getMemInstValueType(I); 6938 Type *VectorTy = ToVectorTy(ValTy, VF); 6939 unsigned Alignment = getMemInstAlignment(I); 6940 Value *Ptr = getPointerOperand(I); 6941 unsigned AS = getMemInstAddressSpace(I); 6942 int ConsecutiveStride = Legal->isConsecutivePtr(Ptr); 6943 6944 assert((ConsecutiveStride == 1 || ConsecutiveStride == -1) && 6945 "Stride should be 1 or -1 for consecutive memory access"); 6946 unsigned Cost = 0; 6947 if (Legal->isMaskRequired(I)) 6948 Cost += TTI.getMaskedMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS); 6949 else 6950 Cost += TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS); 6951 6952 bool Reverse = ConsecutiveStride < 0; 6953 if (Reverse) 6954 Cost += TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, VectorTy, 0); 6955 return Cost; 6956 } 6957 6958 unsigned LoopVectorizationCostModel::getUniformMemOpCost(Instruction *I, 6959 unsigned VF) { 6960 LoadInst *LI = cast<LoadInst>(I); 6961 Type *ValTy = LI->getType(); 6962 Type *VectorTy = ToVectorTy(ValTy, VF); 6963 unsigned Alignment = LI->getAlignment(); 6964 unsigned AS = LI->getPointerAddressSpace(); 6965 6966 return TTI.getAddressComputationCost(ValTy) + 6967 TTI.getMemoryOpCost(Instruction::Load, ValTy, Alignment, AS) + 6968 TTI.getShuffleCost(TargetTransformInfo::SK_Broadcast, VectorTy); 6969 } 6970 6971 unsigned LoopVectorizationCostModel::getGatherScatterCost(Instruction *I, 6972 unsigned VF) { 6973 Type *ValTy = getMemInstValueType(I); 6974 Type *VectorTy = ToVectorTy(ValTy, VF); 6975 unsigned Alignment = getMemInstAlignment(I); 6976 Value *Ptr = getPointerOperand(I); 6977 6978 return TTI.getAddressComputationCost(VectorTy) + 6979 TTI.getGatherScatterOpCost(I->getOpcode(), VectorTy, Ptr, 6980 Legal->isMaskRequired(I), Alignment); 6981 } 6982 6983 unsigned LoopVectorizationCostModel::getInterleaveGroupCost(Instruction *I, 6984 unsigned VF) { 6985 Type *ValTy = getMemInstValueType(I); 6986 Type *VectorTy = ToVectorTy(ValTy, VF); 6987 unsigned AS = getMemInstAddressSpace(I); 6988 6989 auto Group = Legal->getInterleavedAccessGroup(I); 6990 assert(Group && "Fail to get an interleaved access group."); 6991 6992 unsigned InterleaveFactor = Group->getFactor(); 6993 Type *WideVecTy = VectorType::get(ValTy, VF * InterleaveFactor); 6994 6995 // Holds the indices of existing members in an interleaved load group. 6996 // An interleaved store group doesn't need this as it doesn't allow gaps. 6997 SmallVector<unsigned, 4> Indices; 6998 if (isa<LoadInst>(I)) { 6999 for (unsigned i = 0; i < InterleaveFactor; i++) 7000 if (Group->getMember(i)) 7001 Indices.push_back(i); 7002 } 7003 7004 // Calculate the cost of the whole interleaved group. 7005 unsigned Cost = TTI.getInterleavedMemoryOpCost(I->getOpcode(), WideVecTy, 7006 Group->getFactor(), Indices, 7007 Group->getAlignment(), AS); 7008 7009 if (Group->isReverse()) 7010 Cost += Group->getNumMembers() * 7011 TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, VectorTy, 0); 7012 return Cost; 7013 } 7014 7015 unsigned LoopVectorizationCostModel::getMemoryInstructionCost(Instruction *I, 7016 unsigned VF) { 7017 7018 // Calculate scalar cost only. Vectorization cost should be ready at this 7019 // moment. 7020 if (VF == 1) { 7021 Type *ValTy = getMemInstValueType(I); 7022 unsigned Alignment = getMemInstAlignment(I); 7023 unsigned AS = getMemInstAlignment(I); 7024 7025 return TTI.getAddressComputationCost(ValTy) + 7026 TTI.getMemoryOpCost(I->getOpcode(), ValTy, Alignment, AS); 7027 } 7028 return getWideningCost(I, VF); 7029 } 7030 7031 LoopVectorizationCostModel::VectorizationCostTy 7032 LoopVectorizationCostModel::getInstructionCost(Instruction *I, unsigned VF) { 7033 // If we know that this instruction will remain uniform, check the cost of 7034 // the scalar version. 7035 if (isUniformAfterVectorization(I, VF)) 7036 VF = 1; 7037 7038 if (VF > 1 && isProfitableToScalarize(I, VF)) 7039 return VectorizationCostTy(InstsToScalarize[VF][I], false); 7040 7041 Type *VectorTy; 7042 unsigned C = getInstructionCost(I, VF, VectorTy); 7043 7044 bool TypeNotScalarized = 7045 VF > 1 && !VectorTy->isVoidTy() && TTI.getNumberOfParts(VectorTy) < VF; 7046 return VectorizationCostTy(C, TypeNotScalarized); 7047 } 7048 7049 void LoopVectorizationCostModel::setCostBasedWideningDecision(unsigned VF) { 7050 if (VF == 1) 7051 return; 7052 for (BasicBlock *BB : TheLoop->blocks()) { 7053 // For each instruction in the old loop. 7054 for (Instruction &I : *BB) { 7055 Value *Ptr = getPointerOperand(&I); 7056 if (!Ptr) 7057 continue; 7058 7059 if (isa<LoadInst>(&I) && Legal->isUniform(Ptr)) { 7060 // Scalar load + broadcast 7061 unsigned Cost = getUniformMemOpCost(&I, VF); 7062 setWideningDecision(&I, VF, CM_Scalarize, Cost); 7063 continue; 7064 } 7065 7066 // We assume that widening is the best solution when possible. 7067 if (Legal->memoryInstructionCanBeWidened(&I, VF)) { 7068 unsigned Cost = getConsecutiveMemOpCost(&I, VF); 7069 setWideningDecision(&I, VF, CM_Widen, Cost); 7070 continue; 7071 } 7072 7073 // Choose between Interleaving, Gather/Scatter or Scalarization. 7074 unsigned InterleaveCost = UINT_MAX; 7075 unsigned NumAccesses = 1; 7076 if (Legal->isAccessInterleaved(&I)) { 7077 auto Group = Legal->getInterleavedAccessGroup(&I); 7078 assert(Group && "Fail to get an interleaved access group."); 7079 7080 // Make one decision for the whole group. 7081 if (getWideningDecision(&I, VF) != CM_Unknown) 7082 continue; 7083 7084 NumAccesses = Group->getNumMembers(); 7085 InterleaveCost = getInterleaveGroupCost(&I, VF); 7086 } 7087 7088 unsigned GatherScatterCost = 7089 Legal->isLegalGatherOrScatter(&I) 7090 ? getGatherScatterCost(&I, VF) * NumAccesses 7091 : UINT_MAX; 7092 7093 unsigned ScalarizationCost = 7094 getMemInstScalarizationCost(&I, VF) * NumAccesses; 7095 7096 // Choose better solution for the current VF, 7097 // write down this decision and use it during vectorization. 7098 unsigned Cost; 7099 InstWidening Decision; 7100 if (InterleaveCost <= GatherScatterCost && 7101 InterleaveCost < ScalarizationCost) { 7102 Decision = CM_Interleave; 7103 Cost = InterleaveCost; 7104 } else if (GatherScatterCost < ScalarizationCost) { 7105 Decision = CM_GatherScatter; 7106 Cost = GatherScatterCost; 7107 } else { 7108 Decision = CM_Scalarize; 7109 Cost = ScalarizationCost; 7110 } 7111 // If the instructions belongs to an interleave group, the whole group 7112 // receives the same decision. The whole group receives the cost, but 7113 // the cost will actually be assigned to one instruction. 7114 if (auto Group = Legal->getInterleavedAccessGroup(&I)) 7115 setWideningDecision(Group, VF, Decision, Cost); 7116 else 7117 setWideningDecision(&I, VF, Decision, Cost); 7118 } 7119 } 7120 } 7121 7122 unsigned LoopVectorizationCostModel::getInstructionCost(Instruction *I, 7123 unsigned VF, 7124 Type *&VectorTy) { 7125 Type *RetTy = I->getType(); 7126 if (canTruncateToMinimalBitwidth(I, VF)) 7127 RetTy = IntegerType::get(RetTy->getContext(), MinBWs[I]); 7128 VectorTy = ToVectorTy(RetTy, VF); 7129 auto SE = PSE.getSE(); 7130 7131 // TODO: We need to estimate the cost of intrinsic calls. 7132 switch (I->getOpcode()) { 7133 case Instruction::GetElementPtr: 7134 // We mark this instruction as zero-cost because the cost of GEPs in 7135 // vectorized code depends on whether the corresponding memory instruction 7136 // is scalarized or not. Therefore, we handle GEPs with the memory 7137 // instruction cost. 7138 return 0; 7139 case Instruction::Br: { 7140 return TTI.getCFInstrCost(I->getOpcode()); 7141 } 7142 case Instruction::PHI: { 7143 auto *Phi = cast<PHINode>(I); 7144 7145 // First-order recurrences are replaced by vector shuffles inside the loop. 7146 if (VF > 1 && Legal->isFirstOrderRecurrence(Phi)) 7147 return TTI.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector, 7148 VectorTy, VF - 1, VectorTy); 7149 7150 // TODO: IF-converted IFs become selects. 7151 return 0; 7152 } 7153 case Instruction::UDiv: 7154 case Instruction::SDiv: 7155 case Instruction::URem: 7156 case Instruction::SRem: 7157 // If we have a predicated instruction, it may not be executed for each 7158 // vector lane. Get the scalarization cost and scale this amount by the 7159 // probability of executing the predicated block. If the instruction is not 7160 // predicated, we fall through to the next case. 7161 if (VF > 1 && Legal->isScalarWithPredication(I)) { 7162 unsigned Cost = 0; 7163 7164 // These instructions have a non-void type, so account for the phi nodes 7165 // that we will create. This cost is likely to be zero. The phi node 7166 // cost, if any, should be scaled by the block probability because it 7167 // models a copy at the end of each predicated block. 7168 Cost += VF * TTI.getCFInstrCost(Instruction::PHI); 7169 7170 // The cost of the non-predicated instruction. 7171 Cost += VF * TTI.getArithmeticInstrCost(I->getOpcode(), RetTy); 7172 7173 // The cost of insertelement and extractelement instructions needed for 7174 // scalarization. 7175 Cost += getScalarizationOverhead(I, VF, TTI); 7176 7177 // Scale the cost by the probability of executing the predicated blocks. 7178 // This assumes the predicated block for each vector lane is equally 7179 // likely. 7180 return Cost / getReciprocalPredBlockProb(); 7181 } 7182 case Instruction::Add: 7183 case Instruction::FAdd: 7184 case Instruction::Sub: 7185 case Instruction::FSub: 7186 case Instruction::Mul: 7187 case Instruction::FMul: 7188 case Instruction::FDiv: 7189 case Instruction::FRem: 7190 case Instruction::Shl: 7191 case Instruction::LShr: 7192 case Instruction::AShr: 7193 case Instruction::And: 7194 case Instruction::Or: 7195 case Instruction::Xor: { 7196 // Since we will replace the stride by 1 the multiplication should go away. 7197 if (I->getOpcode() == Instruction::Mul && isStrideMul(I, Legal)) 7198 return 0; 7199 // Certain instructions can be cheaper to vectorize if they have a constant 7200 // second vector operand. One example of this are shifts on x86. 7201 TargetTransformInfo::OperandValueKind Op1VK = 7202 TargetTransformInfo::OK_AnyValue; 7203 TargetTransformInfo::OperandValueKind Op2VK = 7204 TargetTransformInfo::OK_AnyValue; 7205 TargetTransformInfo::OperandValueProperties Op1VP = 7206 TargetTransformInfo::OP_None; 7207 TargetTransformInfo::OperandValueProperties Op2VP = 7208 TargetTransformInfo::OP_None; 7209 Value *Op2 = I->getOperand(1); 7210 7211 // Check for a splat or for a non uniform vector of constants. 7212 if (isa<ConstantInt>(Op2)) { 7213 ConstantInt *CInt = cast<ConstantInt>(Op2); 7214 if (CInt && CInt->getValue().isPowerOf2()) 7215 Op2VP = TargetTransformInfo::OP_PowerOf2; 7216 Op2VK = TargetTransformInfo::OK_UniformConstantValue; 7217 } else if (isa<ConstantVector>(Op2) || isa<ConstantDataVector>(Op2)) { 7218 Op2VK = TargetTransformInfo::OK_NonUniformConstantValue; 7219 Constant *SplatValue = cast<Constant>(Op2)->getSplatValue(); 7220 if (SplatValue) { 7221 ConstantInt *CInt = dyn_cast<ConstantInt>(SplatValue); 7222 if (CInt && CInt->getValue().isPowerOf2()) 7223 Op2VP = TargetTransformInfo::OP_PowerOf2; 7224 Op2VK = TargetTransformInfo::OK_UniformConstantValue; 7225 } 7226 } else if (Legal->isUniform(Op2)) { 7227 Op2VK = TargetTransformInfo::OK_UniformValue; 7228 } 7229 SmallVector<const Value *, 4> Operands(I->operand_values()); 7230 return TTI.getArithmeticInstrCost(I->getOpcode(), VectorTy, Op1VK, 7231 Op2VK, Op1VP, Op2VP, Operands); 7232 } 7233 case Instruction::Select: { 7234 SelectInst *SI = cast<SelectInst>(I); 7235 const SCEV *CondSCEV = SE->getSCEV(SI->getCondition()); 7236 bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop)); 7237 Type *CondTy = SI->getCondition()->getType(); 7238 if (!ScalarCond) 7239 CondTy = VectorType::get(CondTy, VF); 7240 7241 return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, CondTy); 7242 } 7243 case Instruction::ICmp: 7244 case Instruction::FCmp: { 7245 Type *ValTy = I->getOperand(0)->getType(); 7246 Instruction *Op0AsInstruction = dyn_cast<Instruction>(I->getOperand(0)); 7247 if (canTruncateToMinimalBitwidth(Op0AsInstruction, VF)) 7248 ValTy = IntegerType::get(ValTy->getContext(), MinBWs[Op0AsInstruction]); 7249 VectorTy = ToVectorTy(ValTy, VF); 7250 return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy); 7251 } 7252 case Instruction::Store: 7253 case Instruction::Load: { 7254 VectorTy = ToVectorTy(getMemInstValueType(I), VF); 7255 return getMemoryInstructionCost(I, VF); 7256 } 7257 case Instruction::ZExt: 7258 case Instruction::SExt: 7259 case Instruction::FPToUI: 7260 case Instruction::FPToSI: 7261 case Instruction::FPExt: 7262 case Instruction::PtrToInt: 7263 case Instruction::IntToPtr: 7264 case Instruction::SIToFP: 7265 case Instruction::UIToFP: 7266 case Instruction::Trunc: 7267 case Instruction::FPTrunc: 7268 case Instruction::BitCast: { 7269 // We optimize the truncation of induction variables having constant 7270 // integer steps. The cost of these truncations is the same as the scalar 7271 // operation. 7272 if (isOptimizableIVTruncate(I, VF)) { 7273 auto *Trunc = cast<TruncInst>(I); 7274 return TTI.getCastInstrCost(Instruction::Trunc, Trunc->getDestTy(), 7275 Trunc->getSrcTy()); 7276 } 7277 7278 Type *SrcScalarTy = I->getOperand(0)->getType(); 7279 Type *SrcVecTy = ToVectorTy(SrcScalarTy, VF); 7280 if (canTruncateToMinimalBitwidth(I, VF)) { 7281 // This cast is going to be shrunk. This may remove the cast or it might 7282 // turn it into slightly different cast. For example, if MinBW == 16, 7283 // "zext i8 %1 to i32" becomes "zext i8 %1 to i16". 7284 // 7285 // Calculate the modified src and dest types. 7286 Type *MinVecTy = VectorTy; 7287 if (I->getOpcode() == Instruction::Trunc) { 7288 SrcVecTy = smallestIntegerVectorType(SrcVecTy, MinVecTy); 7289 VectorTy = 7290 largestIntegerVectorType(ToVectorTy(I->getType(), VF), MinVecTy); 7291 } else if (I->getOpcode() == Instruction::ZExt || 7292 I->getOpcode() == Instruction::SExt) { 7293 SrcVecTy = largestIntegerVectorType(SrcVecTy, MinVecTy); 7294 VectorTy = 7295 smallestIntegerVectorType(ToVectorTy(I->getType(), VF), MinVecTy); 7296 } 7297 } 7298 7299 return TTI.getCastInstrCost(I->getOpcode(), VectorTy, SrcVecTy); 7300 } 7301 case Instruction::Call: { 7302 bool NeedToScalarize; 7303 CallInst *CI = cast<CallInst>(I); 7304 unsigned CallCost = getVectorCallCost(CI, VF, TTI, TLI, NeedToScalarize); 7305 if (getVectorIntrinsicIDForCall(CI, TLI)) 7306 return std::min(CallCost, getVectorIntrinsicCost(CI, VF, TTI, TLI)); 7307 return CallCost; 7308 } 7309 default: 7310 // The cost of executing VF copies of the scalar instruction. This opcode 7311 // is unknown. Assume that it is the same as 'mul'. 7312 return VF * TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy) + 7313 getScalarizationOverhead(I, VF, TTI); 7314 } // end of switch. 7315 } 7316 7317 char LoopVectorize::ID = 0; 7318 static const char lv_name[] = "Loop Vectorization"; 7319 INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false) 7320 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass) 7321 INITIALIZE_PASS_DEPENDENCY(BasicAAWrapperPass) 7322 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass) 7323 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass) 7324 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 7325 INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass) 7326 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 7327 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass) 7328 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 7329 INITIALIZE_PASS_DEPENDENCY(LoopAccessLegacyAnalysis) 7330 INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass) 7331 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass) 7332 INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false) 7333 7334 namespace llvm { 7335 Pass *createLoopVectorizePass(bool NoUnrolling, bool AlwaysVectorize) { 7336 return new LoopVectorize(NoUnrolling, AlwaysVectorize); 7337 } 7338 } 7339 7340 bool LoopVectorizationCostModel::isConsecutiveLoadOrStore(Instruction *Inst) { 7341 7342 // Check if the pointer operand of a load or store instruction is 7343 // consecutive. 7344 if (auto *Ptr = getPointerOperand(Inst)) 7345 return Legal->isConsecutivePtr(Ptr); 7346 return false; 7347 } 7348 7349 void LoopVectorizationCostModel::collectValuesToIgnore() { 7350 // Ignore ephemeral values. 7351 CodeMetrics::collectEphemeralValues(TheLoop, AC, ValuesToIgnore); 7352 7353 // Ignore type-promoting instructions we identified during reduction 7354 // detection. 7355 for (auto &Reduction : *Legal->getReductionVars()) { 7356 RecurrenceDescriptor &RedDes = Reduction.second; 7357 SmallPtrSetImpl<Instruction *> &Casts = RedDes.getCastInsts(); 7358 VecValuesToIgnore.insert(Casts.begin(), Casts.end()); 7359 } 7360 } 7361 7362 LoopVectorizationCostModel::VectorizationFactor 7363 LoopVectorizationPlanner::plan(bool OptForSize, unsigned UserVF) { 7364 7365 // Width 1 means no vectorize, cost 0 means uncomputed cost. 7366 const LoopVectorizationCostModel::VectorizationFactor NoVectorization = {1U, 7367 0U}; 7368 Optional<unsigned> MaybeMaxVF = CM.computeMaxVF(OptForSize); 7369 if (!MaybeMaxVF.hasValue()) // Cases considered too costly to vectorize. 7370 return NoVectorization; 7371 7372 if (UserVF) { 7373 DEBUG(dbgs() << "LV: Using user VF " << UserVF << ".\n"); 7374 assert(isPowerOf2_32(UserVF) && "VF needs to be a power of two"); 7375 // Collect the instructions (and their associated costs) that will be more 7376 // profitable to scalarize. 7377 CM.selectUserVectorizationFactor(UserVF); 7378 return {UserVF, 0}; 7379 } 7380 7381 unsigned MaxVF = MaybeMaxVF.getValue(); 7382 assert(MaxVF != 0 && "MaxVF is zero."); 7383 if (MaxVF == 1) 7384 return NoVectorization; 7385 7386 // Select the optimal vectorization factor. 7387 return CM.selectVectorizationFactor(MaxVF); 7388 } 7389 7390 void InnerLoopUnroller::vectorizeMemoryInstruction(Instruction *Instr) { 7391 auto *SI = dyn_cast<StoreInst>(Instr); 7392 bool IfPredicateInstr = (SI && Legal->blockNeedsPredication(SI->getParent())); 7393 7394 return scalarizeInstruction(Instr, IfPredicateInstr); 7395 } 7396 7397 Value *InnerLoopUnroller::reverseVector(Value *Vec) { return Vec; } 7398 7399 Value *InnerLoopUnroller::getBroadcastInstrs(Value *V) { return V; } 7400 7401 Value *InnerLoopUnroller::getStepVector(Value *Val, int StartIdx, Value *Step, 7402 Instruction::BinaryOps BinOp) { 7403 // When unrolling and the VF is 1, we only need to add a simple scalar. 7404 Type *Ty = Val->getType(); 7405 assert(!Ty->isVectorTy() && "Val must be a scalar"); 7406 7407 if (Ty->isFloatingPointTy()) { 7408 Constant *C = ConstantFP::get(Ty, (double)StartIdx); 7409 7410 // Floating point operations had to be 'fast' to enable the unrolling. 7411 Value *MulOp = addFastMathFlag(Builder.CreateFMul(C, Step)); 7412 return addFastMathFlag(Builder.CreateBinOp(BinOp, Val, MulOp)); 7413 } 7414 Constant *C = ConstantInt::get(Ty, StartIdx); 7415 return Builder.CreateAdd(Val, Builder.CreateMul(C, Step), "induction"); 7416 } 7417 7418 static void AddRuntimeUnrollDisableMetaData(Loop *L) { 7419 SmallVector<Metadata *, 4> MDs; 7420 // Reserve first location for self reference to the LoopID metadata node. 7421 MDs.push_back(nullptr); 7422 bool IsUnrollMetadata = false; 7423 MDNode *LoopID = L->getLoopID(); 7424 if (LoopID) { 7425 // First find existing loop unrolling disable metadata. 7426 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) { 7427 auto *MD = dyn_cast<MDNode>(LoopID->getOperand(i)); 7428 if (MD) { 7429 const auto *S = dyn_cast<MDString>(MD->getOperand(0)); 7430 IsUnrollMetadata = 7431 S && S->getString().startswith("llvm.loop.unroll.disable"); 7432 } 7433 MDs.push_back(LoopID->getOperand(i)); 7434 } 7435 } 7436 7437 if (!IsUnrollMetadata) { 7438 // Add runtime unroll disable metadata. 7439 LLVMContext &Context = L->getHeader()->getContext(); 7440 SmallVector<Metadata *, 1> DisableOperands; 7441 DisableOperands.push_back( 7442 MDString::get(Context, "llvm.loop.unroll.runtime.disable")); 7443 MDNode *DisableNode = MDNode::get(Context, DisableOperands); 7444 MDs.push_back(DisableNode); 7445 MDNode *NewLoopID = MDNode::get(Context, MDs); 7446 // Set operand 0 to refer to the loop id itself. 7447 NewLoopID->replaceOperandWith(0, NewLoopID); 7448 L->setLoopID(NewLoopID); 7449 } 7450 } 7451 7452 bool LoopVectorizePass::processLoop(Loop *L) { 7453 assert(L->empty() && "Only process inner loops."); 7454 7455 #ifndef NDEBUG 7456 const std::string DebugLocStr = getDebugLocString(L); 7457 #endif /* NDEBUG */ 7458 7459 DEBUG(dbgs() << "\nLV: Checking a loop in \"" 7460 << L->getHeader()->getParent()->getName() << "\" from " 7461 << DebugLocStr << "\n"); 7462 7463 LoopVectorizeHints Hints(L, DisableUnrolling, *ORE); 7464 7465 DEBUG(dbgs() << "LV: Loop hints:" 7466 << " force=" 7467 << (Hints.getForce() == LoopVectorizeHints::FK_Disabled 7468 ? "disabled" 7469 : (Hints.getForce() == LoopVectorizeHints::FK_Enabled 7470 ? "enabled" 7471 : "?")) 7472 << " width=" << Hints.getWidth() 7473 << " unroll=" << Hints.getInterleave() << "\n"); 7474 7475 // Function containing loop 7476 Function *F = L->getHeader()->getParent(); 7477 7478 // Looking at the diagnostic output is the only way to determine if a loop 7479 // was vectorized (other than looking at the IR or machine code), so it 7480 // is important to generate an optimization remark for each loop. Most of 7481 // these messages are generated as OptimizationRemarkAnalysis. Remarks 7482 // generated as OptimizationRemark and OptimizationRemarkMissed are 7483 // less verbose reporting vectorized loops and unvectorized loops that may 7484 // benefit from vectorization, respectively. 7485 7486 if (!Hints.allowVectorization(F, L, AlwaysVectorize)) { 7487 DEBUG(dbgs() << "LV: Loop hints prevent vectorization.\n"); 7488 return false; 7489 } 7490 7491 // Check the loop for a trip count threshold: 7492 // do not vectorize loops with a tiny trip count. 7493 const unsigned MaxTC = SE->getSmallConstantMaxTripCount(L); 7494 if (MaxTC > 0u && MaxTC < TinyTripCountVectorThreshold) { 7495 DEBUG(dbgs() << "LV: Found a loop with a very small trip count. " 7496 << "This loop is not worth vectorizing."); 7497 if (Hints.getForce() == LoopVectorizeHints::FK_Enabled) 7498 DEBUG(dbgs() << " But vectorizing was explicitly forced.\n"); 7499 else { 7500 DEBUG(dbgs() << "\n"); 7501 ORE->emit(createMissedAnalysis(Hints.vectorizeAnalysisPassName(), 7502 "NotBeneficial", L) 7503 << "vectorization is not beneficial " 7504 "and is not explicitly forced"); 7505 return false; 7506 } 7507 } 7508 7509 PredicatedScalarEvolution PSE(*SE, *L); 7510 7511 // Check if it is legal to vectorize the loop. 7512 LoopVectorizationRequirements Requirements(*ORE); 7513 LoopVectorizationLegality LVL(L, PSE, DT, TLI, AA, F, TTI, GetLAA, LI, ORE, 7514 &Requirements, &Hints); 7515 if (!LVL.canVectorize()) { 7516 DEBUG(dbgs() << "LV: Not vectorizing: Cannot prove legality.\n"); 7517 emitMissedWarning(F, L, Hints, ORE); 7518 return false; 7519 } 7520 7521 // Check the function attributes to find out if this function should be 7522 // optimized for size. 7523 bool OptForSize = 7524 Hints.getForce() != LoopVectorizeHints::FK_Enabled && F->optForSize(); 7525 7526 // Compute the weighted frequency of this loop being executed and see if it 7527 // is less than 20% of the function entry baseline frequency. Note that we 7528 // always have a canonical loop here because we think we *can* vectorize. 7529 // FIXME: This is hidden behind a flag due to pervasive problems with 7530 // exactly what block frequency models. 7531 if (LoopVectorizeWithBlockFrequency) { 7532 BlockFrequency LoopEntryFreq = BFI->getBlockFreq(L->getLoopPreheader()); 7533 if (Hints.getForce() != LoopVectorizeHints::FK_Enabled && 7534 LoopEntryFreq < ColdEntryFreq) 7535 OptForSize = true; 7536 } 7537 7538 // Check the function attributes to see if implicit floats are allowed. 7539 // FIXME: This check doesn't seem possibly correct -- what if the loop is 7540 // an integer loop and the vector instructions selected are purely integer 7541 // vector instructions? 7542 if (F->hasFnAttribute(Attribute::NoImplicitFloat)) { 7543 DEBUG(dbgs() << "LV: Can't vectorize when the NoImplicitFloat" 7544 "attribute is used.\n"); 7545 ORE->emit(createMissedAnalysis(Hints.vectorizeAnalysisPassName(), 7546 "NoImplicitFloat", L) 7547 << "loop not vectorized due to NoImplicitFloat attribute"); 7548 emitMissedWarning(F, L, Hints, ORE); 7549 return false; 7550 } 7551 7552 // Check if the target supports potentially unsafe FP vectorization. 7553 // FIXME: Add a check for the type of safety issue (denormal, signaling) 7554 // for the target we're vectorizing for, to make sure none of the 7555 // additional fp-math flags can help. 7556 if (Hints.isPotentiallyUnsafe() && 7557 TTI->isFPVectorizationPotentiallyUnsafe()) { 7558 DEBUG(dbgs() << "LV: Potentially unsafe FP op prevents vectorization.\n"); 7559 ORE->emit( 7560 createMissedAnalysis(Hints.vectorizeAnalysisPassName(), "UnsafeFP", L) 7561 << "loop not vectorized due to unsafe FP support."); 7562 emitMissedWarning(F, L, Hints, ORE); 7563 return false; 7564 } 7565 7566 // Use the cost model. 7567 LoopVectorizationCostModel CM(L, PSE, LI, &LVL, *TTI, TLI, DB, AC, ORE, F, 7568 &Hints); 7569 CM.collectValuesToIgnore(); 7570 7571 // Use the planner for vectorization. 7572 LoopVectorizationPlanner LVP(CM); 7573 7574 // Get user vectorization factor. 7575 unsigned UserVF = Hints.getWidth(); 7576 7577 // Plan how to best vectorize, return the best VF and its cost. 7578 LoopVectorizationCostModel::VectorizationFactor VF = 7579 LVP.plan(OptForSize, UserVF); 7580 7581 // Select the interleave count. 7582 unsigned IC = CM.selectInterleaveCount(OptForSize, VF.Width, VF.Cost); 7583 7584 // Get user interleave count. 7585 unsigned UserIC = Hints.getInterleave(); 7586 7587 // Identify the diagnostic messages that should be produced. 7588 std::pair<StringRef, std::string> VecDiagMsg, IntDiagMsg; 7589 bool VectorizeLoop = true, InterleaveLoop = true; 7590 if (Requirements.doesNotMeet(F, L, Hints)) { 7591 DEBUG(dbgs() << "LV: Not vectorizing: loop did not meet vectorization " 7592 "requirements.\n"); 7593 emitMissedWarning(F, L, Hints, ORE); 7594 return false; 7595 } 7596 7597 if (VF.Width == 1) { 7598 DEBUG(dbgs() << "LV: Vectorization is possible but not beneficial.\n"); 7599 VecDiagMsg = std::make_pair( 7600 "VectorizationNotBeneficial", 7601 "the cost-model indicates that vectorization is not beneficial"); 7602 VectorizeLoop = false; 7603 } 7604 7605 if (IC == 1 && UserIC <= 1) { 7606 // Tell the user interleaving is not beneficial. 7607 DEBUG(dbgs() << "LV: Interleaving is not beneficial.\n"); 7608 IntDiagMsg = std::make_pair( 7609 "InterleavingNotBeneficial", 7610 "the cost-model indicates that interleaving is not beneficial"); 7611 InterleaveLoop = false; 7612 if (UserIC == 1) { 7613 IntDiagMsg.first = "InterleavingNotBeneficialAndDisabled"; 7614 IntDiagMsg.second += 7615 " and is explicitly disabled or interleave count is set to 1"; 7616 } 7617 } else if (IC > 1 && UserIC == 1) { 7618 // Tell the user interleaving is beneficial, but it explicitly disabled. 7619 DEBUG(dbgs() 7620 << "LV: Interleaving is beneficial but is explicitly disabled."); 7621 IntDiagMsg = std::make_pair( 7622 "InterleavingBeneficialButDisabled", 7623 "the cost-model indicates that interleaving is beneficial " 7624 "but is explicitly disabled or interleave count is set to 1"); 7625 InterleaveLoop = false; 7626 } 7627 7628 // Override IC if user provided an interleave count. 7629 IC = UserIC > 0 ? UserIC : IC; 7630 7631 // Emit diagnostic messages, if any. 7632 const char *VAPassName = Hints.vectorizeAnalysisPassName(); 7633 if (!VectorizeLoop && !InterleaveLoop) { 7634 // Do not vectorize or interleaving the loop. 7635 ORE->emit(OptimizationRemarkMissed(VAPassName, VecDiagMsg.first, 7636 L->getStartLoc(), L->getHeader()) 7637 << VecDiagMsg.second); 7638 ORE->emit(OptimizationRemarkMissed(LV_NAME, IntDiagMsg.first, 7639 L->getStartLoc(), L->getHeader()) 7640 << IntDiagMsg.second); 7641 return false; 7642 } else if (!VectorizeLoop && InterleaveLoop) { 7643 DEBUG(dbgs() << "LV: Interleave Count is " << IC << '\n'); 7644 ORE->emit(OptimizationRemarkAnalysis(VAPassName, VecDiagMsg.first, 7645 L->getStartLoc(), L->getHeader()) 7646 << VecDiagMsg.second); 7647 } else if (VectorizeLoop && !InterleaveLoop) { 7648 DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width << ") in " 7649 << DebugLocStr << '\n'); 7650 ORE->emit(OptimizationRemarkAnalysis(LV_NAME, IntDiagMsg.first, 7651 L->getStartLoc(), L->getHeader()) 7652 << IntDiagMsg.second); 7653 } else if (VectorizeLoop && InterleaveLoop) { 7654 DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width << ") in " 7655 << DebugLocStr << '\n'); 7656 DEBUG(dbgs() << "LV: Interleave Count is " << IC << '\n'); 7657 } 7658 7659 using namespace ore; 7660 if (!VectorizeLoop) { 7661 assert(IC > 1 && "interleave count should not be 1 or 0"); 7662 // If we decided that it is not legal to vectorize the loop, then 7663 // interleave it. 7664 InnerLoopUnroller Unroller(L, PSE, LI, DT, TLI, TTI, AC, ORE, IC, &LVL, 7665 &CM); 7666 Unroller.vectorize(); 7667 7668 ORE->emit(OptimizationRemark(LV_NAME, "Interleaved", L->getStartLoc(), 7669 L->getHeader()) 7670 << "interleaved loop (interleaved count: " 7671 << NV("InterleaveCount", IC) << ")"); 7672 } else { 7673 // If we decided that it is *legal* to vectorize the loop, then do it. 7674 InnerLoopVectorizer LB(L, PSE, LI, DT, TLI, TTI, AC, ORE, VF.Width, IC, 7675 &LVL, &CM); 7676 LB.vectorize(); 7677 ++LoopsVectorized; 7678 7679 // Add metadata to disable runtime unrolling a scalar loop when there are 7680 // no runtime checks about strides and memory. A scalar loop that is 7681 // rarely used is not worth unrolling. 7682 if (!LB.areSafetyChecksAdded()) 7683 AddRuntimeUnrollDisableMetaData(L); 7684 7685 // Report the vectorization decision. 7686 ORE->emit(OptimizationRemark(LV_NAME, "Vectorized", L->getStartLoc(), 7687 L->getHeader()) 7688 << "vectorized loop (vectorization width: " 7689 << NV("VectorizationFactor", VF.Width) 7690 << ", interleaved count: " << NV("InterleaveCount", IC) << ")"); 7691 } 7692 7693 // Mark the loop as already vectorized to avoid vectorizing again. 7694 Hints.setAlreadyVectorized(); 7695 7696 DEBUG(verifyFunction(*L->getHeader()->getParent())); 7697 return true; 7698 } 7699 7700 bool LoopVectorizePass::runImpl( 7701 Function &F, ScalarEvolution &SE_, LoopInfo &LI_, TargetTransformInfo &TTI_, 7702 DominatorTree &DT_, BlockFrequencyInfo &BFI_, TargetLibraryInfo *TLI_, 7703 DemandedBits &DB_, AliasAnalysis &AA_, AssumptionCache &AC_, 7704 std::function<const LoopAccessInfo &(Loop &)> &GetLAA_, 7705 OptimizationRemarkEmitter &ORE_) { 7706 7707 SE = &SE_; 7708 LI = &LI_; 7709 TTI = &TTI_; 7710 DT = &DT_; 7711 BFI = &BFI_; 7712 TLI = TLI_; 7713 AA = &AA_; 7714 AC = &AC_; 7715 GetLAA = &GetLAA_; 7716 DB = &DB_; 7717 ORE = &ORE_; 7718 7719 // Compute some weights outside of the loop over the loops. Compute this 7720 // using a BranchProbability to re-use its scaling math. 7721 const BranchProbability ColdProb(1, 5); // 20% 7722 ColdEntryFreq = BlockFrequency(BFI->getEntryFreq()) * ColdProb; 7723 7724 // Don't attempt if 7725 // 1. the target claims to have no vector registers, and 7726 // 2. interleaving won't help ILP. 7727 // 7728 // The second condition is necessary because, even if the target has no 7729 // vector registers, loop vectorization may still enable scalar 7730 // interleaving. 7731 if (!TTI->getNumberOfRegisters(true) && TTI->getMaxInterleaveFactor(1) < 2) 7732 return false; 7733 7734 bool Changed = false; 7735 7736 // The vectorizer requires loops to be in simplified form. 7737 // Since simplification may add new inner loops, it has to run before the 7738 // legality and profitability checks. This means running the loop vectorizer 7739 // will simplify all loops, regardless of whether anything end up being 7740 // vectorized. 7741 for (auto &L : *LI) 7742 Changed |= simplifyLoop(L, DT, LI, SE, AC, false /* PreserveLCSSA */); 7743 7744 // Build up a worklist of inner-loops to vectorize. This is necessary as 7745 // the act of vectorizing or partially unrolling a loop creates new loops 7746 // and can invalidate iterators across the loops. 7747 SmallVector<Loop *, 8> Worklist; 7748 7749 for (Loop *L : *LI) 7750 addAcyclicInnerLoop(*L, Worklist); 7751 7752 LoopsAnalyzed += Worklist.size(); 7753 7754 // Now walk the identified inner loops. 7755 while (!Worklist.empty()) { 7756 Loop *L = Worklist.pop_back_val(); 7757 7758 // For the inner loops we actually process, form LCSSA to simplify the 7759 // transform. 7760 Changed |= formLCSSARecursively(*L, *DT, LI, SE); 7761 7762 Changed |= processLoop(L); 7763 } 7764 7765 // Process each loop nest in the function. 7766 return Changed; 7767 7768 } 7769 7770 7771 PreservedAnalyses LoopVectorizePass::run(Function &F, 7772 FunctionAnalysisManager &AM) { 7773 auto &SE = AM.getResult<ScalarEvolutionAnalysis>(F); 7774 auto &LI = AM.getResult<LoopAnalysis>(F); 7775 auto &TTI = AM.getResult<TargetIRAnalysis>(F); 7776 auto &DT = AM.getResult<DominatorTreeAnalysis>(F); 7777 auto &BFI = AM.getResult<BlockFrequencyAnalysis>(F); 7778 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F); 7779 auto &AA = AM.getResult<AAManager>(F); 7780 auto &AC = AM.getResult<AssumptionAnalysis>(F); 7781 auto &DB = AM.getResult<DemandedBitsAnalysis>(F); 7782 auto &ORE = AM.getResult<OptimizationRemarkEmitterAnalysis>(F); 7783 7784 auto &LAM = AM.getResult<LoopAnalysisManagerFunctionProxy>(F).getManager(); 7785 std::function<const LoopAccessInfo &(Loop &)> GetLAA = 7786 [&](Loop &L) -> const LoopAccessInfo & { 7787 LoopStandardAnalysisResults AR = {AA, AC, DT, LI, SE, TLI, TTI}; 7788 return LAM.getResult<LoopAccessAnalysis>(L, AR); 7789 }; 7790 bool Changed = 7791 runImpl(F, SE, LI, TTI, DT, BFI, &TLI, DB, AA, AC, GetLAA, ORE); 7792 if (!Changed) 7793 return PreservedAnalyses::all(); 7794 PreservedAnalyses PA; 7795 PA.preserve<LoopAnalysis>(); 7796 PA.preserve<DominatorTreeAnalysis>(); 7797 PA.preserve<BasicAA>(); 7798 PA.preserve<GlobalsAA>(); 7799 return PA; 7800 } 7801