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