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