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/Analysis/DemandedBits.h" 15 #include "llvm/Analysis/LoopInfo.h" 16 #include "llvm/Analysis/ScalarEvolution.h" 17 #include "llvm/Analysis/ScalarEvolutionExpressions.h" 18 #include "llvm/Analysis/ValueTracking.h" 19 #include "llvm/IR/Dominators.h" 20 #include "llvm/IR/Instructions.h" 21 #include "llvm/IR/Module.h" 22 #include "llvm/IR/PatternMatch.h" 23 #include "llvm/IR/ValueHandle.h" 24 #include "llvm/Support/Debug.h" 25 #include "llvm/Support/KnownBits.h" 26 27 #include <set> 28 29 using namespace llvm; 30 using namespace llvm::PatternMatch; 31 32 #define DEBUG_TYPE "iv-descriptors" 33 34 bool RecurrenceDescriptor::areAllUsesIn(Instruction *I, 35 SmallPtrSetImpl<Instruction *> &Set) { 36 for (const Use &Use : I->operands()) 37 if (!Set.count(dyn_cast<Instruction>(Use))) 38 return false; 39 return true; 40 } 41 42 bool RecurrenceDescriptor::isIntegerRecurrenceKind(RecurKind Kind) { 43 switch (Kind) { 44 default: 45 break; 46 case RecurKind::Add: 47 case RecurKind::Mul: 48 case RecurKind::Or: 49 case RecurKind::And: 50 case RecurKind::Xor: 51 case RecurKind::SMax: 52 case RecurKind::SMin: 53 case RecurKind::UMax: 54 case RecurKind::UMin: 55 case RecurKind::SelectICmp: 56 case RecurKind::SelectFCmp: 57 return true; 58 } 59 return false; 60 } 61 62 bool RecurrenceDescriptor::isFloatingPointRecurrenceKind(RecurKind Kind) { 63 return (Kind != RecurKind::None) && !isIntegerRecurrenceKind(Kind); 64 } 65 66 bool RecurrenceDescriptor::isArithmeticRecurrenceKind(RecurKind Kind) { 67 switch (Kind) { 68 default: 69 break; 70 case RecurKind::Add: 71 case RecurKind::Mul: 72 case RecurKind::FAdd: 73 case RecurKind::FMul: 74 case RecurKind::FMulAdd: 75 return true; 76 } 77 return false; 78 } 79 80 /// Determines if Phi may have been type-promoted. If Phi has a single user 81 /// that ANDs the Phi with a type mask, return the user. RT is updated to 82 /// account for the narrower bit width represented by the mask, and the AND 83 /// instruction is added to CI. 84 static Instruction *lookThroughAnd(PHINode *Phi, Type *&RT, 85 SmallPtrSetImpl<Instruction *> &Visited, 86 SmallPtrSetImpl<Instruction *> &CI) { 87 if (!Phi->hasOneUse()) 88 return Phi; 89 90 const APInt *M = nullptr; 91 Instruction *I, *J = cast<Instruction>(Phi->use_begin()->getUser()); 92 93 // Matches either I & 2^x-1 or 2^x-1 & I. If we find a match, we update RT 94 // with a new integer type of the corresponding bit width. 95 if (match(J, m_c_And(m_Instruction(I), m_APInt(M)))) { 96 int32_t Bits = (*M + 1).exactLogBase2(); 97 if (Bits > 0) { 98 RT = IntegerType::get(Phi->getContext(), Bits); 99 Visited.insert(Phi); 100 CI.insert(J); 101 return J; 102 } 103 } 104 return Phi; 105 } 106 107 /// Compute the minimal bit width needed to represent a reduction whose exit 108 /// instruction is given by Exit. 109 static std::pair<Type *, bool> computeRecurrenceType(Instruction *Exit, 110 DemandedBits *DB, 111 AssumptionCache *AC, 112 DominatorTree *DT) { 113 bool IsSigned = false; 114 const DataLayout &DL = Exit->getModule()->getDataLayout(); 115 uint64_t MaxBitWidth = DL.getTypeSizeInBits(Exit->getType()); 116 117 if (DB) { 118 // Use the demanded bits analysis to determine the bits that are live out 119 // of the exit instruction, rounding up to the nearest power of two. If the 120 // use of demanded bits results in a smaller bit width, we know the value 121 // must be positive (i.e., IsSigned = false), because if this were not the 122 // case, the sign bit would have been demanded. 123 auto Mask = DB->getDemandedBits(Exit); 124 MaxBitWidth = Mask.getBitWidth() - Mask.countLeadingZeros(); 125 } 126 127 if (MaxBitWidth == DL.getTypeSizeInBits(Exit->getType()) && AC && DT) { 128 // If demanded bits wasn't able to limit the bit width, we can try to use 129 // value tracking instead. This can be the case, for example, if the value 130 // may be negative. 131 auto NumSignBits = ComputeNumSignBits(Exit, DL, 0, AC, nullptr, DT); 132 auto NumTypeBits = DL.getTypeSizeInBits(Exit->getType()); 133 MaxBitWidth = NumTypeBits - NumSignBits; 134 KnownBits Bits = computeKnownBits(Exit, DL); 135 if (!Bits.isNonNegative()) { 136 // If the value is not known to be non-negative, we set IsSigned to true, 137 // meaning that we will use sext instructions instead of zext 138 // instructions to restore the original type. 139 IsSigned = true; 140 // Make sure at at least one sign bit is included in the result, so it 141 // will get properly sign-extended. 142 ++MaxBitWidth; 143 } 144 } 145 if (!isPowerOf2_64(MaxBitWidth)) 146 MaxBitWidth = NextPowerOf2(MaxBitWidth); 147 148 return std::make_pair(Type::getIntNTy(Exit->getContext(), MaxBitWidth), 149 IsSigned); 150 } 151 152 /// Collect cast instructions that can be ignored in the vectorizer's cost 153 /// model, given a reduction exit value and the minimal type in which the 154 // reduction can be represented. Also search casts to the recurrence type 155 // to find the minimum width used by the recurrence. 156 static void collectCastInstrs(Loop *TheLoop, Instruction *Exit, 157 Type *RecurrenceType, 158 SmallPtrSetImpl<Instruction *> &Casts, 159 unsigned &MinWidthCastToRecurTy) { 160 161 SmallVector<Instruction *, 8> Worklist; 162 SmallPtrSet<Instruction *, 8> Visited; 163 Worklist.push_back(Exit); 164 MinWidthCastToRecurTy = -1U; 165 166 while (!Worklist.empty()) { 167 Instruction *Val = Worklist.pop_back_val(); 168 Visited.insert(Val); 169 if (auto *Cast = dyn_cast<CastInst>(Val)) { 170 if (Cast->getSrcTy() == RecurrenceType) { 171 // If the source type of a cast instruction is equal to the recurrence 172 // type, it will be eliminated, and should be ignored in the vectorizer 173 // cost model. 174 Casts.insert(Cast); 175 continue; 176 } 177 if (Cast->getDestTy() == RecurrenceType) { 178 // The minimum width used by the recurrence is found by checking for 179 // casts on its operands. The minimum width is used by the vectorizer 180 // when finding the widest type for in-loop reductions without any 181 // loads/stores. 182 MinWidthCastToRecurTy = std::min<unsigned>( 183 MinWidthCastToRecurTy, Cast->getSrcTy()->getScalarSizeInBits()); 184 continue; 185 } 186 } 187 // Add all operands to the work list if they are loop-varying values that 188 // we haven't yet visited. 189 for (Value *O : cast<User>(Val)->operands()) 190 if (auto *I = dyn_cast<Instruction>(O)) 191 if (TheLoop->contains(I) && !Visited.count(I)) 192 Worklist.push_back(I); 193 } 194 } 195 196 // Check if a given Phi node can be recognized as an ordered reduction for 197 // vectorizing floating point operations without unsafe math. 198 static bool checkOrderedReduction(RecurKind Kind, Instruction *ExactFPMathInst, 199 Instruction *Exit, PHINode *Phi) { 200 // Currently only FAdd and FMulAdd are supported. 201 if (Kind != RecurKind::FAdd && Kind != RecurKind::FMulAdd) 202 return false; 203 204 if (Kind == RecurKind::FAdd && Exit->getOpcode() != Instruction::FAdd) 205 return false; 206 207 if (Kind == RecurKind::FMulAdd && 208 !RecurrenceDescriptor::isFMulAddIntrinsic(Exit)) 209 return false; 210 211 // Ensure the exit instruction has only one user other than the reduction PHI 212 if (Exit != ExactFPMathInst || Exit->hasNUsesOrMore(3)) 213 return false; 214 215 // The only pattern accepted is the one in which the reduction PHI 216 // is used as one of the operands of the exit instruction 217 auto *Op0 = Exit->getOperand(0); 218 auto *Op1 = Exit->getOperand(1); 219 if (Kind == RecurKind::FAdd && Op0 != Phi && Op1 != Phi) 220 return false; 221 if (Kind == RecurKind::FMulAdd && Exit->getOperand(2) != Phi) 222 return false; 223 224 LLVM_DEBUG(dbgs() << "LV: Found an ordered reduction: Phi: " << *Phi 225 << ", ExitInst: " << *Exit << "\n"); 226 227 return true; 228 } 229 230 bool RecurrenceDescriptor::AddReductionVar(PHINode *Phi, RecurKind Kind, 231 Loop *TheLoop, FastMathFlags FuncFMF, 232 RecurrenceDescriptor &RedDes, 233 DemandedBits *DB, 234 AssumptionCache *AC, 235 DominatorTree *DT) { 236 if (Phi->getNumIncomingValues() != 2) 237 return false; 238 239 // Reduction variables are only found in the loop header block. 240 if (Phi->getParent() != TheLoop->getHeader()) 241 return false; 242 243 // Obtain the reduction start value from the value that comes from the loop 244 // preheader. 245 Value *RdxStart = Phi->getIncomingValueForBlock(TheLoop->getLoopPreheader()); 246 247 // ExitInstruction is the single value which is used outside the loop. 248 // We only allow for a single reduction value to be used outside the loop. 249 // This includes users of the reduction, variables (which form a cycle 250 // which ends in the phi node). 251 Instruction *ExitInstruction = nullptr; 252 // Indicates that we found a reduction operation in our scan. 253 bool FoundReduxOp = false; 254 255 // We start with the PHI node and scan for all of the users of this 256 // instruction. All users must be instructions that can be used as reduction 257 // variables (such as ADD). We must have a single out-of-block user. The cycle 258 // must include the original PHI. 259 bool FoundStartPHI = false; 260 261 // To recognize min/max patterns formed by a icmp select sequence, we store 262 // the number of instruction we saw from the recognized min/max pattern, 263 // to make sure we only see exactly the two instructions. 264 unsigned NumCmpSelectPatternInst = 0; 265 InstDesc ReduxDesc(false, nullptr); 266 267 // Data used for determining if the recurrence has been type-promoted. 268 Type *RecurrenceType = Phi->getType(); 269 SmallPtrSet<Instruction *, 4> CastInsts; 270 unsigned MinWidthCastToRecurrenceType; 271 Instruction *Start = Phi; 272 bool IsSigned = false; 273 274 SmallPtrSet<Instruction *, 8> VisitedInsts; 275 SmallVector<Instruction *, 8> Worklist; 276 277 // Return early if the recurrence kind does not match the type of Phi. If the 278 // recurrence kind is arithmetic, we attempt to look through AND operations 279 // resulting from the type promotion performed by InstCombine. Vector 280 // operations are not limited to the legal integer widths, so we may be able 281 // to evaluate the reduction in the narrower width. 282 if (RecurrenceType->isFloatingPointTy()) { 283 if (!isFloatingPointRecurrenceKind(Kind)) 284 return false; 285 } else if (RecurrenceType->isIntegerTy()) { 286 if (!isIntegerRecurrenceKind(Kind)) 287 return false; 288 if (!isMinMaxRecurrenceKind(Kind)) 289 Start = lookThroughAnd(Phi, RecurrenceType, VisitedInsts, CastInsts); 290 } else { 291 // Pointer min/max may exist, but it is not supported as a reduction op. 292 return false; 293 } 294 295 Worklist.push_back(Start); 296 VisitedInsts.insert(Start); 297 298 // Start with all flags set because we will intersect this with the reduction 299 // flags from all the reduction operations. 300 FastMathFlags FMF = FastMathFlags::getFast(); 301 302 // The first instruction in the use-def chain of the Phi node that requires 303 // exact floating point operations. 304 Instruction *ExactFPMathInst = nullptr; 305 306 // A value in the reduction can be used: 307 // - By the reduction: 308 // - Reduction operation: 309 // - One use of reduction value (safe). 310 // - Multiple use of reduction value (not safe). 311 // - PHI: 312 // - All uses of the PHI must be the reduction (safe). 313 // - Otherwise, not safe. 314 // - By instructions outside of the loop (safe). 315 // * One value may have several outside users, but all outside 316 // uses must be of the same value. 317 // - By an instruction that is not part of the reduction (not safe). 318 // This is either: 319 // * An instruction type other than PHI or the reduction operation. 320 // * A PHI in the header other than the initial PHI. 321 while (!Worklist.empty()) { 322 Instruction *Cur = Worklist.pop_back_val(); 323 324 // No Users. 325 // If the instruction has no users then this is a broken chain and can't be 326 // a reduction variable. 327 if (Cur->use_empty()) 328 return false; 329 330 bool IsAPhi = isa<PHINode>(Cur); 331 332 // A header PHI use other than the original PHI. 333 if (Cur != Phi && IsAPhi && Cur->getParent() == Phi->getParent()) 334 return false; 335 336 // Reductions of instructions such as Div, and Sub is only possible if the 337 // LHS is the reduction variable. 338 if (!Cur->isCommutative() && !IsAPhi && !isa<SelectInst>(Cur) && 339 !isa<ICmpInst>(Cur) && !isa<FCmpInst>(Cur) && 340 !VisitedInsts.count(dyn_cast<Instruction>(Cur->getOperand(0)))) 341 return false; 342 343 // Any reduction instruction must be of one of the allowed kinds. We ignore 344 // the starting value (the Phi or an AND instruction if the Phi has been 345 // type-promoted). 346 if (Cur != Start) { 347 ReduxDesc = 348 isRecurrenceInstr(TheLoop, Phi, Cur, Kind, ReduxDesc, FuncFMF); 349 ExactFPMathInst = ExactFPMathInst == nullptr 350 ? ReduxDesc.getExactFPMathInst() 351 : ExactFPMathInst; 352 if (!ReduxDesc.isRecurrence()) 353 return false; 354 // FIXME: FMF is allowed on phi, but propagation is not handled correctly. 355 if (isa<FPMathOperator>(ReduxDesc.getPatternInst()) && !IsAPhi) { 356 FastMathFlags CurFMF = ReduxDesc.getPatternInst()->getFastMathFlags(); 357 if (auto *Sel = dyn_cast<SelectInst>(ReduxDesc.getPatternInst())) { 358 // Accept FMF on either fcmp or select of a min/max idiom. 359 // TODO: This is a hack to work-around the fact that FMF may not be 360 // assigned/propagated correctly. If that problem is fixed or we 361 // standardize on fmin/fmax via intrinsics, this can be removed. 362 if (auto *FCmp = dyn_cast<FCmpInst>(Sel->getCondition())) 363 CurFMF |= FCmp->getFastMathFlags(); 364 } 365 FMF &= CurFMF; 366 } 367 // Update this reduction kind if we matched a new instruction. 368 // TODO: Can we eliminate the need for a 2nd InstDesc by keeping 'Kind' 369 // state accurate while processing the worklist? 370 if (ReduxDesc.getRecKind() != RecurKind::None) 371 Kind = ReduxDesc.getRecKind(); 372 } 373 374 bool IsASelect = isa<SelectInst>(Cur); 375 376 // A conditional reduction operation must only have 2 or less uses in 377 // VisitedInsts. 378 if (IsASelect && (Kind == RecurKind::FAdd || Kind == RecurKind::FMul) && 379 hasMultipleUsesOf(Cur, VisitedInsts, 2)) 380 return false; 381 382 // A reduction operation must only have one use of the reduction value. 383 if (!IsAPhi && !IsASelect && !isMinMaxRecurrenceKind(Kind) && 384 !isSelectCmpRecurrenceKind(Kind) && 385 hasMultipleUsesOf(Cur, VisitedInsts, 1)) 386 return false; 387 388 // All inputs to a PHI node must be a reduction value. 389 if (IsAPhi && Cur != Phi && !areAllUsesIn(Cur, VisitedInsts)) 390 return false; 391 392 if ((isIntMinMaxRecurrenceKind(Kind) || Kind == RecurKind::SelectICmp) && 393 (isa<ICmpInst>(Cur) || isa<SelectInst>(Cur))) 394 ++NumCmpSelectPatternInst; 395 if ((isFPMinMaxRecurrenceKind(Kind) || Kind == RecurKind::SelectFCmp) && 396 (isa<FCmpInst>(Cur) || isa<SelectInst>(Cur))) 397 ++NumCmpSelectPatternInst; 398 399 // Check whether we found a reduction operator. 400 FoundReduxOp |= !IsAPhi && Cur != Start; 401 402 // Process users of current instruction. Push non-PHI nodes after PHI nodes 403 // onto the stack. This way we are going to have seen all inputs to PHI 404 // nodes once we get to them. 405 SmallVector<Instruction *, 8> NonPHIs; 406 SmallVector<Instruction *, 8> PHIs; 407 for (User *U : Cur->users()) { 408 Instruction *UI = cast<Instruction>(U); 409 410 // If the user is a call to llvm.fmuladd then the instruction can only be 411 // the final operand. 412 if (isFMulAddIntrinsic(UI)) 413 if (Cur == UI->getOperand(0) || Cur == UI->getOperand(1)) 414 return false; 415 416 // Check if we found the exit user. 417 BasicBlock *Parent = UI->getParent(); 418 if (!TheLoop->contains(Parent)) { 419 // If we already know this instruction is used externally, move on to 420 // the next user. 421 if (ExitInstruction == Cur) 422 continue; 423 424 // Exit if you find multiple values used outside or if the header phi 425 // node is being used. In this case the user uses the value of the 426 // previous iteration, in which case we would loose "VF-1" iterations of 427 // the reduction operation if we vectorize. 428 if (ExitInstruction != nullptr || Cur == Phi) 429 return false; 430 431 // The instruction used by an outside user must be the last instruction 432 // before we feed back to the reduction phi. Otherwise, we loose VF-1 433 // operations on the value. 434 if (!is_contained(Phi->operands(), Cur)) 435 return false; 436 437 ExitInstruction = Cur; 438 continue; 439 } 440 441 // Process instructions only once (termination). Each reduction cycle 442 // value must only be used once, except by phi nodes and min/max 443 // reductions which are represented as a cmp followed by a select. 444 InstDesc IgnoredVal(false, nullptr); 445 if (VisitedInsts.insert(UI).second) { 446 if (isa<PHINode>(UI)) 447 PHIs.push_back(UI); 448 else 449 NonPHIs.push_back(UI); 450 } else if (!isa<PHINode>(UI) && 451 ((!isa<FCmpInst>(UI) && !isa<ICmpInst>(UI) && 452 !isa<SelectInst>(UI)) || 453 (!isConditionalRdxPattern(Kind, UI).isRecurrence() && 454 !isSelectCmpPattern(TheLoop, Phi, UI, IgnoredVal) 455 .isRecurrence() && 456 !isMinMaxPattern(UI, Kind, IgnoredVal).isRecurrence()))) 457 return false; 458 459 // Remember that we completed the cycle. 460 if (UI == Phi) 461 FoundStartPHI = true; 462 } 463 Worklist.append(PHIs.begin(), PHIs.end()); 464 Worklist.append(NonPHIs.begin(), NonPHIs.end()); 465 } 466 467 // This means we have seen one but not the other instruction of the 468 // pattern or more than just a select and cmp. Zero implies that we saw a 469 // llvm.min/max instrinsic, which is always OK. 470 if (isMinMaxRecurrenceKind(Kind) && NumCmpSelectPatternInst != 2 && 471 NumCmpSelectPatternInst != 0) 472 return false; 473 474 if (isSelectCmpRecurrenceKind(Kind) && NumCmpSelectPatternInst != 1) 475 return false; 476 477 if (!FoundStartPHI || !FoundReduxOp || !ExitInstruction) 478 return false; 479 480 const bool IsOrdered = 481 checkOrderedReduction(Kind, ExactFPMathInst, ExitInstruction, Phi); 482 483 if (Start != Phi) { 484 // If the starting value is not the same as the phi node, we speculatively 485 // looked through an 'and' instruction when evaluating a potential 486 // arithmetic reduction to determine if it may have been type-promoted. 487 // 488 // We now compute the minimal bit width that is required to represent the 489 // reduction. If this is the same width that was indicated by the 'and', we 490 // can represent the reduction in the smaller type. The 'and' instruction 491 // will be eliminated since it will essentially be a cast instruction that 492 // can be ignore in the cost model. If we compute a different type than we 493 // did when evaluating the 'and', the 'and' will not be eliminated, and we 494 // will end up with different kinds of operations in the recurrence 495 // expression (e.g., IntegerAND, IntegerADD). We give up if this is 496 // the case. 497 // 498 // The vectorizer relies on InstCombine to perform the actual 499 // type-shrinking. It does this by inserting instructions to truncate the 500 // exit value of the reduction to the width indicated by RecurrenceType and 501 // then extend this value back to the original width. If IsSigned is false, 502 // a 'zext' instruction will be generated; otherwise, a 'sext' will be 503 // used. 504 // 505 // TODO: We should not rely on InstCombine to rewrite the reduction in the 506 // smaller type. We should just generate a correctly typed expression 507 // to begin with. 508 Type *ComputedType; 509 std::tie(ComputedType, IsSigned) = 510 computeRecurrenceType(ExitInstruction, DB, AC, DT); 511 if (ComputedType != RecurrenceType) 512 return false; 513 } 514 515 // Collect cast instructions and the minimum width used by the recurrence. 516 // If the starting value is not the same as the phi node and the computed 517 // recurrence type is equal to the recurrence type, the recurrence expression 518 // will be represented in a narrower or wider type. If there are any cast 519 // instructions that will be unnecessary, collect them in CastsFromRecurTy. 520 // Note that the 'and' instruction was already included in this list. 521 // 522 // TODO: A better way to represent this may be to tag in some way all the 523 // instructions that are a part of the reduction. The vectorizer cost 524 // model could then apply the recurrence type to these instructions, 525 // without needing a white list of instructions to ignore. 526 // This may also be useful for the inloop reductions, if it can be 527 // kept simple enough. 528 collectCastInstrs(TheLoop, ExitInstruction, RecurrenceType, CastInsts, 529 MinWidthCastToRecurrenceType); 530 531 // We found a reduction var if we have reached the original phi node and we 532 // only have a single instruction with out-of-loop users. 533 534 // The ExitInstruction(Instruction which is allowed to have out-of-loop users) 535 // is saved as part of the RecurrenceDescriptor. 536 537 // Save the description of this reduction variable. 538 RecurrenceDescriptor RD(RdxStart, ExitInstruction, Kind, FMF, ExactFPMathInst, 539 RecurrenceType, IsSigned, IsOrdered, CastInsts, 540 MinWidthCastToRecurrenceType); 541 RedDes = RD; 542 543 return true; 544 } 545 546 // We are looking for loops that do something like this: 547 // int r = 0; 548 // for (int i = 0; i < n; i++) { 549 // if (src[i] > 3) 550 // r = 3; 551 // } 552 // where the reduction value (r) only has two states, in this example 0 or 3. 553 // The generated LLVM IR for this type of loop will be like this: 554 // for.body: 555 // %r = phi i32 [ %spec.select, %for.body ], [ 0, %entry ] 556 // ... 557 // %cmp = icmp sgt i32 %5, 3 558 // %spec.select = select i1 %cmp, i32 3, i32 %r 559 // ... 560 // In general we can support vectorization of loops where 'r' flips between 561 // any two non-constants, provided they are loop invariant. The only thing 562 // we actually care about at the end of the loop is whether or not any lane 563 // in the selected vector is different from the start value. The final 564 // across-vector reduction after the loop simply involves choosing the start 565 // value if nothing changed (0 in the example above) or the other selected 566 // value (3 in the example above). 567 RecurrenceDescriptor::InstDesc 568 RecurrenceDescriptor::isSelectCmpPattern(Loop *Loop, PHINode *OrigPhi, 569 Instruction *I, InstDesc &Prev) { 570 // We must handle the select(cmp(),x,y) as a single instruction. Advance to 571 // the select. 572 CmpInst::Predicate Pred; 573 if (match(I, m_OneUse(m_Cmp(Pred, m_Value(), m_Value())))) { 574 if (auto *Select = dyn_cast<SelectInst>(*I->user_begin())) 575 return InstDesc(Select, Prev.getRecKind()); 576 } 577 578 // Only match select with single use cmp condition. 579 if (!match(I, m_Select(m_OneUse(m_Cmp(Pred, m_Value(), m_Value())), m_Value(), 580 m_Value()))) 581 return InstDesc(false, I); 582 583 SelectInst *SI = cast<SelectInst>(I); 584 Value *NonPhi = nullptr; 585 586 if (OrigPhi == dyn_cast<PHINode>(SI->getTrueValue())) 587 NonPhi = SI->getFalseValue(); 588 else if (OrigPhi == dyn_cast<PHINode>(SI->getFalseValue())) 589 NonPhi = SI->getTrueValue(); 590 else 591 return InstDesc(false, I); 592 593 // We are looking for selects of the form: 594 // select(cmp(), phi, loop_invariant) or 595 // select(cmp(), loop_invariant, phi) 596 if (!Loop->isLoopInvariant(NonPhi)) 597 return InstDesc(false, I); 598 599 return InstDesc(I, isa<ICmpInst>(I->getOperand(0)) ? RecurKind::SelectICmp 600 : RecurKind::SelectFCmp); 601 } 602 603 RecurrenceDescriptor::InstDesc 604 RecurrenceDescriptor::isMinMaxPattern(Instruction *I, RecurKind Kind, 605 const InstDesc &Prev) { 606 assert((isa<CmpInst>(I) || isa<SelectInst>(I) || isa<CallInst>(I)) && 607 "Expected a cmp or select or call instruction"); 608 if (!isMinMaxRecurrenceKind(Kind)) 609 return InstDesc(false, I); 610 611 // We must handle the select(cmp()) as a single instruction. Advance to the 612 // select. 613 CmpInst::Predicate Pred; 614 if (match(I, m_OneUse(m_Cmp(Pred, m_Value(), m_Value())))) { 615 if (auto *Select = dyn_cast<SelectInst>(*I->user_begin())) 616 return InstDesc(Select, Prev.getRecKind()); 617 } 618 619 // Only match select with single use cmp condition, or a min/max intrinsic. 620 if (!isa<IntrinsicInst>(I) && 621 !match(I, m_Select(m_OneUse(m_Cmp(Pred, m_Value(), m_Value())), m_Value(), 622 m_Value()))) 623 return InstDesc(false, I); 624 625 // Look for a min/max pattern. 626 if (match(I, m_UMin(m_Value(), m_Value()))) 627 return InstDesc(Kind == RecurKind::UMin, I); 628 if (match(I, m_UMax(m_Value(), m_Value()))) 629 return InstDesc(Kind == RecurKind::UMax, I); 630 if (match(I, m_SMax(m_Value(), m_Value()))) 631 return InstDesc(Kind == RecurKind::SMax, I); 632 if (match(I, m_SMin(m_Value(), m_Value()))) 633 return InstDesc(Kind == RecurKind::SMin, I); 634 if (match(I, m_OrdFMin(m_Value(), m_Value()))) 635 return InstDesc(Kind == RecurKind::FMin, I); 636 if (match(I, m_OrdFMax(m_Value(), m_Value()))) 637 return InstDesc(Kind == RecurKind::FMax, I); 638 if (match(I, m_UnordFMin(m_Value(), m_Value()))) 639 return InstDesc(Kind == RecurKind::FMin, I); 640 if (match(I, m_UnordFMax(m_Value(), m_Value()))) 641 return InstDesc(Kind == RecurKind::FMax, I); 642 if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(), m_Value()))) 643 return InstDesc(Kind == RecurKind::FMin, I); 644 if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(), m_Value()))) 645 return InstDesc(Kind == RecurKind::FMax, I); 646 647 return InstDesc(false, I); 648 } 649 650 /// Returns true if the select instruction has users in the compare-and-add 651 /// reduction pattern below. The select instruction argument is the last one 652 /// in the sequence. 653 /// 654 /// %sum.1 = phi ... 655 /// ... 656 /// %cmp = fcmp pred %0, %CFP 657 /// %add = fadd %0, %sum.1 658 /// %sum.2 = select %cmp, %add, %sum.1 659 RecurrenceDescriptor::InstDesc 660 RecurrenceDescriptor::isConditionalRdxPattern(RecurKind Kind, Instruction *I) { 661 SelectInst *SI = dyn_cast<SelectInst>(I); 662 if (!SI) 663 return InstDesc(false, I); 664 665 CmpInst *CI = dyn_cast<CmpInst>(SI->getCondition()); 666 // Only handle single use cases for now. 667 if (!CI || !CI->hasOneUse()) 668 return InstDesc(false, I); 669 670 Value *TrueVal = SI->getTrueValue(); 671 Value *FalseVal = SI->getFalseValue(); 672 // Handle only when either of operands of select instruction is a PHI 673 // node for now. 674 if ((isa<PHINode>(*TrueVal) && isa<PHINode>(*FalseVal)) || 675 (!isa<PHINode>(*TrueVal) && !isa<PHINode>(*FalseVal))) 676 return InstDesc(false, I); 677 678 Instruction *I1 = 679 isa<PHINode>(*TrueVal) ? dyn_cast<Instruction>(FalseVal) 680 : dyn_cast<Instruction>(TrueVal); 681 if (!I1 || !I1->isBinaryOp()) 682 return InstDesc(false, I); 683 684 Value *Op1, *Op2; 685 if ((m_FAdd(m_Value(Op1), m_Value(Op2)).match(I1) || 686 m_FSub(m_Value(Op1), m_Value(Op2)).match(I1)) && 687 I1->isFast()) 688 return InstDesc(Kind == RecurKind::FAdd, SI); 689 690 if (m_FMul(m_Value(Op1), m_Value(Op2)).match(I1) && (I1->isFast())) 691 return InstDesc(Kind == RecurKind::FMul, SI); 692 693 return InstDesc(false, I); 694 } 695 696 RecurrenceDescriptor::InstDesc 697 RecurrenceDescriptor::isRecurrenceInstr(Loop *L, PHINode *OrigPhi, 698 Instruction *I, RecurKind Kind, 699 InstDesc &Prev, FastMathFlags FuncFMF) { 700 assert(Prev.getRecKind() == RecurKind::None || Prev.getRecKind() == Kind); 701 switch (I->getOpcode()) { 702 default: 703 return InstDesc(false, I); 704 case Instruction::PHI: 705 return InstDesc(I, Prev.getRecKind(), Prev.getExactFPMathInst()); 706 case Instruction::Sub: 707 case Instruction::Add: 708 return InstDesc(Kind == RecurKind::Add, I); 709 case Instruction::Mul: 710 return InstDesc(Kind == RecurKind::Mul, I); 711 case Instruction::And: 712 return InstDesc(Kind == RecurKind::And, I); 713 case Instruction::Or: 714 return InstDesc(Kind == RecurKind::Or, I); 715 case Instruction::Xor: 716 return InstDesc(Kind == RecurKind::Xor, I); 717 case Instruction::FDiv: 718 case Instruction::FMul: 719 return InstDesc(Kind == RecurKind::FMul, I, 720 I->hasAllowReassoc() ? nullptr : I); 721 case Instruction::FSub: 722 case Instruction::FAdd: 723 return InstDesc(Kind == RecurKind::FAdd, I, 724 I->hasAllowReassoc() ? nullptr : I); 725 case Instruction::Select: 726 if (Kind == RecurKind::FAdd || Kind == RecurKind::FMul) 727 return isConditionalRdxPattern(Kind, I); 728 LLVM_FALLTHROUGH; 729 case Instruction::FCmp: 730 case Instruction::ICmp: 731 case Instruction::Call: 732 if (isSelectCmpRecurrenceKind(Kind)) 733 return isSelectCmpPattern(L, OrigPhi, I, Prev); 734 if (isIntMinMaxRecurrenceKind(Kind) || 735 (((FuncFMF.noNaNs() && FuncFMF.noSignedZeros()) || 736 (isa<FPMathOperator>(I) && I->hasNoNaNs() && 737 I->hasNoSignedZeros())) && 738 isFPMinMaxRecurrenceKind(Kind))) 739 return isMinMaxPattern(I, Kind, Prev); 740 else if (isFMulAddIntrinsic(I)) 741 return InstDesc(Kind == RecurKind::FMulAdd, I, 742 I->hasAllowReassoc() ? nullptr : I); 743 return InstDesc(false, I); 744 } 745 } 746 747 bool RecurrenceDescriptor::hasMultipleUsesOf( 748 Instruction *I, SmallPtrSetImpl<Instruction *> &Insts, 749 unsigned MaxNumUses) { 750 unsigned NumUses = 0; 751 for (const Use &U : I->operands()) { 752 if (Insts.count(dyn_cast<Instruction>(U))) 753 ++NumUses; 754 if (NumUses > MaxNumUses) 755 return true; 756 } 757 758 return false; 759 } 760 761 bool RecurrenceDescriptor::isReductionPHI(PHINode *Phi, Loop *TheLoop, 762 RecurrenceDescriptor &RedDes, 763 DemandedBits *DB, AssumptionCache *AC, 764 DominatorTree *DT) { 765 BasicBlock *Header = TheLoop->getHeader(); 766 Function &F = *Header->getParent(); 767 FastMathFlags FMF; 768 FMF.setNoNaNs( 769 F.getFnAttribute("no-nans-fp-math").getValueAsBool()); 770 FMF.setNoSignedZeros( 771 F.getFnAttribute("no-signed-zeros-fp-math").getValueAsBool()); 772 773 if (AddReductionVar(Phi, RecurKind::Add, TheLoop, FMF, RedDes, DB, AC, DT)) { 774 LLVM_DEBUG(dbgs() << "Found an ADD reduction PHI." << *Phi << "\n"); 775 return true; 776 } 777 if (AddReductionVar(Phi, RecurKind::Mul, TheLoop, FMF, RedDes, DB, AC, DT)) { 778 LLVM_DEBUG(dbgs() << "Found a MUL reduction PHI." << *Phi << "\n"); 779 return true; 780 } 781 if (AddReductionVar(Phi, RecurKind::Or, TheLoop, FMF, RedDes, DB, AC, DT)) { 782 LLVM_DEBUG(dbgs() << "Found an OR reduction PHI." << *Phi << "\n"); 783 return true; 784 } 785 if (AddReductionVar(Phi, RecurKind::And, TheLoop, FMF, RedDes, DB, AC, DT)) { 786 LLVM_DEBUG(dbgs() << "Found an AND reduction PHI." << *Phi << "\n"); 787 return true; 788 } 789 if (AddReductionVar(Phi, RecurKind::Xor, TheLoop, FMF, RedDes, DB, AC, DT)) { 790 LLVM_DEBUG(dbgs() << "Found a XOR reduction PHI." << *Phi << "\n"); 791 return true; 792 } 793 if (AddReductionVar(Phi, RecurKind::SMax, TheLoop, FMF, RedDes, DB, AC, DT)) { 794 LLVM_DEBUG(dbgs() << "Found a SMAX reduction PHI." << *Phi << "\n"); 795 return true; 796 } 797 if (AddReductionVar(Phi, RecurKind::SMin, TheLoop, FMF, RedDes, DB, AC, DT)) { 798 LLVM_DEBUG(dbgs() << "Found a SMIN reduction PHI." << *Phi << "\n"); 799 return true; 800 } 801 if (AddReductionVar(Phi, RecurKind::UMax, TheLoop, FMF, RedDes, DB, AC, DT)) { 802 LLVM_DEBUG(dbgs() << "Found a UMAX reduction PHI." << *Phi << "\n"); 803 return true; 804 } 805 if (AddReductionVar(Phi, RecurKind::UMin, TheLoop, FMF, RedDes, DB, AC, DT)) { 806 LLVM_DEBUG(dbgs() << "Found a UMIN reduction PHI." << *Phi << "\n"); 807 return true; 808 } 809 if (AddReductionVar(Phi, RecurKind::SelectICmp, TheLoop, FMF, RedDes, DB, AC, 810 DT)) { 811 LLVM_DEBUG(dbgs() << "Found an integer conditional select reduction PHI." 812 << *Phi << "\n"); 813 return true; 814 } 815 if (AddReductionVar(Phi, RecurKind::FMul, TheLoop, FMF, RedDes, DB, AC, DT)) { 816 LLVM_DEBUG(dbgs() << "Found an FMult reduction PHI." << *Phi << "\n"); 817 return true; 818 } 819 if (AddReductionVar(Phi, RecurKind::FAdd, TheLoop, FMF, RedDes, DB, AC, DT)) { 820 LLVM_DEBUG(dbgs() << "Found an FAdd reduction PHI." << *Phi << "\n"); 821 return true; 822 } 823 if (AddReductionVar(Phi, RecurKind::FMax, TheLoop, FMF, RedDes, DB, AC, DT)) { 824 LLVM_DEBUG(dbgs() << "Found a float MAX reduction PHI." << *Phi << "\n"); 825 return true; 826 } 827 if (AddReductionVar(Phi, RecurKind::FMin, TheLoop, FMF, RedDes, DB, AC, DT)) { 828 LLVM_DEBUG(dbgs() << "Found a float MIN reduction PHI." << *Phi << "\n"); 829 return true; 830 } 831 if (AddReductionVar(Phi, RecurKind::SelectFCmp, TheLoop, FMF, RedDes, DB, AC, 832 DT)) { 833 LLVM_DEBUG(dbgs() << "Found a float conditional select reduction PHI." 834 << " PHI." << *Phi << "\n"); 835 return true; 836 } 837 if (AddReductionVar(Phi, RecurKind::FMulAdd, TheLoop, FMF, RedDes, DB, AC, 838 DT)) { 839 LLVM_DEBUG(dbgs() << "Found an FMulAdd reduction PHI." << *Phi << "\n"); 840 return true; 841 } 842 // Not a reduction of known type. 843 return false; 844 } 845 846 bool RecurrenceDescriptor::isFirstOrderRecurrence( 847 PHINode *Phi, Loop *TheLoop, 848 MapVector<Instruction *, Instruction *> &SinkAfter, DominatorTree *DT) { 849 850 // Ensure the phi node is in the loop header and has two incoming values. 851 if (Phi->getParent() != TheLoop->getHeader() || 852 Phi->getNumIncomingValues() != 2) 853 return false; 854 855 // Ensure the loop has a preheader and a single latch block. The loop 856 // vectorizer will need the latch to set up the next iteration of the loop. 857 auto *Preheader = TheLoop->getLoopPreheader(); 858 auto *Latch = TheLoop->getLoopLatch(); 859 if (!Preheader || !Latch) 860 return false; 861 862 // Ensure the phi node's incoming blocks are the loop preheader and latch. 863 if (Phi->getBasicBlockIndex(Preheader) < 0 || 864 Phi->getBasicBlockIndex(Latch) < 0) 865 return false; 866 867 // Get the previous value. The previous value comes from the latch edge while 868 // the initial value comes form the preheader edge. 869 auto *Previous = dyn_cast<Instruction>(Phi->getIncomingValueForBlock(Latch)); 870 if (!Previous || !TheLoop->contains(Previous) || isa<PHINode>(Previous) || 871 SinkAfter.count(Previous)) // Cannot rely on dominance due to motion. 872 return false; 873 874 // Ensure every user of the phi node (recursively) is dominated by the 875 // previous value. The dominance requirement ensures the loop vectorizer will 876 // not need to vectorize the initial value prior to the first iteration of the 877 // loop. 878 // TODO: Consider extending this sinking to handle memory instructions. 879 880 // We optimistically assume we can sink all users after Previous. Keep a set 881 // of instructions to sink after Previous ordered by dominance in the common 882 // basic block. It will be applied to SinkAfter if all users can be sunk. 883 auto CompareByComesBefore = [](const Instruction *A, const Instruction *B) { 884 return A->comesBefore(B); 885 }; 886 std::set<Instruction *, decltype(CompareByComesBefore)> InstrsToSink( 887 CompareByComesBefore); 888 889 BasicBlock *PhiBB = Phi->getParent(); 890 SmallVector<Instruction *, 8> WorkList; 891 auto TryToPushSinkCandidate = [&](Instruction *SinkCandidate) { 892 // Already sunk SinkCandidate. 893 if (SinkCandidate->getParent() == PhiBB && 894 InstrsToSink.find(SinkCandidate) != InstrsToSink.end()) 895 return true; 896 897 // Cyclic dependence. 898 if (Previous == SinkCandidate) 899 return false; 900 901 if (DT->dominates(Previous, 902 SinkCandidate)) // We already are good w/o sinking. 903 return true; 904 905 if (SinkCandidate->getParent() != PhiBB || 906 SinkCandidate->mayHaveSideEffects() || 907 SinkCandidate->mayReadFromMemory() || SinkCandidate->isTerminator()) 908 return false; 909 910 // Try to sink an instruction after the 'deepest' previous instruction, 911 // which has multiple operands for first order recurrences. 912 auto It = SinkAfter.find(SinkCandidate); 913 if (It != SinkAfter.end()) { 914 auto LastPrev = It->second; 915 if (LastPrev->getParent() != Previous->getParent()) 916 return false; 917 918 // If LastPrev comes after the current Previous, SinkCandidate already 919 // gets sunk past Previous and nothing left to do. 920 return Previous->comesBefore(LastPrev); 921 } 922 923 // If we reach a PHI node that is not dominated by Previous, we reached a 924 // header PHI. No need for sinking. 925 if (isa<PHINode>(SinkCandidate)) 926 return true; 927 928 // Sink User tentatively and check its users 929 InstrsToSink.insert(SinkCandidate); 930 WorkList.push_back(SinkCandidate); 931 return true; 932 }; 933 934 WorkList.push_back(Phi); 935 // Try to recursively sink instructions and their users after Previous. 936 while (!WorkList.empty()) { 937 Instruction *Current = WorkList.pop_back_val(); 938 for (User *User : Current->users()) { 939 if (!TryToPushSinkCandidate(cast<Instruction>(User))) 940 return false; 941 } 942 } 943 944 // We can sink all users of Phi. Update the mapping. 945 for (Instruction *I : InstrsToSink) { 946 SinkAfter[I] = Previous; 947 Previous = I; 948 } 949 return true; 950 } 951 952 /// This function returns the identity element (or neutral element) for 953 /// the operation K. 954 Value *RecurrenceDescriptor::getRecurrenceIdentity(RecurKind K, Type *Tp, 955 FastMathFlags FMF) const { 956 switch (K) { 957 case RecurKind::Xor: 958 case RecurKind::Add: 959 case RecurKind::Or: 960 // Adding, Xoring, Oring zero to a number does not change it. 961 return ConstantInt::get(Tp, 0); 962 case RecurKind::Mul: 963 // Multiplying a number by 1 does not change it. 964 return ConstantInt::get(Tp, 1); 965 case RecurKind::And: 966 // AND-ing a number with an all-1 value does not change it. 967 return ConstantInt::get(Tp, -1, true); 968 case RecurKind::FMul: 969 // Multiplying a number by 1 does not change it. 970 return ConstantFP::get(Tp, 1.0L); 971 case RecurKind::FMulAdd: 972 case RecurKind::FAdd: 973 // Adding zero to a number does not change it. 974 // FIXME: Ideally we should not need to check FMF for FAdd and should always 975 // use -0.0. However, this will currently result in mixed vectors of 0.0/-0.0. 976 // Instead, we should ensure that 1) the FMF from FAdd are propagated to the PHI 977 // nodes where possible, and 2) PHIs with the nsz flag + -0.0 use 0.0. This would 978 // mean we can then remove the check for noSignedZeros() below (see D98963). 979 if (FMF.noSignedZeros()) 980 return ConstantFP::get(Tp, 0.0L); 981 return ConstantFP::get(Tp, -0.0L); 982 case RecurKind::UMin: 983 return ConstantInt::get(Tp, -1); 984 case RecurKind::UMax: 985 return ConstantInt::get(Tp, 0); 986 case RecurKind::SMin: 987 return ConstantInt::get(Tp, 988 APInt::getSignedMaxValue(Tp->getIntegerBitWidth())); 989 case RecurKind::SMax: 990 return ConstantInt::get(Tp, 991 APInt::getSignedMinValue(Tp->getIntegerBitWidth())); 992 case RecurKind::FMin: 993 return ConstantFP::getInfinity(Tp, true); 994 case RecurKind::FMax: 995 return ConstantFP::getInfinity(Tp, false); 996 case RecurKind::SelectICmp: 997 case RecurKind::SelectFCmp: 998 return getRecurrenceStartValue(); 999 break; 1000 default: 1001 llvm_unreachable("Unknown recurrence kind"); 1002 } 1003 } 1004 1005 unsigned RecurrenceDescriptor::getOpcode(RecurKind Kind) { 1006 switch (Kind) { 1007 case RecurKind::Add: 1008 return Instruction::Add; 1009 case RecurKind::Mul: 1010 return Instruction::Mul; 1011 case RecurKind::Or: 1012 return Instruction::Or; 1013 case RecurKind::And: 1014 return Instruction::And; 1015 case RecurKind::Xor: 1016 return Instruction::Xor; 1017 case RecurKind::FMul: 1018 return Instruction::FMul; 1019 case RecurKind::FMulAdd: 1020 case RecurKind::FAdd: 1021 return Instruction::FAdd; 1022 case RecurKind::SMax: 1023 case RecurKind::SMin: 1024 case RecurKind::UMax: 1025 case RecurKind::UMin: 1026 case RecurKind::SelectICmp: 1027 return Instruction::ICmp; 1028 case RecurKind::FMax: 1029 case RecurKind::FMin: 1030 case RecurKind::SelectFCmp: 1031 return Instruction::FCmp; 1032 default: 1033 llvm_unreachable("Unknown recurrence operation"); 1034 } 1035 } 1036 1037 SmallVector<Instruction *, 4> 1038 RecurrenceDescriptor::getReductionOpChain(PHINode *Phi, Loop *L) const { 1039 SmallVector<Instruction *, 4> ReductionOperations; 1040 unsigned RedOp = getOpcode(Kind); 1041 1042 // Search down from the Phi to the LoopExitInstr, looking for instructions 1043 // with a single user of the correct type for the reduction. 1044 1045 // Note that we check that the type of the operand is correct for each item in 1046 // the chain, including the last (the loop exit value). This can come up from 1047 // sub, which would otherwise be treated as an add reduction. MinMax also need 1048 // to check for a pair of icmp/select, for which we use getNextInstruction and 1049 // isCorrectOpcode functions to step the right number of instruction, and 1050 // check the icmp/select pair. 1051 // FIXME: We also do not attempt to look through Select's yet, which might 1052 // be part of the reduction chain, or attempt to looks through And's to find a 1053 // smaller bitwidth. Subs are also currently not allowed (which are usually 1054 // treated as part of a add reduction) as they are expected to generally be 1055 // more expensive than out-of-loop reductions, and need to be costed more 1056 // carefully. 1057 unsigned ExpectedUses = 1; 1058 if (RedOp == Instruction::ICmp || RedOp == Instruction::FCmp) 1059 ExpectedUses = 2; 1060 1061 auto getNextInstruction = [&](Instruction *Cur) -> Instruction * { 1062 for (auto User : Cur->users()) { 1063 Instruction *UI = cast<Instruction>(User); 1064 if (isa<PHINode>(UI)) 1065 continue; 1066 if (RedOp == Instruction::ICmp || RedOp == Instruction::FCmp) { 1067 // We are expecting a icmp/select pair, which we go to the next select 1068 // instruction if we can. We already know that Cur has 2 uses. 1069 if (isa<SelectInst>(UI)) 1070 return UI; 1071 continue; 1072 } 1073 return UI; 1074 } 1075 return nullptr; 1076 }; 1077 auto isCorrectOpcode = [&](Instruction *Cur) { 1078 if (RedOp == Instruction::ICmp || RedOp == Instruction::FCmp) { 1079 Value *LHS, *RHS; 1080 return SelectPatternResult::isMinOrMax( 1081 matchSelectPattern(Cur, LHS, RHS).Flavor); 1082 } 1083 // Recognize a call to the llvm.fmuladd intrinsic. 1084 if (isFMulAddIntrinsic(Cur)) 1085 return true; 1086 1087 return Cur->getOpcode() == RedOp; 1088 }; 1089 1090 // Attempt to look through Phis which are part of the reduction chain 1091 unsigned ExtraPhiUses = 0; 1092 Instruction *RdxInstr = LoopExitInstr; 1093 if (auto ExitPhi = dyn_cast<PHINode>(LoopExitInstr)) { 1094 if (ExitPhi->getNumIncomingValues() != 2) 1095 return {}; 1096 1097 Instruction *Inc0 = dyn_cast<Instruction>(ExitPhi->getIncomingValue(0)); 1098 Instruction *Inc1 = dyn_cast<Instruction>(ExitPhi->getIncomingValue(1)); 1099 1100 Instruction *Chain = nullptr; 1101 if (Inc0 == Phi) 1102 Chain = Inc1; 1103 else if (Inc1 == Phi) 1104 Chain = Inc0; 1105 else 1106 return {}; 1107 1108 RdxInstr = Chain; 1109 ExtraPhiUses = 1; 1110 } 1111 1112 // The loop exit instruction we check first (as a quick test) but add last. We 1113 // check the opcode is correct (and dont allow them to be Subs) and that they 1114 // have expected to have the expected number of uses. They will have one use 1115 // from the phi and one from a LCSSA value, no matter the type. 1116 if (!isCorrectOpcode(RdxInstr) || !LoopExitInstr->hasNUses(2)) 1117 return {}; 1118 1119 // Check that the Phi has one (or two for min/max) uses, plus an extra use 1120 // for conditional reductions. 1121 if (!Phi->hasNUses(ExpectedUses + ExtraPhiUses)) 1122 return {}; 1123 1124 Instruction *Cur = getNextInstruction(Phi); 1125 1126 // Each other instruction in the chain should have the expected number of uses 1127 // and be the correct opcode. 1128 while (Cur != RdxInstr) { 1129 if (!Cur || !isCorrectOpcode(Cur) || !Cur->hasNUses(ExpectedUses)) 1130 return {}; 1131 1132 ReductionOperations.push_back(Cur); 1133 Cur = getNextInstruction(Cur); 1134 } 1135 1136 ReductionOperations.push_back(Cur); 1137 return ReductionOperations; 1138 } 1139 1140 InductionDescriptor::InductionDescriptor(Value *Start, InductionKind K, 1141 const SCEV *Step, BinaryOperator *BOp, 1142 Type *ElementType, 1143 SmallVectorImpl<Instruction *> *Casts) 1144 : StartValue(Start), IK(K), Step(Step), InductionBinOp(BOp), 1145 ElementType(ElementType) { 1146 assert(IK != IK_NoInduction && "Not an induction"); 1147 1148 // Start value type should match the induction kind and the value 1149 // itself should not be null. 1150 assert(StartValue && "StartValue is null"); 1151 assert((IK != IK_PtrInduction || StartValue->getType()->isPointerTy()) && 1152 "StartValue is not a pointer for pointer induction"); 1153 assert((IK != IK_IntInduction || StartValue->getType()->isIntegerTy()) && 1154 "StartValue is not an integer for integer induction"); 1155 1156 // Check the Step Value. It should be non-zero integer value. 1157 assert((!getConstIntStepValue() || !getConstIntStepValue()->isZero()) && 1158 "Step value is zero"); 1159 1160 assert((IK != IK_PtrInduction || getConstIntStepValue()) && 1161 "Step value should be constant for pointer induction"); 1162 assert((IK == IK_FpInduction || Step->getType()->isIntegerTy()) && 1163 "StepValue is not an integer"); 1164 1165 assert((IK != IK_FpInduction || Step->getType()->isFloatingPointTy()) && 1166 "StepValue is not FP for FpInduction"); 1167 assert((IK != IK_FpInduction || 1168 (InductionBinOp && 1169 (InductionBinOp->getOpcode() == Instruction::FAdd || 1170 InductionBinOp->getOpcode() == Instruction::FSub))) && 1171 "Binary opcode should be specified for FP induction"); 1172 1173 if (IK == IK_PtrInduction) 1174 assert(ElementType && "Pointer induction must have element type"); 1175 else 1176 assert(!ElementType && "Non-pointer induction cannot have element type"); 1177 1178 if (Casts) { 1179 for (auto &Inst : *Casts) { 1180 RedundantCasts.push_back(Inst); 1181 } 1182 } 1183 } 1184 1185 ConstantInt *InductionDescriptor::getConstIntStepValue() const { 1186 if (isa<SCEVConstant>(Step)) 1187 return dyn_cast<ConstantInt>(cast<SCEVConstant>(Step)->getValue()); 1188 return nullptr; 1189 } 1190 1191 bool InductionDescriptor::isFPInductionPHI(PHINode *Phi, const Loop *TheLoop, 1192 ScalarEvolution *SE, 1193 InductionDescriptor &D) { 1194 1195 // Here we only handle FP induction variables. 1196 assert(Phi->getType()->isFloatingPointTy() && "Unexpected Phi type"); 1197 1198 if (TheLoop->getHeader() != Phi->getParent()) 1199 return false; 1200 1201 // The loop may have multiple entrances or multiple exits; we can analyze 1202 // this phi if it has a unique entry value and a unique backedge value. 1203 if (Phi->getNumIncomingValues() != 2) 1204 return false; 1205 Value *BEValue = nullptr, *StartValue = nullptr; 1206 if (TheLoop->contains(Phi->getIncomingBlock(0))) { 1207 BEValue = Phi->getIncomingValue(0); 1208 StartValue = Phi->getIncomingValue(1); 1209 } else { 1210 assert(TheLoop->contains(Phi->getIncomingBlock(1)) && 1211 "Unexpected Phi node in the loop"); 1212 BEValue = Phi->getIncomingValue(1); 1213 StartValue = Phi->getIncomingValue(0); 1214 } 1215 1216 BinaryOperator *BOp = dyn_cast<BinaryOperator>(BEValue); 1217 if (!BOp) 1218 return false; 1219 1220 Value *Addend = nullptr; 1221 if (BOp->getOpcode() == Instruction::FAdd) { 1222 if (BOp->getOperand(0) == Phi) 1223 Addend = BOp->getOperand(1); 1224 else if (BOp->getOperand(1) == Phi) 1225 Addend = BOp->getOperand(0); 1226 } else if (BOp->getOpcode() == Instruction::FSub) 1227 if (BOp->getOperand(0) == Phi) 1228 Addend = BOp->getOperand(1); 1229 1230 if (!Addend) 1231 return false; 1232 1233 // The addend should be loop invariant 1234 if (auto *I = dyn_cast<Instruction>(Addend)) 1235 if (TheLoop->contains(I)) 1236 return false; 1237 1238 // FP Step has unknown SCEV 1239 const SCEV *Step = SE->getUnknown(Addend); 1240 D = InductionDescriptor(StartValue, IK_FpInduction, Step, BOp); 1241 return true; 1242 } 1243 1244 /// This function is called when we suspect that the update-chain of a phi node 1245 /// (whose symbolic SCEV expression sin \p PhiScev) contains redundant casts, 1246 /// that can be ignored. (This can happen when the PSCEV rewriter adds a runtime 1247 /// predicate P under which the SCEV expression for the phi can be the 1248 /// AddRecurrence \p AR; See createAddRecFromPHIWithCast). We want to find the 1249 /// cast instructions that are involved in the update-chain of this induction. 1250 /// A caller that adds the required runtime predicate can be free to drop these 1251 /// cast instructions, and compute the phi using \p AR (instead of some scev 1252 /// expression with casts). 1253 /// 1254 /// For example, without a predicate the scev expression can take the following 1255 /// form: 1256 /// (Ext ix (Trunc iy ( Start + i*Step ) to ix) to iy) 1257 /// 1258 /// It corresponds to the following IR sequence: 1259 /// %for.body: 1260 /// %x = phi i64 [ 0, %ph ], [ %add, %for.body ] 1261 /// %casted_phi = "ExtTrunc i64 %x" 1262 /// %add = add i64 %casted_phi, %step 1263 /// 1264 /// where %x is given in \p PN, 1265 /// PSE.getSCEV(%x) is equal to PSE.getSCEV(%casted_phi) under a predicate, 1266 /// and the IR sequence that "ExtTrunc i64 %x" represents can take one of 1267 /// several forms, for example, such as: 1268 /// ExtTrunc1: %casted_phi = and %x, 2^n-1 1269 /// or: 1270 /// ExtTrunc2: %t = shl %x, m 1271 /// %casted_phi = ashr %t, m 1272 /// 1273 /// If we are able to find such sequence, we return the instructions 1274 /// we found, namely %casted_phi and the instructions on its use-def chain up 1275 /// to the phi (not including the phi). 1276 static bool getCastsForInductionPHI(PredicatedScalarEvolution &PSE, 1277 const SCEVUnknown *PhiScev, 1278 const SCEVAddRecExpr *AR, 1279 SmallVectorImpl<Instruction *> &CastInsts) { 1280 1281 assert(CastInsts.empty() && "CastInsts is expected to be empty."); 1282 auto *PN = cast<PHINode>(PhiScev->getValue()); 1283 assert(PSE.getSCEV(PN) == AR && "Unexpected phi node SCEV expression"); 1284 const Loop *L = AR->getLoop(); 1285 1286 // Find any cast instructions that participate in the def-use chain of 1287 // PhiScev in the loop. 1288 // FORNOW/TODO: We currently expect the def-use chain to include only 1289 // two-operand instructions, where one of the operands is an invariant. 1290 // createAddRecFromPHIWithCasts() currently does not support anything more 1291 // involved than that, so we keep the search simple. This can be 1292 // extended/generalized as needed. 1293 1294 auto getDef = [&](const Value *Val) -> Value * { 1295 const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Val); 1296 if (!BinOp) 1297 return nullptr; 1298 Value *Op0 = BinOp->getOperand(0); 1299 Value *Op1 = BinOp->getOperand(1); 1300 Value *Def = nullptr; 1301 if (L->isLoopInvariant(Op0)) 1302 Def = Op1; 1303 else if (L->isLoopInvariant(Op1)) 1304 Def = Op0; 1305 return Def; 1306 }; 1307 1308 // Look for the instruction that defines the induction via the 1309 // loop backedge. 1310 BasicBlock *Latch = L->getLoopLatch(); 1311 if (!Latch) 1312 return false; 1313 Value *Val = PN->getIncomingValueForBlock(Latch); 1314 if (!Val) 1315 return false; 1316 1317 // Follow the def-use chain until the induction phi is reached. 1318 // If on the way we encounter a Value that has the same SCEV Expr as the 1319 // phi node, we can consider the instructions we visit from that point 1320 // as part of the cast-sequence that can be ignored. 1321 bool InCastSequence = false; 1322 auto *Inst = dyn_cast<Instruction>(Val); 1323 while (Val != PN) { 1324 // If we encountered a phi node other than PN, or if we left the loop, 1325 // we bail out. 1326 if (!Inst || !L->contains(Inst)) { 1327 return false; 1328 } 1329 auto *AddRec = dyn_cast<SCEVAddRecExpr>(PSE.getSCEV(Val)); 1330 if (AddRec && PSE.areAddRecsEqualWithPreds(AddRec, AR)) 1331 InCastSequence = true; 1332 if (InCastSequence) { 1333 // Only the last instruction in the cast sequence is expected to have 1334 // uses outside the induction def-use chain. 1335 if (!CastInsts.empty()) 1336 if (!Inst->hasOneUse()) 1337 return false; 1338 CastInsts.push_back(Inst); 1339 } 1340 Val = getDef(Val); 1341 if (!Val) 1342 return false; 1343 Inst = dyn_cast<Instruction>(Val); 1344 } 1345 1346 return InCastSequence; 1347 } 1348 1349 bool InductionDescriptor::isInductionPHI(PHINode *Phi, const Loop *TheLoop, 1350 PredicatedScalarEvolution &PSE, 1351 InductionDescriptor &D, bool Assume) { 1352 Type *PhiTy = Phi->getType(); 1353 1354 // Handle integer and pointer inductions variables. 1355 // Now we handle also FP induction but not trying to make a 1356 // recurrent expression from the PHI node in-place. 1357 1358 if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy() && !PhiTy->isFloatTy() && 1359 !PhiTy->isDoubleTy() && !PhiTy->isHalfTy()) 1360 return false; 1361 1362 if (PhiTy->isFloatingPointTy()) 1363 return isFPInductionPHI(Phi, TheLoop, PSE.getSE(), D); 1364 1365 const SCEV *PhiScev = PSE.getSCEV(Phi); 1366 const auto *AR = dyn_cast<SCEVAddRecExpr>(PhiScev); 1367 1368 // We need this expression to be an AddRecExpr. 1369 if (Assume && !AR) 1370 AR = PSE.getAsAddRec(Phi); 1371 1372 if (!AR) { 1373 LLVM_DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n"); 1374 return false; 1375 } 1376 1377 // Record any Cast instructions that participate in the induction update 1378 const auto *SymbolicPhi = dyn_cast<SCEVUnknown>(PhiScev); 1379 // If we started from an UnknownSCEV, and managed to build an addRecurrence 1380 // only after enabling Assume with PSCEV, this means we may have encountered 1381 // cast instructions that required adding a runtime check in order to 1382 // guarantee the correctness of the AddRecurrence respresentation of the 1383 // induction. 1384 if (PhiScev != AR && SymbolicPhi) { 1385 SmallVector<Instruction *, 2> Casts; 1386 if (getCastsForInductionPHI(PSE, SymbolicPhi, AR, Casts)) 1387 return isInductionPHI(Phi, TheLoop, PSE.getSE(), D, AR, &Casts); 1388 } 1389 1390 return isInductionPHI(Phi, TheLoop, PSE.getSE(), D, AR); 1391 } 1392 1393 bool InductionDescriptor::isInductionPHI( 1394 PHINode *Phi, const Loop *TheLoop, ScalarEvolution *SE, 1395 InductionDescriptor &D, const SCEV *Expr, 1396 SmallVectorImpl<Instruction *> *CastsToIgnore) { 1397 Type *PhiTy = Phi->getType(); 1398 // We only handle integer and pointer inductions variables. 1399 if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy()) 1400 return false; 1401 1402 // Check that the PHI is consecutive. 1403 const SCEV *PhiScev = Expr ? Expr : SE->getSCEV(Phi); 1404 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev); 1405 1406 if (!AR) { 1407 LLVM_DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n"); 1408 return false; 1409 } 1410 1411 if (AR->getLoop() != TheLoop) { 1412 // FIXME: We should treat this as a uniform. Unfortunately, we 1413 // don't currently know how to handled uniform PHIs. 1414 LLVM_DEBUG( 1415 dbgs() << "LV: PHI is a recurrence with respect to an outer loop.\n"); 1416 return false; 1417 } 1418 1419 Value *StartValue = 1420 Phi->getIncomingValueForBlock(AR->getLoop()->getLoopPreheader()); 1421 1422 BasicBlock *Latch = AR->getLoop()->getLoopLatch(); 1423 if (!Latch) 1424 return false; 1425 1426 const SCEV *Step = AR->getStepRecurrence(*SE); 1427 // Calculate the pointer stride and check if it is consecutive. 1428 // The stride may be a constant or a loop invariant integer value. 1429 const SCEVConstant *ConstStep = dyn_cast<SCEVConstant>(Step); 1430 if (!ConstStep && !SE->isLoopInvariant(Step, TheLoop)) 1431 return false; 1432 1433 if (PhiTy->isIntegerTy()) { 1434 BinaryOperator *BOp = 1435 dyn_cast<BinaryOperator>(Phi->getIncomingValueForBlock(Latch)); 1436 D = InductionDescriptor(StartValue, IK_IntInduction, Step, BOp, 1437 /* ElementType */ nullptr, CastsToIgnore); 1438 return true; 1439 } 1440 1441 assert(PhiTy->isPointerTy() && "The PHI must be a pointer"); 1442 // Pointer induction should be a constant. 1443 if (!ConstStep) 1444 return false; 1445 1446 // Always use i8 element type for opaque pointer inductions. 1447 PointerType *PtrTy = cast<PointerType>(PhiTy); 1448 Type *ElementType = PtrTy->isOpaque() 1449 ? Type::getInt8Ty(PtrTy->getContext()) 1450 : PtrTy->getNonOpaquePointerElementType(); 1451 if (!ElementType->isSized()) 1452 return false; 1453 1454 ConstantInt *CV = ConstStep->getValue(); 1455 const DataLayout &DL = Phi->getModule()->getDataLayout(); 1456 TypeSize TySize = DL.getTypeAllocSize(ElementType); 1457 // TODO: We could potentially support this for scalable vectors if we can 1458 // prove at compile time that the constant step is always a multiple of 1459 // the scalable type. 1460 if (TySize.isZero() || TySize.isScalable()) 1461 return false; 1462 1463 int64_t Size = static_cast<int64_t>(TySize.getFixedSize()); 1464 int64_t CVSize = CV->getSExtValue(); 1465 if (CVSize % Size) 1466 return false; 1467 auto *StepValue = 1468 SE->getConstant(CV->getType(), CVSize / Size, true /* signed */); 1469 D = InductionDescriptor(StartValue, IK_PtrInduction, StepValue, 1470 /* BinOp */ nullptr, ElementType); 1471 return true; 1472 } 1473