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