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