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