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