1 //===- ARMTargetTransformInfo.cpp - ARM 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 #include "ARMTargetTransformInfo.h" 10 #include "ARMSubtarget.h" 11 #include "MCTargetDesc/ARMAddressingModes.h" 12 #include "llvm/ADT/APInt.h" 13 #include "llvm/ADT/SmallVector.h" 14 #include "llvm/Analysis/LoopInfo.h" 15 #include "llvm/CodeGen/CostTable.h" 16 #include "llvm/CodeGen/ISDOpcodes.h" 17 #include "llvm/CodeGen/ValueTypes.h" 18 #include "llvm/IR/BasicBlock.h" 19 #include "llvm/IR/DataLayout.h" 20 #include "llvm/IR/DerivedTypes.h" 21 #include "llvm/IR/Instruction.h" 22 #include "llvm/IR/Instructions.h" 23 #include "llvm/IR/Intrinsics.h" 24 #include "llvm/IR/IntrinsicInst.h" 25 #include "llvm/IR/IntrinsicsARM.h" 26 #include "llvm/IR/PatternMatch.h" 27 #include "llvm/IR/Type.h" 28 #include "llvm/MC/SubtargetFeature.h" 29 #include "llvm/Support/Casting.h" 30 #include "llvm/Support/KnownBits.h" 31 #include "llvm/Support/MachineValueType.h" 32 #include "llvm/Target/TargetMachine.h" 33 #include "llvm/Transforms/InstCombine/InstCombiner.h" 34 #include "llvm/Transforms/Utils/Local.h" 35 #include "llvm/Transforms/Utils/LoopUtils.h" 36 #include <algorithm> 37 #include <cassert> 38 #include <cstdint> 39 #include <utility> 40 41 using namespace llvm; 42 43 #define DEBUG_TYPE "armtti" 44 45 static cl::opt<bool> EnableMaskedLoadStores( 46 "enable-arm-maskedldst", cl::Hidden, cl::init(true), 47 cl::desc("Enable the generation of masked loads and stores")); 48 49 static cl::opt<bool> DisableLowOverheadLoops( 50 "disable-arm-loloops", cl::Hidden, cl::init(false), 51 cl::desc("Disable the generation of low-overhead loops")); 52 53 extern cl::opt<TailPredication::Mode> EnableTailPredication; 54 55 extern cl::opt<bool> EnableMaskedGatherScatters; 56 57 extern cl::opt<unsigned> MVEMaxSupportedInterleaveFactor; 58 59 /// Convert a vector load intrinsic into a simple llvm load instruction. 60 /// This is beneficial when the underlying object being addressed comes 61 /// from a constant, since we get constant-folding for free. 62 static Value *simplifyNeonVld1(const IntrinsicInst &II, unsigned MemAlign, 63 InstCombiner::BuilderTy &Builder) { 64 auto *IntrAlign = dyn_cast<ConstantInt>(II.getArgOperand(1)); 65 66 if (!IntrAlign) 67 return nullptr; 68 69 unsigned Alignment = IntrAlign->getLimitedValue() < MemAlign 70 ? MemAlign 71 : IntrAlign->getLimitedValue(); 72 73 if (!isPowerOf2_32(Alignment)) 74 return nullptr; 75 76 auto *BCastInst = Builder.CreateBitCast(II.getArgOperand(0), 77 PointerType::get(II.getType(), 0)); 78 return Builder.CreateAlignedLoad(II.getType(), BCastInst, Align(Alignment)); 79 } 80 81 bool ARMTTIImpl::areInlineCompatible(const Function *Caller, 82 const Function *Callee) const { 83 const TargetMachine &TM = getTLI()->getTargetMachine(); 84 const FeatureBitset &CallerBits = 85 TM.getSubtargetImpl(*Caller)->getFeatureBits(); 86 const FeatureBitset &CalleeBits = 87 TM.getSubtargetImpl(*Callee)->getFeatureBits(); 88 89 // To inline a callee, all features not in the allowed list must match exactly. 90 bool MatchExact = (CallerBits & ~InlineFeaturesAllowed) == 91 (CalleeBits & ~InlineFeaturesAllowed); 92 // For features in the allowed list, the callee's features must be a subset of 93 // the callers'. 94 bool MatchSubset = ((CallerBits & CalleeBits) & InlineFeaturesAllowed) == 95 (CalleeBits & InlineFeaturesAllowed); 96 return MatchExact && MatchSubset; 97 } 98 99 bool ARMTTIImpl::shouldFavorBackedgeIndex(const Loop *L) const { 100 if (L->getHeader()->getParent()->hasOptSize()) 101 return false; 102 if (ST->hasMVEIntegerOps()) 103 return false; 104 return ST->isMClass() && ST->isThumb2() && L->getNumBlocks() == 1; 105 } 106 107 bool ARMTTIImpl::shouldFavorPostInc() const { 108 if (ST->hasMVEIntegerOps()) 109 return true; 110 return false; 111 } 112 113 Optional<Instruction *> 114 ARMTTIImpl::instCombineIntrinsic(InstCombiner &IC, IntrinsicInst &II) const { 115 using namespace PatternMatch; 116 Intrinsic::ID IID = II.getIntrinsicID(); 117 switch (IID) { 118 default: 119 break; 120 case Intrinsic::arm_neon_vld1: { 121 Align MemAlign = 122 getKnownAlignment(II.getArgOperand(0), IC.getDataLayout(), &II, 123 &IC.getAssumptionCache(), &IC.getDominatorTree()); 124 if (Value *V = simplifyNeonVld1(II, MemAlign.value(), IC.Builder)) { 125 return IC.replaceInstUsesWith(II, V); 126 } 127 break; 128 } 129 130 case Intrinsic::arm_neon_vld2: 131 case Intrinsic::arm_neon_vld3: 132 case Intrinsic::arm_neon_vld4: 133 case Intrinsic::arm_neon_vld2lane: 134 case Intrinsic::arm_neon_vld3lane: 135 case Intrinsic::arm_neon_vld4lane: 136 case Intrinsic::arm_neon_vst1: 137 case Intrinsic::arm_neon_vst2: 138 case Intrinsic::arm_neon_vst3: 139 case Intrinsic::arm_neon_vst4: 140 case Intrinsic::arm_neon_vst2lane: 141 case Intrinsic::arm_neon_vst3lane: 142 case Intrinsic::arm_neon_vst4lane: { 143 Align MemAlign = 144 getKnownAlignment(II.getArgOperand(0), IC.getDataLayout(), &II, 145 &IC.getAssumptionCache(), &IC.getDominatorTree()); 146 unsigned AlignArg = II.getNumArgOperands() - 1; 147 Value *AlignArgOp = II.getArgOperand(AlignArg); 148 MaybeAlign Align = cast<ConstantInt>(AlignArgOp)->getMaybeAlignValue(); 149 if (Align && *Align < MemAlign) { 150 return IC.replaceOperand( 151 II, AlignArg, 152 ConstantInt::get(Type::getInt32Ty(II.getContext()), MemAlign.value(), 153 false)); 154 } 155 break; 156 } 157 158 case Intrinsic::arm_mve_pred_i2v: { 159 Value *Arg = II.getArgOperand(0); 160 Value *ArgArg; 161 if (match(Arg, PatternMatch::m_Intrinsic<Intrinsic::arm_mve_pred_v2i>( 162 PatternMatch::m_Value(ArgArg))) && 163 II.getType() == ArgArg->getType()) { 164 return IC.replaceInstUsesWith(II, ArgArg); 165 } 166 Constant *XorMask; 167 if (match(Arg, m_Xor(PatternMatch::m_Intrinsic<Intrinsic::arm_mve_pred_v2i>( 168 PatternMatch::m_Value(ArgArg)), 169 PatternMatch::m_Constant(XorMask))) && 170 II.getType() == ArgArg->getType()) { 171 if (auto *CI = dyn_cast<ConstantInt>(XorMask)) { 172 if (CI->getValue().trunc(16).isAllOnesValue()) { 173 auto TrueVector = IC.Builder.CreateVectorSplat( 174 cast<FixedVectorType>(II.getType())->getNumElements(), 175 IC.Builder.getTrue()); 176 return BinaryOperator::Create(Instruction::Xor, ArgArg, TrueVector); 177 } 178 } 179 } 180 KnownBits ScalarKnown(32); 181 if (IC.SimplifyDemandedBits(&II, 0, APInt::getLowBitsSet(32, 16), 182 ScalarKnown, 0)) { 183 return &II; 184 } 185 break; 186 } 187 case Intrinsic::arm_mve_pred_v2i: { 188 Value *Arg = II.getArgOperand(0); 189 Value *ArgArg; 190 if (match(Arg, PatternMatch::m_Intrinsic<Intrinsic::arm_mve_pred_i2v>( 191 PatternMatch::m_Value(ArgArg)))) { 192 return IC.replaceInstUsesWith(II, ArgArg); 193 } 194 if (!II.getMetadata(LLVMContext::MD_range)) { 195 Type *IntTy32 = Type::getInt32Ty(II.getContext()); 196 Metadata *M[] = { 197 ConstantAsMetadata::get(ConstantInt::get(IntTy32, 0)), 198 ConstantAsMetadata::get(ConstantInt::get(IntTy32, 0xFFFF))}; 199 II.setMetadata(LLVMContext::MD_range, MDNode::get(II.getContext(), M)); 200 return &II; 201 } 202 break; 203 } 204 case Intrinsic::arm_mve_vadc: 205 case Intrinsic::arm_mve_vadc_predicated: { 206 unsigned CarryOp = 207 (II.getIntrinsicID() == Intrinsic::arm_mve_vadc_predicated) ? 3 : 2; 208 assert(II.getArgOperand(CarryOp)->getType()->getScalarSizeInBits() == 32 && 209 "Bad type for intrinsic!"); 210 211 KnownBits CarryKnown(32); 212 if (IC.SimplifyDemandedBits(&II, CarryOp, APInt::getOneBitSet(32, 29), 213 CarryKnown)) { 214 return &II; 215 } 216 break; 217 } 218 case Intrinsic::arm_mve_vmldava: { 219 Instruction *I = cast<Instruction>(&II); 220 if (I->hasOneUse()) { 221 auto *User = cast<Instruction>(*I->user_begin()); 222 Value *OpZ; 223 if (match(User, m_c_Add(m_Specific(I), m_Value(OpZ))) && 224 match(I->getOperand(3), m_Zero())) { 225 Value *OpX = I->getOperand(4); 226 Value *OpY = I->getOperand(5); 227 Type *OpTy = OpX->getType(); 228 229 IC.Builder.SetInsertPoint(User); 230 Value *V = 231 IC.Builder.CreateIntrinsic(Intrinsic::arm_mve_vmldava, {OpTy}, 232 {I->getOperand(0), I->getOperand(1), 233 I->getOperand(2), OpZ, OpX, OpY}); 234 235 IC.replaceInstUsesWith(*User, V); 236 return IC.eraseInstFromFunction(*User); 237 } 238 } 239 return None; 240 } 241 } 242 return None; 243 } 244 245 int ARMTTIImpl::getIntImmCost(const APInt &Imm, Type *Ty, 246 TTI::TargetCostKind CostKind) { 247 assert(Ty->isIntegerTy()); 248 249 unsigned Bits = Ty->getPrimitiveSizeInBits(); 250 if (Bits == 0 || Imm.getActiveBits() >= 64) 251 return 4; 252 253 int64_t SImmVal = Imm.getSExtValue(); 254 uint64_t ZImmVal = Imm.getZExtValue(); 255 if (!ST->isThumb()) { 256 if ((SImmVal >= 0 && SImmVal < 65536) || 257 (ARM_AM::getSOImmVal(ZImmVal) != -1) || 258 (ARM_AM::getSOImmVal(~ZImmVal) != -1)) 259 return 1; 260 return ST->hasV6T2Ops() ? 2 : 3; 261 } 262 if (ST->isThumb2()) { 263 if ((SImmVal >= 0 && SImmVal < 65536) || 264 (ARM_AM::getT2SOImmVal(ZImmVal) != -1) || 265 (ARM_AM::getT2SOImmVal(~ZImmVal) != -1)) 266 return 1; 267 return ST->hasV6T2Ops() ? 2 : 3; 268 } 269 // Thumb1, any i8 imm cost 1. 270 if (Bits == 8 || (SImmVal >= 0 && SImmVal < 256)) 271 return 1; 272 if ((~SImmVal < 256) || ARM_AM::isThumbImmShiftedVal(ZImmVal)) 273 return 2; 274 // Load from constantpool. 275 return 3; 276 } 277 278 // Constants smaller than 256 fit in the immediate field of 279 // Thumb1 instructions so we return a zero cost and 1 otherwise. 280 int ARMTTIImpl::getIntImmCodeSizeCost(unsigned Opcode, unsigned Idx, 281 const APInt &Imm, Type *Ty) { 282 if (Imm.isNonNegative() && Imm.getLimitedValue() < 256) 283 return 0; 284 285 return 1; 286 } 287 288 // Checks whether Inst is part of a min(max()) or max(min()) pattern 289 // that will match to an SSAT instruction 290 static bool isSSATMinMaxPattern(Instruction *Inst, const APInt &Imm) { 291 Value *LHS, *RHS; 292 ConstantInt *C; 293 SelectPatternFlavor InstSPF = matchSelectPattern(Inst, LHS, RHS).Flavor; 294 295 if (InstSPF == SPF_SMAX && 296 PatternMatch::match(RHS, PatternMatch::m_ConstantInt(C)) && 297 C->getValue() == Imm && Imm.isNegative() && (-Imm).isPowerOf2()) { 298 299 auto isSSatMin = [&](Value *MinInst) { 300 if (isa<SelectInst>(MinInst)) { 301 Value *MinLHS, *MinRHS; 302 ConstantInt *MinC; 303 SelectPatternFlavor MinSPF = 304 matchSelectPattern(MinInst, MinLHS, MinRHS).Flavor; 305 if (MinSPF == SPF_SMIN && 306 PatternMatch::match(MinRHS, PatternMatch::m_ConstantInt(MinC)) && 307 MinC->getValue() == ((-Imm) - 1)) 308 return true; 309 } 310 return false; 311 }; 312 313 if (isSSatMin(Inst->getOperand(1)) || 314 (Inst->hasNUses(2) && (isSSatMin(*Inst->user_begin()) || 315 isSSatMin(*(++Inst->user_begin()))))) 316 return true; 317 } 318 return false; 319 } 320 321 int ARMTTIImpl::getIntImmCostInst(unsigned Opcode, unsigned Idx, 322 const APInt &Imm, Type *Ty, 323 TTI::TargetCostKind CostKind, 324 Instruction *Inst) { 325 // Division by a constant can be turned into multiplication, but only if we 326 // know it's constant. So it's not so much that the immediate is cheap (it's 327 // not), but that the alternative is worse. 328 // FIXME: this is probably unneeded with GlobalISel. 329 if ((Opcode == Instruction::SDiv || Opcode == Instruction::UDiv || 330 Opcode == Instruction::SRem || Opcode == Instruction::URem) && 331 Idx == 1) 332 return 0; 333 334 if (Opcode == Instruction::And) { 335 // UXTB/UXTH 336 if (Imm == 255 || Imm == 65535) 337 return 0; 338 // Conversion to BIC is free, and means we can use ~Imm instead. 339 return std::min(getIntImmCost(Imm, Ty, CostKind), 340 getIntImmCost(~Imm, Ty, CostKind)); 341 } 342 343 if (Opcode == Instruction::Add) 344 // Conversion to SUB is free, and means we can use -Imm instead. 345 return std::min(getIntImmCost(Imm, Ty, CostKind), 346 getIntImmCost(-Imm, Ty, CostKind)); 347 348 if (Opcode == Instruction::ICmp && Imm.isNegative() && 349 Ty->getIntegerBitWidth() == 32) { 350 int64_t NegImm = -Imm.getSExtValue(); 351 if (ST->isThumb2() && NegImm < 1<<12) 352 // icmp X, #-C -> cmn X, #C 353 return 0; 354 if (ST->isThumb() && NegImm < 1<<8) 355 // icmp X, #-C -> adds X, #C 356 return 0; 357 } 358 359 // xor a, -1 can always be folded to MVN 360 if (Opcode == Instruction::Xor && Imm.isAllOnesValue()) 361 return 0; 362 363 // Ensures negative constant of min(max()) or max(min()) patterns that 364 // match to SSAT instructions don't get hoisted 365 if (Inst && ((ST->hasV6Ops() && !ST->isThumb()) || ST->isThumb2()) && 366 Ty->getIntegerBitWidth() <= 32) { 367 if (isSSATMinMaxPattern(Inst, Imm) || 368 (isa<ICmpInst>(Inst) && Inst->hasOneUse() && 369 isSSATMinMaxPattern(cast<Instruction>(*Inst->user_begin()), Imm))) 370 return 0; 371 } 372 373 return getIntImmCost(Imm, Ty, CostKind); 374 } 375 376 int ARMTTIImpl::getCFInstrCost(unsigned Opcode, TTI::TargetCostKind CostKind) { 377 if (CostKind == TTI::TCK_RecipThroughput && 378 (ST->hasNEON() || ST->hasMVEIntegerOps())) { 379 // FIXME: The vectorizer is highly sensistive to the cost of these 380 // instructions, which suggests that it may be using the costs incorrectly. 381 // But, for now, just make them free to avoid performance regressions for 382 // vector targets. 383 return 0; 384 } 385 return BaseT::getCFInstrCost(Opcode, CostKind); 386 } 387 388 int ARMTTIImpl::getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src, 389 TTI::CastContextHint CCH, 390 TTI::TargetCostKind CostKind, 391 const Instruction *I) { 392 int ISD = TLI->InstructionOpcodeToISD(Opcode); 393 assert(ISD && "Invalid opcode"); 394 395 // TODO: Allow non-throughput costs that aren't binary. 396 auto AdjustCost = [&CostKind](int Cost) { 397 if (CostKind != TTI::TCK_RecipThroughput) 398 return Cost == 0 ? 0 : 1; 399 return Cost; 400 }; 401 auto IsLegalFPType = [this](EVT VT) { 402 EVT EltVT = VT.getScalarType(); 403 return (EltVT == MVT::f32 && ST->hasVFP2Base()) || 404 (EltVT == MVT::f64 && ST->hasFP64()) || 405 (EltVT == MVT::f16 && ST->hasFullFP16()); 406 }; 407 408 EVT SrcTy = TLI->getValueType(DL, Src); 409 EVT DstTy = TLI->getValueType(DL, Dst); 410 411 if (!SrcTy.isSimple() || !DstTy.isSimple()) 412 return AdjustCost( 413 BaseT::getCastInstrCost(Opcode, Dst, Src, CCH, CostKind, I)); 414 415 // Extending masked load/Truncating masked stores is expensive because we 416 // currently don't split them. This means that we'll likely end up 417 // loading/storing each element individually (hence the high cost). 418 if ((ST->hasMVEIntegerOps() && 419 (Opcode == Instruction::Trunc || Opcode == Instruction::ZExt || 420 Opcode == Instruction::SExt)) || 421 (ST->hasMVEFloatOps() && 422 (Opcode == Instruction::FPExt || Opcode == Instruction::FPTrunc) && 423 IsLegalFPType(SrcTy) && IsLegalFPType(DstTy))) 424 if (CCH == TTI::CastContextHint::Masked && DstTy.getSizeInBits() > 128) 425 return 2 * DstTy.getVectorNumElements() * ST->getMVEVectorCostFactor(); 426 427 // The extend of other kinds of load is free 428 if (CCH == TTI::CastContextHint::Normal || 429 CCH == TTI::CastContextHint::Masked) { 430 static const TypeConversionCostTblEntry LoadConversionTbl[] = { 431 {ISD::SIGN_EXTEND, MVT::i32, MVT::i16, 0}, 432 {ISD::ZERO_EXTEND, MVT::i32, MVT::i16, 0}, 433 {ISD::SIGN_EXTEND, MVT::i32, MVT::i8, 0}, 434 {ISD::ZERO_EXTEND, MVT::i32, MVT::i8, 0}, 435 {ISD::SIGN_EXTEND, MVT::i16, MVT::i8, 0}, 436 {ISD::ZERO_EXTEND, MVT::i16, MVT::i8, 0}, 437 {ISD::SIGN_EXTEND, MVT::i64, MVT::i32, 1}, 438 {ISD::ZERO_EXTEND, MVT::i64, MVT::i32, 1}, 439 {ISD::SIGN_EXTEND, MVT::i64, MVT::i16, 1}, 440 {ISD::ZERO_EXTEND, MVT::i64, MVT::i16, 1}, 441 {ISD::SIGN_EXTEND, MVT::i64, MVT::i8, 1}, 442 {ISD::ZERO_EXTEND, MVT::i64, MVT::i8, 1}, 443 }; 444 if (const auto *Entry = ConvertCostTableLookup( 445 LoadConversionTbl, ISD, DstTy.getSimpleVT(), SrcTy.getSimpleVT())) 446 return AdjustCost(Entry->Cost); 447 448 static const TypeConversionCostTblEntry MVELoadConversionTbl[] = { 449 {ISD::SIGN_EXTEND, MVT::v4i32, MVT::v4i16, 0}, 450 {ISD::ZERO_EXTEND, MVT::v4i32, MVT::v4i16, 0}, 451 {ISD::SIGN_EXTEND, MVT::v4i32, MVT::v4i8, 0}, 452 {ISD::ZERO_EXTEND, MVT::v4i32, MVT::v4i8, 0}, 453 {ISD::SIGN_EXTEND, MVT::v8i16, MVT::v8i8, 0}, 454 {ISD::ZERO_EXTEND, MVT::v8i16, MVT::v8i8, 0}, 455 // The following extend from a legal type to an illegal type, so need to 456 // split the load. This introduced an extra load operation, but the 457 // extend is still "free". 458 {ISD::SIGN_EXTEND, MVT::v8i32, MVT::v8i16, 1}, 459 {ISD::ZERO_EXTEND, MVT::v8i32, MVT::v8i16, 1}, 460 {ISD::SIGN_EXTEND, MVT::v16i32, MVT::v16i8, 3}, 461 {ISD::ZERO_EXTEND, MVT::v16i32, MVT::v16i8, 3}, 462 {ISD::SIGN_EXTEND, MVT::v16i16, MVT::v16i8, 1}, 463 {ISD::ZERO_EXTEND, MVT::v16i16, MVT::v16i8, 1}, 464 }; 465 if (SrcTy.isVector() && ST->hasMVEIntegerOps()) { 466 if (const auto *Entry = 467 ConvertCostTableLookup(MVELoadConversionTbl, ISD, 468 DstTy.getSimpleVT(), SrcTy.getSimpleVT())) 469 return AdjustCost(Entry->Cost * ST->getMVEVectorCostFactor()); 470 } 471 472 static const TypeConversionCostTblEntry MVEFLoadConversionTbl[] = { 473 // FPExtends are similar but also require the VCVT instructions. 474 {ISD::FP_EXTEND, MVT::v4f32, MVT::v4f16, 1}, 475 {ISD::FP_EXTEND, MVT::v8f32, MVT::v8f16, 3}, 476 }; 477 if (SrcTy.isVector() && ST->hasMVEFloatOps()) { 478 if (const auto *Entry = 479 ConvertCostTableLookup(MVEFLoadConversionTbl, ISD, 480 DstTy.getSimpleVT(), SrcTy.getSimpleVT())) 481 return AdjustCost(Entry->Cost * ST->getMVEVectorCostFactor()); 482 } 483 484 // The truncate of a store is free. This is the mirror of extends above. 485 static const TypeConversionCostTblEntry MVEStoreConversionTbl[] = { 486 {ISD::TRUNCATE, MVT::v4i32, MVT::v4i16, 0}, 487 {ISD::TRUNCATE, MVT::v4i32, MVT::v4i8, 0}, 488 {ISD::TRUNCATE, MVT::v8i16, MVT::v8i8, 0}, 489 {ISD::TRUNCATE, MVT::v8i32, MVT::v8i16, 1}, 490 {ISD::TRUNCATE, MVT::v16i32, MVT::v16i8, 3}, 491 {ISD::TRUNCATE, MVT::v16i16, MVT::v16i8, 1}, 492 }; 493 if (SrcTy.isVector() && ST->hasMVEIntegerOps()) { 494 if (const auto *Entry = 495 ConvertCostTableLookup(MVEStoreConversionTbl, ISD, 496 SrcTy.getSimpleVT(), DstTy.getSimpleVT())) 497 return AdjustCost(Entry->Cost * ST->getMVEVectorCostFactor()); 498 } 499 500 static const TypeConversionCostTblEntry MVEFStoreConversionTbl[] = { 501 {ISD::FP_ROUND, MVT::v4f32, MVT::v4f16, 1}, 502 {ISD::FP_ROUND, MVT::v8f32, MVT::v8f16, 3}, 503 }; 504 if (SrcTy.isVector() && ST->hasMVEFloatOps()) { 505 if (const auto *Entry = 506 ConvertCostTableLookup(MVEFStoreConversionTbl, ISD, 507 SrcTy.getSimpleVT(), DstTy.getSimpleVT())) 508 return AdjustCost(Entry->Cost * ST->getMVEVectorCostFactor()); 509 } 510 } 511 512 // NEON vector operations that can extend their inputs. 513 if ((ISD == ISD::SIGN_EXTEND || ISD == ISD::ZERO_EXTEND) && 514 I && I->hasOneUse() && ST->hasNEON() && SrcTy.isVector()) { 515 static const TypeConversionCostTblEntry NEONDoubleWidthTbl[] = { 516 // vaddl 517 { ISD::ADD, MVT::v4i32, MVT::v4i16, 0 }, 518 { ISD::ADD, MVT::v8i16, MVT::v8i8, 0 }, 519 // vsubl 520 { ISD::SUB, MVT::v4i32, MVT::v4i16, 0 }, 521 { ISD::SUB, MVT::v8i16, MVT::v8i8, 0 }, 522 // vmull 523 { ISD::MUL, MVT::v4i32, MVT::v4i16, 0 }, 524 { ISD::MUL, MVT::v8i16, MVT::v8i8, 0 }, 525 // vshll 526 { ISD::SHL, MVT::v4i32, MVT::v4i16, 0 }, 527 { ISD::SHL, MVT::v8i16, MVT::v8i8, 0 }, 528 }; 529 530 auto *User = cast<Instruction>(*I->user_begin()); 531 int UserISD = TLI->InstructionOpcodeToISD(User->getOpcode()); 532 if (auto *Entry = ConvertCostTableLookup(NEONDoubleWidthTbl, UserISD, 533 DstTy.getSimpleVT(), 534 SrcTy.getSimpleVT())) { 535 return AdjustCost(Entry->Cost); 536 } 537 } 538 539 // Single to/from double precision conversions. 540 if (Src->isVectorTy() && ST->hasNEON() && 541 ((ISD == ISD::FP_ROUND && SrcTy.getScalarType() == MVT::f64 && 542 DstTy.getScalarType() == MVT::f32) || 543 (ISD == ISD::FP_EXTEND && SrcTy.getScalarType() == MVT::f32 && 544 DstTy.getScalarType() == MVT::f64))) { 545 static const CostTblEntry NEONFltDblTbl[] = { 546 // Vector fptrunc/fpext conversions. 547 {ISD::FP_ROUND, MVT::v2f64, 2}, 548 {ISD::FP_EXTEND, MVT::v2f32, 2}, 549 {ISD::FP_EXTEND, MVT::v4f32, 4}}; 550 551 std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Src); 552 if (const auto *Entry = CostTableLookup(NEONFltDblTbl, ISD, LT.second)) 553 return AdjustCost(LT.first * Entry->Cost); 554 } 555 556 // Some arithmetic, load and store operations have specific instructions 557 // to cast up/down their types automatically at no extra cost. 558 // TODO: Get these tables to know at least what the related operations are. 559 static const TypeConversionCostTblEntry NEONVectorConversionTbl[] = { 560 { ISD::SIGN_EXTEND, MVT::v4i32, MVT::v4i16, 1 }, 561 { ISD::ZERO_EXTEND, MVT::v4i32, MVT::v4i16, 1 }, 562 { ISD::SIGN_EXTEND, MVT::v2i64, MVT::v2i32, 1 }, 563 { ISD::ZERO_EXTEND, MVT::v2i64, MVT::v2i32, 1 }, 564 { ISD::TRUNCATE, MVT::v4i32, MVT::v4i64, 0 }, 565 { ISD::TRUNCATE, MVT::v4i16, MVT::v4i32, 1 }, 566 567 // The number of vmovl instructions for the extension. 568 { ISD::SIGN_EXTEND, MVT::v8i16, MVT::v8i8, 1 }, 569 { ISD::ZERO_EXTEND, MVT::v8i16, MVT::v8i8, 1 }, 570 { ISD::SIGN_EXTEND, MVT::v4i32, MVT::v4i8, 2 }, 571 { ISD::ZERO_EXTEND, MVT::v4i32, MVT::v4i8, 2 }, 572 { ISD::SIGN_EXTEND, MVT::v2i64, MVT::v2i8, 3 }, 573 { ISD::ZERO_EXTEND, MVT::v2i64, MVT::v2i8, 3 }, 574 { ISD::SIGN_EXTEND, MVT::v2i64, MVT::v2i16, 2 }, 575 { ISD::ZERO_EXTEND, MVT::v2i64, MVT::v2i16, 2 }, 576 { ISD::SIGN_EXTEND, MVT::v4i64, MVT::v4i16, 3 }, 577 { ISD::ZERO_EXTEND, MVT::v4i64, MVT::v4i16, 3 }, 578 { ISD::SIGN_EXTEND, MVT::v8i32, MVT::v8i8, 3 }, 579 { ISD::ZERO_EXTEND, MVT::v8i32, MVT::v8i8, 3 }, 580 { ISD::SIGN_EXTEND, MVT::v8i64, MVT::v8i8, 7 }, 581 { ISD::ZERO_EXTEND, MVT::v8i64, MVT::v8i8, 7 }, 582 { ISD::SIGN_EXTEND, MVT::v8i64, MVT::v8i16, 6 }, 583 { ISD::ZERO_EXTEND, MVT::v8i64, MVT::v8i16, 6 }, 584 { ISD::SIGN_EXTEND, MVT::v16i32, MVT::v16i8, 6 }, 585 { ISD::ZERO_EXTEND, MVT::v16i32, MVT::v16i8, 6 }, 586 587 // Operations that we legalize using splitting. 588 { ISD::TRUNCATE, MVT::v16i8, MVT::v16i32, 6 }, 589 { ISD::TRUNCATE, MVT::v8i8, MVT::v8i32, 3 }, 590 591 // Vector float <-> i32 conversions. 592 { ISD::SINT_TO_FP, MVT::v4f32, MVT::v4i32, 1 }, 593 { ISD::UINT_TO_FP, MVT::v4f32, MVT::v4i32, 1 }, 594 595 { ISD::SINT_TO_FP, MVT::v2f32, MVT::v2i8, 3 }, 596 { ISD::UINT_TO_FP, MVT::v2f32, MVT::v2i8, 3 }, 597 { ISD::SINT_TO_FP, MVT::v2f32, MVT::v2i16, 2 }, 598 { ISD::UINT_TO_FP, MVT::v2f32, MVT::v2i16, 2 }, 599 { ISD::SINT_TO_FP, MVT::v2f32, MVT::v2i32, 1 }, 600 { ISD::UINT_TO_FP, MVT::v2f32, MVT::v2i32, 1 }, 601 { ISD::SINT_TO_FP, MVT::v4f32, MVT::v4i1, 3 }, 602 { ISD::UINT_TO_FP, MVT::v4f32, MVT::v4i1, 3 }, 603 { ISD::SINT_TO_FP, MVT::v4f32, MVT::v4i8, 3 }, 604 { ISD::UINT_TO_FP, MVT::v4f32, MVT::v4i8, 3 }, 605 { ISD::SINT_TO_FP, MVT::v4f32, MVT::v4i16, 2 }, 606 { ISD::UINT_TO_FP, MVT::v4f32, MVT::v4i16, 2 }, 607 { ISD::SINT_TO_FP, MVT::v8f32, MVT::v8i16, 4 }, 608 { ISD::UINT_TO_FP, MVT::v8f32, MVT::v8i16, 4 }, 609 { ISD::SINT_TO_FP, MVT::v8f32, MVT::v8i32, 2 }, 610 { ISD::UINT_TO_FP, MVT::v8f32, MVT::v8i32, 2 }, 611 { ISD::SINT_TO_FP, MVT::v16f32, MVT::v16i16, 8 }, 612 { ISD::UINT_TO_FP, MVT::v16f32, MVT::v16i16, 8 }, 613 { ISD::SINT_TO_FP, MVT::v16f32, MVT::v16i32, 4 }, 614 { ISD::UINT_TO_FP, MVT::v16f32, MVT::v16i32, 4 }, 615 616 { ISD::FP_TO_SINT, MVT::v4i32, MVT::v4f32, 1 }, 617 { ISD::FP_TO_UINT, MVT::v4i32, MVT::v4f32, 1 }, 618 { ISD::FP_TO_SINT, MVT::v4i8, MVT::v4f32, 3 }, 619 { ISD::FP_TO_UINT, MVT::v4i8, MVT::v4f32, 3 }, 620 { ISD::FP_TO_SINT, MVT::v4i16, MVT::v4f32, 2 }, 621 { ISD::FP_TO_UINT, MVT::v4i16, MVT::v4f32, 2 }, 622 623 // Vector double <-> i32 conversions. 624 { ISD::SINT_TO_FP, MVT::v2f64, MVT::v2i32, 2 }, 625 { ISD::UINT_TO_FP, MVT::v2f64, MVT::v2i32, 2 }, 626 627 { ISD::SINT_TO_FP, MVT::v2f64, MVT::v2i8, 4 }, 628 { ISD::UINT_TO_FP, MVT::v2f64, MVT::v2i8, 4 }, 629 { ISD::SINT_TO_FP, MVT::v2f64, MVT::v2i16, 3 }, 630 { ISD::UINT_TO_FP, MVT::v2f64, MVT::v2i16, 3 }, 631 { ISD::SINT_TO_FP, MVT::v2f64, MVT::v2i32, 2 }, 632 { ISD::UINT_TO_FP, MVT::v2f64, MVT::v2i32, 2 }, 633 634 { ISD::FP_TO_SINT, MVT::v2i32, MVT::v2f64, 2 }, 635 { ISD::FP_TO_UINT, MVT::v2i32, MVT::v2f64, 2 }, 636 { ISD::FP_TO_SINT, MVT::v8i16, MVT::v8f32, 4 }, 637 { ISD::FP_TO_UINT, MVT::v8i16, MVT::v8f32, 4 }, 638 { ISD::FP_TO_SINT, MVT::v16i16, MVT::v16f32, 8 }, 639 { ISD::FP_TO_UINT, MVT::v16i16, MVT::v16f32, 8 } 640 }; 641 642 if (SrcTy.isVector() && ST->hasNEON()) { 643 if (const auto *Entry = ConvertCostTableLookup(NEONVectorConversionTbl, ISD, 644 DstTy.getSimpleVT(), 645 SrcTy.getSimpleVT())) 646 return AdjustCost(Entry->Cost); 647 } 648 649 // Scalar float to integer conversions. 650 static const TypeConversionCostTblEntry NEONFloatConversionTbl[] = { 651 { ISD::FP_TO_SINT, MVT::i1, MVT::f32, 2 }, 652 { ISD::FP_TO_UINT, MVT::i1, MVT::f32, 2 }, 653 { ISD::FP_TO_SINT, MVT::i1, MVT::f64, 2 }, 654 { ISD::FP_TO_UINT, MVT::i1, MVT::f64, 2 }, 655 { ISD::FP_TO_SINT, MVT::i8, MVT::f32, 2 }, 656 { ISD::FP_TO_UINT, MVT::i8, MVT::f32, 2 }, 657 { ISD::FP_TO_SINT, MVT::i8, MVT::f64, 2 }, 658 { ISD::FP_TO_UINT, MVT::i8, MVT::f64, 2 }, 659 { ISD::FP_TO_SINT, MVT::i16, MVT::f32, 2 }, 660 { ISD::FP_TO_UINT, MVT::i16, MVT::f32, 2 }, 661 { ISD::FP_TO_SINT, MVT::i16, MVT::f64, 2 }, 662 { ISD::FP_TO_UINT, MVT::i16, MVT::f64, 2 }, 663 { ISD::FP_TO_SINT, MVT::i32, MVT::f32, 2 }, 664 { ISD::FP_TO_UINT, MVT::i32, MVT::f32, 2 }, 665 { ISD::FP_TO_SINT, MVT::i32, MVT::f64, 2 }, 666 { ISD::FP_TO_UINT, MVT::i32, MVT::f64, 2 }, 667 { ISD::FP_TO_SINT, MVT::i64, MVT::f32, 10 }, 668 { ISD::FP_TO_UINT, MVT::i64, MVT::f32, 10 }, 669 { ISD::FP_TO_SINT, MVT::i64, MVT::f64, 10 }, 670 { ISD::FP_TO_UINT, MVT::i64, MVT::f64, 10 } 671 }; 672 if (SrcTy.isFloatingPoint() && ST->hasNEON()) { 673 if (const auto *Entry = ConvertCostTableLookup(NEONFloatConversionTbl, ISD, 674 DstTy.getSimpleVT(), 675 SrcTy.getSimpleVT())) 676 return AdjustCost(Entry->Cost); 677 } 678 679 // Scalar integer to float conversions. 680 static const TypeConversionCostTblEntry NEONIntegerConversionTbl[] = { 681 { ISD::SINT_TO_FP, MVT::f32, MVT::i1, 2 }, 682 { ISD::UINT_TO_FP, MVT::f32, MVT::i1, 2 }, 683 { ISD::SINT_TO_FP, MVT::f64, MVT::i1, 2 }, 684 { ISD::UINT_TO_FP, MVT::f64, MVT::i1, 2 }, 685 { ISD::SINT_TO_FP, MVT::f32, MVT::i8, 2 }, 686 { ISD::UINT_TO_FP, MVT::f32, MVT::i8, 2 }, 687 { ISD::SINT_TO_FP, MVT::f64, MVT::i8, 2 }, 688 { ISD::UINT_TO_FP, MVT::f64, MVT::i8, 2 }, 689 { ISD::SINT_TO_FP, MVT::f32, MVT::i16, 2 }, 690 { ISD::UINT_TO_FP, MVT::f32, MVT::i16, 2 }, 691 { ISD::SINT_TO_FP, MVT::f64, MVT::i16, 2 }, 692 { ISD::UINT_TO_FP, MVT::f64, MVT::i16, 2 }, 693 { ISD::SINT_TO_FP, MVT::f32, MVT::i32, 2 }, 694 { ISD::UINT_TO_FP, MVT::f32, MVT::i32, 2 }, 695 { ISD::SINT_TO_FP, MVT::f64, MVT::i32, 2 }, 696 { ISD::UINT_TO_FP, MVT::f64, MVT::i32, 2 }, 697 { ISD::SINT_TO_FP, MVT::f32, MVT::i64, 10 }, 698 { ISD::UINT_TO_FP, MVT::f32, MVT::i64, 10 }, 699 { ISD::SINT_TO_FP, MVT::f64, MVT::i64, 10 }, 700 { ISD::UINT_TO_FP, MVT::f64, MVT::i64, 10 } 701 }; 702 703 if (SrcTy.isInteger() && ST->hasNEON()) { 704 if (const auto *Entry = ConvertCostTableLookup(NEONIntegerConversionTbl, 705 ISD, DstTy.getSimpleVT(), 706 SrcTy.getSimpleVT())) 707 return AdjustCost(Entry->Cost); 708 } 709 710 // MVE extend costs, taken from codegen tests. i8->i16 or i16->i32 is one 711 // instruction, i8->i32 is two. i64 zexts are an VAND with a constant, sext 712 // are linearised so take more. 713 static const TypeConversionCostTblEntry MVEVectorConversionTbl[] = { 714 { ISD::SIGN_EXTEND, MVT::v8i16, MVT::v8i8, 1 }, 715 { ISD::ZERO_EXTEND, MVT::v8i16, MVT::v8i8, 1 }, 716 { ISD::SIGN_EXTEND, MVT::v4i32, MVT::v4i8, 2 }, 717 { ISD::ZERO_EXTEND, MVT::v4i32, MVT::v4i8, 2 }, 718 { ISD::SIGN_EXTEND, MVT::v2i64, MVT::v2i8, 10 }, 719 { ISD::ZERO_EXTEND, MVT::v2i64, MVT::v2i8, 2 }, 720 { ISD::SIGN_EXTEND, MVT::v4i32, MVT::v4i16, 1 }, 721 { ISD::ZERO_EXTEND, MVT::v4i32, MVT::v4i16, 1 }, 722 { ISD::SIGN_EXTEND, MVT::v2i64, MVT::v2i16, 10 }, 723 { ISD::ZERO_EXTEND, MVT::v2i64, MVT::v2i16, 2 }, 724 { ISD::SIGN_EXTEND, MVT::v2i64, MVT::v2i32, 8 }, 725 { ISD::ZERO_EXTEND, MVT::v2i64, MVT::v2i32, 2 }, 726 }; 727 728 if (SrcTy.isVector() && ST->hasMVEIntegerOps()) { 729 if (const auto *Entry = ConvertCostTableLookup(MVEVectorConversionTbl, 730 ISD, DstTy.getSimpleVT(), 731 SrcTy.getSimpleVT())) 732 return AdjustCost(Entry->Cost * ST->getMVEVectorCostFactor()); 733 } 734 735 if (ISD == ISD::FP_ROUND || ISD == ISD::FP_EXTEND) { 736 // As general rule, fp converts that were not matched above are scalarized 737 // and cost 1 vcvt for each lane, so long as the instruction is available. 738 // If not it will become a series of function calls. 739 const int CallCost = getCallInstrCost(nullptr, Dst, {Src}, CostKind); 740 int Lanes = 1; 741 if (SrcTy.isFixedLengthVector()) 742 Lanes = SrcTy.getVectorNumElements(); 743 744 if (IsLegalFPType(SrcTy) && IsLegalFPType(DstTy)) 745 return Lanes; 746 else 747 return Lanes * CallCost; 748 } 749 750 // Scalar integer conversion costs. 751 static const TypeConversionCostTblEntry ARMIntegerConversionTbl[] = { 752 // i16 -> i64 requires two dependent operations. 753 { ISD::SIGN_EXTEND, MVT::i64, MVT::i16, 2 }, 754 755 // Truncates on i64 are assumed to be free. 756 { ISD::TRUNCATE, MVT::i32, MVT::i64, 0 }, 757 { ISD::TRUNCATE, MVT::i16, MVT::i64, 0 }, 758 { ISD::TRUNCATE, MVT::i8, MVT::i64, 0 }, 759 { ISD::TRUNCATE, MVT::i1, MVT::i64, 0 } 760 }; 761 762 if (SrcTy.isInteger()) { 763 if (const auto *Entry = ConvertCostTableLookup(ARMIntegerConversionTbl, ISD, 764 DstTy.getSimpleVT(), 765 SrcTy.getSimpleVT())) 766 return AdjustCost(Entry->Cost); 767 } 768 769 int BaseCost = ST->hasMVEIntegerOps() && Src->isVectorTy() 770 ? ST->getMVEVectorCostFactor() 771 : 1; 772 return AdjustCost( 773 BaseCost * BaseT::getCastInstrCost(Opcode, Dst, Src, CCH, CostKind, I)); 774 } 775 776 int ARMTTIImpl::getVectorInstrCost(unsigned Opcode, Type *ValTy, 777 unsigned Index) { 778 // Penalize inserting into an D-subregister. We end up with a three times 779 // lower estimated throughput on swift. 780 if (ST->hasSlowLoadDSubregister() && Opcode == Instruction::InsertElement && 781 ValTy->isVectorTy() && ValTy->getScalarSizeInBits() <= 32) 782 return 3; 783 784 if (ST->hasNEON() && (Opcode == Instruction::InsertElement || 785 Opcode == Instruction::ExtractElement)) { 786 // Cross-class copies are expensive on many microarchitectures, 787 // so assume they are expensive by default. 788 if (cast<VectorType>(ValTy)->getElementType()->isIntegerTy()) 789 return 3; 790 791 // Even if it's not a cross class copy, this likely leads to mixing 792 // of NEON and VFP code and should be therefore penalized. 793 if (ValTy->isVectorTy() && 794 ValTy->getScalarSizeInBits() <= 32) 795 return std::max(BaseT::getVectorInstrCost(Opcode, ValTy, Index), 2U); 796 } 797 798 if (ST->hasMVEIntegerOps() && (Opcode == Instruction::InsertElement || 799 Opcode == Instruction::ExtractElement)) { 800 // We say MVE moves costs at least the MVEVectorCostFactor, even though 801 // they are scalar instructions. This helps prevent mixing scalar and 802 // vector, to prevent vectorising where we end up just scalarising the 803 // result anyway. 804 return std::max(BaseT::getVectorInstrCost(Opcode, ValTy, Index), 805 ST->getMVEVectorCostFactor()) * 806 cast<FixedVectorType>(ValTy)->getNumElements() / 2; 807 } 808 809 return BaseT::getVectorInstrCost(Opcode, ValTy, Index); 810 } 811 812 int ARMTTIImpl::getCmpSelInstrCost(unsigned Opcode, Type *ValTy, Type *CondTy, 813 CmpInst::Predicate VecPred, 814 TTI::TargetCostKind CostKind, 815 const Instruction *I) { 816 int ISD = TLI->InstructionOpcodeToISD(Opcode); 817 818 // Thumb scalar code size cost for select. 819 if (CostKind == TTI::TCK_CodeSize && ISD == ISD::SELECT && 820 ST->isThumb() && !ValTy->isVectorTy()) { 821 // Assume expensive structs. 822 if (TLI->getValueType(DL, ValTy, true) == MVT::Other) 823 return TTI::TCC_Expensive; 824 825 // Select costs can vary because they: 826 // - may require one or more conditional mov (including an IT), 827 // - can't operate directly on immediates, 828 // - require live flags, which we can't copy around easily. 829 int Cost = TLI->getTypeLegalizationCost(DL, ValTy).first; 830 831 // Possible IT instruction for Thumb2, or more for Thumb1. 832 ++Cost; 833 834 // i1 values may need rematerialising by using mov immediates and/or 835 // flag setting instructions. 836 if (ValTy->isIntegerTy(1)) 837 ++Cost; 838 839 return Cost; 840 } 841 842 // On NEON a vector select gets lowered to vbsl. 843 if (ST->hasNEON() && ValTy->isVectorTy() && ISD == ISD::SELECT && CondTy) { 844 // Lowering of some vector selects is currently far from perfect. 845 static const TypeConversionCostTblEntry NEONVectorSelectTbl[] = { 846 { ISD::SELECT, MVT::v4i1, MVT::v4i64, 4*4 + 1*2 + 1 }, 847 { ISD::SELECT, MVT::v8i1, MVT::v8i64, 50 }, 848 { ISD::SELECT, MVT::v16i1, MVT::v16i64, 100 } 849 }; 850 851 EVT SelCondTy = TLI->getValueType(DL, CondTy); 852 EVT SelValTy = TLI->getValueType(DL, ValTy); 853 if (SelCondTy.isSimple() && SelValTy.isSimple()) { 854 if (const auto *Entry = ConvertCostTableLookup(NEONVectorSelectTbl, ISD, 855 SelCondTy.getSimpleVT(), 856 SelValTy.getSimpleVT())) 857 return Entry->Cost; 858 } 859 860 std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, ValTy); 861 return LT.first; 862 } 863 864 // Default to cheap (throughput/size of 1 instruction) but adjust throughput 865 // for "multiple beats" potentially needed by MVE instructions. 866 int BaseCost = 1; 867 if (CostKind != TTI::TCK_CodeSize && ST->hasMVEIntegerOps() && 868 ValTy->isVectorTy()) 869 BaseCost = ST->getMVEVectorCostFactor(); 870 871 return BaseCost * 872 BaseT::getCmpSelInstrCost(Opcode, ValTy, CondTy, VecPred, CostKind, I); 873 } 874 875 int ARMTTIImpl::getAddressComputationCost(Type *Ty, ScalarEvolution *SE, 876 const SCEV *Ptr) { 877 // Address computations in vectorized code with non-consecutive addresses will 878 // likely result in more instructions compared to scalar code where the 879 // computation can more often be merged into the index mode. The resulting 880 // extra micro-ops can significantly decrease throughput. 881 unsigned NumVectorInstToHideOverhead = 10; 882 int MaxMergeDistance = 64; 883 884 if (ST->hasNEON()) { 885 if (Ty->isVectorTy() && SE && 886 !BaseT::isConstantStridedAccessLessThan(SE, Ptr, MaxMergeDistance + 1)) 887 return NumVectorInstToHideOverhead; 888 889 // In many cases the address computation is not merged into the instruction 890 // addressing mode. 891 return 1; 892 } 893 return BaseT::getAddressComputationCost(Ty, SE, Ptr); 894 } 895 896 bool ARMTTIImpl::isProfitableLSRChainElement(Instruction *I) { 897 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) { 898 // If a VCTP is part of a chain, it's already profitable and shouldn't be 899 // optimized, else LSR may block tail-predication. 900 switch (II->getIntrinsicID()) { 901 case Intrinsic::arm_mve_vctp8: 902 case Intrinsic::arm_mve_vctp16: 903 case Intrinsic::arm_mve_vctp32: 904 case Intrinsic::arm_mve_vctp64: 905 return true; 906 default: 907 break; 908 } 909 } 910 return false; 911 } 912 913 bool ARMTTIImpl::isLegalMaskedLoad(Type *DataTy, Align Alignment) { 914 if (!EnableMaskedLoadStores || !ST->hasMVEIntegerOps()) 915 return false; 916 917 if (auto *VecTy = dyn_cast<FixedVectorType>(DataTy)) { 918 // Don't support v2i1 yet. 919 if (VecTy->getNumElements() == 2) 920 return false; 921 922 // We don't support extending fp types. 923 unsigned VecWidth = DataTy->getPrimitiveSizeInBits(); 924 if (VecWidth != 128 && VecTy->getElementType()->isFloatingPointTy()) 925 return false; 926 } 927 928 unsigned EltWidth = DataTy->getScalarSizeInBits(); 929 return (EltWidth == 32 && Alignment >= 4) || 930 (EltWidth == 16 && Alignment >= 2) || (EltWidth == 8); 931 } 932 933 bool ARMTTIImpl::isLegalMaskedGather(Type *Ty, Align Alignment) { 934 if (!EnableMaskedGatherScatters || !ST->hasMVEIntegerOps()) 935 return false; 936 937 // This method is called in 2 places: 938 // - from the vectorizer with a scalar type, in which case we need to get 939 // this as good as we can with the limited info we have (and rely on the cost 940 // model for the rest). 941 // - from the masked intrinsic lowering pass with the actual vector type. 942 // For MVE, we have a custom lowering pass that will already have custom 943 // legalised any gathers that we can to MVE intrinsics, and want to expand all 944 // the rest. The pass runs before the masked intrinsic lowering pass, so if we 945 // are here, we know we want to expand. 946 if (isa<VectorType>(Ty)) 947 return false; 948 949 unsigned EltWidth = Ty->getScalarSizeInBits(); 950 return ((EltWidth == 32 && Alignment >= 4) || 951 (EltWidth == 16 && Alignment >= 2) || EltWidth == 8); 952 } 953 954 /// Given a memcpy/memset/memmove instruction, return the number of memory 955 /// operations performed, via querying findOptimalMemOpLowering. Returns -1 if a 956 /// call is used. 957 int ARMTTIImpl::getNumMemOps(const IntrinsicInst *I) const { 958 MemOp MOp; 959 unsigned DstAddrSpace = ~0u; 960 unsigned SrcAddrSpace = ~0u; 961 const Function *F = I->getParent()->getParent(); 962 963 if (const auto *MC = dyn_cast<MemTransferInst>(I)) { 964 ConstantInt *C = dyn_cast<ConstantInt>(MC->getLength()); 965 // If 'size' is not a constant, a library call will be generated. 966 if (!C) 967 return -1; 968 969 const unsigned Size = C->getValue().getZExtValue(); 970 const Align DstAlign = *MC->getDestAlign(); 971 const Align SrcAlign = *MC->getSourceAlign(); 972 973 MOp = MemOp::Copy(Size, /*DstAlignCanChange*/ false, DstAlign, SrcAlign, 974 /*IsVolatile*/ false); 975 DstAddrSpace = MC->getDestAddressSpace(); 976 SrcAddrSpace = MC->getSourceAddressSpace(); 977 } 978 else if (const auto *MS = dyn_cast<MemSetInst>(I)) { 979 ConstantInt *C = dyn_cast<ConstantInt>(MS->getLength()); 980 // If 'size' is not a constant, a library call will be generated. 981 if (!C) 982 return -1; 983 984 const unsigned Size = C->getValue().getZExtValue(); 985 const Align DstAlign = *MS->getDestAlign(); 986 987 MOp = MemOp::Set(Size, /*DstAlignCanChange*/ false, DstAlign, 988 /*IsZeroMemset*/ false, /*IsVolatile*/ false); 989 DstAddrSpace = MS->getDestAddressSpace(); 990 } 991 else 992 llvm_unreachable("Expected a memcpy/move or memset!"); 993 994 unsigned Limit, Factor = 2; 995 switch(I->getIntrinsicID()) { 996 case Intrinsic::memcpy: 997 Limit = TLI->getMaxStoresPerMemcpy(F->hasMinSize()); 998 break; 999 case Intrinsic::memmove: 1000 Limit = TLI->getMaxStoresPerMemmove(F->hasMinSize()); 1001 break; 1002 case Intrinsic::memset: 1003 Limit = TLI->getMaxStoresPerMemset(F->hasMinSize()); 1004 Factor = 1; 1005 break; 1006 default: 1007 llvm_unreachable("Expected a memcpy/move or memset!"); 1008 } 1009 1010 // MemOps will be poplulated with a list of data types that needs to be 1011 // loaded and stored. That's why we multiply the number of elements by 2 to 1012 // get the cost for this memcpy. 1013 std::vector<EVT> MemOps; 1014 if (getTLI()->findOptimalMemOpLowering( 1015 MemOps, Limit, MOp, DstAddrSpace, 1016 SrcAddrSpace, F->getAttributes())) 1017 return MemOps.size() * Factor; 1018 1019 // If we can't find an optimal memop lowering, return the default cost 1020 return -1; 1021 } 1022 1023 int ARMTTIImpl::getMemcpyCost(const Instruction *I) { 1024 int NumOps = getNumMemOps(cast<IntrinsicInst>(I)); 1025 1026 // To model the cost of a library call, we assume 1 for the call, and 1027 // 3 for the argument setup. 1028 if (NumOps == -1) 1029 return 4; 1030 return NumOps; 1031 } 1032 1033 int ARMTTIImpl::getShuffleCost(TTI::ShuffleKind Kind, VectorType *Tp, 1034 int Index, VectorType *SubTp) { 1035 if (ST->hasNEON()) { 1036 if (Kind == TTI::SK_Broadcast) { 1037 static const CostTblEntry NEONDupTbl[] = { 1038 // VDUP handles these cases. 1039 {ISD::VECTOR_SHUFFLE, MVT::v2i32, 1}, 1040 {ISD::VECTOR_SHUFFLE, MVT::v2f32, 1}, 1041 {ISD::VECTOR_SHUFFLE, MVT::v2i64, 1}, 1042 {ISD::VECTOR_SHUFFLE, MVT::v2f64, 1}, 1043 {ISD::VECTOR_SHUFFLE, MVT::v4i16, 1}, 1044 {ISD::VECTOR_SHUFFLE, MVT::v8i8, 1}, 1045 1046 {ISD::VECTOR_SHUFFLE, MVT::v4i32, 1}, 1047 {ISD::VECTOR_SHUFFLE, MVT::v4f32, 1}, 1048 {ISD::VECTOR_SHUFFLE, MVT::v8i16, 1}, 1049 {ISD::VECTOR_SHUFFLE, MVT::v16i8, 1}}; 1050 1051 std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Tp); 1052 1053 if (const auto *Entry = 1054 CostTableLookup(NEONDupTbl, ISD::VECTOR_SHUFFLE, LT.second)) 1055 return LT.first * Entry->Cost; 1056 } 1057 if (Kind == TTI::SK_Reverse) { 1058 static const CostTblEntry NEONShuffleTbl[] = { 1059 // Reverse shuffle cost one instruction if we are shuffling within a 1060 // double word (vrev) or two if we shuffle a quad word (vrev, vext). 1061 {ISD::VECTOR_SHUFFLE, MVT::v2i32, 1}, 1062 {ISD::VECTOR_SHUFFLE, MVT::v2f32, 1}, 1063 {ISD::VECTOR_SHUFFLE, MVT::v2i64, 1}, 1064 {ISD::VECTOR_SHUFFLE, MVT::v2f64, 1}, 1065 {ISD::VECTOR_SHUFFLE, MVT::v4i16, 1}, 1066 {ISD::VECTOR_SHUFFLE, MVT::v8i8, 1}, 1067 1068 {ISD::VECTOR_SHUFFLE, MVT::v4i32, 2}, 1069 {ISD::VECTOR_SHUFFLE, MVT::v4f32, 2}, 1070 {ISD::VECTOR_SHUFFLE, MVT::v8i16, 2}, 1071 {ISD::VECTOR_SHUFFLE, MVT::v16i8, 2}}; 1072 1073 std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Tp); 1074 1075 if (const auto *Entry = 1076 CostTableLookup(NEONShuffleTbl, ISD::VECTOR_SHUFFLE, LT.second)) 1077 return LT.first * Entry->Cost; 1078 } 1079 if (Kind == TTI::SK_Select) { 1080 static const CostTblEntry NEONSelShuffleTbl[] = { 1081 // Select shuffle cost table for ARM. Cost is the number of 1082 // instructions 1083 // required to create the shuffled vector. 1084 1085 {ISD::VECTOR_SHUFFLE, MVT::v2f32, 1}, 1086 {ISD::VECTOR_SHUFFLE, MVT::v2i64, 1}, 1087 {ISD::VECTOR_SHUFFLE, MVT::v2f64, 1}, 1088 {ISD::VECTOR_SHUFFLE, MVT::v2i32, 1}, 1089 1090 {ISD::VECTOR_SHUFFLE, MVT::v4i32, 2}, 1091 {ISD::VECTOR_SHUFFLE, MVT::v4f32, 2}, 1092 {ISD::VECTOR_SHUFFLE, MVT::v4i16, 2}, 1093 1094 {ISD::VECTOR_SHUFFLE, MVT::v8i16, 16}, 1095 1096 {ISD::VECTOR_SHUFFLE, MVT::v16i8, 32}}; 1097 1098 std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Tp); 1099 if (const auto *Entry = CostTableLookup(NEONSelShuffleTbl, 1100 ISD::VECTOR_SHUFFLE, LT.second)) 1101 return LT.first * Entry->Cost; 1102 } 1103 } 1104 if (ST->hasMVEIntegerOps()) { 1105 if (Kind == TTI::SK_Broadcast) { 1106 static const CostTblEntry MVEDupTbl[] = { 1107 // VDUP handles these cases. 1108 {ISD::VECTOR_SHUFFLE, MVT::v4i32, 1}, 1109 {ISD::VECTOR_SHUFFLE, MVT::v8i16, 1}, 1110 {ISD::VECTOR_SHUFFLE, MVT::v16i8, 1}, 1111 {ISD::VECTOR_SHUFFLE, MVT::v4f32, 1}, 1112 {ISD::VECTOR_SHUFFLE, MVT::v8f16, 1}}; 1113 1114 std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Tp); 1115 1116 if (const auto *Entry = CostTableLookup(MVEDupTbl, ISD::VECTOR_SHUFFLE, 1117 LT.second)) 1118 return LT.first * Entry->Cost * ST->getMVEVectorCostFactor(); 1119 } 1120 } 1121 int BaseCost = ST->hasMVEIntegerOps() && Tp->isVectorTy() 1122 ? ST->getMVEVectorCostFactor() 1123 : 1; 1124 return BaseCost * BaseT::getShuffleCost(Kind, Tp, Index, SubTp); 1125 } 1126 1127 int ARMTTIImpl::getArithmeticInstrCost(unsigned Opcode, Type *Ty, 1128 TTI::TargetCostKind CostKind, 1129 TTI::OperandValueKind Op1Info, 1130 TTI::OperandValueKind Op2Info, 1131 TTI::OperandValueProperties Opd1PropInfo, 1132 TTI::OperandValueProperties Opd2PropInfo, 1133 ArrayRef<const Value *> Args, 1134 const Instruction *CxtI) { 1135 int ISDOpcode = TLI->InstructionOpcodeToISD(Opcode); 1136 if (ST->isThumb() && CostKind == TTI::TCK_CodeSize && Ty->isIntegerTy(1)) { 1137 // Make operations on i1 relatively expensive as this often involves 1138 // combining predicates. AND and XOR should be easier to handle with IT 1139 // blocks. 1140 switch (ISDOpcode) { 1141 default: 1142 break; 1143 case ISD::AND: 1144 case ISD::XOR: 1145 return 2; 1146 case ISD::OR: 1147 return 3; 1148 } 1149 } 1150 1151 std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Ty); 1152 1153 if (ST->hasNEON()) { 1154 const unsigned FunctionCallDivCost = 20; 1155 const unsigned ReciprocalDivCost = 10; 1156 static const CostTblEntry CostTbl[] = { 1157 // Division. 1158 // These costs are somewhat random. Choose a cost of 20 to indicate that 1159 // vectorizing devision (added function call) is going to be very expensive. 1160 // Double registers types. 1161 { ISD::SDIV, MVT::v1i64, 1 * FunctionCallDivCost}, 1162 { ISD::UDIV, MVT::v1i64, 1 * FunctionCallDivCost}, 1163 { ISD::SREM, MVT::v1i64, 1 * FunctionCallDivCost}, 1164 { ISD::UREM, MVT::v1i64, 1 * FunctionCallDivCost}, 1165 { ISD::SDIV, MVT::v2i32, 2 * FunctionCallDivCost}, 1166 { ISD::UDIV, MVT::v2i32, 2 * FunctionCallDivCost}, 1167 { ISD::SREM, MVT::v2i32, 2 * FunctionCallDivCost}, 1168 { ISD::UREM, MVT::v2i32, 2 * FunctionCallDivCost}, 1169 { ISD::SDIV, MVT::v4i16, ReciprocalDivCost}, 1170 { ISD::UDIV, MVT::v4i16, ReciprocalDivCost}, 1171 { ISD::SREM, MVT::v4i16, 4 * FunctionCallDivCost}, 1172 { ISD::UREM, MVT::v4i16, 4 * FunctionCallDivCost}, 1173 { ISD::SDIV, MVT::v8i8, ReciprocalDivCost}, 1174 { ISD::UDIV, MVT::v8i8, ReciprocalDivCost}, 1175 { ISD::SREM, MVT::v8i8, 8 * FunctionCallDivCost}, 1176 { ISD::UREM, MVT::v8i8, 8 * FunctionCallDivCost}, 1177 // Quad register types. 1178 { ISD::SDIV, MVT::v2i64, 2 * FunctionCallDivCost}, 1179 { ISD::UDIV, MVT::v2i64, 2 * FunctionCallDivCost}, 1180 { ISD::SREM, MVT::v2i64, 2 * FunctionCallDivCost}, 1181 { ISD::UREM, MVT::v2i64, 2 * FunctionCallDivCost}, 1182 { ISD::SDIV, MVT::v4i32, 4 * FunctionCallDivCost}, 1183 { ISD::UDIV, MVT::v4i32, 4 * FunctionCallDivCost}, 1184 { ISD::SREM, MVT::v4i32, 4 * FunctionCallDivCost}, 1185 { ISD::UREM, MVT::v4i32, 4 * FunctionCallDivCost}, 1186 { ISD::SDIV, MVT::v8i16, 8 * FunctionCallDivCost}, 1187 { ISD::UDIV, MVT::v8i16, 8 * FunctionCallDivCost}, 1188 { ISD::SREM, MVT::v8i16, 8 * FunctionCallDivCost}, 1189 { ISD::UREM, MVT::v8i16, 8 * FunctionCallDivCost}, 1190 { ISD::SDIV, MVT::v16i8, 16 * FunctionCallDivCost}, 1191 { ISD::UDIV, MVT::v16i8, 16 * FunctionCallDivCost}, 1192 { ISD::SREM, MVT::v16i8, 16 * FunctionCallDivCost}, 1193 { ISD::UREM, MVT::v16i8, 16 * FunctionCallDivCost}, 1194 // Multiplication. 1195 }; 1196 1197 if (const auto *Entry = CostTableLookup(CostTbl, ISDOpcode, LT.second)) 1198 return LT.first * Entry->Cost; 1199 1200 int Cost = BaseT::getArithmeticInstrCost(Opcode, Ty, CostKind, Op1Info, 1201 Op2Info, 1202 Opd1PropInfo, Opd2PropInfo); 1203 1204 // This is somewhat of a hack. The problem that we are facing is that SROA 1205 // creates a sequence of shift, and, or instructions to construct values. 1206 // These sequences are recognized by the ISel and have zero-cost. Not so for 1207 // the vectorized code. Because we have support for v2i64 but not i64 those 1208 // sequences look particularly beneficial to vectorize. 1209 // To work around this we increase the cost of v2i64 operations to make them 1210 // seem less beneficial. 1211 if (LT.second == MVT::v2i64 && 1212 Op2Info == TargetTransformInfo::OK_UniformConstantValue) 1213 Cost += 4; 1214 1215 return Cost; 1216 } 1217 1218 // If this operation is a shift on arm/thumb2, it might well be folded into 1219 // the following instruction, hence having a cost of 0. 1220 auto LooksLikeAFreeShift = [&]() { 1221 if (ST->isThumb1Only() || Ty->isVectorTy()) 1222 return false; 1223 1224 if (!CxtI || !CxtI->hasOneUse() || !CxtI->isShift()) 1225 return false; 1226 if (Op2Info != TargetTransformInfo::OK_UniformConstantValue) 1227 return false; 1228 1229 // Folded into a ADC/ADD/AND/BIC/CMP/EOR/MVN/ORR/ORN/RSB/SBC/SUB 1230 switch (cast<Instruction>(CxtI->user_back())->getOpcode()) { 1231 case Instruction::Add: 1232 case Instruction::Sub: 1233 case Instruction::And: 1234 case Instruction::Xor: 1235 case Instruction::Or: 1236 case Instruction::ICmp: 1237 return true; 1238 default: 1239 return false; 1240 } 1241 }; 1242 if (LooksLikeAFreeShift()) 1243 return 0; 1244 1245 // Default to cheap (throughput/size of 1 instruction) but adjust throughput 1246 // for "multiple beats" potentially needed by MVE instructions. 1247 int BaseCost = 1; 1248 if (CostKind != TTI::TCK_CodeSize && ST->hasMVEIntegerOps() && 1249 Ty->isVectorTy()) 1250 BaseCost = ST->getMVEVectorCostFactor(); 1251 1252 // The rest of this mostly follows what is done in BaseT::getArithmeticInstrCost, 1253 // without treating floats as more expensive that scalars or increasing the 1254 // costs for custom operations. The results is also multiplied by the 1255 // MVEVectorCostFactor where appropriate. 1256 if (TLI->isOperationLegalOrCustomOrPromote(ISDOpcode, LT.second)) 1257 return LT.first * BaseCost; 1258 1259 // Else this is expand, assume that we need to scalarize this op. 1260 if (auto *VTy = dyn_cast<FixedVectorType>(Ty)) { 1261 unsigned Num = VTy->getNumElements(); 1262 unsigned Cost = getArithmeticInstrCost(Opcode, Ty->getScalarType(), 1263 CostKind); 1264 // Return the cost of multiple scalar invocation plus the cost of 1265 // inserting and extracting the values. 1266 return BaseT::getScalarizationOverhead(VTy, Args) + Num * Cost; 1267 } 1268 1269 return BaseCost; 1270 } 1271 1272 int ARMTTIImpl::getMemoryOpCost(unsigned Opcode, Type *Src, 1273 MaybeAlign Alignment, unsigned AddressSpace, 1274 TTI::TargetCostKind CostKind, 1275 const Instruction *I) { 1276 // TODO: Handle other cost kinds. 1277 if (CostKind != TTI::TCK_RecipThroughput) 1278 return 1; 1279 1280 // Type legalization can't handle structs 1281 if (TLI->getValueType(DL, Src, true) == MVT::Other) 1282 return BaseT::getMemoryOpCost(Opcode, Src, Alignment, AddressSpace, 1283 CostKind); 1284 1285 if (ST->hasNEON() && Src->isVectorTy() && 1286 (Alignment && *Alignment != Align(16)) && 1287 cast<VectorType>(Src)->getElementType()->isDoubleTy()) { 1288 // Unaligned loads/stores are extremely inefficient. 1289 // We need 4 uops for vst.1/vld.1 vs 1uop for vldr/vstr. 1290 std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Src); 1291 return LT.first * 4; 1292 } 1293 1294 // MVE can optimize a fpext(load(4xhalf)) using an extending integer load. 1295 // Same for stores. 1296 if (ST->hasMVEFloatOps() && isa<FixedVectorType>(Src) && I && 1297 ((Opcode == Instruction::Load && I->hasOneUse() && 1298 isa<FPExtInst>(*I->user_begin())) || 1299 (Opcode == Instruction::Store && isa<FPTruncInst>(I->getOperand(0))))) { 1300 FixedVectorType *SrcVTy = cast<FixedVectorType>(Src); 1301 Type *DstTy = 1302 Opcode == Instruction::Load 1303 ? (*I->user_begin())->getType() 1304 : cast<Instruction>(I->getOperand(0))->getOperand(0)->getType(); 1305 if (SrcVTy->getNumElements() == 4 && SrcVTy->getScalarType()->isHalfTy() && 1306 DstTy->getScalarType()->isFloatTy()) 1307 return ST->getMVEVectorCostFactor(); 1308 } 1309 1310 int BaseCost = ST->hasMVEIntegerOps() && Src->isVectorTy() 1311 ? ST->getMVEVectorCostFactor() 1312 : 1; 1313 return BaseCost * BaseT::getMemoryOpCost(Opcode, Src, Alignment, AddressSpace, 1314 CostKind, I); 1315 } 1316 1317 int ARMTTIImpl::getInterleavedMemoryOpCost( 1318 unsigned Opcode, Type *VecTy, unsigned Factor, ArrayRef<unsigned> Indices, 1319 Align Alignment, unsigned AddressSpace, TTI::TargetCostKind CostKind, 1320 bool UseMaskForCond, bool UseMaskForGaps) { 1321 assert(Factor >= 2 && "Invalid interleave factor"); 1322 assert(isa<VectorType>(VecTy) && "Expect a vector type"); 1323 1324 // vldN/vstN doesn't support vector types of i64/f64 element. 1325 bool EltIs64Bits = DL.getTypeSizeInBits(VecTy->getScalarType()) == 64; 1326 1327 if (Factor <= TLI->getMaxSupportedInterleaveFactor() && !EltIs64Bits && 1328 !UseMaskForCond && !UseMaskForGaps) { 1329 unsigned NumElts = cast<FixedVectorType>(VecTy)->getNumElements(); 1330 auto *SubVecTy = 1331 FixedVectorType::get(VecTy->getScalarType(), NumElts / Factor); 1332 1333 // vldN/vstN only support legal vector types of size 64 or 128 in bits. 1334 // Accesses having vector types that are a multiple of 128 bits can be 1335 // matched to more than one vldN/vstN instruction. 1336 int BaseCost = ST->hasMVEIntegerOps() ? ST->getMVEVectorCostFactor() : 1; 1337 if (NumElts % Factor == 0 && 1338 TLI->isLegalInterleavedAccessType(Factor, SubVecTy, DL)) 1339 return Factor * BaseCost * TLI->getNumInterleavedAccesses(SubVecTy, DL); 1340 1341 // Some smaller than legal interleaved patterns are cheap as we can make 1342 // use of the vmovn or vrev patterns to interleave a standard load. This is 1343 // true for v4i8, v8i8 and v4i16 at least (but not for v4f16 as it is 1344 // promoted differently). The cost of 2 here is then a load and vrev or 1345 // vmovn. 1346 if (ST->hasMVEIntegerOps() && Factor == 2 && NumElts / Factor > 2 && 1347 VecTy->isIntOrIntVectorTy() && 1348 DL.getTypeSizeInBits(SubVecTy).getFixedSize() <= 64) 1349 return 2 * BaseCost; 1350 } 1351 1352 return BaseT::getInterleavedMemoryOpCost(Opcode, VecTy, Factor, Indices, 1353 Alignment, AddressSpace, CostKind, 1354 UseMaskForCond, UseMaskForGaps); 1355 } 1356 1357 unsigned ARMTTIImpl::getGatherScatterOpCost(unsigned Opcode, Type *DataTy, 1358 const Value *Ptr, bool VariableMask, 1359 Align Alignment, 1360 TTI::TargetCostKind CostKind, 1361 const Instruction *I) { 1362 using namespace PatternMatch; 1363 if (!ST->hasMVEIntegerOps() || !EnableMaskedGatherScatters) 1364 return BaseT::getGatherScatterOpCost(Opcode, DataTy, Ptr, VariableMask, 1365 Alignment, CostKind, I); 1366 1367 assert(DataTy->isVectorTy() && "Can't do gather/scatters on scalar!"); 1368 auto *VTy = cast<FixedVectorType>(DataTy); 1369 1370 // TODO: Splitting, once we do that. 1371 1372 unsigned NumElems = VTy->getNumElements(); 1373 unsigned EltSize = VTy->getScalarSizeInBits(); 1374 std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, DataTy); 1375 1376 // For now, it is assumed that for the MVE gather instructions the loads are 1377 // all effectively serialised. This means the cost is the scalar cost 1378 // multiplied by the number of elements being loaded. This is possibly very 1379 // conservative, but even so we still end up vectorising loops because the 1380 // cost per iteration for many loops is lower than for scalar loops. 1381 unsigned VectorCost = NumElems * LT.first * ST->getMVEVectorCostFactor(); 1382 // The scalarization cost should be a lot higher. We use the number of vector 1383 // elements plus the scalarization overhead. 1384 unsigned ScalarCost = 1385 NumElems * LT.first + BaseT::getScalarizationOverhead(VTy, {}); 1386 1387 if (EltSize < 8 || Alignment < EltSize / 8) 1388 return ScalarCost; 1389 1390 unsigned ExtSize = EltSize; 1391 // Check whether there's a single user that asks for an extended type 1392 if (I != nullptr) { 1393 // Dependent of the caller of this function, a gather instruction will 1394 // either have opcode Instruction::Load or be a call to the masked_gather 1395 // intrinsic 1396 if ((I->getOpcode() == Instruction::Load || 1397 match(I, m_Intrinsic<Intrinsic::masked_gather>())) && 1398 I->hasOneUse()) { 1399 const User *Us = *I->users().begin(); 1400 if (isa<ZExtInst>(Us) || isa<SExtInst>(Us)) { 1401 // only allow valid type combinations 1402 unsigned TypeSize = 1403 cast<Instruction>(Us)->getType()->getScalarSizeInBits(); 1404 if (((TypeSize == 32 && (EltSize == 8 || EltSize == 16)) || 1405 (TypeSize == 16 && EltSize == 8)) && 1406 TypeSize * NumElems == 128) { 1407 ExtSize = TypeSize; 1408 } 1409 } 1410 } 1411 // Check whether the input data needs to be truncated 1412 TruncInst *T; 1413 if ((I->getOpcode() == Instruction::Store || 1414 match(I, m_Intrinsic<Intrinsic::masked_scatter>())) && 1415 (T = dyn_cast<TruncInst>(I->getOperand(0)))) { 1416 // Only allow valid type combinations 1417 unsigned TypeSize = T->getOperand(0)->getType()->getScalarSizeInBits(); 1418 if (((EltSize == 16 && TypeSize == 32) || 1419 (EltSize == 8 && (TypeSize == 32 || TypeSize == 16))) && 1420 TypeSize * NumElems == 128) 1421 ExtSize = TypeSize; 1422 } 1423 } 1424 1425 if (ExtSize * NumElems != 128 || NumElems < 4) 1426 return ScalarCost; 1427 1428 // Any (aligned) i32 gather will not need to be scalarised. 1429 if (ExtSize == 32) 1430 return VectorCost; 1431 // For smaller types, we need to ensure that the gep's inputs are correctly 1432 // extended from a small enough value. Other sizes (including i64) are 1433 // scalarized for now. 1434 if (ExtSize != 8 && ExtSize != 16) 1435 return ScalarCost; 1436 1437 if (const auto *BC = dyn_cast<BitCastInst>(Ptr)) 1438 Ptr = BC->getOperand(0); 1439 if (const auto *GEP = dyn_cast<GetElementPtrInst>(Ptr)) { 1440 if (GEP->getNumOperands() != 2) 1441 return ScalarCost; 1442 unsigned Scale = DL.getTypeAllocSize(GEP->getResultElementType()); 1443 // Scale needs to be correct (which is only relevant for i16s). 1444 if (Scale != 1 && Scale * 8 != ExtSize) 1445 return ScalarCost; 1446 // And we need to zext (not sext) the indexes from a small enough type. 1447 if (const auto *ZExt = dyn_cast<ZExtInst>(GEP->getOperand(1))) { 1448 if (ZExt->getOperand(0)->getType()->getScalarSizeInBits() <= ExtSize) 1449 return VectorCost; 1450 } 1451 return ScalarCost; 1452 } 1453 return ScalarCost; 1454 } 1455 1456 int ARMTTIImpl::getArithmeticReductionCost(unsigned Opcode, VectorType *ValTy, 1457 bool IsPairwiseForm, 1458 TTI::TargetCostKind CostKind) { 1459 EVT ValVT = TLI->getValueType(DL, ValTy); 1460 int ISD = TLI->InstructionOpcodeToISD(Opcode); 1461 if (!ST->hasMVEIntegerOps() || !ValVT.isSimple() || ISD != ISD::ADD) 1462 return BaseT::getArithmeticReductionCost(Opcode, ValTy, IsPairwiseForm, 1463 CostKind); 1464 1465 std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, ValTy); 1466 1467 static const CostTblEntry CostTblAdd[]{ 1468 {ISD::ADD, MVT::v16i8, 1}, 1469 {ISD::ADD, MVT::v8i16, 1}, 1470 {ISD::ADD, MVT::v4i32, 1}, 1471 }; 1472 if (const auto *Entry = CostTableLookup(CostTblAdd, ISD, LT.second)) 1473 return Entry->Cost * ST->getMVEVectorCostFactor() * LT.first; 1474 1475 return BaseT::getArithmeticReductionCost(Opcode, ValTy, IsPairwiseForm, 1476 CostKind); 1477 } 1478 1479 int ARMTTIImpl::getIntrinsicInstrCost(const IntrinsicCostAttributes &ICA, 1480 TTI::TargetCostKind CostKind) { 1481 // Currently we make a somewhat optimistic assumption that active_lane_mask's 1482 // are always free. In reality it may be freely folded into a tail predicated 1483 // loop, expanded into a VCPT or expanded into a lot of add/icmp code. We 1484 // may need to improve this in the future, but being able to detect if it 1485 // is free or not involves looking at a lot of other code. We currently assume 1486 // that the vectorizer inserted these, and knew what it was doing in adding 1487 // one. 1488 if (ST->hasMVEIntegerOps() && ICA.getID() == Intrinsic::get_active_lane_mask) 1489 return 0; 1490 1491 return BaseT::getIntrinsicInstrCost(ICA, CostKind); 1492 } 1493 1494 bool ARMTTIImpl::isLoweredToCall(const Function *F) { 1495 if (!F->isIntrinsic()) 1496 BaseT::isLoweredToCall(F); 1497 1498 // Assume all Arm-specific intrinsics map to an instruction. 1499 if (F->getName().startswith("llvm.arm")) 1500 return false; 1501 1502 switch (F->getIntrinsicID()) { 1503 default: break; 1504 case Intrinsic::powi: 1505 case Intrinsic::sin: 1506 case Intrinsic::cos: 1507 case Intrinsic::pow: 1508 case Intrinsic::log: 1509 case Intrinsic::log10: 1510 case Intrinsic::log2: 1511 case Intrinsic::exp: 1512 case Intrinsic::exp2: 1513 return true; 1514 case Intrinsic::sqrt: 1515 case Intrinsic::fabs: 1516 case Intrinsic::copysign: 1517 case Intrinsic::floor: 1518 case Intrinsic::ceil: 1519 case Intrinsic::trunc: 1520 case Intrinsic::rint: 1521 case Intrinsic::nearbyint: 1522 case Intrinsic::round: 1523 case Intrinsic::canonicalize: 1524 case Intrinsic::lround: 1525 case Intrinsic::llround: 1526 case Intrinsic::lrint: 1527 case Intrinsic::llrint: 1528 if (F->getReturnType()->isDoubleTy() && !ST->hasFP64()) 1529 return true; 1530 if (F->getReturnType()->isHalfTy() && !ST->hasFullFP16()) 1531 return true; 1532 // Some operations can be handled by vector instructions and assume 1533 // unsupported vectors will be expanded into supported scalar ones. 1534 // TODO Handle scalar operations properly. 1535 return !ST->hasFPARMv8Base() && !ST->hasVFP2Base(); 1536 case Intrinsic::masked_store: 1537 case Intrinsic::masked_load: 1538 case Intrinsic::masked_gather: 1539 case Intrinsic::masked_scatter: 1540 return !ST->hasMVEIntegerOps(); 1541 case Intrinsic::sadd_with_overflow: 1542 case Intrinsic::uadd_with_overflow: 1543 case Intrinsic::ssub_with_overflow: 1544 case Intrinsic::usub_with_overflow: 1545 case Intrinsic::sadd_sat: 1546 case Intrinsic::uadd_sat: 1547 case Intrinsic::ssub_sat: 1548 case Intrinsic::usub_sat: 1549 return false; 1550 } 1551 1552 return BaseT::isLoweredToCall(F); 1553 } 1554 1555 bool ARMTTIImpl::maybeLoweredToCall(Instruction &I) { 1556 unsigned ISD = TLI->InstructionOpcodeToISD(I.getOpcode()); 1557 EVT VT = TLI->getValueType(DL, I.getType(), true); 1558 if (TLI->getOperationAction(ISD, VT) == TargetLowering::LibCall) 1559 return true; 1560 1561 // Check if an intrinsic will be lowered to a call and assume that any 1562 // other CallInst will generate a bl. 1563 if (auto *Call = dyn_cast<CallInst>(&I)) { 1564 if (auto *II = dyn_cast<IntrinsicInst>(Call)) { 1565 switch(II->getIntrinsicID()) { 1566 case Intrinsic::memcpy: 1567 case Intrinsic::memset: 1568 case Intrinsic::memmove: 1569 return getNumMemOps(II) == -1; 1570 default: 1571 if (const Function *F = Call->getCalledFunction()) 1572 return isLoweredToCall(F); 1573 } 1574 } 1575 return true; 1576 } 1577 1578 // FPv5 provides conversions between integer, double-precision, 1579 // single-precision, and half-precision formats. 1580 switch (I.getOpcode()) { 1581 default: 1582 break; 1583 case Instruction::FPToSI: 1584 case Instruction::FPToUI: 1585 case Instruction::SIToFP: 1586 case Instruction::UIToFP: 1587 case Instruction::FPTrunc: 1588 case Instruction::FPExt: 1589 return !ST->hasFPARMv8Base(); 1590 } 1591 1592 // FIXME: Unfortunately the approach of checking the Operation Action does 1593 // not catch all cases of Legalization that use library calls. Our 1594 // Legalization step categorizes some transformations into library calls as 1595 // Custom, Expand or even Legal when doing type legalization. So for now 1596 // we have to special case for instance the SDIV of 64bit integers and the 1597 // use of floating point emulation. 1598 if (VT.isInteger() && VT.getSizeInBits() >= 64) { 1599 switch (ISD) { 1600 default: 1601 break; 1602 case ISD::SDIV: 1603 case ISD::UDIV: 1604 case ISD::SREM: 1605 case ISD::UREM: 1606 case ISD::SDIVREM: 1607 case ISD::UDIVREM: 1608 return true; 1609 } 1610 } 1611 1612 // Assume all other non-float operations are supported. 1613 if (!VT.isFloatingPoint()) 1614 return false; 1615 1616 // We'll need a library call to handle most floats when using soft. 1617 if (TLI->useSoftFloat()) { 1618 switch (I.getOpcode()) { 1619 default: 1620 return true; 1621 case Instruction::Alloca: 1622 case Instruction::Load: 1623 case Instruction::Store: 1624 case Instruction::Select: 1625 case Instruction::PHI: 1626 return false; 1627 } 1628 } 1629 1630 // We'll need a libcall to perform double precision operations on a single 1631 // precision only FPU. 1632 if (I.getType()->isDoubleTy() && !ST->hasFP64()) 1633 return true; 1634 1635 // Likewise for half precision arithmetic. 1636 if (I.getType()->isHalfTy() && !ST->hasFullFP16()) 1637 return true; 1638 1639 return false; 1640 } 1641 1642 bool ARMTTIImpl::isHardwareLoopProfitable(Loop *L, ScalarEvolution &SE, 1643 AssumptionCache &AC, 1644 TargetLibraryInfo *LibInfo, 1645 HardwareLoopInfo &HWLoopInfo) { 1646 // Low-overhead branches are only supported in the 'low-overhead branch' 1647 // extension of v8.1-m. 1648 if (!ST->hasLOB() || DisableLowOverheadLoops) { 1649 LLVM_DEBUG(dbgs() << "ARMHWLoops: Disabled\n"); 1650 return false; 1651 } 1652 1653 if (!SE.hasLoopInvariantBackedgeTakenCount(L)) { 1654 LLVM_DEBUG(dbgs() << "ARMHWLoops: No BETC\n"); 1655 return false; 1656 } 1657 1658 const SCEV *BackedgeTakenCount = SE.getBackedgeTakenCount(L); 1659 if (isa<SCEVCouldNotCompute>(BackedgeTakenCount)) { 1660 LLVM_DEBUG(dbgs() << "ARMHWLoops: Uncomputable BETC\n"); 1661 return false; 1662 } 1663 1664 const SCEV *TripCountSCEV = 1665 SE.getAddExpr(BackedgeTakenCount, 1666 SE.getOne(BackedgeTakenCount->getType())); 1667 1668 // We need to store the trip count in LR, a 32-bit register. 1669 if (SE.getUnsignedRangeMax(TripCountSCEV).getBitWidth() > 32) { 1670 LLVM_DEBUG(dbgs() << "ARMHWLoops: Trip count does not fit into 32bits\n"); 1671 return false; 1672 } 1673 1674 // Making a call will trash LR and clear LO_BRANCH_INFO, so there's little 1675 // point in generating a hardware loop if that's going to happen. 1676 1677 auto IsHardwareLoopIntrinsic = [](Instruction &I) { 1678 if (auto *Call = dyn_cast<IntrinsicInst>(&I)) { 1679 switch (Call->getIntrinsicID()) { 1680 default: 1681 break; 1682 case Intrinsic::set_loop_iterations: 1683 case Intrinsic::test_set_loop_iterations: 1684 case Intrinsic::loop_decrement: 1685 case Intrinsic::loop_decrement_reg: 1686 return true; 1687 } 1688 } 1689 return false; 1690 }; 1691 1692 // Scan the instructions to see if there's any that we know will turn into a 1693 // call or if this loop is already a low-overhead loop. 1694 auto ScanLoop = [&](Loop *L) { 1695 for (auto *BB : L->getBlocks()) { 1696 for (auto &I : *BB) { 1697 if (maybeLoweredToCall(I) || IsHardwareLoopIntrinsic(I)) { 1698 LLVM_DEBUG(dbgs() << "ARMHWLoops: Bad instruction: " << I << "\n"); 1699 return false; 1700 } 1701 } 1702 } 1703 return true; 1704 }; 1705 1706 // Visit inner loops. 1707 for (auto Inner : *L) 1708 if (!ScanLoop(Inner)) 1709 return false; 1710 1711 if (!ScanLoop(L)) 1712 return false; 1713 1714 // TODO: Check whether the trip count calculation is expensive. If L is the 1715 // inner loop but we know it has a low trip count, calculating that trip 1716 // count (in the parent loop) may be detrimental. 1717 1718 LLVMContext &C = L->getHeader()->getContext(); 1719 HWLoopInfo.CounterInReg = true; 1720 HWLoopInfo.IsNestingLegal = false; 1721 HWLoopInfo.PerformEntryTest = true; 1722 HWLoopInfo.CountType = Type::getInt32Ty(C); 1723 HWLoopInfo.LoopDecrement = ConstantInt::get(HWLoopInfo.CountType, 1); 1724 return true; 1725 } 1726 1727 static bool canTailPredicateInstruction(Instruction &I, int &ICmpCount) { 1728 // We don't allow icmp's, and because we only look at single block loops, 1729 // we simply count the icmps, i.e. there should only be 1 for the backedge. 1730 if (isa<ICmpInst>(&I) && ++ICmpCount > 1) 1731 return false; 1732 1733 if (isa<FCmpInst>(&I)) 1734 return false; 1735 1736 // We could allow extending/narrowing FP loads/stores, but codegen is 1737 // too inefficient so reject this for now. 1738 if (isa<FPExtInst>(&I) || isa<FPTruncInst>(&I)) 1739 return false; 1740 1741 // Extends have to be extending-loads 1742 if (isa<SExtInst>(&I) || isa<ZExtInst>(&I) ) 1743 if (!I.getOperand(0)->hasOneUse() || !isa<LoadInst>(I.getOperand(0))) 1744 return false; 1745 1746 // Truncs have to be narrowing-stores 1747 if (isa<TruncInst>(&I) ) 1748 if (!I.hasOneUse() || !isa<StoreInst>(*I.user_begin())) 1749 return false; 1750 1751 return true; 1752 } 1753 1754 // To set up a tail-predicated loop, we need to know the total number of 1755 // elements processed by that loop. Thus, we need to determine the element 1756 // size and: 1757 // 1) it should be uniform for all operations in the vector loop, so we 1758 // e.g. don't want any widening/narrowing operations. 1759 // 2) it should be smaller than i64s because we don't have vector operations 1760 // that work on i64s. 1761 // 3) we don't want elements to be reversed or shuffled, to make sure the 1762 // tail-predication masks/predicates the right lanes. 1763 // 1764 static bool canTailPredicateLoop(Loop *L, LoopInfo *LI, ScalarEvolution &SE, 1765 const DataLayout &DL, 1766 const LoopAccessInfo *LAI) { 1767 LLVM_DEBUG(dbgs() << "Tail-predication: checking allowed instructions\n"); 1768 1769 // If there are live-out values, it is probably a reduction. We can predicate 1770 // most reduction operations freely under MVE using a combination of 1771 // prefer-predicated-reduction-select and inloop reductions. We limit this to 1772 // floating point and integer reductions, but don't check for operators 1773 // specifically here. If the value ends up not being a reduction (and so the 1774 // vectorizer cannot tailfold the loop), we should fall back to standard 1775 // vectorization automatically. 1776 SmallVector< Instruction *, 8 > LiveOuts; 1777 LiveOuts = llvm::findDefsUsedOutsideOfLoop(L); 1778 bool ReductionsDisabled = 1779 EnableTailPredication == TailPredication::EnabledNoReductions || 1780 EnableTailPredication == TailPredication::ForceEnabledNoReductions; 1781 1782 for (auto *I : LiveOuts) { 1783 if (!I->getType()->isIntegerTy() && !I->getType()->isFloatTy() && 1784 !I->getType()->isHalfTy()) { 1785 LLVM_DEBUG(dbgs() << "Don't tail-predicate loop with non-integer/float " 1786 "live-out value\n"); 1787 return false; 1788 } 1789 if (ReductionsDisabled) { 1790 LLVM_DEBUG(dbgs() << "Reductions not enabled\n"); 1791 return false; 1792 } 1793 } 1794 1795 // Next, check that all instructions can be tail-predicated. 1796 PredicatedScalarEvolution PSE = LAI->getPSE(); 1797 SmallVector<Instruction *, 16> LoadStores; 1798 int ICmpCount = 0; 1799 1800 for (BasicBlock *BB : L->blocks()) { 1801 for (Instruction &I : BB->instructionsWithoutDebug()) { 1802 if (isa<PHINode>(&I)) 1803 continue; 1804 if (!canTailPredicateInstruction(I, ICmpCount)) { 1805 LLVM_DEBUG(dbgs() << "Instruction not allowed: "; I.dump()); 1806 return false; 1807 } 1808 1809 Type *T = I.getType(); 1810 if (T->isPointerTy()) 1811 T = T->getPointerElementType(); 1812 1813 if (T->getScalarSizeInBits() > 32) { 1814 LLVM_DEBUG(dbgs() << "Unsupported Type: "; T->dump()); 1815 return false; 1816 } 1817 if (isa<StoreInst>(I) || isa<LoadInst>(I)) { 1818 Value *Ptr = isa<LoadInst>(I) ? I.getOperand(0) : I.getOperand(1); 1819 int64_t NextStride = getPtrStride(PSE, Ptr, L); 1820 if (NextStride == 1) { 1821 // TODO: for now only allow consecutive strides of 1. We could support 1822 // other strides as long as it is uniform, but let's keep it simple 1823 // for now. 1824 continue; 1825 } else if (NextStride == -1 || 1826 (NextStride == 2 && MVEMaxSupportedInterleaveFactor >= 2) || 1827 (NextStride == 4 && MVEMaxSupportedInterleaveFactor >= 4)) { 1828 LLVM_DEBUG(dbgs() 1829 << "Consecutive strides of 2 found, vld2/vstr2 can't " 1830 "be tail-predicated\n."); 1831 return false; 1832 // TODO: don't tail predicate if there is a reversed load? 1833 } else if (EnableMaskedGatherScatters) { 1834 // Gather/scatters do allow loading from arbitrary strides, at 1835 // least if they are loop invariant. 1836 // TODO: Loop variant strides should in theory work, too, but 1837 // this requires further testing. 1838 const SCEV *PtrScev = 1839 replaceSymbolicStrideSCEV(PSE, llvm::ValueToValueMap(), Ptr); 1840 if (auto AR = dyn_cast<SCEVAddRecExpr>(PtrScev)) { 1841 const SCEV *Step = AR->getStepRecurrence(*PSE.getSE()); 1842 if (PSE.getSE()->isLoopInvariant(Step, L)) 1843 continue; 1844 } 1845 } 1846 LLVM_DEBUG(dbgs() << "Bad stride found, can't " 1847 "tail-predicate\n."); 1848 return false; 1849 } 1850 } 1851 } 1852 1853 LLVM_DEBUG(dbgs() << "tail-predication: all instructions allowed!\n"); 1854 return true; 1855 } 1856 1857 bool ARMTTIImpl::preferPredicateOverEpilogue(Loop *L, LoopInfo *LI, 1858 ScalarEvolution &SE, 1859 AssumptionCache &AC, 1860 TargetLibraryInfo *TLI, 1861 DominatorTree *DT, 1862 const LoopAccessInfo *LAI) { 1863 if (!EnableTailPredication) { 1864 LLVM_DEBUG(dbgs() << "Tail-predication not enabled.\n"); 1865 return false; 1866 } 1867 1868 // Creating a predicated vector loop is the first step for generating a 1869 // tail-predicated hardware loop, for which we need the MVE masked 1870 // load/stores instructions: 1871 if (!ST->hasMVEIntegerOps()) 1872 return false; 1873 1874 // For now, restrict this to single block loops. 1875 if (L->getNumBlocks() > 1) { 1876 LLVM_DEBUG(dbgs() << "preferPredicateOverEpilogue: not a single block " 1877 "loop.\n"); 1878 return false; 1879 } 1880 1881 assert(L->isInnermost() && "preferPredicateOverEpilogue: inner-loop expected"); 1882 1883 HardwareLoopInfo HWLoopInfo(L); 1884 if (!HWLoopInfo.canAnalyze(*LI)) { 1885 LLVM_DEBUG(dbgs() << "preferPredicateOverEpilogue: hardware-loop is not " 1886 "analyzable.\n"); 1887 return false; 1888 } 1889 1890 // This checks if we have the low-overhead branch architecture 1891 // extension, and if we will create a hardware-loop: 1892 if (!isHardwareLoopProfitable(L, SE, AC, TLI, HWLoopInfo)) { 1893 LLVM_DEBUG(dbgs() << "preferPredicateOverEpilogue: hardware-loop is not " 1894 "profitable.\n"); 1895 return false; 1896 } 1897 1898 if (!HWLoopInfo.isHardwareLoopCandidate(SE, *LI, *DT)) { 1899 LLVM_DEBUG(dbgs() << "preferPredicateOverEpilogue: hardware-loop is not " 1900 "a candidate.\n"); 1901 return false; 1902 } 1903 1904 return canTailPredicateLoop(L, LI, SE, DL, LAI); 1905 } 1906 1907 bool ARMTTIImpl::emitGetActiveLaneMask() const { 1908 if (!ST->hasMVEIntegerOps() || !EnableTailPredication) 1909 return false; 1910 1911 // Intrinsic @llvm.get.active.lane.mask is supported. 1912 // It is used in the MVETailPredication pass, which requires the number of 1913 // elements processed by this vector loop to setup the tail-predicated 1914 // loop. 1915 return true; 1916 } 1917 void ARMTTIImpl::getUnrollingPreferences(Loop *L, ScalarEvolution &SE, 1918 TTI::UnrollingPreferences &UP) { 1919 // Only currently enable these preferences for M-Class cores. 1920 if (!ST->isMClass()) 1921 return BasicTTIImplBase::getUnrollingPreferences(L, SE, UP); 1922 1923 // Disable loop unrolling for Oz and Os. 1924 UP.OptSizeThreshold = 0; 1925 UP.PartialOptSizeThreshold = 0; 1926 if (L->getHeader()->getParent()->hasOptSize()) 1927 return; 1928 1929 // Only enable on Thumb-2 targets. 1930 if (!ST->isThumb2()) 1931 return; 1932 1933 SmallVector<BasicBlock*, 4> ExitingBlocks; 1934 L->getExitingBlocks(ExitingBlocks); 1935 LLVM_DEBUG(dbgs() << "Loop has:\n" 1936 << "Blocks: " << L->getNumBlocks() << "\n" 1937 << "Exit blocks: " << ExitingBlocks.size() << "\n"); 1938 1939 // Only allow another exit other than the latch. This acts as an early exit 1940 // as it mirrors the profitability calculation of the runtime unroller. 1941 if (ExitingBlocks.size() > 2) 1942 return; 1943 1944 // Limit the CFG of the loop body for targets with a branch predictor. 1945 // Allowing 4 blocks permits if-then-else diamonds in the body. 1946 if (ST->hasBranchPredictor() && L->getNumBlocks() > 4) 1947 return; 1948 1949 // Scan the loop: don't unroll loops with calls as this could prevent 1950 // inlining. 1951 unsigned Cost = 0; 1952 for (auto *BB : L->getBlocks()) { 1953 for (auto &I : *BB) { 1954 // Don't unroll vectorised loop. MVE does not benefit from it as much as 1955 // scalar code. 1956 if (I.getType()->isVectorTy()) 1957 return; 1958 1959 if (isa<CallInst>(I) || isa<InvokeInst>(I)) { 1960 if (const Function *F = cast<CallBase>(I).getCalledFunction()) { 1961 if (!isLoweredToCall(F)) 1962 continue; 1963 } 1964 return; 1965 } 1966 1967 SmallVector<const Value*, 4> Operands(I.value_op_begin(), 1968 I.value_op_end()); 1969 Cost += 1970 getUserCost(&I, Operands, TargetTransformInfo::TCK_SizeAndLatency); 1971 } 1972 } 1973 1974 LLVM_DEBUG(dbgs() << "Cost of loop: " << Cost << "\n"); 1975 1976 UP.Partial = true; 1977 UP.Runtime = true; 1978 UP.UpperBound = true; 1979 UP.UnrollRemainder = true; 1980 UP.DefaultUnrollRuntimeCount = 4; 1981 UP.UnrollAndJam = true; 1982 UP.UnrollAndJamInnerLoopThreshold = 60; 1983 1984 // Force unrolling small loops can be very useful because of the branch 1985 // taken cost of the backedge. 1986 if (Cost < 12) 1987 UP.Force = true; 1988 } 1989 1990 void ARMTTIImpl::getPeelingPreferences(Loop *L, ScalarEvolution &SE, 1991 TTI::PeelingPreferences &PP) { 1992 BaseT::getPeelingPreferences(L, SE, PP); 1993 } 1994 1995 bool ARMTTIImpl::useReductionIntrinsic(unsigned Opcode, Type *Ty, 1996 TTI::ReductionFlags Flags) const { 1997 return ST->hasMVEIntegerOps(); 1998 } 1999 2000 bool ARMTTIImpl::preferInLoopReduction(unsigned Opcode, Type *Ty, 2001 TTI::ReductionFlags Flags) const { 2002 if (!ST->hasMVEIntegerOps()) 2003 return false; 2004 2005 unsigned ScalarBits = Ty->getScalarSizeInBits(); 2006 switch (Opcode) { 2007 case Instruction::Add: 2008 return ScalarBits <= 32; 2009 default: 2010 return false; 2011 } 2012 } 2013 2014 bool ARMTTIImpl::preferPredicatedReductionSelect( 2015 unsigned Opcode, Type *Ty, TTI::ReductionFlags Flags) const { 2016 if (!ST->hasMVEIntegerOps()) 2017 return false; 2018 return true; 2019 } 2020