xref: /llvm-project/llvm/lib/Target/PowerPC/PPCTargetTransformInfo.cpp (revision d28f86723f37b2329428dfbcf847d3261f38dcc8)
1 //===-- PPCTargetTransformInfo.cpp - PPC specific TTI ---------------------===//
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 #include "PPCTargetTransformInfo.h"
10 #include "llvm/Analysis/CodeMetrics.h"
11 #include "llvm/Analysis/TargetTransformInfo.h"
12 #include "llvm/CodeGen/BasicTTIImpl.h"
13 #include "llvm/CodeGen/CostTable.h"
14 #include "llvm/CodeGen/TargetLowering.h"
15 #include "llvm/CodeGen/TargetSchedule.h"
16 #include "llvm/IR/IntrinsicsPowerPC.h"
17 #include "llvm/Support/CommandLine.h"
18 #include "llvm/Support/Debug.h"
19 #include "llvm/Transforms/InstCombine/InstCombiner.h"
20 #include "llvm/Transforms/Utils/Local.h"
21 using namespace llvm;
22 
23 #define DEBUG_TYPE "ppctti"
24 
25 static cl::opt<bool> DisablePPCConstHoist("disable-ppc-constant-hoisting",
26 cl::desc("disable constant hoisting on PPC"), cl::init(false), cl::Hidden);
27 
28 // This is currently only used for the data prefetch pass
29 static cl::opt<unsigned>
30 CacheLineSize("ppc-loop-prefetch-cache-line", cl::Hidden, cl::init(64),
31               cl::desc("The loop prefetch cache line size"));
32 
33 static cl::opt<bool>
34 EnablePPCColdCC("ppc-enable-coldcc", cl::Hidden, cl::init(false),
35                 cl::desc("Enable using coldcc calling conv for cold "
36                          "internal functions"));
37 
38 static cl::opt<bool>
39 LsrNoInsnsCost("ppc-lsr-no-insns-cost", cl::Hidden, cl::init(false),
40                cl::desc("Do not add instruction count to lsr cost model"));
41 
42 // The latency of mtctr is only justified if there are more than 4
43 // comparisons that will be removed as a result.
44 static cl::opt<unsigned>
45 SmallCTRLoopThreshold("min-ctr-loop-threshold", cl::init(4), cl::Hidden,
46                       cl::desc("Loops with a constant trip count smaller than "
47                                "this value will not use the count register."));
48 
49 //===----------------------------------------------------------------------===//
50 //
51 // PPC cost model.
52 //
53 //===----------------------------------------------------------------------===//
54 
55 TargetTransformInfo::PopcntSupportKind
56 PPCTTIImpl::getPopcntSupport(unsigned TyWidth) {
57   assert(isPowerOf2_32(TyWidth) && "Ty width must be power of 2");
58   if (ST->hasPOPCNTD() != PPCSubtarget::POPCNTD_Unavailable && TyWidth <= 64)
59     return ST->hasPOPCNTD() == PPCSubtarget::POPCNTD_Slow ?
60              TTI::PSK_SlowHardware : TTI::PSK_FastHardware;
61   return TTI::PSK_Software;
62 }
63 
64 Optional<Instruction *>
65 PPCTTIImpl::instCombineIntrinsic(InstCombiner &IC, IntrinsicInst &II) const {
66   Intrinsic::ID IID = II.getIntrinsicID();
67   switch (IID) {
68   default:
69     break;
70   case Intrinsic::ppc_altivec_lvx:
71   case Intrinsic::ppc_altivec_lvxl:
72     // Turn PPC lvx -> load if the pointer is known aligned.
73     if (getOrEnforceKnownAlignment(
74             II.getArgOperand(0), Align(16), IC.getDataLayout(), &II,
75             &IC.getAssumptionCache(), &IC.getDominatorTree()) >= 16) {
76       Value *Ptr = IC.Builder.CreateBitCast(
77           II.getArgOperand(0), PointerType::getUnqual(II.getType()));
78       return new LoadInst(II.getType(), Ptr, "", false, Align(16));
79     }
80     break;
81   case Intrinsic::ppc_vsx_lxvw4x:
82   case Intrinsic::ppc_vsx_lxvd2x: {
83     // Turn PPC VSX loads into normal loads.
84     Value *Ptr = IC.Builder.CreateBitCast(II.getArgOperand(0),
85                                           PointerType::getUnqual(II.getType()));
86     return new LoadInst(II.getType(), Ptr, Twine(""), false, Align(1));
87   }
88   case Intrinsic::ppc_altivec_stvx:
89   case Intrinsic::ppc_altivec_stvxl:
90     // Turn stvx -> store if the pointer is known aligned.
91     if (getOrEnforceKnownAlignment(
92             II.getArgOperand(1), Align(16), IC.getDataLayout(), &II,
93             &IC.getAssumptionCache(), &IC.getDominatorTree()) >= 16) {
94       Type *OpPtrTy = PointerType::getUnqual(II.getArgOperand(0)->getType());
95       Value *Ptr = IC.Builder.CreateBitCast(II.getArgOperand(1), OpPtrTy);
96       return new StoreInst(II.getArgOperand(0), Ptr, false, Align(16));
97     }
98     break;
99   case Intrinsic::ppc_vsx_stxvw4x:
100   case Intrinsic::ppc_vsx_stxvd2x: {
101     // Turn PPC VSX stores into normal stores.
102     Type *OpPtrTy = PointerType::getUnqual(II.getArgOperand(0)->getType());
103     Value *Ptr = IC.Builder.CreateBitCast(II.getArgOperand(1), OpPtrTy);
104     return new StoreInst(II.getArgOperand(0), Ptr, false, Align(1));
105   }
106   case Intrinsic::ppc_altivec_vperm:
107     // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
108     // Note that ppc_altivec_vperm has a big-endian bias, so when creating
109     // a vectorshuffle for little endian, we must undo the transformation
110     // performed on vec_perm in altivec.h.  That is, we must complement
111     // the permutation mask with respect to 31 and reverse the order of
112     // V1 and V2.
113     if (Constant *Mask = dyn_cast<Constant>(II.getArgOperand(2))) {
114       assert(cast<VectorType>(Mask->getType())->getNumElements() == 16 &&
115              "Bad type for intrinsic!");
116 
117       // Check that all of the elements are integer constants or undefs.
118       bool AllEltsOk = true;
119       for (unsigned i = 0; i != 16; ++i) {
120         Constant *Elt = Mask->getAggregateElement(i);
121         if (!Elt || !(isa<ConstantInt>(Elt) || isa<UndefValue>(Elt))) {
122           AllEltsOk = false;
123           break;
124         }
125       }
126 
127       if (AllEltsOk) {
128         // Cast the input vectors to byte vectors.
129         Value *Op0 =
130             IC.Builder.CreateBitCast(II.getArgOperand(0), Mask->getType());
131         Value *Op1 =
132             IC.Builder.CreateBitCast(II.getArgOperand(1), Mask->getType());
133         Value *Result = UndefValue::get(Op0->getType());
134 
135         // Only extract each element once.
136         Value *ExtractedElts[32];
137         memset(ExtractedElts, 0, sizeof(ExtractedElts));
138 
139         for (unsigned i = 0; i != 16; ++i) {
140           if (isa<UndefValue>(Mask->getAggregateElement(i)))
141             continue;
142           unsigned Idx =
143               cast<ConstantInt>(Mask->getAggregateElement(i))->getZExtValue();
144           Idx &= 31; // Match the hardware behavior.
145           if (DL.isLittleEndian())
146             Idx = 31 - Idx;
147 
148           if (!ExtractedElts[Idx]) {
149             Value *Op0ToUse = (DL.isLittleEndian()) ? Op1 : Op0;
150             Value *Op1ToUse = (DL.isLittleEndian()) ? Op0 : Op1;
151             ExtractedElts[Idx] = IC.Builder.CreateExtractElement(
152                 Idx < 16 ? Op0ToUse : Op1ToUse, IC.Builder.getInt32(Idx & 15));
153           }
154 
155           // Insert this value into the result vector.
156           Result = IC.Builder.CreateInsertElement(Result, ExtractedElts[Idx],
157                                                   IC.Builder.getInt32(i));
158         }
159         return CastInst::Create(Instruction::BitCast, Result, II.getType());
160       }
161     }
162     break;
163   }
164   return None;
165 }
166 
167 int PPCTTIImpl::getIntImmCost(const APInt &Imm, Type *Ty,
168                               TTI::TargetCostKind CostKind) {
169   if (DisablePPCConstHoist)
170     return BaseT::getIntImmCost(Imm, Ty, CostKind);
171 
172   assert(Ty->isIntegerTy());
173 
174   unsigned BitSize = Ty->getPrimitiveSizeInBits();
175   if (BitSize == 0)
176     return ~0U;
177 
178   if (Imm == 0)
179     return TTI::TCC_Free;
180 
181   if (Imm.getBitWidth() <= 64) {
182     if (isInt<16>(Imm.getSExtValue()))
183       return TTI::TCC_Basic;
184 
185     if (isInt<32>(Imm.getSExtValue())) {
186       // A constant that can be materialized using lis.
187       if ((Imm.getZExtValue() & 0xFFFF) == 0)
188         return TTI::TCC_Basic;
189 
190       return 2 * TTI::TCC_Basic;
191     }
192   }
193 
194   return 4 * TTI::TCC_Basic;
195 }
196 
197 int PPCTTIImpl::getIntImmCostIntrin(Intrinsic::ID IID, unsigned Idx,
198                                     const APInt &Imm, Type *Ty,
199                                     TTI::TargetCostKind CostKind) {
200   if (DisablePPCConstHoist)
201     return BaseT::getIntImmCostIntrin(IID, Idx, Imm, Ty, CostKind);
202 
203   assert(Ty->isIntegerTy());
204 
205   unsigned BitSize = Ty->getPrimitiveSizeInBits();
206   if (BitSize == 0)
207     return ~0U;
208 
209   switch (IID) {
210   default:
211     return TTI::TCC_Free;
212   case Intrinsic::sadd_with_overflow:
213   case Intrinsic::uadd_with_overflow:
214   case Intrinsic::ssub_with_overflow:
215   case Intrinsic::usub_with_overflow:
216     if ((Idx == 1) && Imm.getBitWidth() <= 64 && isInt<16>(Imm.getSExtValue()))
217       return TTI::TCC_Free;
218     break;
219   case Intrinsic::experimental_stackmap:
220     if ((Idx < 2) || (Imm.getBitWidth() <= 64 && isInt<64>(Imm.getSExtValue())))
221       return TTI::TCC_Free;
222     break;
223   case Intrinsic::experimental_patchpoint_void:
224   case Intrinsic::experimental_patchpoint_i64:
225     if ((Idx < 4) || (Imm.getBitWidth() <= 64 && isInt<64>(Imm.getSExtValue())))
226       return TTI::TCC_Free;
227     break;
228   }
229   return PPCTTIImpl::getIntImmCost(Imm, Ty, CostKind);
230 }
231 
232 int PPCTTIImpl::getIntImmCostInst(unsigned Opcode, unsigned Idx,
233                                   const APInt &Imm, Type *Ty,
234                                   TTI::TargetCostKind CostKind) {
235   if (DisablePPCConstHoist)
236     return BaseT::getIntImmCostInst(Opcode, Idx, Imm, Ty, CostKind);
237 
238   assert(Ty->isIntegerTy());
239 
240   unsigned BitSize = Ty->getPrimitiveSizeInBits();
241   if (BitSize == 0)
242     return ~0U;
243 
244   unsigned ImmIdx = ~0U;
245   bool ShiftedFree = false, RunFree = false, UnsignedFree = false,
246        ZeroFree = false;
247   switch (Opcode) {
248   default:
249     return TTI::TCC_Free;
250   case Instruction::GetElementPtr:
251     // Always hoist the base address of a GetElementPtr. This prevents the
252     // creation of new constants for every base constant that gets constant
253     // folded with the offset.
254     if (Idx == 0)
255       return 2 * TTI::TCC_Basic;
256     return TTI::TCC_Free;
257   case Instruction::And:
258     RunFree = true; // (for the rotate-and-mask instructions)
259     LLVM_FALLTHROUGH;
260   case Instruction::Add:
261   case Instruction::Or:
262   case Instruction::Xor:
263     ShiftedFree = true;
264     LLVM_FALLTHROUGH;
265   case Instruction::Sub:
266   case Instruction::Mul:
267   case Instruction::Shl:
268   case Instruction::LShr:
269   case Instruction::AShr:
270     ImmIdx = 1;
271     break;
272   case Instruction::ICmp:
273     UnsignedFree = true;
274     ImmIdx = 1;
275     // Zero comparisons can use record-form instructions.
276     LLVM_FALLTHROUGH;
277   case Instruction::Select:
278     ZeroFree = true;
279     break;
280   case Instruction::PHI:
281   case Instruction::Call:
282   case Instruction::Ret:
283   case Instruction::Load:
284   case Instruction::Store:
285     break;
286   }
287 
288   if (ZeroFree && Imm == 0)
289     return TTI::TCC_Free;
290 
291   if (Idx == ImmIdx && Imm.getBitWidth() <= 64) {
292     if (isInt<16>(Imm.getSExtValue()))
293       return TTI::TCC_Free;
294 
295     if (RunFree) {
296       if (Imm.getBitWidth() <= 32 &&
297           (isShiftedMask_32(Imm.getZExtValue()) ||
298            isShiftedMask_32(~Imm.getZExtValue())))
299         return TTI::TCC_Free;
300 
301       if (ST->isPPC64() &&
302           (isShiftedMask_64(Imm.getZExtValue()) ||
303            isShiftedMask_64(~Imm.getZExtValue())))
304         return TTI::TCC_Free;
305     }
306 
307     if (UnsignedFree && isUInt<16>(Imm.getZExtValue()))
308       return TTI::TCC_Free;
309 
310     if (ShiftedFree && (Imm.getZExtValue() & 0xFFFF) == 0)
311       return TTI::TCC_Free;
312   }
313 
314   return PPCTTIImpl::getIntImmCost(Imm, Ty, CostKind);
315 }
316 
317 unsigned
318 PPCTTIImpl::getUserCost(const User *U, ArrayRef<const Value *> Operands,
319                         TTI::TargetCostKind CostKind) {
320   // We already implement getCastInstrCost and getMemoryOpCost where we perform
321   // the vector adjustment there.
322   if (isa<CastInst>(U) || isa<LoadInst>(U) || isa<StoreInst>(U))
323     return BaseT::getUserCost(U, Operands, CostKind);
324 
325   if (U->getType()->isVectorTy()) {
326     // Instructions that need to be split should cost more.
327     std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, U->getType());
328     return LT.first * BaseT::getUserCost(U, Operands, CostKind);
329   }
330 
331   return BaseT::getUserCost(U, Operands, CostKind);
332 }
333 
334 bool PPCTTIImpl::mightUseCTR(BasicBlock *BB, TargetLibraryInfo *LibInfo,
335                              SmallPtrSetImpl<const Value *> &Visited) {
336   const PPCTargetMachine &TM = ST->getTargetMachine();
337 
338   // Loop through the inline asm constraints and look for something that
339   // clobbers ctr.
340   auto asmClobbersCTR = [](InlineAsm *IA) {
341     InlineAsm::ConstraintInfoVector CIV = IA->ParseConstraints();
342     for (unsigned i = 0, ie = CIV.size(); i < ie; ++i) {
343       InlineAsm::ConstraintInfo &C = CIV[i];
344       if (C.Type != InlineAsm::isInput)
345         for (unsigned j = 0, je = C.Codes.size(); j < je; ++j)
346           if (StringRef(C.Codes[j]).equals_lower("{ctr}"))
347             return true;
348     }
349     return false;
350   };
351 
352   // Determining the address of a TLS variable results in a function call in
353   // certain TLS models.
354   std::function<bool(const Value *)> memAddrUsesCTR =
355       [&memAddrUsesCTR, &TM, &Visited](const Value *MemAddr) -> bool {
356     // No need to traverse again if we already checked this operand.
357     if (!Visited.insert(MemAddr).second)
358       return false;
359     const auto *GV = dyn_cast<GlobalValue>(MemAddr);
360     if (!GV) {
361       // Recurse to check for constants that refer to TLS global variables.
362       if (const auto *CV = dyn_cast<Constant>(MemAddr))
363         for (const auto &CO : CV->operands())
364           if (memAddrUsesCTR(CO))
365             return true;
366 
367       return false;
368     }
369 
370     if (!GV->isThreadLocal())
371       return false;
372     TLSModel::Model Model = TM.getTLSModel(GV);
373     return Model == TLSModel::GeneralDynamic ||
374       Model == TLSModel::LocalDynamic;
375   };
376 
377   auto isLargeIntegerTy = [](bool Is32Bit, Type *Ty) {
378     if (IntegerType *ITy = dyn_cast<IntegerType>(Ty))
379       return ITy->getBitWidth() > (Is32Bit ? 32U : 64U);
380 
381     return false;
382   };
383 
384   for (BasicBlock::iterator J = BB->begin(), JE = BB->end();
385        J != JE; ++J) {
386     if (CallInst *CI = dyn_cast<CallInst>(J)) {
387       // Inline ASM is okay, unless it clobbers the ctr register.
388       if (InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledOperand())) {
389         if (asmClobbersCTR(IA))
390           return true;
391         continue;
392       }
393 
394       if (Function *F = CI->getCalledFunction()) {
395         // Most intrinsics don't become function calls, but some might.
396         // sin, cos, exp and log are always calls.
397         unsigned Opcode = 0;
398         if (F->getIntrinsicID() != Intrinsic::not_intrinsic) {
399           switch (F->getIntrinsicID()) {
400           default: continue;
401           // If we have a call to loop_decrement or set_loop_iterations,
402           // we're definitely using CTR.
403           case Intrinsic::set_loop_iterations:
404           case Intrinsic::loop_decrement:
405             return true;
406 
407           // Exclude eh_sjlj_setjmp; we don't need to exclude eh_sjlj_longjmp
408           // because, although it does clobber the counter register, the
409           // control can't then return to inside the loop unless there is also
410           // an eh_sjlj_setjmp.
411           case Intrinsic::eh_sjlj_setjmp:
412 
413           case Intrinsic::memcpy:
414           case Intrinsic::memmove:
415           case Intrinsic::memset:
416           case Intrinsic::powi:
417           case Intrinsic::log:
418           case Intrinsic::log2:
419           case Intrinsic::log10:
420           case Intrinsic::exp:
421           case Intrinsic::exp2:
422           case Intrinsic::pow:
423           case Intrinsic::sin:
424           case Intrinsic::cos:
425             return true;
426           case Intrinsic::copysign:
427             if (CI->getArgOperand(0)->getType()->getScalarType()->
428                 isPPC_FP128Ty())
429               return true;
430             else
431               continue; // ISD::FCOPYSIGN is never a library call.
432           case Intrinsic::fma:                Opcode = ISD::FMA;        break;
433           case Intrinsic::sqrt:               Opcode = ISD::FSQRT;      break;
434           case Intrinsic::floor:              Opcode = ISD::FFLOOR;     break;
435           case Intrinsic::ceil:               Opcode = ISD::FCEIL;      break;
436           case Intrinsic::trunc:              Opcode = ISD::FTRUNC;     break;
437           case Intrinsic::rint:               Opcode = ISD::FRINT;      break;
438           case Intrinsic::lrint:              Opcode = ISD::LRINT;      break;
439           case Intrinsic::llrint:             Opcode = ISD::LLRINT;     break;
440           case Intrinsic::nearbyint:          Opcode = ISD::FNEARBYINT; break;
441           case Intrinsic::round:              Opcode = ISD::FROUND;     break;
442           case Intrinsic::lround:             Opcode = ISD::LROUND;     break;
443           case Intrinsic::llround:            Opcode = ISD::LLROUND;    break;
444           case Intrinsic::minnum:             Opcode = ISD::FMINNUM;    break;
445           case Intrinsic::maxnum:             Opcode = ISD::FMAXNUM;    break;
446           case Intrinsic::umul_with_overflow: Opcode = ISD::UMULO;      break;
447           case Intrinsic::smul_with_overflow: Opcode = ISD::SMULO;      break;
448           }
449         }
450 
451         // PowerPC does not use [US]DIVREM or other library calls for
452         // operations on regular types which are not otherwise library calls
453         // (i.e. soft float or atomics). If adapting for targets that do,
454         // additional care is required here.
455 
456         LibFunc Func;
457         if (!F->hasLocalLinkage() && F->hasName() && LibInfo &&
458             LibInfo->getLibFunc(F->getName(), Func) &&
459             LibInfo->hasOptimizedCodeGen(Func)) {
460           // Non-read-only functions are never treated as intrinsics.
461           if (!CI->onlyReadsMemory())
462             return true;
463 
464           // Conversion happens only for FP calls.
465           if (!CI->getArgOperand(0)->getType()->isFloatingPointTy())
466             return true;
467 
468           switch (Func) {
469           default: return true;
470           case LibFunc_copysign:
471           case LibFunc_copysignf:
472             continue; // ISD::FCOPYSIGN is never a library call.
473           case LibFunc_copysignl:
474             return true;
475           case LibFunc_fabs:
476           case LibFunc_fabsf:
477           case LibFunc_fabsl:
478             continue; // ISD::FABS is never a library call.
479           case LibFunc_sqrt:
480           case LibFunc_sqrtf:
481           case LibFunc_sqrtl:
482             Opcode = ISD::FSQRT; break;
483           case LibFunc_floor:
484           case LibFunc_floorf:
485           case LibFunc_floorl:
486             Opcode = ISD::FFLOOR; break;
487           case LibFunc_nearbyint:
488           case LibFunc_nearbyintf:
489           case LibFunc_nearbyintl:
490             Opcode = ISD::FNEARBYINT; break;
491           case LibFunc_ceil:
492           case LibFunc_ceilf:
493           case LibFunc_ceill:
494             Opcode = ISD::FCEIL; break;
495           case LibFunc_rint:
496           case LibFunc_rintf:
497           case LibFunc_rintl:
498             Opcode = ISD::FRINT; break;
499           case LibFunc_round:
500           case LibFunc_roundf:
501           case LibFunc_roundl:
502             Opcode = ISD::FROUND; break;
503           case LibFunc_trunc:
504           case LibFunc_truncf:
505           case LibFunc_truncl:
506             Opcode = ISD::FTRUNC; break;
507           case LibFunc_fmin:
508           case LibFunc_fminf:
509           case LibFunc_fminl:
510             Opcode = ISD::FMINNUM; break;
511           case LibFunc_fmax:
512           case LibFunc_fmaxf:
513           case LibFunc_fmaxl:
514             Opcode = ISD::FMAXNUM; break;
515           }
516         }
517 
518         if (Opcode) {
519           EVT EVTy =
520               TLI->getValueType(DL, CI->getArgOperand(0)->getType(), true);
521 
522           if (EVTy == MVT::Other)
523             return true;
524 
525           if (TLI->isOperationLegalOrCustom(Opcode, EVTy))
526             continue;
527           else if (EVTy.isVector() &&
528                    TLI->isOperationLegalOrCustom(Opcode, EVTy.getScalarType()))
529             continue;
530 
531           return true;
532         }
533       }
534 
535       return true;
536     } else if (isa<BinaryOperator>(J) &&
537                (J->getType()->getScalarType()->isFP128Ty() ||
538                 J->getType()->getScalarType()->isPPC_FP128Ty())) {
539       // Most operations on f128 or ppc_f128 values become calls.
540       return true;
541     } else if (isa<UIToFPInst>(J) || isa<SIToFPInst>(J) ||
542                isa<FPToUIInst>(J) || isa<FPToSIInst>(J)) {
543       CastInst *CI = cast<CastInst>(J);
544       if (CI->getSrcTy()->getScalarType()->isPPC_FP128Ty() ||
545           CI->getDestTy()->getScalarType()->isPPC_FP128Ty() ||
546           isLargeIntegerTy(!TM.isPPC64(), CI->getSrcTy()->getScalarType()) ||
547           isLargeIntegerTy(!TM.isPPC64(), CI->getDestTy()->getScalarType()))
548         return true;
549     } else if (isLargeIntegerTy(!TM.isPPC64(),
550                                 J->getType()->getScalarType()) &&
551                (J->getOpcode() == Instruction::UDiv ||
552                 J->getOpcode() == Instruction::SDiv ||
553                 J->getOpcode() == Instruction::URem ||
554                 J->getOpcode() == Instruction::SRem)) {
555       return true;
556     } else if (!TM.isPPC64() &&
557                isLargeIntegerTy(false, J->getType()->getScalarType()) &&
558                (J->getOpcode() == Instruction::Shl ||
559                 J->getOpcode() == Instruction::AShr ||
560                 J->getOpcode() == Instruction::LShr)) {
561       // Only on PPC32, for 128-bit integers (specifically not 64-bit
562       // integers), these might be runtime calls.
563       return true;
564     } else if (isa<IndirectBrInst>(J) || isa<InvokeInst>(J)) {
565       // On PowerPC, indirect jumps use the counter register.
566       return true;
567     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(J)) {
568       if (SI->getNumCases() + 1 >= (unsigned)TLI->getMinimumJumpTableEntries())
569         return true;
570     }
571 
572     // FREM is always a call.
573     if (J->getOpcode() == Instruction::FRem)
574       return true;
575 
576     if (ST->useSoftFloat()) {
577       switch(J->getOpcode()) {
578       case Instruction::FAdd:
579       case Instruction::FSub:
580       case Instruction::FMul:
581       case Instruction::FDiv:
582       case Instruction::FPTrunc:
583       case Instruction::FPExt:
584       case Instruction::FPToUI:
585       case Instruction::FPToSI:
586       case Instruction::UIToFP:
587       case Instruction::SIToFP:
588       case Instruction::FCmp:
589         return true;
590       }
591     }
592 
593     for (Value *Operand : J->operands())
594       if (memAddrUsesCTR(Operand))
595         return true;
596   }
597 
598   return false;
599 }
600 
601 bool PPCTTIImpl::isHardwareLoopProfitable(Loop *L, ScalarEvolution &SE,
602                                           AssumptionCache &AC,
603                                           TargetLibraryInfo *LibInfo,
604                                           HardwareLoopInfo &HWLoopInfo) {
605   const PPCTargetMachine &TM = ST->getTargetMachine();
606   TargetSchedModel SchedModel;
607   SchedModel.init(ST);
608 
609   // Do not convert small short loops to CTR loop.
610   unsigned ConstTripCount = SE.getSmallConstantTripCount(L);
611   if (ConstTripCount && ConstTripCount < SmallCTRLoopThreshold) {
612     SmallPtrSet<const Value *, 32> EphValues;
613     CodeMetrics::collectEphemeralValues(L, &AC, EphValues);
614     CodeMetrics Metrics;
615     for (BasicBlock *BB : L->blocks())
616       Metrics.analyzeBasicBlock(BB, *this, EphValues);
617     // 6 is an approximate latency for the mtctr instruction.
618     if (Metrics.NumInsts <= (6 * SchedModel.getIssueWidth()))
619       return false;
620   }
621 
622   // We don't want to spill/restore the counter register, and so we don't
623   // want to use the counter register if the loop contains calls.
624   SmallPtrSet<const Value *, 4> Visited;
625   for (Loop::block_iterator I = L->block_begin(), IE = L->block_end();
626        I != IE; ++I)
627     if (mightUseCTR(*I, LibInfo, Visited))
628       return false;
629 
630   SmallVector<BasicBlock*, 4> ExitingBlocks;
631   L->getExitingBlocks(ExitingBlocks);
632 
633   // If there is an exit edge known to be frequently taken,
634   // we should not transform this loop.
635   for (auto &BB : ExitingBlocks) {
636     Instruction *TI = BB->getTerminator();
637     if (!TI) continue;
638 
639     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
640       uint64_t TrueWeight = 0, FalseWeight = 0;
641       if (!BI->isConditional() ||
642           !BI->extractProfMetadata(TrueWeight, FalseWeight))
643         continue;
644 
645       // If the exit path is more frequent than the loop path,
646       // we return here without further analysis for this loop.
647       bool TrueIsExit = !L->contains(BI->getSuccessor(0));
648       if (( TrueIsExit && FalseWeight < TrueWeight) ||
649           (!TrueIsExit && FalseWeight > TrueWeight))
650         return false;
651     }
652   }
653 
654   LLVMContext &C = L->getHeader()->getContext();
655   HWLoopInfo.CountType = TM.isPPC64() ?
656     Type::getInt64Ty(C) : Type::getInt32Ty(C);
657   HWLoopInfo.LoopDecrement = ConstantInt::get(HWLoopInfo.CountType, 1);
658   return true;
659 }
660 
661 void PPCTTIImpl::getUnrollingPreferences(Loop *L, ScalarEvolution &SE,
662                                          TTI::UnrollingPreferences &UP) {
663   if (ST->getCPUDirective() == PPC::DIR_A2) {
664     // The A2 is in-order with a deep pipeline, and concatenation unrolling
665     // helps expose latency-hiding opportunities to the instruction scheduler.
666     UP.Partial = UP.Runtime = true;
667 
668     // We unroll a lot on the A2 (hundreds of instructions), and the benefits
669     // often outweigh the cost of a division to compute the trip count.
670     UP.AllowExpensiveTripCount = true;
671   }
672 
673   BaseT::getUnrollingPreferences(L, SE, UP);
674 }
675 
676 void PPCTTIImpl::getPeelingPreferences(Loop *L, ScalarEvolution &SE,
677                                        TTI::PeelingPreferences &PP) {
678   BaseT::getPeelingPreferences(L, SE, PP);
679 }
680 // This function returns true to allow using coldcc calling convention.
681 // Returning true results in coldcc being used for functions which are cold at
682 // all call sites when the callers of the functions are not calling any other
683 // non coldcc functions.
684 bool PPCTTIImpl::useColdCCForColdCall(Function &F) {
685   return EnablePPCColdCC;
686 }
687 
688 bool PPCTTIImpl::enableAggressiveInterleaving(bool LoopHasReductions) {
689   // On the A2, always unroll aggressively.
690   if (ST->getCPUDirective() == PPC::DIR_A2)
691     return true;
692 
693   return LoopHasReductions;
694 }
695 
696 PPCTTIImpl::TTI::MemCmpExpansionOptions
697 PPCTTIImpl::enableMemCmpExpansion(bool OptSize, bool IsZeroCmp) const {
698   TTI::MemCmpExpansionOptions Options;
699   Options.LoadSizes = {8, 4, 2, 1};
700   Options.MaxNumLoads = TLI->getMaxExpandSizeMemcmp(OptSize);
701   return Options;
702 }
703 
704 bool PPCTTIImpl::enableInterleavedAccessVectorization() {
705   return true;
706 }
707 
708 unsigned PPCTTIImpl::getNumberOfRegisters(unsigned ClassID) const {
709   assert(ClassID == GPRRC || ClassID == FPRRC ||
710          ClassID == VRRC || ClassID == VSXRC);
711   if (ST->hasVSX()) {
712     assert(ClassID == GPRRC || ClassID == VSXRC || ClassID == VRRC);
713     return ClassID == VSXRC ? 64 : 32;
714   }
715   assert(ClassID == GPRRC || ClassID == FPRRC || ClassID == VRRC);
716   return 32;
717 }
718 
719 unsigned PPCTTIImpl::getRegisterClassForType(bool Vector, Type *Ty) const {
720   if (Vector)
721     return ST->hasVSX() ? VSXRC : VRRC;
722   else if (Ty && (Ty->getScalarType()->isFloatTy() ||
723                   Ty->getScalarType()->isDoubleTy()))
724     return ST->hasVSX() ? VSXRC : FPRRC;
725   else if (Ty && (Ty->getScalarType()->isFP128Ty() ||
726                   Ty->getScalarType()->isPPC_FP128Ty()))
727     return VRRC;
728   else if (Ty && Ty->getScalarType()->isHalfTy())
729     return VSXRC;
730   else
731     return GPRRC;
732 }
733 
734 const char* PPCTTIImpl::getRegisterClassName(unsigned ClassID) const {
735 
736   switch (ClassID) {
737     default:
738       llvm_unreachable("unknown register class");
739       return "PPC::unknown register class";
740     case GPRRC:       return "PPC::GPRRC";
741     case FPRRC:       return "PPC::FPRRC";
742     case VRRC:        return "PPC::VRRC";
743     case VSXRC:       return "PPC::VSXRC";
744   }
745 }
746 
747 unsigned PPCTTIImpl::getRegisterBitWidth(bool Vector) const {
748   if (Vector) {
749     if (ST->hasAltivec()) return 128;
750     return 0;
751   }
752 
753   if (ST->isPPC64())
754     return 64;
755   return 32;
756 
757 }
758 
759 unsigned PPCTTIImpl::getCacheLineSize() const {
760   // Check first if the user specified a custom line size.
761   if (CacheLineSize.getNumOccurrences() > 0)
762     return CacheLineSize;
763 
764   // Starting with P7 we have a cache line size of 128.
765   unsigned Directive = ST->getCPUDirective();
766   // Assume that Future CPU has the same cache line size as the others.
767   if (Directive == PPC::DIR_PWR7 || Directive == PPC::DIR_PWR8 ||
768       Directive == PPC::DIR_PWR9 || Directive == PPC::DIR_PWR10 ||
769       Directive == PPC::DIR_PWR_FUTURE)
770     return 128;
771 
772   // On other processors return a default of 64 bytes.
773   return 64;
774 }
775 
776 unsigned PPCTTIImpl::getPrefetchDistance() const {
777   return 300;
778 }
779 
780 unsigned PPCTTIImpl::getMaxInterleaveFactor(unsigned VF) {
781   unsigned Directive = ST->getCPUDirective();
782   // The 440 has no SIMD support, but floating-point instructions
783   // have a 5-cycle latency, so unroll by 5x for latency hiding.
784   if (Directive == PPC::DIR_440)
785     return 5;
786 
787   // The A2 has no SIMD support, but floating-point instructions
788   // have a 6-cycle latency, so unroll by 6x for latency hiding.
789   if (Directive == PPC::DIR_A2)
790     return 6;
791 
792   // FIXME: For lack of any better information, do no harm...
793   if (Directive == PPC::DIR_E500mc || Directive == PPC::DIR_E5500)
794     return 1;
795 
796   // For P7 and P8, floating-point instructions have a 6-cycle latency and
797   // there are two execution units, so unroll by 12x for latency hiding.
798   // FIXME: the same for P9 as previous gen until POWER9 scheduling is ready
799   // FIXME: the same for P10 as previous gen until POWER10 scheduling is ready
800   // Assume that future is the same as the others.
801   if (Directive == PPC::DIR_PWR7 || Directive == PPC::DIR_PWR8 ||
802       Directive == PPC::DIR_PWR9 || Directive == PPC::DIR_PWR10 ||
803       Directive == PPC::DIR_PWR_FUTURE)
804     return 12;
805 
806   // For most things, modern systems have two execution units (and
807   // out-of-order execution).
808   return 2;
809 }
810 
811 // Adjust the cost of vector instructions on targets which there is overlap
812 // between the vector and scalar units, thereby reducing the overall throughput
813 // of vector code wrt. scalar code.
814 int PPCTTIImpl::vectorCostAdjustment(int Cost, unsigned Opcode, Type *Ty1,
815                                      Type *Ty2) {
816   if (!ST->vectorsUseTwoUnits() || !Ty1->isVectorTy())
817     return Cost;
818 
819   std::pair<int, MVT> LT1 = TLI->getTypeLegalizationCost(DL, Ty1);
820   // If type legalization involves splitting the vector, we don't want to
821   // double the cost at every step - only the last step.
822   if (LT1.first != 1 || !LT1.second.isVector())
823     return Cost;
824 
825   int ISD = TLI->InstructionOpcodeToISD(Opcode);
826   if (TLI->isOperationExpand(ISD, LT1.second))
827     return Cost;
828 
829   if (Ty2) {
830     std::pair<int, MVT> LT2 = TLI->getTypeLegalizationCost(DL, Ty2);
831     if (LT2.first != 1 || !LT2.second.isVector())
832       return Cost;
833   }
834 
835   return Cost * 2;
836 }
837 
838 int PPCTTIImpl::getArithmeticInstrCost(unsigned Opcode, Type *Ty,
839                                        TTI::TargetCostKind CostKind,
840                                        TTI::OperandValueKind Op1Info,
841                                        TTI::OperandValueKind Op2Info,
842                                        TTI::OperandValueProperties Opd1PropInfo,
843                                        TTI::OperandValueProperties Opd2PropInfo,
844                                        ArrayRef<const Value *> Args,
845                                        const Instruction *CxtI) {
846   assert(TLI->InstructionOpcodeToISD(Opcode) && "Invalid opcode");
847   // TODO: Handle more cost kinds.
848   if (CostKind != TTI::TCK_RecipThroughput)
849     return BaseT::getArithmeticInstrCost(Opcode, Ty, CostKind, Op1Info,
850                                          Op2Info, Opd1PropInfo,
851                                          Opd2PropInfo, Args, CxtI);
852 
853   // Fallback to the default implementation.
854   int Cost = BaseT::getArithmeticInstrCost(Opcode, Ty, CostKind, Op1Info,
855                                            Op2Info,
856                                            Opd1PropInfo, Opd2PropInfo);
857   return vectorCostAdjustment(Cost, Opcode, Ty, nullptr);
858 }
859 
860 int PPCTTIImpl::getShuffleCost(TTI::ShuffleKind Kind, Type *Tp, int Index,
861                                Type *SubTp) {
862   // Legalize the type.
863   std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Tp);
864 
865   // PPC, for both Altivec/VSX, support cheap arbitrary permutations
866   // (at least in the sense that there need only be one non-loop-invariant
867   // instruction). We need one such shuffle instruction for each actual
868   // register (this is not true for arbitrary shuffles, but is true for the
869   // structured types of shuffles covered by TTI::ShuffleKind).
870   return vectorCostAdjustment(LT.first, Instruction::ShuffleVector, Tp,
871                               nullptr);
872 }
873 
874 int PPCTTIImpl::getCFInstrCost(unsigned Opcode, TTI::TargetCostKind CostKind) {
875   if (CostKind != TTI::TCK_RecipThroughput)
876     return Opcode == Instruction::PHI ? 0 : 1;
877   // Branches are assumed to be predicted.
878   return CostKind == TTI::TCK_RecipThroughput ? 0 : 1;
879 }
880 
881 int PPCTTIImpl::getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src,
882                                  TTI::TargetCostKind CostKind,
883                                  const Instruction *I) {
884   assert(TLI->InstructionOpcodeToISD(Opcode) && "Invalid opcode");
885 
886   int Cost = BaseT::getCastInstrCost(Opcode, Dst, Src, CostKind, I);
887   Cost = vectorCostAdjustment(Cost, Opcode, Dst, Src);
888   // TODO: Allow non-throughput costs that aren't binary.
889   if (CostKind != TTI::TCK_RecipThroughput)
890     return Cost == 0 ? 0 : 1;
891   return Cost;
892 }
893 
894 int PPCTTIImpl::getCmpSelInstrCost(unsigned Opcode, Type *ValTy, Type *CondTy,
895                                    TTI::TargetCostKind CostKind,
896                                    const Instruction *I) {
897   int Cost = BaseT::getCmpSelInstrCost(Opcode, ValTy, CondTy, CostKind, I);
898   // TODO: Handle other cost kinds.
899   if (CostKind != TTI::TCK_RecipThroughput)
900     return Cost;
901   return vectorCostAdjustment(Cost, Opcode, ValTy, nullptr);
902 }
903 
904 int PPCTTIImpl::getVectorInstrCost(unsigned Opcode, Type *Val, unsigned Index) {
905   assert(Val->isVectorTy() && "This must be a vector type");
906 
907   int ISD = TLI->InstructionOpcodeToISD(Opcode);
908   assert(ISD && "Invalid opcode");
909 
910   int Cost = BaseT::getVectorInstrCost(Opcode, Val, Index);
911   Cost = vectorCostAdjustment(Cost, Opcode, Val, nullptr);
912 
913   if (ST->hasVSX() && Val->getScalarType()->isDoubleTy()) {
914     // Double-precision scalars are already located in index #0 (or #1 if LE).
915     if (ISD == ISD::EXTRACT_VECTOR_ELT &&
916         Index == (ST->isLittleEndian() ? 1 : 0))
917       return 0;
918 
919     return Cost;
920 
921   } else if (Val->getScalarType()->isIntegerTy() && Index != -1U) {
922     if (ST->hasP9Altivec()) {
923       if (ISD == ISD::INSERT_VECTOR_ELT)
924         // A move-to VSR and a permute/insert.  Assume vector operation cost
925         // for both (cost will be 2x on P9).
926         return vectorCostAdjustment(2, Opcode, Val, nullptr);
927 
928       // It's an extract.  Maybe we can do a cheap move-from VSR.
929       unsigned EltSize = Val->getScalarSizeInBits();
930       if (EltSize == 64) {
931         unsigned MfvsrdIndex = ST->isLittleEndian() ? 1 : 0;
932         if (Index == MfvsrdIndex)
933           return 1;
934       } else if (EltSize == 32) {
935         unsigned MfvsrwzIndex = ST->isLittleEndian() ? 2 : 1;
936         if (Index == MfvsrwzIndex)
937           return 1;
938       }
939 
940       // We need a vector extract (or mfvsrld).  Assume vector operation cost.
941       // The cost of the load constant for a vector extract is disregarded
942       // (invariant, easily schedulable).
943       return vectorCostAdjustment(1, Opcode, Val, nullptr);
944 
945     } else if (ST->hasDirectMove())
946       // Assume permute has standard cost.
947       // Assume move-to/move-from VSR have 2x standard cost.
948       return 3;
949   }
950 
951   // Estimated cost of a load-hit-store delay.  This was obtained
952   // experimentally as a minimum needed to prevent unprofitable
953   // vectorization for the paq8p benchmark.  It may need to be
954   // raised further if other unprofitable cases remain.
955   unsigned LHSPenalty = 2;
956   if (ISD == ISD::INSERT_VECTOR_ELT)
957     LHSPenalty += 7;
958 
959   // Vector element insert/extract with Altivec is very expensive,
960   // because they require store and reload with the attendant
961   // processor stall for load-hit-store.  Until VSX is available,
962   // these need to be estimated as very costly.
963   if (ISD == ISD::EXTRACT_VECTOR_ELT ||
964       ISD == ISD::INSERT_VECTOR_ELT)
965     return LHSPenalty + Cost;
966 
967   return Cost;
968 }
969 
970 int PPCTTIImpl::getMemoryOpCost(unsigned Opcode, Type *Src,
971                                 MaybeAlign Alignment, unsigned AddressSpace,
972                                 TTI::TargetCostKind CostKind,
973                                 const Instruction *I) {
974   if (TLI->getValueType(DL, Src,  true) == MVT::Other)
975     return BaseT::getMemoryOpCost(Opcode, Src, Alignment, AddressSpace,
976                                   CostKind);
977   // Legalize the type.
978   std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Src);
979   assert((Opcode == Instruction::Load || Opcode == Instruction::Store) &&
980          "Invalid Opcode");
981 
982   int Cost = BaseT::getMemoryOpCost(Opcode, Src, Alignment, AddressSpace,
983                                     CostKind);
984   // TODO: Handle other cost kinds.
985   if (CostKind != TTI::TCK_RecipThroughput)
986     return Cost;
987 
988   Cost = vectorCostAdjustment(Cost, Opcode, Src, nullptr);
989 
990   bool IsAltivecType = ST->hasAltivec() &&
991                        (LT.second == MVT::v16i8 || LT.second == MVT::v8i16 ||
992                         LT.second == MVT::v4i32 || LT.second == MVT::v4f32);
993   bool IsVSXType = ST->hasVSX() &&
994                    (LT.second == MVT::v2f64 || LT.second == MVT::v2i64);
995 
996   // VSX has 32b/64b load instructions. Legalization can handle loading of
997   // 32b/64b to VSR correctly and cheaply. But BaseT::getMemoryOpCost and
998   // PPCTargetLowering can't compute the cost appropriately. So here we
999   // explicitly check this case.
1000   unsigned MemBytes = Src->getPrimitiveSizeInBits();
1001   if (Opcode == Instruction::Load && ST->hasVSX() && IsAltivecType &&
1002       (MemBytes == 64 || (ST->hasP8Vector() && MemBytes == 32)))
1003     return 1;
1004 
1005   // Aligned loads and stores are easy.
1006   unsigned SrcBytes = LT.second.getStoreSize();
1007   if (!SrcBytes || !Alignment || *Alignment >= SrcBytes)
1008     return Cost;
1009 
1010   // If we can use the permutation-based load sequence, then this is also
1011   // relatively cheap (not counting loop-invariant instructions): one load plus
1012   // one permute (the last load in a series has extra cost, but we're
1013   // neglecting that here). Note that on the P7, we could do unaligned loads
1014   // for Altivec types using the VSX instructions, but that's more expensive
1015   // than using the permutation-based load sequence. On the P8, that's no
1016   // longer true.
1017   if (Opcode == Instruction::Load && (!ST->hasP8Vector() && IsAltivecType) &&
1018       *Alignment >= LT.second.getScalarType().getStoreSize())
1019     return Cost + LT.first; // Add the cost of the permutations.
1020 
1021   // For VSX, we can do unaligned loads and stores on Altivec/VSX types. On the
1022   // P7, unaligned vector loads are more expensive than the permutation-based
1023   // load sequence, so that might be used instead, but regardless, the net cost
1024   // is about the same (not counting loop-invariant instructions).
1025   if (IsVSXType || (ST->hasVSX() && IsAltivecType))
1026     return Cost;
1027 
1028   // Newer PPC supports unaligned memory access.
1029   if (TLI->allowsMisalignedMemoryAccesses(LT.second, 0))
1030     return Cost;
1031 
1032   // PPC in general does not support unaligned loads and stores. They'll need
1033   // to be decomposed based on the alignment factor.
1034 
1035   // Add the cost of each scalar load or store.
1036   assert(Alignment);
1037   Cost += LT.first * ((SrcBytes / Alignment->value()) - 1);
1038 
1039   // For a vector type, there is also scalarization overhead (only for
1040   // stores, loads are expanded using the vector-load + permutation sequence,
1041   // which is much less expensive).
1042   if (Src->isVectorTy() && Opcode == Instruction::Store)
1043     for (int i = 0, e = cast<FixedVectorType>(Src)->getNumElements(); i < e;
1044          ++i)
1045       Cost += getVectorInstrCost(Instruction::ExtractElement, Src, i);
1046 
1047   return Cost;
1048 }
1049 
1050 int PPCTTIImpl::getInterleavedMemoryOpCost(
1051     unsigned Opcode, Type *VecTy, unsigned Factor, ArrayRef<unsigned> Indices,
1052     Align Alignment, unsigned AddressSpace, TTI::TargetCostKind CostKind,
1053     bool UseMaskForCond, bool UseMaskForGaps) {
1054   if (UseMaskForCond || UseMaskForGaps)
1055     return BaseT::getInterleavedMemoryOpCost(Opcode, VecTy, Factor, Indices,
1056                                              Alignment, AddressSpace, CostKind,
1057                                              UseMaskForCond, UseMaskForGaps);
1058 
1059   assert(isa<VectorType>(VecTy) &&
1060          "Expect a vector type for interleaved memory op");
1061 
1062   // Legalize the type.
1063   std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, VecTy);
1064 
1065   // Firstly, the cost of load/store operation.
1066   int Cost =
1067       getMemoryOpCost(Opcode, VecTy, MaybeAlign(Alignment), AddressSpace,
1068                       CostKind);
1069 
1070   // PPC, for both Altivec/VSX, support cheap arbitrary permutations
1071   // (at least in the sense that there need only be one non-loop-invariant
1072   // instruction). For each result vector, we need one shuffle per incoming
1073   // vector (except that the first shuffle can take two incoming vectors
1074   // because it does not need to take itself).
1075   Cost += Factor*(LT.first-1);
1076 
1077   return Cost;
1078 }
1079 
1080 unsigned PPCTTIImpl::getIntrinsicInstrCost(const IntrinsicCostAttributes &ICA,
1081                                            TTI::TargetCostKind CostKind) {
1082   return BaseT::getIntrinsicInstrCost(ICA, CostKind);
1083 }
1084 
1085 bool PPCTTIImpl::canSaveCmp(Loop *L, BranchInst **BI, ScalarEvolution *SE,
1086                             LoopInfo *LI, DominatorTree *DT,
1087                             AssumptionCache *AC, TargetLibraryInfo *LibInfo) {
1088   // Process nested loops first.
1089   for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
1090     if (canSaveCmp(*I, BI, SE, LI, DT, AC, LibInfo))
1091       return false; // Stop search.
1092 
1093   HardwareLoopInfo HWLoopInfo(L);
1094 
1095   if (!HWLoopInfo.canAnalyze(*LI))
1096     return false;
1097 
1098   if (!isHardwareLoopProfitable(L, *SE, *AC, LibInfo, HWLoopInfo))
1099     return false;
1100 
1101   if (!HWLoopInfo.isHardwareLoopCandidate(*SE, *LI, *DT))
1102     return false;
1103 
1104   *BI = HWLoopInfo.ExitBranch;
1105   return true;
1106 }
1107 
1108 bool PPCTTIImpl::isLSRCostLess(TargetTransformInfo::LSRCost &C1,
1109                                TargetTransformInfo::LSRCost &C2) {
1110   // PowerPC default behaviour here is "instruction number 1st priority".
1111   // If LsrNoInsnsCost is set, call default implementation.
1112   if (!LsrNoInsnsCost)
1113     return std::tie(C1.Insns, C1.NumRegs, C1.AddRecCost, C1.NumIVMuls,
1114                     C1.NumBaseAdds, C1.ScaleCost, C1.ImmCost, C1.SetupCost) <
1115            std::tie(C2.Insns, C2.NumRegs, C2.AddRecCost, C2.NumIVMuls,
1116                     C2.NumBaseAdds, C2.ScaleCost, C2.ImmCost, C2.SetupCost);
1117   else
1118     return TargetTransformInfoImplBase::isLSRCostLess(C1, C2);
1119 }
1120