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 TypeSize
327 SystemZTTIImpl::getRegisterBitWidth(TargetTransformInfo::RegisterKind K) const {
328   switch (K) {
329   case TargetTransformInfo::RGK_Scalar:
330     return TypeSize::getFixed(64);
331   case TargetTransformInfo::RGK_FixedWidthVector:
332     return TypeSize::getFixed(ST->hasVector() ? 128 : 0);
333   case TargetTransformInfo::RGK_ScalableVector:
334     return TypeSize::getScalable(0);
335   }
336 
337   llvm_unreachable("Unsupported register kind");
338 }
339 
340 unsigned SystemZTTIImpl::getMinPrefetchStride(unsigned NumMemAccesses,
341                                               unsigned NumStridedMemAccesses,
342                                               unsigned NumPrefetches,
343                                               bool HasCall) const {
344   // Don't prefetch a loop with many far apart accesses.
345   if (NumPrefetches > 16)
346     return UINT_MAX;
347 
348   // Emit prefetch instructions for smaller strides in cases where we think
349   // the hardware prefetcher might not be able to keep up.
350   if (NumStridedMemAccesses > 32 && !HasCall &&
351       (NumMemAccesses - NumStridedMemAccesses) * 32 <= NumStridedMemAccesses)
352     return 1;
353 
354   return ST->hasMiscellaneousExtensions3() ? 8192 : 2048;
355 }
356 
357 bool SystemZTTIImpl::hasDivRemOp(Type *DataType, bool IsSigned) {
358   EVT VT = TLI->getValueType(DL, DataType);
359   return (VT.isScalarInteger() && TLI->isTypeLegal(VT));
360 }
361 
362 // Return the bit size for the scalar type or vector element
363 // type. getScalarSizeInBits() returns 0 for a pointer type.
364 static unsigned getScalarSizeInBits(Type *Ty) {
365   unsigned Size =
366     (Ty->isPtrOrPtrVectorTy() ? 64U : Ty->getScalarSizeInBits());
367   assert(Size > 0 && "Element must have non-zero size.");
368   return Size;
369 }
370 
371 // getNumberOfParts() calls getTypeLegalizationCost() which splits the vector
372 // type until it is legal. This would e.g. return 4 for <6 x i64>, instead of
373 // 3.
374 static unsigned getNumVectorRegs(Type *Ty) {
375   auto *VTy = cast<FixedVectorType>(Ty);
376   unsigned WideBits = getScalarSizeInBits(Ty) * VTy->getNumElements();
377   assert(WideBits > 0 && "Could not compute size of vector");
378   return ((WideBits % 128U) ? ((WideBits / 128U) + 1) : (WideBits / 128U));
379 }
380 
381 int SystemZTTIImpl::getArithmeticInstrCost(
382     unsigned Opcode, Type *Ty, TTI::TargetCostKind CostKind,
383     TTI::OperandValueKind Op1Info,
384     TTI::OperandValueKind Op2Info, TTI::OperandValueProperties Opd1PropInfo,
385     TTI::OperandValueProperties Opd2PropInfo, ArrayRef<const Value *> Args,
386     const Instruction *CxtI) {
387 
388   // TODO: Handle more cost kinds.
389   if (CostKind != TTI::TCK_RecipThroughput)
390     return BaseT::getArithmeticInstrCost(Opcode, Ty, CostKind, Op1Info,
391                                          Op2Info, Opd1PropInfo,
392                                          Opd2PropInfo, Args, CxtI);
393 
394   // TODO: return a good value for BB-VECTORIZER that includes the
395   // immediate loads, which we do not want to count for the loop
396   // vectorizer, since they are hopefully hoisted out of the loop. This
397   // would require a new parameter 'InLoop', but not sure if constant
398   // args are common enough to motivate this.
399 
400   unsigned ScalarBits = Ty->getScalarSizeInBits();
401 
402   // There are thre cases of division and remainder: Dividing with a register
403   // needs a divide instruction. A divisor which is a power of two constant
404   // can be implemented with a sequence of shifts. Any other constant needs a
405   // multiply and shifts.
406   const unsigned DivInstrCost = 20;
407   const unsigned DivMulSeqCost = 10;
408   const unsigned SDivPow2Cost = 4;
409 
410   bool SignedDivRem =
411       Opcode == Instruction::SDiv || Opcode == Instruction::SRem;
412   bool UnsignedDivRem =
413       Opcode == Instruction::UDiv || Opcode == Instruction::URem;
414 
415   // Check for a constant divisor.
416   bool DivRemConst = false;
417   bool DivRemConstPow2 = false;
418   if ((SignedDivRem || UnsignedDivRem) && Args.size() == 2) {
419     if (const Constant *C = dyn_cast<Constant>(Args[1])) {
420       const ConstantInt *CVal =
421           (C->getType()->isVectorTy()
422                ? dyn_cast_or_null<const ConstantInt>(C->getSplatValue())
423                : dyn_cast<const ConstantInt>(C));
424       if (CVal != nullptr &&
425           (CVal->getValue().isPowerOf2() || (-CVal->getValue()).isPowerOf2()))
426         DivRemConstPow2 = true;
427       else
428         DivRemConst = true;
429     }
430   }
431 
432   if (!Ty->isVectorTy()) {
433     // These FP operations are supported with a dedicated instruction for
434     // float, double and fp128 (base implementation assumes float generally
435     // costs 2).
436     if (Opcode == Instruction::FAdd || Opcode == Instruction::FSub ||
437         Opcode == Instruction::FMul || Opcode == Instruction::FDiv)
438       return 1;
439 
440     // There is no native support for FRem.
441     if (Opcode == Instruction::FRem)
442       return LIBCALL_COST;
443 
444     // Give discount for some combined logical operations if supported.
445     if (Args.size() == 2 && ST->hasMiscellaneousExtensions3()) {
446       if (Opcode == Instruction::Xor) {
447         for (const Value *A : Args) {
448           if (const Instruction *I = dyn_cast<Instruction>(A))
449             if (I->hasOneUse() &&
450                 (I->getOpcode() == Instruction::And ||
451                  I->getOpcode() == Instruction::Or ||
452                  I->getOpcode() == Instruction::Xor))
453               return 0;
454         }
455       }
456       else if (Opcode == Instruction::Or || Opcode == Instruction::And) {
457         for (const Value *A : Args) {
458           if (const Instruction *I = dyn_cast<Instruction>(A))
459             if (I->hasOneUse() && I->getOpcode() == Instruction::Xor)
460               return 0;
461         }
462       }
463     }
464 
465     // Or requires one instruction, although it has custom handling for i64.
466     if (Opcode == Instruction::Or)
467       return 1;
468 
469     if (Opcode == Instruction::Xor && ScalarBits == 1) {
470       if (ST->hasLoadStoreOnCond2())
471         return 5; // 2 * (li 0; loc 1); xor
472       return 7; // 2 * ipm sequences ; xor ; shift ; compare
473     }
474 
475     if (DivRemConstPow2)
476       return (SignedDivRem ? SDivPow2Cost : 1);
477     if (DivRemConst)
478       return DivMulSeqCost;
479     if (SignedDivRem || UnsignedDivRem)
480       return DivInstrCost;
481   }
482   else if (ST->hasVector()) {
483     auto *VTy = cast<FixedVectorType>(Ty);
484     unsigned VF = VTy->getNumElements();
485     unsigned NumVectors = getNumVectorRegs(Ty);
486 
487     // These vector operations are custom handled, but are still supported
488     // with one instruction per vector, regardless of element size.
489     if (Opcode == Instruction::Shl || Opcode == Instruction::LShr ||
490         Opcode == Instruction::AShr) {
491       return NumVectors;
492     }
493 
494     if (DivRemConstPow2)
495       return (NumVectors * (SignedDivRem ? SDivPow2Cost : 1));
496     if (DivRemConst) {
497       SmallVector<Type *> Tys(Args.size(), Ty);
498       return VF * DivMulSeqCost + getScalarizationOverhead(VTy, Args, Tys);
499     }
500     if ((SignedDivRem || UnsignedDivRem) && VF > 4)
501       // Temporary hack: disable high vectorization factors with integer
502       // division/remainder, which will get scalarized and handled with
503       // GR128 registers. The mischeduler is not clever enough to avoid
504       // spilling yet.
505       return 1000;
506 
507     // These FP operations are supported with a single vector instruction for
508     // double (base implementation assumes float generally costs 2). For
509     // FP128, the scalar cost is 1, and there is no overhead since the values
510     // are already in scalar registers.
511     if (Opcode == Instruction::FAdd || Opcode == Instruction::FSub ||
512         Opcode == Instruction::FMul || Opcode == Instruction::FDiv) {
513       switch (ScalarBits) {
514       case 32: {
515         // The vector enhancements facility 1 provides v4f32 instructions.
516         if (ST->hasVectorEnhancements1())
517           return NumVectors;
518         // Return the cost of multiple scalar invocation plus the cost of
519         // inserting and extracting the values.
520         unsigned ScalarCost =
521             getArithmeticInstrCost(Opcode, Ty->getScalarType(), CostKind);
522         SmallVector<Type *> Tys(Args.size(), Ty);
523         unsigned Cost =
524             (VF * ScalarCost) + getScalarizationOverhead(VTy, Args, Tys);
525         // FIXME: VF 2 for these FP operations are currently just as
526         // expensive as for VF 4.
527         if (VF == 2)
528           Cost *= 2;
529         return Cost;
530       }
531       case 64:
532       case 128:
533         return NumVectors;
534       default:
535         break;
536       }
537     }
538 
539     // There is no native support for FRem.
540     if (Opcode == Instruction::FRem) {
541       SmallVector<Type *> Tys(Args.size(), Ty);
542       unsigned Cost =
543           (VF * LIBCALL_COST) + getScalarizationOverhead(VTy, Args, Tys);
544       // FIXME: VF 2 for float is currently just as expensive as for VF 4.
545       if (VF == 2 && ScalarBits == 32)
546         Cost *= 2;
547       return Cost;
548     }
549   }
550 
551   // Fallback to the default implementation.
552   return BaseT::getArithmeticInstrCost(Opcode, Ty, CostKind, Op1Info, Op2Info,
553                                        Opd1PropInfo, Opd2PropInfo, Args, CxtI);
554 }
555 
556 int SystemZTTIImpl::getShuffleCost(TTI::ShuffleKind Kind, VectorType *Tp,
557                                    ArrayRef<int> Mask, int Index,
558                                    VectorType *SubTp) {
559   if (ST->hasVector()) {
560     unsigned NumVectors = getNumVectorRegs(Tp);
561 
562     // TODO: Since fp32 is expanded, the shuffle cost should always be 0.
563 
564     // FP128 values are always in scalar registers, so there is no work
565     // involved with a shuffle, except for broadcast. In that case register
566     // moves are done with a single instruction per element.
567     if (Tp->getScalarType()->isFP128Ty())
568       return (Kind == TargetTransformInfo::SK_Broadcast ? NumVectors - 1 : 0);
569 
570     switch (Kind) {
571     case  TargetTransformInfo::SK_ExtractSubvector:
572       // ExtractSubvector Index indicates start offset.
573 
574       // Extracting a subvector from first index is a noop.
575       return (Index == 0 ? 0 : NumVectors);
576 
577     case TargetTransformInfo::SK_Broadcast:
578       // Loop vectorizer calls here to figure out the extra cost of
579       // broadcasting a loaded value to all elements of a vector. Since vlrep
580       // loads and replicates with a single instruction, adjust the returned
581       // value.
582       return NumVectors - 1;
583 
584     default:
585 
586       // SystemZ supports single instruction permutation / replication.
587       return NumVectors;
588     }
589   }
590 
591   return BaseT::getShuffleCost(Kind, Tp, Mask, Index, SubTp);
592 }
593 
594 // Return the log2 difference of the element sizes of the two vector types.
595 static unsigned getElSizeLog2Diff(Type *Ty0, Type *Ty1) {
596   unsigned Bits0 = Ty0->getScalarSizeInBits();
597   unsigned Bits1 = Ty1->getScalarSizeInBits();
598 
599   if (Bits1 >  Bits0)
600     return (Log2_32(Bits1) - Log2_32(Bits0));
601 
602   return (Log2_32(Bits0) - Log2_32(Bits1));
603 }
604 
605 // Return the number of instructions needed to truncate SrcTy to DstTy.
606 unsigned SystemZTTIImpl::
607 getVectorTruncCost(Type *SrcTy, Type *DstTy) {
608   assert (SrcTy->isVectorTy() && DstTy->isVectorTy());
609   assert(SrcTy->getPrimitiveSizeInBits().getFixedSize() >
610              DstTy->getPrimitiveSizeInBits().getFixedSize() &&
611          "Packing must reduce size of vector type.");
612   assert(cast<FixedVectorType>(SrcTy)->getNumElements() ==
613              cast<FixedVectorType>(DstTy)->getNumElements() &&
614          "Packing should not change number of elements.");
615 
616   // TODO: Since fp32 is expanded, the extract cost should always be 0.
617 
618   unsigned NumParts = getNumVectorRegs(SrcTy);
619   if (NumParts <= 2)
620     // Up to 2 vector registers can be truncated efficiently with pack or
621     // permute. The latter requires an immediate mask to be loaded, which
622     // typically gets hoisted out of a loop.  TODO: return a good value for
623     // BB-VECTORIZER that includes the immediate loads, which we do not want
624     // to count for the loop vectorizer.
625     return 1;
626 
627   unsigned Cost = 0;
628   unsigned Log2Diff = getElSizeLog2Diff(SrcTy, DstTy);
629   unsigned VF = cast<FixedVectorType>(SrcTy)->getNumElements();
630   for (unsigned P = 0; P < Log2Diff; ++P) {
631     if (NumParts > 1)
632       NumParts /= 2;
633     Cost += NumParts;
634   }
635 
636   // Currently, a general mix of permutes and pack instructions is output by
637   // isel, which follow the cost computation above except for this case which
638   // is one instruction less:
639   if (VF == 8 && SrcTy->getScalarSizeInBits() == 64 &&
640       DstTy->getScalarSizeInBits() == 8)
641     Cost--;
642 
643   return Cost;
644 }
645 
646 // Return the cost of converting a vector bitmask produced by a compare
647 // (SrcTy), to the type of the select or extend instruction (DstTy).
648 unsigned SystemZTTIImpl::
649 getVectorBitmaskConversionCost(Type *SrcTy, Type *DstTy) {
650   assert (SrcTy->isVectorTy() && DstTy->isVectorTy() &&
651           "Should only be called with vector types.");
652 
653   unsigned PackCost = 0;
654   unsigned SrcScalarBits = SrcTy->getScalarSizeInBits();
655   unsigned DstScalarBits = DstTy->getScalarSizeInBits();
656   unsigned Log2Diff = getElSizeLog2Diff(SrcTy, DstTy);
657   if (SrcScalarBits > DstScalarBits)
658     // The bitmask will be truncated.
659     PackCost = getVectorTruncCost(SrcTy, DstTy);
660   else if (SrcScalarBits < DstScalarBits) {
661     unsigned DstNumParts = getNumVectorRegs(DstTy);
662     // Each vector select needs its part of the bitmask unpacked.
663     PackCost = Log2Diff * DstNumParts;
664     // Extra cost for moving part of mask before unpacking.
665     PackCost += DstNumParts - 1;
666   }
667 
668   return PackCost;
669 }
670 
671 // Return the type of the compared operands. This is needed to compute the
672 // cost for a Select / ZExt or SExt instruction.
673 static Type *getCmpOpsType(const Instruction *I, unsigned VF = 1) {
674   Type *OpTy = nullptr;
675   if (CmpInst *CI = dyn_cast<CmpInst>(I->getOperand(0)))
676     OpTy = CI->getOperand(0)->getType();
677   else if (Instruction *LogicI = dyn_cast<Instruction>(I->getOperand(0)))
678     if (LogicI->getNumOperands() == 2)
679       if (CmpInst *CI0 = dyn_cast<CmpInst>(LogicI->getOperand(0)))
680         if (isa<CmpInst>(LogicI->getOperand(1)))
681           OpTy = CI0->getOperand(0)->getType();
682 
683   if (OpTy != nullptr) {
684     if (VF == 1) {
685       assert (!OpTy->isVectorTy() && "Expected scalar type");
686       return OpTy;
687     }
688     // Return the potentially vectorized type based on 'I' and 'VF'.  'I' may
689     // be either scalar or already vectorized with a same or lesser VF.
690     Type *ElTy = OpTy->getScalarType();
691     return FixedVectorType::get(ElTy, VF);
692   }
693 
694   return nullptr;
695 }
696 
697 // Get the cost of converting a boolean vector to a vector with same width
698 // and element size as Dst, plus the cost of zero extending if needed.
699 unsigned SystemZTTIImpl::
700 getBoolVecToIntConversionCost(unsigned Opcode, Type *Dst,
701                               const Instruction *I) {
702   auto *DstVTy = cast<FixedVectorType>(Dst);
703   unsigned VF = DstVTy->getNumElements();
704   unsigned Cost = 0;
705   // If we know what the widths of the compared operands, get any cost of
706   // converting it to match Dst. Otherwise assume same widths.
707   Type *CmpOpTy = ((I != nullptr) ? getCmpOpsType(I, VF) : nullptr);
708   if (CmpOpTy != nullptr)
709     Cost = getVectorBitmaskConversionCost(CmpOpTy, Dst);
710   if (Opcode == Instruction::ZExt || Opcode == Instruction::UIToFP)
711     // One 'vn' per dst vector with an immediate mask.
712     Cost += getNumVectorRegs(Dst);
713   return Cost;
714 }
715 
716 InstructionCost SystemZTTIImpl::getCastInstrCost(unsigned Opcode, Type *Dst,
717                                                  Type *Src,
718                                                  TTI::CastContextHint CCH,
719                                                  TTI::TargetCostKind CostKind,
720                                                  const Instruction *I) {
721   // FIXME: Can the logic below also be used for these cost kinds?
722   if (CostKind == TTI::TCK_CodeSize || CostKind == TTI::TCK_SizeAndLatency) {
723     auto BaseCost = BaseT::getCastInstrCost(Opcode, Dst, Src, CCH, CostKind, I);
724     return BaseCost == 0 ? BaseCost : 1;
725   }
726 
727   unsigned DstScalarBits = Dst->getScalarSizeInBits();
728   unsigned SrcScalarBits = Src->getScalarSizeInBits();
729 
730   if (!Src->isVectorTy()) {
731     assert (!Dst->isVectorTy());
732 
733     if (Opcode == Instruction::SIToFP || Opcode == Instruction::UIToFP) {
734       if (SrcScalarBits >= 32 ||
735           (I != nullptr && isa<LoadInst>(I->getOperand(0))))
736         return 1;
737       return SrcScalarBits > 1 ? 2 /*i8/i16 extend*/ : 5 /*branch seq.*/;
738     }
739 
740     if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
741         Src->isIntegerTy(1)) {
742       if (ST->hasLoadStoreOnCond2())
743         return 2; // li 0; loc 1
744 
745       // This should be extension of a compare i1 result, which is done with
746       // ipm and a varying sequence of instructions.
747       unsigned Cost = 0;
748       if (Opcode == Instruction::SExt)
749         Cost = (DstScalarBits < 64 ? 3 : 4);
750       if (Opcode == Instruction::ZExt)
751         Cost = 3;
752       Type *CmpOpTy = ((I != nullptr) ? getCmpOpsType(I) : nullptr);
753       if (CmpOpTy != nullptr && CmpOpTy->isFloatingPointTy())
754         // If operands of an fp-type was compared, this costs +1.
755         Cost++;
756       return Cost;
757     }
758   }
759   else if (ST->hasVector()) {
760     // Vector to scalar cast.
761     auto *SrcVecTy = cast<FixedVectorType>(Src);
762     auto *DstVecTy = dyn_cast<FixedVectorType>(Dst);
763     if (!DstVecTy) {
764       // TODO: tune vector-to-scalar cast.
765       return BaseT::getCastInstrCost(Opcode, Dst, Src, CCH, CostKind, I);
766     }
767     unsigned VF = SrcVecTy->getNumElements();
768     unsigned NumDstVectors = getNumVectorRegs(Dst);
769     unsigned NumSrcVectors = getNumVectorRegs(Src);
770 
771     if (Opcode == Instruction::Trunc) {
772       if (Src->getScalarSizeInBits() == Dst->getScalarSizeInBits())
773         return 0; // Check for NOOP conversions.
774       return getVectorTruncCost(Src, Dst);
775     }
776 
777     if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
778       if (SrcScalarBits >= 8) {
779         // ZExt/SExt will be handled with one unpack per doubling of width.
780         unsigned NumUnpacks = getElSizeLog2Diff(Src, Dst);
781 
782         // For types that spans multiple vector registers, some additional
783         // instructions are used to setup the unpacking.
784         unsigned NumSrcVectorOps =
785           (NumUnpacks > 1 ? (NumDstVectors - NumSrcVectors)
786                           : (NumDstVectors / 2));
787 
788         return (NumUnpacks * NumDstVectors) + NumSrcVectorOps;
789       }
790       else if (SrcScalarBits == 1)
791         return getBoolVecToIntConversionCost(Opcode, Dst, I);
792     }
793 
794     if (Opcode == Instruction::SIToFP || Opcode == Instruction::UIToFP ||
795         Opcode == Instruction::FPToSI || Opcode == Instruction::FPToUI) {
796       // TODO: Fix base implementation which could simplify things a bit here
797       // (seems to miss on differentiating on scalar/vector types).
798 
799       // Only 64 bit vector conversions are natively supported before z15.
800       if (DstScalarBits == 64 || ST->hasVectorEnhancements2()) {
801         if (SrcScalarBits == DstScalarBits)
802           return NumDstVectors;
803 
804         if (SrcScalarBits == 1)
805           return getBoolVecToIntConversionCost(Opcode, Dst, I) + NumDstVectors;
806       }
807 
808       // Return the cost of multiple scalar invocation plus the cost of
809       // inserting and extracting the values. Base implementation does not
810       // realize float->int gets scalarized.
811       InstructionCost ScalarCost = getCastInstrCost(
812           Opcode, Dst->getScalarType(), Src->getScalarType(), CCH, CostKind);
813       InstructionCost TotCost = VF * ScalarCost;
814       bool NeedsInserts = true, NeedsExtracts = true;
815       // FP128 registers do not get inserted or extracted.
816       if (DstScalarBits == 128 &&
817           (Opcode == Instruction::SIToFP || Opcode == Instruction::UIToFP))
818         NeedsInserts = false;
819       if (SrcScalarBits == 128 &&
820           (Opcode == Instruction::FPToSI || Opcode == Instruction::FPToUI))
821         NeedsExtracts = false;
822 
823       TotCost += getScalarizationOverhead(SrcVecTy, false, NeedsExtracts);
824       TotCost += getScalarizationOverhead(DstVecTy, NeedsInserts, false);
825 
826       // FIXME: VF 2 for float<->i32 is currently just as expensive as for VF 4.
827       if (VF == 2 && SrcScalarBits == 32 && DstScalarBits == 32)
828         TotCost *= 2;
829 
830       return TotCost;
831     }
832 
833     if (Opcode == Instruction::FPTrunc) {
834       if (SrcScalarBits == 128)  // fp128 -> double/float + inserts of elements.
835         return VF /*ldxbr/lexbr*/ +
836                getScalarizationOverhead(DstVecTy, true, false);
837       else // double -> float
838         return VF / 2 /*vledb*/ + std::max(1U, VF / 4 /*vperm*/);
839     }
840 
841     if (Opcode == Instruction::FPExt) {
842       if (SrcScalarBits == 32 && DstScalarBits == 64) {
843         // float -> double is very rare and currently unoptimized. Instead of
844         // using vldeb, which can do two at a time, all conversions are
845         // scalarized.
846         return VF * 2;
847       }
848       // -> fp128.  VF * lxdb/lxeb + extraction of elements.
849       return VF + getScalarizationOverhead(SrcVecTy, false, true);
850     }
851   }
852 
853   return BaseT::getCastInstrCost(Opcode, Dst, Src, CCH, CostKind, I);
854 }
855 
856 // Scalar i8 / i16 operations will typically be made after first extending
857 // the operands to i32.
858 static unsigned getOperandsExtensionCost(const Instruction *I) {
859   unsigned ExtCost = 0;
860   for (Value *Op : I->operands())
861     // A load of i8 or i16 sign/zero extends to i32.
862     if (!isa<LoadInst>(Op) && !isa<ConstantInt>(Op))
863       ExtCost++;
864 
865   return ExtCost;
866 }
867 
868 InstructionCost SystemZTTIImpl::getCmpSelInstrCost(unsigned Opcode, Type *ValTy,
869                                                    Type *CondTy,
870                                                    CmpInst::Predicate VecPred,
871                                                    TTI::TargetCostKind CostKind,
872                                                    const Instruction *I) {
873   if (CostKind != TTI::TCK_RecipThroughput)
874     return BaseT::getCmpSelInstrCost(Opcode, ValTy, CondTy, VecPred, CostKind);
875 
876   if (!ValTy->isVectorTy()) {
877     switch (Opcode) {
878     case Instruction::ICmp: {
879       // A loaded value compared with 0 with multiple users becomes Load and
880       // Test. The load is then not foldable, so return 0 cost for the ICmp.
881       unsigned ScalarBits = ValTy->getScalarSizeInBits();
882       if (I != nullptr && ScalarBits >= 32)
883         if (LoadInst *Ld = dyn_cast<LoadInst>(I->getOperand(0)))
884           if (const ConstantInt *C = dyn_cast<ConstantInt>(I->getOperand(1)))
885             if (!Ld->hasOneUse() && Ld->getParent() == I->getParent() &&
886                 C->isZero())
887               return 0;
888 
889       unsigned Cost = 1;
890       if (ValTy->isIntegerTy() && ValTy->getScalarSizeInBits() <= 16)
891         Cost += (I != nullptr ? getOperandsExtensionCost(I) : 2);
892       return Cost;
893     }
894     case Instruction::Select:
895       if (ValTy->isFloatingPointTy())
896         return 4; // No load on condition for FP - costs a conditional jump.
897       return 1; // Load On Condition / Select Register.
898     }
899   }
900   else if (ST->hasVector()) {
901     unsigned VF = cast<FixedVectorType>(ValTy)->getNumElements();
902 
903     // Called with a compare instruction.
904     if (Opcode == Instruction::ICmp || Opcode == Instruction::FCmp) {
905       unsigned PredicateExtraCost = 0;
906       if (I != nullptr) {
907         // Some predicates cost one or two extra instructions.
908         switch (cast<CmpInst>(I)->getPredicate()) {
909         case CmpInst::Predicate::ICMP_NE:
910         case CmpInst::Predicate::ICMP_UGE:
911         case CmpInst::Predicate::ICMP_ULE:
912         case CmpInst::Predicate::ICMP_SGE:
913         case CmpInst::Predicate::ICMP_SLE:
914           PredicateExtraCost = 1;
915           break;
916         case CmpInst::Predicate::FCMP_ONE:
917         case CmpInst::Predicate::FCMP_ORD:
918         case CmpInst::Predicate::FCMP_UEQ:
919         case CmpInst::Predicate::FCMP_UNO:
920           PredicateExtraCost = 2;
921           break;
922         default:
923           break;
924         }
925       }
926 
927       // Float is handled with 2*vmr[lh]f + 2*vldeb + vfchdb for each pair of
928       // floats.  FIXME: <2 x float> generates same code as <4 x float>.
929       unsigned CmpCostPerVector = (ValTy->getScalarType()->isFloatTy() ? 10 : 1);
930       unsigned NumVecs_cmp = getNumVectorRegs(ValTy);
931 
932       unsigned Cost = (NumVecs_cmp * (CmpCostPerVector + PredicateExtraCost));
933       return Cost;
934     }
935     else { // Called with a select instruction.
936       assert (Opcode == Instruction::Select);
937 
938       // We can figure out the extra cost of packing / unpacking if the
939       // instruction was passed and the compare instruction is found.
940       unsigned PackCost = 0;
941       Type *CmpOpTy = ((I != nullptr) ? getCmpOpsType(I, VF) : nullptr);
942       if (CmpOpTy != nullptr)
943         PackCost =
944           getVectorBitmaskConversionCost(CmpOpTy, ValTy);
945 
946       return getNumVectorRegs(ValTy) /*vsel*/ + PackCost;
947     }
948   }
949 
950   return BaseT::getCmpSelInstrCost(Opcode, ValTy, CondTy, VecPred, CostKind);
951 }
952 
953 int SystemZTTIImpl::
954 getVectorInstrCost(unsigned Opcode, Type *Val, unsigned Index) {
955   // vlvgp will insert two grs into a vector register, so only count half the
956   // number of instructions.
957   if (Opcode == Instruction::InsertElement && Val->isIntOrIntVectorTy(64))
958     return ((Index % 2 == 0) ? 1 : 0);
959 
960   if (Opcode == Instruction::ExtractElement) {
961     int Cost = ((getScalarSizeInBits(Val) == 1) ? 2 /*+test-under-mask*/ : 1);
962 
963     // Give a slight penalty for moving out of vector pipeline to FXU unit.
964     if (Index == 0 && Val->isIntOrIntVectorTy())
965       Cost += 1;
966 
967     return Cost;
968   }
969 
970   return BaseT::getVectorInstrCost(Opcode, Val, Index);
971 }
972 
973 // Check if a load may be folded as a memory operand in its user.
974 bool SystemZTTIImpl::
975 isFoldableLoad(const LoadInst *Ld, const Instruction *&FoldedValue) {
976   if (!Ld->hasOneUse())
977     return false;
978   FoldedValue = Ld;
979   const Instruction *UserI = cast<Instruction>(*Ld->user_begin());
980   unsigned LoadedBits = getScalarSizeInBits(Ld->getType());
981   unsigned TruncBits = 0;
982   unsigned SExtBits = 0;
983   unsigned ZExtBits = 0;
984   if (UserI->hasOneUse()) {
985     unsigned UserBits = UserI->getType()->getScalarSizeInBits();
986     if (isa<TruncInst>(UserI))
987       TruncBits = UserBits;
988     else if (isa<SExtInst>(UserI))
989       SExtBits = UserBits;
990     else if (isa<ZExtInst>(UserI))
991       ZExtBits = UserBits;
992   }
993   if (TruncBits || SExtBits || ZExtBits) {
994     FoldedValue = UserI;
995     UserI = cast<Instruction>(*UserI->user_begin());
996     // Load (single use) -> trunc/extend (single use) -> UserI
997   }
998   if ((UserI->getOpcode() == Instruction::Sub ||
999        UserI->getOpcode() == Instruction::SDiv ||
1000        UserI->getOpcode() == Instruction::UDiv) &&
1001       UserI->getOperand(1) != FoldedValue)
1002     return false; // Not commutative, only RHS foldable.
1003   // LoadOrTruncBits holds the number of effectively loaded bits, but 0 if an
1004   // extension was made of the load.
1005   unsigned LoadOrTruncBits =
1006       ((SExtBits || ZExtBits) ? 0 : (TruncBits ? TruncBits : LoadedBits));
1007   switch (UserI->getOpcode()) {
1008   case Instruction::Add: // SE: 16->32, 16/32->64, z14:16->64. ZE: 32->64
1009   case Instruction::Sub:
1010   case Instruction::ICmp:
1011     if (LoadedBits == 32 && ZExtBits == 64)
1012       return true;
1013     LLVM_FALLTHROUGH;
1014   case Instruction::Mul: // SE: 16->32, 32->64, z14:16->64
1015     if (UserI->getOpcode() != Instruction::ICmp) {
1016       if (LoadedBits == 16 &&
1017           (SExtBits == 32 ||
1018            (SExtBits == 64 && ST->hasMiscellaneousExtensions2())))
1019         return true;
1020       if (LoadOrTruncBits == 16)
1021         return true;
1022     }
1023     LLVM_FALLTHROUGH;
1024   case Instruction::SDiv:// SE: 32->64
1025     if (LoadedBits == 32 && SExtBits == 64)
1026       return true;
1027     LLVM_FALLTHROUGH;
1028   case Instruction::UDiv:
1029   case Instruction::And:
1030   case Instruction::Or:
1031   case Instruction::Xor:
1032     // This also makes sense for float operations, but disabled for now due
1033     // to regressions.
1034     // case Instruction::FCmp:
1035     // case Instruction::FAdd:
1036     // case Instruction::FSub:
1037     // case Instruction::FMul:
1038     // case Instruction::FDiv:
1039 
1040     // All possible extensions of memory checked above.
1041 
1042     // Comparison between memory and immediate.
1043     if (UserI->getOpcode() == Instruction::ICmp)
1044       if (ConstantInt *CI = dyn_cast<ConstantInt>(UserI->getOperand(1)))
1045         if (CI->getValue().isIntN(16))
1046           return true;
1047     return (LoadOrTruncBits == 32 || LoadOrTruncBits == 64);
1048     break;
1049   }
1050   return false;
1051 }
1052 
1053 static bool isBswapIntrinsicCall(const Value *V) {
1054   if (const Instruction *I = dyn_cast<Instruction>(V))
1055     if (auto *CI = dyn_cast<CallInst>(I))
1056       if (auto *F = CI->getCalledFunction())
1057         if (F->getIntrinsicID() == Intrinsic::bswap)
1058           return true;
1059   return false;
1060 }
1061 
1062 int SystemZTTIImpl::getMemoryOpCost(unsigned Opcode, Type *Src,
1063                                     MaybeAlign Alignment, unsigned AddressSpace,
1064                                     TTI::TargetCostKind CostKind,
1065                                     const Instruction *I) {
1066   assert(!Src->isVoidTy() && "Invalid type");
1067 
1068   // TODO: Handle other cost kinds.
1069   if (CostKind != TTI::TCK_RecipThroughput)
1070     return 1;
1071 
1072   if (!Src->isVectorTy() && Opcode == Instruction::Load && I != nullptr) {
1073     // Store the load or its truncated or extended value in FoldedValue.
1074     const Instruction *FoldedValue = nullptr;
1075     if (isFoldableLoad(cast<LoadInst>(I), FoldedValue)) {
1076       const Instruction *UserI = cast<Instruction>(*FoldedValue->user_begin());
1077       assert (UserI->getNumOperands() == 2 && "Expected a binop.");
1078 
1079       // UserI can't fold two loads, so in that case return 0 cost only
1080       // half of the time.
1081       for (unsigned i = 0; i < 2; ++i) {
1082         if (UserI->getOperand(i) == FoldedValue)
1083           continue;
1084 
1085         if (Instruction *OtherOp = dyn_cast<Instruction>(UserI->getOperand(i))){
1086           LoadInst *OtherLoad = dyn_cast<LoadInst>(OtherOp);
1087           if (!OtherLoad &&
1088               (isa<TruncInst>(OtherOp) || isa<SExtInst>(OtherOp) ||
1089                isa<ZExtInst>(OtherOp)))
1090             OtherLoad = dyn_cast<LoadInst>(OtherOp->getOperand(0));
1091           if (OtherLoad && isFoldableLoad(OtherLoad, FoldedValue/*dummy*/))
1092             return i == 0; // Both operands foldable.
1093         }
1094       }
1095 
1096       return 0; // Only I is foldable in user.
1097     }
1098   }
1099 
1100   unsigned NumOps =
1101     (Src->isVectorTy() ? getNumVectorRegs(Src) : getNumberOfParts(Src));
1102 
1103   // Store/Load reversed saves one instruction.
1104   if (((!Src->isVectorTy() && NumOps == 1) || ST->hasVectorEnhancements2()) &&
1105       I != nullptr) {
1106     if (Opcode == Instruction::Load && I->hasOneUse()) {
1107       const Instruction *LdUser = cast<Instruction>(*I->user_begin());
1108       // In case of load -> bswap -> store, return normal cost for the load.
1109       if (isBswapIntrinsicCall(LdUser) &&
1110           (!LdUser->hasOneUse() || !isa<StoreInst>(*LdUser->user_begin())))
1111         return 0;
1112     }
1113     else if (const StoreInst *SI = dyn_cast<StoreInst>(I)) {
1114       const Value *StoredVal = SI->getValueOperand();
1115       if (StoredVal->hasOneUse() && isBswapIntrinsicCall(StoredVal))
1116         return 0;
1117     }
1118   }
1119 
1120   if (Src->getScalarSizeInBits() == 128)
1121     // 128 bit scalars are held in a pair of two 64 bit registers.
1122     NumOps *= 2;
1123 
1124   return  NumOps;
1125 }
1126 
1127 // The generic implementation of getInterleavedMemoryOpCost() is based on
1128 // adding costs of the memory operations plus all the extracts and inserts
1129 // needed for using / defining the vector operands. The SystemZ version does
1130 // roughly the same but bases the computations on vector permutations
1131 // instead.
1132 int SystemZTTIImpl::getInterleavedMemoryOpCost(
1133     unsigned Opcode, Type *VecTy, unsigned Factor, ArrayRef<unsigned> Indices,
1134     Align Alignment, unsigned AddressSpace, TTI::TargetCostKind CostKind,
1135     bool UseMaskForCond, bool UseMaskForGaps) {
1136   if (UseMaskForCond || UseMaskForGaps)
1137     return BaseT::getInterleavedMemoryOpCost(Opcode, VecTy, Factor, Indices,
1138                                              Alignment, AddressSpace, CostKind,
1139                                              UseMaskForCond, UseMaskForGaps);
1140   assert(isa<VectorType>(VecTy) &&
1141          "Expect a vector type for interleaved memory op");
1142 
1143   // Return the ceiling of dividing A by B.
1144   auto ceil = [](unsigned A, unsigned B) { return (A + B - 1) / B; };
1145 
1146   unsigned NumElts = cast<FixedVectorType>(VecTy)->getNumElements();
1147   assert(Factor > 1 && NumElts % Factor == 0 && "Invalid interleave factor");
1148   unsigned VF = NumElts / Factor;
1149   unsigned NumEltsPerVecReg = (128U / getScalarSizeInBits(VecTy));
1150   unsigned NumVectorMemOps = getNumVectorRegs(VecTy);
1151   unsigned NumPermutes = 0;
1152 
1153   if (Opcode == Instruction::Load) {
1154     // Loading interleave groups may have gaps, which may mean fewer
1155     // loads. Find out how many vectors will be loaded in total, and in how
1156     // many of them each value will be in.
1157     BitVector UsedInsts(NumVectorMemOps, false);
1158     std::vector<BitVector> ValueVecs(Factor, BitVector(NumVectorMemOps, false));
1159     for (unsigned Index : Indices)
1160       for (unsigned Elt = 0; Elt < VF; ++Elt) {
1161         unsigned Vec = (Index + Elt * Factor) / NumEltsPerVecReg;
1162         UsedInsts.set(Vec);
1163         ValueVecs[Index].set(Vec);
1164       }
1165     NumVectorMemOps = UsedInsts.count();
1166 
1167     for (unsigned Index : Indices) {
1168       // Estimate that each loaded source vector containing this Index
1169       // requires one operation, except that vperm can handle two input
1170       // registers first time for each dst vector.
1171       unsigned NumSrcVecs = ValueVecs[Index].count();
1172       unsigned NumDstVecs = ceil(VF * getScalarSizeInBits(VecTy), 128U);
1173       assert (NumSrcVecs >= NumDstVecs && "Expected at least as many sources");
1174       NumPermutes += std::max(1U, NumSrcVecs - NumDstVecs);
1175     }
1176   } else {
1177     // Estimate the permutes for each stored vector as the smaller of the
1178     // number of elements and the number of source vectors. Subtract one per
1179     // dst vector for vperm (S.A.).
1180     unsigned NumSrcVecs = std::min(NumEltsPerVecReg, Factor);
1181     unsigned NumDstVecs = NumVectorMemOps;
1182     assert (NumSrcVecs > 1 && "Expected at least two source vectors.");
1183     NumPermutes += (NumDstVecs * NumSrcVecs) - NumDstVecs;
1184   }
1185 
1186   // Cost of load/store operations and the permutations needed.
1187   return NumVectorMemOps + NumPermutes;
1188 }
1189 
1190 static int getVectorIntrinsicInstrCost(Intrinsic::ID ID, Type *RetTy) {
1191   if (RetTy->isVectorTy() && ID == Intrinsic::bswap)
1192     return getNumVectorRegs(RetTy); // VPERM
1193   return -1;
1194 }
1195 
1196 InstructionCost
1197 SystemZTTIImpl::getIntrinsicInstrCost(const IntrinsicCostAttributes &ICA,
1198                                       TTI::TargetCostKind CostKind) {
1199   InstructionCost Cost =
1200       getVectorIntrinsicInstrCost(ICA.getID(), ICA.getReturnType());
1201   if (Cost != -1)
1202     return Cost;
1203   return BaseT::getIntrinsicInstrCost(ICA, CostKind);
1204 }
1205