1 //===- llvm/Analysis/IVDescriptors.cpp - IndVar Descriptors -----*- C++ -*-===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file "describes" induction and recurrence variables. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "llvm/Analysis/IVDescriptors.h" 14 #include "llvm/ADT/ScopeExit.h" 15 #include "llvm/Analysis/AliasAnalysis.h" 16 #include "llvm/Analysis/BasicAliasAnalysis.h" 17 #include "llvm/Analysis/DomTreeUpdater.h" 18 #include "llvm/Analysis/GlobalsModRef.h" 19 #include "llvm/Analysis/InstructionSimplify.h" 20 #include "llvm/Analysis/LoopInfo.h" 21 #include "llvm/Analysis/LoopPass.h" 22 #include "llvm/Analysis/MustExecute.h" 23 #include "llvm/Analysis/ScalarEvolution.h" 24 #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h" 25 #include "llvm/Analysis/ScalarEvolutionExpander.h" 26 #include "llvm/Analysis/ScalarEvolutionExpressions.h" 27 #include "llvm/Analysis/TargetTransformInfo.h" 28 #include "llvm/Analysis/ValueTracking.h" 29 #include "llvm/IR/Dominators.h" 30 #include "llvm/IR/Instructions.h" 31 #include "llvm/IR/Module.h" 32 #include "llvm/IR/PatternMatch.h" 33 #include "llvm/IR/ValueHandle.h" 34 #include "llvm/Pass.h" 35 #include "llvm/Support/Debug.h" 36 #include "llvm/Support/KnownBits.h" 37 38 using namespace llvm; 39 using namespace llvm::PatternMatch; 40 41 #define DEBUG_TYPE "iv-descriptors" 42 43 bool RecurrenceDescriptor::areAllUsesIn(Instruction *I, 44 SmallPtrSetImpl<Instruction *> &Set) { 45 for (User::op_iterator Use = I->op_begin(), E = I->op_end(); Use != E; ++Use) 46 if (!Set.count(dyn_cast<Instruction>(*Use))) 47 return false; 48 return true; 49 } 50 51 bool RecurrenceDescriptor::isIntegerRecurrenceKind(RecurrenceKind Kind) { 52 switch (Kind) { 53 default: 54 break; 55 case RK_IntegerAdd: 56 case RK_IntegerMult: 57 case RK_IntegerOr: 58 case RK_IntegerAnd: 59 case RK_IntegerXor: 60 case RK_IntegerMinMax: 61 return true; 62 } 63 return false; 64 } 65 66 bool RecurrenceDescriptor::isFloatingPointRecurrenceKind(RecurrenceKind Kind) { 67 return (Kind != RK_NoRecurrence) && !isIntegerRecurrenceKind(Kind); 68 } 69 70 bool RecurrenceDescriptor::isArithmeticRecurrenceKind(RecurrenceKind Kind) { 71 switch (Kind) { 72 default: 73 break; 74 case RK_IntegerAdd: 75 case RK_IntegerMult: 76 case RK_FloatAdd: 77 case RK_FloatMult: 78 return true; 79 } 80 return false; 81 } 82 83 /// Determines if Phi may have been type-promoted. If Phi has a single user 84 /// that ANDs the Phi with a type mask, return the user. RT is updated to 85 /// account for the narrower bit width represented by the mask, and the AND 86 /// instruction is added to CI. 87 static Instruction *lookThroughAnd(PHINode *Phi, Type *&RT, 88 SmallPtrSetImpl<Instruction *> &Visited, 89 SmallPtrSetImpl<Instruction *> &CI) { 90 if (!Phi->hasOneUse()) 91 return Phi; 92 93 const APInt *M = nullptr; 94 Instruction *I, *J = cast<Instruction>(Phi->use_begin()->getUser()); 95 96 // Matches either I & 2^x-1 or 2^x-1 & I. If we find a match, we update RT 97 // with a new integer type of the corresponding bit width. 98 if (match(J, m_c_And(m_Instruction(I), m_APInt(M)))) { 99 int32_t Bits = (*M + 1).exactLogBase2(); 100 if (Bits > 0) { 101 RT = IntegerType::get(Phi->getContext(), Bits); 102 Visited.insert(Phi); 103 CI.insert(J); 104 return J; 105 } 106 } 107 return Phi; 108 } 109 110 /// Compute the minimal bit width needed to represent a reduction whose exit 111 /// instruction is given by Exit. 112 static std::pair<Type *, bool> computeRecurrenceType(Instruction *Exit, 113 DemandedBits *DB, 114 AssumptionCache *AC, 115 DominatorTree *DT) { 116 bool IsSigned = false; 117 const DataLayout &DL = Exit->getModule()->getDataLayout(); 118 uint64_t MaxBitWidth = DL.getTypeSizeInBits(Exit->getType()); 119 120 if (DB) { 121 // Use the demanded bits analysis to determine the bits that are live out 122 // of the exit instruction, rounding up to the nearest power of two. If the 123 // use of demanded bits results in a smaller bit width, we know the value 124 // must be positive (i.e., IsSigned = false), because if this were not the 125 // case, the sign bit would have been demanded. 126 auto Mask = DB->getDemandedBits(Exit); 127 MaxBitWidth = Mask.getBitWidth() - Mask.countLeadingZeros(); 128 } 129 130 if (MaxBitWidth == DL.getTypeSizeInBits(Exit->getType()) && AC && DT) { 131 // If demanded bits wasn't able to limit the bit width, we can try to use 132 // value tracking instead. This can be the case, for example, if the value 133 // may be negative. 134 auto NumSignBits = ComputeNumSignBits(Exit, DL, 0, AC, nullptr, DT); 135 auto NumTypeBits = DL.getTypeSizeInBits(Exit->getType()); 136 MaxBitWidth = NumTypeBits - NumSignBits; 137 KnownBits Bits = computeKnownBits(Exit, DL); 138 if (!Bits.isNonNegative()) { 139 // If the value is not known to be non-negative, we set IsSigned to true, 140 // meaning that we will use sext instructions instead of zext 141 // instructions to restore the original type. 142 IsSigned = true; 143 if (!Bits.isNegative()) 144 // If the value is not known to be negative, we don't known what the 145 // upper bit is, and therefore, we don't know what kind of extend we 146 // will need. In this case, just increase the bit width by one bit and 147 // use sext. 148 ++MaxBitWidth; 149 } 150 } 151 if (!isPowerOf2_64(MaxBitWidth)) 152 MaxBitWidth = NextPowerOf2(MaxBitWidth); 153 154 return std::make_pair(Type::getIntNTy(Exit->getContext(), MaxBitWidth), 155 IsSigned); 156 } 157 158 /// Collect cast instructions that can be ignored in the vectorizer's cost 159 /// model, given a reduction exit value and the minimal type in which the 160 /// reduction can be represented. 161 static void collectCastsToIgnore(Loop *TheLoop, Instruction *Exit, 162 Type *RecurrenceType, 163 SmallPtrSetImpl<Instruction *> &Casts) { 164 165 SmallVector<Instruction *, 8> Worklist; 166 SmallPtrSet<Instruction *, 8> Visited; 167 Worklist.push_back(Exit); 168 169 while (!Worklist.empty()) { 170 Instruction *Val = Worklist.pop_back_val(); 171 Visited.insert(Val); 172 if (auto *Cast = dyn_cast<CastInst>(Val)) 173 if (Cast->getSrcTy() == RecurrenceType) { 174 // If the source type of a cast instruction is equal to the recurrence 175 // type, it will be eliminated, and should be ignored in the vectorizer 176 // cost model. 177 Casts.insert(Cast); 178 continue; 179 } 180 181 // Add all operands to the work list if they are loop-varying values that 182 // we haven't yet visited. 183 for (Value *O : cast<User>(Val)->operands()) 184 if (auto *I = dyn_cast<Instruction>(O)) 185 if (TheLoop->contains(I) && !Visited.count(I)) 186 Worklist.push_back(I); 187 } 188 } 189 190 bool RecurrenceDescriptor::AddReductionVar(PHINode *Phi, RecurrenceKind Kind, 191 Loop *TheLoop, bool HasFunNoNaNAttr, 192 RecurrenceDescriptor &RedDes, 193 DemandedBits *DB, 194 AssumptionCache *AC, 195 DominatorTree *DT) { 196 if (Phi->getNumIncomingValues() != 2) 197 return false; 198 199 // Reduction variables are only found in the loop header block. 200 if (Phi->getParent() != TheLoop->getHeader()) 201 return false; 202 203 // Obtain the reduction start value from the value that comes from the loop 204 // preheader. 205 Value *RdxStart = Phi->getIncomingValueForBlock(TheLoop->getLoopPreheader()); 206 207 // ExitInstruction is the single value which is used outside the loop. 208 // We only allow for a single reduction value to be used outside the loop. 209 // This includes users of the reduction, variables (which form a cycle 210 // which ends in the phi node). 211 Instruction *ExitInstruction = nullptr; 212 // Indicates that we found a reduction operation in our scan. 213 bool FoundReduxOp = false; 214 215 // We start with the PHI node and scan for all of the users of this 216 // instruction. All users must be instructions that can be used as reduction 217 // variables (such as ADD). We must have a single out-of-block user. The cycle 218 // must include the original PHI. 219 bool FoundStartPHI = false; 220 221 // To recognize min/max patterns formed by a icmp select sequence, we store 222 // the number of instruction we saw from the recognized min/max pattern, 223 // to make sure we only see exactly the two instructions. 224 unsigned NumCmpSelectPatternInst = 0; 225 InstDesc ReduxDesc(false, nullptr); 226 227 // Data used for determining if the recurrence has been type-promoted. 228 Type *RecurrenceType = Phi->getType(); 229 SmallPtrSet<Instruction *, 4> CastInsts; 230 Instruction *Start = Phi; 231 bool IsSigned = false; 232 233 SmallPtrSet<Instruction *, 8> VisitedInsts; 234 SmallVector<Instruction *, 8> Worklist; 235 236 // Return early if the recurrence kind does not match the type of Phi. If the 237 // recurrence kind is arithmetic, we attempt to look through AND operations 238 // resulting from the type promotion performed by InstCombine. Vector 239 // operations are not limited to the legal integer widths, so we may be able 240 // to evaluate the reduction in the narrower width. 241 if (RecurrenceType->isFloatingPointTy()) { 242 if (!isFloatingPointRecurrenceKind(Kind)) 243 return false; 244 } else { 245 if (!isIntegerRecurrenceKind(Kind)) 246 return false; 247 if (isArithmeticRecurrenceKind(Kind)) 248 Start = lookThroughAnd(Phi, RecurrenceType, VisitedInsts, CastInsts); 249 } 250 251 Worklist.push_back(Start); 252 VisitedInsts.insert(Start); 253 254 // A value in the reduction can be used: 255 // - By the reduction: 256 // - Reduction operation: 257 // - One use of reduction value (safe). 258 // - Multiple use of reduction value (not safe). 259 // - PHI: 260 // - All uses of the PHI must be the reduction (safe). 261 // - Otherwise, not safe. 262 // - By instructions outside of the loop (safe). 263 // * One value may have several outside users, but all outside 264 // uses must be of the same value. 265 // - By an instruction that is not part of the reduction (not safe). 266 // This is either: 267 // * An instruction type other than PHI or the reduction operation. 268 // * A PHI in the header other than the initial PHI. 269 while (!Worklist.empty()) { 270 Instruction *Cur = Worklist.back(); 271 Worklist.pop_back(); 272 273 // No Users. 274 // If the instruction has no users then this is a broken chain and can't be 275 // a reduction variable. 276 if (Cur->use_empty()) 277 return false; 278 279 bool IsAPhi = isa<PHINode>(Cur); 280 281 // A header PHI use other than the original PHI. 282 if (Cur != Phi && IsAPhi && Cur->getParent() == Phi->getParent()) 283 return false; 284 285 // Reductions of instructions such as Div, and Sub is only possible if the 286 // LHS is the reduction variable. 287 if (!Cur->isCommutative() && !IsAPhi && !isa<SelectInst>(Cur) && 288 !isa<ICmpInst>(Cur) && !isa<FCmpInst>(Cur) && 289 !VisitedInsts.count(dyn_cast<Instruction>(Cur->getOperand(0)))) 290 return false; 291 292 // Any reduction instruction must be of one of the allowed kinds. We ignore 293 // the starting value (the Phi or an AND instruction if the Phi has been 294 // type-promoted). 295 if (Cur != Start) { 296 ReduxDesc = isRecurrenceInstr(Cur, Kind, ReduxDesc, HasFunNoNaNAttr); 297 if (!ReduxDesc.isRecurrence()) 298 return false; 299 } 300 301 bool IsASelect = isa<SelectInst>(Cur); 302 303 // A conditional reduction operation must only have 2 or less uses in 304 // VisitedInsts. 305 if (IsASelect && (Kind == RK_FloatAdd || Kind == RK_FloatMult) && 306 hasMultipleUsesOf(Cur, VisitedInsts, 2)) 307 return false; 308 309 // A reduction operation must only have one use of the reduction value. 310 if (!IsAPhi && !IsASelect && Kind != RK_IntegerMinMax && 311 Kind != RK_FloatMinMax && hasMultipleUsesOf(Cur, VisitedInsts, 1)) 312 return false; 313 314 // All inputs to a PHI node must be a reduction value. 315 if (IsAPhi && Cur != Phi && !areAllUsesIn(Cur, VisitedInsts)) 316 return false; 317 318 if (Kind == RK_IntegerMinMax && 319 (isa<ICmpInst>(Cur) || isa<SelectInst>(Cur))) 320 ++NumCmpSelectPatternInst; 321 if (Kind == RK_FloatMinMax && (isa<FCmpInst>(Cur) || isa<SelectInst>(Cur))) 322 ++NumCmpSelectPatternInst; 323 324 // Check whether we found a reduction operator. 325 FoundReduxOp |= !IsAPhi && Cur != Start; 326 327 // Process users of current instruction. Push non-PHI nodes after PHI nodes 328 // onto the stack. This way we are going to have seen all inputs to PHI 329 // nodes once we get to them. 330 SmallVector<Instruction *, 8> NonPHIs; 331 SmallVector<Instruction *, 8> PHIs; 332 for (User *U : Cur->users()) { 333 Instruction *UI = cast<Instruction>(U); 334 335 // Check if we found the exit user. 336 BasicBlock *Parent = UI->getParent(); 337 if (!TheLoop->contains(Parent)) { 338 // If we already know this instruction is used externally, move on to 339 // the next user. 340 if (ExitInstruction == Cur) 341 continue; 342 343 // Exit if you find multiple values used outside or if the header phi 344 // node is being used. In this case the user uses the value of the 345 // previous iteration, in which case we would loose "VF-1" iterations of 346 // the reduction operation if we vectorize. 347 if (ExitInstruction != nullptr || Cur == Phi) 348 return false; 349 350 // The instruction used by an outside user must be the last instruction 351 // before we feed back to the reduction phi. Otherwise, we loose VF-1 352 // operations on the value. 353 if (!is_contained(Phi->operands(), Cur)) 354 return false; 355 356 ExitInstruction = Cur; 357 continue; 358 } 359 360 // Process instructions only once (termination). Each reduction cycle 361 // value must only be used once, except by phi nodes and min/max 362 // reductions which are represented as a cmp followed by a select. 363 InstDesc IgnoredVal(false, nullptr); 364 if (VisitedInsts.insert(UI).second) { 365 if (isa<PHINode>(UI)) 366 PHIs.push_back(UI); 367 else 368 NonPHIs.push_back(UI); 369 } else if (!isa<PHINode>(UI) && 370 ((!isa<FCmpInst>(UI) && !isa<ICmpInst>(UI) && 371 !isa<SelectInst>(UI)) || 372 (!isConditionalRdxPattern(Kind, UI).isRecurrence() && 373 !isMinMaxSelectCmpPattern(UI, IgnoredVal).isRecurrence()))) 374 return false; 375 376 // Remember that we completed the cycle. 377 if (UI == Phi) 378 FoundStartPHI = true; 379 } 380 Worklist.append(PHIs.begin(), PHIs.end()); 381 Worklist.append(NonPHIs.begin(), NonPHIs.end()); 382 } 383 384 // This means we have seen one but not the other instruction of the 385 // pattern or more than just a select and cmp. 386 if ((Kind == RK_IntegerMinMax || Kind == RK_FloatMinMax) && 387 NumCmpSelectPatternInst != 2) 388 return false; 389 390 if (!FoundStartPHI || !FoundReduxOp || !ExitInstruction) 391 return false; 392 393 if (Start != Phi) { 394 // If the starting value is not the same as the phi node, we speculatively 395 // looked through an 'and' instruction when evaluating a potential 396 // arithmetic reduction to determine if it may have been type-promoted. 397 // 398 // We now compute the minimal bit width that is required to represent the 399 // reduction. If this is the same width that was indicated by the 'and', we 400 // can represent the reduction in the smaller type. The 'and' instruction 401 // will be eliminated since it will essentially be a cast instruction that 402 // can be ignore in the cost model. If we compute a different type than we 403 // did when evaluating the 'and', the 'and' will not be eliminated, and we 404 // will end up with different kinds of operations in the recurrence 405 // expression (e.g., RK_IntegerAND, RK_IntegerADD). We give up if this is 406 // the case. 407 // 408 // The vectorizer relies on InstCombine to perform the actual 409 // type-shrinking. It does this by inserting instructions to truncate the 410 // exit value of the reduction to the width indicated by RecurrenceType and 411 // then extend this value back to the original width. If IsSigned is false, 412 // a 'zext' instruction will be generated; otherwise, a 'sext' will be 413 // used. 414 // 415 // TODO: We should not rely on InstCombine to rewrite the reduction in the 416 // smaller type. We should just generate a correctly typed expression 417 // to begin with. 418 Type *ComputedType; 419 std::tie(ComputedType, IsSigned) = 420 computeRecurrenceType(ExitInstruction, DB, AC, DT); 421 if (ComputedType != RecurrenceType) 422 return false; 423 424 // The recurrence expression will be represented in a narrower type. If 425 // there are any cast instructions that will be unnecessary, collect them 426 // in CastInsts. Note that the 'and' instruction was already included in 427 // this list. 428 // 429 // TODO: A better way to represent this may be to tag in some way all the 430 // instructions that are a part of the reduction. The vectorizer cost 431 // model could then apply the recurrence type to these instructions, 432 // without needing a white list of instructions to ignore. 433 collectCastsToIgnore(TheLoop, ExitInstruction, RecurrenceType, CastInsts); 434 } 435 436 // We found a reduction var if we have reached the original phi node and we 437 // only have a single instruction with out-of-loop users. 438 439 // The ExitInstruction(Instruction which is allowed to have out-of-loop users) 440 // is saved as part of the RecurrenceDescriptor. 441 442 // Save the description of this reduction variable. 443 RecurrenceDescriptor RD( 444 RdxStart, ExitInstruction, Kind, ReduxDesc.getMinMaxKind(), 445 ReduxDesc.getUnsafeAlgebraInst(), RecurrenceType, IsSigned, CastInsts); 446 RedDes = RD; 447 448 return true; 449 } 450 451 /// Returns true if the instruction is a Select(ICmp(X, Y), X, Y) instruction 452 /// pattern corresponding to a min(X, Y) or max(X, Y). 453 RecurrenceDescriptor::InstDesc 454 RecurrenceDescriptor::isMinMaxSelectCmpPattern(Instruction *I, InstDesc &Prev) { 455 456 assert((isa<ICmpInst>(I) || isa<FCmpInst>(I) || isa<SelectInst>(I)) && 457 "Expect a select instruction"); 458 Instruction *Cmp = nullptr; 459 SelectInst *Select = nullptr; 460 461 // We must handle the select(cmp()) as a single instruction. Advance to the 462 // select. 463 if ((Cmp = dyn_cast<ICmpInst>(I)) || (Cmp = dyn_cast<FCmpInst>(I))) { 464 if (!Cmp->hasOneUse() || !(Select = dyn_cast<SelectInst>(*I->user_begin()))) 465 return InstDesc(false, I); 466 return InstDesc(Select, Prev.getMinMaxKind()); 467 } 468 469 // Only handle single use cases for now. 470 if (!(Select = dyn_cast<SelectInst>(I))) 471 return InstDesc(false, I); 472 if (!(Cmp = dyn_cast<ICmpInst>(I->getOperand(0))) && 473 !(Cmp = dyn_cast<FCmpInst>(I->getOperand(0)))) 474 return InstDesc(false, I); 475 if (!Cmp->hasOneUse()) 476 return InstDesc(false, I); 477 478 Value *CmpLeft; 479 Value *CmpRight; 480 481 // Look for a min/max pattern. 482 if (m_UMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select)) 483 return InstDesc(Select, MRK_UIntMin); 484 else if (m_UMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select)) 485 return InstDesc(Select, MRK_UIntMax); 486 else if (m_SMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select)) 487 return InstDesc(Select, MRK_SIntMax); 488 else if (m_SMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select)) 489 return InstDesc(Select, MRK_SIntMin); 490 else if (m_OrdFMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select)) 491 return InstDesc(Select, MRK_FloatMin); 492 else if (m_OrdFMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select)) 493 return InstDesc(Select, MRK_FloatMax); 494 else if (m_UnordFMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select)) 495 return InstDesc(Select, MRK_FloatMin); 496 else if (m_UnordFMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select)) 497 return InstDesc(Select, MRK_FloatMax); 498 499 return InstDesc(false, I); 500 } 501 502 /// Returns true if the select instruction has users in the compare-and-add 503 /// reduction pattern below. The select instruction argument is the last one 504 /// in the sequence. 505 /// 506 /// %sum.1 = phi ... 507 /// ... 508 /// %cmp = fcmp pred %0, %CFP 509 /// %add = fadd %0, %sum.1 510 /// %sum.2 = select %cmp, %add, %sum.1 511 RecurrenceDescriptor::InstDesc 512 RecurrenceDescriptor::isConditionalRdxPattern( 513 RecurrenceKind Kind, Instruction *I) { 514 SelectInst *SI = dyn_cast<SelectInst>(I); 515 if (!SI) 516 return InstDesc(false, I); 517 518 CmpInst *CI = dyn_cast<CmpInst>(SI->getCondition()); 519 // Only handle single use cases for now. 520 if (!CI || !CI->hasOneUse()) 521 return InstDesc(false, I); 522 523 Value *TrueVal = SI->getTrueValue(); 524 Value *FalseVal = SI->getFalseValue(); 525 // Handle only when either of operands of select instruction is a PHI 526 // node for now. 527 if ((isa<PHINode>(*TrueVal) && isa<PHINode>(*FalseVal)) || 528 (!isa<PHINode>(*TrueVal) && !isa<PHINode>(*FalseVal))) 529 return InstDesc(false, I); 530 531 Instruction *I1 = 532 isa<PHINode>(*TrueVal) ? dyn_cast<Instruction>(FalseVal) 533 : dyn_cast<Instruction>(TrueVal); 534 if (!I1 || !I1->isBinaryOp()) 535 return InstDesc(false, I); 536 537 Value *Op1, *Op2; 538 if ((m_FAdd(m_Value(Op1), m_Value(Op2)).match(I1) || 539 m_FSub(m_Value(Op1), m_Value(Op2)).match(I1)) && 540 I1->isFast()) 541 return InstDesc(Kind == RK_FloatAdd, SI); 542 543 if (m_FMul(m_Value(Op1), m_Value(Op2)).match(I1) && (I1->isFast())) 544 return InstDesc(Kind == RK_FloatMult, SI); 545 546 return InstDesc(false, I); 547 } 548 549 RecurrenceDescriptor::InstDesc 550 RecurrenceDescriptor::isRecurrenceInstr(Instruction *I, RecurrenceKind Kind, 551 InstDesc &Prev, bool HasFunNoNaNAttr) { 552 Instruction *UAI = Prev.getUnsafeAlgebraInst(); 553 if (!UAI && isa<FPMathOperator>(I) && !I->isFast()) 554 UAI = I; // Found an unsafe (unvectorizable) algebra instruction. 555 556 switch (I->getOpcode()) { 557 default: 558 return InstDesc(false, I); 559 case Instruction::PHI: 560 return InstDesc(I, Prev.getMinMaxKind(), Prev.getUnsafeAlgebraInst()); 561 case Instruction::Sub: 562 case Instruction::Add: 563 return InstDesc(Kind == RK_IntegerAdd, I); 564 case Instruction::Mul: 565 return InstDesc(Kind == RK_IntegerMult, I); 566 case Instruction::And: 567 return InstDesc(Kind == RK_IntegerAnd, I); 568 case Instruction::Or: 569 return InstDesc(Kind == RK_IntegerOr, I); 570 case Instruction::Xor: 571 return InstDesc(Kind == RK_IntegerXor, I); 572 case Instruction::FMul: 573 return InstDesc(Kind == RK_FloatMult, I, UAI); 574 case Instruction::FSub: 575 case Instruction::FAdd: 576 return InstDesc(Kind == RK_FloatAdd, I, UAI); 577 case Instruction::Select: 578 if (Kind == RK_FloatAdd || Kind == RK_FloatMult) 579 return isConditionalRdxPattern(Kind, I); 580 LLVM_FALLTHROUGH; 581 case Instruction::FCmp: 582 case Instruction::ICmp: 583 if (Kind != RK_IntegerMinMax && 584 (!HasFunNoNaNAttr || Kind != RK_FloatMinMax)) 585 return InstDesc(false, I); 586 return isMinMaxSelectCmpPattern(I, Prev); 587 } 588 } 589 590 bool RecurrenceDescriptor::hasMultipleUsesOf( 591 Instruction *I, SmallPtrSetImpl<Instruction *> &Insts, 592 unsigned MaxNumUses) { 593 unsigned NumUses = 0; 594 for (User::op_iterator Use = I->op_begin(), E = I->op_end(); Use != E; 595 ++Use) { 596 if (Insts.count(dyn_cast<Instruction>(*Use))) 597 ++NumUses; 598 if (NumUses > MaxNumUses) 599 return true; 600 } 601 602 return false; 603 } 604 bool RecurrenceDescriptor::isReductionPHI(PHINode *Phi, Loop *TheLoop, 605 RecurrenceDescriptor &RedDes, 606 DemandedBits *DB, AssumptionCache *AC, 607 DominatorTree *DT) { 608 609 BasicBlock *Header = TheLoop->getHeader(); 610 Function &F = *Header->getParent(); 611 bool HasFunNoNaNAttr = 612 F.getFnAttribute("no-nans-fp-math").getValueAsString() == "true"; 613 614 if (AddReductionVar(Phi, RK_IntegerAdd, TheLoop, HasFunNoNaNAttr, RedDes, DB, 615 AC, DT)) { 616 LLVM_DEBUG(dbgs() << "Found an ADD reduction PHI." << *Phi << "\n"); 617 return true; 618 } 619 if (AddReductionVar(Phi, RK_IntegerMult, TheLoop, HasFunNoNaNAttr, RedDes, DB, 620 AC, DT)) { 621 LLVM_DEBUG(dbgs() << "Found a MUL reduction PHI." << *Phi << "\n"); 622 return true; 623 } 624 if (AddReductionVar(Phi, RK_IntegerOr, TheLoop, HasFunNoNaNAttr, RedDes, DB, 625 AC, DT)) { 626 LLVM_DEBUG(dbgs() << "Found an OR reduction PHI." << *Phi << "\n"); 627 return true; 628 } 629 if (AddReductionVar(Phi, RK_IntegerAnd, TheLoop, HasFunNoNaNAttr, RedDes, DB, 630 AC, DT)) { 631 LLVM_DEBUG(dbgs() << "Found an AND reduction PHI." << *Phi << "\n"); 632 return true; 633 } 634 if (AddReductionVar(Phi, RK_IntegerXor, TheLoop, HasFunNoNaNAttr, RedDes, DB, 635 AC, DT)) { 636 LLVM_DEBUG(dbgs() << "Found a XOR reduction PHI." << *Phi << "\n"); 637 return true; 638 } 639 if (AddReductionVar(Phi, RK_IntegerMinMax, TheLoop, HasFunNoNaNAttr, RedDes, 640 DB, AC, DT)) { 641 LLVM_DEBUG(dbgs() << "Found a MINMAX reduction PHI." << *Phi << "\n"); 642 return true; 643 } 644 if (AddReductionVar(Phi, RK_FloatMult, TheLoop, HasFunNoNaNAttr, RedDes, DB, 645 AC, DT)) { 646 LLVM_DEBUG(dbgs() << "Found an FMult reduction PHI." << *Phi << "\n"); 647 return true; 648 } 649 if (AddReductionVar(Phi, RK_FloatAdd, TheLoop, HasFunNoNaNAttr, RedDes, DB, 650 AC, DT)) { 651 LLVM_DEBUG(dbgs() << "Found an FAdd reduction PHI." << *Phi << "\n"); 652 return true; 653 } 654 if (AddReductionVar(Phi, RK_FloatMinMax, TheLoop, HasFunNoNaNAttr, RedDes, DB, 655 AC, DT)) { 656 LLVM_DEBUG(dbgs() << "Found an float MINMAX reduction PHI." << *Phi 657 << "\n"); 658 return true; 659 } 660 // Not a reduction of known type. 661 return false; 662 } 663 664 bool RecurrenceDescriptor::isFirstOrderRecurrence( 665 PHINode *Phi, Loop *TheLoop, 666 DenseMap<Instruction *, Instruction *> &SinkAfter, DominatorTree *DT) { 667 668 // Ensure the phi node is in the loop header and has two incoming values. 669 if (Phi->getParent() != TheLoop->getHeader() || 670 Phi->getNumIncomingValues() != 2) 671 return false; 672 673 // Ensure the loop has a preheader and a single latch block. The loop 674 // vectorizer will need the latch to set up the next iteration of the loop. 675 auto *Preheader = TheLoop->getLoopPreheader(); 676 auto *Latch = TheLoop->getLoopLatch(); 677 if (!Preheader || !Latch) 678 return false; 679 680 // Ensure the phi node's incoming blocks are the loop preheader and latch. 681 if (Phi->getBasicBlockIndex(Preheader) < 0 || 682 Phi->getBasicBlockIndex(Latch) < 0) 683 return false; 684 685 // Get the previous value. The previous value comes from the latch edge while 686 // the initial value comes form the preheader edge. 687 auto *Previous = dyn_cast<Instruction>(Phi->getIncomingValueForBlock(Latch)); 688 if (!Previous || !TheLoop->contains(Previous) || isa<PHINode>(Previous) || 689 SinkAfter.count(Previous)) // Cannot rely on dominance due to motion. 690 return false; 691 692 // Ensure every user of the phi node is dominated by the previous value. 693 // The dominance requirement ensures the loop vectorizer will not need to 694 // vectorize the initial value prior to the first iteration of the loop. 695 // TODO: Consider extending this sinking to handle other kinds of instructions 696 // and expressions, beyond sinking a single cast past Previous. 697 if (Phi->hasOneUse()) { 698 auto *I = Phi->user_back(); 699 if (I->isCast() && (I->getParent() == Phi->getParent()) && I->hasOneUse() && 700 DT->dominates(Previous, I->user_back())) { 701 if (!DT->dominates(Previous, I)) // Otherwise we're good w/o sinking. 702 SinkAfter[I] = Previous; 703 return true; 704 } 705 } 706 707 for (User *U : Phi->users()) 708 if (auto *I = dyn_cast<Instruction>(U)) { 709 if (!DT->dominates(Previous, I)) 710 return false; 711 } 712 713 return true; 714 } 715 716 /// This function returns the identity element (or neutral element) for 717 /// the operation K. 718 Constant *RecurrenceDescriptor::getRecurrenceIdentity(RecurrenceKind K, 719 Type *Tp) { 720 switch (K) { 721 case RK_IntegerXor: 722 case RK_IntegerAdd: 723 case RK_IntegerOr: 724 // Adding, Xoring, Oring zero to a number does not change it. 725 return ConstantInt::get(Tp, 0); 726 case RK_IntegerMult: 727 // Multiplying a number by 1 does not change it. 728 return ConstantInt::get(Tp, 1); 729 case RK_IntegerAnd: 730 // AND-ing a number with an all-1 value does not change it. 731 return ConstantInt::get(Tp, -1, true); 732 case RK_FloatMult: 733 // Multiplying a number by 1 does not change it. 734 return ConstantFP::get(Tp, 1.0L); 735 case RK_FloatAdd: 736 // Adding zero to a number does not change it. 737 return ConstantFP::get(Tp, 0.0L); 738 default: 739 llvm_unreachable("Unknown recurrence kind"); 740 } 741 } 742 743 /// This function translates the recurrence kind to an LLVM binary operator. 744 unsigned RecurrenceDescriptor::getRecurrenceBinOp(RecurrenceKind Kind) { 745 switch (Kind) { 746 case RK_IntegerAdd: 747 return Instruction::Add; 748 case RK_IntegerMult: 749 return Instruction::Mul; 750 case RK_IntegerOr: 751 return Instruction::Or; 752 case RK_IntegerAnd: 753 return Instruction::And; 754 case RK_IntegerXor: 755 return Instruction::Xor; 756 case RK_FloatMult: 757 return Instruction::FMul; 758 case RK_FloatAdd: 759 return Instruction::FAdd; 760 case RK_IntegerMinMax: 761 return Instruction::ICmp; 762 case RK_FloatMinMax: 763 return Instruction::FCmp; 764 default: 765 llvm_unreachable("Unknown recurrence operation"); 766 } 767 } 768 769 InductionDescriptor::InductionDescriptor(Value *Start, InductionKind K, 770 const SCEV *Step, BinaryOperator *BOp, 771 SmallVectorImpl<Instruction *> *Casts) 772 : StartValue(Start), IK(K), Step(Step), InductionBinOp(BOp) { 773 assert(IK != IK_NoInduction && "Not an induction"); 774 775 // Start value type should match the induction kind and the value 776 // itself should not be null. 777 assert(StartValue && "StartValue is null"); 778 assert((IK != IK_PtrInduction || StartValue->getType()->isPointerTy()) && 779 "StartValue is not a pointer for pointer induction"); 780 assert((IK != IK_IntInduction || StartValue->getType()->isIntegerTy()) && 781 "StartValue is not an integer for integer induction"); 782 783 // Check the Step Value. It should be non-zero integer value. 784 assert((!getConstIntStepValue() || !getConstIntStepValue()->isZero()) && 785 "Step value is zero"); 786 787 assert((IK != IK_PtrInduction || getConstIntStepValue()) && 788 "Step value should be constant for pointer induction"); 789 assert((IK == IK_FpInduction || Step->getType()->isIntegerTy()) && 790 "StepValue is not an integer"); 791 792 assert((IK != IK_FpInduction || Step->getType()->isFloatingPointTy()) && 793 "StepValue is not FP for FpInduction"); 794 assert((IK != IK_FpInduction || 795 (InductionBinOp && 796 (InductionBinOp->getOpcode() == Instruction::FAdd || 797 InductionBinOp->getOpcode() == Instruction::FSub))) && 798 "Binary opcode should be specified for FP induction"); 799 800 if (Casts) { 801 for (auto &Inst : *Casts) { 802 RedundantCasts.push_back(Inst); 803 } 804 } 805 } 806 807 int InductionDescriptor::getConsecutiveDirection() const { 808 ConstantInt *ConstStep = getConstIntStepValue(); 809 if (ConstStep && (ConstStep->isOne() || ConstStep->isMinusOne())) 810 return ConstStep->getSExtValue(); 811 return 0; 812 } 813 814 ConstantInt *InductionDescriptor::getConstIntStepValue() const { 815 if (isa<SCEVConstant>(Step)) 816 return dyn_cast<ConstantInt>(cast<SCEVConstant>(Step)->getValue()); 817 return nullptr; 818 } 819 820 bool InductionDescriptor::isFPInductionPHI(PHINode *Phi, const Loop *TheLoop, 821 ScalarEvolution *SE, 822 InductionDescriptor &D) { 823 824 // Here we only handle FP induction variables. 825 assert(Phi->getType()->isFloatingPointTy() && "Unexpected Phi type"); 826 827 if (TheLoop->getHeader() != Phi->getParent()) 828 return false; 829 830 // The loop may have multiple entrances or multiple exits; we can analyze 831 // this phi if it has a unique entry value and a unique backedge value. 832 if (Phi->getNumIncomingValues() != 2) 833 return false; 834 Value *BEValue = nullptr, *StartValue = nullptr; 835 if (TheLoop->contains(Phi->getIncomingBlock(0))) { 836 BEValue = Phi->getIncomingValue(0); 837 StartValue = Phi->getIncomingValue(1); 838 } else { 839 assert(TheLoop->contains(Phi->getIncomingBlock(1)) && 840 "Unexpected Phi node in the loop"); 841 BEValue = Phi->getIncomingValue(1); 842 StartValue = Phi->getIncomingValue(0); 843 } 844 845 BinaryOperator *BOp = dyn_cast<BinaryOperator>(BEValue); 846 if (!BOp) 847 return false; 848 849 Value *Addend = nullptr; 850 if (BOp->getOpcode() == Instruction::FAdd) { 851 if (BOp->getOperand(0) == Phi) 852 Addend = BOp->getOperand(1); 853 else if (BOp->getOperand(1) == Phi) 854 Addend = BOp->getOperand(0); 855 } else if (BOp->getOpcode() == Instruction::FSub) 856 if (BOp->getOperand(0) == Phi) 857 Addend = BOp->getOperand(1); 858 859 if (!Addend) 860 return false; 861 862 // The addend should be loop invariant 863 if (auto *I = dyn_cast<Instruction>(Addend)) 864 if (TheLoop->contains(I)) 865 return false; 866 867 // FP Step has unknown SCEV 868 const SCEV *Step = SE->getUnknown(Addend); 869 D = InductionDescriptor(StartValue, IK_FpInduction, Step, BOp); 870 return true; 871 } 872 873 /// This function is called when we suspect that the update-chain of a phi node 874 /// (whose symbolic SCEV expression sin \p PhiScev) contains redundant casts, 875 /// that can be ignored. (This can happen when the PSCEV rewriter adds a runtime 876 /// predicate P under which the SCEV expression for the phi can be the 877 /// AddRecurrence \p AR; See createAddRecFromPHIWithCast). We want to find the 878 /// cast instructions that are involved in the update-chain of this induction. 879 /// A caller that adds the required runtime predicate can be free to drop these 880 /// cast instructions, and compute the phi using \p AR (instead of some scev 881 /// expression with casts). 882 /// 883 /// For example, without a predicate the scev expression can take the following 884 /// form: 885 /// (Ext ix (Trunc iy ( Start + i*Step ) to ix) to iy) 886 /// 887 /// It corresponds to the following IR sequence: 888 /// %for.body: 889 /// %x = phi i64 [ 0, %ph ], [ %add, %for.body ] 890 /// %casted_phi = "ExtTrunc i64 %x" 891 /// %add = add i64 %casted_phi, %step 892 /// 893 /// where %x is given in \p PN, 894 /// PSE.getSCEV(%x) is equal to PSE.getSCEV(%casted_phi) under a predicate, 895 /// and the IR sequence that "ExtTrunc i64 %x" represents can take one of 896 /// several forms, for example, such as: 897 /// ExtTrunc1: %casted_phi = and %x, 2^n-1 898 /// or: 899 /// ExtTrunc2: %t = shl %x, m 900 /// %casted_phi = ashr %t, m 901 /// 902 /// If we are able to find such sequence, we return the instructions 903 /// we found, namely %casted_phi and the instructions on its use-def chain up 904 /// to the phi (not including the phi). 905 static bool getCastsForInductionPHI(PredicatedScalarEvolution &PSE, 906 const SCEVUnknown *PhiScev, 907 const SCEVAddRecExpr *AR, 908 SmallVectorImpl<Instruction *> &CastInsts) { 909 910 assert(CastInsts.empty() && "CastInsts is expected to be empty."); 911 auto *PN = cast<PHINode>(PhiScev->getValue()); 912 assert(PSE.getSCEV(PN) == AR && "Unexpected phi node SCEV expression"); 913 const Loop *L = AR->getLoop(); 914 915 // Find any cast instructions that participate in the def-use chain of 916 // PhiScev in the loop. 917 // FORNOW/TODO: We currently expect the def-use chain to include only 918 // two-operand instructions, where one of the operands is an invariant. 919 // createAddRecFromPHIWithCasts() currently does not support anything more 920 // involved than that, so we keep the search simple. This can be 921 // extended/generalized as needed. 922 923 auto getDef = [&](const Value *Val) -> Value * { 924 const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Val); 925 if (!BinOp) 926 return nullptr; 927 Value *Op0 = BinOp->getOperand(0); 928 Value *Op1 = BinOp->getOperand(1); 929 Value *Def = nullptr; 930 if (L->isLoopInvariant(Op0)) 931 Def = Op1; 932 else if (L->isLoopInvariant(Op1)) 933 Def = Op0; 934 return Def; 935 }; 936 937 // Look for the instruction that defines the induction via the 938 // loop backedge. 939 BasicBlock *Latch = L->getLoopLatch(); 940 if (!Latch) 941 return false; 942 Value *Val = PN->getIncomingValueForBlock(Latch); 943 if (!Val) 944 return false; 945 946 // Follow the def-use chain until the induction phi is reached. 947 // If on the way we encounter a Value that has the same SCEV Expr as the 948 // phi node, we can consider the instructions we visit from that point 949 // as part of the cast-sequence that can be ignored. 950 bool InCastSequence = false; 951 auto *Inst = dyn_cast<Instruction>(Val); 952 while (Val != PN) { 953 // If we encountered a phi node other than PN, or if we left the loop, 954 // we bail out. 955 if (!Inst || !L->contains(Inst)) { 956 return false; 957 } 958 auto *AddRec = dyn_cast<SCEVAddRecExpr>(PSE.getSCEV(Val)); 959 if (AddRec && PSE.areAddRecsEqualWithPreds(AddRec, AR)) 960 InCastSequence = true; 961 if (InCastSequence) { 962 // Only the last instruction in the cast sequence is expected to have 963 // uses outside the induction def-use chain. 964 if (!CastInsts.empty()) 965 if (!Inst->hasOneUse()) 966 return false; 967 CastInsts.push_back(Inst); 968 } 969 Val = getDef(Val); 970 if (!Val) 971 return false; 972 Inst = dyn_cast<Instruction>(Val); 973 } 974 975 return InCastSequence; 976 } 977 978 bool InductionDescriptor::isInductionPHI(PHINode *Phi, const Loop *TheLoop, 979 PredicatedScalarEvolution &PSE, 980 InductionDescriptor &D, bool Assume) { 981 Type *PhiTy = Phi->getType(); 982 983 // Handle integer and pointer inductions variables. 984 // Now we handle also FP induction but not trying to make a 985 // recurrent expression from the PHI node in-place. 986 987 if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy() && !PhiTy->isFloatTy() && 988 !PhiTy->isDoubleTy() && !PhiTy->isHalfTy()) 989 return false; 990 991 if (PhiTy->isFloatingPointTy()) 992 return isFPInductionPHI(Phi, TheLoop, PSE.getSE(), D); 993 994 const SCEV *PhiScev = PSE.getSCEV(Phi); 995 const auto *AR = dyn_cast<SCEVAddRecExpr>(PhiScev); 996 997 // We need this expression to be an AddRecExpr. 998 if (Assume && !AR) 999 AR = PSE.getAsAddRec(Phi); 1000 1001 if (!AR) { 1002 LLVM_DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n"); 1003 return false; 1004 } 1005 1006 // Record any Cast instructions that participate in the induction update 1007 const auto *SymbolicPhi = dyn_cast<SCEVUnknown>(PhiScev); 1008 // If we started from an UnknownSCEV, and managed to build an addRecurrence 1009 // only after enabling Assume with PSCEV, this means we may have encountered 1010 // cast instructions that required adding a runtime check in order to 1011 // guarantee the correctness of the AddRecurrence respresentation of the 1012 // induction. 1013 if (PhiScev != AR && SymbolicPhi) { 1014 SmallVector<Instruction *, 2> Casts; 1015 if (getCastsForInductionPHI(PSE, SymbolicPhi, AR, Casts)) 1016 return isInductionPHI(Phi, TheLoop, PSE.getSE(), D, AR, &Casts); 1017 } 1018 1019 return isInductionPHI(Phi, TheLoop, PSE.getSE(), D, AR); 1020 } 1021 1022 bool InductionDescriptor::isInductionPHI( 1023 PHINode *Phi, const Loop *TheLoop, ScalarEvolution *SE, 1024 InductionDescriptor &D, const SCEV *Expr, 1025 SmallVectorImpl<Instruction *> *CastsToIgnore) { 1026 Type *PhiTy = Phi->getType(); 1027 // We only handle integer and pointer inductions variables. 1028 if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy()) 1029 return false; 1030 1031 // Check that the PHI is consecutive. 1032 const SCEV *PhiScev = Expr ? Expr : SE->getSCEV(Phi); 1033 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev); 1034 1035 if (!AR) { 1036 LLVM_DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n"); 1037 return false; 1038 } 1039 1040 if (AR->getLoop() != TheLoop) { 1041 // FIXME: We should treat this as a uniform. Unfortunately, we 1042 // don't currently know how to handled uniform PHIs. 1043 LLVM_DEBUG( 1044 dbgs() << "LV: PHI is a recurrence with respect to an outer loop.\n"); 1045 return false; 1046 } 1047 1048 Value *StartValue = 1049 Phi->getIncomingValueForBlock(AR->getLoop()->getLoopPreheader()); 1050 const SCEV *Step = AR->getStepRecurrence(*SE); 1051 // Calculate the pointer stride and check if it is consecutive. 1052 // The stride may be a constant or a loop invariant integer value. 1053 const SCEVConstant *ConstStep = dyn_cast<SCEVConstant>(Step); 1054 if (!ConstStep && !SE->isLoopInvariant(Step, TheLoop)) 1055 return false; 1056 1057 if (PhiTy->isIntegerTy()) { 1058 D = InductionDescriptor(StartValue, IK_IntInduction, Step, /*BOp=*/nullptr, 1059 CastsToIgnore); 1060 return true; 1061 } 1062 1063 assert(PhiTy->isPointerTy() && "The PHI must be a pointer"); 1064 // Pointer induction should be a constant. 1065 if (!ConstStep) 1066 return false; 1067 1068 ConstantInt *CV = ConstStep->getValue(); 1069 Type *PointerElementType = PhiTy->getPointerElementType(); 1070 // The pointer stride cannot be determined if the pointer element type is not 1071 // sized. 1072 if (!PointerElementType->isSized()) 1073 return false; 1074 1075 const DataLayout &DL = Phi->getModule()->getDataLayout(); 1076 int64_t Size = static_cast<int64_t>(DL.getTypeAllocSize(PointerElementType)); 1077 if (!Size) 1078 return false; 1079 1080 int64_t CVSize = CV->getSExtValue(); 1081 if (CVSize % Size) 1082 return false; 1083 auto *StepValue = 1084 SE->getConstant(CV->getType(), CVSize / Size, true /* signed */); 1085 D = InductionDescriptor(StartValue, IK_PtrInduction, StepValue); 1086 return true; 1087 } 1088