LLVM  9.0.0svn
ARMISelLowering.cpp
Go to the documentation of this file.
1 //===- ARMISelLowering.cpp - ARM DAG Lowering Implementation --------------===//
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 // This file defines the interfaces that ARM uses to lower LLVM code into a
10 // selection DAG.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "ARMISelLowering.h"
15 #include "ARMBaseInstrInfo.h"
16 #include "ARMBaseRegisterInfo.h"
17 #include "ARMCallingConv.h"
18 #include "ARMConstantPoolValue.h"
19 #include "ARMMachineFunctionInfo.h"
20 #include "ARMPerfectShuffle.h"
21 #include "ARMRegisterInfo.h"
22 #include "ARMSelectionDAGInfo.h"
23 #include "ARMSubtarget.h"
26 #include "Utils/ARMBaseInfo.h"
27 #include "llvm/ADT/APFloat.h"
28 #include "llvm/ADT/APInt.h"
29 #include "llvm/ADT/ArrayRef.h"
30 #include "llvm/ADT/BitVector.h"
31 #include "llvm/ADT/DenseMap.h"
32 #include "llvm/ADT/STLExtras.h"
33 #include "llvm/ADT/SmallPtrSet.h"
34 #include "llvm/ADT/SmallVector.h"
35 #include "llvm/ADT/Statistic.h"
36 #include "llvm/ADT/StringExtras.h"
37 #include "llvm/ADT/StringRef.h"
38 #include "llvm/ADT/StringSwitch.h"
39 #include "llvm/ADT/Triple.h"
40 #include "llvm/ADT/Twine.h"
64 #include "llvm/IR/Attributes.h"
65 #include "llvm/IR/CallingConv.h"
66 #include "llvm/IR/Constant.h"
67 #include "llvm/IR/Constants.h"
68 #include "llvm/IR/DataLayout.h"
69 #include "llvm/IR/DebugLoc.h"
70 #include "llvm/IR/DerivedTypes.h"
71 #include "llvm/IR/Function.h"
72 #include "llvm/IR/GlobalAlias.h"
73 #include "llvm/IR/GlobalValue.h"
74 #include "llvm/IR/GlobalVariable.h"
75 #include "llvm/IR/IRBuilder.h"
76 #include "llvm/IR/InlineAsm.h"
77 #include "llvm/IR/Instruction.h"
78 #include "llvm/IR/Instructions.h"
79 #include "llvm/IR/IntrinsicInst.h"
80 #include "llvm/IR/Intrinsics.h"
81 #include "llvm/IR/Module.h"
82 #include "llvm/IR/PatternMatch.h"
83 #include "llvm/IR/Type.h"
84 #include "llvm/IR/User.h"
85 #include "llvm/IR/Value.h"
86 #include "llvm/MC/MCInstrDesc.h"
88 #include "llvm/MC/MCRegisterInfo.h"
89 #include "llvm/MC/MCSchedule.h"
92 #include "llvm/Support/Casting.h"
93 #include "llvm/Support/CodeGen.h"
95 #include "llvm/Support/Compiler.h"
96 #include "llvm/Support/Debug.h"
98 #include "llvm/Support/KnownBits.h"
100 #include "llvm/Support/MathExtras.h"
104 #include <algorithm>
105 #include <cassert>
106 #include <cstdint>
107 #include <cstdlib>
108 #include <iterator>
109 #include <limits>
110 #include <string>
111 #include <tuple>
112 #include <utility>
113 #include <vector>
114 
115 using namespace llvm;
116 using namespace llvm::PatternMatch;
117 
118 #define DEBUG_TYPE "arm-isel"
119 
120 STATISTIC(NumTailCalls, "Number of tail calls");
121 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
122 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments");
123 STATISTIC(NumConstpoolPromoted,
124  "Number of constants with their storage promoted into constant pools");
125 
126 static cl::opt<bool>
127 ARMInterworking("arm-interworking", cl::Hidden,
128  cl::desc("Enable / disable ARM interworking (for debugging only)"),
129  cl::init(true));
130 
132  "arm-promote-constant", cl::Hidden,
133  cl::desc("Enable / disable promotion of unnamed_addr constants into "
134  "constant pools"),
135  cl::init(false)); // FIXME: set to true by default once PR32780 is fixed
137  "arm-promote-constant-max-size", cl::Hidden,
138  cl::desc("Maximum size of constant to promote into a constant pool"),
139  cl::init(64));
141  "arm-promote-constant-max-total", cl::Hidden,
142  cl::desc("Maximum size of ALL constants to promote into a constant pool"),
143  cl::init(128));
144 
145 // The APCS parameter registers.
146 static const MCPhysReg GPRArgRegs[] = {
147  ARM::R0, ARM::R1, ARM::R2, ARM::R3
148 };
149 
150 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT,
151  MVT PromotedBitwiseVT) {
152  if (VT != PromotedLdStVT) {
153  setOperationAction(ISD::LOAD, VT, Promote);
154  AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
155 
156  setOperationAction(ISD::STORE, VT, Promote);
157  AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
158  }
159 
160  MVT ElemTy = VT.getVectorElementType();
161  if (ElemTy != MVT::f64)
162  setOperationAction(ISD::SETCC, VT, Custom);
163  setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
164  setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
165  if (ElemTy == MVT::i32) {
166  setOperationAction(ISD::SINT_TO_FP, VT, Custom);
167  setOperationAction(ISD::UINT_TO_FP, VT, Custom);
168  setOperationAction(ISD::FP_TO_SINT, VT, Custom);
169  setOperationAction(ISD::FP_TO_UINT, VT, Custom);
170  } else {
171  setOperationAction(ISD::SINT_TO_FP, VT, Expand);
172  setOperationAction(ISD::UINT_TO_FP, VT, Expand);
173  setOperationAction(ISD::FP_TO_SINT, VT, Expand);
174  setOperationAction(ISD::FP_TO_UINT, VT, Expand);
175  }
176  setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
177  setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
178  setOperationAction(ISD::CONCAT_VECTORS, VT, Legal);
179  setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
180  setOperationAction(ISD::SELECT, VT, Expand);
181  setOperationAction(ISD::SELECT_CC, VT, Expand);
182  setOperationAction(ISD::VSELECT, VT, Expand);
183  setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
184  if (VT.isInteger()) {
185  setOperationAction(ISD::SHL, VT, Custom);
186  setOperationAction(ISD::SRA, VT, Custom);
187  setOperationAction(ISD::SRL, VT, Custom);
188  }
189 
190  // Promote all bit-wise operations.
191  if (VT.isInteger() && VT != PromotedBitwiseVT) {
192  setOperationAction(ISD::AND, VT, Promote);
193  AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT);
194  setOperationAction(ISD::OR, VT, Promote);
195  AddPromotedToType (ISD::OR, VT, PromotedBitwiseVT);
196  setOperationAction(ISD::XOR, VT, Promote);
197  AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT);
198  }
199 
200  // Neon does not support vector divide/remainder operations.
201  setOperationAction(ISD::SDIV, VT, Expand);
202  setOperationAction(ISD::UDIV, VT, Expand);
203  setOperationAction(ISD::FDIV, VT, Expand);
204  setOperationAction(ISD::SREM, VT, Expand);
205  setOperationAction(ISD::UREM, VT, Expand);
206  setOperationAction(ISD::FREM, VT, Expand);
207 
208  if (!VT.isFloatingPoint() &&
209  VT != MVT::v2i64 && VT != MVT::v1i64)
210  for (auto Opcode : {ISD::ABS, ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
211  setOperationAction(Opcode, VT, Legal);
212 }
213 
214 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
215  addRegisterClass(VT, &ARM::DPRRegClass);
216  addTypeForNEON(VT, MVT::f64, MVT::v2i32);
217 }
218 
219 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
220  addRegisterClass(VT, &ARM::DPairRegClass);
221  addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
222 }
223 
225  const ARMSubtarget &STI)
226  : TargetLowering(TM), Subtarget(&STI) {
227  RegInfo = Subtarget->getRegisterInfo();
228  Itins = Subtarget->getInstrItineraryData();
229 
232 
233  if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetIOS() &&
234  !Subtarget->isTargetWatchOS()) {
235  bool IsHFTarget = TM.Options.FloatABIType == FloatABI::Hard;
236  for (int LCID = 0; LCID < RTLIB::UNKNOWN_LIBCALL; ++LCID)
237  setLibcallCallingConv(static_cast<RTLIB::Libcall>(LCID),
238  IsHFTarget ? CallingConv::ARM_AAPCS_VFP
240  }
241 
242  if (Subtarget->isTargetMachO()) {
243  // Uses VFP for Thumb libfuncs if available.
244  if (Subtarget->isThumb() && Subtarget->hasVFP2Base() &&
245  Subtarget->hasARMOps() && !Subtarget->useSoftFloat()) {
246  static const struct {
247  const RTLIB::Libcall Op;
248  const char * const Name;
249  const ISD::CondCode Cond;
250  } LibraryCalls[] = {
251  // Single-precision floating-point arithmetic.
252  { RTLIB::ADD_F32, "__addsf3vfp", ISD::SETCC_INVALID },
253  { RTLIB::SUB_F32, "__subsf3vfp", ISD::SETCC_INVALID },
254  { RTLIB::MUL_F32, "__mulsf3vfp", ISD::SETCC_INVALID },
255  { RTLIB::DIV_F32, "__divsf3vfp", ISD::SETCC_INVALID },
256 
257  // Double-precision floating-point arithmetic.
258  { RTLIB::ADD_F64, "__adddf3vfp", ISD::SETCC_INVALID },
259  { RTLIB::SUB_F64, "__subdf3vfp", ISD::SETCC_INVALID },
260  { RTLIB::MUL_F64, "__muldf3vfp", ISD::SETCC_INVALID },
261  { RTLIB::DIV_F64, "__divdf3vfp", ISD::SETCC_INVALID },
262 
263  // Single-precision comparisons.
264  { RTLIB::OEQ_F32, "__eqsf2vfp", ISD::SETNE },
265  { RTLIB::UNE_F32, "__nesf2vfp", ISD::SETNE },
266  { RTLIB::OLT_F32, "__ltsf2vfp", ISD::SETNE },
267  { RTLIB::OLE_F32, "__lesf2vfp", ISD::SETNE },
268  { RTLIB::OGE_F32, "__gesf2vfp", ISD::SETNE },
269  { RTLIB::OGT_F32, "__gtsf2vfp", ISD::SETNE },
270  { RTLIB::UO_F32, "__unordsf2vfp", ISD::SETNE },
271  { RTLIB::O_F32, "__unordsf2vfp", ISD::SETEQ },
272 
273  // Double-precision comparisons.
274  { RTLIB::OEQ_F64, "__eqdf2vfp", ISD::SETNE },
275  { RTLIB::UNE_F64, "__nedf2vfp", ISD::SETNE },
276  { RTLIB::OLT_F64, "__ltdf2vfp", ISD::SETNE },
277  { RTLIB::OLE_F64, "__ledf2vfp", ISD::SETNE },
278  { RTLIB::OGE_F64, "__gedf2vfp", ISD::SETNE },
279  { RTLIB::OGT_F64, "__gtdf2vfp", ISD::SETNE },
280  { RTLIB::UO_F64, "__unorddf2vfp", ISD::SETNE },
281  { RTLIB::O_F64, "__unorddf2vfp", ISD::SETEQ },
282 
283  // Floating-point to integer conversions.
284  // i64 conversions are done via library routines even when generating VFP
285  // instructions, so use the same ones.
286  { RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp", ISD::SETCC_INVALID },
287  { RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp", ISD::SETCC_INVALID },
288  { RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp", ISD::SETCC_INVALID },
289  { RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp", ISD::SETCC_INVALID },
290 
291  // Conversions between floating types.
292  { RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp", ISD::SETCC_INVALID },
293  { RTLIB::FPEXT_F32_F64, "__extendsfdf2vfp", ISD::SETCC_INVALID },
294 
295  // Integer to floating-point conversions.
296  // i64 conversions are done via library routines even when generating VFP
297  // instructions, so use the same ones.
298  // FIXME: There appears to be some naming inconsistency in ARM libgcc:
299  // e.g., __floatunsidf vs. __floatunssidfvfp.
300  { RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp", ISD::SETCC_INVALID },
301  { RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp", ISD::SETCC_INVALID },
302  { RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp", ISD::SETCC_INVALID },
303  { RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp", ISD::SETCC_INVALID },
304  };
305 
306  for (const auto &LC : LibraryCalls) {
307  setLibcallName(LC.Op, LC.Name);
308  if (LC.Cond != ISD::SETCC_INVALID)
309  setCmpLibcallCC(LC.Op, LC.Cond);
310  }
311  }
312  }
313 
314  // These libcalls are not available in 32-bit.
315  setLibcallName(RTLIB::SHL_I128, nullptr);
316  setLibcallName(RTLIB::SRL_I128, nullptr);
317  setLibcallName(RTLIB::SRA_I128, nullptr);
318 
319  // RTLIB
320  if (Subtarget->isAAPCS_ABI() &&
321  (Subtarget->isTargetAEABI() || Subtarget->isTargetGNUAEABI() ||
322  Subtarget->isTargetMuslAEABI() || Subtarget->isTargetAndroid())) {
323  static const struct {
324  const RTLIB::Libcall Op;
325  const char * const Name;
326  const CallingConv::ID CC;
327  const ISD::CondCode Cond;
328  } LibraryCalls[] = {
329  // Double-precision floating-point arithmetic helper functions
330  // RTABI chapter 4.1.2, Table 2
331  { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
332  { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
333  { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
334  { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
335 
336  // Double-precision floating-point comparison helper functions
337  // RTABI chapter 4.1.2, Table 3
338  { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
339  { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
340  { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
341  { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
342  { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
343  { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
344  { RTLIB::UO_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
345  { RTLIB::O_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
346 
347  // Single-precision floating-point arithmetic helper functions
348  // RTABI chapter 4.1.2, Table 4
349  { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
350  { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
351  { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
352  { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
353 
354  // Single-precision floating-point comparison helper functions
355  // RTABI chapter 4.1.2, Table 5
356  { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
357  { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
358  { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
359  { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
360  { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
361  { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
362  { RTLIB::UO_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
363  { RTLIB::O_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
364 
365  // Floating-point to integer conversions.
366  // RTABI chapter 4.1.2, Table 6
367  { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
368  { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
369  { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
370  { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
371  { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
372  { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
373  { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
374  { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
375 
376  // Conversions between floating types.
377  // RTABI chapter 4.1.2, Table 7
378  { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
379  { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
380  { RTLIB::FPEXT_F32_F64, "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
381 
382  // Integer to floating-point conversions.
383  // RTABI chapter 4.1.2, Table 8
384  { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
385  { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
386  { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
387  { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
388  { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
389  { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
390  { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
391  { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
392 
393  // Long long helper functions
394  // RTABI chapter 4.2, Table 9
395  { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
396  { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
397  { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
398  { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
399 
400  // Integer division functions
401  // RTABI chapter 4.3.1
402  { RTLIB::SDIV_I8, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
403  { RTLIB::SDIV_I16, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
404  { RTLIB::SDIV_I32, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
405  { RTLIB::SDIV_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
406  { RTLIB::UDIV_I8, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
407  { RTLIB::UDIV_I16, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
408  { RTLIB::UDIV_I32, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
409  { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
410  };
411 
412  for (const auto &LC : LibraryCalls) {
413  setLibcallName(LC.Op, LC.Name);
414  setLibcallCallingConv(LC.Op, LC.CC);
415  if (LC.Cond != ISD::SETCC_INVALID)
416  setCmpLibcallCC(LC.Op, LC.Cond);
417  }
418 
419  // EABI dependent RTLIB
420  if (TM.Options.EABIVersion == EABI::EABI4 ||
422  static const struct {
423  const RTLIB::Libcall Op;
424  const char *const Name;
425  const CallingConv::ID CC;
426  const ISD::CondCode Cond;
427  } MemOpsLibraryCalls[] = {
428  // Memory operations
429  // RTABI chapter 4.3.4
431  { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
432  { RTLIB::MEMSET, "__aeabi_memset", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
433  };
434 
435  for (const auto &LC : MemOpsLibraryCalls) {
436  setLibcallName(LC.Op, LC.Name);
437  setLibcallCallingConv(LC.Op, LC.CC);
438  if (LC.Cond != ISD::SETCC_INVALID)
439  setCmpLibcallCC(LC.Op, LC.Cond);
440  }
441  }
442  }
443 
444  if (Subtarget->isTargetWindows()) {
445  static const struct {
446  const RTLIB::Libcall Op;
447  const char * const Name;
448  const CallingConv::ID CC;
449  } LibraryCalls[] = {
450  { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP },
451  { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP },
452  { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP },
453  { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP },
454  { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP },
455  { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP },
456  { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP },
457  { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP },
458  };
459 
460  for (const auto &LC : LibraryCalls) {
461  setLibcallName(LC.Op, LC.Name);
462  setLibcallCallingConv(LC.Op, LC.CC);
463  }
464  }
465 
466  // Use divmod compiler-rt calls for iOS 5.0 and later.
467  if (Subtarget->isTargetMachO() &&
468  !(Subtarget->isTargetIOS() &&
469  Subtarget->getTargetTriple().isOSVersionLT(5, 0))) {
470  setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
471  setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
472  }
473 
474  // The half <-> float conversion functions are always soft-float on
475  // non-watchos platforms, but are needed for some targets which use a
476  // hard-float calling convention by default.
477  if (!Subtarget->isTargetWatchABI()) {
478  if (Subtarget->isAAPCS_ABI()) {
479  setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS);
480  setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS);
481  setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS);
482  } else {
483  setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS);
484  setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS);
485  setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS);
486  }
487  }
488 
489  // In EABI, these functions have an __aeabi_ prefix, but in GNUEABI they have
490  // a __gnu_ prefix (which is the default).
491  if (Subtarget->isTargetAEABI()) {
492  static const struct {
493  const RTLIB::Libcall Op;
494  const char * const Name;
495  const CallingConv::ID CC;
496  } LibraryCalls[] = {
497  { RTLIB::FPROUND_F32_F16, "__aeabi_f2h", CallingConv::ARM_AAPCS },
498  { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS },
499  { RTLIB::FPEXT_F16_F32, "__aeabi_h2f", CallingConv::ARM_AAPCS },
500  };
501 
502  for (const auto &LC : LibraryCalls) {
503  setLibcallName(LC.Op, LC.Name);
504  setLibcallCallingConv(LC.Op, LC.CC);
505  }
506  }
507 
508  if (Subtarget->isThumb1Only())
509  addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
510  else
511  addRegisterClass(MVT::i32, &ARM::GPRRegClass);
512 
513  if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2Base() &&
514  !Subtarget->isThumb1Only()) {
515  addRegisterClass(MVT::f32, &ARM::SPRRegClass);
516  addRegisterClass(MVT::f64, &ARM::DPRRegClass);
517  }
518 
519  if (Subtarget->hasFullFP16()) {
520  addRegisterClass(MVT::f16, &ARM::HPRRegClass);
524 
527  }
528 
529  for (MVT VT : MVT::vector_valuetypes()) {
530  for (MVT InnerVT : MVT::vector_valuetypes()) {
531  setTruncStoreAction(VT, InnerVT, Expand);
532  setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
533  setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
534  setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
535  }
536 
541 
543  }
544 
547 
550 
551  if (Subtarget->hasNEON()) {
552  addDRTypeForNEON(MVT::v2f32);
553  addDRTypeForNEON(MVT::v8i8);
554  addDRTypeForNEON(MVT::v4i16);
555  addDRTypeForNEON(MVT::v2i32);
556  addDRTypeForNEON(MVT::v1i64);
557 
558  addQRTypeForNEON(MVT::v4f32);
559  addQRTypeForNEON(MVT::v2f64);
560  addQRTypeForNEON(MVT::v16i8);
561  addQRTypeForNEON(MVT::v8i16);
562  addQRTypeForNEON(MVT::v4i32);
563  addQRTypeForNEON(MVT::v2i64);
564 
565  if (Subtarget->hasFullFP16()) {
566  addQRTypeForNEON(MVT::v8f16);
567  addDRTypeForNEON(MVT::v4f16);
568  }
569 
570  // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
571  // neither Neon nor VFP support any arithmetic operations on it.
572  // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
573  // supported for v4f32.
577  // FIXME: Code duplication: FDIV and FREM are expanded always, see
578  // ARMTargetLowering::addTypeForNEON method for details.
581  // FIXME: Create unittest.
582  // In another words, find a way when "copysign" appears in DAG with vector
583  // operands.
585  // FIXME: Code duplication: SETCC has custom operation action, see
586  // ARMTargetLowering::addTypeForNEON method for details.
588  // FIXME: Create unittest for FNEG and for FABS.
600  // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
607 
622 
623  // Mark v2f32 intrinsics.
638 
639  // Neon does not support some operations on v1i64 and v2i64 types.
641  // Custom handling for some quad-vector types to detect VMULL.
645  // Custom handling for some vector types to avoid expensive expansions
650  // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
651  // a destination type that is wider than the source, and nor does
652  // it have a FP_TO_[SU]INT instruction with a narrower destination than
653  // source.
662 
665 
666  // NEON does not have single instruction CTPOP for vectors with element
667  // types wider than 8-bits. However, custom lowering can leverage the
668  // v8i8/v16i8 vcnt instruction.
675 
678 
679  // NEON does not have single instruction CTTZ for vectors.
684 
689 
694 
699 
700  // NEON only has FMA instructions as of VFP4.
701  if (!Subtarget->hasVFP4Base()) {
704  }
705 
723 
724  // It is legal to extload from v4i8 to v4i16 or v4i32.
726  MVT::v2i32}) {
727  for (MVT VT : MVT::integer_vector_valuetypes()) {
731  }
732  }
733  }
734 
735  if (!Subtarget->hasFP64()) {
736  // When targeting a floating-point unit with only single-precision
737  // operations, f64 is legal for the few double-precision instructions which
738  // are present However, no double-precision operations other than moves,
739  // loads and stores are provided by the hardware.
772  }
773 
775 
776  // ARM does not have floating-point extending loads.
777  for (MVT VT : MVT::fp_valuetypes()) {
780  }
781 
782  // ... or truncating stores
786 
787  // ARM does not have i1 sign extending load.
788  for (MVT VT : MVT::integer_valuetypes())
790 
791  // ARM supports all 4 flavors of integer indexed load / store.
792  if (!Subtarget->isThumb1Only()) {
793  for (unsigned im = (unsigned)ISD::PRE_INC;
803  }
804  } else {
805  // Thumb-1 has limited post-inc load/store support - LDM r0!, {r1}.
808  }
809 
814 
817 
818  // i64 operation support.
821  if (Subtarget->isThumb1Only()) {
824  }
825  if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
826  || (Subtarget->isThumb2() && !Subtarget->hasDSP()))
828 
835 
836  // Expand to __aeabi_l{lsl,lsr,asr} calls for Thumb1.
837  if (Subtarget->isThumb1Only()) {
841  }
842 
843  if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops())
845 
846  // ARM does not have ROTL.
848  for (MVT VT : MVT::vector_valuetypes()) {
851  }
854  if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only()) {
857  }
858 
859  // @llvm.readcyclecounter requires the Performance Monitors extension.
860  // Default to the 0 expansion on unsupported platforms.
861  // FIXME: Technically there are older ARM CPUs that have
862  // implementation-specific ways of obtaining this information.
863  if (Subtarget->hasPerfMon())
865 
866  // Only ARMv6 has BSWAP.
867  if (!Subtarget->hasV6Ops())
869 
870  bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode()
871  : Subtarget->hasDivideInARMMode();
872  if (!hasDivide) {
873  // These are expanded into libcalls if the cpu doesn't have HW divider.
876  }
877 
878  if (Subtarget->isTargetWindows() && !Subtarget->hasDivideInThumbMode()) {
881 
884  }
885 
888 
889  // Register based DivRem for AEABI (RTABI 4.2)
890  if (Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() ||
891  Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() ||
892  Subtarget->isTargetWindows()) {
895  HasStandaloneRem = false;
896 
897  if (Subtarget->isTargetWindows()) {
898  const struct {
899  const RTLIB::Libcall Op;
900  const char * const Name;
901  const CallingConv::ID CC;
902  } LibraryCalls[] = {
903  { RTLIB::SDIVREM_I8, "__rt_sdiv", CallingConv::ARM_AAPCS },
904  { RTLIB::SDIVREM_I16, "__rt_sdiv", CallingConv::ARM_AAPCS },
905  { RTLIB::SDIVREM_I32, "__rt_sdiv", CallingConv::ARM_AAPCS },
906  { RTLIB::SDIVREM_I64, "__rt_sdiv64", CallingConv::ARM_AAPCS },
907 
908  { RTLIB::UDIVREM_I8, "__rt_udiv", CallingConv::ARM_AAPCS },
909  { RTLIB::UDIVREM_I16, "__rt_udiv", CallingConv::ARM_AAPCS },
910  { RTLIB::UDIVREM_I32, "__rt_udiv", CallingConv::ARM_AAPCS },
911  { RTLIB::UDIVREM_I64, "__rt_udiv64", CallingConv::ARM_AAPCS },
912  };
913 
914  for (const auto &LC : LibraryCalls) {
915  setLibcallName(LC.Op, LC.Name);
916  setLibcallCallingConv(LC.Op, LC.CC);
917  }
918  } else {
919  const struct {
920  const RTLIB::Libcall Op;
921  const char * const Name;
922  const CallingConv::ID CC;
923  } LibraryCalls[] = {
924  { RTLIB::SDIVREM_I8, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
925  { RTLIB::SDIVREM_I16, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
926  { RTLIB::SDIVREM_I32, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
927  { RTLIB::SDIVREM_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS },
928 
929  { RTLIB::UDIVREM_I8, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
930  { RTLIB::UDIVREM_I16, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
931  { RTLIB::UDIVREM_I32, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
932  { RTLIB::UDIVREM_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS },
933  };
934 
935  for (const auto &LC : LibraryCalls) {
936  setLibcallName(LC.Op, LC.Name);
937  setLibcallCallingConv(LC.Op, LC.CC);
938  }
939  }
940 
945  } else {
948  }
949 
950  if (Subtarget->isTargetWindows() && Subtarget->getTargetTriple().isOSMSVCRT())
951  for (auto &VT : {MVT::f32, MVT::f64})
953 
958 
961 
962  // Use the default implementation.
969 
970  if (Subtarget->isTargetWindows())
972  else
974 
975  // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
976  // the default expansion.
977  InsertFencesForAtomic = false;
978  if (Subtarget->hasAnyDataBarrier() &&
979  (!Subtarget->isThumb() || Subtarget->hasV8MBaselineOps())) {
980  // ATOMIC_FENCE needs custom lowering; the others should have been expanded
981  // to ldrex/strex loops already.
983  if (!Subtarget->isThumb() || !Subtarget->isMClass())
985 
986  // On v8, we have particularly efficient implementations of atomic fences
987  // if they can be combined with nearby atomic loads and stores.
988  if (!Subtarget->hasAcquireRelease() ||
989  getTargetMachine().getOptLevel() == 0) {
990  // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
991  InsertFencesForAtomic = true;
992  }
993  } else {
994  // If there's anything we can use as a barrier, go through custom lowering
995  // for ATOMIC_FENCE.
996  // If target has DMB in thumb, Fences can be inserted.
997  if (Subtarget->hasDataBarrier())
998  InsertFencesForAtomic = true;
999 
1001  Subtarget->hasAnyDataBarrier() ? Custom : Expand);
1002 
1003  // Set them all for expansion, which will force libcalls.
1016  // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
1017  // Unordered/Monotonic case.
1018  if (!InsertFencesForAtomic) {
1021  }
1022  }
1023 
1025 
1026  // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
1027  if (!Subtarget->hasV6Ops()) {
1030  }
1032 
1033  if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2Base() &&
1034  !Subtarget->isThumb1Only()) {
1035  // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
1036  // iff target supports vfp2.
1039  }
1040 
1041  // We want to custom lower some of our intrinsics.
1046  if (Subtarget->useSjLjEH())
1047  setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
1048 
1058  if (Subtarget->hasFullFP16()) {
1062  }
1063 
1065 
1068  if (Subtarget->hasFullFP16())
1073 
1074  // We don't support sin/cos/fmod/copysign/pow
1083  if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2Base() &&
1084  !Subtarget->isThumb1Only()) {
1087  }
1090 
1091  if (!Subtarget->hasVFP4Base()) {
1094  }
1095 
1096  // Various VFP goodness
1097  if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) {
1098  // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded.
1099  if (!Subtarget->hasFPARMv8Base() || !Subtarget->hasFP64()) {
1102  }
1103 
1104  // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
1105  if (!Subtarget->hasFP16()) {
1108  }
1109  }
1110 
1111  // Use __sincos_stret if available.
1112  if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr &&
1113  getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) {
1116  }
1117 
1118  // FP-ARMv8 implements a lot of rounding-like FP operations.
1119  if (Subtarget->hasFPARMv8Base()) {
1132 
1133  if (Subtarget->hasFP64()) {
1142  }
1143  }
1144 
1145  // FP16 often need to be promoted to call lib functions
1146  if (Subtarget->hasFullFP16()) {
1159 
1161  }
1162 
1163  if (Subtarget->hasNEON()) {
1164  // vmin and vmax aren't available in a scalar form, so we use
1165  // a NEON instruction with an undef lane instead.
1174 
1175  if (Subtarget->hasFullFP16()) {
1180 
1185  }
1186  }
1187 
1188  // We have target-specific dag combine patterns for the following nodes:
1189  // ARMISD::VMOVRRD - No need to call setTargetDAGCombine
1196 
1197  if (Subtarget->hasV6Ops())
1199  if (Subtarget->isThumb1Only())
1201 
1203 
1204  if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() ||
1205  !Subtarget->hasVFP2Base() || Subtarget->hasMinSize())
1207  else
1209 
1210  //// temporary - rewrite interface to use type
1211  MaxStoresPerMemset = 8;
1213  MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
1215  MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
1217 
1218  // On ARM arguments smaller than 4 bytes are extended, so all arguments
1219  // are at least 4 bytes aligned.
1221 
1222  // Prefer likely predicted branches to selects on out-of-order cores.
1223  PredictableSelectIsExpensive = Subtarget->getSchedModel().isOutOfOrder();
1224 
1226 
1227  setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
1228 
1229  if (Subtarget->isThumb() || Subtarget->isThumb2())
1231 }
1232 
1234  return Subtarget->useSoftFloat();
1235 }
1236 
1237 // FIXME: It might make sense to define the representative register class as the
1238 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
1239 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
1240 // SPR's representative would be DPR_VFP2. This should work well if register
1241 // pressure tracking were modified such that a register use would increment the
1242 // pressure of the register class's representative and all of it's super
1243 // classes' representatives transitively. We have not implemented this because
1244 // of the difficulty prior to coalescing of modeling operand register classes
1245 // due to the common occurrence of cross class copies and subregister insertions
1246 // and extractions.
1247 std::pair<const TargetRegisterClass *, uint8_t>
1249  MVT VT) const {
1250  const TargetRegisterClass *RRC = nullptr;
1251  uint8_t Cost = 1;
1252  switch (VT.SimpleTy) {
1253  default:
1255  // Use DPR as representative register class for all floating point
1256  // and vector types. Since there are 32 SPR registers and 32 DPR registers so
1257  // the cost is 1 for both f32 and f64.
1258  case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
1259  case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
1260  RRC = &ARM::DPRRegClass;
1261  // When NEON is used for SP, only half of the register file is available
1262  // because operations that define both SP and DP results will be constrained
1263  // to the VFP2 class (D0-D15). We currently model this constraint prior to
1264  // coalescing by double-counting the SP regs. See the FIXME above.
1265  if (Subtarget->useNEONForSinglePrecisionFP())
1266  Cost = 2;
1267  break;
1268  case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1269  case MVT::v4f32: case MVT::v2f64:
1270  RRC = &ARM::DPRRegClass;
1271  Cost = 2;
1272  break;
1273  case MVT::v4i64:
1274  RRC = &ARM::DPRRegClass;
1275  Cost = 4;
1276  break;
1277  case MVT::v8i64:
1278  RRC = &ARM::DPRRegClass;
1279  Cost = 8;
1280  break;
1281  }
1282  return std::make_pair(RRC, Cost);
1283 }
1284 
1285 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1286  switch ((ARMISD::NodeType)Opcode) {
1287  case ARMISD::FIRST_NUMBER: break;
1288  case ARMISD::Wrapper: return "ARMISD::Wrapper";
1289  case ARMISD::WrapperPIC: return "ARMISD::WrapperPIC";
1290  case ARMISD::WrapperJT: return "ARMISD::WrapperJT";
1291  case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL";
1292  case ARMISD::CALL: return "ARMISD::CALL";
1293  case ARMISD::CALL_PRED: return "ARMISD::CALL_PRED";
1294  case ARMISD::CALL_NOLINK: return "ARMISD::CALL_NOLINK";
1295  case ARMISD::BRCOND: return "ARMISD::BRCOND";
1296  case ARMISD::BR_JT: return "ARMISD::BR_JT";
1297  case ARMISD::BR2_JT: return "ARMISD::BR2_JT";
1298  case ARMISD::RET_FLAG: return "ARMISD::RET_FLAG";
1299  case ARMISD::INTRET_FLAG: return "ARMISD::INTRET_FLAG";
1300  case ARMISD::PIC_ADD: return "ARMISD::PIC_ADD";
1301  case ARMISD::CMP: return "ARMISD::CMP";
1302  case ARMISD::CMN: return "ARMISD::CMN";
1303  case ARMISD::CMPZ: return "ARMISD::CMPZ";
1304  case ARMISD::CMPFP: return "ARMISD::CMPFP";
1305  case ARMISD::CMPFPw0: return "ARMISD::CMPFPw0";
1306  case ARMISD::BCC_i64: return "ARMISD::BCC_i64";
1307  case ARMISD::FMSTAT: return "ARMISD::FMSTAT";
1308 
1309  case ARMISD::CMOV: return "ARMISD::CMOV";
1310  case ARMISD::SUBS: return "ARMISD::SUBS";
1311 
1312  case ARMISD::SSAT: return "ARMISD::SSAT";
1313  case ARMISD::USAT: return "ARMISD::USAT";
1314 
1315  case ARMISD::SRL_FLAG: return "ARMISD::SRL_FLAG";
1316  case ARMISD::SRA_FLAG: return "ARMISD::SRA_FLAG";
1317  case ARMISD::RRX: return "ARMISD::RRX";
1318 
1319  case ARMISD::ADDC: return "ARMISD::ADDC";
1320  case ARMISD::ADDE: return "ARMISD::ADDE";
1321  case ARMISD::SUBC: return "ARMISD::SUBC";
1322  case ARMISD::SUBE: return "ARMISD::SUBE";
1323 
1324  case ARMISD::VMOVRRD: return "ARMISD::VMOVRRD";
1325  case ARMISD::VMOVDRR: return "ARMISD::VMOVDRR";
1326  case ARMISD::VMOVhr: return "ARMISD::VMOVhr";
1327  case ARMISD::VMOVrh: return "ARMISD::VMOVrh";
1328  case ARMISD::VMOVSR: return "ARMISD::VMOVSR";
1329 
1330  case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1331  case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP";
1332  case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH";
1333 
1334  case ARMISD::TC_RETURN: return "ARMISD::TC_RETURN";
1335 
1336  case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1337 
1338  case ARMISD::DYN_ALLOC: return "ARMISD::DYN_ALLOC";
1339 
1340  case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1341 
1342  case ARMISD::PRELOAD: return "ARMISD::PRELOAD";
1343 
1344  case ARMISD::WIN__CHKSTK: return "ARMISD::WIN__CHKSTK";
1345  case ARMISD::WIN__DBZCHK: return "ARMISD::WIN__DBZCHK";
1346 
1347  case ARMISD::VCEQ: return "ARMISD::VCEQ";
1348  case ARMISD::VCEQZ: return "ARMISD::VCEQZ";
1349  case ARMISD::VCGE: return "ARMISD::VCGE";
1350  case ARMISD::VCGEZ: return "ARMISD::VCGEZ";
1351  case ARMISD::VCLEZ: return "ARMISD::VCLEZ";
1352  case ARMISD::VCGEU: return "ARMISD::VCGEU";
1353  case ARMISD::VCGT: return "ARMISD::VCGT";
1354  case ARMISD::VCGTZ: return "ARMISD::VCGTZ";
1355  case ARMISD::VCLTZ: return "ARMISD::VCLTZ";
1356  case ARMISD::VCGTU: return "ARMISD::VCGTU";
1357  case ARMISD::VTST: return "ARMISD::VTST";
1358 
1359  case ARMISD::VSHL: return "ARMISD::VSHL";
1360  case ARMISD::VSHRs: return "ARMISD::VSHRs";
1361  case ARMISD::VSHRu: return "ARMISD::VSHRu";
1362  case ARMISD::VRSHRs: return "ARMISD::VRSHRs";
1363  case ARMISD::VRSHRu: return "ARMISD::VRSHRu";
1364  case ARMISD::VRSHRN: return "ARMISD::VRSHRN";
1365  case ARMISD::VQSHLs: return "ARMISD::VQSHLs";
1366  case ARMISD::VQSHLu: return "ARMISD::VQSHLu";
1367  case ARMISD::VQSHLsu: return "ARMISD::VQSHLsu";
1368  case ARMISD::VQSHRNs: return "ARMISD::VQSHRNs";
1369  case ARMISD::VQSHRNu: return "ARMISD::VQSHRNu";
1370  case ARMISD::VQSHRNsu: return "ARMISD::VQSHRNsu";
1371  case ARMISD::VQRSHRNs: return "ARMISD::VQRSHRNs";
1372  case ARMISD::VQRSHRNu: return "ARMISD::VQRSHRNu";
1373  case ARMISD::VQRSHRNsu: return "ARMISD::VQRSHRNsu";
1374  case ARMISD::VSLI: return "ARMISD::VSLI";
1375  case ARMISD::VSRI: return "ARMISD::VSRI";
1376  case ARMISD::VGETLANEu: return "ARMISD::VGETLANEu";
1377  case ARMISD::VGETLANEs: return "ARMISD::VGETLANEs";
1378  case ARMISD::VMOVIMM: return "ARMISD::VMOVIMM";
1379  case ARMISD::VMVNIMM: return "ARMISD::VMVNIMM";
1380  case ARMISD::VMOVFPIMM: return "ARMISD::VMOVFPIMM";
1381  case ARMISD::VDUP: return "ARMISD::VDUP";
1382  case ARMISD::VDUPLANE: return "ARMISD::VDUPLANE";
1383  case ARMISD::VEXT: return "ARMISD::VEXT";
1384  case ARMISD::VREV64: return "ARMISD::VREV64";
1385  case ARMISD::VREV32: return "ARMISD::VREV32";
1386  case ARMISD::VREV16: return "ARMISD::VREV16";
1387  case ARMISD::VZIP: return "ARMISD::VZIP";
1388  case ARMISD::VUZP: return "ARMISD::VUZP";
1389  case ARMISD::VTRN: return "ARMISD::VTRN";
1390  case ARMISD::VTBL1: return "ARMISD::VTBL1";
1391  case ARMISD::VTBL2: return "ARMISD::VTBL2";
1392  case ARMISD::VMULLs: return "ARMISD::VMULLs";
1393  case ARMISD::VMULLu: return "ARMISD::VMULLu";
1394  case ARMISD::UMAAL: return "ARMISD::UMAAL";
1395  case ARMISD::UMLAL: return "ARMISD::UMLAL";
1396  case ARMISD::SMLAL: return "ARMISD::SMLAL";
1397  case ARMISD::SMLALBB: return "ARMISD::SMLALBB";
1398  case ARMISD::SMLALBT: return "ARMISD::SMLALBT";
1399  case ARMISD::SMLALTB: return "ARMISD::SMLALTB";
1400  case ARMISD::SMLALTT: return "ARMISD::SMLALTT";
1401  case ARMISD::SMULWB: return "ARMISD::SMULWB";
1402  case ARMISD::SMULWT: return "ARMISD::SMULWT";
1403  case ARMISD::SMLALD: return "ARMISD::SMLALD";
1404  case ARMISD::SMLALDX: return "ARMISD::SMLALDX";
1405  case ARMISD::SMLSLD: return "ARMISD::SMLSLD";
1406  case ARMISD::SMLSLDX: return "ARMISD::SMLSLDX";
1407  case ARMISD::SMMLAR: return "ARMISD::SMMLAR";
1408  case ARMISD::SMMLSR: return "ARMISD::SMMLSR";
1409  case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR";
1410  case ARMISD::BFI: return "ARMISD::BFI";
1411  case ARMISD::VORRIMM: return "ARMISD::VORRIMM";
1412  case ARMISD::VBICIMM: return "ARMISD::VBICIMM";
1413  case ARMISD::VBSL: return "ARMISD::VBSL";
1414  case ARMISD::MEMCPY: return "ARMISD::MEMCPY";
1415  case ARMISD::VLD1DUP: return "ARMISD::VLD1DUP";
1416  case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP";
1417  case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP";
1418  case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP";
1419  case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD";
1420  case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD";
1421  case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD";
1422  case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD";
1423  case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD";
1424  case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD";
1425  case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD";
1426  case ARMISD::VLD1DUP_UPD: return "ARMISD::VLD1DUP_UPD";
1427  case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD";
1428  case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD";
1429  case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD";
1430  case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD";
1431  case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD";
1432  case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD";
1433  case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD";
1434  case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD";
1435  case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD";
1436  case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD";
1437  }
1438  return nullptr;
1439 }
1440 
1442  EVT VT) const {
1443  if (!VT.isVector())
1444  return getPointerTy(DL);
1446 }
1447 
1448 /// getRegClassFor - Return the register class that should be used for the
1449 /// specified value type.
1450 const TargetRegisterClass *
1451 ARMTargetLowering::getRegClassFor(MVT VT, bool isDivergent) const {
1452  (void)isDivergent;
1453  // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1454  // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1455  // load / store 4 to 8 consecutive D registers.
1456  if (Subtarget->hasNEON()) {
1457  if (VT == MVT::v4i64)
1458  return &ARM::QQPRRegClass;
1459  if (VT == MVT::v8i64)
1460  return &ARM::QQQQPRRegClass;
1461  }
1462  return TargetLowering::getRegClassFor(VT);
1463 }
1464 
1465 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the
1466 // source/dest is aligned and the copy size is large enough. We therefore want
1467 // to align such objects passed to memory intrinsics.
1469  unsigned &PrefAlign) const {
1470  if (!isa<MemIntrinsic>(CI))
1471  return false;
1472  MinSize = 8;
1473  // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1
1474  // cycle faster than 4-byte aligned LDM.
1475  PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4);
1476  return true;
1477 }
1478 
1479 // Create a fast isel object.
1480 FastISel *
1482  const TargetLibraryInfo *libInfo) const {
1483  return ARM::createFastISel(funcInfo, libInfo);
1484 }
1485 
1487  unsigned NumVals = N->getNumValues();
1488  if (!NumVals)
1489  return Sched::RegPressure;
1490 
1491  for (unsigned i = 0; i != NumVals; ++i) {
1492  EVT VT = N->getValueType(i);
1493  if (VT == MVT::Glue || VT == MVT::Other)
1494  continue;
1495  if (VT.isFloatingPoint() || VT.isVector())
1496  return Sched::ILP;
1497  }
1498 
1499  if (!N->isMachineOpcode())
1500  return Sched::RegPressure;
1501 
1502  // Load are scheduled for latency even if there instruction itinerary
1503  // is not available.
1504  const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1505  const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1506 
1507  if (MCID.getNumDefs() == 0)
1508  return Sched::RegPressure;
1509  if (!Itins->isEmpty() &&
1510  Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1511  return Sched::ILP;
1512 
1513  return Sched::RegPressure;
1514 }
1515 
1516 //===----------------------------------------------------------------------===//
1517 // Lowering Code
1518 //===----------------------------------------------------------------------===//
1519 
1520 static bool isSRL16(const SDValue &Op) {
1521  if (Op.getOpcode() != ISD::SRL)
1522  return false;
1523  if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1524  return Const->getZExtValue() == 16;
1525  return false;
1526 }
1527 
1528 static bool isSRA16(const SDValue &Op) {
1529  if (Op.getOpcode() != ISD::SRA)
1530  return false;
1531  if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1532  return Const->getZExtValue() == 16;
1533  return false;
1534 }
1535 
1536 static bool isSHL16(const SDValue &Op) {
1537  if (Op.getOpcode() != ISD::SHL)
1538  return false;
1539  if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1540  return Const->getZExtValue() == 16;
1541  return false;
1542 }
1543 
1544 // Check for a signed 16-bit value. We special case SRA because it makes it
1545 // more simple when also looking for SRAs that aren't sign extending a
1546 // smaller value. Without the check, we'd need to take extra care with
1547 // checking order for some operations.
1548 static bool isS16(const SDValue &Op, SelectionDAG &DAG) {
1549  if (isSRA16(Op))
1550  return isSHL16(Op.getOperand(0));
1551  return DAG.ComputeNumSignBits(Op) == 17;
1552 }
1553 
1554 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1556  switch (CC) {
1557  default: llvm_unreachable("Unknown condition code!");
1558  case ISD::SETNE: return ARMCC::NE;
1559  case ISD::SETEQ: return ARMCC::EQ;
1560  case ISD::SETGT: return ARMCC::GT;
1561  case ISD::SETGE: return ARMCC::GE;
1562  case ISD::SETLT: return ARMCC::LT;
1563  case ISD::SETLE: return ARMCC::LE;
1564  case ISD::SETUGT: return ARMCC::HI;
1565  case ISD::SETUGE: return ARMCC::HS;
1566  case ISD::SETULT: return ARMCC::LO;
1567  case ISD::SETULE: return ARMCC::LS;
1568  }
1569 }
1570 
1571 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1573  ARMCC::CondCodes &CondCode2, bool &InvalidOnQNaN) {
1574  CondCode2 = ARMCC::AL;
1575  InvalidOnQNaN = true;
1576  switch (CC) {
1577  default: llvm_unreachable("Unknown FP condition!");
1578  case ISD::SETEQ:
1579  case ISD::SETOEQ:
1580  CondCode = ARMCC::EQ;
1581  InvalidOnQNaN = false;
1582  break;
1583  case ISD::SETGT:
1584  case ISD::SETOGT: CondCode = ARMCC::GT; break;
1585  case ISD::SETGE:
1586  case ISD::SETOGE: CondCode = ARMCC::GE; break;
1587  case ISD::SETOLT: CondCode = ARMCC::MI; break;
1588  case ISD::SETOLE: CondCode = ARMCC::LS; break;
1589  case ISD::SETONE:
1590  CondCode = ARMCC::MI;
1591  CondCode2 = ARMCC::GT;
1592  InvalidOnQNaN = false;
1593  break;
1594  case ISD::SETO: CondCode = ARMCC::VC; break;
1595  case ISD::SETUO: CondCode = ARMCC::VS; break;
1596  case ISD::SETUEQ:
1597  CondCode = ARMCC::EQ;
1598  CondCode2 = ARMCC::VS;
1599  InvalidOnQNaN = false;
1600  break;
1601  case ISD::SETUGT: CondCode = ARMCC::HI; break;
1602  case ISD::SETUGE: CondCode = ARMCC::PL; break;
1603  case ISD::SETLT:
1604  case ISD::SETULT: CondCode = ARMCC::LT; break;
1605  case ISD::SETLE:
1606  case ISD::SETULE: CondCode = ARMCC::LE; break;
1607  case ISD::SETNE:
1608  case ISD::SETUNE:
1609  CondCode = ARMCC::NE;
1610  InvalidOnQNaN = false;
1611  break;
1612  }
1613 }
1614 
1615 //===----------------------------------------------------------------------===//
1616 // Calling Convention Implementation
1617 //===----------------------------------------------------------------------===//
1618 
1619 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1620 /// account presence of floating point hardware and calling convention
1621 /// limitations, such as support for variadic functions.
1623 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1624  bool isVarArg) const {
1625  switch (CC) {
1626  default:
1627  report_fatal_error("Unsupported calling convention");
1629  case CallingConv::ARM_APCS:
1630  case CallingConv::GHC:
1631  return CC;
1635  case CallingConv::Swift:
1637  case CallingConv::C:
1638  if (!Subtarget->isAAPCS_ABI())
1639  return CallingConv::ARM_APCS;
1640  else if (Subtarget->hasVFP2Base() && !Subtarget->isThumb1Only() &&
1642  !isVarArg)
1644  else
1645  return CallingConv::ARM_AAPCS;
1646  case CallingConv::Fast:
1648  if (!Subtarget->isAAPCS_ABI()) {
1649  if (Subtarget->hasVFP2Base() && !Subtarget->isThumb1Only() && !isVarArg)
1650  return CallingConv::Fast;
1651  return CallingConv::ARM_APCS;
1652  } else if (Subtarget->hasVFP2Base() &&
1653  !Subtarget->isThumb1Only() && !isVarArg)
1655  else
1656  return CallingConv::ARM_AAPCS;
1657  }
1658 }
1659 
1661  bool isVarArg) const {
1662  return CCAssignFnForNode(CC, false, isVarArg);
1663 }
1664 
1666  bool isVarArg) const {
1667  return CCAssignFnForNode(CC, true, isVarArg);
1668 }
1669 
1670 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1671 /// CallingConvention.
1672 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1673  bool Return,
1674  bool isVarArg) const {
1675  switch (getEffectiveCallingConv(CC, isVarArg)) {
1676  default:
1677  report_fatal_error("Unsupported calling convention");
1678  case CallingConv::ARM_APCS:
1679  return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1681  return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1683  return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1684  case CallingConv::Fast:
1685  return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1686  case CallingConv::GHC:
1687  return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1689  return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1690  }
1691 }
1692 
1693 /// LowerCallResult - Lower the result values of a call into the
1694 /// appropriate copies out of appropriate physical registers.
1695 SDValue ARMTargetLowering::LowerCallResult(
1696  SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
1697  const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
1698  SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
1699  SDValue ThisVal) const {
1700  // Assign locations to each value returned by this call.
1702  CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1703  *DAG.getContext());
1704  CCInfo.AnalyzeCallResult(Ins, CCAssignFnForReturn(CallConv, isVarArg));
1705 
1706  // Copy all of the result registers out of their specified physreg.
1707  for (unsigned i = 0; i != RVLocs.size(); ++i) {
1708  CCValAssign VA = RVLocs[i];
1709 
1710  // Pass 'this' value directly from the argument to return value, to avoid
1711  // reg unit interference
1712  if (i == 0 && isThisReturn) {
1713  assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1714  "unexpected return calling convention register assignment");
1715  InVals.push_back(ThisVal);
1716  continue;
1717  }
1718 
1719  SDValue Val;
1720  if (VA.needsCustom()) {
1721  // Handle f64 or half of a v2f64.
1722  SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1723  InFlag);
1724  Chain = Lo.getValue(1);
1725  InFlag = Lo.getValue(2);
1726  VA = RVLocs[++i]; // skip ahead to next loc
1727  SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1728  InFlag);
1729  Chain = Hi.getValue(1);
1730  InFlag = Hi.getValue(2);
1731  if (!Subtarget->isLittle())
1732  std::swap (Lo, Hi);
1733  Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1734 
1735  if (VA.getLocVT() == MVT::v2f64) {
1736  SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1737  Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1738  DAG.getConstant(0, dl, MVT::i32));
1739 
1740  VA = RVLocs[++i]; // skip ahead to next loc
1741  Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1742  Chain = Lo.getValue(1);
1743  InFlag = Lo.getValue(2);
1744  VA = RVLocs[++i]; // skip ahead to next loc
1745  Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1746  Chain = Hi.getValue(1);
1747  InFlag = Hi.getValue(2);
1748  if (!Subtarget->isLittle())
1749  std::swap (Lo, Hi);
1750  Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1751  Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1752  DAG.getConstant(1, dl, MVT::i32));
1753  }
1754  } else {
1755  Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1756  InFlag);
1757  Chain = Val.getValue(1);
1758  InFlag = Val.getValue(2);
1759  }
1760 
1761  switch (VA.getLocInfo()) {
1762  default: llvm_unreachable("Unknown loc info!");
1763  case CCValAssign::Full: break;
1764  case CCValAssign::BCvt:
1765  Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1766  break;
1767  }
1768 
1769  InVals.push_back(Val);
1770  }
1771 
1772  return Chain;
1773 }
1774 
1775 /// LowerMemOpCallTo - Store the argument to the stack.
1776 SDValue ARMTargetLowering::LowerMemOpCallTo(SDValue Chain, SDValue StackPtr,
1777  SDValue Arg, const SDLoc &dl,
1778  SelectionDAG &DAG,
1779  const CCValAssign &VA,
1780  ISD::ArgFlagsTy Flags) const {
1781  unsigned LocMemOffset = VA.getLocMemOffset();
1782  SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1783  PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
1784  StackPtr, PtrOff);
1785  return DAG.getStore(
1786  Chain, dl, Arg, PtrOff,
1787  MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset));
1788 }
1789 
1790 void ARMTargetLowering::PassF64ArgInRegs(const SDLoc &dl, SelectionDAG &DAG,
1791  SDValue Chain, SDValue &Arg,
1792  RegsToPassVector &RegsToPass,
1793  CCValAssign &VA, CCValAssign &NextVA,
1794  SDValue &StackPtr,
1795  SmallVectorImpl<SDValue> &MemOpChains,
1796  ISD::ArgFlagsTy Flags) const {
1797  SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1798  DAG.getVTList(MVT::i32, MVT::i32), Arg);
1799  unsigned id = Subtarget->isLittle() ? 0 : 1;
1800  RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1801 
1802  if (NextVA.isRegLoc())
1803  RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1804  else {
1805  assert(NextVA.isMemLoc());
1806  if (!StackPtr.getNode())
1807  StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP,
1808  getPointerTy(DAG.getDataLayout()));
1809 
1810  MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1811  dl, DAG, NextVA,
1812  Flags));
1813  }
1814 }
1815 
1816 /// LowerCall - Lowering a call into a callseq_start <-
1817 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1818 /// nodes.
1819 SDValue
1820 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1821  SmallVectorImpl<SDValue> &InVals) const {
1822  SelectionDAG &DAG = CLI.DAG;
1823  SDLoc &dl = CLI.DL;
1825  SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
1827  SDValue Chain = CLI.Chain;
1828  SDValue Callee = CLI.Callee;
1829  bool &isTailCall = CLI.IsTailCall;
1830  CallingConv::ID CallConv = CLI.CallConv;
1831  bool doesNotRet = CLI.DoesNotReturn;
1832  bool isVarArg = CLI.IsVarArg;
1833 
1834  MachineFunction &MF = DAG.getMachineFunction();
1835  bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1836  bool isThisReturn = false;
1837  auto Attr = MF.getFunction().getFnAttribute("disable-tail-calls");
1838  bool PreferIndirect = false;
1839 
1840  // Disable tail calls if they're not supported.
1841  if (!Subtarget->supportsTailCall() || Attr.getValueAsString() == "true")
1842  isTailCall = false;
1843 
1844  if (isa<GlobalAddressSDNode>(Callee)) {
1845  // If we're optimizing for minimum size and the function is called three or
1846  // more times in this block, we can improve codesize by calling indirectly
1847  // as BLXr has a 16-bit encoding.
1848  auto *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal();
1849  auto *BB = CLI.CS.getParent();
1850  PreferIndirect =
1851  Subtarget->isThumb() && Subtarget->hasMinSize() &&
1852  count_if(GV->users(), [&BB](const User *U) {
1853  return isa<Instruction>(U) && cast<Instruction>(U)->getParent() == BB;
1854  }) > 2;
1855  }
1856  if (isTailCall) {
1857  // Check if it's really possible to do a tail call.
1858  isTailCall = IsEligibleForTailCallOptimization(
1859  Callee, CallConv, isVarArg, isStructRet,
1860  MF.getFunction().hasStructRetAttr(), Outs, OutVals, Ins, DAG,
1861  PreferIndirect);
1862  if (!isTailCall && CLI.CS && CLI.CS.isMustTailCall())
1863  report_fatal_error("failed to perform tail call elimination on a call "
1864  "site marked musttail");
1865  // We don't support GuaranteedTailCallOpt for ARM, only automatically
1866  // detected sibcalls.
1867  if (isTailCall)
1868  ++NumTailCalls;
1869  }
1870 
1871  // Analyze operands of the call, assigning locations to each operand.
1873  CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1874  *DAG.getContext());
1875  CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CallConv, isVarArg));
1876 
1877  // Get a count of how many bytes are to be pushed on the stack.
1878  unsigned NumBytes = CCInfo.getNextStackOffset();
1879 
1880  if (isTailCall) {
1881  // For tail calls, memory operands are available in our caller's stack.
1882  NumBytes = 0;
1883  } else {
1884  // Adjust the stack pointer for the new arguments...
1885  // These operations are automatically eliminated by the prolog/epilog pass
1886  Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
1887  }
1888 
1889  SDValue StackPtr =
1890  DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout()));
1891 
1892  RegsToPassVector RegsToPass;
1893  SmallVector<SDValue, 8> MemOpChains;
1894 
1895  // Walk the register/memloc assignments, inserting copies/loads. In the case
1896  // of tail call optimization, arguments are handled later.
1897  for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1898  i != e;
1899  ++i, ++realArgIdx) {
1900  CCValAssign &VA = ArgLocs[i];
1901  SDValue Arg = OutVals[realArgIdx];
1902  ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1903  bool isByVal = Flags.isByVal();
1904 
1905  // Promote the value if needed.
1906  switch (VA.getLocInfo()) {
1907  default: llvm_unreachable("Unknown loc info!");
1908  case CCValAssign::Full: break;
1909  case CCValAssign::SExt:
1910  Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1911  break;
1912  case CCValAssign::ZExt:
1913  Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1914  break;
1915  case CCValAssign::AExt:
1916  Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1917  break;
1918  case CCValAssign::BCvt:
1919  Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1920  break;
1921  }
1922 
1923  // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1924  if (VA.needsCustom()) {
1925  if (VA.getLocVT() == MVT::v2f64) {
1926  SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1927  DAG.getConstant(0, dl, MVT::i32));
1928  SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1929  DAG.getConstant(1, dl, MVT::i32));
1930 
1931  PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1932  VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1933 
1934  VA = ArgLocs[++i]; // skip ahead to next loc
1935  if (VA.isRegLoc()) {
1936  PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1937  VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1938  } else {
1939  assert(VA.isMemLoc());
1940 
1941  MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1942  dl, DAG, VA, Flags));
1943  }
1944  } else {
1945  PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1946  StackPtr, MemOpChains, Flags);
1947  }
1948  } else if (VA.isRegLoc()) {
1949  if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() &&
1950  Outs[0].VT == MVT::i32) {
1951  assert(VA.getLocVT() == MVT::i32 &&
1952  "unexpected calling convention register assignment");
1953  assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1954  "unexpected use of 'returned'");
1955  isThisReturn = true;
1956  }
1957  RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1958  } else if (isByVal) {
1959  assert(VA.isMemLoc());
1960  unsigned offset = 0;
1961 
1962  // True if this byval aggregate will be split between registers
1963  // and memory.
1964  unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1965  unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
1966 
1967  if (CurByValIdx < ByValArgsCount) {
1968 
1969  unsigned RegBegin, RegEnd;
1970  CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1971 
1972  EVT PtrVT =
1974  unsigned int i, j;
1975  for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1976  SDValue Const = DAG.getConstant(4*i, dl, MVT::i32);
1977  SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1978  SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1980  DAG.InferPtrAlignment(AddArg));
1981  MemOpChains.push_back(Load.getValue(1));
1982  RegsToPass.push_back(std::make_pair(j, Load));
1983  }
1984 
1985  // If parameter size outsides register area, "offset" value
1986  // helps us to calculate stack slot for remained part properly.
1987  offset = RegEnd - RegBegin;
1988 
1989  CCInfo.nextInRegsParam();
1990  }
1991 
1992  if (Flags.getByValSize() > 4*offset) {
1993  auto PtrVT = getPointerTy(DAG.getDataLayout());
1994  unsigned LocMemOffset = VA.getLocMemOffset();
1995  SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1996  SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff);
1997  SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl);
1998  SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset);
1999  SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl,
2000  MVT::i32);
2001  SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl,
2002  MVT::i32);
2003 
2004  SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
2005  SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
2006  MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
2007  Ops));
2008  }
2009  } else if (!isTailCall) {
2010  assert(VA.isMemLoc());
2011 
2012  MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2013  dl, DAG, VA, Flags));
2014  }
2015  }
2016 
2017  if (!MemOpChains.empty())
2018  Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2019 
2020  // Build a sequence of copy-to-reg nodes chained together with token chain
2021  // and flag operands which copy the outgoing args into the appropriate regs.
2022  SDValue InFlag;
2023  for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2024  Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2025  RegsToPass[i].second, InFlag);
2026  InFlag = Chain.getValue(1);
2027  }
2028 
2029  // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2030  // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2031  // node so that legalize doesn't hack it.
2032  bool isDirect = false;
2033 
2034  const TargetMachine &TM = getTargetMachine();
2035  const Module *Mod = MF.getFunction().getParent();
2036  const GlobalValue *GV = nullptr;
2037  if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
2038  GV = G->getGlobal();
2039  bool isStub =
2040  !TM.shouldAssumeDSOLocal(*Mod, GV) && Subtarget->isTargetMachO();
2041 
2042  bool isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
2043  bool isLocalARMFunc = false;
2045  auto PtrVt = getPointerTy(DAG.getDataLayout());
2046 
2047  if (Subtarget->genLongCalls()) {
2048  assert((!isPositionIndependent() || Subtarget->isTargetWindows()) &&
2049  "long-calls codegen is not position independent!");
2050  // Handle a global address or an external symbol. If it's not one of
2051  // those, the target's already in a register, so we don't need to do
2052  // anything extra.
2053  if (isa<GlobalAddressSDNode>(Callee)) {
2054  // Create a constant pool entry for the callee address
2055  unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2056  ARMConstantPoolValue *CPV =
2057  ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
2058 
2059  // Get the address of the callee into a register
2060  SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
2061  CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2062  Callee = DAG.getLoad(
2063  PtrVt, dl, DAG.getEntryNode(), CPAddr,
2065  } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
2066  const char *Sym = S->getSymbol();
2067 
2068  // Create a constant pool entry for the callee address
2069  unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2070  ARMConstantPoolValue *CPV =
2072  ARMPCLabelIndex, 0);
2073  // Get the address of the callee into a register
2074  SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
2075  CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2076  Callee = DAG.getLoad(
2077  PtrVt, dl, DAG.getEntryNode(), CPAddr,
2079  }
2080  } else if (isa<GlobalAddressSDNode>(Callee)) {
2081  if (!PreferIndirect) {
2082  isDirect = true;
2083  bool isDef = GV->isStrongDefinitionForLinker();
2084 
2085  // ARM call to a local ARM function is predicable.
2086  isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking);
2087  // tBX takes a register source operand.
2088  if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
2089  assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
2090  Callee = DAG.getNode(
2091  ARMISD::WrapperPIC, dl, PtrVt,
2092  DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY));
2093  Callee = DAG.getLoad(
2094  PtrVt, dl, DAG.getEntryNode(), Callee,
2096  /* Alignment = */ 0, MachineMemOperand::MODereferenceable |
2098  } else if (Subtarget->isTargetCOFF()) {
2099  assert(Subtarget->isTargetWindows() &&
2100  "Windows is the only supported COFF target");
2101  unsigned TargetFlags = GV->hasDLLImportStorageClass()
2104  Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*Offset=*/0,
2105  TargetFlags);
2106  if (GV->hasDLLImportStorageClass())
2107  Callee =
2108  DAG.getLoad(PtrVt, dl, DAG.getEntryNode(),
2109  DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee),
2111  } else {
2112  Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, 0);
2113  }
2114  }
2115  } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2116  isDirect = true;
2117  // tBX takes a register source operand.
2118  const char *Sym = S->getSymbol();
2119  if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
2120  unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2121  ARMConstantPoolValue *CPV =
2123  ARMPCLabelIndex, 4);
2124  SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
2125  CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2126  Callee = DAG.getLoad(
2127  PtrVt, dl, DAG.getEntryNode(), CPAddr,
2129  SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2130  Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel);
2131  } else {
2132  Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, 0);
2133  }
2134  }
2135 
2136  // FIXME: handle tail calls differently.
2137  unsigned CallOpc;
2138  if (Subtarget->isThumb()) {
2139  if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
2140  CallOpc = ARMISD::CALL_NOLINK;
2141  else
2142  CallOpc = ARMISD::CALL;
2143  } else {
2144  if (!isDirect && !Subtarget->hasV5TOps())
2145  CallOpc = ARMISD::CALL_NOLINK;
2146  else if (doesNotRet && isDirect && Subtarget->hasRetAddrStack() &&
2147  // Emit regular call when code size is the priority
2148  !Subtarget->hasMinSize())
2149  // "mov lr, pc; b _foo" to avoid confusing the RSP
2150  CallOpc = ARMISD::CALL_NOLINK;
2151  else
2152  CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
2153  }
2154 
2155  std::vector<SDValue> Ops;
2156  Ops.push_back(Chain);
2157  Ops.push_back(Callee);
2158 
2159  // Add argument registers to the end of the list so that they are known live
2160  // into the call.
2161  for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2162  Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2163  RegsToPass[i].second.getValueType()));
2164 
2165  // Add a register mask operand representing the call-preserved registers.
2166  if (!isTailCall) {
2167  const uint32_t *Mask;
2168  const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
2169  if (isThisReturn) {
2170  // For 'this' returns, use the R0-preserving mask if applicable
2171  Mask = ARI->getThisReturnPreservedMask(MF, CallConv);
2172  if (!Mask) {
2173  // Set isThisReturn to false if the calling convention is not one that
2174  // allows 'returned' to be modeled in this way, so LowerCallResult does
2175  // not try to pass 'this' straight through
2176  isThisReturn = false;
2177  Mask = ARI->getCallPreservedMask(MF, CallConv);
2178  }
2179  } else
2180  Mask = ARI->getCallPreservedMask(MF, CallConv);
2181 
2182  assert(Mask && "Missing call preserved mask for calling convention");
2183  Ops.push_back(DAG.getRegisterMask(Mask));
2184  }
2185 
2186  if (InFlag.getNode())
2187  Ops.push_back(InFlag);
2188 
2189  SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2190  if (isTailCall) {
2192  return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
2193  }
2194 
2195  // Returns a chain and a flag for retval copy to use.
2196  Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
2197  InFlag = Chain.getValue(1);
2198 
2199  Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
2200  DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
2201  if (!Ins.empty())
2202  InFlag = Chain.getValue(1);
2203 
2204  // Handle result values, copying them out of physregs into vregs that we
2205  // return.
2206  return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
2207  InVals, isThisReturn,
2208  isThisReturn ? OutVals[0] : SDValue());
2209 }
2210 
2211 /// HandleByVal - Every parameter *after* a byval parameter is passed
2212 /// on the stack. Remember the next parameter register to allocate,
2213 /// and then confiscate the rest of the parameter registers to insure
2214 /// this.
2215 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size,
2216  unsigned Align) const {
2217  // Byval (as with any stack) slots are always at least 4 byte aligned.
2218  Align = std::max(Align, 4U);
2219 
2220  unsigned Reg = State->AllocateReg(GPRArgRegs);
2221  if (!Reg)
2222  return;
2223 
2224  unsigned AlignInRegs = Align / 4;
2225  unsigned Waste = (ARM::R4 - Reg) % AlignInRegs;
2226  for (unsigned i = 0; i < Waste; ++i)
2227  Reg = State->AllocateReg(GPRArgRegs);
2228 
2229  if (!Reg)
2230  return;
2231 
2232  unsigned Excess = 4 * (ARM::R4 - Reg);
2233 
2234  // Special case when NSAA != SP and parameter size greater than size of
2235  // all remained GPR regs. In that case we can't split parameter, we must
2236  // send it to stack. We also must set NCRN to R4, so waste all
2237  // remained registers.
2238  const unsigned NSAAOffset = State->getNextStackOffset();
2239  if (NSAAOffset != 0 && Size > Excess) {
2240  while (State->AllocateReg(GPRArgRegs))
2241  ;
2242  return;
2243  }
2244 
2245  // First register for byval parameter is the first register that wasn't
2246  // allocated before this method call, so it would be "reg".
2247  // If parameter is small enough to be saved in range [reg, r4), then
2248  // the end (first after last) register would be reg + param-size-in-regs,
2249  // else parameter would be splitted between registers and stack,
2250  // end register would be r4 in this case.
2251  unsigned ByValRegBegin = Reg;
2252  unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4);
2253  State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
2254  // Note, first register is allocated in the beginning of function already,
2255  // allocate remained amount of registers we need.
2256  for (unsigned i = Reg + 1; i != ByValRegEnd; ++i)
2257  State->AllocateReg(GPRArgRegs);
2258  // A byval parameter that is split between registers and memory needs its
2259  // size truncated here.
2260  // In the case where the entire structure fits in registers, we set the
2261  // size in memory to zero.
2262  Size = std::max<int>(Size - Excess, 0);
2263 }
2264 
2265 /// MatchingStackOffset - Return true if the given stack call argument is
2266 /// already available in the same position (relatively) of the caller's
2267 /// incoming argument stack.
2268 static
2271  const TargetInstrInfo *TII) {
2272  unsigned Bytes = Arg.getValueSizeInBits() / 8;
2273  int FI = std::numeric_limits<int>::max();
2274  if (Arg.getOpcode() == ISD::CopyFromReg) {
2275  unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2277  return false;
2278  MachineInstr *Def = MRI->getVRegDef(VR);
2279  if (!Def)
2280  return false;
2281  if (!Flags.isByVal()) {
2282  if (!TII->isLoadFromStackSlot(*Def, FI))
2283  return false;
2284  } else {
2285  return false;
2286  }
2287  } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2288  if (Flags.isByVal())
2289  // ByVal argument is passed in as a pointer but it's now being
2290  // dereferenced. e.g.
2291  // define @foo(%struct.X* %A) {
2292  // tail call @bar(%struct.X* byval %A)
2293  // }
2294  return false;
2295  SDValue Ptr = Ld->getBasePtr();
2296  FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2297  if (!FINode)
2298  return false;
2299  FI = FINode->getIndex();
2300  } else
2301  return false;
2302 
2304  if (!MFI.isFixedObjectIndex(FI))
2305  return false;
2306  return Offset == MFI.getObjectOffset(FI) && Bytes == MFI.getObjectSize(FI);
2307 }
2308 
2309 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2310 /// for tail call optimization. Targets which want to do tail call
2311 /// optimization should implement this function.
2312 bool ARMTargetLowering::IsEligibleForTailCallOptimization(
2313  SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
2314  bool isCalleeStructRet, bool isCallerStructRet,
2315  const SmallVectorImpl<ISD::OutputArg> &Outs,
2316  const SmallVectorImpl<SDValue> &OutVals,
2318  const bool isIndirect) const {
2319  MachineFunction &MF = DAG.getMachineFunction();
2320  const Function &CallerF = MF.getFunction();
2321  CallingConv::ID CallerCC = CallerF.getCallingConv();
2322 
2323  assert(Subtarget->supportsTailCall());
2324 
2325  // Indirect tail calls cannot be optimized for Thumb1 if the args
2326  // to the call take up r0-r3. The reason is that there are no legal registers
2327  // left to hold the pointer to the function to be called.
2328  if (Subtarget->isThumb1Only() && Outs.size() >= 4 &&
2329  (!isa<GlobalAddressSDNode>(Callee.getNode()) || isIndirect))
2330  return false;
2331 
2332  // Look for obvious safe cases to perform tail call optimization that do not
2333  // require ABI changes. This is what gcc calls sibcall.
2334 
2335  // Exception-handling functions need a special set of instructions to indicate
2336  // a return to the hardware. Tail-calling another function would probably
2337  // break this.
2338  if (CallerF.hasFnAttribute("interrupt"))
2339  return false;
2340 
2341  // Also avoid sibcall optimization if either caller or callee uses struct
2342  // return semantics.
2343  if (isCalleeStructRet || isCallerStructRet)
2344  return false;
2345 
2346  // Externally-defined functions with weak linkage should not be
2347  // tail-called on ARM when the OS does not support dynamic
2348  // pre-emption of symbols, as the AAELF spec requires normal calls
2349  // to undefined weak functions to be replaced with a NOP or jump to the
2350  // next instruction. The behaviour of branch instructions in this
2351  // situation (as used for tail calls) is implementation-defined, so we
2352  // cannot rely on the linker replacing the tail call with a return.
2353  if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2354  const GlobalValue *GV = G->getGlobal();
2356  if (GV->hasExternalWeakLinkage() &&
2357  (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2358  return false;
2359  }
2360 
2361  // Check that the call results are passed in the same way.
2362  LLVMContext &C = *DAG.getContext();
2363  if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
2364  CCAssignFnForReturn(CalleeCC, isVarArg),
2365  CCAssignFnForReturn(CallerCC, isVarArg)))
2366  return false;
2367  // The callee has to preserve all registers the caller needs to preserve.
2368  const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
2369  const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2370  if (CalleeCC != CallerCC) {
2371  const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2372  if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
2373  return false;
2374  }
2375 
2376  // If Caller's vararg or byval argument has been split between registers and
2377  // stack, do not perform tail call, since part of the argument is in caller's
2378  // local frame.
2379  const ARMFunctionInfo *AFI_Caller = MF.getInfo<ARMFunctionInfo>();
2380  if (AFI_Caller->getArgRegsSaveSize())
2381  return false;
2382 
2383  // If the callee takes no arguments then go on to check the results of the
2384  // call.
2385  if (!Outs.empty()) {
2386  // Check if stack adjustment is needed. For now, do not do this if any
2387  // argument is passed on the stack.
2389  CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
2390  CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
2391  if (CCInfo.getNextStackOffset()) {
2392  // Check if the arguments are already laid out in the right way as
2393  // the caller's fixed stack objects.
2394  MachineFrameInfo &MFI = MF.getFrameInfo();
2395  const MachineRegisterInfo *MRI = &MF.getRegInfo();
2396  const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2397  for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2398  i != e;
2399  ++i, ++realArgIdx) {
2400  CCValAssign &VA = ArgLocs[i];
2401  EVT RegVT = VA.getLocVT();
2402  SDValue Arg = OutVals[realArgIdx];
2403  ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2404  if (VA.getLocInfo() == CCValAssign::Indirect)
2405  return false;
2406  if (VA.needsCustom()) {
2407  // f64 and vector types are split into multiple registers or
2408  // register/stack-slot combinations. The types will not match
2409  // the registers; give up on memory f64 refs until we figure
2410  // out what to do about this.
2411  if (!VA.isRegLoc())
2412  return false;
2413  if (!ArgLocs[++i].isRegLoc())
2414  return false;
2415  if (RegVT == MVT::v2f64) {
2416  if (!ArgLocs[++i].isRegLoc())
2417  return false;
2418  if (!ArgLocs[++i].isRegLoc())
2419  return false;
2420  }
2421  } else if (!VA.isRegLoc()) {
2422  if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2423  MFI, MRI, TII))
2424  return false;
2425  }
2426  }
2427  }
2428 
2429  const MachineRegisterInfo &MRI = MF.getRegInfo();
2430  if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
2431  return false;
2432  }
2433 
2434  return true;
2435 }
2436 
2437 bool
2438 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2439  MachineFunction &MF, bool isVarArg,
2440  const SmallVectorImpl<ISD::OutputArg> &Outs,
2441  LLVMContext &Context) const {
2443  CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2444  return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2445 }
2446 
2448  const SDLoc &DL, SelectionDAG &DAG) {
2449  const MachineFunction &MF = DAG.getMachineFunction();
2450  const Function &F = MF.getFunction();
2451 
2452  StringRef IntKind = F.getFnAttribute("interrupt").getValueAsString();
2453 
2454  // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2455  // version of the "preferred return address". These offsets affect the return
2456  // instruction if this is a return from PL1 without hypervisor extensions.
2457  // IRQ/FIQ: +4 "subs pc, lr, #4"
2458  // SWI: 0 "subs pc, lr, #0"
2459  // ABORT: +4 "subs pc, lr, #4"
2460  // UNDEF: +4/+2 "subs pc, lr, #0"
2461  // UNDEF varies depending on where the exception came from ARM or Thumb
2462  // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2463 
2464  int64_t LROffset;
2465  if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2466  IntKind == "ABORT")
2467  LROffset = 4;
2468  else if (IntKind == "SWI" || IntKind == "UNDEF")
2469  LROffset = 0;
2470  else
2471  report_fatal_error("Unsupported interrupt attribute. If present, value "
2472  "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2473 
2474  RetOps.insert(RetOps.begin() + 1,
2475  DAG.getConstant(LROffset, DL, MVT::i32, false));
2476 
2477  return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2478 }
2479 
2480 SDValue
2481 ARMTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2482  bool isVarArg,
2483  const SmallVectorImpl<ISD::OutputArg> &Outs,
2484  const SmallVectorImpl<SDValue> &OutVals,
2485  const SDLoc &dl, SelectionDAG &DAG) const {
2486  // CCValAssign - represent the assignment of the return value to a location.
2488 
2489  // CCState - Info about the registers and stack slots.
2490  CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2491  *DAG.getContext());
2492 
2493  // Analyze outgoing return values.
2494  CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2495 
2496  SDValue Flag;
2497  SmallVector<SDValue, 4> RetOps;
2498  RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2499  bool isLittleEndian = Subtarget->isLittle();
2500 
2501  MachineFunction &MF = DAG.getMachineFunction();
2503  AFI->setReturnRegsCount(RVLocs.size());
2504 
2505  // Copy the result values into the output registers.
2506  for (unsigned i = 0, realRVLocIdx = 0;
2507  i != RVLocs.size();
2508  ++i, ++realRVLocIdx) {
2509  CCValAssign &VA = RVLocs[i];
2510  assert(VA.isRegLoc() && "Can only return in registers!");
2511 
2512  SDValue Arg = OutVals[realRVLocIdx];
2513  bool ReturnF16 = false;
2514 
2515  if (Subtarget->hasFullFP16() && Subtarget->isTargetHardFloat()) {
2516  // Half-precision return values can be returned like this:
2517  //
2518  // t11 f16 = fadd ...
2519  // t12: i16 = bitcast t11
2520  // t13: i32 = zero_extend t12
2521  // t14: f32 = bitcast t13 <~~~~~~~ Arg
2522  //
2523  // to avoid code generation for bitcasts, we simply set Arg to the node
2524  // that produces the f16 value, t11 in this case.
2525  //
2526  if (Arg.getValueType() == MVT::f32 && Arg.getOpcode() == ISD::BITCAST) {
2527  SDValue ZE = Arg.getOperand(0);
2528  if (ZE.getOpcode() == ISD::ZERO_EXTEND && ZE.getValueType() == MVT::i32) {
2529  SDValue BC = ZE.getOperand(0);
2530  if (BC.getOpcode() == ISD::BITCAST && BC.getValueType() == MVT::i16) {
2531  Arg = BC.getOperand(0);
2532  ReturnF16 = true;
2533  }
2534  }
2535  }
2536  }
2537 
2538  switch (VA.getLocInfo()) {
2539  default: llvm_unreachable("Unknown loc info!");
2540  case CCValAssign::Full: break;
2541  case CCValAssign::BCvt:
2542  if (!ReturnF16)
2543  Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2544  break;
2545  }
2546 
2547  if (VA.needsCustom()) {
2548  if (VA.getLocVT() == MVT::v2f64) {
2549  // Extract the first half and return it in two registers.
2550  SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2551  DAG.getConstant(0, dl, MVT::i32));
2552  SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2553  DAG.getVTList(MVT::i32, MVT::i32), Half);
2554 
2555  Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2556  HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2557  Flag);
2558  Flag = Chain.getValue(1);
2559  RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2560  VA = RVLocs[++i]; // skip ahead to next loc
2561  Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2562  HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2563  Flag);
2564  Flag = Chain.getValue(1);
2565  RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2566  VA = RVLocs[++i]; // skip ahead to next loc
2567 
2568  // Extract the 2nd half and fall through to handle it as an f64 value.
2569  Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2570  DAG.getConstant(1, dl, MVT::i32));
2571  }
2572  // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is
2573  // available.
2574  SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2575  DAG.getVTList(MVT::i32, MVT::i32), Arg);
2576  Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2577  fmrrd.getValue(isLittleEndian ? 0 : 1),
2578  Flag);
2579  Flag = Chain.getValue(1);
2580  RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2581  VA = RVLocs[++i]; // skip ahead to next loc
2582  Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2583  fmrrd.getValue(isLittleEndian ? 1 : 0),
2584  Flag);
2585  } else
2586  Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2587 
2588  // Guarantee that all emitted copies are
2589  // stuck together, avoiding something bad.
2590  Flag = Chain.getValue(1);
2591  RetOps.push_back(DAG.getRegister(VA.getLocReg(),
2592  ReturnF16 ? MVT::f16 : VA.getLocVT()));
2593  }
2594  const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
2595  const MCPhysReg *I =
2597  if (I) {
2598  for (; *I; ++I) {
2599  if (ARM::GPRRegClass.contains(*I))
2600  RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2601  else if (ARM::DPRRegClass.contains(*I))
2602  RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
2603  else
2604  llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2605  }
2606  }
2607 
2608  // Update chain and glue.
2609  RetOps[0] = Chain;
2610  if (Flag.getNode())
2611  RetOps.push_back(Flag);
2612 
2613  // CPUs which aren't M-class use a special sequence to return from
2614  // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2615  // though we use "subs pc, lr, #N").
2616  //
2617  // M-class CPUs actually use a normal return sequence with a special
2618  // (hardware-provided) value in LR, so the normal code path works.
2619  if (DAG.getMachineFunction().getFunction().hasFnAttribute("interrupt") &&
2620  !Subtarget->isMClass()) {
2621  if (Subtarget->isThumb1Only())
2622  report_fatal_error("interrupt attribute is not supported in Thumb1");
2623  return LowerInterruptReturn(RetOps, dl, DAG);
2624  }
2625 
2626  return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2627 }
2628 
2629 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2630  if (N->getNumValues() != 1)
2631  return false;
2632  if (!N->hasNUsesOfValue(1, 0))
2633  return false;
2634 
2635  SDValue TCChain = Chain;
2636  SDNode *Copy = *N->use_begin();
2637  if (Copy->getOpcode() == ISD::CopyToReg) {
2638  // If the copy has a glue operand, we conservatively assume it isn't safe to
2639  // perform a tail call.
2640  if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2641  return false;
2642  TCChain = Copy->getOperand(0);
2643  } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2644  SDNode *VMov = Copy;
2645  // f64 returned in a pair of GPRs.
2647  for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2648  UI != UE; ++UI) {
2649  if (UI->getOpcode() != ISD::CopyToReg)
2650  return false;
2651  Copies.insert(*UI);
2652  }
2653  if (Copies.size() > 2)
2654  return false;
2655 
2656  for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2657  UI != UE; ++UI) {
2658  SDValue UseChain = UI->getOperand(0);
2659  if (Copies.count(UseChain.getNode()))
2660  // Second CopyToReg
2661  Copy = *UI;
2662  else {
2663  // We are at the top of this chain.
2664  // If the copy has a glue operand, we conservatively assume it
2665  // isn't safe to perform a tail call.
2666  if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
2667  return false;
2668  // First CopyToReg
2669  TCChain = UseChain;
2670  }
2671  }
2672  } else if (Copy->getOpcode() == ISD::BITCAST) {
2673  // f32 returned in a single GPR.
2674  if (!Copy->hasOneUse())
2675  return false;
2676  Copy = *Copy->use_begin();
2677  if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2678  return false;
2679  // If the copy has a glue operand, we conservatively assume it isn't safe to
2680  // perform a tail call.
2681  if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2682  return false;
2683  TCChain = Copy->getOperand(0);
2684  } else {
2685  return false;
2686  }
2687 
2688  bool HasRet = false;
2689  for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2690  UI != UE; ++UI) {
2691  if (UI->getOpcode() != ARMISD::RET_FLAG &&
2692  UI->getOpcode() != ARMISD::INTRET_FLAG)
2693  return false;
2694  HasRet = true;
2695  }
2696 
2697  if (!HasRet)
2698  return false;
2699 
2700  Chain = TCChain;
2701  return true;
2702 }
2703 
2704 bool ARMTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
2705  if (!Subtarget->supportsTailCall())
2706  return false;
2707 
2708  auto Attr =
2709  CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2710  if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2711  return false;
2712 
2713  return true;
2714 }
2715 
2716 // Trying to write a 64 bit value so need to split into two 32 bit values first,
2717 // and pass the lower and high parts through.
2719  SDLoc DL(Op);
2720  SDValue WriteValue = Op->getOperand(2);
2721 
2722  // This function is only supposed to be called for i64 type argument.
2723  assert(WriteValue.getValueType() == MVT::i64
2724  && "LowerWRITE_REGISTER called for non-i64 type argument.");
2725 
2726  SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2727  DAG.getConstant(0, DL, MVT::i32));
2728  SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2729  DAG.getConstant(1, DL, MVT::i32));
2730  SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi };
2731  return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops);
2732 }
2733 
2734 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2735 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2736 // one of the above mentioned nodes. It has to be wrapped because otherwise
2737 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2738 // be used to form addressing mode. These wrapped nodes will be selected
2739 // into MOVi.
2740 SDValue ARMTargetLowering::LowerConstantPool(SDValue Op,
2741  SelectionDAG &DAG) const {
2742  EVT PtrVT = Op.getValueType();
2743  // FIXME there is no actual debug info here
2744  SDLoc dl(Op);
2745  ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2746  SDValue Res;
2747 
2748  // When generating execute-only code Constant Pools must be promoted to the
2749  // global data section. It's a bit ugly that we can't share them across basic
2750  // blocks, but this way we guarantee that execute-only behaves correct with
2751  // position-independent addressing modes.
2752  if (Subtarget->genExecuteOnly()) {
2753  auto AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
2754  auto T = const_cast<Type*>(CP->getType());
2755  auto C = const_cast<Constant*>(CP->getConstVal());
2756  auto M = const_cast<Module*>(DAG.getMachineFunction().
2757  getFunction().getParent());
2758  auto GV = new GlobalVariable(
2759  *M, T, /*isConst=*/true, GlobalVariable::InternalLinkage, C,
2760  Twine(DAG.getDataLayout().getPrivateGlobalPrefix()) + "CP" +
2761  Twine(DAG.getMachineFunction().getFunctionNumber()) + "_" +
2762  Twine(AFI->createPICLabelUId())
2763  );
2764  SDValue GA = DAG.getTargetGlobalAddress(dyn_cast<GlobalValue>(GV),
2765  dl, PtrVT);
2766  return LowerGlobalAddress(GA, DAG);
2767  }
2768 
2769  if (CP->isMachineConstantPoolEntry())
2770  Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2771  CP->getAlignment());
2772  else
2773  Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2774  CP->getAlignment());
2775  return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2776 }
2777 
2780 }
2781 
2782 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2783  SelectionDAG &DAG) const {
2784  MachineFunction &MF = DAG.getMachineFunction();
2786  unsigned ARMPCLabelIndex = 0;
2787  SDLoc DL(Op);
2788  EVT PtrVT = getPointerTy(DAG.getDataLayout());
2789  const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2790  SDValue CPAddr;
2791  bool IsPositionIndependent = isPositionIndependent() || Subtarget->isROPI();
2792  if (!IsPositionIndependent) {
2793  CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2794  } else {
2795  unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2796  ARMPCLabelIndex = AFI->createPICLabelUId();
2797  ARMConstantPoolValue *CPV =
2798  ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2799  ARMCP::CPBlockAddress, PCAdj);
2800  CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2801  }
2802  CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2803  SDValue Result = DAG.getLoad(
2804  PtrVT, DL, DAG.getEntryNode(), CPAddr,
2806  if (!IsPositionIndependent)
2807  return Result;
2808  SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32);
2809  return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2810 }
2811 
2812 /// Convert a TLS address reference into the correct sequence of loads
2813 /// and calls to compute the variable's address for Darwin, and return an
2814 /// SDValue containing the final node.
2815 
2816 /// Darwin only has one TLS scheme which must be capable of dealing with the
2817 /// fully general situation, in the worst case. This means:
2818 /// + "extern __thread" declaration.
2819 /// + Defined in a possibly unknown dynamic library.
2820 ///
2821 /// The general system is that each __thread variable has a [3 x i32] descriptor
2822 /// which contains information used by the runtime to calculate the address. The
2823 /// only part of this the compiler needs to know about is the first word, which
2824 /// contains a function pointer that must be called with the address of the
2825 /// entire descriptor in "r0".
2826 ///
2827 /// Since this descriptor may be in a different unit, in general access must
2828 /// proceed along the usual ARM rules. A common sequence to produce is:
2829 ///
2830 /// movw rT1, :lower16:_var$non_lazy_ptr
2831 /// movt rT1, :upper16:_var$non_lazy_ptr
2832 /// ldr r0, [rT1]
2833 /// ldr rT2, [r0]
2834 /// blx rT2
2835 /// [...address now in r0...]
2836 SDValue
2837 ARMTargetLowering::LowerGlobalTLSAddressDarwin(SDValue Op,
2838  SelectionDAG &DAG) const {
2839  assert(Subtarget->isTargetDarwin() &&
2840  "This function expects a Darwin target");
2841  SDLoc DL(Op);
2842 
2843  // First step is to get the address of the actua global symbol. This is where
2844  // the TLS descriptor lives.
2845  SDValue DescAddr = LowerGlobalAddressDarwin(Op, DAG);
2846 
2847  // The first entry in the descriptor is a function pointer that we must call
2848  // to obtain the address of the variable.
2849  SDValue Chain = DAG.getEntryNode();
2850  SDValue FuncTLVGet = DAG.getLoad(
2851  MVT::i32, DL, Chain, DescAddr,
2853  /* Alignment = */ 4,
2856  Chain = FuncTLVGet.getValue(1);
2857 
2859  MachineFrameInfo &MFI = F.getFrameInfo();
2860  MFI.setAdjustsStack(true);
2861 
2862  // TLS calls preserve all registers except those that absolutely must be
2863  // trashed: R0 (it takes an argument), LR (it's a call) and CPSR (let's not be
2864  // silly).
2865  auto TRI =
2866  getTargetMachine().getSubtargetImpl(F.getFunction())->getRegisterInfo();
2867  auto ARI = static_cast<const ARMRegisterInfo *>(TRI);
2868  const uint32_t *Mask = ARI->getTLSCallPreservedMask(DAG.getMachineFunction());
2869 
2870  // Finally, we can make the call. This is just a degenerate version of a
2871  // normal AArch64 call node: r0 takes the address of the descriptor, and
2872  // returns the address of the variable in this thread.
2873  Chain = DAG.getCopyToReg(Chain, DL, ARM::R0, DescAddr, SDValue());
2874  Chain =
2876  Chain, FuncTLVGet, DAG.getRegister(ARM::R0, MVT::i32),
2877  DAG.getRegisterMask(Mask), Chain.getValue(1));
2878  return DAG.getCopyFromReg(Chain, DL, ARM::R0, MVT::i32, Chain.getValue(1));
2879 }
2880 
2881 SDValue
2882 ARMTargetLowering::LowerGlobalTLSAddressWindows(SDValue Op,
2883  SelectionDAG &DAG) const {
2884  assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering");
2885 
2886  SDValue Chain = DAG.getEntryNode();
2887  EVT PtrVT = getPointerTy(DAG.getDataLayout());
2888  SDLoc DL(Op);
2889 
2890  // Load the current TEB (thread environment block)
2891  SDValue Ops[] = {Chain,
2892  DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
2893  DAG.getConstant(15, DL, MVT::i32),
2894  DAG.getConstant(0, DL, MVT::i32),
2895  DAG.getConstant(13, DL, MVT::i32),
2896  DAG.getConstant(0, DL, MVT::i32),
2897  DAG.getConstant(2, DL, MVT::i32)};
2898  SDValue CurrentTEB = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
2899  DAG.getVTList(MVT::i32, MVT::Other), Ops);
2900 
2901  SDValue TEB = CurrentTEB.getValue(0);
2902  Chain = CurrentTEB.getValue(1);
2903 
2904  // Load the ThreadLocalStoragePointer from the TEB
2905  // A pointer to the TLS array is located at offset 0x2c from the TEB.
2906  SDValue TLSArray =
2907  DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x2c, DL));
2908  TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo());
2909 
2910  // The pointer to the thread's TLS data area is at the TLS Index scaled by 4
2911  // offset into the TLSArray.
2912 
2913  // Load the TLS index from the C runtime
2914  SDValue TLSIndex =
2915  DAG.getTargetExternalSymbol("_tls_index", PtrVT, ARMII::MO_NO_FLAG);
2916  TLSIndex = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, TLSIndex);
2917  TLSIndex = DAG.getLoad(PtrVT, DL, Chain, TLSIndex, MachinePointerInfo());
2918 
2919  SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex,
2920  DAG.getConstant(2, DL, MVT::i32));
2921  SDValue TLS = DAG.getLoad(PtrVT, DL, Chain,
2922  DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot),
2923  MachinePointerInfo());
2924 
2925  // Get the offset of the start of the .tls section (section base)
2926  const auto *GA = cast<GlobalAddressSDNode>(Op);
2927  auto *CPV = ARMConstantPoolConstant::Create(GA->getGlobal(), ARMCP::SECREL);
2928  SDValue Offset = DAG.getLoad(
2929  PtrVT, DL, Chain, DAG.getNode(ARMISD::Wrapper, DL, MVT::i32,
2930  DAG.getTargetConstantPool(CPV, PtrVT, 4)),
2932 
2933  return DAG.getNode(ISD::ADD, DL, PtrVT, TLS, Offset);
2934 }
2935 
2936 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2937 SDValue
2938 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2939  SelectionDAG &DAG) const {
2940  SDLoc dl(GA);
2941  EVT PtrVT = getPointerTy(DAG.getDataLayout());
2942  unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2943  MachineFunction &MF = DAG.getMachineFunction();
2945  unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2946  ARMConstantPoolValue *CPV =
2947  ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2948  ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2949  SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2950  Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2951  Argument = DAG.getLoad(
2952  PtrVT, dl, DAG.getEntryNode(), Argument,
2954  SDValue Chain = Argument.getValue(1);
2955 
2956  SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2957  Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2958 
2959  // call __tls_get_addr.
2960  ArgListTy Args;
2962  Entry.Node = Argument;
2963  Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2964  Args.push_back(Entry);
2965 
2966  // FIXME: is there useful debug info available here?
2968  CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
2970  DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args));
2971 
2972  std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2973  return CallResult.first;
2974 }
2975 
2976 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2977 // "local exec" model.
2978 SDValue
2979 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2980  SelectionDAG &DAG,
2981  TLSModel::Model model) const {
2982  const GlobalValue *GV = GA->getGlobal();
2983  SDLoc dl(GA);
2984  SDValue Offset;
2985  SDValue Chain = DAG.getEntryNode();
2986  EVT PtrVT = getPointerTy(DAG.getDataLayout());
2987  // Get the Thread Pointer
2989 
2990  if (model == TLSModel::InitialExec) {
2991  MachineFunction &MF = DAG.getMachineFunction();
2993  unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2994  // Initial exec model.
2995  unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2996  ARMConstantPoolValue *CPV =
2997  ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2999  true);
3000  Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3001  Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
3002  Offset = DAG.getLoad(
3003  PtrVT, dl, Chain, Offset,
3005  Chain = Offset.getValue(1);
3006 
3007  SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
3008  Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
3009 
3010  Offset = DAG.getLoad(
3011  PtrVT, dl, Chain, Offset,
3013  } else {
3014  // local exec model
3015  assert(model == TLSModel::LocalExec);
3016  ARMConstantPoolValue *CPV =
3018  Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3019  Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
3020  Offset = DAG.getLoad(
3021  PtrVT, dl, Chain, Offset,
3023  }
3024 
3025  // The address of the thread local variable is the add of the thread
3026  // pointer with the offset of the variable.
3027  return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
3028 }
3029 
3030 SDValue
3031 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
3032  GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3033  if (DAG.getTarget().useEmulatedTLS())
3034  return LowerToTLSEmulatedModel(GA, DAG);
3035 
3036  if (Subtarget->isTargetDarwin())
3037  return LowerGlobalTLSAddressDarwin(Op, DAG);
3038 
3039  if (Subtarget->isTargetWindows())
3040  return LowerGlobalTLSAddressWindows(Op, DAG);
3041 
3042  // TODO: implement the "local dynamic" model
3043  assert(Subtarget->isTargetELF() && "Only ELF implemented here");
3045 
3046  switch (model) {
3049  return LowerToTLSGeneralDynamicModel(GA, DAG);
3050  case TLSModel::InitialExec:
3051  case TLSModel::LocalExec:
3052  return LowerToTLSExecModels(GA, DAG, model);
3053  }
3054  llvm_unreachable("bogus TLS model");
3055 }
3056 
3057 /// Return true if all users of V are within function F, looking through
3058 /// ConstantExprs.
3059 static bool allUsersAreInFunction(const Value *V, const Function *F) {
3060  SmallVector<const User*,4> Worklist;
3061  for (auto *U : V->users())
3062  Worklist.push_back(U);
3063  while (!Worklist.empty()) {
3064  auto *U = Worklist.pop_back_val();
3065  if (isa<ConstantExpr>(U)) {
3066  for (auto *UU : U->users())
3067  Worklist.push_back(UU);
3068  continue;
3069  }
3070 
3071  auto *I = dyn_cast<Instruction>(U);
3072  if (!I || I->getParent()->getParent() != F)
3073  return false;
3074  }
3075  return true;
3076 }
3077 
3079  const GlobalValue *GV, SelectionDAG &DAG,
3080  EVT PtrVT, const SDLoc &dl) {
3081  // If we're creating a pool entry for a constant global with unnamed address,
3082  // and the global is small enough, we can emit it inline into the constant pool
3083  // to save ourselves an indirection.
3084  //
3085  // This is a win if the constant is only used in one function (so it doesn't
3086  // need to be duplicated) or duplicating the constant wouldn't increase code
3087  // size (implying the constant is no larger than 4 bytes).
3088  const Function &F = DAG.getMachineFunction().getFunction();
3089 
3090  // We rely on this decision to inline being idemopotent and unrelated to the
3091  // use-site. We know that if we inline a variable at one use site, we'll
3092  // inline it elsewhere too (and reuse the constant pool entry). Fast-isel
3093  // doesn't know about this optimization, so bail out if it's enabled else
3094  // we could decide to inline here (and thus never emit the GV) but require
3095  // the GV from fast-isel generated code.
3096  if (!EnableConstpoolPromotion ||
3098  return SDValue();
3099 
3100  auto *GVar = dyn_cast<GlobalVariable>(GV);
3101  if (!GVar || !GVar->hasInitializer() ||
3102  !GVar->isConstant() || !GVar->hasGlobalUnnamedAddr() ||
3103  !GVar->hasLocalLinkage())
3104  return SDValue();
3105 
3106  // If we inline a value that contains relocations, we move the relocations
3107  // from .data to .text. This is not allowed in position-independent code.
3108  auto *Init = GVar->getInitializer();
3109  if ((TLI->isPositionIndependent() || TLI->getSubtarget()->isROPI()) &&
3110  Init->needsRelocation())
3111  return SDValue();
3112 
3113  // The constant islands pass can only really deal with alignment requests
3114  // <= 4 bytes and cannot pad constants itself. Therefore we cannot promote
3115  // any type wanting greater alignment requirements than 4 bytes. We also
3116  // can only promote constants that are multiples of 4 bytes in size or
3117  // are paddable to a multiple of 4. Currently we only try and pad constants
3118  // that are strings for simplicity.
3119  auto *CDAInit = dyn_cast<ConstantDataArray>(Init);
3120  unsigned Size = DAG.getDataLayout().getTypeAllocSize(Init->getType());
3121  unsigned Align = DAG.getDataLayout().getPreferredAlignment(GVar);
3122  unsigned RequiredPadding = 4 - (Size % 4);
3123  bool PaddingPossible =
3124  RequiredPadding == 4 || (CDAInit && CDAInit->isString());
3125  if (!PaddingPossible || Align > 4 || Size > ConstpoolPromotionMaxSize ||
3126  Size == 0)
3127  return SDValue();
3128 
3129  unsigned PaddedSize = Size + ((RequiredPadding == 4) ? 0 : RequiredPadding);
3130  MachineFunction &MF = DAG.getMachineFunction();
3132 
3133  // We can't bloat the constant pool too much, else the ConstantIslands pass
3134  // may fail to converge. If we haven't promoted this global yet (it may have
3135  // multiple uses), and promoting it would increase the constant pool size (Sz
3136  // > 4), ensure we have space to do so up to MaxTotal.
3137  if (!AFI->getGlobalsPromotedToConstantPool().count(GVar) && Size > 4)
3138  if (AFI->getPromotedConstpoolIncrease() + PaddedSize - 4 >=
3140  return SDValue();
3141 
3142  // This is only valid if all users are in a single function; we can't clone
3143  // the constant in general. The LLVM IR unnamed_addr allows merging
3144  // constants, but not cloning them.
3145  //
3146  // We could potentially allow cloning if we could prove all uses of the
3147  // constant in the current function don't care about the address, like
3148  // printf format strings. But that isn't implemented for now.
3149  if (!allUsersAreInFunction(GVar, &F))
3150  return SDValue();
3151 
3152  // We're going to inline this global. Pad it out if needed.
3153  if (RequiredPadding != 4) {
3154  StringRef S = CDAInit->getAsString();
3155 
3157  std::copy(S.bytes_begin(), S.bytes_end(), V.begin());
3158  while (RequiredPadding--)
3159  V.push_back(0);
3160  Init = ConstantDataArray::get(*DAG.getContext(), V);
3161  }
3162 
3163  auto CPVal = ARMConstantPoolConstant::Create(GVar, Init);
3164  SDValue CPAddr =
3165  DAG.getTargetConstantPool(CPVal, PtrVT, /*Align=*/4);
3166  if (!AFI->getGlobalsPromotedToConstantPool().count(GVar)) {
3169  PaddedSize - 4);
3170  }
3171  ++NumConstpoolPromoted;
3172  return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3173 }
3174 
3176  if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
3177  if (!(GV = GA->getBaseObject()))
3178  return false;
3179  if (const auto *V = dyn_cast<GlobalVariable>(GV))
3180  return V->isConstant();
3181  return isa<Function>(GV);
3182 }
3183 
3184 SDValue ARMTargetLowering::LowerGlobalAddress(SDValue Op,
3185  SelectionDAG &DAG) const {
3186  switch (Subtarget->getTargetTriple().getObjectFormat()) {
3187  default: llvm_unreachable("unknown object format");
3188  case Triple::COFF:
3189  return LowerGlobalAddressWindows(Op, DAG);
3190  case Triple::ELF:
3191  return LowerGlobalAddressELF(Op, DAG);
3192  case Triple::MachO:
3193  return LowerGlobalAddressDarwin(Op, DAG);
3194  }
3195 }
3196 
3197 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
3198  SelectionDAG &DAG) const {
3199  EVT PtrVT = getPointerTy(DAG.getDataLayout());
3200  SDLoc dl(Op);
3201  const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3202  const TargetMachine &TM = getTargetMachine();
3203  bool IsRO = isReadOnly(GV);
3204 
3205  // promoteToConstantPool only if not generating XO text section
3206  if (TM.shouldAssumeDSOLocal(*GV->getParent(), GV) && !Subtarget->genExecuteOnly())
3207  if (SDValue V = promoteToConstantPool(this, GV, DAG, PtrVT, dl))
3208  return V;
3209 
3210  if (isPositionIndependent()) {
3211  bool UseGOT_PREL = !TM.shouldAssumeDSOLocal(*GV->getParent(), GV);
3212  SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3213  UseGOT_PREL ? ARMII::MO_GOT : 0);
3214  SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G);
3215  if (UseGOT_PREL)
3216  Result =
3217  DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
3219  return Result;
3220  } else if (Subtarget->isROPI() && IsRO) {
3221  // PC-relative.
3222  SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT);
3223  SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G);
3224  return Result;
3225  } else if (Subtarget->isRWPI() && !IsRO) {
3226  // SB-relative.
3227  SDValue RelAddr;
3228  if (Subtarget->useMovt()) {
3229  ++NumMovwMovt;
3230  SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_SBREL);
3231  RelAddr = DAG.getNode(ARMISD::Wrapper, dl, PtrVT, G);
3232  } else { // use literal pool for address constant
3233  ARMConstantPoolValue *CPV =
3235  SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3236  CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3237  RelAddr = DAG.getLoad(
3238  PtrVT, dl, DAG.getEntryNode(), CPAddr,
3240  }
3241  SDValue SB = DAG.getCopyFromReg(DAG.getEntryNode(), dl, ARM::R9, PtrVT);
3242  SDValue Result = DAG.getNode(ISD::ADD, dl, PtrVT, SB, RelAddr);
3243  return Result;
3244  }
3245 
3246  // If we have T2 ops, we can materialize the address directly via movt/movw
3247  // pair. This is always cheaper.
3248  if (Subtarget->useMovt()) {
3249  ++NumMovwMovt;
3250  // FIXME: Once remat is capable of dealing with instructions with register
3251  // operands, expand this into two nodes.
3252  return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
3253  DAG.getTargetGlobalAddress(GV, dl, PtrVT));
3254  } else {
3255  SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
3256  CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3257  return DAG.getLoad(
3258  PtrVT, dl, DAG.getEntryNode(), CPAddr,
3260  }
3261 }
3262 
3263 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
3264  SelectionDAG &DAG) const {
3265  assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
3266  "ROPI/RWPI not currently supported for Darwin");
3267  EVT PtrVT = getPointerTy(DAG.getDataLayout());
3268  SDLoc dl(Op);
3269  const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3270 
3271  if (Subtarget->useMovt())
3272  ++NumMovwMovt;
3273 
3274  // FIXME: Once remat is capable of dealing with instructions with register
3275  // operands, expand this into multiple nodes
3276  unsigned Wrapper =
3278 
3279  SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
3280  SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
3281 
3282  if (Subtarget->isGVIndirectSymbol(GV))
3283  Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
3285  return Result;
3286 }
3287 
3288 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
3289  SelectionDAG &DAG) const {
3290  assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
3291  assert(Subtarget->useMovt() &&
3292  "Windows on ARM expects to use movw/movt");
3293  assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
3294  "ROPI/RWPI not currently supported for Windows");
3295 
3296  const TargetMachine &TM = getTargetMachine();
3297  const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3298  ARMII::TOF TargetFlags = ARMII::MO_NO_FLAG;
3299  if (GV->hasDLLImportStorageClass())
3300  TargetFlags = ARMII::MO_DLLIMPORT;
3301  else if (!TM.shouldAssumeDSOLocal(*GV->getParent(), GV))
3302  TargetFlags = ARMII::MO_COFFSTUB;
3303  EVT PtrVT = getPointerTy(DAG.getDataLayout());
3304  SDValue Result;
3305  SDLoc DL(Op);
3306 
3307  ++NumMovwMovt;
3308 
3309  // FIXME: Once remat is capable of dealing with instructions with register
3310  // operands, expand this into two nodes.
3311  Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
3312  DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
3313  TargetFlags));
3314  if (TargetFlags & (ARMII::MO_DLLIMPORT | ARMII::MO_COFFSTUB))
3315  Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
3317  return Result;
3318 }
3319 
3320 SDValue
3321 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
3322  SDLoc dl(Op);
3323  SDValue Val = DAG.getConstant(0, dl, MVT::i32);
3324  return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
3325  DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
3326  Op.getOperand(1), Val);
3327 }
3328 
3329 SDValue
3330 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
3331  SDLoc dl(Op);
3332  return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
3333  Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32));
3334 }
3335 
3336 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op,
3337  SelectionDAG &DAG) const {
3338  SDLoc dl(Op);
3340  Op.getOperand(0));
3341 }
3342 
3343 SDValue
3344 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
3345  const ARMSubtarget *Subtarget) const {
3346  unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3347  SDLoc dl(Op);
3348  switch (IntNo) {
3349  default: return SDValue(); // Don't custom lower most intrinsics.
3350  case Intrinsic::thread_pointer: {
3351  EVT PtrVT = getPointerTy(DAG.getDataLayout());
3352  return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
3353  }
3354  case Intrinsic::eh_sjlj_lsda: {
3355  MachineFunction &MF = DAG.getMachineFunction();
3357  unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3358  EVT PtrVT = getPointerTy(DAG.getDataLayout());
3359  SDValue CPAddr;
3360  bool IsPositionIndependent = isPositionIndependent();
3361  unsigned PCAdj = IsPositionIndependent ? (Subtarget->isThumb() ? 4 : 8) : 0;
3362  ARMConstantPoolValue *CPV =
3363  ARMConstantPoolConstant::Create(&MF.getFunction(), ARMPCLabelIndex,
3364  ARMCP::CPLSDA, PCAdj);
3365  CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3366  CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3367  SDValue Result = DAG.getLoad(
3368  PtrVT, dl, DAG.getEntryNode(), CPAddr,
3370 
3371  if (IsPositionIndependent) {
3372  SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
3373  Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
3374  }
3375  return Result;
3376  }
3377  case Intrinsic::arm_neon_vabs:
3378  return DAG.getNode(ISD::ABS, SDLoc(Op), Op.getValueType(),
3379  Op.getOperand(1));
3380  case Intrinsic::arm_neon_vmulls:
3381  case Intrinsic::arm_neon_vmullu: {
3382  unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
3384  return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3385  Op.getOperand(1), Op.getOperand(2));
3386  }
3387  case Intrinsic::arm_neon_vminnm:
3388  case Intrinsic::arm_neon_vmaxnm: {
3389  unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm)
3391  return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3392  Op.getOperand(1), Op.getOperand(2));
3393  }
3394  case Intrinsic::arm_neon_vminu:
3395  case Intrinsic::arm_neon_vmaxu: {
3396  if (Op.getValueType().isFloatingPoint())
3397  return SDValue();
3398  unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu)
3399  ? ISD::UMIN : ISD::UMAX;
3400  return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3401  Op.getOperand(1), Op.getOperand(2));
3402  }
3403  case Intrinsic::arm_neon_vmins:
3404  case Intrinsic::arm_neon_vmaxs: {
3405  // v{min,max}s is overloaded between signed integers and floats.
3406  if (!Op.getValueType().isFloatingPoint()) {
3407  unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
3408  ? ISD::SMIN : ISD::SMAX;
3409  return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3410  Op.getOperand(1), Op.getOperand(2));
3411  }
3412  unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
3414  return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3415  Op.getOperand(1), Op.getOperand(2));
3416  }
3417  case Intrinsic::arm_neon_vtbl1:
3418  return DAG.getNode(ARMISD::VTBL1, SDLoc(Op), Op.getValueType(),
3419  Op.getOperand(1), Op.getOperand(2));
3420  case Intrinsic::arm_neon_vtbl2:
3421  return DAG.getNode(ARMISD::VTBL2, SDLoc(Op), Op.getValueType(),
3422  Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
3423  }
3424 }
3425 
3427  const ARMSubtarget *Subtarget) {
3428  SDLoc dl(Op);
3429  ConstantSDNode *SSIDNode = cast<ConstantSDNode>(Op.getOperand(2));
3430  auto SSID = static_cast<SyncScope::ID>(SSIDNode->getZExtValue());
3431  if (SSID == SyncScope::SingleThread)
3432  return Op;
3433 
3434  if (!Subtarget->hasDataBarrier()) {
3435  // Some ARMv6 cpus can support data barriers with an mcr instruction.
3436  // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
3437  // here.
3438  assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
3439  "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
3440  return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
3441  DAG.getConstant(0, dl, MVT::i32));
3442  }
3443 
3444  ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
3445  AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
3446  ARM_MB::MemBOpt Domain = ARM_MB::ISH;
3447  if (Subtarget->isMClass()) {
3448  // Only a full system barrier exists in the M-class architectures.
3449  Domain = ARM_MB::SY;
3450  } else if (Subtarget->preferISHSTBarriers() &&
3451  Ord == AtomicOrdering::Release) {
3452  // Swift happens to implement ISHST barriers in a way that's compatible with
3453  // Release semantics but weaker than ISH so we'd be fools not to use
3454  // it. Beware: other processors probably don't!
3455  Domain = ARM_MB::ISHST;
3456  }
3457 
3458  return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
3459  DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32),
3460  DAG.getConstant(Domain, dl, MVT::i32));
3461 }
3462 
3464  const ARMSubtarget *Subtarget) {
3465  // ARM pre v5TE and Thumb1 does not have preload instructions.
3466  if (!(Subtarget->isThumb2() ||
3467  (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
3468  // Just preserve the chain.
3469  return Op.getOperand(0);
3470 
3471  SDLoc dl(Op);
3472  unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
3473  if (!isRead &&
3474  (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
3475  // ARMv7 with MP extension has PLDW.
3476  return Op.getOperand(0);
3477 
3478  unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
3479  if (Subtarget->isThumb()) {
3480  // Invert the bits.
3481  isRead = ~isRead & 1;
3482  isData = ~isData & 1;
3483  }
3484 
3485  return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
3486  Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32),
3487  DAG.getConstant(isData, dl, MVT::i32));
3488 }
3489 
3491  MachineFunction &MF = DAG.getMachineFunction();
3492  ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
3493 
3494  // vastart just stores the address of the VarArgsFrameIndex slot into the
3495  // memory location argument.
3496  SDLoc dl(Op);
3497  EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
3498  SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3499  const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3500  return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
3501  MachinePointerInfo(SV));
3502 }
3503 
3504 SDValue ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA,
3505  CCValAssign &NextVA,
3506  SDValue &Root,
3507  SelectionDAG &DAG,
3508  const SDLoc &dl) const {
3509  MachineFunction &MF = DAG.getMachineFunction();
3511 
3512  const TargetRegisterClass *RC;
3513  if (AFI->isThumb1OnlyFunction())
3514  RC = &ARM::tGPRRegClass;
3515  else
3516  RC = &ARM::GPRRegClass;
3517 
3518  // Transform the arguments stored in physical registers into virtual ones.
3519  unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3520  SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
3521 
3522  SDValue ArgValue2;
3523  if (NextVA.isMemLoc()) {
3524  MachineFrameInfo &MFI = MF.getFrameInfo();
3525  int FI = MFI.CreateFixedObject(4, NextVA.getLocMemOffset(), true);
3526 
3527  // Create load node to retrieve arguments from the stack.
3528  SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3529  ArgValue2 = DAG.getLoad(
3530  MVT::i32, dl, Root, FIN,
3532  } else {
3533  Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
3534  ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
3535  }
3536  if (!Subtarget->isLittle())
3537  std::swap (ArgValue, ArgValue2);
3538  return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
3539 }
3540 
3541 // The remaining GPRs hold either the beginning of variable-argument
3542 // data, or the beginning of an aggregate passed by value (usually
3543 // byval). Either way, we allocate stack slots adjacent to the data
3544 // provided by our caller, and store the unallocated registers there.
3545 // If this is a variadic function, the va_list pointer will begin with
3546 // these values; otherwise, this reassembles a (byval) structure that
3547 // was split between registers and memory.
3548 // Return: The frame index registers were stored into.
3549 int ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
3550  const SDLoc &dl, SDValue &Chain,
3551  const Value *OrigArg,
3552  unsigned InRegsParamRecordIdx,
3553  int ArgOffset, unsigned ArgSize) const {
3554  // Currently, two use-cases possible:
3555  // Case #1. Non-var-args function, and we meet first byval parameter.
3556  // Setup first unallocated register as first byval register;
3557  // eat all remained registers
3558  // (these two actions are performed by HandleByVal method).
3559  // Then, here, we initialize stack frame with
3560  // "store-reg" instructions.
3561  // Case #2. Var-args function, that doesn't contain byval parameters.
3562  // The same: eat all remained unallocated registers,
3563  // initialize stack frame.
3564 
3565  MachineFunction &MF = DAG.getMachineFunction();
3566  MachineFrameInfo &MFI = MF.getFrameInfo();
3568  unsigned RBegin, REnd;
3569  if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
3570  CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
3571  } else {
3572  unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3573  RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx];
3574  REnd = ARM::R4;
3575  }
3576 
3577  if (REnd != RBegin)
3578  ArgOffset = -4 * (ARM::R4 - RBegin);
3579 
3580  auto PtrVT = getPointerTy(DAG.getDataLayout());
3581  int FrameIndex = MFI.CreateFixedObject(ArgSize, ArgOffset, false);
3582  SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT);
3583 
3584  SmallVector<SDValue, 4> MemOps;
3585  const TargetRegisterClass *RC =
3586  AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
3587 
3588  for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) {
3589  unsigned VReg = MF.addLiveIn(Reg, RC);
3590  SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3591  SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3592  MachinePointerInfo(OrigArg, 4 * i));
3593  MemOps.push_back(Store);
3594  FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT));
3595  }
3596 
3597  if (!MemOps.empty())
3598  Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3599  return FrameIndex;
3600 }
3601 
3602 // Setup stack frame, the va_list pointer will start from.
3603 void ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
3604  const SDLoc &dl, SDValue &Chain,
3605  unsigned ArgOffset,
3606  unsigned TotalArgRegsSaveSize,
3607  bool ForceMutable) const {
3608  MachineFunction &MF = DAG.getMachineFunction();
3610 
3611  // Try to store any remaining integer argument regs
3612  // to their spots on the stack so that they may be loaded by dereferencing
3613  // the result of va_next.
3614  // If there is no regs to be stored, just point address after last
3615  // argument passed via stack.
3616  int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
3617  CCInfo.getInRegsParamsCount(),
3618  CCInfo.getNextStackOffset(), 4);
3619  AFI->setVarArgsFrameIndex(FrameIndex);
3620 }
3621 
3622 SDValue ARMTargetLowering::LowerFormalArguments(
3623  SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3624  const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3625  SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3626  MachineFunction &MF = DAG.getMachineFunction();
3627  MachineFrameInfo &MFI = MF.getFrameInfo();
3628 
3630 
3631  // Assign locations to all of the incoming arguments.
3633  CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3634  *DAG.getContext());
3635  CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForCall(CallConv, isVarArg));
3636 
3637  SmallVector<SDValue, 16> ArgValues;
3638  SDValue ArgValue;
3640  unsigned CurArgIdx = 0;
3641 
3642  // Initially ArgRegsSaveSize is zero.
3643  // Then we increase this value each time we meet byval parameter.
3644  // We also increase this value in case of varargs function.
3645  AFI->setArgRegsSaveSize(0);
3646 
3647  // Calculate the amount of stack space that we need to allocate to store
3648  // byval and variadic arguments that are passed in registers.
3649  // We need to know this before we allocate the first byval or variadic
3650  // argument, as they will be allocated a stack slot below the CFA (Canonical
3651  // Frame Address, the stack pointer at entry to the function).
3652  unsigned ArgRegBegin = ARM::R4;
3653  for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3654  if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount())
3655  break;
3656 
3657  CCValAssign &VA = ArgLocs[i];
3658  unsigned Index = VA.getValNo();
3659  ISD::ArgFlagsTy Flags = Ins[Index].Flags;
3660  if (!Flags.isByVal())
3661  continue;
3662 
3663  assert(VA.isMemLoc() && "unexpected byval pointer in reg");
3664  unsigned RBegin, REnd;
3665  CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd);
3666  ArgRegBegin = std::min(ArgRegBegin, RBegin);
3667 
3668  CCInfo.nextInRegsParam();
3669  }
3670  CCInfo.rewindByValRegsInfo();
3671 
3672  int lastInsIndex = -1;
3673  if (isVarArg && MFI.hasVAStart()) {
3674  unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3675  if (RegIdx != array_lengthof(GPRArgRegs))
3676  ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]);
3677  }
3678 
3679  unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin);
3680  AFI->setArgRegsSaveSize(TotalArgRegsSaveSize);
3681  auto PtrVT = getPointerTy(DAG.getDataLayout());
3682 
3683  for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3684  CCValAssign &VA = ArgLocs[i];
3685  if (Ins[VA.getValNo()].isOrigArg()) {
3686  std::advance(CurOrigArg,
3687  Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
3688  CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
3689  }
3690  // Arguments stored in registers.
3691  if (VA.isRegLoc()) {
3692  EVT RegVT = VA.getLocVT();
3693 
3694  if (VA.needsCustom()) {
3695  // f64 and vector types are split up into multiple registers or
3696  // combinations of registers and stack slots.
3697  if (VA.getLocVT() == MVT::v2f64) {
3698  SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3699  Chain, DAG, dl);
3700  VA = ArgLocs[++i]; // skip ahead to next loc
3701  SDValue ArgValue2;
3702  if (VA.isMemLoc()) {
3703  int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), true);
3704  SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3705  ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
3707  DAG.getMachineFunction(), FI));
3708  } else {
3709  ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3710  Chain, DAG, dl);
3711  }
3712  ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3713  ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3714  ArgValue, ArgValue1,
3715  DAG.getIntPtrConstant(0, dl));
3716  ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3717  ArgValue, ArgValue2,
3718  DAG.getIntPtrConstant(1, dl));
3719  } else
3720  ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3721  } else {
3722  const TargetRegisterClass *RC;
3723 
3724 
3725  if (RegVT == MVT::f16)
3726  RC = &ARM::HPRRegClass;
3727  else if (RegVT == MVT::f32)
3728  RC = &ARM::SPRRegClass;
3729  else if (RegVT == MVT::f64 || RegVT == MVT::v4f16)
3730  RC = &ARM::DPRRegClass;
3731  else if (RegVT == MVT::v2f64 || RegVT == MVT::v8f16)
3732  RC = &ARM::QPRRegClass;
3733  else if (RegVT == MVT::i32)
3734  RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
3735  : &ARM::GPRRegClass;
3736  else
3737  llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3738 
3739  // Transform the arguments in physical registers into virtual ones.
3740  unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3741  ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3742  }
3743 
3744  // If this is an 8 or 16-bit value, it is really passed promoted
3745  // to 32 bits. Insert an assert[sz]ext to capture this, then
3746  // truncate to the right size.
3747  switch (VA.getLocInfo()) {
3748  default: llvm_unreachable("Unknown loc info!");
3749  case CCValAssign::Full: break;
3750  case CCValAssign::BCvt:
3751  ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3752  break;
3753  case CCValAssign::SExt:
3754  ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3755  DAG.getValueType(VA.getValVT()));
3756  ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3757  break;
3758  case CCValAssign::ZExt:
3759  ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3760  DAG.getValueType(VA.getValVT()));
3761  ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3762  break;
3763  }
3764 
3765  InVals.push_back(ArgValue);
3766  } else { // VA.isRegLoc()
3767  // sanity check
3768  assert(VA.isMemLoc());
3769  assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3770 
3771  int index = VA.getValNo();
3772 
3773  // Some Ins[] entries become multiple ArgLoc[] entries.
3774  // Process them only once.
3775  if (index != lastInsIndex)
3776  {
3777  ISD::ArgFlagsTy Flags = Ins[index].Flags;
3778  // FIXME: For now, all byval parameter objects are marked mutable.
3779  // This can be changed with more analysis.
3780  // In case of tail call optimization mark all arguments mutable.
3781  // Since they could be overwritten by lowering of arguments in case of
3782  // a tail call.
3783  if (Flags.isByVal()) {
3784  assert(Ins[index].isOrigArg() &&
3785  "Byval arguments cannot be implicit");
3786  unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
3787 
3788  int FrameIndex = StoreByValRegs(
3789  CCInfo, DAG, dl, Chain, &*CurOrigArg, CurByValIndex,
3790  VA.getLocMemOffset(), Flags.getByValSize());
3791  InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT));
3792  CCInfo.nextInRegsParam();
3793  } else {
3794  unsigned FIOffset = VA.getLocMemOffset();
3795  int FI = MFI.CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3796  FIOffset, true);
3797 
3798  // Create load nodes to retrieve arguments from the stack.
3799  SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3800  InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3802  DAG.getMachineFunction(), FI)));
3803  }
3804  lastInsIndex = index;
3805  }
3806  }
3807  }
3808 
3809  // varargs
3810  if (isVarArg && MFI.hasVAStart())
3811  VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3812  CCInfo.getNextStackOffset(),
3813  TotalArgRegsSaveSize);
3814 
3816 
3817  return Chain;
3818 }
3819 
3820 /// isFloatingPointZero - Return true if this is +0.0.
3821 static bool isFloatingPointZero(SDValue Op) {
3822  if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3823  return CFP->getValueAPF().isPosZero();
3824  else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3825  // Maybe this has already been legalized into the constant pool?
3826  if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3827  SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3828  if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3829  if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3830  return CFP->getValueAPF().isPosZero();
3831  }
3832  } else if (Op->getOpcode() == ISD::BITCAST &&
3833  Op->getValueType(0) == MVT::f64) {
3834  // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
3835  // created by LowerConstantFP().
3836  SDValue BitcastOp = Op->getOperand(0);
3837  if (BitcastOp->getOpcode() == ARMISD::VMOVIMM &&
3838  isNullConstant(BitcastOp->getOperand(0)))
3839  return true;
3840  }
3841  return false;
3842 }
3843 
3844 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3845 /// the given operands.
3846 SDValue ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3847  SDValue &ARMcc, SelectionDAG &DAG,
3848  const SDLoc &dl) const {
3849  if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3850  unsigned C = RHSC->getZExtValue();
3851  if (!isLegalICmpImmediate((int32_t)C)) {
3852  // Constant does not fit, try adjusting it by one.
3853  switch (CC) {
3854  default: break;
3855  case ISD::SETLT:
3856  case ISD::SETGE:
3857  if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3858  CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3859  RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3860  }
3861  break;
3862  case ISD::SETULT:
3863  case ISD::SETUGE:
3864  if (C != 0 && isLegalICmpImmediate(C-1)) {
3865  CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3866  RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3867  }
3868  break;
3869  case ISD::SETLE:
3870  case ISD::SETGT:
3871  if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3872  CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3873  RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3874  }
3875  break;
3876  case ISD::SETULE:
3877  case ISD::SETUGT:
3878  if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3879  CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3880  RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3881  }
3882  break;
3883  }
3884  }
3885  } else if ((ARM_AM::getShiftOpcForNode(LHS.getOpcode()) != ARM_AM::no_shift) &&
3887  // In ARM and Thumb-2, the compare instructions can shift their second
3888  // operand.
3890  std::swap(LHS, RHS);
3891  }
3892 
3894  ARMISD::NodeType CompareType;
3895  switch (CondCode) {
3896  default:
3897  CompareType = ARMISD::CMP;
3898  break;
3899  case ARMCC::EQ:
3900  case ARMCC::NE:
3901  // Uses only Z Flag
3902  CompareType = ARMISD::CMPZ;
3903  break;
3904  }
3905  ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3906  return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3907 }
3908 
3909 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3910 SDValue ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS,
3911  SelectionDAG &DAG, const SDLoc &dl,
3912  bool InvalidOnQNaN) const {
3913  assert(Subtarget->hasFP64() || RHS.getValueType() != MVT::f64);
3914  SDValue Cmp;
3915  SDValue C = DAG.getConstant(InvalidOnQNaN, dl, MVT::i32);
3916  if (!isFloatingPointZero(RHS))
3917  Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS, C);
3918  else
3919  Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS, C);
3920  return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3921 }
3922 
3923 /// duplicateCmp - Glue values can have only one use, so this function
3924 /// duplicates a comparison node.
3925 SDValue
3926 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3927  unsigned Opc = Cmp.getOpcode();
3928  SDLoc DL(Cmp);
3929  if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3930  return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3931 
3932  assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3933  Cmp = Cmp.getOperand(0);
3934  Opc = Cmp.getOpcode();
3935  if (Opc == ARMISD::CMPFP)
3936  Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),
3937  Cmp.getOperand(1), Cmp.getOperand(2));
3938  else {
3939  assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3940  Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),
3941  Cmp.getOperand(1));
3942  }
3943  return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3944 }
3945 
3946 // This function returns three things: the arithmetic computation itself
3947 // (Value), a comparison (OverflowCmp), and a condition code (ARMcc). The
3948 // comparison and the condition code define the case in which the arithmetic
3949 // computation *does not* overflow.
3950 std::pair<SDValue, SDValue>
3951 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3952  SDValue &ARMcc) const {
3953  assert(Op.getValueType() == MVT::i32 && "Unsupported value type");
3954 
3955  SDValue Value, OverflowCmp;
3956  SDValue LHS = Op.getOperand(0);
3957  SDValue RHS = Op.getOperand(1);
3958  SDLoc dl(Op);
3959 
3960  // FIXME: We are currently always generating CMPs because we don't support
3961  // generating CMN through the backend. This is not as good as the natural
3962  // CMP case because it causes a register dependency and cannot be folded
3963  // later.
3964 
3965  switch (Op.getOpcode()) {
3966  default:
3967  llvm_unreachable("Unknown overflow instruction!");
3968  case ISD::SADDO:
3969  ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3970  Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3971  OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3972  break;
3973  case ISD::UADDO:
3974  ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3975  // We use ADDC here to correspond to its use in LowerUnsignedALUO.
3976  // We do not use it in the USUBO case as Value may not be used.
3977  Value = DAG.getNode(ARMISD::ADDC, dl,
3978  DAG.getVTList(Op.getValueType(), MVT::i32), LHS, RHS)
3979  .getValue(0);
3980  OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3981  break;
3982  case ISD::SSUBO:
3983  ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3984  Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3985  OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3986  break;
3987  case ISD::USUBO:
3988  ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3989  Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3990  OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3991  break;
3992  case ISD::UMULO:
3993  // We generate a UMUL_LOHI and then check if the high word is 0.
3994  ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32);
3995  Value = DAG.getNode(ISD::UMUL_LOHI, dl,
3996  DAG.getVTList(Op.getValueType(), Op.getValueType()),
3997  LHS, RHS);
3998  OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value.getValue(1),
3999  DAG.getConstant(0, dl, MVT::i32));
4000  Value = Value.getValue(0); // We only want the low 32 bits for the result.
4001  break;
4002  case ISD::SMULO:
4003  // We generate a SMUL_LOHI and then check if all the bits of the high word
4004  // are the same as the sign bit of the low word.
4005  ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32);
4006  Value = DAG.getNode(ISD::SMUL_LOHI, dl,
4007  DAG.getVTList(Op.getValueType(), Op.getValueType()),
4008  LHS, RHS);
4009  OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value.getValue(1),
4010  DAG.getNode(ISD::SRA, dl, Op.getValueType(),
4011  Value.getValue(0),
4012  DAG.getConstant(31, dl, MVT::i32)));
4013  Value = Value.getValue(0); // We only want the low 32 bits for the result.
4014  break;
4015  } // switch (...)
4016 
4017  return std::make_pair(Value, OverflowCmp);
4018 }
4019 
4020 SDValue
4021 ARMTargetLowering::LowerSignedALUO(SDValue Op, SelectionDAG &DAG) const {
4022  // Let legalize expand this if it isn't a legal type yet.
4024  return SDValue();
4025 
4026  SDValue Value, OverflowCmp;
4027  SDValue ARMcc;
4028  std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
4029  SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4030  SDLoc dl(Op);
4031  // We use 0 and 1 as false and true values.
4032  SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
4033  SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
4034  EVT VT = Op.getValueType();
4035 
4036  SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal,
4037  ARMcc, CCR, OverflowCmp);
4038 
4039  SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
4040  return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
4041 }
4042 
4044  SelectionDAG &DAG) {
4045  SDLoc DL(BoolCarry);
4046  EVT CarryVT = BoolCarry.