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