1 //===-- SystemZTargetTransformInfo.cpp - SystemZ-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 // This file implements a TargetTransformInfo analysis pass specific to the
10 // SystemZ target machine. It uses the target's detailed information to provide
11 // more precise answers to certain TTI queries, while letting the target
12 // independent and default TTI implementations handle the rest.
13 //
14 //===----------------------------------------------------------------------===//
15 
16 #include "SystemZTargetTransformInfo.h"
17 #include "llvm/Analysis/TargetTransformInfo.h"
18 #include "llvm/CodeGen/BasicTTIImpl.h"
19 #include "llvm/CodeGen/CostTable.h"
20 #include "llvm/CodeGen/TargetLowering.h"
21 #include "llvm/IR/IntrinsicInst.h"
22 #include "llvm/Support/Debug.h"
23 using namespace llvm;
24 
25 #define DEBUG_TYPE "systemztti"
26 
27 //===----------------------------------------------------------------------===//
28 //
29 // SystemZ cost model.
30 //
31 //===----------------------------------------------------------------------===//
32 
33 int SystemZTTIImpl::getIntImmCost(const APInt &Imm, Type *Ty,
34                                   TTI::TargetCostKind CostKind) {
35   assert(Ty->isIntegerTy());
36 
37   unsigned BitSize = Ty->getPrimitiveSizeInBits();
38   // There is no cost model for constants with a bit size of 0. Return TCC_Free
39   // here, so that constant hoisting will ignore this constant.
40   if (BitSize == 0)
41     return TTI::TCC_Free;
42   // No cost model for operations on integers larger than 64 bit implemented yet.
43   if (BitSize > 64)
44     return TTI::TCC_Free;
45 
46   if (Imm == 0)
47     return TTI::TCC_Free;
48 
49   if (Imm.getBitWidth() <= 64) {
50     // Constants loaded via lgfi.
51     if (isInt<32>(Imm.getSExtValue()))
52       return TTI::TCC_Basic;
53     // Constants loaded via llilf.
54     if (isUInt<32>(Imm.getZExtValue()))
55       return TTI::TCC_Basic;
56     // Constants loaded via llihf:
57     if ((Imm.getZExtValue() & 0xffffffff) == 0)
58       return TTI::TCC_Basic;
59 
60     return 2 * TTI::TCC_Basic;
61   }
62 
63   return 4 * TTI::TCC_Basic;
64 }
65 
66 int SystemZTTIImpl::getIntImmCostInst(unsigned Opcode, unsigned Idx,
67                                       const APInt &Imm, Type *Ty,
68                                       TTI::TargetCostKind CostKind,
69                                       Instruction *Inst) {
70   assert(Ty->isIntegerTy());
71 
72   unsigned BitSize = Ty->getPrimitiveSizeInBits();
73   // There is no cost model for constants with a bit size of 0. Return TCC_Free
74   // here, so that constant hoisting will ignore this constant.
75   if (BitSize == 0)
76     return TTI::TCC_Free;
77   // No cost model for operations on integers larger than 64 bit implemented yet.
78   if (BitSize > 64)
79     return TTI::TCC_Free;
80 
81   switch (Opcode) {
82   default:
83     return TTI::TCC_Free;
84   case Instruction::GetElementPtr:
85     // Always hoist the base address of a GetElementPtr. This prevents the
86     // creation of new constants for every base constant that gets constant
87     // folded with the offset.
88     if (Idx == 0)
89       return 2 * TTI::TCC_Basic;
90     return TTI::TCC_Free;
91   case Instruction::Store:
92     if (Idx == 0 && Imm.getBitWidth() <= 64) {
93       // Any 8-bit immediate store can by implemented via mvi.
94       if (BitSize == 8)
95         return TTI::TCC_Free;
96       // 16-bit immediate values can be stored via mvhhi/mvhi/mvghi.
97       if (isInt<16>(Imm.getSExtValue()))
98         return TTI::TCC_Free;
99     }
100     break;
101   case Instruction::ICmp:
102     if (Idx == 1 && Imm.getBitWidth() <= 64) {
103       // Comparisons against signed 32-bit immediates implemented via cgfi.
104       if (isInt<32>(Imm.getSExtValue()))
105         return TTI::TCC_Free;
106       // Comparisons against unsigned 32-bit immediates implemented via clgfi.
107       if (isUInt<32>(Imm.getZExtValue()))
108         return TTI::TCC_Free;
109     }
110     break;
111   case Instruction::Add:
112   case Instruction::Sub:
113     if (Idx == 1 && Imm.getBitWidth() <= 64) {
114       // We use algfi/slgfi to add/subtract 32-bit unsigned immediates.
115       if (isUInt<32>(Imm.getZExtValue()))
116         return TTI::TCC_Free;
117       // Or their negation, by swapping addition vs. subtraction.
118       if (isUInt<32>(-Imm.getSExtValue()))
119         return TTI::TCC_Free;
120     }
121     break;
122   case Instruction::Mul:
123     if (Idx == 1 && Imm.getBitWidth() <= 64) {
124       // We use msgfi to multiply by 32-bit signed immediates.
125       if (isInt<32>(Imm.getSExtValue()))
126         return TTI::TCC_Free;
127     }
128     break;
129   case Instruction::Or:
130   case Instruction::Xor:
131     if (Idx == 1 && Imm.getBitWidth() <= 64) {
132       // Masks supported by oilf/xilf.
133       if (isUInt<32>(Imm.getZExtValue()))
134         return TTI::TCC_Free;
135       // Masks supported by oihf/xihf.
136       if ((Imm.getZExtValue() & 0xffffffff) == 0)
137         return TTI::TCC_Free;
138     }
139     break;
140   case Instruction::And:
141     if (Idx == 1 && Imm.getBitWidth() <= 64) {
142       // Any 32-bit AND operation can by implemented via nilf.
143       if (BitSize <= 32)
144         return TTI::TCC_Free;
145       // 64-bit masks supported by nilf.
146       if (isUInt<32>(~Imm.getZExtValue()))
147         return TTI::TCC_Free;
148       // 64-bit masks supported by nilh.
149       if ((Imm.getZExtValue() & 0xffffffff) == 0xffffffff)
150         return TTI::TCC_Free;
151       // Some 64-bit AND operations can be implemented via risbg.
152       const SystemZInstrInfo *TII = ST->getInstrInfo();
153       unsigned Start, End;
154       if (TII->isRxSBGMask(Imm.getZExtValue(), BitSize, Start, End))
155         return TTI::TCC_Free;
156     }
157     break;
158   case Instruction::Shl:
159   case Instruction::LShr:
160   case Instruction::AShr:
161     // Always return TCC_Free for the shift value of a shift instruction.
162     if (Idx == 1)
163       return TTI::TCC_Free;
164     break;
165   case Instruction::UDiv:
166   case Instruction::SDiv:
167   case Instruction::URem:
168   case Instruction::SRem:
169   case Instruction::Trunc:
170   case Instruction::ZExt:
171   case Instruction::SExt:
172   case Instruction::IntToPtr:
173   case Instruction::PtrToInt:
174   case Instruction::BitCast:
175   case Instruction::PHI:
176   case Instruction::Call:
177   case Instruction::Select:
178   case Instruction::Ret:
179   case Instruction::Load:
180     break;
181   }
182 
183   return SystemZTTIImpl::getIntImmCost(Imm, Ty, CostKind);
184 }
185 
186 int SystemZTTIImpl::getIntImmCostIntrin(Intrinsic::ID IID, unsigned Idx,
187                                         const APInt &Imm, Type *Ty,
188                                         TTI::TargetCostKind CostKind) {
189   assert(Ty->isIntegerTy());
190 
191   unsigned BitSize = Ty->getPrimitiveSizeInBits();
192   // There is no cost model for constants with a bit size of 0. Return TCC_Free
193   // here, so that constant hoisting will ignore this constant.
194   if (BitSize == 0)
195     return TTI::TCC_Free;
196   // No cost model for operations on integers larger than 64 bit implemented yet.
197   if (BitSize > 64)
198     return TTI::TCC_Free;
199 
200   switch (IID) {
201   default:
202     return TTI::TCC_Free;
203   case Intrinsic::sadd_with_overflow:
204   case Intrinsic::uadd_with_overflow:
205   case Intrinsic::ssub_with_overflow:
206   case Intrinsic::usub_with_overflow:
207     // These get expanded to include a normal addition/subtraction.
208     if (Idx == 1 && Imm.getBitWidth() <= 64) {
209       if (isUInt<32>(Imm.getZExtValue()))
210         return TTI::TCC_Free;
211       if (isUInt<32>(-Imm.getSExtValue()))
212         return TTI::TCC_Free;
213     }
214     break;
215   case Intrinsic::smul_with_overflow:
216   case Intrinsic::umul_with_overflow:
217     // These get expanded to include a normal multiplication.
218     if (Idx == 1 && Imm.getBitWidth() <= 64) {
219       if (isInt<32>(Imm.getSExtValue()))
220         return TTI::TCC_Free;
221     }
222     break;
223   case Intrinsic::experimental_stackmap:
224     if ((Idx < 2) || (Imm.getBitWidth() <= 64 && isInt<64>(Imm.getSExtValue())))
225       return TTI::TCC_Free;
226     break;
227   case Intrinsic::experimental_patchpoint_void:
228   case Intrinsic::experimental_patchpoint_i64:
229     if ((Idx < 4) || (Imm.getBitWidth() <= 64 && isInt<64>(Imm.getSExtValue())))
230       return TTI::TCC_Free;
231     break;
232   }
233   return SystemZTTIImpl::getIntImmCost(Imm, Ty, CostKind);
234 }
235 
236 TargetTransformInfo::PopcntSupportKind
237 SystemZTTIImpl::getPopcntSupport(unsigned TyWidth) {
238   assert(isPowerOf2_32(TyWidth) && "Type width must be power of 2");
239   if (ST->hasPopulationCount() && TyWidth <= 64)
240     return TTI::PSK_FastHardware;
241   return TTI::PSK_Software;
242 }
243 
244 void SystemZTTIImpl::getUnrollingPreferences(Loop *L, ScalarEvolution &SE,
245                                              TTI::UnrollingPreferences &UP) {
246   // Find out if L contains a call, what the machine instruction count
247   // estimate is, and how many stores there are.
248   bool HasCall = false;
249   unsigned NumStores = 0;
250   for (auto &BB : L->blocks())
251     for (auto &I : *BB) {
252       if (isa<CallInst>(&I) || isa<InvokeInst>(&I)) {
253         if (const Function *F = cast<CallBase>(I).getCalledFunction()) {
254           if (isLoweredToCall(F))
255             HasCall = true;
256           if (F->getIntrinsicID() == Intrinsic::memcpy ||
257               F->getIntrinsicID() == Intrinsic::memset)
258             NumStores++;
259         } else { // indirect call.
260           HasCall = true;
261         }
262       }
263       if (isa<StoreInst>(&I)) {
264         Type *MemAccessTy = I.getOperand(0)->getType();
265         NumStores += getMemoryOpCost(Instruction::Store, MemAccessTy, None, 0,
266                                      TTI::TCK_RecipThroughput);
267       }
268     }
269 
270   // The z13 processor will run out of store tags if too many stores
271   // are fed into it too quickly. Therefore make sure there are not
272   // too many stores in the resulting unrolled loop.
273   unsigned const Max = (NumStores ? (12 / NumStores) : UINT_MAX);
274 
275   if (HasCall) {
276     // Only allow full unrolling if loop has any calls.
277     UP.FullUnrollMaxCount = Max;
278     UP.MaxCount = 1;
279     return;
280   }
281 
282   UP.MaxCount = Max;
283   if (UP.MaxCount <= 1)
284     return;
285 
286   // Allow partial and runtime trip count unrolling.
287   UP.Partial = UP.Runtime = true;
288 
289   UP.PartialThreshold = 75;
290   UP.DefaultUnrollRuntimeCount = 4;
291 
292   // Allow expensive instructions in the pre-header of the loop.
293   UP.AllowExpensiveTripCount = true;
294 
295   UP.Force = true;
296 }
297 
298 void SystemZTTIImpl::getPeelingPreferences(Loop *L, ScalarEvolution &SE,
299                                            TTI::PeelingPreferences &PP) {
300   BaseT::getPeelingPreferences(L, SE, PP);
301 }
302 
303 bool SystemZTTIImpl::isLSRCostLess(TargetTransformInfo::LSRCost &C1,
304                                    TargetTransformInfo::LSRCost &C2) {
305   // SystemZ specific: check instruction count (first), and don't care about
306   // ImmCost, since offsets are checked explicitly.
307   return std::tie(C1.Insns, C1.NumRegs, C1.AddRecCost,
308                   C1.NumIVMuls, C1.NumBaseAdds,
309                   C1.ScaleCost, C1.SetupCost) <
310     std::tie(C2.Insns, C2.NumRegs, C2.AddRecCost,
311              C2.NumIVMuls, C2.NumBaseAdds,
312              C2.ScaleCost, C2.SetupCost);
313 }
314 
315 unsigned SystemZTTIImpl::getNumberOfRegisters(unsigned ClassID) const {
316   bool Vector = (ClassID == 1);
317   if (!Vector)
318     // Discount the stack pointer.  Also leave out %r0, since it can't
319     // be used in an address.
320     return 14;
321   if (ST->hasVector())
322     return 32;
323   return 0;
324 }
325 
326 unsigned SystemZTTIImpl::getRegisterBitWidth(bool Vector) const {
327   if (!Vector)
328     return 64;
329   if (ST->hasVector())
330     return 128;
331   return 0;
332 }
333 
334 unsigned SystemZTTIImpl::getMinPrefetchStride(unsigned NumMemAccesses,
335                                               unsigned NumStridedMemAccesses,
336                                               unsigned NumPrefetches,
337                                               bool HasCall) const {
338   // Don't prefetch a loop with many far apart accesses.
339   if (NumPrefetches > 16)
340     return UINT_MAX;
341 
342   // Emit prefetch instructions for smaller strides in cases where we think
343   // the hardware prefetcher might not be able to keep up.
344   if (NumStridedMemAccesses > 32 &&
345       NumStridedMemAccesses == NumMemAccesses && !HasCall)
346     return 1;
347 
348   return ST->hasMiscellaneousExtensions3() ? 8192 : 2048;
349 }
350 
351 bool SystemZTTIImpl::hasDivRemOp(Type *DataType, bool IsSigned) {
352   EVT VT = TLI->getValueType(DL, DataType);
353   return (VT.isScalarInteger() && TLI->isTypeLegal(VT));
354 }
355 
356 // Return the bit size for the scalar type or vector element
357 // type. getScalarSizeInBits() returns 0 for a pointer type.
358 static unsigned getScalarSizeInBits(Type *Ty) {
359   unsigned Size =
360     (Ty->isPtrOrPtrVectorTy() ? 64U : Ty->getScalarSizeInBits());
361   assert(Size > 0 && "Element must have non-zero size.");
362   return Size;
363 }
364 
365 // getNumberOfParts() calls getTypeLegalizationCost() which splits the vector
366 // type until it is legal. This would e.g. return 4 for <6 x i64>, instead of
367 // 3.
368 static unsigned getNumVectorRegs(Type *Ty) {
369   auto *VTy = cast<FixedVectorType>(Ty);
370   unsigned WideBits = getScalarSizeInBits(Ty) * VTy->getNumElements();
371   assert(WideBits > 0 && "Could not compute size of vector");
372   return ((WideBits % 128U) ? ((WideBits / 128U) + 1) : (WideBits / 128U));
373 }
374 
375 int SystemZTTIImpl::getArithmeticInstrCost(
376     unsigned Opcode, Type *Ty, TTI::TargetCostKind CostKind,
377     TTI::OperandValueKind Op1Info,
378     TTI::OperandValueKind Op2Info, TTI::OperandValueProperties Opd1PropInfo,
379     TTI::OperandValueProperties Opd2PropInfo, ArrayRef<const Value *> Args,
380     const Instruction *CxtI) {
381 
382   // TODO: Handle more cost kinds.
383   if (CostKind != TTI::TCK_RecipThroughput)
384     return BaseT::getArithmeticInstrCost(Opcode, Ty, CostKind, Op1Info,
385                                          Op2Info, Opd1PropInfo,
386                                          Opd2PropInfo, Args, CxtI);
387 
388   // TODO: return a good value for BB-VECTORIZER that includes the
389   // immediate loads, which we do not want to count for the loop
390   // vectorizer, since they are hopefully hoisted out of the loop. This
391   // would require a new parameter 'InLoop', but not sure if constant
392   // args are common enough to motivate this.
393 
394   unsigned ScalarBits = Ty->getScalarSizeInBits();
395 
396   // There are thre cases of division and remainder: Dividing with a register
397   // needs a divide instruction. A divisor which is a power of two constant
398   // can be implemented with a sequence of shifts. Any other constant needs a
399   // multiply and shifts.
400   const unsigned DivInstrCost = 20;
401   const unsigned DivMulSeqCost = 10;
402   const unsigned SDivPow2Cost = 4;
403 
404   bool SignedDivRem =
405       Opcode == Instruction::SDiv || Opcode == Instruction::SRem;
406   bool UnsignedDivRem =
407       Opcode == Instruction::UDiv || Opcode == Instruction::URem;
408 
409   // Check for a constant divisor.
410   bool DivRemConst = false;
411   bool DivRemConstPow2 = false;
412   if ((SignedDivRem || UnsignedDivRem) && Args.size() == 2) {
413     if (const Constant *C = dyn_cast<Constant>(Args[1])) {
414       const ConstantInt *CVal =
415           (C->getType()->isVectorTy()
416                ? dyn_cast_or_null<const ConstantInt>(C->getSplatValue())
417                : dyn_cast<const ConstantInt>(C));
418       if (CVal != nullptr &&
419           (CVal->getValue().isPowerOf2() || (-CVal->getValue()).isPowerOf2()))
420         DivRemConstPow2 = true;
421       else
422         DivRemConst = true;
423     }
424   }
425 
426   if (!Ty->isVectorTy()) {
427     // These FP operations are supported with a dedicated instruction for
428     // float, double and fp128 (base implementation assumes float generally
429     // costs 2).
430     if (Opcode == Instruction::FAdd || Opcode == Instruction::FSub ||
431         Opcode == Instruction::FMul || Opcode == Instruction::FDiv)
432       return 1;
433 
434     // There is no native support for FRem.
435     if (Opcode == Instruction::FRem)
436       return LIBCALL_COST;
437 
438     // Give discount for some combined logical operations if supported.
439     if (Args.size() == 2 && ST->hasMiscellaneousExtensions3()) {
440       if (Opcode == Instruction::Xor) {
441         for (const Value *A : Args) {
442           if (const Instruction *I = dyn_cast<Instruction>(A))
443             if (I->hasOneUse() &&
444                 (I->getOpcode() == Instruction::And ||
445                  I->getOpcode() == Instruction::Or ||
446                  I->getOpcode() == Instruction::Xor))
447               return 0;
448         }
449       }
450       else if (Opcode == Instruction::Or || Opcode == Instruction::And) {
451         for (const Value *A : Args) {
452           if (const Instruction *I = dyn_cast<Instruction>(A))
453             if (I->hasOneUse() && I->getOpcode() == Instruction::Xor)
454               return 0;
455         }
456       }
457     }
458 
459     // Or requires one instruction, although it has custom handling for i64.
460     if (Opcode == Instruction::Or)
461       return 1;
462 
463     if (Opcode == Instruction::Xor && ScalarBits == 1) {
464       if (ST->hasLoadStoreOnCond2())
465         return 5; // 2 * (li 0; loc 1); xor
466       return 7; // 2 * ipm sequences ; xor ; shift ; compare
467     }
468 
469     if (DivRemConstPow2)
470       return (SignedDivRem ? SDivPow2Cost : 1);
471     if (DivRemConst)
472       return DivMulSeqCost;
473     if (SignedDivRem || UnsignedDivRem)
474       return DivInstrCost;
475   }
476   else if (ST->hasVector()) {
477     auto *VTy = cast<FixedVectorType>(Ty);
478     unsigned VF = VTy->getNumElements();
479     unsigned NumVectors = getNumVectorRegs(Ty);
480 
481     // These vector operations are custom handled, but are still supported
482     // with one instruction per vector, regardless of element size.
483     if (Opcode == Instruction::Shl || Opcode == Instruction::LShr ||
484         Opcode == Instruction::AShr) {
485       return NumVectors;
486     }
487 
488     if (DivRemConstPow2)
489       return (NumVectors * (SignedDivRem ? SDivPow2Cost : 1));
490     if (DivRemConst)
491       return VF * DivMulSeqCost + getScalarizationOverhead(VTy, Args);
492     if ((SignedDivRem || UnsignedDivRem) && VF > 4)
493       // Temporary hack: disable high vectorization factors with integer
494       // division/remainder, which will get scalarized and handled with
495       // GR128 registers. The mischeduler is not clever enough to avoid
496       // spilling yet.
497       return 1000;
498 
499     // These FP operations are supported with a single vector instruction for
500     // double (base implementation assumes float generally costs 2). For
501     // FP128, the scalar cost is 1, and there is no overhead since the values
502     // are already in scalar registers.
503     if (Opcode == Instruction::FAdd || Opcode == Instruction::FSub ||
504         Opcode == Instruction::FMul || Opcode == Instruction::FDiv) {
505       switch (ScalarBits) {
506       case 32: {
507         // The vector enhancements facility 1 provides v4f32 instructions.
508         if (ST->hasVectorEnhancements1())
509           return NumVectors;
510         // Return the cost of multiple scalar invocation plus the cost of
511         // inserting and extracting the values.
512         unsigned ScalarCost =
513             getArithmeticInstrCost(Opcode, Ty->getScalarType(), CostKind);
514         unsigned Cost = (VF * ScalarCost) + getScalarizationOverhead(VTy, Args);
515         // FIXME: VF 2 for these FP operations are currently just as
516         // expensive as for VF 4.
517         if (VF == 2)
518           Cost *= 2;
519         return Cost;
520       }
521       case 64:
522       case 128:
523         return NumVectors;
524       default:
525         break;
526       }
527     }
528 
529     // There is no native support for FRem.
530     if (Opcode == Instruction::FRem) {
531       unsigned Cost = (VF * LIBCALL_COST) + getScalarizationOverhead(VTy, Args);
532       // FIXME: VF 2 for float is currently just as expensive as for VF 4.
533       if (VF == 2 && ScalarBits == 32)
534         Cost *= 2;
535       return Cost;
536     }
537   }
538 
539   // Fallback to the default implementation.
540   return BaseT::getArithmeticInstrCost(Opcode, Ty, CostKind, Op1Info, Op2Info,
541                                        Opd1PropInfo, Opd2PropInfo, Args, CxtI);
542 }
543 
544 int SystemZTTIImpl::getShuffleCost(TTI::ShuffleKind Kind, VectorType *Tp,
545                                    int Index, VectorType *SubTp) {
546   if (ST->hasVector()) {
547     unsigned NumVectors = getNumVectorRegs(Tp);
548 
549     // TODO: Since fp32 is expanded, the shuffle cost should always be 0.
550 
551     // FP128 values are always in scalar registers, so there is no work
552     // involved with a shuffle, except for broadcast. In that case register
553     // moves are done with a single instruction per element.
554     if (Tp->getScalarType()->isFP128Ty())
555       return (Kind == TargetTransformInfo::SK_Broadcast ? NumVectors - 1 : 0);
556 
557     switch (Kind) {
558     case  TargetTransformInfo::SK_ExtractSubvector:
559       // ExtractSubvector Index indicates start offset.
560 
561       // Extracting a subvector from first index is a noop.
562       return (Index == 0 ? 0 : NumVectors);
563 
564     case TargetTransformInfo::SK_Broadcast:
565       // Loop vectorizer calls here to figure out the extra cost of
566       // broadcasting a loaded value to all elements of a vector. Since vlrep
567       // loads and replicates with a single instruction, adjust the returned
568       // value.
569       return NumVectors - 1;
570 
571     default:
572 
573       // SystemZ supports single instruction permutation / replication.
574       return NumVectors;
575     }
576   }
577 
578   return BaseT::getShuffleCost(Kind, Tp, Index, SubTp);
579 }
580 
581 // Return the log2 difference of the element sizes of the two vector types.
582 static unsigned getElSizeLog2Diff(Type *Ty0, Type *Ty1) {
583   unsigned Bits0 = Ty0->getScalarSizeInBits();
584   unsigned Bits1 = Ty1->getScalarSizeInBits();
585 
586   if (Bits1 >  Bits0)
587     return (Log2_32(Bits1) - Log2_32(Bits0));
588 
589   return (Log2_32(Bits0) - Log2_32(Bits1));
590 }
591 
592 // Return the number of instructions needed to truncate SrcTy to DstTy.
593 unsigned SystemZTTIImpl::
594 getVectorTruncCost(Type *SrcTy, Type *DstTy) {
595   assert (SrcTy->isVectorTy() && DstTy->isVectorTy());
596   assert (SrcTy->getPrimitiveSizeInBits() > DstTy->getPrimitiveSizeInBits() &&
597           "Packing must reduce size of vector type.");
598   assert(cast<FixedVectorType>(SrcTy)->getNumElements() ==
599              cast<FixedVectorType>(DstTy)->getNumElements() &&
600          "Packing should not change number of elements.");
601 
602   // TODO: Since fp32 is expanded, the extract cost should always be 0.
603 
604   unsigned NumParts = getNumVectorRegs(SrcTy);
605   if (NumParts <= 2)
606     // Up to 2 vector registers can be truncated efficiently with pack or
607     // permute. The latter requires an immediate mask to be loaded, which
608     // typically gets hoisted out of a loop.  TODO: return a good value for
609     // BB-VECTORIZER that includes the immediate loads, which we do not want
610     // to count for the loop vectorizer.
611     return 1;
612 
613   unsigned Cost = 0;
614   unsigned Log2Diff = getElSizeLog2Diff(SrcTy, DstTy);
615   unsigned VF = cast<FixedVectorType>(SrcTy)->getNumElements();
616   for (unsigned P = 0; P < Log2Diff; ++P) {
617     if (NumParts > 1)
618       NumParts /= 2;
619     Cost += NumParts;
620   }
621 
622   // Currently, a general mix of permutes and pack instructions is output by
623   // isel, which follow the cost computation above except for this case which
624   // is one instruction less:
625   if (VF == 8 && SrcTy->getScalarSizeInBits() == 64 &&
626       DstTy->getScalarSizeInBits() == 8)
627     Cost--;
628 
629   return Cost;
630 }
631 
632 // Return the cost of converting a vector bitmask produced by a compare
633 // (SrcTy), to the type of the select or extend instruction (DstTy).
634 unsigned SystemZTTIImpl::
635 getVectorBitmaskConversionCost(Type *SrcTy, Type *DstTy) {
636   assert (SrcTy->isVectorTy() && DstTy->isVectorTy() &&
637           "Should only be called with vector types.");
638 
639   unsigned PackCost = 0;
640   unsigned SrcScalarBits = SrcTy->getScalarSizeInBits();
641   unsigned DstScalarBits = DstTy->getScalarSizeInBits();
642   unsigned Log2Diff = getElSizeLog2Diff(SrcTy, DstTy);
643   if (SrcScalarBits > DstScalarBits)
644     // The bitmask will be truncated.
645     PackCost = getVectorTruncCost(SrcTy, DstTy);
646   else if (SrcScalarBits < DstScalarBits) {
647     unsigned DstNumParts = getNumVectorRegs(DstTy);
648     // Each vector select needs its part of the bitmask unpacked.
649     PackCost = Log2Diff * DstNumParts;
650     // Extra cost for moving part of mask before unpacking.
651     PackCost += DstNumParts - 1;
652   }
653 
654   return PackCost;
655 }
656 
657 // Return the type of the compared operands. This is needed to compute the
658 // cost for a Select / ZExt or SExt instruction.
659 static Type *getCmpOpsType(const Instruction *I, unsigned VF = 1) {
660   Type *OpTy = nullptr;
661   if (CmpInst *CI = dyn_cast<CmpInst>(I->getOperand(0)))
662     OpTy = CI->getOperand(0)->getType();
663   else if (Instruction *LogicI = dyn_cast<Instruction>(I->getOperand(0)))
664     if (LogicI->getNumOperands() == 2)
665       if (CmpInst *CI0 = dyn_cast<CmpInst>(LogicI->getOperand(0)))
666         if (isa<CmpInst>(LogicI->getOperand(1)))
667           OpTy = CI0->getOperand(0)->getType();
668 
669   if (OpTy != nullptr) {
670     if (VF == 1) {
671       assert (!OpTy->isVectorTy() && "Expected scalar type");
672       return OpTy;
673     }
674     // Return the potentially vectorized type based on 'I' and 'VF'.  'I' may
675     // be either scalar or already vectorized with a same or lesser VF.
676     Type *ElTy = OpTy->getScalarType();
677     return FixedVectorType::get(ElTy, VF);
678   }
679 
680   return nullptr;
681 }
682 
683 // Get the cost of converting a boolean vector to a vector with same width
684 // and element size as Dst, plus the cost of zero extending if needed.
685 unsigned SystemZTTIImpl::
686 getBoolVecToIntConversionCost(unsigned Opcode, Type *Dst,
687                               const Instruction *I) {
688   auto *DstVTy = cast<FixedVectorType>(Dst);
689   unsigned VF = DstVTy->getNumElements();
690   unsigned Cost = 0;
691   // If we know what the widths of the compared operands, get any cost of
692   // converting it to match Dst. Otherwise assume same widths.
693   Type *CmpOpTy = ((I != nullptr) ? getCmpOpsType(I, VF) : nullptr);
694   if (CmpOpTy != nullptr)
695     Cost = getVectorBitmaskConversionCost(CmpOpTy, Dst);
696   if (Opcode == Instruction::ZExt || Opcode == Instruction::UIToFP)
697     // One 'vn' per dst vector with an immediate mask.
698     Cost += getNumVectorRegs(Dst);
699   return Cost;
700 }
701 
702 int SystemZTTIImpl::getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src,
703                                      TTI::CastContextHint CCH,
704                                      TTI::TargetCostKind CostKind,
705                                      const Instruction *I) {
706   // FIXME: Can the logic below also be used for these cost kinds?
707   if (CostKind == TTI::TCK_CodeSize || CostKind == TTI::TCK_SizeAndLatency) {
708     int BaseCost = BaseT::getCastInstrCost(Opcode, Dst, Src, CCH, CostKind, I);
709     return BaseCost == 0 ? BaseCost : 1;
710   }
711 
712   unsigned DstScalarBits = Dst->getScalarSizeInBits();
713   unsigned SrcScalarBits = Src->getScalarSizeInBits();
714 
715   if (!Src->isVectorTy()) {
716     assert (!Dst->isVectorTy());
717 
718     if (Opcode == Instruction::SIToFP || Opcode == Instruction::UIToFP) {
719       if (SrcScalarBits >= 32 ||
720           (I != nullptr && isa<LoadInst>(I->getOperand(0))))
721         return 1;
722       return SrcScalarBits > 1 ? 2 /*i8/i16 extend*/ : 5 /*branch seq.*/;
723     }
724 
725     if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
726         Src->isIntegerTy(1)) {
727       if (ST->hasLoadStoreOnCond2())
728         return 2; // li 0; loc 1
729 
730       // This should be extension of a compare i1 result, which is done with
731       // ipm and a varying sequence of instructions.
732       unsigned Cost = 0;
733       if (Opcode == Instruction::SExt)
734         Cost = (DstScalarBits < 64 ? 3 : 4);
735       if (Opcode == Instruction::ZExt)
736         Cost = 3;
737       Type *CmpOpTy = ((I != nullptr) ? getCmpOpsType(I) : nullptr);
738       if (CmpOpTy != nullptr && CmpOpTy->isFloatingPointTy())
739         // If operands of an fp-type was compared, this costs +1.
740         Cost++;
741       return Cost;
742     }
743   }
744   else if (ST->hasVector()) {
745     auto *SrcVecTy = cast<FixedVectorType>(Src);
746     auto *DstVecTy = cast<FixedVectorType>(Dst);
747     unsigned VF = SrcVecTy->getNumElements();
748     unsigned NumDstVectors = getNumVectorRegs(Dst);
749     unsigned NumSrcVectors = getNumVectorRegs(Src);
750 
751     if (Opcode == Instruction::Trunc) {
752       if (Src->getScalarSizeInBits() == Dst->getScalarSizeInBits())
753         return 0; // Check for NOOP conversions.
754       return getVectorTruncCost(Src, Dst);
755     }
756 
757     if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
758       if (SrcScalarBits >= 8) {
759         // ZExt/SExt will be handled with one unpack per doubling of width.
760         unsigned NumUnpacks = getElSizeLog2Diff(Src, Dst);
761 
762         // For types that spans multiple vector registers, some additional
763         // instructions are used to setup the unpacking.
764         unsigned NumSrcVectorOps =
765           (NumUnpacks > 1 ? (NumDstVectors - NumSrcVectors)
766                           : (NumDstVectors / 2));
767 
768         return (NumUnpacks * NumDstVectors) + NumSrcVectorOps;
769       }
770       else if (SrcScalarBits == 1)
771         return getBoolVecToIntConversionCost(Opcode, Dst, I);
772     }
773 
774     if (Opcode == Instruction::SIToFP || Opcode == Instruction::UIToFP ||
775         Opcode == Instruction::FPToSI || Opcode == Instruction::FPToUI) {
776       // TODO: Fix base implementation which could simplify things a bit here
777       // (seems to miss on differentiating on scalar/vector types).
778 
779       // Only 64 bit vector conversions are natively supported before z15.
780       if (DstScalarBits == 64 || ST->hasVectorEnhancements2()) {
781         if (SrcScalarBits == DstScalarBits)
782           return NumDstVectors;
783 
784         if (SrcScalarBits == 1)
785           return getBoolVecToIntConversionCost(Opcode, Dst, I) + NumDstVectors;
786       }
787 
788       // Return the cost of multiple scalar invocation plus the cost of
789       // inserting and extracting the values. Base implementation does not
790       // realize float->int gets scalarized.
791       unsigned ScalarCost = getCastInstrCost(
792           Opcode, Dst->getScalarType(), Src->getScalarType(), CCH, CostKind);
793       unsigned TotCost = VF * ScalarCost;
794       bool NeedsInserts = true, NeedsExtracts = true;
795       // FP128 registers do not get inserted or extracted.
796       if (DstScalarBits == 128 &&
797           (Opcode == Instruction::SIToFP || Opcode == Instruction::UIToFP))
798         NeedsInserts = false;
799       if (SrcScalarBits == 128 &&
800           (Opcode == Instruction::FPToSI || Opcode == Instruction::FPToUI))
801         NeedsExtracts = false;
802 
803       TotCost += getScalarizationOverhead(SrcVecTy, false, NeedsExtracts);
804       TotCost += getScalarizationOverhead(DstVecTy, NeedsInserts, false);
805 
806       // FIXME: VF 2 for float<->i32 is currently just as expensive as for VF 4.
807       if (VF == 2 && SrcScalarBits == 32 && DstScalarBits == 32)
808         TotCost *= 2;
809 
810       return TotCost;
811     }
812 
813     if (Opcode == Instruction::FPTrunc) {
814       if (SrcScalarBits == 128)  // fp128 -> double/float + inserts of elements.
815         return VF /*ldxbr/lexbr*/ +
816                getScalarizationOverhead(DstVecTy, true, false);
817       else // double -> float
818         return VF / 2 /*vledb*/ + std::max(1U, VF / 4 /*vperm*/);
819     }
820 
821     if (Opcode == Instruction::FPExt) {
822       if (SrcScalarBits == 32 && DstScalarBits == 64) {
823         // float -> double is very rare and currently unoptimized. Instead of
824         // using vldeb, which can do two at a time, all conversions are
825         // scalarized.
826         return VF * 2;
827       }
828       // -> fp128.  VF * lxdb/lxeb + extraction of elements.
829       return VF + getScalarizationOverhead(SrcVecTy, false, true);
830     }
831   }
832 
833   return BaseT::getCastInstrCost(Opcode, Dst, Src, CCH, CostKind, I);
834 }
835 
836 // Scalar i8 / i16 operations will typically be made after first extending
837 // the operands to i32.
838 static unsigned getOperandsExtensionCost(const Instruction *I) {
839   unsigned ExtCost = 0;
840   for (Value *Op : I->operands())
841     // A load of i8 or i16 sign/zero extends to i32.
842     if (!isa<LoadInst>(Op) && !isa<ConstantInt>(Op))
843       ExtCost++;
844 
845   return ExtCost;
846 }
847 
848 int SystemZTTIImpl::getCmpSelInstrCost(unsigned Opcode, Type *ValTy,
849                                        Type *CondTy,
850                                        TTI::TargetCostKind CostKind,
851                                        const Instruction *I) {
852   if (CostKind != TTI::TCK_RecipThroughput)
853     return BaseT::getCmpSelInstrCost(Opcode, ValTy, CondTy, CostKind);
854 
855   if (!ValTy->isVectorTy()) {
856     switch (Opcode) {
857     case Instruction::ICmp: {
858       // A loaded value compared with 0 with multiple users becomes Load and
859       // Test. The load is then not foldable, so return 0 cost for the ICmp.
860       unsigned ScalarBits = ValTy->getScalarSizeInBits();
861       if (I != nullptr && ScalarBits >= 32)
862         if (LoadInst *Ld = dyn_cast<LoadInst>(I->getOperand(0)))
863           if (const ConstantInt *C = dyn_cast<ConstantInt>(I->getOperand(1)))
864             if (!Ld->hasOneUse() && Ld->getParent() == I->getParent() &&
865                 C->isZero())
866               return 0;
867 
868       unsigned Cost = 1;
869       if (ValTy->isIntegerTy() && ValTy->getScalarSizeInBits() <= 16)
870         Cost += (I != nullptr ? getOperandsExtensionCost(I) : 2);
871       return Cost;
872     }
873     case Instruction::Select:
874       if (ValTy->isFloatingPointTy())
875         return 4; // No load on condition for FP - costs a conditional jump.
876       return 1; // Load On Condition / Select Register.
877     }
878   }
879   else if (ST->hasVector()) {
880     unsigned VF = cast<FixedVectorType>(ValTy)->getNumElements();
881 
882     // Called with a compare instruction.
883     if (Opcode == Instruction::ICmp || Opcode == Instruction::FCmp) {
884       unsigned PredicateExtraCost = 0;
885       if (I != nullptr) {
886         // Some predicates cost one or two extra instructions.
887         switch (cast<CmpInst>(I)->getPredicate()) {
888         case CmpInst::Predicate::ICMP_NE:
889         case CmpInst::Predicate::ICMP_UGE:
890         case CmpInst::Predicate::ICMP_ULE:
891         case CmpInst::Predicate::ICMP_SGE:
892         case CmpInst::Predicate::ICMP_SLE:
893           PredicateExtraCost = 1;
894           break;
895         case CmpInst::Predicate::FCMP_ONE:
896         case CmpInst::Predicate::FCMP_ORD:
897         case CmpInst::Predicate::FCMP_UEQ:
898         case CmpInst::Predicate::FCMP_UNO:
899           PredicateExtraCost = 2;
900           break;
901         default:
902           break;
903         }
904       }
905 
906       // Float is handled with 2*vmr[lh]f + 2*vldeb + vfchdb for each pair of
907       // floats.  FIXME: <2 x float> generates same code as <4 x float>.
908       unsigned CmpCostPerVector = (ValTy->getScalarType()->isFloatTy() ? 10 : 1);
909       unsigned NumVecs_cmp = getNumVectorRegs(ValTy);
910 
911       unsigned Cost = (NumVecs_cmp * (CmpCostPerVector + PredicateExtraCost));
912       return Cost;
913     }
914     else { // Called with a select instruction.
915       assert (Opcode == Instruction::Select);
916 
917       // We can figure out the extra cost of packing / unpacking if the
918       // instruction was passed and the compare instruction is found.
919       unsigned PackCost = 0;
920       Type *CmpOpTy = ((I != nullptr) ? getCmpOpsType(I, VF) : nullptr);
921       if (CmpOpTy != nullptr)
922         PackCost =
923           getVectorBitmaskConversionCost(CmpOpTy, ValTy);
924 
925       return getNumVectorRegs(ValTy) /*vsel*/ + PackCost;
926     }
927   }
928 
929   return BaseT::getCmpSelInstrCost(Opcode, ValTy, CondTy, CostKind);
930 }
931 
932 int SystemZTTIImpl::
933 getVectorInstrCost(unsigned Opcode, Type *Val, unsigned Index) {
934   // vlvgp will insert two grs into a vector register, so only count half the
935   // number of instructions.
936   if (Opcode == Instruction::InsertElement && Val->isIntOrIntVectorTy(64))
937     return ((Index % 2 == 0) ? 1 : 0);
938 
939   if (Opcode == Instruction::ExtractElement) {
940     int Cost = ((getScalarSizeInBits(Val) == 1) ? 2 /*+test-under-mask*/ : 1);
941 
942     // Give a slight penalty for moving out of vector pipeline to FXU unit.
943     if (Index == 0 && Val->isIntOrIntVectorTy())
944       Cost += 1;
945 
946     return Cost;
947   }
948 
949   return BaseT::getVectorInstrCost(Opcode, Val, Index);
950 }
951 
952 // Check if a load may be folded as a memory operand in its user.
953 bool SystemZTTIImpl::
954 isFoldableLoad(const LoadInst *Ld, const Instruction *&FoldedValue) {
955   if (!Ld->hasOneUse())
956     return false;
957   FoldedValue = Ld;
958   const Instruction *UserI = cast<Instruction>(*Ld->user_begin());
959   unsigned LoadedBits = getScalarSizeInBits(Ld->getType());
960   unsigned TruncBits = 0;
961   unsigned SExtBits = 0;
962   unsigned ZExtBits = 0;
963   if (UserI->hasOneUse()) {
964     unsigned UserBits = UserI->getType()->getScalarSizeInBits();
965     if (isa<TruncInst>(UserI))
966       TruncBits = UserBits;
967     else if (isa<SExtInst>(UserI))
968       SExtBits = UserBits;
969     else if (isa<ZExtInst>(UserI))
970       ZExtBits = UserBits;
971   }
972   if (TruncBits || SExtBits || ZExtBits) {
973     FoldedValue = UserI;
974     UserI = cast<Instruction>(*UserI->user_begin());
975     // Load (single use) -> trunc/extend (single use) -> UserI
976   }
977   if ((UserI->getOpcode() == Instruction::Sub ||
978        UserI->getOpcode() == Instruction::SDiv ||
979        UserI->getOpcode() == Instruction::UDiv) &&
980       UserI->getOperand(1) != FoldedValue)
981     return false; // Not commutative, only RHS foldable.
982   // LoadOrTruncBits holds the number of effectively loaded bits, but 0 if an
983   // extension was made of the load.
984   unsigned LoadOrTruncBits =
985       ((SExtBits || ZExtBits) ? 0 : (TruncBits ? TruncBits : LoadedBits));
986   switch (UserI->getOpcode()) {
987   case Instruction::Add: // SE: 16->32, 16/32->64, z14:16->64. ZE: 32->64
988   case Instruction::Sub:
989   case Instruction::ICmp:
990     if (LoadedBits == 32 && ZExtBits == 64)
991       return true;
992     LLVM_FALLTHROUGH;
993   case Instruction::Mul: // SE: 16->32, 32->64, z14:16->64
994     if (UserI->getOpcode() != Instruction::ICmp) {
995       if (LoadedBits == 16 &&
996           (SExtBits == 32 ||
997            (SExtBits == 64 && ST->hasMiscellaneousExtensions2())))
998         return true;
999       if (LoadOrTruncBits == 16)
1000         return true;
1001     }
1002     LLVM_FALLTHROUGH;
1003   case Instruction::SDiv:// SE: 32->64
1004     if (LoadedBits == 32 && SExtBits == 64)
1005       return true;
1006     LLVM_FALLTHROUGH;
1007   case Instruction::UDiv:
1008   case Instruction::And:
1009   case Instruction::Or:
1010   case Instruction::Xor:
1011     // This also makes sense for float operations, but disabled for now due
1012     // to regressions.
1013     // case Instruction::FCmp:
1014     // case Instruction::FAdd:
1015     // case Instruction::FSub:
1016     // case Instruction::FMul:
1017     // case Instruction::FDiv:
1018 
1019     // All possible extensions of memory checked above.
1020 
1021     // Comparison between memory and immediate.
1022     if (UserI->getOpcode() == Instruction::ICmp)
1023       if (ConstantInt *CI = dyn_cast<ConstantInt>(UserI->getOperand(1)))
1024         if (CI->getValue().isIntN(16))
1025           return true;
1026     return (LoadOrTruncBits == 32 || LoadOrTruncBits == 64);
1027     break;
1028   }
1029   return false;
1030 }
1031 
1032 static bool isBswapIntrinsicCall(const Value *V) {
1033   if (const Instruction *I = dyn_cast<Instruction>(V))
1034     if (auto *CI = dyn_cast<CallInst>(I))
1035       if (auto *F = CI->getCalledFunction())
1036         if (F->getIntrinsicID() == Intrinsic::bswap)
1037           return true;
1038   return false;
1039 }
1040 
1041 int SystemZTTIImpl::getMemoryOpCost(unsigned Opcode, Type *Src,
1042                                     MaybeAlign Alignment, unsigned AddressSpace,
1043                                     TTI::TargetCostKind CostKind,
1044                                     const Instruction *I) {
1045   assert(!Src->isVoidTy() && "Invalid type");
1046 
1047   // TODO: Handle other cost kinds.
1048   if (CostKind != TTI::TCK_RecipThroughput)
1049     return 1;
1050 
1051   if (!Src->isVectorTy() && Opcode == Instruction::Load && I != nullptr) {
1052     // Store the load or its truncated or extended value in FoldedValue.
1053     const Instruction *FoldedValue = nullptr;
1054     if (isFoldableLoad(cast<LoadInst>(I), FoldedValue)) {
1055       const Instruction *UserI = cast<Instruction>(*FoldedValue->user_begin());
1056       assert (UserI->getNumOperands() == 2 && "Expected a binop.");
1057 
1058       // UserI can't fold two loads, so in that case return 0 cost only
1059       // half of the time.
1060       for (unsigned i = 0; i < 2; ++i) {
1061         if (UserI->getOperand(i) == FoldedValue)
1062           continue;
1063 
1064         if (Instruction *OtherOp = dyn_cast<Instruction>(UserI->getOperand(i))){
1065           LoadInst *OtherLoad = dyn_cast<LoadInst>(OtherOp);
1066           if (!OtherLoad &&
1067               (isa<TruncInst>(OtherOp) || isa<SExtInst>(OtherOp) ||
1068                isa<ZExtInst>(OtherOp)))
1069             OtherLoad = dyn_cast<LoadInst>(OtherOp->getOperand(0));
1070           if (OtherLoad && isFoldableLoad(OtherLoad, FoldedValue/*dummy*/))
1071             return i == 0; // Both operands foldable.
1072         }
1073       }
1074 
1075       return 0; // Only I is foldable in user.
1076     }
1077   }
1078 
1079   unsigned NumOps =
1080     (Src->isVectorTy() ? getNumVectorRegs(Src) : getNumberOfParts(Src));
1081 
1082   // Store/Load reversed saves one instruction.
1083   if (((!Src->isVectorTy() && NumOps == 1) || ST->hasVectorEnhancements2()) &&
1084       I != nullptr) {
1085     if (Opcode == Instruction::Load && I->hasOneUse()) {
1086       const Instruction *LdUser = cast<Instruction>(*I->user_begin());
1087       // In case of load -> bswap -> store, return normal cost for the load.
1088       if (isBswapIntrinsicCall(LdUser) &&
1089           (!LdUser->hasOneUse() || !isa<StoreInst>(*LdUser->user_begin())))
1090         return 0;
1091     }
1092     else if (const StoreInst *SI = dyn_cast<StoreInst>(I)) {
1093       const Value *StoredVal = SI->getValueOperand();
1094       if (StoredVal->hasOneUse() && isBswapIntrinsicCall(StoredVal))
1095         return 0;
1096     }
1097   }
1098 
1099   if (Src->getScalarSizeInBits() == 128)
1100     // 128 bit scalars are held in a pair of two 64 bit registers.
1101     NumOps *= 2;
1102 
1103   return  NumOps;
1104 }
1105 
1106 // The generic implementation of getInterleavedMemoryOpCost() is based on
1107 // adding costs of the memory operations plus all the extracts and inserts
1108 // needed for using / defining the vector operands. The SystemZ version does
1109 // roughly the same but bases the computations on vector permutations
1110 // instead.
1111 int SystemZTTIImpl::getInterleavedMemoryOpCost(
1112     unsigned Opcode, Type *VecTy, unsigned Factor, ArrayRef<unsigned> Indices,
1113     Align Alignment, unsigned AddressSpace, TTI::TargetCostKind CostKind,
1114     bool UseMaskForCond, bool UseMaskForGaps) {
1115   if (UseMaskForCond || UseMaskForGaps)
1116     return BaseT::getInterleavedMemoryOpCost(Opcode, VecTy, Factor, Indices,
1117                                              Alignment, AddressSpace, CostKind,
1118                                              UseMaskForCond, UseMaskForGaps);
1119   assert(isa<VectorType>(VecTy) &&
1120          "Expect a vector type for interleaved memory op");
1121 
1122   // Return the ceiling of dividing A by B.
1123   auto ceil = [](unsigned A, unsigned B) { return (A + B - 1) / B; };
1124 
1125   unsigned NumElts = cast<FixedVectorType>(VecTy)->getNumElements();
1126   assert(Factor > 1 && NumElts % Factor == 0 && "Invalid interleave factor");
1127   unsigned VF = NumElts / Factor;
1128   unsigned NumEltsPerVecReg = (128U / getScalarSizeInBits(VecTy));
1129   unsigned NumVectorMemOps = getNumVectorRegs(VecTy);
1130   unsigned NumPermutes = 0;
1131 
1132   if (Opcode == Instruction::Load) {
1133     // Loading interleave groups may have gaps, which may mean fewer
1134     // loads. Find out how many vectors will be loaded in total, and in how
1135     // many of them each value will be in.
1136     BitVector UsedInsts(NumVectorMemOps, false);
1137     std::vector<BitVector> ValueVecs(Factor, BitVector(NumVectorMemOps, false));
1138     for (unsigned Index : Indices)
1139       for (unsigned Elt = 0; Elt < VF; ++Elt) {
1140         unsigned Vec = (Index + Elt * Factor) / NumEltsPerVecReg;
1141         UsedInsts.set(Vec);
1142         ValueVecs[Index].set(Vec);
1143       }
1144     NumVectorMemOps = UsedInsts.count();
1145 
1146     for (unsigned Index : Indices) {
1147       // Estimate that each loaded source vector containing this Index
1148       // requires one operation, except that vperm can handle two input
1149       // registers first time for each dst vector.
1150       unsigned NumSrcVecs = ValueVecs[Index].count();
1151       unsigned NumDstVecs = ceil(VF * getScalarSizeInBits(VecTy), 128U);
1152       assert (NumSrcVecs >= NumDstVecs && "Expected at least as many sources");
1153       NumPermutes += std::max(1U, NumSrcVecs - NumDstVecs);
1154     }
1155   } else {
1156     // Estimate the permutes for each stored vector as the smaller of the
1157     // number of elements and the number of source vectors. Subtract one per
1158     // dst vector for vperm (S.A.).
1159     unsigned NumSrcVecs = std::min(NumEltsPerVecReg, Factor);
1160     unsigned NumDstVecs = NumVectorMemOps;
1161     assert (NumSrcVecs > 1 && "Expected at least two source vectors.");
1162     NumPermutes += (NumDstVecs * NumSrcVecs) - NumDstVecs;
1163   }
1164 
1165   // Cost of load/store operations and the permutations needed.
1166   return NumVectorMemOps + NumPermutes;
1167 }
1168 
1169 static int getVectorIntrinsicInstrCost(Intrinsic::ID ID, Type *RetTy) {
1170   if (RetTy->isVectorTy() && ID == Intrinsic::bswap)
1171     return getNumVectorRegs(RetTy); // VPERM
1172   return -1;
1173 }
1174 
1175 int SystemZTTIImpl::getIntrinsicInstrCost(const IntrinsicCostAttributes &ICA,
1176                                           TTI::TargetCostKind CostKind) {
1177   int Cost = getVectorIntrinsicInstrCost(ICA.getID(), ICA.getReturnType());
1178   if (Cost != -1)
1179     return Cost;
1180   return BaseT::getIntrinsicInstrCost(ICA, CostKind);
1181 }
1182