AArch64/ARM64: add non-scalar lowering for more FCVT operations.
[oota-llvm.git] / lib / Target / ARM64 / ARM64TargetTransformInfo.cpp
1 //===-- ARM64TargetTransformInfo.cpp - ARM64 specific TTI pass ------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 /// \file
10 /// This file implements a TargetTransformInfo analysis pass specific to the
11 /// ARM64 target machine. It uses the target's detailed information to provide
12 /// more precise answers to certain TTI queries, while letting the target
13 /// independent and default TTI implementations handle the rest.
14 ///
15 //===----------------------------------------------------------------------===//
16
17 #define DEBUG_TYPE "arm64tti"
18 #include "ARM64.h"
19 #include "ARM64TargetMachine.h"
20 #include "MCTargetDesc/ARM64AddressingModes.h"
21 #include "llvm/Analysis/TargetTransformInfo.h"
22 #include "llvm/Support/Debug.h"
23 #include "llvm/Target/CostTable.h"
24 #include "llvm/Target/TargetLowering.h"
25 #include <algorithm>
26 using namespace llvm;
27
28 // Declare the pass initialization routine locally as target-specific passes
29 // don't havve a target-wide initialization entry point, and so we rely on the
30 // pass constructor initialization.
31 namespace llvm {
32 void initializeARM64TTIPass(PassRegistry &);
33 }
34
35 namespace {
36
37 class ARM64TTI final : public ImmutablePass, public TargetTransformInfo {
38   const ARM64TargetMachine *TM;
39   const ARM64Subtarget *ST;
40   const ARM64TargetLowering *TLI;
41
42   /// Estimate the overhead of scalarizing an instruction. Insert and Extract
43   /// are set if the result needs to be inserted and/or extracted from vectors.
44   unsigned getScalarizationOverhead(Type *Ty, bool Insert, bool Extract) const;
45
46 public:
47   ARM64TTI() : ImmutablePass(ID), TM(0), ST(0), TLI(0) {
48     llvm_unreachable("This pass cannot be directly constructed");
49   }
50
51   ARM64TTI(const ARM64TargetMachine *TM)
52       : ImmutablePass(ID), TM(TM), ST(TM->getSubtargetImpl()),
53         TLI(TM->getTargetLowering()) {
54     initializeARM64TTIPass(*PassRegistry::getPassRegistry());
55   }
56
57   void initializePass() override { pushTTIStack(this); }
58
59   void getAnalysisUsage(AnalysisUsage &AU) const override {
60     TargetTransformInfo::getAnalysisUsage(AU);
61   }
62
63   /// Pass identification.
64   static char ID;
65
66   /// Provide necessary pointer adjustments for the two base classes.
67   void *getAdjustedAnalysisPointer(const void *ID) override {
68     if (ID == &TargetTransformInfo::ID)
69       return (TargetTransformInfo *)this;
70     return this;
71   }
72
73   /// \name Scalar TTI Implementations
74   /// @{
75   unsigned getIntImmCost(int64_t Val) const;
76   unsigned getIntImmCost(const APInt &Imm, Type *Ty) const override;
77   unsigned getIntImmCost(unsigned Opcode, unsigned Idx, const APInt &Imm,
78                          Type *Ty) const override;
79   unsigned getIntImmCost(Intrinsic::ID IID, unsigned Idx, const APInt &Imm,
80                          Type *Ty) const override;
81   PopcntSupportKind getPopcntSupport(unsigned TyWidth) const override;
82
83   /// @}
84
85   /// \name Vector TTI Implementations
86   /// @{
87
88   unsigned getNumberOfRegisters(bool Vector) const override {
89     if (Vector)
90       return 32;
91
92     return 31;
93   }
94
95   unsigned getRegisterBitWidth(bool Vector) const override {
96     if (Vector)
97       return 128;
98
99     return 64;
100   }
101
102   unsigned getMaximumUnrollFactor() const override { return 2; }
103
104   unsigned getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src) const
105       override;
106
107   unsigned getVectorInstrCost(unsigned Opcode, Type *Val, unsigned Index) const
108       override;
109
110   unsigned getArithmeticInstrCost(unsigned Opcode, Type *Ty,
111                                   OperandValueKind Opd1Info = OK_AnyValue,
112                                   OperandValueKind Opd2Info = OK_AnyValue) const
113       override;
114
115   unsigned getAddressComputationCost(Type *Ty, bool IsComplex) const override;
116
117   unsigned getCmpSelInstrCost(unsigned Opcode, Type *ValTy, Type *CondTy) const
118       override;
119
120   unsigned getMemoryOpCost(unsigned Opcode, Type *Src, unsigned Alignment,
121                            unsigned AddressSpace) const override;
122   /// @}
123 };
124
125 } // end anonymous namespace
126
127 INITIALIZE_AG_PASS(ARM64TTI, TargetTransformInfo, "arm64tti",
128                    "ARM64 Target Transform Info", true, true, false)
129 char ARM64TTI::ID = 0;
130
131 ImmutablePass *
132 llvm::createARM64TargetTransformInfoPass(const ARM64TargetMachine *TM) {
133   return new ARM64TTI(TM);
134 }
135
136 /// \brief Calculate the cost of materializing a 64-bit value. This helper
137 /// method might only calculate a fraction of a larger immediate. Therefore it
138 /// is valid to return a cost of ZERO.
139 unsigned ARM64TTI::getIntImmCost(int64_t Val) const {
140   // Check if the immediate can be encoded within an instruction.
141   if (Val == 0 || ARM64_AM::isLogicalImmediate(Val, 64))
142     return 0;
143
144   if (Val < 0)
145     Val = ~Val;
146
147   // Calculate how many moves we will need to materialize this constant.
148   unsigned LZ = countLeadingZeros((uint64_t)Val);
149   return (64 - LZ + 15) / 16;
150 }
151
152 /// \brief Calculate the cost of materializing the given constant.
153 unsigned ARM64TTI::getIntImmCost(const APInt &Imm, Type *Ty) const {
154   assert(Ty->isIntegerTy());
155
156   unsigned BitSize = Ty->getPrimitiveSizeInBits();
157   if (BitSize == 0)
158     return ~0U;
159
160   // Sign-extend all constants to a multiple of 64-bit.
161   APInt ImmVal = Imm;
162   if (BitSize & 0x3f)
163     ImmVal = Imm.sext((BitSize + 63) & ~0x3fU);
164
165   // Split the constant into 64-bit chunks and calculate the cost for each
166   // chunk.
167   unsigned Cost = 0;
168   for (unsigned ShiftVal = 0; ShiftVal < BitSize; ShiftVal += 64) {
169     APInt Tmp = ImmVal.ashr(ShiftVal).sextOrTrunc(64);
170     int64_t Val = Tmp.getSExtValue();
171     Cost += getIntImmCost(Val);
172   }
173   // We need at least one instruction to materialze the constant.
174   return std::max(1U, Cost);
175 }
176
177 unsigned ARM64TTI::getIntImmCost(unsigned Opcode, unsigned Idx,
178                                  const APInt &Imm, Type *Ty) const {
179   assert(Ty->isIntegerTy());
180
181   unsigned BitSize = Ty->getPrimitiveSizeInBits();
182   // There is no cost model for constants with a bit size of 0. Return TCC_Free
183   // here, so that constant hoisting will ignore this constant.
184   if (BitSize == 0)
185     return TCC_Free;
186
187   unsigned ImmIdx = ~0U;
188   switch (Opcode) {
189   default:
190     return TCC_Free;
191   case Instruction::GetElementPtr:
192     // Always hoist the base address of a GetElementPtr.
193     if (Idx == 0)
194       return 2 * TCC_Basic;
195     return TCC_Free;
196   case Instruction::Store:
197     ImmIdx = 0;
198     break;
199   case Instruction::Add:
200   case Instruction::Sub:
201   case Instruction::Mul:
202   case Instruction::UDiv:
203   case Instruction::SDiv:
204   case Instruction::URem:
205   case Instruction::SRem:
206   case Instruction::And:
207   case Instruction::Or:
208   case Instruction::Xor:
209   case Instruction::ICmp:
210     ImmIdx = 1;
211     break;
212   // Always return TCC_Free for the shift value of a shift instruction.
213   case Instruction::Shl:
214   case Instruction::LShr:
215   case Instruction::AShr:
216     if (Idx == 1)
217       return TCC_Free;
218     break;
219   case Instruction::Trunc:
220   case Instruction::ZExt:
221   case Instruction::SExt:
222   case Instruction::IntToPtr:
223   case Instruction::PtrToInt:
224   case Instruction::BitCast:
225   case Instruction::PHI:
226   case Instruction::Call:
227   case Instruction::Select:
228   case Instruction::Ret:
229   case Instruction::Load:
230     break;
231   }
232
233   if (Idx == ImmIdx) {
234     unsigned NumConstants = (BitSize + 63) / 64;
235     unsigned Cost = ARM64TTI::getIntImmCost(Imm, Ty);
236     return (Cost <= NumConstants * TCC_Basic)
237       ? static_cast<unsigned>(TCC_Free) : Cost;
238   }
239   return ARM64TTI::getIntImmCost(Imm, Ty);
240 }
241
242 unsigned ARM64TTI::getIntImmCost(Intrinsic::ID IID, unsigned Idx,
243                                  const APInt &Imm, Type *Ty) const {
244   assert(Ty->isIntegerTy());
245
246   unsigned BitSize = Ty->getPrimitiveSizeInBits();
247   // There is no cost model for constants with a bit size of 0. Return TCC_Free
248   // here, so that constant hoisting will ignore this constant.
249   if (BitSize == 0)
250     return TCC_Free;
251
252   switch (IID) {
253   default:
254     return TCC_Free;
255   case Intrinsic::sadd_with_overflow:
256   case Intrinsic::uadd_with_overflow:
257   case Intrinsic::ssub_with_overflow:
258   case Intrinsic::usub_with_overflow:
259   case Intrinsic::smul_with_overflow:
260   case Intrinsic::umul_with_overflow:
261     if (Idx == 1) {
262       unsigned NumConstants = (BitSize + 63) / 64;
263       unsigned Cost = ARM64TTI::getIntImmCost(Imm, Ty);
264       return (Cost <= NumConstants * TCC_Basic)
265         ? static_cast<unsigned>(TCC_Free) : Cost;
266     }
267     break;
268   case Intrinsic::experimental_stackmap:
269     if ((Idx < 2) || (Imm.getBitWidth() <= 64 && isInt<64>(Imm.getSExtValue())))
270       return TCC_Free;
271     break;
272   case Intrinsic::experimental_patchpoint_void:
273   case Intrinsic::experimental_patchpoint_i64:
274     if ((Idx < 4) || (Imm.getBitWidth() <= 64 && isInt<64>(Imm.getSExtValue())))
275       return TCC_Free;
276     break;
277   }
278   return ARM64TTI::getIntImmCost(Imm, Ty);
279 }
280
281 ARM64TTI::PopcntSupportKind ARM64TTI::getPopcntSupport(unsigned TyWidth) const {
282   assert(isPowerOf2_32(TyWidth) && "Ty width must be power of 2");
283   if (TyWidth == 32 || TyWidth == 64)
284     return PSK_FastHardware;
285   // TODO: ARM64TargetLowering::LowerCTPOP() supports 128bit popcount.
286   return PSK_Software;
287 }
288
289 unsigned ARM64TTI::getCastInstrCost(unsigned Opcode, Type *Dst,
290                                     Type *Src) const {
291   int ISD = TLI->InstructionOpcodeToISD(Opcode);
292   assert(ISD && "Invalid opcode");
293
294   EVT SrcTy = TLI->getValueType(Src);
295   EVT DstTy = TLI->getValueType(Dst);
296
297   if (!SrcTy.isSimple() || !DstTy.isSimple())
298     return TargetTransformInfo::getCastInstrCost(Opcode, Dst, Src);
299
300   static const TypeConversionCostTblEntry<MVT> ConversionTbl[] = {
301     // LowerVectorINT_TO_FP:
302     { ISD::SINT_TO_FP, MVT::v2f32, MVT::v2i32, 1 },
303     { ISD::SINT_TO_FP, MVT::v2f64, MVT::v2i8, 1 },
304     { ISD::SINT_TO_FP, MVT::v2f64, MVT::v2i16, 1 },
305     { ISD::SINT_TO_FP, MVT::v2f64, MVT::v2i32, 1 },
306     { ISD::SINT_TO_FP, MVT::v2f64, MVT::v2i64, 1 },
307     { ISD::UINT_TO_FP, MVT::v2f32, MVT::v2i32, 1 },
308     { ISD::UINT_TO_FP, MVT::v2f64, MVT::v2i8, 1 },
309     { ISD::UINT_TO_FP, MVT::v2f64, MVT::v2i16, 1 },
310     { ISD::UINT_TO_FP, MVT::v2f64, MVT::v2i32, 1 },
311     { ISD::UINT_TO_FP, MVT::v2f64, MVT::v2i64, 1 },
312     // LowerVectorFP_TO_INT
313     { ISD::FP_TO_SINT, MVT::v4i32, MVT::v4f32, 1 },
314     { ISD::FP_TO_SINT, MVT::v2i64, MVT::v2f64, 1 },
315     { ISD::FP_TO_UINT, MVT::v4i32, MVT::v4f32, 1 },
316     { ISD::FP_TO_UINT, MVT::v2i64, MVT::v2f64, 1 },
317     { ISD::FP_TO_UINT, MVT::v2i32, MVT::v2f64, 1 },
318     { ISD::FP_TO_SINT, MVT::v2i32, MVT::v2f64, 1 },
319     { ISD::FP_TO_UINT, MVT::v2i64, MVT::v2f32, 4 },
320     { ISD::FP_TO_SINT, MVT::v2i64, MVT::v2f32, 4 },
321     { ISD::FP_TO_UINT, MVT::v4i16, MVT::v4f32, 4 },
322     { ISD::FP_TO_SINT, MVT::v4i16, MVT::v4f32, 4 },
323     { ISD::FP_TO_UINT, MVT::v2i64, MVT::v2f64, 4 },
324     { ISD::FP_TO_SINT, MVT::v2i64, MVT::v2f64, 4 },
325   };
326
327   int Idx = ConvertCostTableLookup<MVT>(
328       ConversionTbl, array_lengthof(ConversionTbl), ISD, DstTy.getSimpleVT(),
329       SrcTy.getSimpleVT());
330   if (Idx != -1)
331     return ConversionTbl[Idx].Cost;
332
333   return TargetTransformInfo::getCastInstrCost(Opcode, Dst, Src);
334 }
335
336 unsigned ARM64TTI::getVectorInstrCost(unsigned Opcode, Type *Val,
337                                       unsigned Index) const {
338   assert(Val->isVectorTy() && "This must be a vector type");
339
340   if (Index != -1U) {
341     // Legalize the type.
342     std::pair<unsigned, MVT> LT = TLI->getTypeLegalizationCost(Val);
343
344     // This type is legalized to a scalar type.
345     if (!LT.second.isVector())
346       return 0;
347
348     // The type may be split. Normalize the index to the new type.
349     unsigned Width = LT.second.getVectorNumElements();
350     Index = Index % Width;
351
352     // The element at index zero is already inside the vector.
353     if (Index == 0)
354       return 0;
355   }
356
357   // All other insert/extracts cost this much.
358   return 2;
359 }
360
361 unsigned ARM64TTI::getArithmeticInstrCost(unsigned Opcode, Type *Ty,
362                                           OperandValueKind Opd1Info,
363                                           OperandValueKind Opd2Info) const {
364   // Legalize the type.
365   std::pair<unsigned, MVT> LT = TLI->getTypeLegalizationCost(Ty);
366
367   int ISD = TLI->InstructionOpcodeToISD(Opcode);
368
369   switch (ISD) {
370   default:
371     return TargetTransformInfo::getArithmeticInstrCost(Opcode, Ty, Opd1Info,
372                                                        Opd2Info);
373   case ISD::ADD:
374   case ISD::MUL:
375   case ISD::XOR:
376   case ISD::OR:
377   case ISD::AND:
378     // These nodes are marked as 'custom' for combining purposes only.
379     // We know that they are legal. See LowerAdd in ISelLowering.
380     return 1 * LT.first;
381   }
382 }
383
384 unsigned ARM64TTI::getAddressComputationCost(Type *Ty, bool IsComplex) const {
385   // Address computations in vectorized code with non-consecutive addresses will
386   // likely result in more instructions compared to scalar code where the
387   // computation can more often be merged into the index mode. The resulting
388   // extra micro-ops can significantly decrease throughput.
389   unsigned NumVectorInstToHideOverhead = 10;
390
391   if (Ty->isVectorTy() && IsComplex)
392     return NumVectorInstToHideOverhead;
393
394   // In many cases the address computation is not merged into the instruction
395   // addressing mode.
396   return 1;
397 }
398
399 unsigned ARM64TTI::getCmpSelInstrCost(unsigned Opcode, Type *ValTy,
400                                       Type *CondTy) const {
401
402   int ISD = TLI->InstructionOpcodeToISD(Opcode);
403   // We don't lower vector selects well that are wider than the register width.
404   if (ValTy->isVectorTy() && ISD == ISD::SELECT) {
405     // We would need this many instructions to hide the scalarization happening.
406     unsigned AmortizationCost = 20;
407     static const TypeConversionCostTblEntry<MVT::SimpleValueType>
408     VectorSelectTbl[] = {
409       { ISD::SELECT, MVT::v16i1, MVT::v16i16, 16 * AmortizationCost },
410       { ISD::SELECT, MVT::v8i1, MVT::v8i32, 8 * AmortizationCost },
411       { ISD::SELECT, MVT::v16i1, MVT::v16i32, 16 * AmortizationCost },
412       { ISD::SELECT, MVT::v4i1, MVT::v4i64, 4 * AmortizationCost },
413       { ISD::SELECT, MVT::v8i1, MVT::v8i64, 8 * AmortizationCost },
414       { ISD::SELECT, MVT::v16i1, MVT::v16i64, 16 * AmortizationCost }
415     };
416
417     EVT SelCondTy = TLI->getValueType(CondTy);
418     EVT SelValTy = TLI->getValueType(ValTy);
419     if (SelCondTy.isSimple() && SelValTy.isSimple()) {
420       int Idx =
421           ConvertCostTableLookup(VectorSelectTbl, ISD, SelCondTy.getSimpleVT(),
422                                  SelValTy.getSimpleVT());
423       if (Idx != -1)
424         return VectorSelectTbl[Idx].Cost;
425     }
426   }
427   return TargetTransformInfo::getCmpSelInstrCost(Opcode, ValTy, CondTy);
428 }
429
430 unsigned ARM64TTI::getMemoryOpCost(unsigned Opcode, Type *Src,
431                                    unsigned Alignment,
432                                    unsigned AddressSpace) const {
433   std::pair<unsigned, MVT> LT = TLI->getTypeLegalizationCost(Src);
434
435   if (Opcode == Instruction::Store && Src->isVectorTy() && Alignment != 16 &&
436       Src->getVectorElementType()->isIntegerTy(64)) {
437     // Unaligned stores are extremely inefficient. We don't split
438     // unaligned v2i64 stores because the negative impact that has shown in
439     // practice on inlined memcpy code.
440     // We make v2i64 stores expensive so that we will only vectorize if there
441     // are 6 other instructions getting vectorized.
442     unsigned AmortizationCost = 6;
443
444     return LT.first * 2 * AmortizationCost;
445   }
446
447   if (Src->isVectorTy() && Src->getVectorElementType()->isIntegerTy(8) &&
448       Src->getVectorNumElements() < 8) {
449     // We scalarize the loads/stores because there is not v.4b register and we
450     // have to promote the elements to v.4h.
451     unsigned NumVecElts = Src->getVectorNumElements();
452     unsigned NumVectorizableInstsToAmortize = NumVecElts * 2;
453     // We generate 2 instructions per vector element.
454     return NumVectorizableInstsToAmortize * NumVecElts * 2;
455   }
456
457   return LT.first;
458 }