-
Notifications
You must be signed in to change notification settings - Fork 13.3k
/
Copy pathAArch64TargetTransformInfo.cpp
6255 lines (5590 loc) · 250 KB
/
AArch64TargetTransformInfo.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//===-- AArch64TargetTransformInfo.cpp - AArch64 specific TTI -------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "AArch64TargetTransformInfo.h"
#include "AArch64ExpandImm.h"
#include "AArch64PerfectShuffle.h"
#include "MCTargetDesc/AArch64AddressingModes.h"
#include "Utils/AArch64SMEAttributes.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/Analysis/LoopInfo.h"
#include "llvm/Analysis/TargetTransformInfo.h"
#include "llvm/CodeGen/BasicTTIImpl.h"
#include "llvm/CodeGen/CostTable.h"
#include "llvm/CodeGen/TargetLowering.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/Intrinsics.h"
#include "llvm/IR/IntrinsicsAArch64.h"
#include "llvm/IR/PatternMatch.h"
#include "llvm/Support/Debug.h"
#include "llvm/TargetParser/AArch64TargetParser.h"
#include "llvm/Transforms/InstCombine/InstCombiner.h"
#include "llvm/Transforms/Vectorize/LoopVectorizationLegality.h"
#include <algorithm>
#include <optional>
using namespace llvm;
using namespace llvm::PatternMatch;
#define DEBUG_TYPE "aarch64tti"
static cl::opt<bool> EnableFalkorHWPFUnrollFix("enable-falkor-hwpf-unroll-fix",
cl::init(true), cl::Hidden);
static cl::opt<bool> SVEPreferFixedOverScalableIfEqualCost(
"sve-prefer-fixed-over-scalable-if-equal", cl::Hidden);
static cl::opt<unsigned> SVEGatherOverhead("sve-gather-overhead", cl::init(10),
cl::Hidden);
static cl::opt<unsigned> SVEScatterOverhead("sve-scatter-overhead",
cl::init(10), cl::Hidden);
static cl::opt<unsigned> SVETailFoldInsnThreshold("sve-tail-folding-insn-threshold",
cl::init(15), cl::Hidden);
static cl::opt<unsigned>
NeonNonConstStrideOverhead("neon-nonconst-stride-overhead", cl::init(10),
cl::Hidden);
static cl::opt<unsigned> CallPenaltyChangeSM(
"call-penalty-sm-change", cl::init(5), cl::Hidden,
cl::desc(
"Penalty of calling a function that requires a change to PSTATE.SM"));
static cl::opt<unsigned> InlineCallPenaltyChangeSM(
"inline-call-penalty-sm-change", cl::init(10), cl::Hidden,
cl::desc("Penalty of inlining a call that requires a change to PSTATE.SM"));
static cl::opt<bool> EnableOrLikeSelectOpt("enable-aarch64-or-like-select",
cl::init(true), cl::Hidden);
static cl::opt<bool> EnableLSRCostOpt("enable-aarch64-lsr-cost-opt",
cl::init(true), cl::Hidden);
// A complete guess as to a reasonable cost.
static cl::opt<unsigned>
BaseHistCntCost("aarch64-base-histcnt-cost", cl::init(8), cl::Hidden,
cl::desc("The cost of a histcnt instruction"));
static cl::opt<unsigned> DMBLookaheadThreshold(
"dmb-lookahead-threshold", cl::init(10), cl::Hidden,
cl::desc("The number of instructions to search for a redundant dmb"));
namespace {
class TailFoldingOption {
// These bitfields will only ever be set to something non-zero in operator=,
// when setting the -sve-tail-folding option. This option should always be of
// the form (default|simple|all|disable)[+(Flag1|Flag2|etc)], where here
// InitialBits is one of (disabled|all|simple). EnableBits represents
// additional flags we're enabling, and DisableBits for those flags we're
// disabling. The default flag is tracked in the variable NeedsDefault, since
// at the time of setting the option we may not know what the default value
// for the CPU is.
TailFoldingOpts InitialBits = TailFoldingOpts::Disabled;
TailFoldingOpts EnableBits = TailFoldingOpts::Disabled;
TailFoldingOpts DisableBits = TailFoldingOpts::Disabled;
// This value needs to be initialised to true in case the user does not
// explicitly set the -sve-tail-folding option.
bool NeedsDefault = true;
void setInitialBits(TailFoldingOpts Bits) { InitialBits = Bits; }
void setNeedsDefault(bool V) { NeedsDefault = V; }
void setEnableBit(TailFoldingOpts Bit) {
EnableBits |= Bit;
DisableBits &= ~Bit;
}
void setDisableBit(TailFoldingOpts Bit) {
EnableBits &= ~Bit;
DisableBits |= Bit;
}
TailFoldingOpts getBits(TailFoldingOpts DefaultBits) const {
TailFoldingOpts Bits = TailFoldingOpts::Disabled;
assert((InitialBits == TailFoldingOpts::Disabled || !NeedsDefault) &&
"Initial bits should only include one of "
"(disabled|all|simple|default)");
Bits = NeedsDefault ? DefaultBits : InitialBits;
Bits |= EnableBits;
Bits &= ~DisableBits;
return Bits;
}
void reportError(std::string Opt) {
errs() << "invalid argument '" << Opt
<< "' to -sve-tail-folding=; the option should be of the form\n"
" (disabled|all|default|simple)[+(reductions|recurrences"
"|reverse|noreductions|norecurrences|noreverse)]\n";
report_fatal_error("Unrecognised tail-folding option");
}
public:
void operator=(const std::string &Val) {
// If the user explicitly sets -sve-tail-folding= then treat as an error.
if (Val.empty()) {
reportError("");
return;
}
// Since the user is explicitly setting the option we don't automatically
// need the default unless they require it.
setNeedsDefault(false);
SmallVector<StringRef, 4> TailFoldTypes;
StringRef(Val).split(TailFoldTypes, '+', -1, false);
unsigned StartIdx = 1;
if (TailFoldTypes[0] == "disabled")
setInitialBits(TailFoldingOpts::Disabled);
else if (TailFoldTypes[0] == "all")
setInitialBits(TailFoldingOpts::All);
else if (TailFoldTypes[0] == "default")
setNeedsDefault(true);
else if (TailFoldTypes[0] == "simple")
setInitialBits(TailFoldingOpts::Simple);
else {
StartIdx = 0;
setInitialBits(TailFoldingOpts::Disabled);
}
for (unsigned I = StartIdx; I < TailFoldTypes.size(); I++) {
if (TailFoldTypes[I] == "reductions")
setEnableBit(TailFoldingOpts::Reductions);
else if (TailFoldTypes[I] == "recurrences")
setEnableBit(TailFoldingOpts::Recurrences);
else if (TailFoldTypes[I] == "reverse")
setEnableBit(TailFoldingOpts::Reverse);
else if (TailFoldTypes[I] == "noreductions")
setDisableBit(TailFoldingOpts::Reductions);
else if (TailFoldTypes[I] == "norecurrences")
setDisableBit(TailFoldingOpts::Recurrences);
else if (TailFoldTypes[I] == "noreverse")
setDisableBit(TailFoldingOpts::Reverse);
else
reportError(Val);
}
}
bool satisfies(TailFoldingOpts DefaultBits, TailFoldingOpts Required) const {
return (getBits(DefaultBits) & Required) == Required;
}
};
} // namespace
TailFoldingOption TailFoldingOptionLoc;
static cl::opt<TailFoldingOption, true, cl::parser<std::string>> SVETailFolding(
"sve-tail-folding",
cl::desc(
"Control the use of vectorisation using tail-folding for SVE where the"
" option is specified in the form (Initial)[+(Flag1|Flag2|...)]:"
"\ndisabled (Initial) No loop types will vectorize using "
"tail-folding"
"\ndefault (Initial) Uses the default tail-folding settings for "
"the target CPU"
"\nall (Initial) All legal loop types will vectorize using "
"tail-folding"
"\nsimple (Initial) Use tail-folding for simple loops (not "
"reductions or recurrences)"
"\nreductions Use tail-folding for loops containing reductions"
"\nnoreductions Inverse of above"
"\nrecurrences Use tail-folding for loops containing fixed order "
"recurrences"
"\nnorecurrences Inverse of above"
"\nreverse Use tail-folding for loops requiring reversed "
"predicates"
"\nnoreverse Inverse of above"),
cl::location(TailFoldingOptionLoc));
// Experimental option that will only be fully functional when the
// code-generator is changed to use SVE instead of NEON for all fixed-width
// operations.
static cl::opt<bool> EnableFixedwidthAutovecInStreamingMode(
"enable-fixedwidth-autovec-in-streaming-mode", cl::init(false), cl::Hidden);
// Experimental option that will only be fully functional when the cost-model
// and code-generator have been changed to avoid using scalable vector
// instructions that are not legal in streaming SVE mode.
static cl::opt<bool> EnableScalableAutovecInStreamingMode(
"enable-scalable-autovec-in-streaming-mode", cl::init(false), cl::Hidden);
static bool isSMEABIRoutineCall(const CallInst &CI) {
const auto *F = CI.getCalledFunction();
return F && StringSwitch<bool>(F->getName())
.Case("__arm_sme_state", true)
.Case("__arm_tpidr2_save", true)
.Case("__arm_tpidr2_restore", true)
.Case("__arm_za_disable", true)
.Default(false);
}
/// Returns true if the function has explicit operations that can only be
/// lowered using incompatible instructions for the selected mode. This also
/// returns true if the function F may use or modify ZA state.
static bool hasPossibleIncompatibleOps(const Function *F) {
for (const BasicBlock &BB : *F) {
for (const Instruction &I : BB) {
// Be conservative for now and assume that any call to inline asm or to
// intrinsics could could result in non-streaming ops (e.g. calls to
// @llvm.aarch64.* or @llvm.gather/scatter intrinsics). We can assume that
// all native LLVM instructions can be lowered to compatible instructions.
if (isa<CallInst>(I) && !I.isDebugOrPseudoInst() &&
(cast<CallInst>(I).isInlineAsm() || isa<IntrinsicInst>(I) ||
isSMEABIRoutineCall(cast<CallInst>(I))))
return true;
}
}
return false;
}
uint64_t AArch64TTIImpl::getFeatureMask(const Function &F) const {
StringRef AttributeStr =
isMultiversionedFunction(F) ? "fmv-features" : "target-features";
StringRef FeatureStr = F.getFnAttribute(AttributeStr).getValueAsString();
SmallVector<StringRef, 8> Features;
FeatureStr.split(Features, ",");
return AArch64::getFMVPriority(Features);
}
bool AArch64TTIImpl::isMultiversionedFunction(const Function &F) const {
return F.hasFnAttribute("fmv-features");
}
const FeatureBitset AArch64TTIImpl::InlineInverseFeatures = {
AArch64::FeatureExecuteOnly,
};
bool AArch64TTIImpl::areInlineCompatible(const Function *Caller,
const Function *Callee) const {
SMEAttrs CallerAttrs(*Caller), CalleeAttrs(*Callee);
// When inlining, we should consider the body of the function, not the
// interface.
if (CalleeAttrs.hasStreamingBody()) {
CalleeAttrs.set(SMEAttrs::SM_Compatible, false);
CalleeAttrs.set(SMEAttrs::SM_Enabled, true);
}
if (CalleeAttrs.isNewZA() || CalleeAttrs.isNewZT0())
return false;
if (CallerAttrs.requiresLazySave(CalleeAttrs) ||
CallerAttrs.requiresSMChange(CalleeAttrs) ||
CallerAttrs.requiresPreservingZT0(CalleeAttrs) ||
CallerAttrs.requiresPreservingAllZAState(CalleeAttrs)) {
if (hasPossibleIncompatibleOps(Callee))
return false;
}
const TargetMachine &TM = getTLI()->getTargetMachine();
const FeatureBitset &CallerBits =
TM.getSubtargetImpl(*Caller)->getFeatureBits();
const FeatureBitset &CalleeBits =
TM.getSubtargetImpl(*Callee)->getFeatureBits();
// Adjust the feature bitsets by inverting some of the bits. This is needed
// for target features that represent restrictions rather than capabilities,
// for example a "+execute-only" callee can be inlined into a caller without
// "+execute-only", but not vice versa.
FeatureBitset EffectiveCallerBits = CallerBits ^ InlineInverseFeatures;
FeatureBitset EffectiveCalleeBits = CalleeBits ^ InlineInverseFeatures;
return (EffectiveCallerBits & EffectiveCalleeBits) == EffectiveCalleeBits;
}
bool AArch64TTIImpl::areTypesABICompatible(
const Function *Caller, const Function *Callee,
const ArrayRef<Type *> &Types) const {
if (!BaseT::areTypesABICompatible(Caller, Callee, Types))
return false;
// We need to ensure that argument promotion does not attempt to promote
// pointers to fixed-length vector types larger than 128 bits like
// <8 x float> (and pointers to aggregate types which have such fixed-length
// vector type members) into the values of the pointees. Such vector types
// are used for SVE VLS but there is no ABI for SVE VLS arguments and the
// backend cannot lower such value arguments. The 128-bit fixed-length SVE
// types can be safely treated as 128-bit NEON types and they cannot be
// distinguished in IR.
if (ST->useSVEForFixedLengthVectors() && llvm::any_of(Types, [](Type *Ty) {
auto FVTy = dyn_cast<FixedVectorType>(Ty);
return FVTy &&
FVTy->getScalarSizeInBits() * FVTy->getNumElements() > 128;
}))
return false;
return true;
}
unsigned
AArch64TTIImpl::getInlineCallPenalty(const Function *F, const CallBase &Call,
unsigned DefaultCallPenalty) const {
// This function calculates a penalty for executing Call in F.
//
// There are two ways this function can be called:
// (1) F:
// call from F -> G (the call here is Call)
//
// For (1), Call.getCaller() == F, so it will always return a high cost if
// a streaming-mode change is required (thus promoting the need to inline the
// function)
//
// (2) F:
// call from F -> G (the call here is not Call)
// G:
// call from G -> H (the call here is Call)
//
// For (2), if after inlining the body of G into F the call to H requires a
// streaming-mode change, and the call to G from F would also require a
// streaming-mode change, then there is benefit to do the streaming-mode
// change only once and avoid inlining of G into F.
SMEAttrs FAttrs(*F);
SMEAttrs CalleeAttrs(Call);
if (FAttrs.requiresSMChange(CalleeAttrs)) {
if (F == Call.getCaller()) // (1)
return CallPenaltyChangeSM * DefaultCallPenalty;
if (FAttrs.requiresSMChange(SMEAttrs(*Call.getCaller()))) // (2)
return InlineCallPenaltyChangeSM * DefaultCallPenalty;
}
return DefaultCallPenalty;
}
bool AArch64TTIImpl::shouldMaximizeVectorBandwidth(
TargetTransformInfo::RegisterKind K) const {
assert(K != TargetTransformInfo::RGK_Scalar);
return (K == TargetTransformInfo::RGK_FixedWidthVector &&
ST->isNeonAvailable());
}
/// Calculate the cost of materializing a 64-bit value. This helper
/// method might only calculate a fraction of a larger immediate. Therefore it
/// is valid to return a cost of ZERO.
InstructionCost AArch64TTIImpl::getIntImmCost(int64_t Val) {
// Check if the immediate can be encoded within an instruction.
if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, 64))
return 0;
if (Val < 0)
Val = ~Val;
// Calculate how many moves we will need to materialize this constant.
SmallVector<AArch64_IMM::ImmInsnModel, 4> Insn;
AArch64_IMM::expandMOVImm(Val, 64, Insn);
return Insn.size();
}
/// Calculate the cost of materializing the given constant.
InstructionCost AArch64TTIImpl::getIntImmCost(const APInt &Imm, Type *Ty,
TTI::TargetCostKind CostKind) {
assert(Ty->isIntegerTy());
unsigned BitSize = Ty->getPrimitiveSizeInBits();
if (BitSize == 0)
return ~0U;
// Sign-extend all constants to a multiple of 64-bit.
APInt ImmVal = Imm;
if (BitSize & 0x3f)
ImmVal = Imm.sext((BitSize + 63) & ~0x3fU);
// Split the constant into 64-bit chunks and calculate the cost for each
// chunk.
InstructionCost Cost = 0;
for (unsigned ShiftVal = 0; ShiftVal < BitSize; ShiftVal += 64) {
APInt Tmp = ImmVal.ashr(ShiftVal).sextOrTrunc(64);
int64_t Val = Tmp.getSExtValue();
Cost += getIntImmCost(Val);
}
// We need at least one instruction to materialze the constant.
return std::max<InstructionCost>(1, Cost);
}
InstructionCost AArch64TTIImpl::getIntImmCostInst(unsigned Opcode, unsigned Idx,
const APInt &Imm, Type *Ty,
TTI::TargetCostKind CostKind,
Instruction *Inst) {
assert(Ty->isIntegerTy());
unsigned BitSize = Ty->getPrimitiveSizeInBits();
// There is no cost model for constants with a bit size of 0. Return TCC_Free
// here, so that constant hoisting will ignore this constant.
if (BitSize == 0)
return TTI::TCC_Free;
unsigned ImmIdx = ~0U;
switch (Opcode) {
default:
return TTI::TCC_Free;
case Instruction::GetElementPtr:
// Always hoist the base address of a GetElementPtr.
if (Idx == 0)
return 2 * TTI::TCC_Basic;
return TTI::TCC_Free;
case Instruction::Store:
ImmIdx = 0;
break;
case Instruction::Add:
case Instruction::Sub:
case Instruction::Mul:
case Instruction::UDiv:
case Instruction::SDiv:
case Instruction::URem:
case Instruction::SRem:
case Instruction::And:
case Instruction::Or:
case Instruction::Xor:
case Instruction::ICmp:
ImmIdx = 1;
break;
// Always return TCC_Free for the shift value of a shift instruction.
case Instruction::Shl:
case Instruction::LShr:
case Instruction::AShr:
if (Idx == 1)
return TTI::TCC_Free;
break;
case Instruction::Trunc:
case Instruction::ZExt:
case Instruction::SExt:
case Instruction::IntToPtr:
case Instruction::PtrToInt:
case Instruction::BitCast:
case Instruction::PHI:
case Instruction::Call:
case Instruction::Select:
case Instruction::Ret:
case Instruction::Load:
break;
}
if (Idx == ImmIdx) {
int NumConstants = (BitSize + 63) / 64;
InstructionCost Cost = AArch64TTIImpl::getIntImmCost(Imm, Ty, CostKind);
return (Cost <= NumConstants * TTI::TCC_Basic)
? static_cast<int>(TTI::TCC_Free)
: Cost;
}
return AArch64TTIImpl::getIntImmCost(Imm, Ty, CostKind);
}
InstructionCost
AArch64TTIImpl::getIntImmCostIntrin(Intrinsic::ID IID, unsigned Idx,
const APInt &Imm, Type *Ty,
TTI::TargetCostKind CostKind) {
assert(Ty->isIntegerTy());
unsigned BitSize = Ty->getPrimitiveSizeInBits();
// There is no cost model for constants with a bit size of 0. Return TCC_Free
// here, so that constant hoisting will ignore this constant.
if (BitSize == 0)
return TTI::TCC_Free;
// Most (all?) AArch64 intrinsics do not support folding immediates into the
// selected instruction, so we compute the materialization cost for the
// immediate directly.
if (IID >= Intrinsic::aarch64_addg && IID <= Intrinsic::aarch64_udiv)
return AArch64TTIImpl::getIntImmCost(Imm, Ty, CostKind);
switch (IID) {
default:
return TTI::TCC_Free;
case Intrinsic::sadd_with_overflow:
case Intrinsic::uadd_with_overflow:
case Intrinsic::ssub_with_overflow:
case Intrinsic::usub_with_overflow:
case Intrinsic::smul_with_overflow:
case Intrinsic::umul_with_overflow:
if (Idx == 1) {
int NumConstants = (BitSize + 63) / 64;
InstructionCost Cost = AArch64TTIImpl::getIntImmCost(Imm, Ty, CostKind);
return (Cost <= NumConstants * TTI::TCC_Basic)
? static_cast<int>(TTI::TCC_Free)
: Cost;
}
break;
case Intrinsic::experimental_stackmap:
if ((Idx < 2) || (Imm.getBitWidth() <= 64 && isInt<64>(Imm.getSExtValue())))
return TTI::TCC_Free;
break;
case Intrinsic::experimental_patchpoint_void:
case Intrinsic::experimental_patchpoint:
if ((Idx < 4) || (Imm.getBitWidth() <= 64 && isInt<64>(Imm.getSExtValue())))
return TTI::TCC_Free;
break;
case Intrinsic::experimental_gc_statepoint:
if ((Idx < 5) || (Imm.getBitWidth() <= 64 && isInt<64>(Imm.getSExtValue())))
return TTI::TCC_Free;
break;
}
return AArch64TTIImpl::getIntImmCost(Imm, Ty, CostKind);
}
TargetTransformInfo::PopcntSupportKind
AArch64TTIImpl::getPopcntSupport(unsigned TyWidth) {
assert(isPowerOf2_32(TyWidth) && "Ty width must be power of 2");
if (TyWidth == 32 || TyWidth == 64)
return TTI::PSK_FastHardware;
// TODO: AArch64TargetLowering::LowerCTPOP() supports 128bit popcount.
return TTI::PSK_Software;
}
static bool isUnpackedVectorVT(EVT VecVT) {
return VecVT.isScalableVector() &&
VecVT.getSizeInBits().getKnownMinValue() < AArch64::SVEBitsPerBlock;
}
static InstructionCost getHistogramCost(const IntrinsicCostAttributes &ICA) {
Type *BucketPtrsTy = ICA.getArgTypes()[0]; // Type of vector of pointers
Type *EltTy = ICA.getArgTypes()[1]; // Type of bucket elements
unsigned TotalHistCnts = 1;
unsigned EltSize = EltTy->getScalarSizeInBits();
// Only allow (up to 64b) integers or pointers
if ((!EltTy->isIntegerTy() && !EltTy->isPointerTy()) || EltSize > 64)
return InstructionCost::getInvalid();
// FIXME: We should be able to generate histcnt for fixed-length vectors
// using ptrue with a specific VL.
if (VectorType *VTy = dyn_cast<VectorType>(BucketPtrsTy)) {
unsigned EC = VTy->getElementCount().getKnownMinValue();
if (!isPowerOf2_64(EC) || !VTy->isScalableTy())
return InstructionCost::getInvalid();
// HistCnt only supports 32b and 64b element types
unsigned LegalEltSize = EltSize <= 32 ? 32 : 64;
if (EC == 2 || (LegalEltSize == 32 && EC == 4))
return InstructionCost(BaseHistCntCost);
unsigned NaturalVectorWidth = AArch64::SVEBitsPerBlock / LegalEltSize;
TotalHistCnts = EC / NaturalVectorWidth;
}
return InstructionCost(BaseHistCntCost * TotalHistCnts);
}
InstructionCost
AArch64TTIImpl::getIntrinsicInstrCost(const IntrinsicCostAttributes &ICA,
TTI::TargetCostKind CostKind) {
// The code-generator is currently not able to handle scalable vectors
// of <vscale x 1 x eltty> yet, so return an invalid cost to avoid selecting
// it. This change will be removed when code-generation for these types is
// sufficiently reliable.
auto *RetTy = ICA.getReturnType();
if (auto *VTy = dyn_cast<ScalableVectorType>(RetTy))
if (VTy->getElementCount() == ElementCount::getScalable(1))
return InstructionCost::getInvalid();
switch (ICA.getID()) {
case Intrinsic::experimental_vector_histogram_add:
if (!ST->hasSVE2())
return InstructionCost::getInvalid();
return getHistogramCost(ICA);
case Intrinsic::umin:
case Intrinsic::umax:
case Intrinsic::smin:
case Intrinsic::smax: {
static const auto ValidMinMaxTys = {MVT::v8i8, MVT::v16i8, MVT::v4i16,
MVT::v8i16, MVT::v2i32, MVT::v4i32,
MVT::nxv16i8, MVT::nxv8i16, MVT::nxv4i32,
MVT::nxv2i64};
auto LT = getTypeLegalizationCost(RetTy);
// v2i64 types get converted to cmp+bif hence the cost of 2
if (LT.second == MVT::v2i64)
return LT.first * 2;
if (any_of(ValidMinMaxTys, [<](MVT M) { return M == LT.second; }))
return LT.first;
break;
}
case Intrinsic::sadd_sat:
case Intrinsic::ssub_sat:
case Intrinsic::uadd_sat:
case Intrinsic::usub_sat: {
static const auto ValidSatTys = {MVT::v8i8, MVT::v16i8, MVT::v4i16,
MVT::v8i16, MVT::v2i32, MVT::v4i32,
MVT::v2i64};
auto LT = getTypeLegalizationCost(RetTy);
// This is a base cost of 1 for the vadd, plus 3 extract shifts if we
// need to extend the type, as it uses shr(qadd(shl, shl)).
unsigned Instrs =
LT.second.getScalarSizeInBits() == RetTy->getScalarSizeInBits() ? 1 : 4;
if (any_of(ValidSatTys, [<](MVT M) { return M == LT.second; }))
return LT.first * Instrs;
break;
}
case Intrinsic::abs: {
static const auto ValidAbsTys = {MVT::v8i8, MVT::v16i8, MVT::v4i16,
MVT::v8i16, MVT::v2i32, MVT::v4i32,
MVT::v2i64};
auto LT = getTypeLegalizationCost(RetTy);
if (any_of(ValidAbsTys, [<](MVT M) { return M == LT.second; }))
return LT.first;
break;
}
case Intrinsic::bswap: {
static const auto ValidAbsTys = {MVT::v4i16, MVT::v8i16, MVT::v2i32,
MVT::v4i32, MVT::v2i64};
auto LT = getTypeLegalizationCost(RetTy);
if (any_of(ValidAbsTys, [<](MVT M) { return M == LT.second; }) &&
LT.second.getScalarSizeInBits() == RetTy->getScalarSizeInBits())
return LT.first;
break;
}
case Intrinsic::stepvector: {
InstructionCost Cost = 1; // Cost of the `index' instruction
auto LT = getTypeLegalizationCost(RetTy);
// Legalisation of illegal vectors involves an `index' instruction plus
// (LT.first - 1) vector adds.
if (LT.first > 1) {
Type *LegalVTy = EVT(LT.second).getTypeForEVT(RetTy->getContext());
InstructionCost AddCost =
getArithmeticInstrCost(Instruction::Add, LegalVTy, CostKind);
Cost += AddCost * (LT.first - 1);
}
return Cost;
}
case Intrinsic::vector_extract:
case Intrinsic::vector_insert: {
// If both the vector and subvector types are legal types and the index
// is 0, then this should be a no-op or simple operation; return a
// relatively low cost.
// If arguments aren't actually supplied, then we cannot determine the
// value of the index. We also want to skip predicate types.
if (ICA.getArgs().size() != ICA.getArgTypes().size() ||
ICA.getReturnType()->getScalarType()->isIntegerTy(1))
break;
LLVMContext &C = RetTy->getContext();
EVT VecVT = getTLI()->getValueType(DL, ICA.getArgTypes()[0]);
bool IsExtract = ICA.getID() == Intrinsic::vector_extract;
EVT SubVecVT = IsExtract ? getTLI()->getValueType(DL, RetTy)
: getTLI()->getValueType(DL, ICA.getArgTypes()[1]);
// Skip this if either the vector or subvector types are unpacked
// SVE types; they may get lowered to stack stores and loads.
if (isUnpackedVectorVT(VecVT) || isUnpackedVectorVT(SubVecVT))
break;
TargetLoweringBase::LegalizeKind SubVecLK =
getTLI()->getTypeConversion(C, SubVecVT);
TargetLoweringBase::LegalizeKind VecLK =
getTLI()->getTypeConversion(C, VecVT);
const Value *Idx = IsExtract ? ICA.getArgs()[1] : ICA.getArgs()[2];
const ConstantInt *CIdx = cast<ConstantInt>(Idx);
if (SubVecLK.first == TargetLoweringBase::TypeLegal &&
VecLK.first == TargetLoweringBase::TypeLegal && CIdx->isZero())
return TTI::TCC_Free;
break;
}
case Intrinsic::bitreverse: {
static const CostTblEntry BitreverseTbl[] = {
{Intrinsic::bitreverse, MVT::i32, 1},
{Intrinsic::bitreverse, MVT::i64, 1},
{Intrinsic::bitreverse, MVT::v8i8, 1},
{Intrinsic::bitreverse, MVT::v16i8, 1},
{Intrinsic::bitreverse, MVT::v4i16, 2},
{Intrinsic::bitreverse, MVT::v8i16, 2},
{Intrinsic::bitreverse, MVT::v2i32, 2},
{Intrinsic::bitreverse, MVT::v4i32, 2},
{Intrinsic::bitreverse, MVT::v1i64, 2},
{Intrinsic::bitreverse, MVT::v2i64, 2},
};
const auto LegalisationCost = getTypeLegalizationCost(RetTy);
const auto *Entry =
CostTableLookup(BitreverseTbl, ICA.getID(), LegalisationCost.second);
if (Entry) {
// Cost Model is using the legal type(i32) that i8 and i16 will be
// converted to +1 so that we match the actual lowering cost
if (TLI->getValueType(DL, RetTy, true) == MVT::i8 ||
TLI->getValueType(DL, RetTy, true) == MVT::i16)
return LegalisationCost.first * Entry->Cost + 1;
return LegalisationCost.first * Entry->Cost;
}
break;
}
case Intrinsic::ctpop: {
if (!ST->hasNEON()) {
// 32-bit or 64-bit ctpop without NEON is 12 instructions.
return getTypeLegalizationCost(RetTy).first * 12;
}
static const CostTblEntry CtpopCostTbl[] = {
{ISD::CTPOP, MVT::v2i64, 4},
{ISD::CTPOP, MVT::v4i32, 3},
{ISD::CTPOP, MVT::v8i16, 2},
{ISD::CTPOP, MVT::v16i8, 1},
{ISD::CTPOP, MVT::i64, 4},
{ISD::CTPOP, MVT::v2i32, 3},
{ISD::CTPOP, MVT::v4i16, 2},
{ISD::CTPOP, MVT::v8i8, 1},
{ISD::CTPOP, MVT::i32, 5},
};
auto LT = getTypeLegalizationCost(RetTy);
MVT MTy = LT.second;
if (const auto *Entry = CostTableLookup(CtpopCostTbl, ISD::CTPOP, MTy)) {
// Extra cost of +1 when illegal vector types are legalized by promoting
// the integer type.
int ExtraCost = MTy.isVector() && MTy.getScalarSizeInBits() !=
RetTy->getScalarSizeInBits()
? 1
: 0;
return LT.first * Entry->Cost + ExtraCost;
}
break;
}
case Intrinsic::sadd_with_overflow:
case Intrinsic::uadd_with_overflow:
case Intrinsic::ssub_with_overflow:
case Intrinsic::usub_with_overflow:
case Intrinsic::smul_with_overflow:
case Intrinsic::umul_with_overflow: {
static const CostTblEntry WithOverflowCostTbl[] = {
{Intrinsic::sadd_with_overflow, MVT::i8, 3},
{Intrinsic::uadd_with_overflow, MVT::i8, 3},
{Intrinsic::sadd_with_overflow, MVT::i16, 3},
{Intrinsic::uadd_with_overflow, MVT::i16, 3},
{Intrinsic::sadd_with_overflow, MVT::i32, 1},
{Intrinsic::uadd_with_overflow, MVT::i32, 1},
{Intrinsic::sadd_with_overflow, MVT::i64, 1},
{Intrinsic::uadd_with_overflow, MVT::i64, 1},
{Intrinsic::ssub_with_overflow, MVT::i8, 3},
{Intrinsic::usub_with_overflow, MVT::i8, 3},
{Intrinsic::ssub_with_overflow, MVT::i16, 3},
{Intrinsic::usub_with_overflow, MVT::i16, 3},
{Intrinsic::ssub_with_overflow, MVT::i32, 1},
{Intrinsic::usub_with_overflow, MVT::i32, 1},
{Intrinsic::ssub_with_overflow, MVT::i64, 1},
{Intrinsic::usub_with_overflow, MVT::i64, 1},
{Intrinsic::smul_with_overflow, MVT::i8, 5},
{Intrinsic::umul_with_overflow, MVT::i8, 4},
{Intrinsic::smul_with_overflow, MVT::i16, 5},
{Intrinsic::umul_with_overflow, MVT::i16, 4},
{Intrinsic::smul_with_overflow, MVT::i32, 2}, // eg umull;tst
{Intrinsic::umul_with_overflow, MVT::i32, 2}, // eg umull;cmp sxtw
{Intrinsic::smul_with_overflow, MVT::i64, 3}, // eg mul;smulh;cmp
{Intrinsic::umul_with_overflow, MVT::i64, 3}, // eg mul;umulh;cmp asr
};
EVT MTy = TLI->getValueType(DL, RetTy->getContainedType(0), true);
if (MTy.isSimple())
if (const auto *Entry = CostTableLookup(WithOverflowCostTbl, ICA.getID(),
MTy.getSimpleVT()))
return Entry->Cost;
break;
}
case Intrinsic::fptosi_sat:
case Intrinsic::fptoui_sat: {
if (ICA.getArgTypes().empty())
break;
bool IsSigned = ICA.getID() == Intrinsic::fptosi_sat;
auto LT = getTypeLegalizationCost(ICA.getArgTypes()[0]);
EVT MTy = TLI->getValueType(DL, RetTy);
// Check for the legal types, which are where the size of the input and the
// output are the same, or we are using cvt f64->i32 or f32->i64.
if ((LT.second == MVT::f32 || LT.second == MVT::f64 ||
LT.second == MVT::v2f32 || LT.second == MVT::v4f32 ||
LT.second == MVT::v2f64)) {
if ((LT.second.getScalarSizeInBits() == MTy.getScalarSizeInBits() ||
(LT.second == MVT::f64 && MTy == MVT::i32) ||
(LT.second == MVT::f32 && MTy == MVT::i64)))
return LT.first;
// Extending vector types v2f32->v2i64, fcvtl*2 + fcvt*2
if (LT.second.getScalarType() == MVT::f32 && MTy.isFixedLengthVector() &&
MTy.getScalarSizeInBits() == 64)
return LT.first * (MTy.getVectorNumElements() > 2 ? 4 : 2);
}
// Similarly for fp16 sizes. Without FullFP16 we generally need to fcvt to
// f32.
if (LT.second.getScalarType() == MVT::f16 && !ST->hasFullFP16())
return LT.first + getIntrinsicInstrCost(
{ICA.getID(),
RetTy,
{ICA.getArgTypes()[0]->getWithNewType(
Type::getFloatTy(RetTy->getContext()))}},
CostKind);
if ((LT.second == MVT::f16 && MTy == MVT::i32) ||
(LT.second == MVT::f16 && MTy == MVT::i64) ||
((LT.second == MVT::v4f16 || LT.second == MVT::v8f16) &&
(LT.second.getScalarSizeInBits() == MTy.getScalarSizeInBits())))
return LT.first;
// Extending vector types v8f16->v8i32, fcvtl*2 + fcvt*2
if (LT.second.getScalarType() == MVT::f16 && MTy.isFixedLengthVector() &&
MTy.getScalarSizeInBits() == 32)
return LT.first * (MTy.getVectorNumElements() > 4 ? 4 : 2);
// Extending vector types v8f16->v8i32. These current scalarize but the
// codegen could be better.
if (LT.second.getScalarType() == MVT::f16 && MTy.isFixedLengthVector() &&
MTy.getScalarSizeInBits() == 64)
return MTy.getVectorNumElements() * 3;
// If we can we use a legal convert followed by a min+max
if ((LT.second.getScalarType() == MVT::f32 ||
LT.second.getScalarType() == MVT::f64 ||
LT.second.getScalarType() == MVT::f16) &&
LT.second.getScalarSizeInBits() >= MTy.getScalarSizeInBits()) {
Type *LegalTy =
Type::getIntNTy(RetTy->getContext(), LT.second.getScalarSizeInBits());
if (LT.second.isVector())
LegalTy = VectorType::get(LegalTy, LT.second.getVectorElementCount());
InstructionCost Cost = 1;
IntrinsicCostAttributes Attrs1(IsSigned ? Intrinsic::smin : Intrinsic::umin,
LegalTy, {LegalTy, LegalTy});
Cost += getIntrinsicInstrCost(Attrs1, CostKind);
IntrinsicCostAttributes Attrs2(IsSigned ? Intrinsic::smax : Intrinsic::umax,
LegalTy, {LegalTy, LegalTy});
Cost += getIntrinsicInstrCost(Attrs2, CostKind);
return LT.first * Cost +
((LT.second.getScalarType() != MVT::f16 || ST->hasFullFP16()) ? 0
: 1);
}
// Otherwise we need to follow the default expansion that clamps the value
// using a float min/max with a fcmp+sel for nan handling when signed.
Type *FPTy = ICA.getArgTypes()[0]->getScalarType();
RetTy = RetTy->getScalarType();
if (LT.second.isVector()) {
FPTy = VectorType::get(FPTy, LT.second.getVectorElementCount());
RetTy = VectorType::get(RetTy, LT.second.getVectorElementCount());
}
IntrinsicCostAttributes Attrs1(Intrinsic::minnum, FPTy, {FPTy, FPTy});
InstructionCost Cost = getIntrinsicInstrCost(Attrs1, CostKind);
IntrinsicCostAttributes Attrs2(Intrinsic::maxnum, FPTy, {FPTy, FPTy});
Cost += getIntrinsicInstrCost(Attrs2, CostKind);
Cost +=
getCastInstrCost(IsSigned ? Instruction::FPToSI : Instruction::FPToUI,
RetTy, FPTy, TTI::CastContextHint::None, CostKind);
if (IsSigned) {
Type *CondTy = RetTy->getWithNewBitWidth(1);
Cost += getCmpSelInstrCost(BinaryOperator::FCmp, FPTy, CondTy,
CmpInst::FCMP_UNO, CostKind);
Cost += getCmpSelInstrCost(BinaryOperator::Select, RetTy, CondTy,
CmpInst::FCMP_UNO, CostKind);
}
return LT.first * Cost;
}
case Intrinsic::fshl:
case Intrinsic::fshr: {
if (ICA.getArgs().empty())
break;
// TODO: Add handling for fshl where third argument is not a constant.
const TTI::OperandValueInfo OpInfoZ = TTI::getOperandInfo(ICA.getArgs()[2]);
if (!OpInfoZ.isConstant())
break;
const auto LegalisationCost = getTypeLegalizationCost(RetTy);
if (OpInfoZ.isUniform()) {
static const CostTblEntry FshlTbl[] = {
{Intrinsic::fshl, MVT::v4i32, 2}, // shl + usra
{Intrinsic::fshl, MVT::v2i64, 2}, {Intrinsic::fshl, MVT::v16i8, 2},
{Intrinsic::fshl, MVT::v8i16, 2}, {Intrinsic::fshl, MVT::v2i32, 2},
{Intrinsic::fshl, MVT::v8i8, 2}, {Intrinsic::fshl, MVT::v4i16, 2}};
// Costs for both fshl & fshr are the same, so just pass Intrinsic::fshl
// to avoid having to duplicate the costs.
const auto *Entry =
CostTableLookup(FshlTbl, Intrinsic::fshl, LegalisationCost.second);
if (Entry)
return LegalisationCost.first * Entry->Cost;
}
auto TyL = getTypeLegalizationCost(RetTy);
if (!RetTy->isIntegerTy())
break;
// Estimate cost manually, as types like i8 and i16 will get promoted to
// i32 and CostTableLookup will ignore the extra conversion cost.
bool HigherCost = (RetTy->getScalarSizeInBits() != 32 &&
RetTy->getScalarSizeInBits() < 64) ||
(RetTy->getScalarSizeInBits() % 64 != 0);
unsigned ExtraCost = HigherCost ? 1 : 0;
if (RetTy->getScalarSizeInBits() == 32 ||
RetTy->getScalarSizeInBits() == 64)
ExtraCost = 0; // fhsl/fshr for i32 and i64 can be lowered to a single
// extr instruction.
else if (HigherCost)
ExtraCost = 1;
else
break;
return TyL.first + ExtraCost;
}
case Intrinsic::get_active_lane_mask: {
auto *RetTy = dyn_cast<FixedVectorType>(ICA.getReturnType());
if (RetTy) {
EVT RetVT = getTLI()->getValueType(DL, RetTy);
EVT OpVT = getTLI()->getValueType(DL, ICA.getArgTypes()[0]);
if (!getTLI()->shouldExpandGetActiveLaneMask(RetVT, OpVT) &&
!getTLI()->isTypeLegal(RetVT)) {
// We don't have enough context at this point to determine if the mask
// is going to be kept live after the block, which will force the vXi1
// type to be expanded to legal vectors of integers, e.g. v4i1->v4i32.
// For now, we just assume the vectorizer created this intrinsic and
// the result will be the input for a PHI. In this case the cost will
// be extremely high for fixed-width vectors.
// NOTE: getScalarizationOverhead returns a cost that's far too
// pessimistic for the actual generated codegen. In reality there are
// two instructions generated per lane.
return RetTy->getNumElements() * 2;
}
}
break;
}
case Intrinsic::experimental_vector_match: {
auto *NeedleTy = cast<FixedVectorType>(ICA.getArgTypes()[1]);
EVT SearchVT = getTLI()->getValueType(DL, ICA.getArgTypes()[0]);
unsigned SearchSize = NeedleTy->getNumElements();
if (!getTLI()->shouldExpandVectorMatch(SearchVT, SearchSize)) {
// Base cost for MATCH instructions. At least on the Neoverse V2 and
// Neoverse V3, these are cheap operations with the same latency as a
// vector ADD. In most cases, however, we also need to do an extra DUP.
// For fixed-length vectors we currently need an extra five--six
// instructions besides the MATCH.
InstructionCost Cost = 4;
if (isa<FixedVectorType>(RetTy))
Cost += 10;
return Cost;
}
break;
}
case Intrinsic::experimental_cttz_elts: {
EVT ArgVT = getTLI()->getValueType(DL, ICA.getArgTypes()[0]);
if (!getTLI()->shouldExpandCttzElements(ArgVT)) {
// This will consist of a SVE brkb and a cntp instruction. These
// typically have the same latency and half the throughput as a vector
// add instruction.
return 4;
}
break;
}
default:
break;
}
return BaseT::getIntrinsicInstrCost(ICA, CostKind);
}
/// The function will remove redundant reinterprets casting in the presence
/// of the control flow
static std::optional<Instruction *> processPhiNode(InstCombiner &IC,
IntrinsicInst &II) {
SmallVector<Instruction *, 32> Worklist;
auto RequiredType = II.getType();
auto *PN = dyn_cast<PHINode>(II.getArgOperand(0));
assert(PN && "Expected Phi Node!");
// Don't create a new Phi unless we can remove the old one.
if (!PN->hasOneUse())
return std::nullopt;
for (Value *IncValPhi : PN->incoming_values()) {
auto *Reinterpret = dyn_cast<IntrinsicInst>(IncValPhi);
if (!Reinterpret ||
Reinterpret->getIntrinsicID() !=
Intrinsic::aarch64_sve_convert_to_svbool ||
RequiredType != Reinterpret->getArgOperand(0)->getType())
return std::nullopt;
}
// Create the new Phi
IC.Builder.SetInsertPoint(PN);
PHINode *NPN = IC.Builder.CreatePHI(RequiredType, PN->getNumIncomingValues());
Worklist.push_back(PN);