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