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