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