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