LLVM 24.0.0git
SystemZTargetTransformInfo.cpp
Go to the documentation of this file.
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
23#include "llvm/IR/Intrinsics.h"
24#include "llvm/Support/Debug.h"
27
28using namespace llvm;
29
30#define DEBUG_TYPE "systemztti"
31
32//===----------------------------------------------------------------------===//
33//
34// SystemZ cost model.
35//
36//===----------------------------------------------------------------------===//
37
38static bool isUsedAsMemCpySource(const Value *V, bool &OtherUse) {
39 bool UsedAsMemCpySource = false;
40 for (const User *U : V->users())
41 if (const Instruction *User = dyn_cast<Instruction>(U)) {
43 UsedAsMemCpySource |= isUsedAsMemCpySource(User, OtherUse);
44 continue;
45 }
46 if (const MemCpyInst *Memcpy = dyn_cast<MemCpyInst>(User)) {
47 if (Memcpy->getOperand(1) == V && !Memcpy->isVolatile()) {
48 UsedAsMemCpySource = true;
49 continue;
50 }
51 }
52 OtherUse = true;
53 }
54 return UsedAsMemCpySource;
55}
56
57static void countNumMemAccesses(const Value *Ptr, unsigned &NumStores,
58 unsigned &NumLoads, const Function *F) {
59 if (!isa<PointerType>(Ptr->getType()))
60 return;
61 for (const User *U : Ptr->users())
62 if (const Instruction *User = dyn_cast<Instruction>(U)) {
63 if (User->getParent()->getParent() == F) {
64 if (const auto *SI = dyn_cast<StoreInst>(User)) {
65 if (SI->getPointerOperand() == Ptr && !SI->isVolatile())
66 NumStores++;
67 } else if (const auto *LI = dyn_cast<LoadInst>(User)) {
68 if (LI->getPointerOperand() == Ptr && !LI->isVolatile())
69 NumLoads++;
70 } else if (const auto *GEP = dyn_cast<GetElementPtrInst>(User)) {
71 if (GEP->getPointerOperand() == Ptr)
72 countNumMemAccesses(GEP, NumStores, NumLoads, F);
73 }
74 }
75 }
76}
77
79 unsigned Bonus = 0;
80 const Function *Caller = CB->getParent()->getParent();
81 const Function *Callee = CB->getCalledFunction();
82 if (!Callee)
83 return 0;
84
85 // Increase the threshold if an incoming argument is used only as a memcpy
86 // source.
87 for (const Argument &Arg : Callee->args()) {
88 bool OtherUse = false;
89 if (isUsedAsMemCpySource(&Arg, OtherUse) && !OtherUse) {
90 Bonus = 1000;
91 break;
92 }
93 }
94
95 // Give bonus for globals used much in both caller and a relatively small
96 // callee.
97 unsigned InstrCount = 0;
99 for (auto &I : instructions(Callee)) {
100 if (++InstrCount == 200) {
101 Ptr2NumUses.clear();
102 break;
103 }
104 if (const auto *SI = dyn_cast<StoreInst>(&I)) {
105 if (!SI->isVolatile())
106 if (auto *GV = dyn_cast<GlobalVariable>(SI->getPointerOperand()))
107 Ptr2NumUses[GV]++;
108 } else if (const auto *LI = dyn_cast<LoadInst>(&I)) {
109 if (!LI->isVolatile())
110 if (auto *GV = dyn_cast<GlobalVariable>(LI->getPointerOperand()))
111 Ptr2NumUses[GV]++;
112 } else if (const auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
113 if (auto *GV = dyn_cast<GlobalVariable>(GEP->getPointerOperand())) {
114 unsigned NumStores = 0, NumLoads = 0;
115 countNumMemAccesses(GEP, NumStores, NumLoads, Callee);
116 Ptr2NumUses[GV] += NumLoads + NumStores;
117 }
118 }
119 }
120
121 for (auto [Ptr, NumCalleeUses] : Ptr2NumUses)
122 if (NumCalleeUses > 10) {
123 unsigned CallerStores = 0, CallerLoads = 0;
124 countNumMemAccesses(Ptr, CallerStores, CallerLoads, Caller);
125 if (CallerStores + CallerLoads > 10) {
126 Bonus = 1000;
127 break;
128 }
129 }
130
131 // Give bonus when Callee accesses an Alloca of Caller heavily.
132 unsigned NumStores = 0;
133 unsigned NumLoads = 0;
134 for (unsigned OpIdx = 0; OpIdx != Callee->arg_size(); ++OpIdx) {
135 Value *CallerArg = CB->getArgOperand(OpIdx);
136 Argument *CalleeArg = Callee->getArg(OpIdx);
137 if (isa<AllocaInst>(CallerArg))
138 countNumMemAccesses(CalleeArg, NumStores, NumLoads, Callee);
139 }
140 if (NumLoads > 10)
141 Bonus += NumLoads * 50;
142 if (NumStores > 10)
143 Bonus += NumStores * 50;
144 Bonus = std::min(Bonus, unsigned(1000));
145
146 LLVM_DEBUG(if (Bonus)
147 dbgs() << "++ SZTTI Adding inlining bonus: " << Bonus << "\n";);
148 return Bonus;
149}
150
153 TTI::TargetCostKind CostKind) const {
154 assert(Ty->isIntegerTy());
155
156 unsigned BitSize = Ty->getPrimitiveSizeInBits();
157 // There is no cost model for constants with a bit size of 0. Return TCC_Free
158 // here, so that constant hoisting will ignore this constant.
159 if (BitSize == 0)
160 return TTI::TCC_Free;
161 // No cost model for operations on integers larger than 128 bit implemented yet.
162 if ((!ST->hasVector() && BitSize > 64) || BitSize > 128)
163 return TTI::TCC_Free;
164
165 if (Imm == 0)
166 return TTI::TCC_Free;
167
168 if (Imm.getBitWidth() <= 64) {
169 // Constants loaded via lgfi.
170 if (isInt<32>(Imm.getSExtValue()))
171 return TTI::TCC_Basic;
172 // Constants loaded via llilf.
173 if (isUInt<32>(Imm.getZExtValue()))
174 return TTI::TCC_Basic;
175 // Constants loaded via llihf:
176 if ((Imm.getZExtValue() & 0xffffffff) == 0)
177 return TTI::TCC_Basic;
178
179 return 2 * TTI::TCC_Basic;
180 }
181
182 // i128 immediates loads from Constant Pool
183 return 2 * TTI::TCC_Basic;
184}
185
187 const APInt &Imm, Type *Ty,
188 TTI::TargetCostKind CostKind,
189 Instruction *Inst) const {
190 assert(Ty->isIntegerTy());
191
192 unsigned BitSize = Ty->getPrimitiveSizeInBits();
193 // There is no cost model for constants with a bit size of 0. Return TCC_Free
194 // here, so that constant hoisting will ignore this constant.
195 if (BitSize == 0)
196 return TTI::TCC_Free;
197 // No cost model for operations on integers larger than 64 bit implemented yet.
198 if (BitSize > 64)
199 return TTI::TCC_Free;
200
201 switch (Opcode) {
202 default:
203 return TTI::TCC_Free;
204 case Instruction::GetElementPtr:
205 // Always hoist the base address of a GetElementPtr. This prevents the
206 // creation of new constants for every base constant that gets constant
207 // folded with the offset.
208 if (Idx == 0)
209 return 2 * TTI::TCC_Basic;
210 return TTI::TCC_Free;
211 case Instruction::Store:
212 if (Idx == 0 && Imm.getBitWidth() <= 64) {
213 // Any 8-bit immediate store can by implemented via mvi.
214 if (BitSize == 8)
215 return TTI::TCC_Free;
216 // 16-bit immediate values can be stored via mvhhi/mvhi/mvghi.
217 if (isInt<16>(Imm.getSExtValue()))
218 return TTI::TCC_Free;
219 }
220 break;
221 case Instruction::ICmp:
222 if (Idx == 1 && Imm.getBitWidth() <= 64) {
223 // Comparisons against signed 32-bit immediates implemented via cgfi.
224 if (isInt<32>(Imm.getSExtValue()))
225 return TTI::TCC_Free;
226 // Comparisons against unsigned 32-bit immediates implemented via clgfi.
227 if (isUInt<32>(Imm.getZExtValue()))
228 return TTI::TCC_Free;
229 }
230 break;
231 case Instruction::Add:
232 case Instruction::Sub:
233 if (Idx == 1 && Imm.getBitWidth() <= 64) {
234 // We use algfi/slgfi to add/subtract 32-bit unsigned immediates.
235 if (isUInt<32>(Imm.getZExtValue()))
236 return TTI::TCC_Free;
237 // Or their negation, by swapping addition vs. subtraction.
238 if (isUInt<32>(-Imm.getSExtValue()))
239 return TTI::TCC_Free;
240 }
241 break;
242 case Instruction::Mul:
243 if (Idx == 1 && Imm.getBitWidth() <= 64) {
244 // We use msgfi to multiply by 32-bit signed immediates.
245 if (isInt<32>(Imm.getSExtValue()))
246 return TTI::TCC_Free;
247 }
248 break;
249 case Instruction::Or:
250 case Instruction::Xor:
251 if (Idx == 1 && Imm.getBitWidth() <= 64) {
252 // Masks supported by oilf/xilf.
253 if (isUInt<32>(Imm.getZExtValue()))
254 return TTI::TCC_Free;
255 // Masks supported by oihf/xihf.
256 if ((Imm.getZExtValue() & 0xffffffff) == 0)
257 return TTI::TCC_Free;
258 }
259 break;
260 case Instruction::And:
261 if (Idx == 1 && Imm.getBitWidth() <= 64) {
262 // Any 32-bit AND operation can by implemented via nilf.
263 if (BitSize <= 32)
264 return TTI::TCC_Free;
265 // 64-bit masks supported by nilf.
266 if (isUInt<32>(~Imm.getZExtValue()))
267 return TTI::TCC_Free;
268 // 64-bit masks supported by nilh.
269 if ((Imm.getZExtValue() & 0xffffffff) == 0xffffffff)
270 return TTI::TCC_Free;
271 // Some 64-bit AND operations can be implemented via risbg.
272 const SystemZInstrInfo *TII = ST->getInstrInfo();
273 unsigned Start, End;
274 if (TII->isRxSBGMask(Imm.getZExtValue(), BitSize, Start, End))
275 return TTI::TCC_Free;
276 }
277 break;
278 case Instruction::Shl:
279 case Instruction::LShr:
280 case Instruction::AShr:
281 // Always return TCC_Free for the shift value of a shift instruction.
282 if (Idx == 1)
283 return TTI::TCC_Free;
284 break;
285 case Instruction::UDiv:
286 case Instruction::SDiv:
287 case Instruction::URem:
288 case Instruction::SRem:
289 case Instruction::Trunc:
290 case Instruction::ZExt:
291 case Instruction::SExt:
292 case Instruction::IntToPtr:
293 case Instruction::PtrToInt:
294 case Instruction::BitCast:
295 case Instruction::PHI:
296 case Instruction::Call:
297 case Instruction::Select:
298 case Instruction::Ret:
299 case Instruction::Load:
300 break;
301 }
302
303 return SystemZTTIImpl::getIntImmCost(Imm, Ty, CostKind);
304}
305
308 const APInt &Imm, Type *Ty,
309 TTI::TargetCostKind CostKind) const {
310 assert(Ty->isIntegerTy());
311
312 unsigned BitSize = Ty->getPrimitiveSizeInBits();
313 // There is no cost model for constants with a bit size of 0. Return TCC_Free
314 // here, so that constant hoisting will ignore this constant.
315 if (BitSize == 0)
316 return TTI::TCC_Free;
317 // No cost model for operations on integers larger than 64 bit implemented yet.
318 if (BitSize > 64)
319 return TTI::TCC_Free;
320
321 switch (IID) {
322 default:
323 return TTI::TCC_Free;
324 case Intrinsic::sadd_with_overflow:
325 case Intrinsic::uadd_with_overflow:
326 case Intrinsic::ssub_with_overflow:
327 case Intrinsic::usub_with_overflow:
328 // These get expanded to include a normal addition/subtraction.
329 if (Idx == 1 && Imm.getBitWidth() <= 64) {
330 if (isUInt<32>(Imm.getZExtValue()))
331 return TTI::TCC_Free;
332 if (isUInt<32>(-Imm.getSExtValue()))
333 return TTI::TCC_Free;
334 }
335 break;
336 case Intrinsic::smul_with_overflow:
337 case Intrinsic::umul_with_overflow:
338 // These get expanded to include a normal multiplication.
339 if (Idx == 1 && Imm.getBitWidth() <= 64) {
340 if (isInt<32>(Imm.getSExtValue()))
341 return TTI::TCC_Free;
342 }
343 break;
344 case Intrinsic::experimental_stackmap:
345 if ((Idx < 2) || (Imm.getBitWidth() <= 64 && isInt<64>(Imm.getSExtValue())))
346 return TTI::TCC_Free;
347 break;
348 case Intrinsic::experimental_patchpoint_void:
349 case Intrinsic::experimental_patchpoint:
350 if ((Idx < 4) || (Imm.getBitWidth() <= 64 && isInt<64>(Imm.getSExtValue())))
351 return TTI::TCC_Free;
352 break;
353 }
354 return SystemZTTIImpl::getIntImmCost(Imm, Ty, CostKind);
355}
356
359 OptimizationRemarkEmitter *ORE) const {
360 // Find out if L contains a call, what the machine instruction count
361 // estimate is, and how many stores there are.
362 bool HasCall = false;
363 InstructionCost NumStores = 0;
364 for (auto &BB : L->blocks())
365 for (auto &I : *BB) {
366 if (isa<CallInst>(&I) || isa<InvokeInst>(&I)) {
367 if (const Function *F = cast<CallBase>(I).getCalledFunction()) {
368 if (isLoweredToCall(F))
369 HasCall = true;
370 if (F->getIntrinsicID() == Intrinsic::memcpy ||
371 F->getIntrinsicID() == Intrinsic::memset)
372 NumStores++;
373 } else { // indirect call.
374 HasCall = true;
375 }
376 }
377 if (isa<StoreInst>(&I)) {
378 Type *MemAccessTy = I.getOperand(0)->getType();
379 NumStores += getMemoryOpCost(Instruction::Store, MemAccessTy, Align(),
381 }
382 }
383
384 // The z13 processor will run out of store tags if too many stores
385 // are fed into it too quickly. Therefore make sure there are not
386 // too many stores in the resulting unrolled loop.
387 unsigned const NumStoresVal = NumStores.getValue();
388 unsigned const Max = (NumStoresVal ? (12 / NumStoresVal) : UINT_MAX);
389
390 if (HasCall) {
391 // Only allow full unrolling if loop has any calls.
392 UP.FullUnrollMaxCount = Max;
393 UP.MaxCount = 1;
394 return;
395 }
396
397 UP.MaxCount = Max;
398 if (UP.MaxCount <= 1)
399 return;
400
401 // Allow partial and runtime trip count unrolling.
402 UP.Partial = UP.Runtime = true;
403
404 UP.PartialThreshold = 75;
406
407 // Allow expensive instructions in the pre-header of the loop.
408 UP.AllowExpensiveTripCount = true;
409
410 UP.Force = true;
411}
412
417
420 const TargetTransformInfo::LSRCost &C2) const {
421 // SystemZ specific: check instruction count (first), and don't care about
422 // ImmCost, since offsets are checked explicitly.
423 return std::tie(C1.Insns, C1.NumRegs, C1.AddRecCost,
424 C1.NumIVMuls, C1.NumBaseAdds,
425 C1.ScaleCost, C1.SetupCost) <
426 std::tie(C2.Insns, C2.NumRegs, C2.AddRecCost,
427 C2.NumIVMuls, C2.NumBaseAdds,
428 C2.ScaleCost, C2.SetupCost);
429}
430
431unsigned SystemZTTIImpl::getNumberOfRegisters(unsigned ClassID) const {
432 bool Vector = (ClassID == 1);
433 if (!Vector)
434 // Discount the stack pointer. Also leave out %r0, since it can't
435 // be used in an address.
436 return 14;
437 if (ST->hasVector())
438 return 32;
439 return 0;
440}
441
444 switch (K) {
446 return TypeSize::getFixed(64);
448 return TypeSize::getFixed(ST->hasVector() ? 128 : 0);
450 return TypeSize::getScalable(0);
451 }
452
453 llvm_unreachable("Unsupported register kind");
454}
455
456unsigned SystemZTTIImpl::getMinPrefetchStride(unsigned NumMemAccesses,
457 unsigned NumStridedMemAccesses,
458 unsigned NumPrefetches,
459 bool HasCall) const {
460 // Don't prefetch a loop with many far apart accesses.
461 if (NumPrefetches > 16)
462 return UINT_MAX;
463
464 // Emit prefetch instructions for smaller strides in cases where we think
465 // the hardware prefetcher might not be able to keep up.
466 if (NumStridedMemAccesses > 32 && !HasCall &&
467 (NumMemAccesses - NumStridedMemAccesses) * 32 <= NumStridedMemAccesses)
468 return 1;
469
470 return ST->hasMiscellaneousExtensions3() ? 8192 : 2048;
471}
472
473unsigned
475 bool HasUnorderedReductions) const {
476 return VF.isVector() ? 8 : 1;
477}
478
479bool SystemZTTIImpl::hasDivRemOp(Type *DataType, bool IsSigned) const {
480 EVT VT = TLI->getValueType(DL, DataType);
481 return (VT.isScalarInteger() && TLI->isTypeLegal(VT));
482}
483
484static bool isFreeEltLoad(const Value *Op) {
485 if (isa<LoadInst>(Op) && Op->hasOneUse()) {
486 const Instruction *UserI = cast<Instruction>(*Op->user_begin());
487 return !isa<StoreInst>(UserI); // Prefer MVC
488 }
489 return false;
490}
491
493 VectorType *Ty, const APInt &DemandedElts, bool Insert, bool Extract,
494 TTI::TargetCostKind CostKind, bool ForPoisonSrc, ArrayRef<Value *> VL,
495 TTI::VectorInstrContext VIC) const {
496 unsigned NumElts = cast<FixedVectorType>(Ty)->getNumElements();
498
499 if (Insert && Ty->isIntOrIntVectorTy(64)) {
500 // VLVGP will insert two GPRs with one instruction, while VLE will load
501 // an element directly with no extra cost
502 assert((VL.empty() || VL.size() == NumElts) &&
503 "Type does not match the number of values.");
504 InstructionCost CurrVectorCost = 0;
505 for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
506 if (DemandedElts[Idx] && !(VL.size() && isFreeEltLoad(VL[Idx])))
507 ++CurrVectorCost;
508 if (Idx % 2 == 1) {
509 Cost += std::min(InstructionCost(1), CurrVectorCost);
510 CurrVectorCost = 0;
511 }
512 }
513 Insert = false;
514 }
515
516 Cost += BaseT::getScalarizationOverhead(Ty, DemandedElts, Insert, Extract,
517 CostKind, ForPoisonSrc, VL);
518 return Cost;
519}
520
521// Return the bit size for the scalar type or vector element
522// type. getScalarSizeInBits() returns 0 for a pointer type.
523static unsigned getScalarSizeInBits(Type *Ty) {
524 unsigned Size =
525 (Ty->isPtrOrPtrVectorTy() ? 64U : Ty->getScalarSizeInBits());
526 assert(Size > 0 && "Element must have non-zero size.");
527 return Size;
528}
529
530// getNumberOfParts() calls getTypeLegalizationCost() which splits the vector
531// type until it is legal. This would e.g. return 4 for <6 x i64>, instead of
532// 3.
533static unsigned getNumVectorRegs(Type *Ty) {
534 auto *VTy = cast<FixedVectorType>(Ty);
535 unsigned WideBits = getScalarSizeInBits(Ty) * VTy->getNumElements();
536 assert(WideBits > 0 && "Could not compute size of vector");
537 return ((WideBits % 128U) ? ((WideBits / 128U) + 1) : (WideBits / 128U));
538}
539
540static bool isFoldableRMW(const Instruction *I, Type *Ty) {
542 if (!BI || !BI->hasOneUse())
543 return false;
544
545 unsigned Opcode = BI->getOpcode();
546 unsigned BitWidth = Ty->getScalarSizeInBits();
547
548 switch (Opcode) {
549 case Instruction::And:
550 case Instruction::Or:
551 case Instruction::Xor: {
552 if (BitWidth == 8)
553 break;
554 if (BitWidth != 16 && BitWidth != 32 && BitWidth != 64)
555 return false;
556
557 auto *CI = dyn_cast<ConstantInt>(I->getOperand(1));
558 if (!CI)
559 return false;
560
561 uint64_t Val = CI->getZExtValue();
562 if (Opcode == Instruction::And) {
563 if (BitWidth == 16 && (Val & 0xff00ULL) != 0xff00ULL)
564 return false;
565 if (BitWidth == 32 && (Val & 0xffffff00ULL) != 0xffffff00ULL)
566 return false;
567 if (BitWidth == 64 &&
568 (Val & 0xffffffffffffff00ULL) != 0xffffffffffffff00ULL)
569 return false;
570 } else {
571 if (CI->getValue().getActiveBits() > 8) {
572 return false;
573 }
574 }
575 break;
576 }
577 case Instruction::Add:
578 case Instruction::Sub:
579 if (BitWidth != 32 && BitWidth != 64)
580 return false;
581 break;
582 default:
583 return false;
584 }
585
586 Value *Op0 = BI->getOperand(0), *Op1 = BI->getOperand(1);
587 if (!isa<ConstantInt>(Op0) && !isa<ConstantInt>(Op1))
588 return false;
589
590 Value *V =
591 (Opcode == Instruction::Sub) ? Op0 : (isa<ConstantInt>(Op0) ? Op1 : Op0);
592 if (Opcode == Instruction::Sub && !isa<ConstantInt>(Op1))
593 return false;
594
595 auto *LI = dyn_cast_or_null<LoadInst>(V);
596 // Already checked BI hasOneUse.
597 auto *SI = dyn_cast<StoreInst>(BI->user_back());
598
599 return LI && SI && !LI->isVolatile() && !SI->isVolatile() &&
600 LI->hasOneUse() && LI->getPointerOperand() == SI->getPointerOperand();
601}
602
604 unsigned Opcode, Type *Ty, TTI::TargetCostKind CostKind,
606 ArrayRef<const Value *> Args, const Instruction *CtxI,
607 const TargetLibraryInfo *TLibInfo, ArrayRef<const Value *> Scalars) const {
608
609 // TODO: Handle more cost kinds.
610 if (CostKind != TTI::TCK_RecipThroughput)
611 return BaseT::getArithmeticInstrCost(Opcode, Ty, CostKind, Op1Info, Op2Info,
612 Args, CtxI, TLibInfo, Scalars);
613 if (CtxI && Ty && !Ty->isVectorTy() && isFoldableRMW(CtxI, Ty))
614 return TTI::TCC_Free;
615 // TODO: return a good value for BB-VECTORIZER that includes the
616 // immediate loads, which we do not want to count for the loop
617 // vectorizer, since they are hopefully hoisted out of the loop. This
618 // would require a new parameter 'InLoop', but not sure if constant
619 // args are common enough to motivate this.
620
621 unsigned ScalarBits = Ty->getScalarSizeInBits();
622
623 // There are thre cases of division and remainder: Dividing with a register
624 // needs a divide instruction. A divisor which is a power of two constant
625 // can be implemented with a sequence of shifts. Any other constant needs a
626 // multiply and shifts.
627 const unsigned DivInstrCost = 20;
628 const unsigned DivMulSeqCost = 10;
629 const unsigned SDivPow2Cost = 4;
630
631 bool SignedDivRem =
632 Opcode == Instruction::SDiv || Opcode == Instruction::SRem;
633 bool UnsignedDivRem =
634 Opcode == Instruction::UDiv || Opcode == Instruction::URem;
635
636 // Check for a constant divisor.
637 bool DivRemConst = false;
638 bool DivRemConstPow2 = false;
639 if ((SignedDivRem || UnsignedDivRem) && Args.size() == 2) {
640 if (const Constant *C = dyn_cast<Constant>(Args[1])) {
641 const ConstantInt *CVal =
642 (C->getType()->isVectorTy()
643 ? dyn_cast_or_null<const ConstantInt>(C->getSplatValue())
645 if (CVal && (CVal->getValue().isPowerOf2() ||
646 CVal->getValue().isNegatedPowerOf2()))
647 DivRemConstPow2 = true;
648 else
649 DivRemConst = true;
650 }
651 }
652
653 if (!Ty->isVectorTy()) {
654 // These FP operations are supported with a dedicated instruction for
655 // float, double and fp128 (base implementation assumes float generally
656 // costs 2).
657 if (Opcode == Instruction::FAdd || Opcode == Instruction::FSub ||
658 Opcode == Instruction::FMul || Opcode == Instruction::FDiv)
659 return 1;
660
661 // There is no native support for FRem.
662 if (Opcode == Instruction::FRem)
663 return LIBCALL_COST;
664
665 // Give discount for some combined logical operations if supported.
666 if (Args.size() == 2) {
667 if (Opcode == Instruction::Xor) {
668 for (const Value *A : Args) {
669 if (const Instruction *I = dyn_cast<Instruction>(A))
670 if (I->hasOneUse() &&
671 (I->getOpcode() == Instruction::Or ||
672 I->getOpcode() == Instruction::And ||
673 I->getOpcode() == Instruction::Xor))
674 if ((ScalarBits <= 64 && ST->hasMiscellaneousExtensions3()) ||
675 (isInt128InVR(Ty) &&
676 (I->getOpcode() == Instruction::Or || ST->hasVectorEnhancements1())))
677 return 0;
678 }
679 }
680 else if (Opcode == Instruction::And || Opcode == Instruction::Or) {
681 for (const Value *A : Args) {
682 if (const Instruction *I = dyn_cast<Instruction>(A))
683 if ((I->hasOneUse() && I->getOpcode() == Instruction::Xor) &&
684 ((ScalarBits <= 64 && ST->hasMiscellaneousExtensions3()) ||
685 (isInt128InVR(Ty) &&
686 (Opcode == Instruction::And || ST->hasVectorEnhancements1()))))
687 return 0;
688 }
689 }
690 }
691
692 // Or requires one instruction, although it has custom handling for i64.
693 if (Opcode == Instruction::Or)
694 return 1;
695
696 if (Opcode == Instruction::Xor && ScalarBits == 1) {
697 if (ST->hasLoadStoreOnCond2())
698 return 5; // 2 * (li 0; loc 1); xor
699 return 7; // 2 * ipm sequences ; xor ; shift ; compare
700 }
701
702 if (DivRemConstPow2)
703 return (SignedDivRem ? SDivPow2Cost : 1);
704 if (DivRemConst)
705 return DivMulSeqCost;
706 if (SignedDivRem || UnsignedDivRem)
707 return DivInstrCost;
708 }
709 else if (ST->hasVector()) {
710 auto *VTy = cast<FixedVectorType>(Ty);
711 unsigned VF = VTy->getNumElements();
712 unsigned NumVectors = getNumVectorRegs(Ty);
713
714 // These vector operations are custom handled, but are still supported
715 // with one instruction per vector, regardless of element size.
716 if (Opcode == Instruction::Shl || Opcode == Instruction::LShr ||
717 Opcode == Instruction::AShr) {
718 return NumVectors;
719 }
720
721 if (DivRemConstPow2)
722 return (NumVectors * (SignedDivRem ? SDivPow2Cost : 1));
723 if (DivRemConst) {
724 SmallVector<Type *> Tys(Args.size(), Ty);
725 return VF * DivMulSeqCost +
726 BaseT::getScalarizationOverhead(VTy, Args, Tys, CostKind);
727 }
728 if (SignedDivRem || UnsignedDivRem) {
729 if (ST->hasVectorEnhancements3() && ScalarBits >= 32)
730 return NumVectors * DivInstrCost;
731 else if (VF > 4)
732 // Temporary hack: disable high vectorization factors with integer
733 // division/remainder, which will get scalarized and handled with
734 // GR128 registers. The mischeduler is not clever enough to avoid
735 // spilling yet.
736 return 1000;
737 }
738
739 // These FP operations are supported with a single vector instruction for
740 // double (base implementation assumes float generally costs 2). For
741 // FP128, the scalar cost is 1, and there is no overhead since the values
742 // are already in scalar registers.
743 if (Opcode == Instruction::FAdd || Opcode == Instruction::FSub ||
744 Opcode == Instruction::FMul || Opcode == Instruction::FDiv) {
745 switch (ScalarBits) {
746 case 32: {
747 // The vector enhancements facility 1 provides v4f32 instructions.
748 if (ST->hasVectorEnhancements1())
749 return NumVectors;
750 // Return the cost of multiple scalar invocation plus the cost of
751 // inserting and extracting the values.
752 InstructionCost ScalarCost =
753 getArithmeticInstrCost(Opcode, Ty->getScalarType(), CostKind);
754 SmallVector<Type *> Tys(Args.size(), Ty);
756 (VF * ScalarCost) +
757 BaseT::getScalarizationOverhead(VTy, Args, Tys, CostKind);
758 // FIXME: VF 2 for these FP operations are currently just as
759 // expensive as for VF 4.
760 if (VF == 2)
761 Cost *= 2;
762 return Cost;
763 }
764 case 64:
765 case 128:
766 return NumVectors;
767 default:
768 break;
769 }
770 }
771
772 // There is no native support for FRem.
773 if (Opcode == Instruction::FRem) {
774 SmallVector<Type *> Tys(Args.size(), Ty);
776 (VF * LIBCALL_COST) +
777 BaseT::getScalarizationOverhead(VTy, Args, Tys, CostKind);
778 // FIXME: VF 2 for float is currently just as expensive as for VF 4.
779 if (VF == 2 && ScalarBits == 32)
780 Cost *= 2;
781 return Cost;
782 }
783 }
784
785 // Fallback to the default implementation.
786 return BaseT::getArithmeticInstrCost(Opcode, Ty, CostKind, Op1Info, Op2Info,
787 Args, CtxI, TLibInfo, Scalars);
788}
789
791 TTI::ShuffleKind Kind, VectorType *DstTy, VectorType *SrcTy,
792 TTI::TargetCostKind CostKind, ArrayRef<int> Mask, int Index,
793 VectorType *SubTp, ArrayRef<const Value *> Args, const Instruction *CtxI,
794 TTI::VectorInstrContext VIC) const {
795 Kind = improveShuffleKindFromMask(Kind, Mask, SrcTy, Index, SubTp);
796 if (ST->hasVector()) {
797 unsigned NumVectors = getNumVectorRegs(SrcTy);
798
799 // TODO: Since fp32 is expanded, the shuffle cost should always be 0.
800
801 // FP128 values are always in scalar registers, so there is no work
802 // involved with a shuffle, except for broadcast. In that case register
803 // moves are done with a single instruction per element.
804 if (SrcTy->getScalarType()->isFP128Ty())
805 return (Kind == TargetTransformInfo::SK_Broadcast ? NumVectors - 1 : 0);
806
807 switch (Kind) {
809 // ExtractSubvector Index indicates start offset.
810
811 // Extracting a subvector from first index is a noop.
812 return (Index == 0 ? 0 : NumVectors);
813
815 // Loop vectorizer calls here to figure out the extra cost of
816 // broadcasting a loaded value to all elements of a vector. Since vlrep
817 // loads and replicates with a single instruction, adjust the returned
818 // value.
819 return NumVectors - 1;
820
821 default:
822
823 // SystemZ supports single instruction permutation / replication.
824 return NumVectors;
825 }
826 }
827
828 return BaseT::getShuffleCost(Kind, DstTy, SrcTy, CostKind, Mask, Index,
829 SubTp);
830}
831
832// Return the log2 difference of the element sizes of the two vector types.
833static unsigned getElSizeLog2Diff(Type *Ty0, Type *Ty1) {
834 unsigned Bits0 = getScalarSizeInBits(Ty0);
835 unsigned Bits1 = getScalarSizeInBits(Ty1);
836
837 if (Bits1 > Bits0)
838 return (Log2_32(Bits1) - Log2_32(Bits0));
839
840 return (Log2_32(Bits0) - Log2_32(Bits1));
841}
842
843// Return the number of instructions needed to truncate SrcTy to DstTy.
844unsigned SystemZTTIImpl::getVectorTruncCost(Type *SrcTy, Type *DstTy) const {
845 assert (SrcTy->isVectorTy() && DstTy->isVectorTy());
847 "Packing must reduce size of vector type.");
848 assert(cast<FixedVectorType>(SrcTy)->getNumElements() ==
849 cast<FixedVectorType>(DstTy)->getNumElements() &&
850 "Packing should not change number of elements.");
851
852 // TODO: Since fp32 is expanded, the extract cost should always be 0.
853
854 unsigned NumParts = getNumVectorRegs(SrcTy);
855 if (NumParts <= 2)
856 // Up to 2 vector registers can be truncated efficiently with pack or
857 // permute. The latter requires an immediate mask to be loaded, which
858 // typically gets hoisted out of a loop. TODO: return a good value for
859 // BB-VECTORIZER that includes the immediate loads, which we do not want
860 // to count for the loop vectorizer.
861 return 1;
862
863 unsigned Cost = 0;
864 unsigned Log2Diff = getElSizeLog2Diff(SrcTy, DstTy);
865 unsigned VF = cast<FixedVectorType>(SrcTy)->getNumElements();
866 for (unsigned P = 0; P < Log2Diff; ++P) {
867 if (NumParts > 1)
868 NumParts /= 2;
869 Cost += NumParts;
870 }
871
872 // Currently, a general mix of permutes and pack instructions is output by
873 // isel, which follow the cost computation above except for this case which
874 // is one instruction less:
875 if (VF == 8 && SrcTy->getScalarSizeInBits() == 64 &&
876 DstTy->getScalarSizeInBits() == 8)
877 Cost--;
878
879 return Cost;
880}
881
882// Return the cost of converting a vector bitmask produced by a compare
883// (SrcTy), to the type of the select or extend instruction (DstTy).
885 Type *DstTy) const {
886 assert (SrcTy->isVectorTy() && DstTy->isVectorTy() &&
887 "Should only be called with vector types.");
888
889 unsigned PackCost = 0;
890 unsigned SrcScalarBits = getScalarSizeInBits(SrcTy);
891 unsigned DstScalarBits = getScalarSizeInBits(DstTy);
892 unsigned Log2Diff = getElSizeLog2Diff(SrcTy, DstTy);
893 if (SrcScalarBits > DstScalarBits)
894 // The bitmask will be truncated.
895 PackCost = getVectorTruncCost(SrcTy, DstTy);
896 else if (SrcScalarBits < DstScalarBits) {
897 unsigned DstNumParts = getNumVectorRegs(DstTy);
898 // Each vector select needs its part of the bitmask unpacked.
899 PackCost = Log2Diff * DstNumParts;
900 // Extra cost for moving part of mask before unpacking.
901 PackCost += DstNumParts - 1;
902 }
903
904 return PackCost;
905}
906
907// Return the type of the compared operands. This is needed to compute the
908// cost for a Select / ZExt or SExt instruction.
909static Type *getCmpOpsType(const Instruction *I, unsigned VF = 1) {
910 Type *OpTy = nullptr;
911 if (CmpInst *CI = dyn_cast<CmpInst>(I->getOperand(0)))
912 OpTy = CI->getOperand(0)->getType();
913 else if (Instruction *LogicI = dyn_cast<Instruction>(I->getOperand(0)))
914 if (LogicI->getNumOperands() == 2)
915 if (CmpInst *CI0 = dyn_cast<CmpInst>(LogicI->getOperand(0)))
916 if (isa<CmpInst>(LogicI->getOperand(1)))
917 OpTy = CI0->getOperand(0)->getType();
918
919 if (OpTy != nullptr) {
920 if (VF == 1) {
921 assert (!OpTy->isVectorTy() && "Expected scalar type");
922 return OpTy;
923 }
924 // Return the potentially vectorized type based on 'I' and 'VF'. 'I' may
925 // be either scalar or already vectorized with a same or lesser VF.
926 Type *ElTy = OpTy->getScalarType();
927 return FixedVectorType::get(ElTy, VF);
928 }
929
930 return nullptr;
931}
932
933// Get the cost of converting a boolean vector to a vector with same width
934// and element size as Dst, plus the cost of zero extending if needed.
935unsigned
937 const Instruction *I) const {
938 auto *DstVTy = cast<FixedVectorType>(Dst);
939 unsigned VF = DstVTy->getNumElements();
940 unsigned Cost = 0;
941 // If we know what the widths of the compared operands, get any cost of
942 // converting it to match Dst. Otherwise assume same widths.
943 Type *CmpOpTy = ((I != nullptr) ? getCmpOpsType(I, VF) : nullptr);
944 if (CmpOpTy != nullptr)
945 Cost = getVectorBitmaskConversionCost(CmpOpTy, Dst);
946 if (Opcode == Instruction::ZExt || Opcode == Instruction::UIToFP)
947 // One 'vn' per dst vector with an immediate mask.
948 Cost += getNumVectorRegs(Dst);
949 return Cost;
950}
951
953 Type *Src,
955 TTI::TargetCostKind CostKind,
956 const Instruction *I) const {
957 // FIXME: Can the logic below also be used for these cost kinds?
958 if (CostKind == TTI::TCK_CodeSize || CostKind == TTI::TCK_SizeAndLatency) {
959 auto BaseCost = BaseT::getCastInstrCost(Opcode, Dst, Src, CCH, CostKind, I);
960 return BaseCost == 0 ? BaseCost : 1;
961 }
962
963 unsigned DstScalarBits = Dst->getScalarSizeInBits();
964 unsigned SrcScalarBits = Src->getScalarSizeInBits();
965
966 if (!Src->isVectorTy()) {
967 if (Dst->isVectorTy())
968 return BaseT::getCastInstrCost(Opcode, Dst, Src, CCH, CostKind, I);
969
970 if (Opcode == Instruction::SIToFP || Opcode == Instruction::UIToFP) {
971 if (Src->isIntegerTy(128))
972 return LIBCALL_COST;
973 if (SrcScalarBits >= 32 ||
974 (I != nullptr && isa<LoadInst>(I->getOperand(0))))
975 return 1;
976 return SrcScalarBits > 1 ? 2 /*i8/i16 extend*/ : 5 /*branch seq.*/;
977 }
978
979 if ((Opcode == Instruction::FPToSI || Opcode == Instruction::FPToUI) &&
980 Dst->isIntegerTy(128))
981 return LIBCALL_COST;
982
983 if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt)) {
984 if (Src->isIntegerTy(1)) {
985 if (DstScalarBits == 128) {
986 if (Opcode == Instruction::SExt && ST->hasVectorEnhancements3())
987 return 0;/*VCEQQ*/
988 return 5 /*branch seq.*/;
989 }
990
991 if (ST->hasLoadStoreOnCond2())
992 return 2; // li 0; loc 1
993
994 // This should be extension of a compare i1 result, which is done with
995 // ipm and a varying sequence of instructions.
996 unsigned Cost = 0;
997 if (Opcode == Instruction::SExt)
998 Cost = (DstScalarBits < 64 ? 3 : 4);
999 if (Opcode == Instruction::ZExt)
1000 Cost = 3;
1001 Type *CmpOpTy = ((I != nullptr) ? getCmpOpsType(I) : nullptr);
1002 if (CmpOpTy != nullptr && CmpOpTy->isFloatingPointTy())
1003 // If operands of an fp-type was compared, this costs +1.
1004 Cost++;
1005 return Cost;
1006 }
1007 else if (isInt128InVR(Dst)) {
1008 // Extensions from GPR to i128 (in VR) typically costs two instructions,
1009 // but a zero-extending load would be just one extra instruction.
1010 if (Opcode == Instruction::ZExt && I != nullptr)
1011 if (LoadInst *Ld = dyn_cast<LoadInst>(I->getOperand(0)))
1012 if (Ld->hasOneUse())
1013 return 1;
1014 return 2;
1015 }
1016 }
1017
1018 if (Opcode == Instruction::Trunc && isInt128InVR(Src) && I != nullptr) {
1019 if (LoadInst *Ld = dyn_cast<LoadInst>(I->getOperand(0)))
1020 if (Ld->hasOneUse())
1021 return 0; // Will be converted to GPR load.
1022 bool OnlyTruncatingStores = true;
1023 for (const User *U : I->users())
1024 if (!isa<StoreInst>(U)) {
1025 OnlyTruncatingStores = false;
1026 break;
1027 }
1028 if (OnlyTruncatingStores)
1029 return 0;
1030 return 2; // Vector element extraction.
1031 }
1032 }
1033 else if (ST->hasVector()) {
1034 // Vector to scalar cast.
1035 auto *SrcVecTy = cast<FixedVectorType>(Src);
1036 auto *DstVecTy = dyn_cast<FixedVectorType>(Dst);
1037 if (!DstVecTy) {
1038 // TODO: tune vector-to-scalar cast.
1039 return BaseT::getCastInstrCost(Opcode, Dst, Src, CCH, CostKind, I);
1040 }
1041 unsigned VF = SrcVecTy->getNumElements();
1042 unsigned NumDstVectors = getNumVectorRegs(Dst);
1043 unsigned NumSrcVectors = getNumVectorRegs(Src);
1044
1045 if (Opcode == Instruction::Trunc) {
1046 if (Src->getScalarSizeInBits() == Dst->getScalarSizeInBits())
1047 return 0; // Check for NOOP conversions.
1048 return getVectorTruncCost(Src, Dst);
1049 }
1050
1051 if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
1052 if (SrcScalarBits >= 8) {
1053 // ZExt will use either a single unpack or a vector permute.
1054 if (Opcode == Instruction::ZExt)
1055 return NumDstVectors;
1056
1057 // SExt will be handled with one unpack per doubling of width.
1058 unsigned NumUnpacks = getElSizeLog2Diff(Src, Dst);
1059
1060 // For types that spans multiple vector registers, some additional
1061 // instructions are used to setup the unpacking.
1062 unsigned NumSrcVectorOps =
1063 (NumUnpacks > 1 ? (NumDstVectors - NumSrcVectors)
1064 : (NumDstVectors / 2));
1065
1066 return (NumUnpacks * NumDstVectors) + NumSrcVectorOps;
1067 }
1068 else if (SrcScalarBits == 1)
1069 return getBoolVecToIntConversionCost(Opcode, Dst, I);
1070 }
1071
1072 if (Opcode == Instruction::SIToFP || Opcode == Instruction::UIToFP ||
1073 Opcode == Instruction::FPToSI || Opcode == Instruction::FPToUI) {
1074 // TODO: Fix base implementation which could simplify things a bit here
1075 // (seems to miss on differentiating on scalar/vector types).
1076
1077 // Only 64 bit vector conversions are natively supported before z15.
1078 if (DstScalarBits == 64 || ST->hasVectorEnhancements2()) {
1079 if (SrcScalarBits == DstScalarBits)
1080 return NumDstVectors;
1081
1082 if (SrcScalarBits == 1)
1083 return getBoolVecToIntConversionCost(Opcode, Dst, I) + NumDstVectors;
1084 }
1085
1086 // Return the cost of multiple scalar invocation plus the cost of
1087 // inserting and extracting the values. Base implementation does not
1088 // realize float->int gets scalarized.
1089 InstructionCost ScalarCost = getCastInstrCost(
1090 Opcode, Dst->getScalarType(), Src->getScalarType(), CCH, CostKind);
1091 InstructionCost TotCost = VF * ScalarCost;
1092 bool NeedsInserts = true, NeedsExtracts = true;
1093 // FP128 registers do not get inserted or extracted.
1094 if (DstScalarBits == 128 &&
1095 (Opcode == Instruction::SIToFP || Opcode == Instruction::UIToFP))
1096 NeedsInserts = false;
1097 if (SrcScalarBits == 128 &&
1098 (Opcode == Instruction::FPToSI || Opcode == Instruction::FPToUI))
1099 NeedsExtracts = false;
1100
1101 TotCost += BaseT::getScalarizationOverhead(SrcVecTy, /*Insert*/ false,
1102 NeedsExtracts, CostKind);
1103 TotCost += BaseT::getScalarizationOverhead(DstVecTy, NeedsInserts,
1104 /*Extract*/ false, CostKind);
1105
1106 // FIXME: VF 2 for float<->i32 is currently just as expensive as for VF 4.
1107 if (VF == 2 && SrcScalarBits == 32 && DstScalarBits == 32)
1108 TotCost *= 2;
1109
1110 return TotCost;
1111 }
1112
1113 if (Opcode == Instruction::FPTrunc) {
1114 if (SrcScalarBits == 128) // fp128 -> double/float + inserts of elements.
1115 return VF /*ldxbr/lexbr*/ +
1116 BaseT::getScalarizationOverhead(DstVecTy, /*Insert*/ true,
1117 /*Extract*/ false, CostKind);
1118 else // double -> float
1119 return VF / 2 /*vledb*/ + std::max(1U, VF / 4 /*vperm*/);
1120 }
1121
1122 if (Opcode == Instruction::FPExt) {
1123 if (SrcScalarBits == 32 && DstScalarBits == 64) {
1124 // float -> double is very rare and currently unoptimized. Instead of
1125 // using vldeb, which can do two at a time, all conversions are
1126 // scalarized.
1127 return VF * 2;
1128 }
1129 // -> fp128. VF * lxdb/lxeb + extraction of elements.
1130 return VF + BaseT::getScalarizationOverhead(SrcVecTy, /*Insert*/ false,
1131 /*Extract*/ true, CostKind);
1132 }
1133 }
1134
1135 return BaseT::getCastInstrCost(Opcode, Dst, Src, CCH, CostKind, I);
1136}
1137
1138// Scalar i8 / i16 operations will typically be made after first extending
1139// the operands to i32.
1140static unsigned getOperandsExtensionCost(const Instruction *I) {
1141 unsigned ExtCost = 0;
1142 for (Value *Op : I->operands())
1143 // A load of i8 or i16 sign/zero extends to i32.
1145 ExtCost++;
1146
1147 return ExtCost;
1148}
1149
1151 TTI::TargetCostKind CostKind,
1152 const Instruction *I) const {
1153 if (CostKind != TTI::TCK_RecipThroughput)
1154 return Opcode == Instruction::PHI ? TTI::TCC_Free : TTI::TCC_Basic;
1155 // Branches are assumed to be predicted.
1156 return TTI::TCC_Free;
1157}
1158
1160 unsigned Opcode, Type *ValTy, Type *CondTy, CmpInst::Predicate VecPred,
1162 TTI::OperandValueInfo Op2Info, const Instruction *I) const {
1163 if (CostKind != TTI::TCK_RecipThroughput)
1164 return BaseT::getCmpSelInstrCost(Opcode, ValTy, CondTy, VecPred, CostKind,
1165 Op1Info, Op2Info);
1166
1167 if (!ValTy->isVectorTy()) {
1168 switch (Opcode) {
1169 case Instruction::ICmp: {
1170 // A loaded value compared with 0 with multiple users becomes Load and
1171 // Test. The load is then not foldable, so return 0 cost for the ICmp.
1172 unsigned ScalarBits = ValTy->getScalarSizeInBits();
1173 if (I != nullptr && (ScalarBits == 32 || ScalarBits == 64))
1174 if (LoadInst *Ld = dyn_cast<LoadInst>(I->getOperand(0)))
1175 if (const ConstantInt *C = dyn_cast<ConstantInt>(I->getOperand(1)))
1176 if (!Ld->hasOneUse() && Ld->getParent() == I->getParent() &&
1177 C->isZero())
1178 return 0;
1179
1180 unsigned Cost = 1;
1181 if (ValTy->isIntegerTy() && ValTy->getScalarSizeInBits() <= 16)
1182 Cost += (I != nullptr ? getOperandsExtensionCost(I) : 2);
1183 return Cost;
1184 }
1185 case Instruction::Select:
1186 if (ValTy->isFloatingPointTy())
1187 return 4; // No LOC for FP - costs a conditional jump.
1188
1189 // When selecting based on an i128 comparison, LOC / VSEL is possible
1190 // if i128 comparisons are directly supported.
1191 if (I != nullptr)
1192 if (ICmpInst *CI = dyn_cast<ICmpInst>(I->getOperand(0)))
1193 if (CI->getOperand(0)->getType()->isIntegerTy(128))
1194 return ST->hasVectorEnhancements3() ? 1 : 4;
1195
1196 // Load On Condition / Select Register available, except for i128.
1197 return !isInt128InVR(ValTy) ? 1 : 4;
1198 }
1199 }
1200 else if (ST->hasVector()) {
1201 unsigned VF = cast<FixedVectorType>(ValTy)->getNumElements();
1202
1203 // Called with a compare instruction.
1204 if (Opcode == Instruction::ICmp || Opcode == Instruction::FCmp) {
1205 unsigned PredicateExtraCost = 0;
1206 if (I != nullptr) {
1207 // Some predicates cost one or two extra instructions.
1208 switch (cast<CmpInst>(I)->getPredicate()) {
1214 PredicateExtraCost = 1;
1215 break;
1220 PredicateExtraCost = 2;
1221 break;
1222 default:
1223 break;
1224 }
1225 }
1226
1227 // Float is handled with 2*vmr[lh]f + 2*vldeb + vfchdb for each pair of
1228 // floats. FIXME: <2 x float> generates same code as <4 x float>.
1229 unsigned CmpCostPerVector = (ValTy->getScalarType()->isFloatTy() ? 10 : 1);
1230 unsigned NumVecs_cmp = getNumVectorRegs(ValTy);
1231
1232 unsigned Cost = (NumVecs_cmp * (CmpCostPerVector + PredicateExtraCost));
1233 return Cost;
1234 }
1235 else { // Called with a select instruction.
1236 assert (Opcode == Instruction::Select);
1237
1238 // We can figure out the extra cost of packing / unpacking if the
1239 // instruction was passed and the compare instruction is found.
1240 unsigned PackCost = 0;
1241 Type *CmpOpTy = ((I != nullptr) ? getCmpOpsType(I, VF) : nullptr);
1242 if (CmpOpTy != nullptr)
1243 PackCost =
1244 getVectorBitmaskConversionCost(CmpOpTy, ValTy);
1245
1246 return getNumVectorRegs(ValTy) /*vsel*/ + PackCost;
1247 }
1248 }
1249
1250 return BaseT::getCmpSelInstrCost(Opcode, ValTy, CondTy, VecPred, CostKind,
1251 Op1Info, Op2Info);
1252}
1253
1255 unsigned Opcode, Type *Val, TTI::TargetCostKind CostKind, unsigned Index,
1256 const Value *Op0, const Value *Op1, TTI::VectorInstrContext VIC) const {
1257 if (Opcode == Instruction::InsertElement) {
1258 // Vector Element Load.
1259 if (Op1 != nullptr && isFreeEltLoad(Op1))
1260 return 0;
1261
1262 // vlvgp will insert two grs into a vector register, so count half the
1263 // number of instructions as an estimate when we don't have the full
1264 // picture (as in getScalarizationOverhead()).
1265 if (Val->isIntOrIntVectorTy(64))
1266 return ((Index % 2 == 0) ? 1 : 0);
1267 }
1268
1269 if (Opcode == Instruction::ExtractElement) {
1270 int Cost = ((getScalarSizeInBits(Val) == 1) ? 2 /*+test-under-mask*/ : 1);
1271
1272 // Give a slight penalty for moving out of vector pipeline to FXU unit.
1273 if (Index == 0 && Val->isIntOrIntVectorTy())
1274 Cost += 1;
1275
1276 return Cost;
1277 }
1278
1279 return BaseT::getVectorInstrCost(Opcode, Val, CostKind, Index, Op0, Op1, VIC);
1280}
1281
1282// Check if a load may be folded as a memory operand in its user.
1284 const Instruction *&FoldedValue) const {
1285 if (!Ld->hasOneUse())
1286 return false;
1287 FoldedValue = Ld;
1288 const Instruction *UserI = *Ld->user_begin();
1289 unsigned LoadedBits = getScalarSizeInBits(Ld->getType());
1290 unsigned TruncBits = 0;
1291 unsigned SExtBits = 0;
1292 unsigned ZExtBits = 0;
1293 if (UserI->hasOneUse()) {
1294 unsigned UserBits = UserI->getType()->getScalarSizeInBits();
1295 if (isa<TruncInst>(UserI))
1296 TruncBits = UserBits;
1297 else if (isa<SExtInst>(UserI))
1298 SExtBits = UserBits;
1299 else if (isa<ZExtInst>(UserI))
1300 ZExtBits = UserBits;
1301 }
1302 if (TruncBits || SExtBits || ZExtBits) {
1303 FoldedValue = UserI;
1304 UserI = *UserI->user_begin();
1305 // Load (single use) -> trunc/extend (single use) -> UserI
1306 }
1307 if ((UserI->getOpcode() == Instruction::Sub ||
1308 UserI->getOpcode() == Instruction::SDiv ||
1309 UserI->getOpcode() == Instruction::UDiv) &&
1310 UserI->getOperand(1) != FoldedValue)
1311 return false; // Not commutative, only RHS foldable.
1312 // LoadOrTruncBits holds the number of effectively loaded bits, but 0 if an
1313 // extension was made of the load.
1314 unsigned LoadOrTruncBits =
1315 ((SExtBits || ZExtBits) ? 0 : (TruncBits ? TruncBits : LoadedBits));
1316 switch (UserI->getOpcode()) {
1317 case Instruction::Add: // SE: 16->32, 16/32->64, z14:16->64. ZE: 32->64
1318 case Instruction::Sub:
1319 case Instruction::ICmp:
1320 if (LoadedBits == 32 && ZExtBits == 64)
1321 return true;
1322 [[fallthrough]];
1323 case Instruction::Mul: // SE: 16->32, 32->64, z14:16->64
1324 if (UserI->getOpcode() != Instruction::ICmp) {
1325 if (LoadedBits == 16 &&
1326 (SExtBits == 32 ||
1327 (SExtBits == 64 && ST->hasMiscellaneousExtensions2())))
1328 return true;
1329 if (LoadOrTruncBits == 16)
1330 return true;
1331 }
1332 [[fallthrough]];
1333 case Instruction::SDiv:// SE: 32->64
1334 if (LoadedBits == 32 && SExtBits == 64)
1335 return true;
1336 [[fallthrough]];
1337 case Instruction::UDiv:
1338 case Instruction::And:
1339 case Instruction::Or:
1340 case Instruction::Xor:
1341 // This also makes sense for float operations, but disabled for now due
1342 // to regressions.
1343 // case Instruction::FCmp:
1344 // case Instruction::FAdd:
1345 // case Instruction::FSub:
1346 // case Instruction::FMul:
1347 // case Instruction::FDiv:
1348
1349 // All possible extensions of memory checked above.
1350
1351 // Comparison between memory and immediate.
1352 if (UserI->getOpcode() == Instruction::ICmp)
1353 if (ConstantInt *CI = dyn_cast<ConstantInt>(UserI->getOperand(1)))
1354 if (CI->getValue().isIntN(16))
1355 return true;
1356 return (LoadOrTruncBits == 32 || LoadOrTruncBits == 64);
1357 break;
1358 }
1359 return false;
1360}
1361
1362static bool isBswapIntrinsicCall(const Value *V) {
1363 if (const Instruction *I = dyn_cast<Instruction>(V))
1364 if (auto *CI = dyn_cast<CallInst>(I))
1365 if (auto *F = CI->getCalledFunction())
1366 if (F->getIntrinsicID() == Intrinsic::bswap)
1367 return true;
1368 return false;
1369}
1370
1372 Align Alignment,
1373 unsigned AddressSpace,
1374 TTI::TargetCostKind CostKind,
1375 TTI::OperandValueInfo OpInfo,
1376 const Instruction *I) const {
1377 assert(!Src->isVoidTy() && "Invalid type");
1378
1379 // FIXME: Load latency isn't handled here
1380 if (Opcode == Instruction::Load && CostKind == TTI::TCK_Latency)
1381 return BaseT::getMemoryOpCost(Opcode, Src, Alignment, AddressSpace,
1382 CostKind, OpInfo, I);
1383
1384 // TODO: Handle other cost kinds.
1385 if (CostKind != TTI::TCK_RecipThroughput)
1386 return 1;
1387
1388 if (I && Opcode == Instruction::Store && !Src->isVectorTy()) {
1389 if (isFoldableRMW(dyn_cast<Instruction>(I->getOperand(0)), Src))
1390 return TTI::TCC_Free;
1391 }
1392
1393 if (!Src->isVectorTy() && Opcode == Instruction::Load && I != nullptr) {
1394 // Store the load or its truncated or extended value in FoldedValue.
1395 const Instruction *FoldedValue = nullptr;
1396 if (isFoldableLoad(cast<LoadInst>(I), FoldedValue)) {
1397 const Instruction *UserI = *FoldedValue->user_begin();
1398 assert (UserI->getNumOperands() == 2 && "Expected a binop.");
1399
1400 // UserI can't fold two loads, so in that case return 0 cost only
1401 // half of the time.
1402 for (unsigned i = 0; i < 2; ++i) {
1403 if (UserI->getOperand(i) == FoldedValue)
1404 continue;
1405
1406 if (Instruction *OtherOp = dyn_cast<Instruction>(UserI->getOperand(i))){
1407 LoadInst *OtherLoad = dyn_cast<LoadInst>(OtherOp);
1408 if (!OtherLoad &&
1409 (isa<TruncInst>(OtherOp) || isa<SExtInst>(OtherOp) ||
1410 isa<ZExtInst>(OtherOp)))
1411 OtherLoad = dyn_cast<LoadInst>(OtherOp->getOperand(0));
1412 if (OtherLoad && isFoldableLoad(OtherLoad, FoldedValue/*dummy*/))
1413 return i == 0; // Both operands foldable.
1414 }
1415 }
1416
1417 return 0; // Only I is foldable in user.
1418 }
1419 }
1420
1421 // Type legalization (via getNumberOfParts) can't handle structs
1422 if (TLI->getValueType(DL, Src, true) == MVT::Other)
1423 return BaseT::getMemoryOpCost(Opcode, Src, Alignment, AddressSpace,
1424 CostKind);
1425
1426 // FP128 is a legal type but kept in a register pair on older CPUs.
1427 if (Src->isFP128Ty() && !ST->hasVectorEnhancements1())
1428 return 2;
1429
1430 unsigned NumOps =
1431 (Src->isVectorTy() ? getNumVectorRegs(Src) : getNumberOfParts(Src));
1432
1433 // Store/Load reversed saves one instruction.
1434 if (((!Src->isVectorTy() && NumOps == 1) || ST->hasVectorEnhancements2()) &&
1435 I != nullptr) {
1436 if (Opcode == Instruction::Load && I->hasOneUse()) {
1437 const Instruction *LdUser = *I->user_begin();
1438 // In case of load -> bswap -> store, return normal cost for the load.
1439 if (isBswapIntrinsicCall(LdUser) &&
1440 (!LdUser->hasOneUse() || !isa<StoreInst>(*LdUser->user_begin())))
1441 return 0;
1442 }
1443 else if (const StoreInst *SI = dyn_cast<StoreInst>(I)) {
1444 const Value *StoredVal = SI->getValueOperand();
1445 if (StoredVal->hasOneUse() && isBswapIntrinsicCall(StoredVal))
1446 return 0;
1447 }
1448 }
1449
1450 return NumOps;
1451}
1452
1453// The generic implementation of getInterleavedMemoryOpCost() is based on
1454// adding costs of the memory operations plus all the extracts and inserts
1455// needed for using / defining the vector operands. The SystemZ version does
1456// roughly the same but bases the computations on vector permutations
1457// instead.
1459 unsigned Opcode, Type *VecTy, unsigned Factor, ArrayRef<unsigned> Indices,
1460 Align Alignment, unsigned AddressSpace, TTI::TargetCostKind CostKind,
1461 bool UseMaskForCond, bool UseMaskForGaps) const {
1462 if (UseMaskForCond || UseMaskForGaps)
1463 return BaseT::getInterleavedMemoryOpCost(Opcode, VecTy, Factor, Indices,
1464 Alignment, AddressSpace, CostKind,
1465 UseMaskForCond, UseMaskForGaps);
1466 assert(isa<VectorType>(VecTy) &&
1467 "Expect a vector type for interleaved memory op");
1468
1469 unsigned NumElts = cast<FixedVectorType>(VecTy)->getNumElements();
1470 assert(Factor > 1 && NumElts % Factor == 0 && "Invalid interleave factor");
1471 unsigned VF = NumElts / Factor;
1472 unsigned NumEltsPerVecReg = (128U / getScalarSizeInBits(VecTy));
1473 unsigned NumVectorMemOps = getNumVectorRegs(VecTy);
1474 unsigned NumPermutes = 0;
1475
1476 if (Opcode == Instruction::Load) {
1477 // Loading interleave groups may have gaps, which may mean fewer
1478 // loads. Find out how many vectors will be loaded in total, and in how
1479 // many of them each value will be in.
1480 BitVector UsedInsts(NumVectorMemOps, false);
1481 std::vector<BitVector> ValueVecs(Factor, BitVector(NumVectorMemOps, false));
1482 for (unsigned Index : Indices)
1483 for (unsigned Elt = 0; Elt < VF; ++Elt) {
1484 unsigned Vec = (Index + Elt * Factor) / NumEltsPerVecReg;
1485 UsedInsts.set(Vec);
1486 ValueVecs[Index].set(Vec);
1487 }
1488 NumVectorMemOps = UsedInsts.count();
1489
1490 for (unsigned Index : Indices) {
1491 // Estimate that each loaded source vector containing this Index
1492 // requires one operation, except that vperm can handle two input
1493 // registers first time for each dst vector.
1494 unsigned NumSrcVecs = ValueVecs[Index].count();
1495 unsigned NumDstVecs = divideCeil(VF * getScalarSizeInBits(VecTy), 128U);
1496 assert (NumSrcVecs >= NumDstVecs && "Expected at least as many sources");
1497 NumPermutes += std::max(1U, NumSrcVecs - NumDstVecs);
1498 }
1499 } else {
1500 // Estimate the permutes for each stored vector as the smaller of the
1501 // number of elements and the number of source vectors. Subtract one per
1502 // dst vector for vperm (S.A.).
1503 unsigned NumSrcVecs = std::min(NumEltsPerVecReg, Factor);
1504 unsigned NumDstVecs = NumVectorMemOps;
1505 NumPermutes += (NumDstVecs * NumSrcVecs) - NumDstVecs;
1506 }
1507
1508 // Cost of load/store operations and the permutations needed.
1509 return NumVectorMemOps + NumPermutes;
1510}
1511
1512InstructionCost getIntAddReductionCost(unsigned NumVec, unsigned ScalarBits) {
1513 InstructionCost Cost = 0;
1514 // Binary Tree of N/2 + N/4 + ... operations yields N - 1 operations total.
1515 Cost += NumVec - 1;
1516 // For integer adds, VSUM creates shorter reductions on the final vector.
1517 Cost += (ScalarBits < 32) ? 3 : 2;
1518 return Cost;
1519}
1520
1521InstructionCost getFastReductionCost(unsigned NumVec, unsigned NumElems,
1522 unsigned ScalarBits) {
1523 unsigned NumEltsPerVecReg = (SystemZ::VectorBits / ScalarBits);
1524 InstructionCost Cost = 0;
1525 // Binary Tree of N/2 + N/4 + ... operations yields N - 1 operations total.
1526 Cost += NumVec - 1;
1527 // For each shuffle / arithmetic layer, we need 2 instructions, and we need
1528 // log2(Elements in Last Vector) layers.
1529 Cost += 2 * Log2_32_Ceil(std::min(NumElems, NumEltsPerVecReg));
1530 return Cost;
1531}
1532
1533inline bool customCostReductions(unsigned Opcode) {
1534 return Opcode == Instruction::FAdd || Opcode == Instruction::FMul ||
1535 Opcode == Instruction::Add || Opcode == Instruction::Mul;
1536}
1537
1540 std::optional<FastMathFlags> FMF,
1541 TTI::TargetCostKind CostKind) const {
1542 unsigned ScalarBits = Ty->getScalarSizeInBits();
1543 // The following is only for subtargets with vector math, non-ordered
1544 // reductions, and reasonable scalar sizes for int and fp add/mul.
1545 if (customCostReductions(Opcode) && ST->hasVector() &&
1547 ScalarBits <= SystemZ::VectorBits) {
1548 unsigned NumVectors = getNumVectorRegs(Ty);
1549 unsigned NumElems = ((FixedVectorType *)Ty)->getNumElements();
1550 // Integer Add is using custom code gen, that needs to be accounted for.
1551 if (Opcode == Instruction::Add)
1552 return getIntAddReductionCost(NumVectors, ScalarBits);
1553 // The base cost is the same across all other arithmetic instructions
1555 getFastReductionCost(NumVectors, NumElems, ScalarBits);
1556 // But we need to account for the final op involving the scalar operand.
1557 if ((Opcode == Instruction::FAdd) || (Opcode == Instruction::FMul))
1558 Cost += 1;
1559 return Cost;
1560 }
1561 // otherwise, fall back to the standard implementation
1562 return BaseT::getArithmeticReductionCost(Opcode, Ty, FMF, CostKind);
1563}
1564
1567 FastMathFlags FMF,
1568 TTI::TargetCostKind CostKind) const {
1569 // Return custom costs only on subtargets with vector enhancements.
1570 if (ST->hasVectorEnhancements1()) {
1571 unsigned NumVectors = getNumVectorRegs(Ty);
1572 unsigned NumElems = ((FixedVectorType *)Ty)->getNumElements();
1573 unsigned ScalarBits = Ty->getScalarSizeInBits();
1575 // Binary Tree of N/2 + N/4 + ... operations yields N - 1 operations total.
1576 Cost += NumVectors - 1;
1577 // For the final vector, we need shuffle + min/max operations, and
1578 // we need #Elements - 1 of them.
1579 Cost += 2 * (std::min(NumElems, SystemZ::VectorBits / ScalarBits) - 1);
1580 return Cost;
1581 }
1582 // For other targets, fall back to the standard implementation
1583 return BaseT::getMinMaxReductionCost(IID, Ty, FMF, CostKind);
1584}
1585
1586static int
1588 const SmallVectorImpl<Type *> &ParamTys) {
1589 if (RetTy->isVectorTy() && ID == Intrinsic::bswap)
1590 return getNumVectorRegs(RetTy); // VPERM
1591
1592 return -1;
1593}
1594
1597 TTI::TargetCostKind CostKind) const {
1599 ICA.getID(), ICA.getReturnType(), ICA.getArgTypes());
1600 if (Cost != -1)
1601 return Cost;
1602 return BaseT::getIntrinsicInstrCost(ICA, CostKind);
1603}
1604
1606 // Always expand on Subtargets without vector instructions.
1607 if (!ST->hasVector())
1608 return true;
1609
1610 // Whether or not to expand is a per-intrinsic decision.
1611 switch (II->getIntrinsicID()) {
1612 default:
1613 return true;
1614 // Do not expand vector.reduce.add...
1615 case Intrinsic::vector_reduce_add:
1616 auto *VType = cast<FixedVectorType>(II->getOperand(0)->getType());
1617 // ...unless the scalar size is i64 or larger,
1618 // or the operand vector is not full, since the
1619 // performance benefit is dubious in those cases.
1620 return VType->getScalarSizeInBits() >= 64 ||
1621 VType->getPrimitiveSizeInBits() < SystemZ::VectorBits;
1622 }
1623}
unsigned NumParts
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
uint64_t Imm
Expand Atomic instructions
This file provides a helper that implements much of the TTI interface in terms of the target-independ...
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static unsigned InstrCount
Hexagon Common GEP
const HexagonInstrInfo * TII
This file defines an InstructionCost class that is used when calculating the cost of an instruction,...
const size_t AbstractManglingParser< Derived, Alloc >::NumOps
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
static const Function * getCalledFunction(const MachineInstr &MI)
uint64_t IntrinsicInst * II
#define P(N)
int64_t C1
#define LLVM_DEBUG(...)
Definition Debug.h:119
bool customCostReductions(unsigned Opcode)
static unsigned getElSizeLog2Diff(Type *Ty0, Type *Ty1)
static bool isBswapIntrinsicCall(const Value *V)
InstructionCost getIntAddReductionCost(unsigned NumVec, unsigned ScalarBits)
static void countNumMemAccesses(const Value *Ptr, unsigned &NumStores, unsigned &NumLoads, const Function *F)
static unsigned getOperandsExtensionCost(const Instruction *I)
static Type * getCmpOpsType(const Instruction *I, unsigned VF=1)
static unsigned getScalarSizeInBits(Type *Ty)
static bool isFoldableRMW(const Instruction *I, Type *Ty)
static bool isFreeEltLoad(const Value *Op)
InstructionCost getFastReductionCost(unsigned NumVec, unsigned NumElems, unsigned ScalarBits)
static int getVectorIntrinsicInstrCost(Intrinsic::ID ID, Type *RetTy, const SmallVectorImpl< Type * > &ParamTys)
static bool isUsedAsMemCpySource(const Value *V, bool &OtherUse)
static unsigned getNumVectorRegs(Type *Ty)
This file describes how to lower LLVM code to machine code.
This pass exposes codegen information to IR-level passes.
Class for arbitrary precision integers.
Definition APInt.h:78
bool isNegatedPowerOf2() const
Check if this APInt's negated value is a power of two greater than zero.
Definition APInt.h:445
bool isPowerOf2() const
Check if this APInt's value is a power of two greater than zero.
Definition APInt.h:436
This class represents an incoming formal argument to a Function.
Definition Argument.h:32
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
Get the array size.
Definition ArrayRef.h:141
bool empty() const
Check if the array is empty.
Definition ArrayRef.h:136
InstructionCost getInterleavedMemoryOpCost(unsigned Opcode, Type *VecTy, unsigned Factor, ArrayRef< unsigned > Indices, Align Alignment, unsigned AddressSpace, TTI::TargetCostKind CostKind, bool UseMaskForCond=false, bool UseMaskForGaps=false) const override
InstructionCost getMinMaxReductionCost(Intrinsic::ID IID, VectorType *Ty, FastMathFlags FMF, TTI::TargetCostKind CostKind) const override
unsigned getNumberOfParts(Type *Tp) const override
TTI::ShuffleKind improveShuffleKindFromMask(TTI::ShuffleKind Kind, ArrayRef< int > Mask, VectorType *SrcTy, int &Index, VectorType *&SubTy) const
InstructionCost getScalarizationOverhead(VectorType *InTy, const APInt &DemandedElts, bool Insert, bool Extract, TTI::TargetCostKind CostKind, bool ForPoisonSrc=true, ArrayRef< Value * > VL={}, TTI::VectorInstrContext VIC=TTI::VectorInstrContext::None) const override
InstructionCost getArithmeticReductionCost(unsigned Opcode, VectorType *Ty, std::optional< FastMathFlags > FMF, TTI::TargetCostKind CostKind) const override
InstructionCost getCmpSelInstrCost(unsigned Opcode, Type *ValTy, Type *CondTy, CmpInst::Predicate VecPred, TTI::TargetCostKind CostKind, TTI::OperandValueInfo Op1Info={TTI::OK_AnyValue, TTI::OP_None}, TTI::OperandValueInfo Op2Info={TTI::OK_AnyValue, TTI::OP_None}, const Instruction *I=nullptr) const override
void getPeelingPreferences(Loop *L, ScalarEvolution &SE, TTI::PeelingPreferences &PP) const override
InstructionCost getShuffleCost(TTI::ShuffleKind Kind, VectorType *DstTy, VectorType *SrcTy, TTI::TargetCostKind CostKind, ArrayRef< int > Mask, int Index, VectorType *SubTp, ArrayRef< const Value * > Args={}, const Instruction *CtxI=nullptr, TTI::VectorInstrContext VIC=TTI::VectorInstrContext::None) const override
InstructionCost getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src, TTI::CastContextHint CCH, TTI::TargetCostKind CostKind, const Instruction *I=nullptr) const override
InstructionCost getVectorInstrCost(unsigned Opcode, Type *Val, TTI::TargetCostKind CostKind, unsigned Index, const Value *Op0, const Value *Op1, TTI::VectorInstrContext VIC=TTI::VectorInstrContext::None) const override
InstructionCost getIntrinsicInstrCost(const IntrinsicCostAttributes &ICA, TTI::TargetCostKind CostKind) const override
InstructionCost getMemoryOpCost(unsigned Opcode, Type *Src, Align Alignment, unsigned AddressSpace, TTI::TargetCostKind CostKind, TTI::OperandValueInfo OpInfo={TTI::OK_AnyValue, TTI::OP_None}, const Instruction *I=nullptr) const override
InstructionCost getArithmeticInstrCost(unsigned Opcode, Type *Ty, TTI::TargetCostKind CostKind, TTI::OperandValueInfo Opd1Info={TTI::OK_AnyValue, TTI::OP_None}, TTI::OperandValueInfo Opd2Info={TTI::OK_AnyValue, TTI::OP_None}, ArrayRef< const Value * > Args={}, const Instruction *CtxI=nullptr, const TargetLibraryInfo *TLibInfo=nullptr, ArrayRef< const Value * > Scalars={}) const override
size_type count() const
Returns the number of bits which are set.
Definition BitVector.h:182
BitVector & set()
Set all bits in the bitvector.
Definition BitVector.h:367
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
Value * getArgOperand(unsigned i) const
This class is the base class for the comparison instructions.
Definition InstrTypes.h:728
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:740
@ ICMP_SLE
signed less or equal
Definition InstrTypes.h:770
@ ICMP_UGE
unsigned greater or equal
Definition InstrTypes.h:764
@ FCMP_ONE
0 1 1 0 True if ordered and operands are unequal
Definition InstrTypes.h:748
@ FCMP_UEQ
1 0 0 1 True if unordered or equal
Definition InstrTypes.h:751
@ FCMP_ORD
0 1 1 1 True if ordered (no nans)
Definition InstrTypes.h:749
@ ICMP_NE
not equal
Definition InstrTypes.h:762
@ ICMP_SGE
signed greater or equal
Definition InstrTypes.h:768
@ ICMP_ULE
unsigned less or equal
Definition InstrTypes.h:766
@ FCMP_UNO
1 0 0 0 True if unordered: isnan(X) | isnan(Y)
Definition InstrTypes.h:750
This is the shared class of boolean and integer constants.
Definition Constants.h:87
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition Constants.h:159
This is an important base class in LLVM.
Definition Constant.h:44
constexpr bool isVector() const
One or more elements.
Definition TypeSize.h:321
Convenience struct for specifying and reasoning about fast-math flags.
Definition FMF.h:23
Class to represent fixed width SIMD vectors.
static LLVM_ABI FixedVectorType * get(Type *ElementType, unsigned NumElts)
Definition Type.cpp:838
This instruction compares its operands according to the predicate given to the constructor.
CostType getValue() const
This function is intended to be used as sparingly as possible, since the class provides the full rang...
user_iterator user_begin()
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
const SmallVectorImpl< Type * > & getArgTypes() const
A wrapper class for inspecting calls to intrinsic functions.
An instruction for reading from memory.
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
This class wraps the llvm.memcpy intrinsic.
The optimization diagnostic interface.
The main scalar evolution driver.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
An instruction for storing to memory.
InstructionCost getScalarizationOverhead(VectorType *Ty, const APInt &DemandedElts, bool Insert, bool Extract, TTI::TargetCostKind CostKind, bool ForPoisonSrc=true, ArrayRef< Value * > VL={}, TTI::VectorInstrContext VIC=TTI::VectorInstrContext::None) const override
Estimate the overhead of scalarizing an instruction.
bool isFoldableLoad(const LoadInst *Ld, const Instruction *&FoldedValue) const
bool isLSRCostLess(const TargetTransformInfo::LSRCost &C1, const TargetTransformInfo::LSRCost &C2) const override
InstructionCost getMinMaxReductionCost(Intrinsic::ID IID, VectorType *Ty, FastMathFlags FMF, TTI::TargetCostKind CostKind) const override
Try to calculate op costs for min/max reduction operations.
InstructionCost getCFInstrCost(unsigned Opcode, TTI::TargetCostKind CostKind, const Instruction *I=nullptr) const override
unsigned getNumberOfRegisters(unsigned ClassID) const override
void getPeelingPreferences(Loop *L, ScalarEvolution &SE, TTI::PeelingPreferences &PP) const override
InstructionCost getShuffleCost(TTI::ShuffleKind Kind, VectorType *DstTy, VectorType *SrcTy, TTI::TargetCostKind CostKind, ArrayRef< int > Mask, int Index, VectorType *SubTp, ArrayRef< const Value * > Args={}, const Instruction *CtxI=nullptr, TTI::VectorInstrContext VIC=TTI::VectorInstrContext::None) const override
InstructionCost getIntrinsicInstrCost(const IntrinsicCostAttributes &ICA, TTI::TargetCostKind CostKind) const override
Get intrinsic cost based on arguments.
unsigned getMinPrefetchStride(unsigned NumMemAccesses, unsigned NumStridedMemAccesses, unsigned NumPrefetches, bool HasCall) const override
InstructionCost getVectorInstrCost(unsigned Opcode, Type *Val, TTI::TargetCostKind CostKind, unsigned Index, const Value *Op0, const Value *Op1, TTI::VectorInstrContext VIC=TTI::VectorInstrContext::None) const override
InstructionCost getArithmeticInstrCost(unsigned Opcode, Type *Ty, TTI::TargetCostKind CostKind, TTI::OperandValueInfo Op1Info={TTI::OK_AnyValue, TTI::OP_None}, TTI::OperandValueInfo Op2Info={TTI::OK_AnyValue, TTI::OP_None}, ArrayRef< const Value * > Args={}, const Instruction *CtxI=nullptr, const TargetLibraryInfo *TLibInfo=nullptr, ArrayRef< const Value * > Scalars={}) const override
InstructionCost getIntImmCostIntrin(Intrinsic::ID IID, unsigned Idx, const APInt &Imm, Type *Ty, TTI::TargetCostKind CostKind) const override
unsigned getVectorBitmaskConversionCost(Type *SrcTy, Type *DstTy) const
unsigned getBoolVecToIntConversionCost(unsigned Opcode, Type *Dst, const Instruction *I) const
InstructionCost getIntImmCostInst(unsigned Opcode, unsigned Idx, const APInt &Imm, Type *Ty, TTI::TargetCostKind CostKind, Instruction *Inst=nullptr) const override
bool shouldExpandReduction(const IntrinsicInst *II) const override
InstructionCost getInterleavedMemoryOpCost(unsigned Opcode, Type *VecTy, unsigned Factor, ArrayRef< unsigned > Indices, Align Alignment, unsigned AddressSpace, TTI::TargetCostKind CostKind, bool UseMaskForCond=false, bool UseMaskForGaps=false) const override
InstructionCost getArithmeticReductionCost(unsigned Opcode, VectorType *Ty, std::optional< FastMathFlags > FMF, TTI::TargetCostKind CostKind) const override
bool hasDivRemOp(Type *DataType, bool IsSigned) const override
unsigned getVectorTruncCost(Type *SrcTy, Type *DstTy) const
void getUnrollingPreferences(Loop *L, ScalarEvolution &SE, TTI::UnrollingPreferences &UP, OptimizationRemarkEmitter *ORE) const override
unsigned adjustInliningThreshold(const CallBase *CB) const override
InstructionCost getMemoryOpCost(unsigned Opcode, Type *Src, Align Alignment, unsigned AddressSpace, TTI::TargetCostKind CostKind, TTI::OperandValueInfo OpInfo={TTI::OK_AnyValue, TTI::OP_None}, const Instruction *I=nullptr) const override
InstructionCost getCmpSelInstrCost(unsigned Opcode, Type *ValTy, Type *CondTy, CmpInst::Predicate VecPred, TTI::TargetCostKind CostKind, TTI::OperandValueInfo Op1Info={TTI::OK_AnyValue, TTI::OP_None}, TTI::OperandValueInfo Op2Info={TTI::OK_AnyValue, TTI::OP_None}, const Instruction *I=nullptr) const override
TypeSize getRegisterBitWidth(TargetTransformInfo::RegisterKind K) const override
InstructionCost getIntImmCost(const APInt &Imm, Type *Ty, TTI::TargetCostKind CostKind) const override
unsigned getMaxInterleaveFactor(ElementCount VF, bool HasUnorderedReductions) const override
InstructionCost getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src, TTI::CastContextHint CCH, TTI::TargetCostKind CostKind, const Instruction *I=nullptr) const override
Provides information about what library functions are available for the current target.
virtual bool isLoweredToCall(const Function *F) const
TargetCostKind
The kind of cost model.
@ TCK_RecipThroughput
Reciprocal throughput.
@ TCK_CodeSize
Instruction code size.
@ TCK_SizeAndLatency
The weighted sum of size and latency.
@ TCK_Latency
The latency of instruction.
static bool requiresOrderedReduction(std::optional< FastMathFlags > FMF)
A helper function to determine the type of reduction algorithm used for a given Opcode and set of Fas...
llvm::VectorInstrContext VectorInstrContext
@ TCC_Free
Expected to fold away in lowering.
@ TCC_Basic
The cost of a typical 'add' instruction.
ShuffleKind
The various kinds of shuffle patterns for vector queries.
@ SK_Broadcast
Broadcast element 0 to all other elements.
@ SK_ExtractSubvector
ExtractSubvector Index indicates start offset.
CastContextHint
Represents a hint about the context in which a cast is used.
static constexpr TypeSize getFixed(ScalarTy ExactSize)
Definition TypeSize.h:352
static constexpr TypeSize getScalable(ScalarTy MinimumSize)
Definition TypeSize.h:355
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:283
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
Definition Type.h:258
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.h:354
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:370
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
Definition Type.h:186
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:252
Value * getOperand(unsigned i) const
Definition User.h:207
unsigned getNumOperands() const
Definition User.h:229
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition Value.h:441
iterator_range< user_iterator > users()
Definition Value.h:428
Base class of all SIMD vector types.
const ParentTy * getParent() const
Definition ilist_node.h:34
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
const unsigned VectorBits
Definition SystemZ.h:160
This is an optimization pass for GlobalISel generic memory operations.
unsigned Log2_32_Ceil(uint32_t Value)
Return the ceil log base 2 of the specified value, 32 if the value is zero.
Definition MathExtras.h:339
InstructionCost Cost
constexpr bool isInt(int64_t x)
Checks if an integer fits into the given bit width.
Definition MathExtras.h:166
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
unsigned Log2_32(uint32_t Value)
Return the floor log base 2 of the specified value, -1 if the value is zero.
Definition MathExtras.h:326
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
constexpr bool isUInt(uint64_t x)
Checks if an unsigned integer fits into the given bit width.
Definition MathExtras.h:190
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
constexpr T divideCeil(U Numerator, V Denominator)
Returns the integer ceil(Numerator / Denominator).
Definition MathExtras.h:389
DWARFExpression::Operation Op
constexpr unsigned BitWidth
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:320
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
Extended Value Type.
Definition ValueTypes.h:35
bool isScalarInteger() const
Return true if this is an integer, but not a vector.
Definition ValueTypes.h:180
unsigned Insns
TODO: Some of these could be merged.
Parameters that control the generic loop unrolling transformation.
bool Force
Apply loop unroll on any kind of loop (mainly to loops that fail runtime unrolling).
unsigned DefaultUnrollRuntimeCount
Default unroll count for loops with run-time trip count.
unsigned FullUnrollMaxCount
Set the maximum unrolling factor for full unrolling.
unsigned PartialThreshold
The cost threshold for the unrolled loop, like Threshold, but used for partial/runtime unrolling (set...
bool Runtime
Allow runtime unrolling (unrolling of loops to expand the size of the loop body even when the number ...
bool Partial
Allow partial unrolling (unrolling of loops to expand the size of the loop body, not only to eliminat...
bool AllowExpensiveTripCount
Allow emitting expensive instructions (such as divisions) when computing the trip count of a loop for...