ARMISelLowering.cpp revision 8688a58c53b46d2dda9bf50dafd5195790a7ed58
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#define DEBUG_TYPE "arm-isel"
16#include "ARMISelLowering.h"
17#include "ARM.h"
18#include "ARMCallingConv.h"
19#include "ARMConstantPoolValue.h"
20#include "ARMMachineFunctionInfo.h"
21#include "ARMPerfectShuffle.h"
22#include "ARMSubtarget.h"
23#include "ARMTargetMachine.h"
24#include "ARMTargetObjectFile.h"
25#include "MCTargetDesc/ARMAddressingModes.h"
26#include "llvm/ADT/Statistic.h"
27#include "llvm/ADT/StringExtras.h"
28#include "llvm/CodeGen/CallingConvLower.h"
29#include "llvm/CodeGen/IntrinsicLowering.h"
30#include "llvm/CodeGen/MachineBasicBlock.h"
31#include "llvm/CodeGen/MachineFrameInfo.h"
32#include "llvm/CodeGen/MachineFunction.h"
33#include "llvm/CodeGen/MachineInstrBuilder.h"
34#include "llvm/CodeGen/MachineModuleInfo.h"
35#include "llvm/CodeGen/MachineRegisterInfo.h"
36#include "llvm/CodeGen/SelectionDAG.h"
37#include "llvm/IR/CallingConv.h"
38#include "llvm/IR/Constants.h"
39#include "llvm/IR/Function.h"
40#include "llvm/IR/GlobalValue.h"
41#include "llvm/IR/Instruction.h"
42#include "llvm/IR/Instructions.h"
43#include "llvm/IR/Intrinsics.h"
44#include "llvm/IR/Type.h"
45#include "llvm/MC/MCSectionMachO.h"
46#include "llvm/Support/CommandLine.h"
47#include "llvm/Support/ErrorHandling.h"
48#include "llvm/Support/MathExtras.h"
49#include "llvm/Support/raw_ostream.h"
50#include "llvm/Target/TargetOptions.h"
51using namespace llvm;
52
53STATISTIC(NumTailCalls, "Number of tail calls");
54STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
55STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments");
56
57// This option should go away when tail calls fully work.
58static cl::opt<bool>
59EnableARMTailCalls("arm-tail-calls", cl::Hidden,
60  cl::desc("Generate tail calls (TEMPORARY OPTION)."),
61  cl::init(false));
62
63cl::opt<bool>
64EnableARMLongCalls("arm-long-calls", cl::Hidden,
65  cl::desc("Generate calls via indirect call instructions"),
66  cl::init(false));
67
68static cl::opt<bool>
69ARMInterworking("arm-interworking", cl::Hidden,
70  cl::desc("Enable / disable ARM interworking (for debugging only)"),
71  cl::init(true));
72
73namespace {
74  class ARMCCState : public CCState {
75  public:
76    ARMCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
77               const TargetMachine &TM, SmallVector<CCValAssign, 16> &locs,
78               LLVMContext &C, ParmContext PC)
79        : CCState(CC, isVarArg, MF, TM, locs, C) {
80      assert(((PC == Call) || (PC == Prologue)) &&
81             "ARMCCState users must specify whether their context is call"
82             "or prologue generation.");
83      CallOrPrologue = PC;
84    }
85  };
86}
87
88// The APCS parameter registers.
89static const uint16_t GPRArgRegs[] = {
90  ARM::R0, ARM::R1, ARM::R2, ARM::R3
91};
92
93void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT,
94                                       MVT PromotedBitwiseVT) {
95  if (VT != PromotedLdStVT) {
96    setOperationAction(ISD::LOAD, VT, Promote);
97    AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
98
99    setOperationAction(ISD::STORE, VT, Promote);
100    AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
101  }
102
103  MVT ElemTy = VT.getVectorElementType();
104  if (ElemTy != MVT::i64 && ElemTy != MVT::f64)
105    setOperationAction(ISD::SETCC, VT, Custom);
106  setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
107  setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
108  if (ElemTy == MVT::i32) {
109    setOperationAction(ISD::SINT_TO_FP, VT, Custom);
110    setOperationAction(ISD::UINT_TO_FP, VT, Custom);
111    setOperationAction(ISD::FP_TO_SINT, VT, Custom);
112    setOperationAction(ISD::FP_TO_UINT, VT, Custom);
113  } else {
114    setOperationAction(ISD::SINT_TO_FP, VT, Expand);
115    setOperationAction(ISD::UINT_TO_FP, VT, Expand);
116    setOperationAction(ISD::FP_TO_SINT, VT, Expand);
117    setOperationAction(ISD::FP_TO_UINT, VT, Expand);
118  }
119  setOperationAction(ISD::BUILD_VECTOR,      VT, Custom);
120  setOperationAction(ISD::VECTOR_SHUFFLE,    VT, Custom);
121  setOperationAction(ISD::CONCAT_VECTORS,    VT, Legal);
122  setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
123  setOperationAction(ISD::SELECT,            VT, Expand);
124  setOperationAction(ISD::SELECT_CC,         VT, Expand);
125  setOperationAction(ISD::VSELECT,           VT, Expand);
126  setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
127  if (VT.isInteger()) {
128    setOperationAction(ISD::SHL, VT, Custom);
129    setOperationAction(ISD::SRA, VT, Custom);
130    setOperationAction(ISD::SRL, VT, Custom);
131  }
132
133  // Promote all bit-wise operations.
134  if (VT.isInteger() && VT != PromotedBitwiseVT) {
135    setOperationAction(ISD::AND, VT, Promote);
136    AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT);
137    setOperationAction(ISD::OR,  VT, Promote);
138    AddPromotedToType (ISD::OR,  VT, PromotedBitwiseVT);
139    setOperationAction(ISD::XOR, VT, Promote);
140    AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT);
141  }
142
143  // Neon does not support vector divide/remainder operations.
144  setOperationAction(ISD::SDIV, VT, Expand);
145  setOperationAction(ISD::UDIV, VT, Expand);
146  setOperationAction(ISD::FDIV, VT, Expand);
147  setOperationAction(ISD::SREM, VT, Expand);
148  setOperationAction(ISD::UREM, VT, Expand);
149  setOperationAction(ISD::FREM, VT, Expand);
150}
151
152void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
153  addRegisterClass(VT, &ARM::DPRRegClass);
154  addTypeForNEON(VT, MVT::f64, MVT::v2i32);
155}
156
157void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
158  addRegisterClass(VT, &ARM::QPRRegClass);
159  addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
160}
161
162static TargetLoweringObjectFile *createTLOF(TargetMachine &TM) {
163  if (TM.getSubtarget<ARMSubtarget>().isTargetDarwin())
164    return new TargetLoweringObjectFileMachO();
165
166  return new ARMElfTargetObjectFile();
167}
168
169ARMTargetLowering::ARMTargetLowering(TargetMachine &TM)
170    : TargetLowering(TM, createTLOF(TM)) {
171  Subtarget = &TM.getSubtarget<ARMSubtarget>();
172  RegInfo = TM.getRegisterInfo();
173  Itins = TM.getInstrItineraryData();
174
175  setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
176
177  if (Subtarget->isTargetDarwin()) {
178    // Uses VFP for Thumb libfuncs if available.
179    if (Subtarget->isThumb() && Subtarget->hasVFP2()) {
180      // Single-precision floating-point arithmetic.
181      setLibcallName(RTLIB::ADD_F32, "__addsf3vfp");
182      setLibcallName(RTLIB::SUB_F32, "__subsf3vfp");
183      setLibcallName(RTLIB::MUL_F32, "__mulsf3vfp");
184      setLibcallName(RTLIB::DIV_F32, "__divsf3vfp");
185
186      // Double-precision floating-point arithmetic.
187      setLibcallName(RTLIB::ADD_F64, "__adddf3vfp");
188      setLibcallName(RTLIB::SUB_F64, "__subdf3vfp");
189      setLibcallName(RTLIB::MUL_F64, "__muldf3vfp");
190      setLibcallName(RTLIB::DIV_F64, "__divdf3vfp");
191
192      // Single-precision comparisons.
193      setLibcallName(RTLIB::OEQ_F32, "__eqsf2vfp");
194      setLibcallName(RTLIB::UNE_F32, "__nesf2vfp");
195      setLibcallName(RTLIB::OLT_F32, "__ltsf2vfp");
196      setLibcallName(RTLIB::OLE_F32, "__lesf2vfp");
197      setLibcallName(RTLIB::OGE_F32, "__gesf2vfp");
198      setLibcallName(RTLIB::OGT_F32, "__gtsf2vfp");
199      setLibcallName(RTLIB::UO_F32,  "__unordsf2vfp");
200      setLibcallName(RTLIB::O_F32,   "__unordsf2vfp");
201
202      setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
203      setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETNE);
204      setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
205      setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
206      setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
207      setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
208      setCmpLibcallCC(RTLIB::UO_F32,  ISD::SETNE);
209      setCmpLibcallCC(RTLIB::O_F32,   ISD::SETEQ);
210
211      // Double-precision comparisons.
212      setLibcallName(RTLIB::OEQ_F64, "__eqdf2vfp");
213      setLibcallName(RTLIB::UNE_F64, "__nedf2vfp");
214      setLibcallName(RTLIB::OLT_F64, "__ltdf2vfp");
215      setLibcallName(RTLIB::OLE_F64, "__ledf2vfp");
216      setLibcallName(RTLIB::OGE_F64, "__gedf2vfp");
217      setLibcallName(RTLIB::OGT_F64, "__gtdf2vfp");
218      setLibcallName(RTLIB::UO_F64,  "__unorddf2vfp");
219      setLibcallName(RTLIB::O_F64,   "__unorddf2vfp");
220
221      setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
222      setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETNE);
223      setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
224      setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
225      setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
226      setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
227      setCmpLibcallCC(RTLIB::UO_F64,  ISD::SETNE);
228      setCmpLibcallCC(RTLIB::O_F64,   ISD::SETEQ);
229
230      // Floating-point to integer conversions.
231      // i64 conversions are done via library routines even when generating VFP
232      // instructions, so use the same ones.
233      setLibcallName(RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp");
234      setLibcallName(RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp");
235      setLibcallName(RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp");
236      setLibcallName(RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp");
237
238      // Conversions between floating types.
239      setLibcallName(RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp");
240      setLibcallName(RTLIB::FPEXT_F32_F64,   "__extendsfdf2vfp");
241
242      // Integer to floating-point conversions.
243      // i64 conversions are done via library routines even when generating VFP
244      // instructions, so use the same ones.
245      // FIXME: There appears to be some naming inconsistency in ARM libgcc:
246      // e.g., __floatunsidf vs. __floatunssidfvfp.
247      setLibcallName(RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp");
248      setLibcallName(RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp");
249      setLibcallName(RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp");
250      setLibcallName(RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp");
251    }
252  }
253
254  // These libcalls are not available in 32-bit.
255  setLibcallName(RTLIB::SHL_I128, 0);
256  setLibcallName(RTLIB::SRL_I128, 0);
257  setLibcallName(RTLIB::SRA_I128, 0);
258
259  if (Subtarget->isAAPCS_ABI() && !Subtarget->isTargetDarwin()) {
260    // Double-precision floating-point arithmetic helper functions
261    // RTABI chapter 4.1.2, Table 2
262    setLibcallName(RTLIB::ADD_F64, "__aeabi_dadd");
263    setLibcallName(RTLIB::DIV_F64, "__aeabi_ddiv");
264    setLibcallName(RTLIB::MUL_F64, "__aeabi_dmul");
265    setLibcallName(RTLIB::SUB_F64, "__aeabi_dsub");
266    setLibcallCallingConv(RTLIB::ADD_F64, CallingConv::ARM_AAPCS);
267    setLibcallCallingConv(RTLIB::DIV_F64, CallingConv::ARM_AAPCS);
268    setLibcallCallingConv(RTLIB::MUL_F64, CallingConv::ARM_AAPCS);
269    setLibcallCallingConv(RTLIB::SUB_F64, CallingConv::ARM_AAPCS);
270
271    // Double-precision floating-point comparison helper functions
272    // RTABI chapter 4.1.2, Table 3
273    setLibcallName(RTLIB::OEQ_F64, "__aeabi_dcmpeq");
274    setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
275    setLibcallName(RTLIB::UNE_F64, "__aeabi_dcmpeq");
276    setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETEQ);
277    setLibcallName(RTLIB::OLT_F64, "__aeabi_dcmplt");
278    setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
279    setLibcallName(RTLIB::OLE_F64, "__aeabi_dcmple");
280    setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
281    setLibcallName(RTLIB::OGE_F64, "__aeabi_dcmpge");
282    setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
283    setLibcallName(RTLIB::OGT_F64, "__aeabi_dcmpgt");
284    setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
285    setLibcallName(RTLIB::UO_F64,  "__aeabi_dcmpun");
286    setCmpLibcallCC(RTLIB::UO_F64,  ISD::SETNE);
287    setLibcallName(RTLIB::O_F64,   "__aeabi_dcmpun");
288    setCmpLibcallCC(RTLIB::O_F64,   ISD::SETEQ);
289    setLibcallCallingConv(RTLIB::OEQ_F64, CallingConv::ARM_AAPCS);
290    setLibcallCallingConv(RTLIB::UNE_F64, CallingConv::ARM_AAPCS);
291    setLibcallCallingConv(RTLIB::OLT_F64, CallingConv::ARM_AAPCS);
292    setLibcallCallingConv(RTLIB::OLE_F64, CallingConv::ARM_AAPCS);
293    setLibcallCallingConv(RTLIB::OGE_F64, CallingConv::ARM_AAPCS);
294    setLibcallCallingConv(RTLIB::OGT_F64, CallingConv::ARM_AAPCS);
295    setLibcallCallingConv(RTLIB::UO_F64, CallingConv::ARM_AAPCS);
296    setLibcallCallingConv(RTLIB::O_F64, CallingConv::ARM_AAPCS);
297
298    // Single-precision floating-point arithmetic helper functions
299    // RTABI chapter 4.1.2, Table 4
300    setLibcallName(RTLIB::ADD_F32, "__aeabi_fadd");
301    setLibcallName(RTLIB::DIV_F32, "__aeabi_fdiv");
302    setLibcallName(RTLIB::MUL_F32, "__aeabi_fmul");
303    setLibcallName(RTLIB::SUB_F32, "__aeabi_fsub");
304    setLibcallCallingConv(RTLIB::ADD_F32, CallingConv::ARM_AAPCS);
305    setLibcallCallingConv(RTLIB::DIV_F32, CallingConv::ARM_AAPCS);
306    setLibcallCallingConv(RTLIB::MUL_F32, CallingConv::ARM_AAPCS);
307    setLibcallCallingConv(RTLIB::SUB_F32, CallingConv::ARM_AAPCS);
308
309    // Single-precision floating-point comparison helper functions
310    // RTABI chapter 4.1.2, Table 5
311    setLibcallName(RTLIB::OEQ_F32, "__aeabi_fcmpeq");
312    setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
313    setLibcallName(RTLIB::UNE_F32, "__aeabi_fcmpeq");
314    setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETEQ);
315    setLibcallName(RTLIB::OLT_F32, "__aeabi_fcmplt");
316    setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
317    setLibcallName(RTLIB::OLE_F32, "__aeabi_fcmple");
318    setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
319    setLibcallName(RTLIB::OGE_F32, "__aeabi_fcmpge");
320    setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
321    setLibcallName(RTLIB::OGT_F32, "__aeabi_fcmpgt");
322    setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
323    setLibcallName(RTLIB::UO_F32,  "__aeabi_fcmpun");
324    setCmpLibcallCC(RTLIB::UO_F32,  ISD::SETNE);
325    setLibcallName(RTLIB::O_F32,   "__aeabi_fcmpun");
326    setCmpLibcallCC(RTLIB::O_F32,   ISD::SETEQ);
327    setLibcallCallingConv(RTLIB::OEQ_F32, CallingConv::ARM_AAPCS);
328    setLibcallCallingConv(RTLIB::UNE_F32, CallingConv::ARM_AAPCS);
329    setLibcallCallingConv(RTLIB::OLT_F32, CallingConv::ARM_AAPCS);
330    setLibcallCallingConv(RTLIB::OLE_F32, CallingConv::ARM_AAPCS);
331    setLibcallCallingConv(RTLIB::OGE_F32, CallingConv::ARM_AAPCS);
332    setLibcallCallingConv(RTLIB::OGT_F32, CallingConv::ARM_AAPCS);
333    setLibcallCallingConv(RTLIB::UO_F32, CallingConv::ARM_AAPCS);
334    setLibcallCallingConv(RTLIB::O_F32, CallingConv::ARM_AAPCS);
335
336    // Floating-point to integer conversions.
337    // RTABI chapter 4.1.2, Table 6
338    setLibcallName(RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz");
339    setLibcallName(RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz");
340    setLibcallName(RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz");
341    setLibcallName(RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz");
342    setLibcallName(RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz");
343    setLibcallName(RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz");
344    setLibcallName(RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz");
345    setLibcallName(RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz");
346    setLibcallCallingConv(RTLIB::FPTOSINT_F64_I32, CallingConv::ARM_AAPCS);
347    setLibcallCallingConv(RTLIB::FPTOUINT_F64_I32, CallingConv::ARM_AAPCS);
348    setLibcallCallingConv(RTLIB::FPTOSINT_F64_I64, CallingConv::ARM_AAPCS);
349    setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::ARM_AAPCS);
350    setLibcallCallingConv(RTLIB::FPTOSINT_F32_I32, CallingConv::ARM_AAPCS);
351    setLibcallCallingConv(RTLIB::FPTOUINT_F32_I32, CallingConv::ARM_AAPCS);
352    setLibcallCallingConv(RTLIB::FPTOSINT_F32_I64, CallingConv::ARM_AAPCS);
353    setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::ARM_AAPCS);
354
355    // Conversions between floating types.
356    // RTABI chapter 4.1.2, Table 7
357    setLibcallName(RTLIB::FPROUND_F64_F32, "__aeabi_d2f");
358    setLibcallName(RTLIB::FPEXT_F32_F64,   "__aeabi_f2d");
359    setLibcallCallingConv(RTLIB::FPROUND_F64_F32, CallingConv::ARM_AAPCS);
360    setLibcallCallingConv(RTLIB::FPEXT_F32_F64, CallingConv::ARM_AAPCS);
361
362    // Integer to floating-point conversions.
363    // RTABI chapter 4.1.2, Table 8
364    setLibcallName(RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d");
365    setLibcallName(RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d");
366    setLibcallName(RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d");
367    setLibcallName(RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d");
368    setLibcallName(RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f");
369    setLibcallName(RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f");
370    setLibcallName(RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f");
371    setLibcallName(RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f");
372    setLibcallCallingConv(RTLIB::SINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
373    setLibcallCallingConv(RTLIB::UINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
374    setLibcallCallingConv(RTLIB::SINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
375    setLibcallCallingConv(RTLIB::UINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
376    setLibcallCallingConv(RTLIB::SINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
377    setLibcallCallingConv(RTLIB::UINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
378    setLibcallCallingConv(RTLIB::SINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
379    setLibcallCallingConv(RTLIB::UINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
380
381    // Long long helper functions
382    // RTABI chapter 4.2, Table 9
383    setLibcallName(RTLIB::MUL_I64,  "__aeabi_lmul");
384    setLibcallName(RTLIB::SHL_I64, "__aeabi_llsl");
385    setLibcallName(RTLIB::SRL_I64, "__aeabi_llsr");
386    setLibcallName(RTLIB::SRA_I64, "__aeabi_lasr");
387    setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::ARM_AAPCS);
388    setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::ARM_AAPCS);
389    setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::ARM_AAPCS);
390    setLibcallCallingConv(RTLIB::SHL_I64, CallingConv::ARM_AAPCS);
391    setLibcallCallingConv(RTLIB::SRL_I64, CallingConv::ARM_AAPCS);
392    setLibcallCallingConv(RTLIB::SRA_I64, CallingConv::ARM_AAPCS);
393
394    // Integer division functions
395    // RTABI chapter 4.3.1
396    setLibcallName(RTLIB::SDIV_I8,  "__aeabi_idiv");
397    setLibcallName(RTLIB::SDIV_I16, "__aeabi_idiv");
398    setLibcallName(RTLIB::SDIV_I32, "__aeabi_idiv");
399    setLibcallName(RTLIB::SDIV_I64, "__aeabi_ldivmod");
400    setLibcallName(RTLIB::UDIV_I8,  "__aeabi_uidiv");
401    setLibcallName(RTLIB::UDIV_I16, "__aeabi_uidiv");
402    setLibcallName(RTLIB::UDIV_I32, "__aeabi_uidiv");
403    setLibcallName(RTLIB::UDIV_I64, "__aeabi_uldivmod");
404    setLibcallCallingConv(RTLIB::SDIV_I8, CallingConv::ARM_AAPCS);
405    setLibcallCallingConv(RTLIB::SDIV_I16, CallingConv::ARM_AAPCS);
406    setLibcallCallingConv(RTLIB::SDIV_I32, CallingConv::ARM_AAPCS);
407    setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::ARM_AAPCS);
408    setLibcallCallingConv(RTLIB::UDIV_I8, CallingConv::ARM_AAPCS);
409    setLibcallCallingConv(RTLIB::UDIV_I16, CallingConv::ARM_AAPCS);
410    setLibcallCallingConv(RTLIB::UDIV_I32, CallingConv::ARM_AAPCS);
411    setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::ARM_AAPCS);
412
413    // Memory operations
414    // RTABI chapter 4.3.4
415    setLibcallName(RTLIB::MEMCPY,  "__aeabi_memcpy");
416    setLibcallName(RTLIB::MEMMOVE, "__aeabi_memmove");
417    setLibcallName(RTLIB::MEMSET,  "__aeabi_memset");
418    setLibcallCallingConv(RTLIB::MEMCPY, CallingConv::ARM_AAPCS);
419    setLibcallCallingConv(RTLIB::MEMMOVE, CallingConv::ARM_AAPCS);
420    setLibcallCallingConv(RTLIB::MEMSET, CallingConv::ARM_AAPCS);
421  }
422
423  // Use divmod compiler-rt calls for iOS 5.0 and later.
424  if (Subtarget->getTargetTriple().getOS() == Triple::IOS &&
425      !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) {
426    setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
427    setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
428  }
429
430  if (Subtarget->isThumb1Only())
431    addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
432  else
433    addRegisterClass(MVT::i32, &ARM::GPRRegClass);
434  if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
435      !Subtarget->isThumb1Only()) {
436    addRegisterClass(MVT::f32, &ARM::SPRRegClass);
437    if (!Subtarget->isFPOnlySP())
438      addRegisterClass(MVT::f64, &ARM::DPRRegClass);
439
440    setTruncStoreAction(MVT::f64, MVT::f32, Expand);
441  }
442
443  for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
444       VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
445    for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
446         InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
447      setTruncStoreAction((MVT::SimpleValueType)VT,
448                          (MVT::SimpleValueType)InnerVT, Expand);
449    setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
450    setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
451    setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
452  }
453
454  setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
455
456  if (Subtarget->hasNEON()) {
457    addDRTypeForNEON(MVT::v2f32);
458    addDRTypeForNEON(MVT::v8i8);
459    addDRTypeForNEON(MVT::v4i16);
460    addDRTypeForNEON(MVT::v2i32);
461    addDRTypeForNEON(MVT::v1i64);
462
463    addQRTypeForNEON(MVT::v4f32);
464    addQRTypeForNEON(MVT::v2f64);
465    addQRTypeForNEON(MVT::v16i8);
466    addQRTypeForNEON(MVT::v8i16);
467    addQRTypeForNEON(MVT::v4i32);
468    addQRTypeForNEON(MVT::v2i64);
469
470    // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
471    // neither Neon nor VFP support any arithmetic operations on it.
472    // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
473    // supported for v4f32.
474    setOperationAction(ISD::FADD, MVT::v2f64, Expand);
475    setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
476    setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
477    // FIXME: Code duplication: FDIV and FREM are expanded always, see
478    // ARMTargetLowering::addTypeForNEON method for details.
479    setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
480    setOperationAction(ISD::FREM, MVT::v2f64, Expand);
481    // FIXME: Create unittest.
482    // In another words, find a way when "copysign" appears in DAG with vector
483    // operands.
484    setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
485    // FIXME: Code duplication: SETCC has custom operation action, see
486    // ARMTargetLowering::addTypeForNEON method for details.
487    setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
488    // FIXME: Create unittest for FNEG and for FABS.
489    setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
490    setOperationAction(ISD::FABS, MVT::v2f64, Expand);
491    setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
492    setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
493    setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
494    setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
495    setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
496    setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
497    setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
498    setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
499    setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
500    setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
501    // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
502    setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
503    setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
504    setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
505    setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
506    setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
507
508    setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
509    setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
510    setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
511    setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
512    setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
513    setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
514    setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
515    setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
516    setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
517    setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
518    setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
519    setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
520    setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
521    setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
522    setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
523
524    // Neon does not support some operations on v1i64 and v2i64 types.
525    setOperationAction(ISD::MUL, MVT::v1i64, Expand);
526    // Custom handling for some quad-vector types to detect VMULL.
527    setOperationAction(ISD::MUL, MVT::v8i16, Custom);
528    setOperationAction(ISD::MUL, MVT::v4i32, Custom);
529    setOperationAction(ISD::MUL, MVT::v2i64, Custom);
530    // Custom handling for some vector types to avoid expensive expansions
531    setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
532    setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
533    setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
534    setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
535    setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
536    setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
537    // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
538    // a destination type that is wider than the source, and nor does
539    // it have a FP_TO_[SU]INT instruction with a narrower destination than
540    // source.
541    setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
542    setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
543    setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
544    setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
545
546    setOperationAction(ISD::FP_ROUND,   MVT::v2f32, Expand);
547    setOperationAction(ISD::FP_EXTEND,  MVT::v2f64, Expand);
548
549    // NEON does not have single instruction CTPOP for vectors with element
550    // types wider than 8-bits.  However, custom lowering can leverage the
551    // v8i8/v16i8 vcnt instruction.
552    setOperationAction(ISD::CTPOP,      MVT::v2i32, Custom);
553    setOperationAction(ISD::CTPOP,      MVT::v4i32, Custom);
554    setOperationAction(ISD::CTPOP,      MVT::v4i16, Custom);
555    setOperationAction(ISD::CTPOP,      MVT::v8i16, Custom);
556
557    setTargetDAGCombine(ISD::INTRINSIC_VOID);
558    setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
559    setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
560    setTargetDAGCombine(ISD::SHL);
561    setTargetDAGCombine(ISD::SRL);
562    setTargetDAGCombine(ISD::SRA);
563    setTargetDAGCombine(ISD::SIGN_EXTEND);
564    setTargetDAGCombine(ISD::ZERO_EXTEND);
565    setTargetDAGCombine(ISD::ANY_EXTEND);
566    setTargetDAGCombine(ISD::SELECT_CC);
567    setTargetDAGCombine(ISD::BUILD_VECTOR);
568    setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
569    setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
570    setTargetDAGCombine(ISD::STORE);
571    setTargetDAGCombine(ISD::FP_TO_SINT);
572    setTargetDAGCombine(ISD::FP_TO_UINT);
573    setTargetDAGCombine(ISD::FDIV);
574
575    // It is legal to extload from v4i8 to v4i16 or v4i32.
576    MVT Tys[6] = {MVT::v8i8, MVT::v4i8, MVT::v2i8,
577                  MVT::v4i16, MVT::v2i16,
578                  MVT::v2i32};
579    for (unsigned i = 0; i < 6; ++i) {
580      setLoadExtAction(ISD::EXTLOAD, Tys[i], Legal);
581      setLoadExtAction(ISD::ZEXTLOAD, Tys[i], Legal);
582      setLoadExtAction(ISD::SEXTLOAD, Tys[i], Legal);
583    }
584  }
585
586  // ARM and Thumb2 support UMLAL/SMLAL.
587  if (!Subtarget->isThumb1Only())
588    setTargetDAGCombine(ISD::ADDC);
589
590
591  computeRegisterProperties();
592
593  // ARM does not have f32 extending load.
594  setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
595
596  // ARM does not have i1 sign extending load.
597  setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
598
599  // ARM supports all 4 flavors of integer indexed load / store.
600  if (!Subtarget->isThumb1Only()) {
601    for (unsigned im = (unsigned)ISD::PRE_INC;
602         im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
603      setIndexedLoadAction(im,  MVT::i1,  Legal);
604      setIndexedLoadAction(im,  MVT::i8,  Legal);
605      setIndexedLoadAction(im,  MVT::i16, Legal);
606      setIndexedLoadAction(im,  MVT::i32, Legal);
607      setIndexedStoreAction(im, MVT::i1,  Legal);
608      setIndexedStoreAction(im, MVT::i8,  Legal);
609      setIndexedStoreAction(im, MVT::i16, Legal);
610      setIndexedStoreAction(im, MVT::i32, Legal);
611    }
612  }
613
614  // i64 operation support.
615  setOperationAction(ISD::MUL,     MVT::i64, Expand);
616  setOperationAction(ISD::MULHU,   MVT::i32, Expand);
617  if (Subtarget->isThumb1Only()) {
618    setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
619    setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
620  }
621  if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
622      || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
623    setOperationAction(ISD::MULHS, MVT::i32, Expand);
624
625  setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
626  setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
627  setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
628  setOperationAction(ISD::SRL,       MVT::i64, Custom);
629  setOperationAction(ISD::SRA,       MVT::i64, Custom);
630
631  if (!Subtarget->isThumb1Only()) {
632    // FIXME: We should do this for Thumb1 as well.
633    setOperationAction(ISD::ADDC,    MVT::i32, Custom);
634    setOperationAction(ISD::ADDE,    MVT::i32, Custom);
635    setOperationAction(ISD::SUBC,    MVT::i32, Custom);
636    setOperationAction(ISD::SUBE,    MVT::i32, Custom);
637  }
638
639  // ARM does not have ROTL.
640  setOperationAction(ISD::ROTL,  MVT::i32, Expand);
641  setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
642  setOperationAction(ISD::CTPOP, MVT::i32, Expand);
643  if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
644    setOperationAction(ISD::CTLZ, MVT::i32, Expand);
645
646  // These just redirect to CTTZ and CTLZ on ARM.
647  setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i32  , Expand);
648  setOperationAction(ISD::CTLZ_ZERO_UNDEF  , MVT::i32  , Expand);
649
650  // Only ARMv6 has BSWAP.
651  if (!Subtarget->hasV6Ops())
652    setOperationAction(ISD::BSWAP, MVT::i32, Expand);
653
654  if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
655      !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
656    // These are expanded into libcalls if the cpu doesn't have HW divider.
657    setOperationAction(ISD::SDIV,  MVT::i32, Expand);
658    setOperationAction(ISD::UDIV,  MVT::i32, Expand);
659  }
660  setOperationAction(ISD::SREM,  MVT::i32, Expand);
661  setOperationAction(ISD::UREM,  MVT::i32, Expand);
662  setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
663  setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
664
665  setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
666  setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
667  setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
668  setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
669  setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
670
671  setOperationAction(ISD::TRAP, MVT::Other, Legal);
672
673  // Use the default implementation.
674  setOperationAction(ISD::VASTART,            MVT::Other, Custom);
675  setOperationAction(ISD::VAARG,              MVT::Other, Expand);
676  setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
677  setOperationAction(ISD::VAEND,              MVT::Other, Expand);
678  setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
679  setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
680
681  if (!Subtarget->isTargetDarwin()) {
682    // Non-Darwin platforms may return values in these registers via the
683    // personality function.
684    setOperationAction(ISD::EHSELECTION,      MVT::i32,   Expand);
685    setOperationAction(ISD::EXCEPTIONADDR,    MVT::i32,   Expand);
686    setExceptionPointerRegister(ARM::R0);
687    setExceptionSelectorRegister(ARM::R1);
688  }
689
690  setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
691  // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
692  // the default expansion.
693  // FIXME: This should be checking for v6k, not just v6.
694  if (Subtarget->hasDataBarrier() ||
695      (Subtarget->hasV6Ops() && !Subtarget->isThumb())) {
696    // membarrier needs custom lowering; the rest are legal and handled
697    // normally.
698    setOperationAction(ISD::MEMBARRIER, MVT::Other, Custom);
699    setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
700    // Custom lowering for 64-bit ops
701    setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i64, Custom);
702    setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i64, Custom);
703    setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i64, Custom);
704    setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i64, Custom);
705    setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i64, Custom);
706    setOperationAction(ISD::ATOMIC_SWAP,      MVT::i64, Custom);
707    setOperationAction(ISD::ATOMIC_LOAD_MIN,  MVT::i64, Custom);
708    setOperationAction(ISD::ATOMIC_LOAD_MAX,  MVT::i64, Custom);
709    setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
710    setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
711    setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i64, Custom);
712    // Automatically insert fences (dmb ist) around ATOMIC_SWAP etc.
713    setInsertFencesForAtomic(true);
714  } else {
715    // Set them all for expansion, which will force libcalls.
716    setOperationAction(ISD::MEMBARRIER, MVT::Other, Expand);
717    setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other, Expand);
718    setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
719    setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
720    setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
721    setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
722    setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
723    setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
724    setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
725    setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
726    setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
727    setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
728    setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
729    setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
730    // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
731    // Unordered/Monotonic case.
732    setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
733    setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
734    // Since the libcalls include locking, fold in the fences
735    setShouldFoldAtomicFences(true);
736  }
737
738  setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
739
740  // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
741  if (!Subtarget->hasV6Ops()) {
742    setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
743    setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
744  }
745  setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
746
747  if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
748      !Subtarget->isThumb1Only()) {
749    // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
750    // iff target supports vfp2.
751    setOperationAction(ISD::BITCAST, MVT::i64, Custom);
752    setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
753  }
754
755  // We want to custom lower some of our intrinsics.
756  setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
757  if (Subtarget->isTargetDarwin()) {
758    setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
759    setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
760    setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
761  }
762
763  setOperationAction(ISD::SETCC,     MVT::i32, Expand);
764  setOperationAction(ISD::SETCC,     MVT::f32, Expand);
765  setOperationAction(ISD::SETCC,     MVT::f64, Expand);
766  setOperationAction(ISD::SELECT,    MVT::i32, Custom);
767  setOperationAction(ISD::SELECT,    MVT::f32, Custom);
768  setOperationAction(ISD::SELECT,    MVT::f64, Custom);
769  setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
770  setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
771  setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
772
773  setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
774  setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
775  setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
776  setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
777  setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
778
779  // We don't support sin/cos/fmod/copysign/pow
780  setOperationAction(ISD::FSIN,      MVT::f64, Expand);
781  setOperationAction(ISD::FSIN,      MVT::f32, Expand);
782  setOperationAction(ISD::FCOS,      MVT::f32, Expand);
783  setOperationAction(ISD::FCOS,      MVT::f64, Expand);
784  setOperationAction(ISD::FSINCOS,   MVT::f64, Expand);
785  setOperationAction(ISD::FSINCOS,   MVT::f32, Expand);
786  setOperationAction(ISD::FREM,      MVT::f64, Expand);
787  setOperationAction(ISD::FREM,      MVT::f32, Expand);
788  if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
789      !Subtarget->isThumb1Only()) {
790    setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
791    setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
792  }
793  setOperationAction(ISD::FPOW,      MVT::f64, Expand);
794  setOperationAction(ISD::FPOW,      MVT::f32, Expand);
795
796  if (!Subtarget->hasVFP4()) {
797    setOperationAction(ISD::FMA, MVT::f64, Expand);
798    setOperationAction(ISD::FMA, MVT::f32, Expand);
799  }
800
801  // Various VFP goodness
802  if (!TM.Options.UseSoftFloat && !Subtarget->isThumb1Only()) {
803    // int <-> fp are custom expanded into bit_convert + ARMISD ops.
804    if (Subtarget->hasVFP2()) {
805      setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
806      setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
807      setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
808      setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
809    }
810    // Special handling for half-precision FP.
811    if (!Subtarget->hasFP16()) {
812      setOperationAction(ISD::FP16_TO_FP32, MVT::f32, Expand);
813      setOperationAction(ISD::FP32_TO_FP16, MVT::i32, Expand);
814    }
815  }
816
817  // We have target-specific dag combine patterns for the following nodes:
818  // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
819  setTargetDAGCombine(ISD::ADD);
820  setTargetDAGCombine(ISD::SUB);
821  setTargetDAGCombine(ISD::MUL);
822  setTargetDAGCombine(ISD::AND);
823  setTargetDAGCombine(ISD::OR);
824  setTargetDAGCombine(ISD::XOR);
825
826  if (Subtarget->hasV6Ops())
827    setTargetDAGCombine(ISD::SRL);
828
829  setStackPointerRegisterToSaveRestore(ARM::SP);
830
831  if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
832      !Subtarget->hasVFP2())
833    setSchedulingPreference(Sched::RegPressure);
834  else
835    setSchedulingPreference(Sched::Hybrid);
836
837  //// temporary - rewrite interface to use type
838  maxStoresPerMemset = 8;
839  maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
840  maxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
841  maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
842  maxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
843  maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
844
845  // On ARM arguments smaller than 4 bytes are extended, so all arguments
846  // are at least 4 bytes aligned.
847  setMinStackArgumentAlignment(4);
848
849  benefitFromCodePlacementOpt = true;
850
851  // Prefer likely predicted branches to selects on out-of-order cores.
852  predictableSelectIsExpensive = Subtarget->isLikeA9();
853
854  setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
855}
856
857// FIXME: It might make sense to define the representative register class as the
858// nearest super-register that has a non-null superset. For example, DPR_VFP2 is
859// a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
860// SPR's representative would be DPR_VFP2. This should work well if register
861// pressure tracking were modified such that a register use would increment the
862// pressure of the register class's representative and all of it's super
863// classes' representatives transitively. We have not implemented this because
864// of the difficulty prior to coalescing of modeling operand register classes
865// due to the common occurrence of cross class copies and subregister insertions
866// and extractions.
867std::pair<const TargetRegisterClass*, uint8_t>
868ARMTargetLowering::findRepresentativeClass(MVT VT) const{
869  const TargetRegisterClass *RRC = 0;
870  uint8_t Cost = 1;
871  switch (VT.SimpleTy) {
872  default:
873    return TargetLowering::findRepresentativeClass(VT);
874  // Use DPR as representative register class for all floating point
875  // and vector types. Since there are 32 SPR registers and 32 DPR registers so
876  // the cost is 1 for both f32 and f64.
877  case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
878  case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
879    RRC = &ARM::DPRRegClass;
880    // When NEON is used for SP, only half of the register file is available
881    // because operations that define both SP and DP results will be constrained
882    // to the VFP2 class (D0-D15). We currently model this constraint prior to
883    // coalescing by double-counting the SP regs. See the FIXME above.
884    if (Subtarget->useNEONForSinglePrecisionFP())
885      Cost = 2;
886    break;
887  case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
888  case MVT::v4f32: case MVT::v2f64:
889    RRC = &ARM::DPRRegClass;
890    Cost = 2;
891    break;
892  case MVT::v4i64:
893    RRC = &ARM::DPRRegClass;
894    Cost = 4;
895    break;
896  case MVT::v8i64:
897    RRC = &ARM::DPRRegClass;
898    Cost = 8;
899    break;
900  }
901  return std::make_pair(RRC, Cost);
902}
903
904const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
905  switch (Opcode) {
906  default: return 0;
907  case ARMISD::Wrapper:       return "ARMISD::Wrapper";
908  case ARMISD::WrapperDYN:    return "ARMISD::WrapperDYN";
909  case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
910  case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
911  case ARMISD::CALL:          return "ARMISD::CALL";
912  case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
913  case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
914  case ARMISD::tCALL:         return "ARMISD::tCALL";
915  case ARMISD::BRCOND:        return "ARMISD::BRCOND";
916  case ARMISD::BR_JT:         return "ARMISD::BR_JT";
917  case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
918  case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
919  case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
920  case ARMISD::CMP:           return "ARMISD::CMP";
921  case ARMISD::CMN:           return "ARMISD::CMN";
922  case ARMISD::CMPZ:          return "ARMISD::CMPZ";
923  case ARMISD::CMPFP:         return "ARMISD::CMPFP";
924  case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
925  case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
926  case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
927
928  case ARMISD::CMOV:          return "ARMISD::CMOV";
929
930  case ARMISD::RBIT:          return "ARMISD::RBIT";
931
932  case ARMISD::FTOSI:         return "ARMISD::FTOSI";
933  case ARMISD::FTOUI:         return "ARMISD::FTOUI";
934  case ARMISD::SITOF:         return "ARMISD::SITOF";
935  case ARMISD::UITOF:         return "ARMISD::UITOF";
936
937  case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
938  case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
939  case ARMISD::RRX:           return "ARMISD::RRX";
940
941  case ARMISD::ADDC:          return "ARMISD::ADDC";
942  case ARMISD::ADDE:          return "ARMISD::ADDE";
943  case ARMISD::SUBC:          return "ARMISD::SUBC";
944  case ARMISD::SUBE:          return "ARMISD::SUBE";
945
946  case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
947  case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
948
949  case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
950  case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
951
952  case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
953
954  case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
955
956  case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
957
958  case ARMISD::MEMBARRIER:    return "ARMISD::MEMBARRIER";
959  case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
960
961  case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
962
963  case ARMISD::VCEQ:          return "ARMISD::VCEQ";
964  case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
965  case ARMISD::VCGE:          return "ARMISD::VCGE";
966  case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
967  case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
968  case ARMISD::VCGEU:         return "ARMISD::VCGEU";
969  case ARMISD::VCGT:          return "ARMISD::VCGT";
970  case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
971  case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
972  case ARMISD::VCGTU:         return "ARMISD::VCGTU";
973  case ARMISD::VTST:          return "ARMISD::VTST";
974
975  case ARMISD::VSHL:          return "ARMISD::VSHL";
976  case ARMISD::VSHRs:         return "ARMISD::VSHRs";
977  case ARMISD::VSHRu:         return "ARMISD::VSHRu";
978  case ARMISD::VSHLLs:        return "ARMISD::VSHLLs";
979  case ARMISD::VSHLLu:        return "ARMISD::VSHLLu";
980  case ARMISD::VSHLLi:        return "ARMISD::VSHLLi";
981  case ARMISD::VSHRN:         return "ARMISD::VSHRN";
982  case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
983  case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
984  case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
985  case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
986  case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
987  case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
988  case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
989  case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
990  case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
991  case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
992  case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
993  case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
994  case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
995  case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
996  case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
997  case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
998  case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
999  case ARMISD::VDUP:          return "ARMISD::VDUP";
1000  case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
1001  case ARMISD::VEXT:          return "ARMISD::VEXT";
1002  case ARMISD::VREV64:        return "ARMISD::VREV64";
1003  case ARMISD::VREV32:        return "ARMISD::VREV32";
1004  case ARMISD::VREV16:        return "ARMISD::VREV16";
1005  case ARMISD::VZIP:          return "ARMISD::VZIP";
1006  case ARMISD::VUZP:          return "ARMISD::VUZP";
1007  case ARMISD::VTRN:          return "ARMISD::VTRN";
1008  case ARMISD::VTBL1:         return "ARMISD::VTBL1";
1009  case ARMISD::VTBL2:         return "ARMISD::VTBL2";
1010  case ARMISD::VMULLs:        return "ARMISD::VMULLs";
1011  case ARMISD::VMULLu:        return "ARMISD::VMULLu";
1012  case ARMISD::UMLAL:         return "ARMISD::UMLAL";
1013  case ARMISD::SMLAL:         return "ARMISD::SMLAL";
1014  case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
1015  case ARMISD::FMAX:          return "ARMISD::FMAX";
1016  case ARMISD::FMIN:          return "ARMISD::FMIN";
1017  case ARMISD::BFI:           return "ARMISD::BFI";
1018  case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
1019  case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
1020  case ARMISD::VBSL:          return "ARMISD::VBSL";
1021  case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1022  case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1023  case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1024  case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1025  case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1026  case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1027  case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1028  case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1029  case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1030  case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1031  case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1032  case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1033  case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1034  case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1035  case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1036  case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1037  case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1038  case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1039  case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1040  case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1041  }
1042}
1043
1044EVT ARMTargetLowering::getSetCCResultType(EVT VT) const {
1045  if (!VT.isVector()) return getPointerTy();
1046  return VT.changeVectorElementTypeToInteger();
1047}
1048
1049/// getRegClassFor - Return the register class that should be used for the
1050/// specified value type.
1051const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1052  // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1053  // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1054  // load / store 4 to 8 consecutive D registers.
1055  if (Subtarget->hasNEON()) {
1056    if (VT == MVT::v4i64)
1057      return &ARM::QQPRRegClass;
1058    if (VT == MVT::v8i64)
1059      return &ARM::QQQQPRRegClass;
1060  }
1061  return TargetLowering::getRegClassFor(VT);
1062}
1063
1064// Create a fast isel object.
1065FastISel *
1066ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1067                                  const TargetLibraryInfo *libInfo) const {
1068  return ARM::createFastISel(funcInfo, libInfo);
1069}
1070
1071/// getMaximalGlobalOffset - Returns the maximal possible offset which can
1072/// be used for loads / stores from the global.
1073unsigned ARMTargetLowering::getMaximalGlobalOffset() const {
1074  return (Subtarget->isThumb1Only() ? 127 : 4095);
1075}
1076
1077Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1078  unsigned NumVals = N->getNumValues();
1079  if (!NumVals)
1080    return Sched::RegPressure;
1081
1082  for (unsigned i = 0; i != NumVals; ++i) {
1083    EVT VT = N->getValueType(i);
1084    if (VT == MVT::Glue || VT == MVT::Other)
1085      continue;
1086    if (VT.isFloatingPoint() || VT.isVector())
1087      return Sched::ILP;
1088  }
1089
1090  if (!N->isMachineOpcode())
1091    return Sched::RegPressure;
1092
1093  // Load are scheduled for latency even if there instruction itinerary
1094  // is not available.
1095  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1096  const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1097
1098  if (MCID.getNumDefs() == 0)
1099    return Sched::RegPressure;
1100  if (!Itins->isEmpty() &&
1101      Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1102    return Sched::ILP;
1103
1104  return Sched::RegPressure;
1105}
1106
1107//===----------------------------------------------------------------------===//
1108// Lowering Code
1109//===----------------------------------------------------------------------===//
1110
1111/// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1112static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1113  switch (CC) {
1114  default: llvm_unreachable("Unknown condition code!");
1115  case ISD::SETNE:  return ARMCC::NE;
1116  case ISD::SETEQ:  return ARMCC::EQ;
1117  case ISD::SETGT:  return ARMCC::GT;
1118  case ISD::SETGE:  return ARMCC::GE;
1119  case ISD::SETLT:  return ARMCC::LT;
1120  case ISD::SETLE:  return ARMCC::LE;
1121  case ISD::SETUGT: return ARMCC::HI;
1122  case ISD::SETUGE: return ARMCC::HS;
1123  case ISD::SETULT: return ARMCC::LO;
1124  case ISD::SETULE: return ARMCC::LS;
1125  }
1126}
1127
1128/// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1129static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1130                        ARMCC::CondCodes &CondCode2) {
1131  CondCode2 = ARMCC::AL;
1132  switch (CC) {
1133  default: llvm_unreachable("Unknown FP condition!");
1134  case ISD::SETEQ:
1135  case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1136  case ISD::SETGT:
1137  case ISD::SETOGT: CondCode = ARMCC::GT; break;
1138  case ISD::SETGE:
1139  case ISD::SETOGE: CondCode = ARMCC::GE; break;
1140  case ISD::SETOLT: CondCode = ARMCC::MI; break;
1141  case ISD::SETOLE: CondCode = ARMCC::LS; break;
1142  case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1143  case ISD::SETO:   CondCode = ARMCC::VC; break;
1144  case ISD::SETUO:  CondCode = ARMCC::VS; break;
1145  case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1146  case ISD::SETUGT: CondCode = ARMCC::HI; break;
1147  case ISD::SETUGE: CondCode = ARMCC::PL; break;
1148  case ISD::SETLT:
1149  case ISD::SETULT: CondCode = ARMCC::LT; break;
1150  case ISD::SETLE:
1151  case ISD::SETULE: CondCode = ARMCC::LE; break;
1152  case ISD::SETNE:
1153  case ISD::SETUNE: CondCode = ARMCC::NE; break;
1154  }
1155}
1156
1157//===----------------------------------------------------------------------===//
1158//                      Calling Convention Implementation
1159//===----------------------------------------------------------------------===//
1160
1161#include "ARMGenCallingConv.inc"
1162
1163/// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1164/// given CallingConvention value.
1165CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1166                                                 bool Return,
1167                                                 bool isVarArg) const {
1168  switch (CC) {
1169  default:
1170    llvm_unreachable("Unsupported calling convention");
1171  case CallingConv::Fast:
1172    if (Subtarget->hasVFP2() && !isVarArg) {
1173      if (!Subtarget->isAAPCS_ABI())
1174        return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1175      // For AAPCS ABI targets, just use VFP variant of the calling convention.
1176      return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1177    }
1178    // Fallthrough
1179  case CallingConv::C: {
1180    // Use target triple & subtarget features to do actual dispatch.
1181    if (!Subtarget->isAAPCS_ABI())
1182      return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1183    else if (Subtarget->hasVFP2() &&
1184             getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1185             !isVarArg)
1186      return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1187    return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1188  }
1189  case CallingConv::ARM_AAPCS_VFP:
1190    if (!isVarArg)
1191      return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1192    // Fallthrough
1193  case CallingConv::ARM_AAPCS:
1194    return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1195  case CallingConv::ARM_APCS:
1196    return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1197  case CallingConv::GHC:
1198    return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1199  }
1200}
1201
1202/// LowerCallResult - Lower the result values of a call into the
1203/// appropriate copies out of appropriate physical registers.
1204SDValue
1205ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1206                                   CallingConv::ID CallConv, bool isVarArg,
1207                                   const SmallVectorImpl<ISD::InputArg> &Ins,
1208                                   DebugLoc dl, SelectionDAG &DAG,
1209                                   SmallVectorImpl<SDValue> &InVals) const {
1210
1211  // Assign locations to each value returned by this call.
1212  SmallVector<CCValAssign, 16> RVLocs;
1213  ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1214                    getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1215  CCInfo.AnalyzeCallResult(Ins,
1216                           CCAssignFnForNode(CallConv, /* Return*/ true,
1217                                             isVarArg));
1218
1219  // Copy all of the result registers out of their specified physreg.
1220  for (unsigned i = 0; i != RVLocs.size(); ++i) {
1221    CCValAssign VA = RVLocs[i];
1222
1223    SDValue Val;
1224    if (VA.needsCustom()) {
1225      // Handle f64 or half of a v2f64.
1226      SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1227                                      InFlag);
1228      Chain = Lo.getValue(1);
1229      InFlag = Lo.getValue(2);
1230      VA = RVLocs[++i]; // skip ahead to next loc
1231      SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1232                                      InFlag);
1233      Chain = Hi.getValue(1);
1234      InFlag = Hi.getValue(2);
1235      Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1236
1237      if (VA.getLocVT() == MVT::v2f64) {
1238        SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1239        Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1240                          DAG.getConstant(0, MVT::i32));
1241
1242        VA = RVLocs[++i]; // skip ahead to next loc
1243        Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1244        Chain = Lo.getValue(1);
1245        InFlag = Lo.getValue(2);
1246        VA = RVLocs[++i]; // skip ahead to next loc
1247        Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1248        Chain = Hi.getValue(1);
1249        InFlag = Hi.getValue(2);
1250        Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1251        Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1252                          DAG.getConstant(1, MVT::i32));
1253      }
1254    } else {
1255      Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1256                               InFlag);
1257      Chain = Val.getValue(1);
1258      InFlag = Val.getValue(2);
1259    }
1260
1261    switch (VA.getLocInfo()) {
1262    default: llvm_unreachable("Unknown loc info!");
1263    case CCValAssign::Full: break;
1264    case CCValAssign::BCvt:
1265      Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1266      break;
1267    }
1268
1269    InVals.push_back(Val);
1270  }
1271
1272  return Chain;
1273}
1274
1275/// LowerMemOpCallTo - Store the argument to the stack.
1276SDValue
1277ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1278                                    SDValue StackPtr, SDValue Arg,
1279                                    DebugLoc dl, SelectionDAG &DAG,
1280                                    const CCValAssign &VA,
1281                                    ISD::ArgFlagsTy Flags) const {
1282  unsigned LocMemOffset = VA.getLocMemOffset();
1283  SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1284  PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1285  return DAG.getStore(Chain, dl, Arg, PtrOff,
1286                      MachinePointerInfo::getStack(LocMemOffset),
1287                      false, false, 0);
1288}
1289
1290void ARMTargetLowering::PassF64ArgInRegs(DebugLoc dl, SelectionDAG &DAG,
1291                                         SDValue Chain, SDValue &Arg,
1292                                         RegsToPassVector &RegsToPass,
1293                                         CCValAssign &VA, CCValAssign &NextVA,
1294                                         SDValue &StackPtr,
1295                                         SmallVector<SDValue, 8> &MemOpChains,
1296                                         ISD::ArgFlagsTy Flags) const {
1297
1298  SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1299                              DAG.getVTList(MVT::i32, MVT::i32), Arg);
1300  RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd));
1301
1302  if (NextVA.isRegLoc())
1303    RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1)));
1304  else {
1305    assert(NextVA.isMemLoc());
1306    if (StackPtr.getNode() == 0)
1307      StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1308
1309    MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1),
1310                                           dl, DAG, NextVA,
1311                                           Flags));
1312  }
1313}
1314
1315/// LowerCall - Lowering a call into a callseq_start <-
1316/// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1317/// nodes.
1318SDValue
1319ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1320                             SmallVectorImpl<SDValue> &InVals) const {
1321  SelectionDAG &DAG                     = CLI.DAG;
1322  DebugLoc &dl                          = CLI.DL;
1323  SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
1324  SmallVector<SDValue, 32> &OutVals     = CLI.OutVals;
1325  SmallVector<ISD::InputArg, 32> &Ins   = CLI.Ins;
1326  SDValue Chain                         = CLI.Chain;
1327  SDValue Callee                        = CLI.Callee;
1328  bool &isTailCall                      = CLI.IsTailCall;
1329  CallingConv::ID CallConv              = CLI.CallConv;
1330  bool doesNotRet                       = CLI.DoesNotReturn;
1331  bool isVarArg                         = CLI.IsVarArg;
1332
1333  MachineFunction &MF = DAG.getMachineFunction();
1334  bool IsStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1335  bool IsSibCall = false;
1336  // Disable tail calls if they're not supported.
1337  if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
1338    isTailCall = false;
1339  if (isTailCall) {
1340    // Check if it's really possible to do a tail call.
1341    isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1342                    isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
1343                                                   Outs, OutVals, Ins, DAG);
1344    // We don't support GuaranteedTailCallOpt for ARM, only automatically
1345    // detected sibcalls.
1346    if (isTailCall) {
1347      ++NumTailCalls;
1348      IsSibCall = true;
1349    }
1350  }
1351
1352  // Analyze operands of the call, assigning locations to each operand.
1353  SmallVector<CCValAssign, 16> ArgLocs;
1354  ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1355                 getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1356  CCInfo.AnalyzeCallOperands(Outs,
1357                             CCAssignFnForNode(CallConv, /* Return*/ false,
1358                                               isVarArg));
1359
1360  // Get a count of how many bytes are to be pushed on the stack.
1361  unsigned NumBytes = CCInfo.getNextStackOffset();
1362
1363  // For tail calls, memory operands are available in our caller's stack.
1364  if (IsSibCall)
1365    NumBytes = 0;
1366
1367  // Adjust the stack pointer for the new arguments...
1368  // These operations are automatically eliminated by the prolog/epilog pass
1369  if (!IsSibCall)
1370    Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1371
1372  SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1373
1374  RegsToPassVector RegsToPass;
1375  SmallVector<SDValue, 8> MemOpChains;
1376
1377  // Walk the register/memloc assignments, inserting copies/loads.  In the case
1378  // of tail call optimization, arguments are handled later.
1379  for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1380       i != e;
1381       ++i, ++realArgIdx) {
1382    CCValAssign &VA = ArgLocs[i];
1383    SDValue Arg = OutVals[realArgIdx];
1384    ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1385    bool isByVal = Flags.isByVal();
1386
1387    // Promote the value if needed.
1388    switch (VA.getLocInfo()) {
1389    default: llvm_unreachable("Unknown loc info!");
1390    case CCValAssign::Full: break;
1391    case CCValAssign::SExt:
1392      Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1393      break;
1394    case CCValAssign::ZExt:
1395      Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1396      break;
1397    case CCValAssign::AExt:
1398      Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1399      break;
1400    case CCValAssign::BCvt:
1401      Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1402      break;
1403    }
1404
1405    // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1406    if (VA.needsCustom()) {
1407      if (VA.getLocVT() == MVT::v2f64) {
1408        SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1409                                  DAG.getConstant(0, MVT::i32));
1410        SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1411                                  DAG.getConstant(1, MVT::i32));
1412
1413        PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1414                         VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1415
1416        VA = ArgLocs[++i]; // skip ahead to next loc
1417        if (VA.isRegLoc()) {
1418          PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1419                           VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1420        } else {
1421          assert(VA.isMemLoc());
1422
1423          MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1424                                                 dl, DAG, VA, Flags));
1425        }
1426      } else {
1427        PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1428                         StackPtr, MemOpChains, Flags);
1429      }
1430    } else if (VA.isRegLoc()) {
1431      RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1432    } else if (isByVal) {
1433      assert(VA.isMemLoc());
1434      unsigned offset = 0;
1435
1436      // True if this byval aggregate will be split between registers
1437      // and memory.
1438      if (CCInfo.isFirstByValRegValid()) {
1439        EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1440        unsigned int i, j;
1441        for (i = 0, j = CCInfo.getFirstByValReg(); j < ARM::R4; i++, j++) {
1442          SDValue Const = DAG.getConstant(4*i, MVT::i32);
1443          SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1444          SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1445                                     MachinePointerInfo(),
1446                                     false, false, false, 0);
1447          MemOpChains.push_back(Load.getValue(1));
1448          RegsToPass.push_back(std::make_pair(j, Load));
1449        }
1450        offset = ARM::R4 - CCInfo.getFirstByValReg();
1451        CCInfo.clearFirstByValReg();
1452      }
1453
1454      if (Flags.getByValSize() - 4*offset > 0) {
1455        unsigned LocMemOffset = VA.getLocMemOffset();
1456        SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1457        SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1458                                  StkPtrOff);
1459        SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1460        SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1461        SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1462                                           MVT::i32);
1463        SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), MVT::i32);
1464
1465        SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1466        SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1467        MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1468                                          Ops, array_lengthof(Ops)));
1469      }
1470    } else if (!IsSibCall) {
1471      assert(VA.isMemLoc());
1472
1473      MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1474                                             dl, DAG, VA, Flags));
1475    }
1476  }
1477
1478  if (!MemOpChains.empty())
1479    Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1480                        &MemOpChains[0], MemOpChains.size());
1481
1482  // Build a sequence of copy-to-reg nodes chained together with token chain
1483  // and flag operands which copy the outgoing args into the appropriate regs.
1484  SDValue InFlag;
1485  // Tail call byval lowering might overwrite argument registers so in case of
1486  // tail call optimization the copies to registers are lowered later.
1487  if (!isTailCall)
1488    for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1489      Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1490                               RegsToPass[i].second, InFlag);
1491      InFlag = Chain.getValue(1);
1492    }
1493
1494  // For tail calls lower the arguments to the 'real' stack slot.
1495  if (isTailCall) {
1496    // Force all the incoming stack arguments to be loaded from the stack
1497    // before any new outgoing arguments are stored to the stack, because the
1498    // outgoing stack slots may alias the incoming argument stack slots, and
1499    // the alias isn't otherwise explicit. This is slightly more conservative
1500    // than necessary, because it means that each store effectively depends
1501    // on every argument instead of just those arguments it would clobber.
1502
1503    // Do not flag preceding copytoreg stuff together with the following stuff.
1504    InFlag = SDValue();
1505    for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1506      Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1507                               RegsToPass[i].second, InFlag);
1508      InFlag = Chain.getValue(1);
1509    }
1510    InFlag =SDValue();
1511  }
1512
1513  // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1514  // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1515  // node so that legalize doesn't hack it.
1516  bool isDirect = false;
1517  bool isARMFunc = false;
1518  bool isLocalARMFunc = false;
1519  ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1520
1521  if (EnableARMLongCalls) {
1522    assert (getTargetMachine().getRelocationModel() == Reloc::Static
1523            && "long-calls with non-static relocation model!");
1524    // Handle a global address or an external symbol. If it's not one of
1525    // those, the target's already in a register, so we don't need to do
1526    // anything extra.
1527    if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1528      const GlobalValue *GV = G->getGlobal();
1529      // Create a constant pool entry for the callee address
1530      unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1531      ARMConstantPoolValue *CPV =
1532        ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1533
1534      // Get the address of the callee into a register
1535      SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1536      CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1537      Callee = DAG.getLoad(getPointerTy(), dl,
1538                           DAG.getEntryNode(), CPAddr,
1539                           MachinePointerInfo::getConstantPool(),
1540                           false, false, false, 0);
1541    } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1542      const char *Sym = S->getSymbol();
1543
1544      // Create a constant pool entry for the callee address
1545      unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1546      ARMConstantPoolValue *CPV =
1547        ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1548                                      ARMPCLabelIndex, 0);
1549      // Get the address of the callee into a register
1550      SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1551      CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1552      Callee = DAG.getLoad(getPointerTy(), dl,
1553                           DAG.getEntryNode(), CPAddr,
1554                           MachinePointerInfo::getConstantPool(),
1555                           false, false, false, 0);
1556    }
1557  } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1558    const GlobalValue *GV = G->getGlobal();
1559    isDirect = true;
1560    bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1561    bool isStub = (isExt && Subtarget->isTargetDarwin()) &&
1562                   getTargetMachine().getRelocationModel() != Reloc::Static;
1563    isARMFunc = !Subtarget->isThumb() || isStub;
1564    // ARM call to a local ARM function is predicable.
1565    isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1566    // tBX takes a register source operand.
1567    if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1568      unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1569      ARMConstantPoolValue *CPV =
1570        ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 4);
1571      SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1572      CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1573      Callee = DAG.getLoad(getPointerTy(), dl,
1574                           DAG.getEntryNode(), CPAddr,
1575                           MachinePointerInfo::getConstantPool(),
1576                           false, false, false, 0);
1577      SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1578      Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1579                           getPointerTy(), Callee, PICLabel);
1580    } else {
1581      // On ELF targets for PIC code, direct calls should go through the PLT
1582      unsigned OpFlags = 0;
1583      if (Subtarget->isTargetELF() &&
1584                  getTargetMachine().getRelocationModel() == Reloc::PIC_)
1585        OpFlags = ARMII::MO_PLT;
1586      Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1587    }
1588  } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1589    isDirect = true;
1590    bool isStub = Subtarget->isTargetDarwin() &&
1591                  getTargetMachine().getRelocationModel() != Reloc::Static;
1592    isARMFunc = !Subtarget->isThumb() || isStub;
1593    // tBX takes a register source operand.
1594    const char *Sym = S->getSymbol();
1595    if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1596      unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1597      ARMConstantPoolValue *CPV =
1598        ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1599                                      ARMPCLabelIndex, 4);
1600      SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1601      CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1602      Callee = DAG.getLoad(getPointerTy(), dl,
1603                           DAG.getEntryNode(), CPAddr,
1604                           MachinePointerInfo::getConstantPool(),
1605                           false, false, false, 0);
1606      SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1607      Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1608                           getPointerTy(), Callee, PICLabel);
1609    } else {
1610      unsigned OpFlags = 0;
1611      // On ELF targets for PIC code, direct calls should go through the PLT
1612      if (Subtarget->isTargetELF() &&
1613                  getTargetMachine().getRelocationModel() == Reloc::PIC_)
1614        OpFlags = ARMII::MO_PLT;
1615      Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1616    }
1617  }
1618
1619  // FIXME: handle tail calls differently.
1620  unsigned CallOpc;
1621  bool HasMinSizeAttr = MF.getFunction()->getAttributes().
1622    hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
1623  if (Subtarget->isThumb()) {
1624    if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1625      CallOpc = ARMISD::CALL_NOLINK;
1626    else
1627      CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1628  } else {
1629    if (!isDirect && !Subtarget->hasV5TOps())
1630      CallOpc = ARMISD::CALL_NOLINK;
1631    else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1632               // Emit regular call when code size is the priority
1633               !HasMinSizeAttr)
1634      // "mov lr, pc; b _foo" to avoid confusing the RSP
1635      CallOpc = ARMISD::CALL_NOLINK;
1636    else
1637      CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1638  }
1639
1640  std::vector<SDValue> Ops;
1641  Ops.push_back(Chain);
1642  Ops.push_back(Callee);
1643
1644  // Add argument registers to the end of the list so that they are known live
1645  // into the call.
1646  for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1647    Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1648                                  RegsToPass[i].second.getValueType()));
1649
1650  // Add a register mask operand representing the call-preserved registers.
1651  const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
1652  const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
1653  assert(Mask && "Missing call preserved mask for calling convention");
1654  Ops.push_back(DAG.getRegisterMask(Mask));
1655
1656  if (InFlag.getNode())
1657    Ops.push_back(InFlag);
1658
1659  SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1660  if (isTailCall)
1661    return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
1662
1663  // Returns a chain and a flag for retval copy to use.
1664  Chain = DAG.getNode(CallOpc, dl, NodeTys, &Ops[0], Ops.size());
1665  InFlag = Chain.getValue(1);
1666
1667  Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1668                             DAG.getIntPtrConstant(0, true), InFlag);
1669  if (!Ins.empty())
1670    InFlag = Chain.getValue(1);
1671
1672  // Handle result values, copying them out of physregs into vregs that we
1673  // return.
1674  return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins,
1675                         dl, DAG, InVals);
1676}
1677
1678/// HandleByVal - Every parameter *after* a byval parameter is passed
1679/// on the stack.  Remember the next parameter register to allocate,
1680/// and then confiscate the rest of the parameter registers to insure
1681/// this.
1682void
1683ARMTargetLowering::HandleByVal(
1684    CCState *State, unsigned &size, unsigned Align) const {
1685  unsigned reg = State->AllocateReg(GPRArgRegs, 4);
1686  assert((State->getCallOrPrologue() == Prologue ||
1687          State->getCallOrPrologue() == Call) &&
1688         "unhandled ParmContext");
1689  if ((!State->isFirstByValRegValid()) &&
1690      (ARM::R0 <= reg) && (reg <= ARM::R3)) {
1691    if (Subtarget->isAAPCS_ABI() && Align > 4) {
1692      unsigned AlignInRegs = Align / 4;
1693      unsigned Waste = (ARM::R4 - reg) % AlignInRegs;
1694      for (unsigned i = 0; i < Waste; ++i)
1695        reg = State->AllocateReg(GPRArgRegs, 4);
1696    }
1697    if (reg != 0) {
1698      State->setFirstByValReg(reg);
1699      // At a call site, a byval parameter that is split between
1700      // registers and memory needs its size truncated here.  In a
1701      // function prologue, such byval parameters are reassembled in
1702      // memory, and are not truncated.
1703      if (State->getCallOrPrologue() == Call) {
1704        unsigned excess = 4 * (ARM::R4 - reg);
1705        assert(size >= excess && "expected larger existing stack allocation");
1706        size -= excess;
1707      }
1708    }
1709  }
1710  // Confiscate any remaining parameter registers to preclude their
1711  // assignment to subsequent parameters.
1712  while (State->AllocateReg(GPRArgRegs, 4))
1713    ;
1714}
1715
1716/// MatchingStackOffset - Return true if the given stack call argument is
1717/// already available in the same position (relatively) of the caller's
1718/// incoming argument stack.
1719static
1720bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1721                         MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1722                         const TargetInstrInfo *TII) {
1723  unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1724  int FI = INT_MAX;
1725  if (Arg.getOpcode() == ISD::CopyFromReg) {
1726    unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1727    if (!TargetRegisterInfo::isVirtualRegister(VR))
1728      return false;
1729    MachineInstr *Def = MRI->getVRegDef(VR);
1730    if (!Def)
1731      return false;
1732    if (!Flags.isByVal()) {
1733      if (!TII->isLoadFromStackSlot(Def, FI))
1734        return false;
1735    } else {
1736      return false;
1737    }
1738  } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1739    if (Flags.isByVal())
1740      // ByVal argument is passed in as a pointer but it's now being
1741      // dereferenced. e.g.
1742      // define @foo(%struct.X* %A) {
1743      //   tail call @bar(%struct.X* byval %A)
1744      // }
1745      return false;
1746    SDValue Ptr = Ld->getBasePtr();
1747    FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1748    if (!FINode)
1749      return false;
1750    FI = FINode->getIndex();
1751  } else
1752    return false;
1753
1754  assert(FI != INT_MAX);
1755  if (!MFI->isFixedObjectIndex(FI))
1756    return false;
1757  return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1758}
1759
1760/// IsEligibleForTailCallOptimization - Check whether the call is eligible
1761/// for tail call optimization. Targets which want to do tail call
1762/// optimization should implement this function.
1763bool
1764ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1765                                                     CallingConv::ID CalleeCC,
1766                                                     bool isVarArg,
1767                                                     bool isCalleeStructRet,
1768                                                     bool isCallerStructRet,
1769                                    const SmallVectorImpl<ISD::OutputArg> &Outs,
1770                                    const SmallVectorImpl<SDValue> &OutVals,
1771                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1772                                                     SelectionDAG& DAG) const {
1773  const Function *CallerF = DAG.getMachineFunction().getFunction();
1774  CallingConv::ID CallerCC = CallerF->getCallingConv();
1775  bool CCMatch = CallerCC == CalleeCC;
1776
1777  // Look for obvious safe cases to perform tail call optimization that do not
1778  // require ABI changes. This is what gcc calls sibcall.
1779
1780  // Do not sibcall optimize vararg calls unless the call site is not passing
1781  // any arguments.
1782  if (isVarArg && !Outs.empty())
1783    return false;
1784
1785  // Also avoid sibcall optimization if either caller or callee uses struct
1786  // return semantics.
1787  if (isCalleeStructRet || isCallerStructRet)
1788    return false;
1789
1790  // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
1791  // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
1792  // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
1793  // support in the assembler and linker to be used. This would need to be
1794  // fixed to fully support tail calls in Thumb1.
1795  //
1796  // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
1797  // LR.  This means if we need to reload LR, it takes an extra instructions,
1798  // which outweighs the value of the tail call; but here we don't know yet
1799  // whether LR is going to be used.  Probably the right approach is to
1800  // generate the tail call here and turn it back into CALL/RET in
1801  // emitEpilogue if LR is used.
1802
1803  // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
1804  // but we need to make sure there are enough registers; the only valid
1805  // registers are the 4 used for parameters.  We don't currently do this
1806  // case.
1807  if (Subtarget->isThumb1Only())
1808    return false;
1809
1810  // If the calling conventions do not match, then we'd better make sure the
1811  // results are returned in the same way as what the caller expects.
1812  if (!CCMatch) {
1813    SmallVector<CCValAssign, 16> RVLocs1;
1814    ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
1815                       getTargetMachine(), RVLocs1, *DAG.getContext(), Call);
1816    CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
1817
1818    SmallVector<CCValAssign, 16> RVLocs2;
1819    ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
1820                       getTargetMachine(), RVLocs2, *DAG.getContext(), Call);
1821    CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
1822
1823    if (RVLocs1.size() != RVLocs2.size())
1824      return false;
1825    for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
1826      if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
1827        return false;
1828      if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
1829        return false;
1830      if (RVLocs1[i].isRegLoc()) {
1831        if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
1832          return false;
1833      } else {
1834        if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
1835          return false;
1836      }
1837    }
1838  }
1839
1840  // If Caller's vararg or byval argument has been split between registers and
1841  // stack, do not perform tail call, since part of the argument is in caller's
1842  // local frame.
1843  const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
1844                                      getInfo<ARMFunctionInfo>();
1845  if (AFI_Caller->getVarArgsRegSaveSize())
1846    return false;
1847
1848  // If the callee takes no arguments then go on to check the results of the
1849  // call.
1850  if (!Outs.empty()) {
1851    // Check if stack adjustment is needed. For now, do not do this if any
1852    // argument is passed on the stack.
1853    SmallVector<CCValAssign, 16> ArgLocs;
1854    ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
1855                      getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1856    CCInfo.AnalyzeCallOperands(Outs,
1857                               CCAssignFnForNode(CalleeCC, false, isVarArg));
1858    if (CCInfo.getNextStackOffset()) {
1859      MachineFunction &MF = DAG.getMachineFunction();
1860
1861      // Check if the arguments are already laid out in the right way as
1862      // the caller's fixed stack objects.
1863      MachineFrameInfo *MFI = MF.getFrameInfo();
1864      const MachineRegisterInfo *MRI = &MF.getRegInfo();
1865      const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1866      for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1867           i != e;
1868           ++i, ++realArgIdx) {
1869        CCValAssign &VA = ArgLocs[i];
1870        EVT RegVT = VA.getLocVT();
1871        SDValue Arg = OutVals[realArgIdx];
1872        ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1873        if (VA.getLocInfo() == CCValAssign::Indirect)
1874          return false;
1875        if (VA.needsCustom()) {
1876          // f64 and vector types are split into multiple registers or
1877          // register/stack-slot combinations.  The types will not match
1878          // the registers; give up on memory f64 refs until we figure
1879          // out what to do about this.
1880          if (!VA.isRegLoc())
1881            return false;
1882          if (!ArgLocs[++i].isRegLoc())
1883            return false;
1884          if (RegVT == MVT::v2f64) {
1885            if (!ArgLocs[++i].isRegLoc())
1886              return false;
1887            if (!ArgLocs[++i].isRegLoc())
1888              return false;
1889          }
1890        } else if (!VA.isRegLoc()) {
1891          if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
1892                                   MFI, MRI, TII))
1893            return false;
1894        }
1895      }
1896    }
1897  }
1898
1899  return true;
1900}
1901
1902bool
1903ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1904                                  MachineFunction &MF, bool isVarArg,
1905                                  const SmallVectorImpl<ISD::OutputArg> &Outs,
1906                                  LLVMContext &Context) const {
1907  SmallVector<CCValAssign, 16> RVLocs;
1908  CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), RVLocs, Context);
1909  return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
1910                                                    isVarArg));
1911}
1912
1913SDValue
1914ARMTargetLowering::LowerReturn(SDValue Chain,
1915                               CallingConv::ID CallConv, bool isVarArg,
1916                               const SmallVectorImpl<ISD::OutputArg> &Outs,
1917                               const SmallVectorImpl<SDValue> &OutVals,
1918                               DebugLoc dl, SelectionDAG &DAG) const {
1919
1920  // CCValAssign - represent the assignment of the return value to a location.
1921  SmallVector<CCValAssign, 16> RVLocs;
1922
1923  // CCState - Info about the registers and stack slots.
1924  ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1925                    getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1926
1927  // Analyze outgoing return values.
1928  CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
1929                                               isVarArg));
1930
1931  // If this is the first return lowered for this function, add
1932  // the regs to the liveout set for the function.
1933  if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
1934    for (unsigned i = 0; i != RVLocs.size(); ++i)
1935      if (RVLocs[i].isRegLoc())
1936        DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
1937  }
1938
1939  SDValue Flag;
1940
1941  // Copy the result values into the output registers.
1942  for (unsigned i = 0, realRVLocIdx = 0;
1943       i != RVLocs.size();
1944       ++i, ++realRVLocIdx) {
1945    CCValAssign &VA = RVLocs[i];
1946    assert(VA.isRegLoc() && "Can only return in registers!");
1947
1948    SDValue Arg = OutVals[realRVLocIdx];
1949
1950    switch (VA.getLocInfo()) {
1951    default: llvm_unreachable("Unknown loc info!");
1952    case CCValAssign::Full: break;
1953    case CCValAssign::BCvt:
1954      Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1955      break;
1956    }
1957
1958    if (VA.needsCustom()) {
1959      if (VA.getLocVT() == MVT::v2f64) {
1960        // Extract the first half and return it in two registers.
1961        SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1962                                   DAG.getConstant(0, MVT::i32));
1963        SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
1964                                       DAG.getVTList(MVT::i32, MVT::i32), Half);
1965
1966        Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), HalfGPRs, Flag);
1967        Flag = Chain.getValue(1);
1968        VA = RVLocs[++i]; // skip ahead to next loc
1969        Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
1970                                 HalfGPRs.getValue(1), Flag);
1971        Flag = Chain.getValue(1);
1972        VA = RVLocs[++i]; // skip ahead to next loc
1973
1974        // Extract the 2nd half and fall through to handle it as an f64 value.
1975        Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1976                          DAG.getConstant(1, MVT::i32));
1977      }
1978      // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
1979      // available.
1980      SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1981                                  DAG.getVTList(MVT::i32, MVT::i32), &Arg, 1);
1982      Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd, Flag);
1983      Flag = Chain.getValue(1);
1984      VA = RVLocs[++i]; // skip ahead to next loc
1985      Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd.getValue(1),
1986                               Flag);
1987    } else
1988      Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
1989
1990    // Guarantee that all emitted copies are
1991    // stuck together, avoiding something bad.
1992    Flag = Chain.getValue(1);
1993  }
1994
1995  SDValue result;
1996  if (Flag.getNode())
1997    result = DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, Chain, Flag);
1998  else // Return Void
1999    result = DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, Chain);
2000
2001  return result;
2002}
2003
2004bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2005  if (N->getNumValues() != 1)
2006    return false;
2007  if (!N->hasNUsesOfValue(1, 0))
2008    return false;
2009
2010  SDValue TCChain = Chain;
2011  SDNode *Copy = *N->use_begin();
2012  if (Copy->getOpcode() == ISD::CopyToReg) {
2013    // If the copy has a glue operand, we conservatively assume it isn't safe to
2014    // perform a tail call.
2015    if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2016      return false;
2017    TCChain = Copy->getOperand(0);
2018  } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2019    SDNode *VMov = Copy;
2020    // f64 returned in a pair of GPRs.
2021    SmallPtrSet<SDNode*, 2> Copies;
2022    for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2023         UI != UE; ++UI) {
2024      if (UI->getOpcode() != ISD::CopyToReg)
2025        return false;
2026      Copies.insert(*UI);
2027    }
2028    if (Copies.size() > 2)
2029      return false;
2030
2031    for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2032         UI != UE; ++UI) {
2033      SDValue UseChain = UI->getOperand(0);
2034      if (Copies.count(UseChain.getNode()))
2035        // Second CopyToReg
2036        Copy = *UI;
2037      else
2038        // First CopyToReg
2039        TCChain = UseChain;
2040    }
2041  } else if (Copy->getOpcode() == ISD::BITCAST) {
2042    // f32 returned in a single GPR.
2043    if (!Copy->hasOneUse())
2044      return false;
2045    Copy = *Copy->use_begin();
2046    if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2047      return false;
2048    Chain = Copy->getOperand(0);
2049  } else {
2050    return false;
2051  }
2052
2053  bool HasRet = false;
2054  for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2055       UI != UE; ++UI) {
2056    if (UI->getOpcode() != ARMISD::RET_FLAG)
2057      return false;
2058    HasRet = true;
2059  }
2060
2061  if (!HasRet)
2062    return false;
2063
2064  Chain = TCChain;
2065  return true;
2066}
2067
2068bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2069  if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
2070    return false;
2071
2072  if (!CI->isTailCall())
2073    return false;
2074
2075  return !Subtarget->isThumb1Only();
2076}
2077
2078// ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2079// their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2080// one of the above mentioned nodes. It has to be wrapped because otherwise
2081// Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2082// be used to form addressing mode. These wrapped nodes will be selected
2083// into MOVi.
2084static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2085  EVT PtrVT = Op.getValueType();
2086  // FIXME there is no actual debug info here
2087  DebugLoc dl = Op.getDebugLoc();
2088  ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2089  SDValue Res;
2090  if (CP->isMachineConstantPoolEntry())
2091    Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2092                                    CP->getAlignment());
2093  else
2094    Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2095                                    CP->getAlignment());
2096  return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2097}
2098
2099unsigned ARMTargetLowering::getJumpTableEncoding() const {
2100  return MachineJumpTableInfo::EK_Inline;
2101}
2102
2103SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2104                                             SelectionDAG &DAG) const {
2105  MachineFunction &MF = DAG.getMachineFunction();
2106  ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2107  unsigned ARMPCLabelIndex = 0;
2108  DebugLoc DL = Op.getDebugLoc();
2109  EVT PtrVT = getPointerTy();
2110  const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2111  Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2112  SDValue CPAddr;
2113  if (RelocM == Reloc::Static) {
2114    CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2115  } else {
2116    unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2117    ARMPCLabelIndex = AFI->createPICLabelUId();
2118    ARMConstantPoolValue *CPV =
2119      ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2120                                      ARMCP::CPBlockAddress, PCAdj);
2121    CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2122  }
2123  CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2124  SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2125                               MachinePointerInfo::getConstantPool(),
2126                               false, false, false, 0);
2127  if (RelocM == Reloc::Static)
2128    return Result;
2129  SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2130  return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2131}
2132
2133// Lower ISD::GlobalTLSAddress using the "general dynamic" model
2134SDValue
2135ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2136                                                 SelectionDAG &DAG) const {
2137  DebugLoc dl = GA->getDebugLoc();
2138  EVT PtrVT = getPointerTy();
2139  unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2140  MachineFunction &MF = DAG.getMachineFunction();
2141  ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2142  unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2143  ARMConstantPoolValue *CPV =
2144    ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2145                                    ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2146  SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2147  Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2148  Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2149                         MachinePointerInfo::getConstantPool(),
2150                         false, false, false, 0);
2151  SDValue Chain = Argument.getValue(1);
2152
2153  SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2154  Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2155
2156  // call __tls_get_addr.
2157  ArgListTy Args;
2158  ArgListEntry Entry;
2159  Entry.Node = Argument;
2160  Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2161  Args.push_back(Entry);
2162  // FIXME: is there useful debug info available here?
2163  TargetLowering::CallLoweringInfo CLI(Chain,
2164                (Type *) Type::getInt32Ty(*DAG.getContext()),
2165                false, false, false, false,
2166                0, CallingConv::C, /*isTailCall=*/false,
2167                /*doesNotRet=*/false, /*isReturnValueUsed=*/true,
2168                DAG.getExternalSymbol("__tls_get_addr", PtrVT), Args, DAG, dl);
2169  std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2170  return CallResult.first;
2171}
2172
2173// Lower ISD::GlobalTLSAddress using the "initial exec" or
2174// "local exec" model.
2175SDValue
2176ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2177                                        SelectionDAG &DAG,
2178                                        TLSModel::Model model) const {
2179  const GlobalValue *GV = GA->getGlobal();
2180  DebugLoc dl = GA->getDebugLoc();
2181  SDValue Offset;
2182  SDValue Chain = DAG.getEntryNode();
2183  EVT PtrVT = getPointerTy();
2184  // Get the Thread Pointer
2185  SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2186
2187  if (model == TLSModel::InitialExec) {
2188    MachineFunction &MF = DAG.getMachineFunction();
2189    ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2190    unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2191    // Initial exec model.
2192    unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2193    ARMConstantPoolValue *CPV =
2194      ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2195                                      ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2196                                      true);
2197    Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2198    Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2199    Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2200                         MachinePointerInfo::getConstantPool(),
2201                         false, false, false, 0);
2202    Chain = Offset.getValue(1);
2203
2204    SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2205    Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2206
2207    Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2208                         MachinePointerInfo::getConstantPool(),
2209                         false, false, false, 0);
2210  } else {
2211    // local exec model
2212    assert(model == TLSModel::LocalExec);
2213    ARMConstantPoolValue *CPV =
2214      ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2215    Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2216    Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2217    Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2218                         MachinePointerInfo::getConstantPool(),
2219                         false, false, false, 0);
2220  }
2221
2222  // The address of the thread local variable is the add of the thread
2223  // pointer with the offset of the variable.
2224  return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2225}
2226
2227SDValue
2228ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2229  // TODO: implement the "local dynamic" model
2230  assert(Subtarget->isTargetELF() &&
2231         "TLS not implemented for non-ELF targets");
2232  GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2233
2234  TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2235
2236  switch (model) {
2237    case TLSModel::GeneralDynamic:
2238    case TLSModel::LocalDynamic:
2239      return LowerToTLSGeneralDynamicModel(GA, DAG);
2240    case TLSModel::InitialExec:
2241    case TLSModel::LocalExec:
2242      return LowerToTLSExecModels(GA, DAG, model);
2243  }
2244  llvm_unreachable("bogus TLS model");
2245}
2246
2247SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2248                                                 SelectionDAG &DAG) const {
2249  EVT PtrVT = getPointerTy();
2250  DebugLoc dl = Op.getDebugLoc();
2251  const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2252  Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2253  if (RelocM == Reloc::PIC_) {
2254    bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2255    ARMConstantPoolValue *CPV =
2256      ARMConstantPoolConstant::Create(GV,
2257                                      UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2258    SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2259    CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2260    SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2261                                 CPAddr,
2262                                 MachinePointerInfo::getConstantPool(),
2263                                 false, false, false, 0);
2264    SDValue Chain = Result.getValue(1);
2265    SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2266    Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2267    if (!UseGOTOFF)
2268      Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2269                           MachinePointerInfo::getGOT(),
2270                           false, false, false, 0);
2271    return Result;
2272  }
2273
2274  // If we have T2 ops, we can materialize the address directly via movt/movw
2275  // pair. This is always cheaper.
2276  if (Subtarget->useMovt()) {
2277    ++NumMovwMovt;
2278    // FIXME: Once remat is capable of dealing with instructions with register
2279    // operands, expand this into two nodes.
2280    return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2281                       DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2282  } else {
2283    SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2284    CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2285    return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2286                       MachinePointerInfo::getConstantPool(),
2287                       false, false, false, 0);
2288  }
2289}
2290
2291SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2292                                                    SelectionDAG &DAG) const {
2293  EVT PtrVT = getPointerTy();
2294  DebugLoc dl = Op.getDebugLoc();
2295  const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2296  Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2297  MachineFunction &MF = DAG.getMachineFunction();
2298  ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2299
2300  // FIXME: Enable this for static codegen when tool issues are fixed.  Also
2301  // update ARMFastISel::ARMMaterializeGV.
2302  if (Subtarget->useMovt() && RelocM != Reloc::Static) {
2303    ++NumMovwMovt;
2304    // FIXME: Once remat is capable of dealing with instructions with register
2305    // operands, expand this into two nodes.
2306    if (RelocM == Reloc::Static)
2307      return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2308                                 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2309
2310    unsigned Wrapper = (RelocM == Reloc::PIC_)
2311      ? ARMISD::WrapperPIC : ARMISD::WrapperDYN;
2312    SDValue Result = DAG.getNode(Wrapper, dl, PtrVT,
2313                                 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2314    if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2315      Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2316                           MachinePointerInfo::getGOT(),
2317                           false, false, false, 0);
2318    return Result;
2319  }
2320
2321  unsigned ARMPCLabelIndex = 0;
2322  SDValue CPAddr;
2323  if (RelocM == Reloc::Static) {
2324    CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2325  } else {
2326    ARMPCLabelIndex = AFI->createPICLabelUId();
2327    unsigned PCAdj = (RelocM != Reloc::PIC_) ? 0 : (Subtarget->isThumb()?4:8);
2328    ARMConstantPoolValue *CPV =
2329      ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue,
2330                                      PCAdj);
2331    CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2332  }
2333  CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2334
2335  SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2336                               MachinePointerInfo::getConstantPool(),
2337                               false, false, false, 0);
2338  SDValue Chain = Result.getValue(1);
2339
2340  if (RelocM == Reloc::PIC_) {
2341    SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2342    Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2343  }
2344
2345  if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2346    Result = DAG.getLoad(PtrVT, dl, Chain, Result, MachinePointerInfo::getGOT(),
2347                         false, false, false, 0);
2348
2349  return Result;
2350}
2351
2352SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2353                                                    SelectionDAG &DAG) const {
2354  assert(Subtarget->isTargetELF() &&
2355         "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2356  MachineFunction &MF = DAG.getMachineFunction();
2357  ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2358  unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2359  EVT PtrVT = getPointerTy();
2360  DebugLoc dl = Op.getDebugLoc();
2361  unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2362  ARMConstantPoolValue *CPV =
2363    ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2364                                  ARMPCLabelIndex, PCAdj);
2365  SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2366  CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2367  SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2368                               MachinePointerInfo::getConstantPool(),
2369                               false, false, false, 0);
2370  SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2371  return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2372}
2373
2374SDValue
2375ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2376  DebugLoc dl = Op.getDebugLoc();
2377  SDValue Val = DAG.getConstant(0, MVT::i32);
2378  return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2379                     DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2380                     Op.getOperand(1), Val);
2381}
2382
2383SDValue
2384ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2385  DebugLoc dl = Op.getDebugLoc();
2386  return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2387                     Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2388}
2389
2390SDValue
2391ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2392                                          const ARMSubtarget *Subtarget) const {
2393  unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2394  DebugLoc dl = Op.getDebugLoc();
2395  switch (IntNo) {
2396  default: return SDValue();    // Don't custom lower most intrinsics.
2397  case Intrinsic::arm_thread_pointer: {
2398    EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2399    return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2400  }
2401  case Intrinsic::eh_sjlj_lsda: {
2402    MachineFunction &MF = DAG.getMachineFunction();
2403    ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2404    unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2405    EVT PtrVT = getPointerTy();
2406    DebugLoc dl = Op.getDebugLoc();
2407    Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2408    SDValue CPAddr;
2409    unsigned PCAdj = (RelocM != Reloc::PIC_)
2410      ? 0 : (Subtarget->isThumb() ? 4 : 8);
2411    ARMConstantPoolValue *CPV =
2412      ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2413                                      ARMCP::CPLSDA, PCAdj);
2414    CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2415    CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2416    SDValue Result =
2417      DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2418                  MachinePointerInfo::getConstantPool(),
2419                  false, false, false, 0);
2420
2421    if (RelocM == Reloc::PIC_) {
2422      SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2423      Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2424    }
2425    return Result;
2426  }
2427  case Intrinsic::arm_neon_vmulls:
2428  case Intrinsic::arm_neon_vmullu: {
2429    unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2430      ? ARMISD::VMULLs : ARMISD::VMULLu;
2431    return DAG.getNode(NewOpc, Op.getDebugLoc(), Op.getValueType(),
2432                       Op.getOperand(1), Op.getOperand(2));
2433  }
2434  }
2435}
2436
2437static SDValue LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG,
2438                               const ARMSubtarget *Subtarget) {
2439  DebugLoc dl = Op.getDebugLoc();
2440  if (!Subtarget->hasDataBarrier()) {
2441    // Some ARMv6 cpus can support data barriers with an mcr instruction.
2442    // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2443    // here.
2444    assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2445           "Unexpected ISD::MEMBARRIER encountered. Should be libcall!");
2446    return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2447                       DAG.getConstant(0, MVT::i32));
2448  }
2449
2450  SDValue Op5 = Op.getOperand(5);
2451  bool isDeviceBarrier = cast<ConstantSDNode>(Op5)->getZExtValue() != 0;
2452  unsigned isLL = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
2453  unsigned isLS = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
2454  bool isOnlyStoreBarrier = (isLL == 0 && isLS == 0);
2455
2456  ARM_MB::MemBOpt DMBOpt;
2457  if (isDeviceBarrier)
2458    DMBOpt = isOnlyStoreBarrier ? ARM_MB::ST : ARM_MB::SY;
2459  else
2460    DMBOpt = isOnlyStoreBarrier ? ARM_MB::ISHST : ARM_MB::ISH;
2461  return DAG.getNode(ARMISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0),
2462                     DAG.getConstant(DMBOpt, MVT::i32));
2463}
2464
2465
2466static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2467                                 const ARMSubtarget *Subtarget) {
2468  // FIXME: handle "fence singlethread" more efficiently.
2469  DebugLoc dl = Op.getDebugLoc();
2470  if (!Subtarget->hasDataBarrier()) {
2471    // Some ARMv6 cpus can support data barriers with an mcr instruction.
2472    // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2473    // here.
2474    assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2475           "Unexpected ISD::MEMBARRIER encountered. Should be libcall!");
2476    return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2477                       DAG.getConstant(0, MVT::i32));
2478  }
2479
2480  return DAG.getNode(ARMISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0),
2481                     DAG.getConstant(ARM_MB::ISH, MVT::i32));
2482}
2483
2484static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2485                             const ARMSubtarget *Subtarget) {
2486  // ARM pre v5TE and Thumb1 does not have preload instructions.
2487  if (!(Subtarget->isThumb2() ||
2488        (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2489    // Just preserve the chain.
2490    return Op.getOperand(0);
2491
2492  DebugLoc dl = Op.getDebugLoc();
2493  unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2494  if (!isRead &&
2495      (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2496    // ARMv7 with MP extension has PLDW.
2497    return Op.getOperand(0);
2498
2499  unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2500  if (Subtarget->isThumb()) {
2501    // Invert the bits.
2502    isRead = ~isRead & 1;
2503    isData = ~isData & 1;
2504  }
2505
2506  return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2507                     Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2508                     DAG.getConstant(isData, MVT::i32));
2509}
2510
2511static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2512  MachineFunction &MF = DAG.getMachineFunction();
2513  ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2514
2515  // vastart just stores the address of the VarArgsFrameIndex slot into the
2516  // memory location argument.
2517  DebugLoc dl = Op.getDebugLoc();
2518  EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2519  SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2520  const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2521  return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2522                      MachinePointerInfo(SV), false, false, 0);
2523}
2524
2525SDValue
2526ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2527                                        SDValue &Root, SelectionDAG &DAG,
2528                                        DebugLoc dl) const {
2529  MachineFunction &MF = DAG.getMachineFunction();
2530  ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2531
2532  const TargetRegisterClass *RC;
2533  if (AFI->isThumb1OnlyFunction())
2534    RC = &ARM::tGPRRegClass;
2535  else
2536    RC = &ARM::GPRRegClass;
2537
2538  // Transform the arguments stored in physical registers into virtual ones.
2539  unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2540  SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2541
2542  SDValue ArgValue2;
2543  if (NextVA.isMemLoc()) {
2544    MachineFrameInfo *MFI = MF.getFrameInfo();
2545    int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2546
2547    // Create load node to retrieve arguments from the stack.
2548    SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2549    ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2550                            MachinePointerInfo::getFixedStack(FI),
2551                            false, false, false, 0);
2552  } else {
2553    Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2554    ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2555  }
2556
2557  return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2558}
2559
2560void
2561ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2562                                  unsigned &VARegSize, unsigned &VARegSaveSize)
2563  const {
2564  unsigned NumGPRs;
2565  if (CCInfo.isFirstByValRegValid())
2566    NumGPRs = ARM::R4 - CCInfo.getFirstByValReg();
2567  else {
2568    unsigned int firstUnalloced;
2569    firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs,
2570                                                sizeof(GPRArgRegs) /
2571                                                sizeof(GPRArgRegs[0]));
2572    NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2573  }
2574
2575  unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment();
2576  VARegSize = NumGPRs * 4;
2577  VARegSaveSize = (VARegSize + Align - 1) & ~(Align - 1);
2578}
2579
2580// The remaining GPRs hold either the beginning of variable-argument
2581// data, or the beginning of an aggregate passed by value (usuall
2582// byval).  Either way, we allocate stack slots adjacent to the data
2583// provided by our caller, and store the unallocated registers there.
2584// If this is a variadic function, the va_list pointer will begin with
2585// these values; otherwise, this reassembles a (byval) structure that
2586// was split between registers and memory.
2587void
2588ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2589                                        DebugLoc dl, SDValue &Chain,
2590                                        const Value *OrigArg,
2591                                        unsigned OffsetFromOrigArg,
2592                                        unsigned ArgOffset,
2593                                        bool ForceMutable) const {
2594  MachineFunction &MF = DAG.getMachineFunction();
2595  MachineFrameInfo *MFI = MF.getFrameInfo();
2596  ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2597  unsigned firstRegToSaveIndex;
2598  if (CCInfo.isFirstByValRegValid())
2599    firstRegToSaveIndex = CCInfo.getFirstByValReg() - ARM::R0;
2600  else {
2601    firstRegToSaveIndex = CCInfo.getFirstUnallocated
2602      (GPRArgRegs, sizeof(GPRArgRegs) / sizeof(GPRArgRegs[0]));
2603  }
2604
2605  unsigned VARegSize, VARegSaveSize;
2606  computeRegArea(CCInfo, MF, VARegSize, VARegSaveSize);
2607  if (VARegSaveSize) {
2608    // If this function is vararg, store any remaining integer argument regs
2609    // to their spots on the stack so that they may be loaded by deferencing
2610    // the result of va_next.
2611    AFI->setVarArgsRegSaveSize(VARegSaveSize);
2612    AFI->setVarArgsFrameIndex(MFI->CreateFixedObject(VARegSaveSize,
2613                                                     ArgOffset + VARegSaveSize
2614                                                     - VARegSize,
2615                                                     false));
2616    SDValue FIN = DAG.getFrameIndex(AFI->getVarArgsFrameIndex(),
2617                                    getPointerTy());
2618
2619    SmallVector<SDValue, 4> MemOps;
2620    for (unsigned i = 0; firstRegToSaveIndex < 4; ++firstRegToSaveIndex, ++i) {
2621      const TargetRegisterClass *RC;
2622      if (AFI->isThumb1OnlyFunction())
2623        RC = &ARM::tGPRRegClass;
2624      else
2625        RC = &ARM::GPRRegClass;
2626
2627      unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2628      SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2629      SDValue Store =
2630        DAG.getStore(Val.getValue(1), dl, Val, FIN,
2631                     MachinePointerInfo(OrigArg, OffsetFromOrigArg + 4*i),
2632                     false, false, 0);
2633      MemOps.push_back(Store);
2634      FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2635                        DAG.getConstant(4, getPointerTy()));
2636    }
2637    if (!MemOps.empty())
2638      Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2639                          &MemOps[0], MemOps.size());
2640  } else
2641    // This will point to the next argument passed via stack.
2642    AFI->setVarArgsFrameIndex(
2643        MFI->CreateFixedObject(4, ArgOffset, !ForceMutable));
2644}
2645
2646SDValue
2647ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2648                                        CallingConv::ID CallConv, bool isVarArg,
2649                                        const SmallVectorImpl<ISD::InputArg>
2650                                          &Ins,
2651                                        DebugLoc dl, SelectionDAG &DAG,
2652                                        SmallVectorImpl<SDValue> &InVals)
2653                                          const {
2654  MachineFunction &MF = DAG.getMachineFunction();
2655  MachineFrameInfo *MFI = MF.getFrameInfo();
2656
2657  ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2658
2659  // Assign locations to all of the incoming arguments.
2660  SmallVector<CCValAssign, 16> ArgLocs;
2661  ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2662                    getTargetMachine(), ArgLocs, *DAG.getContext(), Prologue);
2663  CCInfo.AnalyzeFormalArguments(Ins,
2664                                CCAssignFnForNode(CallConv, /* Return*/ false,
2665                                                  isVarArg));
2666
2667  SmallVector<SDValue, 16> ArgValues;
2668  int lastInsIndex = -1;
2669  SDValue ArgValue;
2670  Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2671  unsigned CurArgIdx = 0;
2672  for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2673    CCValAssign &VA = ArgLocs[i];
2674    std::advance(CurOrigArg, Ins[VA.getValNo()].OrigArgIndex - CurArgIdx);
2675    CurArgIdx = Ins[VA.getValNo()].OrigArgIndex;
2676    // Arguments stored in registers.
2677    if (VA.isRegLoc()) {
2678      EVT RegVT = VA.getLocVT();
2679
2680      if (VA.needsCustom()) {
2681        // f64 and vector types are split up into multiple registers or
2682        // combinations of registers and stack slots.
2683        if (VA.getLocVT() == MVT::v2f64) {
2684          SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
2685                                                   Chain, DAG, dl);
2686          VA = ArgLocs[++i]; // skip ahead to next loc
2687          SDValue ArgValue2;
2688          if (VA.isMemLoc()) {
2689            int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
2690            SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2691            ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
2692                                    MachinePointerInfo::getFixedStack(FI),
2693                                    false, false, false, 0);
2694          } else {
2695            ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
2696                                             Chain, DAG, dl);
2697          }
2698          ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
2699          ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2700                                 ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
2701          ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2702                                 ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
2703        } else
2704          ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
2705
2706      } else {
2707        const TargetRegisterClass *RC;
2708
2709        if (RegVT == MVT::f32)
2710          RC = &ARM::SPRRegClass;
2711        else if (RegVT == MVT::f64)
2712          RC = &ARM::DPRRegClass;
2713        else if (RegVT == MVT::v2f64)
2714          RC = &ARM::QPRRegClass;
2715        else if (RegVT == MVT::i32)
2716          RC = AFI->isThumb1OnlyFunction() ?
2717            (const TargetRegisterClass*)&ARM::tGPRRegClass :
2718            (const TargetRegisterClass*)&ARM::GPRRegClass;
2719        else
2720          llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2721
2722        // Transform the arguments in physical registers into virtual ones.
2723        unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2724        ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2725      }
2726
2727      // If this is an 8 or 16-bit value, it is really passed promoted
2728      // to 32 bits.  Insert an assert[sz]ext to capture this, then
2729      // truncate to the right size.
2730      switch (VA.getLocInfo()) {
2731      default: llvm_unreachable("Unknown loc info!");
2732      case CCValAssign::Full: break;
2733      case CCValAssign::BCvt:
2734        ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2735        break;
2736      case CCValAssign::SExt:
2737        ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2738                               DAG.getValueType(VA.getValVT()));
2739        ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2740        break;
2741      case CCValAssign::ZExt:
2742        ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2743                               DAG.getValueType(VA.getValVT()));
2744        ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2745        break;
2746      }
2747
2748      InVals.push_back(ArgValue);
2749
2750    } else { // VA.isRegLoc()
2751
2752      // sanity check
2753      assert(VA.isMemLoc());
2754      assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
2755
2756      int index = ArgLocs[i].getValNo();
2757
2758      // Some Ins[] entries become multiple ArgLoc[] entries.
2759      // Process them only once.
2760      if (index != lastInsIndex)
2761        {
2762          ISD::ArgFlagsTy Flags = Ins[index].Flags;
2763          // FIXME: For now, all byval parameter objects are marked mutable.
2764          // This can be changed with more analysis.
2765          // In case of tail call optimization mark all arguments mutable.
2766          // Since they could be overwritten by lowering of arguments in case of
2767          // a tail call.
2768          if (Flags.isByVal()) {
2769            ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2770            if (!AFI->getVarArgsFrameIndex()) {
2771              VarArgStyleRegisters(CCInfo, DAG,
2772                                   dl, Chain, CurOrigArg,
2773                                   Ins[VA.getValNo()].PartOffset,
2774                                   VA.getLocMemOffset(),
2775                                   true /*force mutable frames*/);
2776              int VAFrameIndex = AFI->getVarArgsFrameIndex();
2777              InVals.push_back(DAG.getFrameIndex(VAFrameIndex, getPointerTy()));
2778            } else {
2779              int FI = MFI->CreateFixedObject(Flags.getByValSize(),
2780                                              VA.getLocMemOffset(), false);
2781              InVals.push_back(DAG.getFrameIndex(FI, getPointerTy()));
2782            }
2783          } else {
2784            int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
2785                                            VA.getLocMemOffset(), true);
2786
2787            // Create load nodes to retrieve arguments from the stack.
2788            SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2789            InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
2790                                         MachinePointerInfo::getFixedStack(FI),
2791                                         false, false, false, 0));
2792          }
2793          lastInsIndex = index;
2794        }
2795    }
2796  }
2797
2798  // varargs
2799  if (isVarArg)
2800    VarArgStyleRegisters(CCInfo, DAG, dl, Chain, 0, 0,
2801                         CCInfo.getNextStackOffset());
2802
2803  return Chain;
2804}
2805
2806/// isFloatingPointZero - Return true if this is +0.0.
2807static bool isFloatingPointZero(SDValue Op) {
2808  if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
2809    return CFP->getValueAPF().isPosZero();
2810  else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
2811    // Maybe this has already been legalized into the constant pool?
2812    if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
2813      SDValue WrapperOp = Op.getOperand(1).getOperand(0);
2814      if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
2815        if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
2816          return CFP->getValueAPF().isPosZero();
2817    }
2818  }
2819  return false;
2820}
2821
2822/// Returns appropriate ARM CMP (cmp) and corresponding condition code for
2823/// the given operands.
2824SDValue
2825ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
2826                             SDValue &ARMcc, SelectionDAG &DAG,
2827                             DebugLoc dl) const {
2828  if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
2829    unsigned C = RHSC->getZExtValue();
2830    if (!isLegalICmpImmediate(C)) {
2831      // Constant does not fit, try adjusting it by one?
2832      switch (CC) {
2833      default: break;
2834      case ISD::SETLT:
2835      case ISD::SETGE:
2836        if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
2837          CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
2838          RHS = DAG.getConstant(C-1, MVT::i32);
2839        }
2840        break;
2841      case ISD::SETULT:
2842      case ISD::SETUGE:
2843        if (C != 0 && isLegalICmpImmediate(C-1)) {
2844          CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
2845          RHS = DAG.getConstant(C-1, MVT::i32);
2846        }
2847        break;
2848      case ISD::SETLE:
2849      case ISD::SETGT:
2850        if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
2851          CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
2852          RHS = DAG.getConstant(C+1, MVT::i32);
2853        }
2854        break;
2855      case ISD::SETULE:
2856      case ISD::SETUGT:
2857        if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
2858          CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
2859          RHS = DAG.getConstant(C+1, MVT::i32);
2860        }
2861        break;
2862      }
2863    }
2864  }
2865
2866  ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
2867  ARMISD::NodeType CompareType;
2868  switch (CondCode) {
2869  default:
2870    CompareType = ARMISD::CMP;
2871    break;
2872  case ARMCC::EQ:
2873  case ARMCC::NE:
2874    // Uses only Z Flag
2875    CompareType = ARMISD::CMPZ;
2876    break;
2877  }
2878  ARMcc = DAG.getConstant(CondCode, MVT::i32);
2879  return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
2880}
2881
2882/// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
2883SDValue
2884ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
2885                             DebugLoc dl) const {
2886  SDValue Cmp;
2887  if (!isFloatingPointZero(RHS))
2888    Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
2889  else
2890    Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
2891  return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
2892}
2893
2894/// duplicateCmp - Glue values can have only one use, so this function
2895/// duplicates a comparison node.
2896SDValue
2897ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
2898  unsigned Opc = Cmp.getOpcode();
2899  DebugLoc DL = Cmp.getDebugLoc();
2900  if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
2901    return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
2902
2903  assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
2904  Cmp = Cmp.getOperand(0);
2905  Opc = Cmp.getOpcode();
2906  if (Opc == ARMISD::CMPFP)
2907    Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
2908  else {
2909    assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
2910    Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
2911  }
2912  return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
2913}
2914
2915SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
2916  SDValue Cond = Op.getOperand(0);
2917  SDValue SelectTrue = Op.getOperand(1);
2918  SDValue SelectFalse = Op.getOperand(2);
2919  DebugLoc dl = Op.getDebugLoc();
2920
2921  // Convert:
2922  //
2923  //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
2924  //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
2925  //
2926  if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
2927    const ConstantSDNode *CMOVTrue =
2928      dyn_cast<ConstantSDNode>(Cond.getOperand(0));
2929    const ConstantSDNode *CMOVFalse =
2930      dyn_cast<ConstantSDNode>(Cond.getOperand(1));
2931
2932    if (CMOVTrue && CMOVFalse) {
2933      unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
2934      unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
2935
2936      SDValue True;
2937      SDValue False;
2938      if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
2939        True = SelectTrue;
2940        False = SelectFalse;
2941      } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
2942        True = SelectFalse;
2943        False = SelectTrue;
2944      }
2945
2946      if (True.getNode() && False.getNode()) {
2947        EVT VT = Op.getValueType();
2948        SDValue ARMcc = Cond.getOperand(2);
2949        SDValue CCR = Cond.getOperand(3);
2950        SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
2951        assert(True.getValueType() == VT);
2952        return DAG.getNode(ARMISD::CMOV, dl, VT, True, False, ARMcc, CCR, Cmp);
2953      }
2954    }
2955  }
2956
2957  // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
2958  // undefined bits before doing a full-word comparison with zero.
2959  Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
2960                     DAG.getConstant(1, Cond.getValueType()));
2961
2962  return DAG.getSelectCC(dl, Cond,
2963                         DAG.getConstant(0, Cond.getValueType()),
2964                         SelectTrue, SelectFalse, ISD::SETNE);
2965}
2966
2967SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
2968  EVT VT = Op.getValueType();
2969  SDValue LHS = Op.getOperand(0);
2970  SDValue RHS = Op.getOperand(1);
2971  ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
2972  SDValue TrueVal = Op.getOperand(2);
2973  SDValue FalseVal = Op.getOperand(3);
2974  DebugLoc dl = Op.getDebugLoc();
2975
2976  if (LHS.getValueType() == MVT::i32) {
2977    SDValue ARMcc;
2978    SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
2979    SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
2980    return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,Cmp);
2981  }
2982
2983  ARMCC::CondCodes CondCode, CondCode2;
2984  FPCCToARMCC(CC, CondCode, CondCode2);
2985
2986  SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
2987  SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
2988  SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
2989  SDValue Result = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
2990                               ARMcc, CCR, Cmp);
2991  if (CondCode2 != ARMCC::AL) {
2992    SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
2993    // FIXME: Needs another CMP because flag can have but one use.
2994    SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
2995    Result = DAG.getNode(ARMISD::CMOV, dl, VT,
2996                         Result, TrueVal, ARMcc2, CCR, Cmp2);
2997  }
2998  return Result;
2999}
3000
3001/// canChangeToInt - Given the fp compare operand, return true if it is suitable
3002/// to morph to an integer compare sequence.
3003static bool canChangeToInt(SDValue Op, bool &SeenZero,
3004                           const ARMSubtarget *Subtarget) {
3005  SDNode *N = Op.getNode();
3006  if (!N->hasOneUse())
3007    // Otherwise it requires moving the value from fp to integer registers.
3008    return false;
3009  if (!N->getNumValues())
3010    return false;
3011  EVT VT = Op.getValueType();
3012  if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3013    // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3014    // vmrs are very slow, e.g. cortex-a8.
3015    return false;
3016
3017  if (isFloatingPointZero(Op)) {
3018    SeenZero = true;
3019    return true;
3020  }
3021  return ISD::isNormalLoad(N);
3022}
3023
3024static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3025  if (isFloatingPointZero(Op))
3026    return DAG.getConstant(0, MVT::i32);
3027
3028  if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3029    return DAG.getLoad(MVT::i32, Op.getDebugLoc(),
3030                       Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3031                       Ld->isVolatile(), Ld->isNonTemporal(),
3032                       Ld->isInvariant(), Ld->getAlignment());
3033
3034  llvm_unreachable("Unknown VFP cmp argument!");
3035}
3036
3037static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3038                           SDValue &RetVal1, SDValue &RetVal2) {
3039  if (isFloatingPointZero(Op)) {
3040    RetVal1 = DAG.getConstant(0, MVT::i32);
3041    RetVal2 = DAG.getConstant(0, MVT::i32);
3042    return;
3043  }
3044
3045  if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3046    SDValue Ptr = Ld->getBasePtr();
3047    RetVal1 = DAG.getLoad(MVT::i32, Op.getDebugLoc(),
3048                          Ld->getChain(), Ptr,
3049                          Ld->getPointerInfo(),
3050                          Ld->isVolatile(), Ld->isNonTemporal(),
3051                          Ld->isInvariant(), Ld->getAlignment());
3052
3053    EVT PtrType = Ptr.getValueType();
3054    unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3055    SDValue NewPtr = DAG.getNode(ISD::ADD, Op.getDebugLoc(),
3056                                 PtrType, Ptr, DAG.getConstant(4, PtrType));
3057    RetVal2 = DAG.getLoad(MVT::i32, Op.getDebugLoc(),
3058                          Ld->getChain(), NewPtr,
3059                          Ld->getPointerInfo().getWithOffset(4),
3060                          Ld->isVolatile(), Ld->isNonTemporal(),
3061                          Ld->isInvariant(), NewAlign);
3062    return;
3063  }
3064
3065  llvm_unreachable("Unknown VFP cmp argument!");
3066}
3067
3068/// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3069/// f32 and even f64 comparisons to integer ones.
3070SDValue
3071ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3072  SDValue Chain = Op.getOperand(0);
3073  ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3074  SDValue LHS = Op.getOperand(2);
3075  SDValue RHS = Op.getOperand(3);
3076  SDValue Dest = Op.getOperand(4);
3077  DebugLoc dl = Op.getDebugLoc();
3078
3079  bool LHSSeenZero = false;
3080  bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3081  bool RHSSeenZero = false;
3082  bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3083  if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3084    // If unsafe fp math optimization is enabled and there are no other uses of
3085    // the CMP operands, and the condition code is EQ or NE, we can optimize it
3086    // to an integer comparison.
3087    if (CC == ISD::SETOEQ)
3088      CC = ISD::SETEQ;
3089    else if (CC == ISD::SETUNE)
3090      CC = ISD::SETNE;
3091
3092    SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3093    SDValue ARMcc;
3094    if (LHS.getValueType() == MVT::f32) {
3095      LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3096                        bitcastf32Toi32(LHS, DAG), Mask);
3097      RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3098                        bitcastf32Toi32(RHS, DAG), Mask);
3099      SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3100      SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3101      return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3102                         Chain, Dest, ARMcc, CCR, Cmp);
3103    }
3104
3105    SDValue LHS1, LHS2;
3106    SDValue RHS1, RHS2;
3107    expandf64Toi32(LHS, DAG, LHS1, LHS2);
3108    expandf64Toi32(RHS, DAG, RHS1, RHS2);
3109    LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3110    RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3111    ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3112    ARMcc = DAG.getConstant(CondCode, MVT::i32);
3113    SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3114    SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3115    return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops, 7);
3116  }
3117
3118  return SDValue();
3119}
3120
3121SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3122  SDValue Chain = Op.getOperand(0);
3123  ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3124  SDValue LHS = Op.getOperand(2);
3125  SDValue RHS = Op.getOperand(3);
3126  SDValue Dest = Op.getOperand(4);
3127  DebugLoc dl = Op.getDebugLoc();
3128
3129  if (LHS.getValueType() == MVT::i32) {
3130    SDValue ARMcc;
3131    SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3132    SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3133    return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3134                       Chain, Dest, ARMcc, CCR, Cmp);
3135  }
3136
3137  assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3138
3139  if (getTargetMachine().Options.UnsafeFPMath &&
3140      (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3141       CC == ISD::SETNE || CC == ISD::SETUNE)) {
3142    SDValue Result = OptimizeVFPBrcond(Op, DAG);
3143    if (Result.getNode())
3144      return Result;
3145  }
3146
3147  ARMCC::CondCodes CondCode, CondCode2;
3148  FPCCToARMCC(CC, CondCode, CondCode2);
3149
3150  SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3151  SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3152  SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3153  SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3154  SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3155  SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3156  if (CondCode2 != ARMCC::AL) {
3157    ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3158    SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3159    Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3160  }
3161  return Res;
3162}
3163
3164SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3165  SDValue Chain = Op.getOperand(0);
3166  SDValue Table = Op.getOperand(1);
3167  SDValue Index = Op.getOperand(2);
3168  DebugLoc dl = Op.getDebugLoc();
3169
3170  EVT PTy = getPointerTy();
3171  JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3172  ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3173  SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3174  SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3175  Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3176  Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3177  SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3178  if (Subtarget->isThumb2()) {
3179    // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3180    // which does another jump to the destination. This also makes it easier
3181    // to translate it to TBB / TBH later.
3182    // FIXME: This might not work if the function is extremely large.
3183    return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3184                       Addr, Op.getOperand(2), JTI, UId);
3185  }
3186  if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3187    Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3188                       MachinePointerInfo::getJumpTable(),
3189                       false, false, false, 0);
3190    Chain = Addr.getValue(1);
3191    Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3192    return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3193  } else {
3194    Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3195                       MachinePointerInfo::getJumpTable(),
3196                       false, false, false, 0);
3197    Chain = Addr.getValue(1);
3198    return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3199  }
3200}
3201
3202static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3203  EVT VT = Op.getValueType();
3204  DebugLoc dl = Op.getDebugLoc();
3205
3206  if (Op.getValueType().getVectorElementType() == MVT::i32) {
3207    if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3208      return Op;
3209    return DAG.UnrollVectorOp(Op.getNode());
3210  }
3211
3212  assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3213         "Invalid type for custom lowering!");
3214  if (VT != MVT::v4i16)
3215    return DAG.UnrollVectorOp(Op.getNode());
3216
3217  Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3218  return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3219}
3220
3221static SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3222  EVT VT = Op.getValueType();
3223  if (VT.isVector())
3224    return LowerVectorFP_TO_INT(Op, DAG);
3225
3226  DebugLoc dl = Op.getDebugLoc();
3227  unsigned Opc;
3228
3229  switch (Op.getOpcode()) {
3230  default: llvm_unreachable("Invalid opcode!");
3231  case ISD::FP_TO_SINT:
3232    Opc = ARMISD::FTOSI;
3233    break;
3234  case ISD::FP_TO_UINT:
3235    Opc = ARMISD::FTOUI;
3236    break;
3237  }
3238  Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3239  return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3240}
3241
3242static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3243  EVT VT = Op.getValueType();
3244  DebugLoc dl = Op.getDebugLoc();
3245
3246  if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3247    if (VT.getVectorElementType() == MVT::f32)
3248      return Op;
3249    return DAG.UnrollVectorOp(Op.getNode());
3250  }
3251
3252  assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3253         "Invalid type for custom lowering!");
3254  if (VT != MVT::v4f32)
3255    return DAG.UnrollVectorOp(Op.getNode());
3256
3257  unsigned CastOpc;
3258  unsigned Opc;
3259  switch (Op.getOpcode()) {
3260  default: llvm_unreachable("Invalid opcode!");
3261  case ISD::SINT_TO_FP:
3262    CastOpc = ISD::SIGN_EXTEND;
3263    Opc = ISD::SINT_TO_FP;
3264    break;
3265  case ISD::UINT_TO_FP:
3266    CastOpc = ISD::ZERO_EXTEND;
3267    Opc = ISD::UINT_TO_FP;
3268    break;
3269  }
3270
3271  Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3272  return DAG.getNode(Opc, dl, VT, Op);
3273}
3274
3275static SDValue LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3276  EVT VT = Op.getValueType();
3277  if (VT.isVector())
3278    return LowerVectorINT_TO_FP(Op, DAG);
3279
3280  DebugLoc dl = Op.getDebugLoc();
3281  unsigned Opc;
3282
3283  switch (Op.getOpcode()) {
3284  default: llvm_unreachable("Invalid opcode!");
3285  case ISD::SINT_TO_FP:
3286    Opc = ARMISD::SITOF;
3287    break;
3288  case ISD::UINT_TO_FP:
3289    Opc = ARMISD::UITOF;
3290    break;
3291  }
3292
3293  Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3294  return DAG.getNode(Opc, dl, VT, Op);
3295}
3296
3297SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3298  // Implement fcopysign with a fabs and a conditional fneg.
3299  SDValue Tmp0 = Op.getOperand(0);
3300  SDValue Tmp1 = Op.getOperand(1);
3301  DebugLoc dl = Op.getDebugLoc();
3302  EVT VT = Op.getValueType();
3303  EVT SrcVT = Tmp1.getValueType();
3304  bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3305    Tmp0.getOpcode() == ARMISD::VMOVDRR;
3306  bool UseNEON = !InGPR && Subtarget->hasNEON();
3307
3308  if (UseNEON) {
3309    // Use VBSL to copy the sign bit.
3310    unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3311    SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3312                               DAG.getTargetConstant(EncodedVal, MVT::i32));
3313    EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3314    if (VT == MVT::f64)
3315      Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3316                         DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3317                         DAG.getConstant(32, MVT::i32));
3318    else /*if (VT == MVT::f32)*/
3319      Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3320    if (SrcVT == MVT::f32) {
3321      Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3322      if (VT == MVT::f64)
3323        Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3324                           DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3325                           DAG.getConstant(32, MVT::i32));
3326    } else if (VT == MVT::f32)
3327      Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3328                         DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
3329                         DAG.getConstant(32, MVT::i32));
3330    Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
3331    Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
3332
3333    SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
3334                                            MVT::i32);
3335    AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
3336    SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
3337                                  DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
3338
3339    SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
3340                              DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
3341                              DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
3342    if (VT == MVT::f32) {
3343      Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
3344      Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
3345                        DAG.getConstant(0, MVT::i32));
3346    } else {
3347      Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
3348    }
3349
3350    return Res;
3351  }
3352
3353  // Bitcast operand 1 to i32.
3354  if (SrcVT == MVT::f64)
3355    Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3356                       &Tmp1, 1).getValue(1);
3357  Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
3358
3359  // Or in the signbit with integer operations.
3360  SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
3361  SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
3362  Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
3363  if (VT == MVT::f32) {
3364    Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
3365                       DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
3366    return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3367                       DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
3368  }
3369
3370  // f64: Or the high part with signbit and then combine two parts.
3371  Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3372                     &Tmp0, 1);
3373  SDValue Lo = Tmp0.getValue(0);
3374  SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
3375  Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
3376  return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
3377}
3378
3379SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
3380  MachineFunction &MF = DAG.getMachineFunction();
3381  MachineFrameInfo *MFI = MF.getFrameInfo();
3382  MFI->setReturnAddressIsTaken(true);
3383
3384  EVT VT = Op.getValueType();
3385  DebugLoc dl = Op.getDebugLoc();
3386  unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3387  if (Depth) {
3388    SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3389    SDValue Offset = DAG.getConstant(4, MVT::i32);
3390    return DAG.getLoad(VT, dl, DAG.getEntryNode(),
3391                       DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
3392                       MachinePointerInfo(), false, false, false, 0);
3393  }
3394
3395  // Return LR, which contains the return address. Mark it an implicit live-in.
3396  unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3397  return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
3398}
3399
3400SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
3401  MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3402  MFI->setFrameAddressIsTaken(true);
3403
3404  EVT VT = Op.getValueType();
3405  DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
3406  unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3407  unsigned FrameReg = (Subtarget->isThumb() || Subtarget->isTargetDarwin())
3408    ? ARM::R7 : ARM::R11;
3409  SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
3410  while (Depth--)
3411    FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
3412                            MachinePointerInfo(),
3413                            false, false, false, 0);
3414  return FrameAddr;
3415}
3416
3417/// ExpandBITCAST - If the target supports VFP, this function is called to
3418/// expand a bit convert where either the source or destination type is i64 to
3419/// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
3420/// operand type is illegal (e.g., v2f32 for a target that doesn't support
3421/// vectors), since the legalizer won't know what to do with that.
3422static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
3423  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3424  DebugLoc dl = N->getDebugLoc();
3425  SDValue Op = N->getOperand(0);
3426
3427  // This function is only supposed to be called for i64 types, either as the
3428  // source or destination of the bit convert.
3429  EVT SrcVT = Op.getValueType();
3430  EVT DstVT = N->getValueType(0);
3431  assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
3432         "ExpandBITCAST called for non-i64 type");
3433
3434  // Turn i64->f64 into VMOVDRR.
3435  if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
3436    SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3437                             DAG.getConstant(0, MVT::i32));
3438    SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3439                             DAG.getConstant(1, MVT::i32));
3440    return DAG.getNode(ISD::BITCAST, dl, DstVT,
3441                       DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
3442  }
3443
3444  // Turn f64->i64 into VMOVRRD.
3445  if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
3446    SDValue Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
3447                              DAG.getVTList(MVT::i32, MVT::i32), &Op, 1);
3448    // Merge the pieces into a single i64 value.
3449    return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
3450  }
3451
3452  return SDValue();
3453}
3454
3455/// getZeroVector - Returns a vector of specified type with all zero elements.
3456/// Zero vectors are used to represent vector negation and in those cases
3457/// will be implemented with the NEON VNEG instruction.  However, VNEG does
3458/// not support i64 elements, so sometimes the zero vectors will need to be
3459/// explicitly constructed.  Regardless, use a canonical VMOV to create the
3460/// zero vector.
3461static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3462  assert(VT.isVector() && "Expected a vector type");
3463  // The canonical modified immediate encoding of a zero vector is....0!
3464  SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
3465  EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
3466  SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
3467  return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
3468}
3469
3470/// LowerShiftRightParts - Lower SRA_PARTS, which returns two
3471/// i32 values and take a 2 x i32 value to shift plus a shift amount.
3472SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
3473                                                SelectionDAG &DAG) const {
3474  assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3475  EVT VT = Op.getValueType();
3476  unsigned VTBits = VT.getSizeInBits();
3477  DebugLoc dl = Op.getDebugLoc();
3478  SDValue ShOpLo = Op.getOperand(0);
3479  SDValue ShOpHi = Op.getOperand(1);
3480  SDValue ShAmt  = Op.getOperand(2);
3481  SDValue ARMcc;
3482  unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
3483
3484  assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
3485
3486  SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3487                                 DAG.getConstant(VTBits, MVT::i32), ShAmt);
3488  SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
3489  SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3490                                   DAG.getConstant(VTBits, MVT::i32));
3491  SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
3492  SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3493  SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
3494
3495  SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3496  SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3497                          ARMcc, DAG, dl);
3498  SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
3499  SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
3500                           CCR, Cmp);
3501
3502  SDValue Ops[2] = { Lo, Hi };
3503  return DAG.getMergeValues(Ops, 2, dl);
3504}
3505
3506/// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
3507/// i32 values and take a 2 x i32 value to shift plus a shift amount.
3508SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
3509                                               SelectionDAG &DAG) const {
3510  assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3511  EVT VT = Op.getValueType();
3512  unsigned VTBits = VT.getSizeInBits();
3513  DebugLoc dl = Op.getDebugLoc();
3514  SDValue ShOpLo = Op.getOperand(0);
3515  SDValue ShOpHi = Op.getOperand(1);
3516  SDValue ShAmt  = Op.getOperand(2);
3517  SDValue ARMcc;
3518
3519  assert(Op.getOpcode() == ISD::SHL_PARTS);
3520  SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3521                                 DAG.getConstant(VTBits, MVT::i32), ShAmt);
3522  SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
3523  SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3524                                   DAG.getConstant(VTBits, MVT::i32));
3525  SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
3526  SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
3527
3528  SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3529  SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3530  SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3531                          ARMcc, DAG, dl);
3532  SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
3533  SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
3534                           CCR, Cmp);
3535
3536  SDValue Ops[2] = { Lo, Hi };
3537  return DAG.getMergeValues(Ops, 2, dl);
3538}
3539
3540SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
3541                                            SelectionDAG &DAG) const {
3542  // The rounding mode is in bits 23:22 of the FPSCR.
3543  // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
3544  // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
3545  // so that the shift + and get folded into a bitfield extract.
3546  DebugLoc dl = Op.getDebugLoc();
3547  SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
3548                              DAG.getConstant(Intrinsic::arm_get_fpscr,
3549                                              MVT::i32));
3550  SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
3551                                  DAG.getConstant(1U << 22, MVT::i32));
3552  SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
3553                              DAG.getConstant(22, MVT::i32));
3554  return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
3555                     DAG.getConstant(3, MVT::i32));
3556}
3557
3558static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
3559                         const ARMSubtarget *ST) {
3560  EVT VT = N->getValueType(0);
3561  DebugLoc dl = N->getDebugLoc();
3562
3563  if (!ST->hasV6T2Ops())
3564    return SDValue();
3565
3566  SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
3567  return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
3568}
3569
3570/// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
3571/// for each 16-bit element from operand, repeated.  The basic idea is to
3572/// leverage vcnt to get the 8-bit counts, gather and add the results.
3573///
3574/// Trace for v4i16:
3575/// input    = [v0    v1    v2    v3   ] (vi 16-bit element)
3576/// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
3577/// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
3578/// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
3579///            [b0 b1 b2 b3 b4 b5 b6 b7]
3580///           +[b1 b0 b3 b2 b5 b4 b7 b6]
3581/// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
3582/// vuzp:    = [k0 k1 k2 k3 k0 k1 k2 k3]  each ki is 8-bits)
3583static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
3584  EVT VT = N->getValueType(0);
3585  DebugLoc DL = N->getDebugLoc();
3586
3587  EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
3588  SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
3589  SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
3590  SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
3591  SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
3592  return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
3593}
3594
3595/// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
3596/// bit-count for each 16-bit element from the operand.  We need slightly
3597/// different sequencing for v4i16 and v8i16 to stay within NEON's available
3598/// 64/128-bit registers.
3599///
3600/// Trace for v4i16:
3601/// input           = [v0    v1    v2    v3    ] (vi 16-bit element)
3602/// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
3603/// v8i16:Extended  = [k0    k1    k2    k3    k0    k1    k2    k3    ]
3604/// v4i16:Extracted = [k0    k1    k2    k3    ]
3605static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
3606  EVT VT = N->getValueType(0);
3607  DebugLoc DL = N->getDebugLoc();
3608
3609  SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
3610  if (VT.is64BitVector()) {
3611    SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
3612    return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
3613                       DAG.getIntPtrConstant(0));
3614  } else {
3615    SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
3616                                    BitCounts, DAG.getIntPtrConstant(0));
3617    return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
3618  }
3619}
3620
3621/// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
3622/// bit-count for each 32-bit element from the operand.  The idea here is
3623/// to split the vector into 16-bit elements, leverage the 16-bit count
3624/// routine, and then combine the results.
3625///
3626/// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
3627/// input    = [v0    v1    ] (vi: 32-bit elements)
3628/// Bitcast  = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
3629/// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
3630/// vrev: N0 = [k1 k0 k3 k2 ]
3631///            [k0 k1 k2 k3 ]
3632///       N1 =+[k1 k0 k3 k2 ]
3633///            [k0 k2 k1 k3 ]
3634///       N2 =+[k1 k3 k0 k2 ]
3635///            [k0    k2    k1    k3    ]
3636/// Extended =+[k1    k3    k0    k2    ]
3637///            [k0    k2    ]
3638/// Extracted=+[k1    k3    ]
3639///
3640static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
3641  EVT VT = N->getValueType(0);
3642  DebugLoc DL = N->getDebugLoc();
3643
3644  EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
3645
3646  SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
3647  SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
3648  SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
3649  SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
3650  SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
3651
3652  if (VT.is64BitVector()) {
3653    SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
3654    return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
3655                       DAG.getIntPtrConstant(0));
3656  } else {
3657    SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
3658                                    DAG.getIntPtrConstant(0));
3659    return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
3660  }
3661}
3662
3663static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
3664                          const ARMSubtarget *ST) {
3665  EVT VT = N->getValueType(0);
3666
3667  assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
3668  assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
3669          VT == MVT::v4i16 || VT == MVT::v8i16) &&
3670         "Unexpected type for custom ctpop lowering");
3671
3672  if (VT.getVectorElementType() == MVT::i32)
3673    return lowerCTPOP32BitElements(N, DAG);
3674  else
3675    return lowerCTPOP16BitElements(N, DAG);
3676}
3677
3678static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
3679                          const ARMSubtarget *ST) {
3680  EVT VT = N->getValueType(0);
3681  DebugLoc dl = N->getDebugLoc();
3682
3683  if (!VT.isVector())
3684    return SDValue();
3685
3686  // Lower vector shifts on NEON to use VSHL.
3687  assert(ST->hasNEON() && "unexpected vector shift");
3688
3689  // Left shifts translate directly to the vshiftu intrinsic.
3690  if (N->getOpcode() == ISD::SHL)
3691    return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
3692                       DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
3693                       N->getOperand(0), N->getOperand(1));
3694
3695  assert((N->getOpcode() == ISD::SRA ||
3696          N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
3697
3698  // NEON uses the same intrinsics for both left and right shifts.  For
3699  // right shifts, the shift amounts are negative, so negate the vector of
3700  // shift amounts.
3701  EVT ShiftVT = N->getOperand(1).getValueType();
3702  SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
3703                                     getZeroVector(ShiftVT, DAG, dl),
3704                                     N->getOperand(1));
3705  Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
3706                             Intrinsic::arm_neon_vshifts :
3707                             Intrinsic::arm_neon_vshiftu);
3708  return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
3709                     DAG.getConstant(vshiftInt, MVT::i32),
3710                     N->getOperand(0), NegatedCount);
3711}
3712
3713static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
3714                                const ARMSubtarget *ST) {
3715  EVT VT = N->getValueType(0);
3716  DebugLoc dl = N->getDebugLoc();
3717
3718  // We can get here for a node like i32 = ISD::SHL i32, i64
3719  if (VT != MVT::i64)
3720    return SDValue();
3721
3722  assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
3723         "Unknown shift to lower!");
3724
3725  // We only lower SRA, SRL of 1 here, all others use generic lowering.
3726  if (!isa<ConstantSDNode>(N->getOperand(1)) ||
3727      cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
3728    return SDValue();
3729
3730  // If we are in thumb mode, we don't have RRX.
3731  if (ST->isThumb1Only()) return SDValue();
3732
3733  // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
3734  SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
3735                           DAG.getConstant(0, MVT::i32));
3736  SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
3737                           DAG.getConstant(1, MVT::i32));
3738
3739  // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
3740  // captures the result into a carry flag.
3741  unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
3742  Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), &Hi, 1);
3743
3744  // The low part is an ARMISD::RRX operand, which shifts the carry in.
3745  Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
3746
3747  // Merge the pieces into a single i64 value.
3748 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
3749}
3750
3751static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
3752  SDValue TmpOp0, TmpOp1;
3753  bool Invert = false;
3754  bool Swap = false;
3755  unsigned Opc = 0;
3756
3757  SDValue Op0 = Op.getOperand(0);
3758  SDValue Op1 = Op.getOperand(1);
3759  SDValue CC = Op.getOperand(2);
3760  EVT VT = Op.getValueType();
3761  ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
3762  DebugLoc dl = Op.getDebugLoc();
3763
3764  if (Op.getOperand(1).getValueType().isFloatingPoint()) {
3765    switch (SetCCOpcode) {
3766    default: llvm_unreachable("Illegal FP comparison");
3767    case ISD::SETUNE:
3768    case ISD::SETNE:  Invert = true; // Fallthrough
3769    case ISD::SETOEQ:
3770    case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
3771    case ISD::SETOLT:
3772    case ISD::SETLT: Swap = true; // Fallthrough
3773    case ISD::SETOGT:
3774    case ISD::SETGT:  Opc = ARMISD::VCGT; break;
3775    case ISD::SETOLE:
3776    case ISD::SETLE:  Swap = true; // Fallthrough
3777    case ISD::SETOGE:
3778    case ISD::SETGE: Opc = ARMISD::VCGE; break;
3779    case ISD::SETUGE: Swap = true; // Fallthrough
3780    case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
3781    case ISD::SETUGT: Swap = true; // Fallthrough
3782    case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
3783    case ISD::SETUEQ: Invert = true; // Fallthrough
3784    case ISD::SETONE:
3785      // Expand this to (OLT | OGT).
3786      TmpOp0 = Op0;
3787      TmpOp1 = Op1;
3788      Opc = ISD::OR;
3789      Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
3790      Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
3791      break;
3792    case ISD::SETUO: Invert = true; // Fallthrough
3793    case ISD::SETO:
3794      // Expand this to (OLT | OGE).
3795      TmpOp0 = Op0;
3796      TmpOp1 = Op1;
3797      Opc = ISD::OR;
3798      Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
3799      Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
3800      break;
3801    }
3802  } else {
3803    // Integer comparisons.
3804    switch (SetCCOpcode) {
3805    default: llvm_unreachable("Illegal integer comparison");
3806    case ISD::SETNE:  Invert = true;
3807    case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
3808    case ISD::SETLT:  Swap = true;
3809    case ISD::SETGT:  Opc = ARMISD::VCGT; break;
3810    case ISD::SETLE:  Swap = true;
3811    case ISD::SETGE:  Opc = ARMISD::VCGE; break;
3812    case ISD::SETULT: Swap = true;
3813    case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
3814    case ISD::SETULE: Swap = true;
3815    case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
3816    }
3817
3818    // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
3819    if (Opc == ARMISD::VCEQ) {
3820
3821      SDValue AndOp;
3822      if (ISD::isBuildVectorAllZeros(Op1.getNode()))
3823        AndOp = Op0;
3824      else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
3825        AndOp = Op1;
3826
3827      // Ignore bitconvert.
3828      if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
3829        AndOp = AndOp.getOperand(0);
3830
3831      if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
3832        Opc = ARMISD::VTST;
3833        Op0 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(0));
3834        Op1 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(1));
3835        Invert = !Invert;
3836      }
3837    }
3838  }
3839
3840  if (Swap)
3841    std::swap(Op0, Op1);
3842
3843  // If one of the operands is a constant vector zero, attempt to fold the
3844  // comparison to a specialized compare-against-zero form.
3845  SDValue SingleOp;
3846  if (ISD::isBuildVectorAllZeros(Op1.getNode()))
3847    SingleOp = Op0;
3848  else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
3849    if (Opc == ARMISD::VCGE)
3850      Opc = ARMISD::VCLEZ;
3851    else if (Opc == ARMISD::VCGT)
3852      Opc = ARMISD::VCLTZ;
3853    SingleOp = Op1;
3854  }
3855
3856  SDValue Result;
3857  if (SingleOp.getNode()) {
3858    switch (Opc) {
3859    case ARMISD::VCEQ:
3860      Result = DAG.getNode(ARMISD::VCEQZ, dl, VT, SingleOp); break;
3861    case ARMISD::VCGE:
3862      Result = DAG.getNode(ARMISD::VCGEZ, dl, VT, SingleOp); break;
3863    case ARMISD::VCLEZ:
3864      Result = DAG.getNode(ARMISD::VCLEZ, dl, VT, SingleOp); break;
3865    case ARMISD::VCGT:
3866      Result = DAG.getNode(ARMISD::VCGTZ, dl, VT, SingleOp); break;
3867    case ARMISD::VCLTZ:
3868      Result = DAG.getNode(ARMISD::VCLTZ, dl, VT, SingleOp); break;
3869    default:
3870      Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
3871    }
3872  } else {
3873     Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
3874  }
3875
3876  if (Invert)
3877    Result = DAG.getNOT(dl, Result, VT);
3878
3879  return Result;
3880}
3881
3882/// isNEONModifiedImm - Check if the specified splat value corresponds to a
3883/// valid vector constant for a NEON instruction with a "modified immediate"
3884/// operand (e.g., VMOV).  If so, return the encoded value.
3885static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
3886                                 unsigned SplatBitSize, SelectionDAG &DAG,
3887                                 EVT &VT, bool is128Bits, NEONModImmType type) {
3888  unsigned OpCmode, Imm;
3889
3890  // SplatBitSize is set to the smallest size that splats the vector, so a
3891  // zero vector will always have SplatBitSize == 8.  However, NEON modified
3892  // immediate instructions others than VMOV do not support the 8-bit encoding
3893  // of a zero vector, and the default encoding of zero is supposed to be the
3894  // 32-bit version.
3895  if (SplatBits == 0)
3896    SplatBitSize = 32;
3897
3898  switch (SplatBitSize) {
3899  case 8:
3900    if (type != VMOVModImm)
3901      return SDValue();
3902    // Any 1-byte value is OK.  Op=0, Cmode=1110.
3903    assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
3904    OpCmode = 0xe;
3905    Imm = SplatBits;
3906    VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
3907    break;
3908
3909  case 16:
3910    // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
3911    VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
3912    if ((SplatBits & ~0xff) == 0) {
3913      // Value = 0x00nn: Op=x, Cmode=100x.
3914      OpCmode = 0x8;
3915      Imm = SplatBits;
3916      break;
3917    }
3918    if ((SplatBits & ~0xff00) == 0) {
3919      // Value = 0xnn00: Op=x, Cmode=101x.
3920      OpCmode = 0xa;
3921      Imm = SplatBits >> 8;
3922      break;
3923    }
3924    return SDValue();
3925
3926  case 32:
3927    // NEON's 32-bit VMOV supports splat values where:
3928    // * only one byte is nonzero, or
3929    // * the least significant byte is 0xff and the second byte is nonzero, or
3930    // * the least significant 2 bytes are 0xff and the third is nonzero.
3931    VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
3932    if ((SplatBits & ~0xff) == 0) {
3933      // Value = 0x000000nn: Op=x, Cmode=000x.
3934      OpCmode = 0;
3935      Imm = SplatBits;
3936      break;
3937    }
3938    if ((SplatBits & ~0xff00) == 0) {
3939      // Value = 0x0000nn00: Op=x, Cmode=001x.
3940      OpCmode = 0x2;
3941      Imm = SplatBits >> 8;
3942      break;
3943    }
3944    if ((SplatBits & ~0xff0000) == 0) {
3945      // Value = 0x00nn0000: Op=x, Cmode=010x.
3946      OpCmode = 0x4;
3947      Imm = SplatBits >> 16;
3948      break;
3949    }
3950    if ((SplatBits & ~0xff000000) == 0) {
3951      // Value = 0xnn000000: Op=x, Cmode=011x.
3952      OpCmode = 0x6;
3953      Imm = SplatBits >> 24;
3954      break;
3955    }
3956
3957    // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
3958    if (type == OtherModImm) return SDValue();
3959
3960    if ((SplatBits & ~0xffff) == 0 &&
3961        ((SplatBits | SplatUndef) & 0xff) == 0xff) {
3962      // Value = 0x0000nnff: Op=x, Cmode=1100.
3963      OpCmode = 0xc;
3964      Imm = SplatBits >> 8;
3965      SplatBits |= 0xff;
3966      break;
3967    }
3968
3969    if ((SplatBits & ~0xffffff) == 0 &&
3970        ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
3971      // Value = 0x00nnffff: Op=x, Cmode=1101.
3972      OpCmode = 0xd;
3973      Imm = SplatBits >> 16;
3974      SplatBits |= 0xffff;
3975      break;
3976    }
3977
3978    // Note: there are a few 32-bit splat values (specifically: 00ffff00,
3979    // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
3980    // VMOV.I32.  A (very) minor optimization would be to replicate the value
3981    // and fall through here to test for a valid 64-bit splat.  But, then the
3982    // caller would also need to check and handle the change in size.
3983    return SDValue();
3984
3985  case 64: {
3986    if (type != VMOVModImm)
3987      return SDValue();
3988    // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
3989    uint64_t BitMask = 0xff;
3990    uint64_t Val = 0;
3991    unsigned ImmMask = 1;
3992    Imm = 0;
3993    for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
3994      if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
3995        Val |= BitMask;
3996        Imm |= ImmMask;
3997      } else if ((SplatBits & BitMask) != 0) {
3998        return SDValue();
3999      }
4000      BitMask <<= 8;
4001      ImmMask <<= 1;
4002    }
4003    // Op=1, Cmode=1110.
4004    OpCmode = 0x1e;
4005    SplatBits = Val;
4006    VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4007    break;
4008  }
4009
4010  default:
4011    llvm_unreachable("unexpected size for isNEONModifiedImm");
4012  }
4013
4014  unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4015  return DAG.getTargetConstant(EncodedVal, MVT::i32);
4016}
4017
4018SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4019                                           const ARMSubtarget *ST) const {
4020  if (!ST->useNEONForSinglePrecisionFP() || !ST->hasVFP3() || ST->hasD16())
4021    return SDValue();
4022
4023  ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4024  assert(Op.getValueType() == MVT::f32 &&
4025         "ConstantFP custom lowering should only occur for f32.");
4026
4027  // Try splatting with a VMOV.f32...
4028  APFloat FPVal = CFP->getValueAPF();
4029  int ImmVal = ARM_AM::getFP32Imm(FPVal);
4030  if (ImmVal != -1) {
4031    DebugLoc DL = Op.getDebugLoc();
4032    SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
4033    SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4034                                      NewVal);
4035    return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4036                       DAG.getConstant(0, MVT::i32));
4037  }
4038
4039  // If that fails, try a VMOV.i32
4040  EVT VMovVT;
4041  unsigned iVal = FPVal.bitcastToAPInt().getZExtValue();
4042  SDValue NewVal = isNEONModifiedImm(iVal, 0, 32, DAG, VMovVT, false,
4043                                     VMOVModImm);
4044  if (NewVal != SDValue()) {
4045    DebugLoc DL = Op.getDebugLoc();
4046    SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4047                                      NewVal);
4048    SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4049                                       VecConstant);
4050    return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4051                       DAG.getConstant(0, MVT::i32));
4052  }
4053
4054  // Finally, try a VMVN.i32
4055  NewVal = isNEONModifiedImm(~iVal & 0xffffffff, 0, 32, DAG, VMovVT, false,
4056                             VMVNModImm);
4057  if (NewVal != SDValue()) {
4058    DebugLoc DL = Op.getDebugLoc();
4059    SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4060    SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4061                                       VecConstant);
4062    return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4063                       DAG.getConstant(0, MVT::i32));
4064  }
4065
4066  return SDValue();
4067}
4068
4069// check if an VEXT instruction can handle the shuffle mask when the
4070// vector sources of the shuffle are the same.
4071static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4072  unsigned NumElts = VT.getVectorNumElements();
4073
4074  // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4075  if (M[0] < 0)
4076    return false;
4077
4078  Imm = M[0];
4079
4080  // If this is a VEXT shuffle, the immediate value is the index of the first
4081  // element.  The other shuffle indices must be the successive elements after
4082  // the first one.
4083  unsigned ExpectedElt = Imm;
4084  for (unsigned i = 1; i < NumElts; ++i) {
4085    // Increment the expected index.  If it wraps around, just follow it
4086    // back to index zero and keep going.
4087    ++ExpectedElt;
4088    if (ExpectedElt == NumElts)
4089      ExpectedElt = 0;
4090
4091    if (M[i] < 0) continue; // ignore UNDEF indices
4092    if (ExpectedElt != static_cast<unsigned>(M[i]))
4093      return false;
4094  }
4095
4096  return true;
4097}
4098
4099
4100static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4101                       bool &ReverseVEXT, unsigned &Imm) {
4102  unsigned NumElts = VT.getVectorNumElements();
4103  ReverseVEXT = false;
4104
4105  // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4106  if (M[0] < 0)
4107    return false;
4108
4109  Imm = M[0];
4110
4111  // If this is a VEXT shuffle, the immediate value is the index of the first
4112  // element.  The other shuffle indices must be the successive elements after
4113  // the first one.
4114  unsigned ExpectedElt = Imm;
4115  for (unsigned i = 1; i < NumElts; ++i) {
4116    // Increment the expected index.  If it wraps around, it may still be
4117    // a VEXT but the source vectors must be swapped.
4118    ExpectedElt += 1;
4119    if (ExpectedElt == NumElts * 2) {
4120      ExpectedElt = 0;
4121      ReverseVEXT = true;
4122    }
4123
4124    if (M[i] < 0) continue; // ignore UNDEF indices
4125    if (ExpectedElt != static_cast<unsigned>(M[i]))
4126      return false;
4127  }
4128
4129  // Adjust the index value if the source operands will be swapped.
4130  if (ReverseVEXT)
4131    Imm -= NumElts;
4132
4133  return true;
4134}
4135
4136/// isVREVMask - Check if a vector shuffle corresponds to a VREV
4137/// instruction with the specified blocksize.  (The order of the elements
4138/// within each block of the vector is reversed.)
4139static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4140  assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4141         "Only possible block sizes for VREV are: 16, 32, 64");
4142
4143  unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4144  if (EltSz == 64)
4145    return false;
4146
4147  unsigned NumElts = VT.getVectorNumElements();
4148  unsigned BlockElts = M[0] + 1;
4149  // If the first shuffle index is UNDEF, be optimistic.
4150  if (M[0] < 0)
4151    BlockElts = BlockSize / EltSz;
4152
4153  if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4154    return false;
4155
4156  for (unsigned i = 0; i < NumElts; ++i) {
4157    if (M[i] < 0) continue; // ignore UNDEF indices
4158    if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4159      return false;
4160  }
4161
4162  return true;
4163}
4164
4165static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
4166  // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
4167  // range, then 0 is placed into the resulting vector. So pretty much any mask
4168  // of 8 elements can work here.
4169  return VT == MVT::v8i8 && M.size() == 8;
4170}
4171
4172static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4173  unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4174  if (EltSz == 64)
4175    return false;
4176
4177  unsigned NumElts = VT.getVectorNumElements();
4178  WhichResult = (M[0] == 0 ? 0 : 1);
4179  for (unsigned i = 0; i < NumElts; i += 2) {
4180    if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4181        (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
4182      return false;
4183  }
4184  return true;
4185}
4186
4187/// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
4188/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4189/// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4190static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4191  unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4192  if (EltSz == 64)
4193    return false;
4194
4195  unsigned NumElts = VT.getVectorNumElements();
4196  WhichResult = (M[0] == 0 ? 0 : 1);
4197  for (unsigned i = 0; i < NumElts; i += 2) {
4198    if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4199        (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4200      return false;
4201  }
4202  return true;
4203}
4204
4205static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4206  unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4207  if (EltSz == 64)
4208    return false;
4209
4210  unsigned NumElts = VT.getVectorNumElements();
4211  WhichResult = (M[0] == 0 ? 0 : 1);
4212  for (unsigned i = 0; i != NumElts; ++i) {
4213    if (M[i] < 0) continue; // ignore UNDEF indices
4214    if ((unsigned) M[i] != 2 * i + WhichResult)
4215      return false;
4216  }
4217
4218  // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4219  if (VT.is64BitVector() && EltSz == 32)
4220    return false;
4221
4222  return true;
4223}
4224
4225/// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4226/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4227/// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4228static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4229  unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4230  if (EltSz == 64)
4231    return false;
4232
4233  unsigned Half = VT.getVectorNumElements() / 2;
4234  WhichResult = (M[0] == 0 ? 0 : 1);
4235  for (unsigned j = 0; j != 2; ++j) {
4236    unsigned Idx = WhichResult;
4237    for (unsigned i = 0; i != Half; ++i) {
4238      int MIdx = M[i + j * Half];
4239      if (MIdx >= 0 && (unsigned) MIdx != Idx)
4240        return false;
4241      Idx += 2;
4242    }
4243  }
4244
4245  // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4246  if (VT.is64BitVector() && EltSz == 32)
4247    return false;
4248
4249  return true;
4250}
4251
4252static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4253  unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4254  if (EltSz == 64)
4255    return false;
4256
4257  unsigned NumElts = VT.getVectorNumElements();
4258  WhichResult = (M[0] == 0 ? 0 : 1);
4259  unsigned Idx = WhichResult * NumElts / 2;
4260  for (unsigned i = 0; i != NumElts; i += 2) {
4261    if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4262        (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
4263      return false;
4264    Idx += 1;
4265  }
4266
4267  // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4268  if (VT.is64BitVector() && EltSz == 32)
4269    return false;
4270
4271  return true;
4272}
4273
4274/// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
4275/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4276/// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4277static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4278  unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4279  if (EltSz == 64)
4280    return false;
4281
4282  unsigned NumElts = VT.getVectorNumElements();
4283  WhichResult = (M[0] == 0 ? 0 : 1);
4284  unsigned Idx = WhichResult * NumElts / 2;
4285  for (unsigned i = 0; i != NumElts; i += 2) {
4286    if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4287        (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
4288      return false;
4289    Idx += 1;
4290  }
4291
4292  // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4293  if (VT.is64BitVector() && EltSz == 32)
4294    return false;
4295
4296  return true;
4297}
4298
4299// If N is an integer constant that can be moved into a register in one
4300// instruction, return an SDValue of such a constant (will become a MOV
4301// instruction).  Otherwise return null.
4302static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
4303                                     const ARMSubtarget *ST, DebugLoc dl) {
4304  uint64_t Val;
4305  if (!isa<ConstantSDNode>(N))
4306    return SDValue();
4307  Val = cast<ConstantSDNode>(N)->getZExtValue();
4308
4309  if (ST->isThumb1Only()) {
4310    if (Val <= 255 || ~Val <= 255)
4311      return DAG.getConstant(Val, MVT::i32);
4312  } else {
4313    if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
4314      return DAG.getConstant(Val, MVT::i32);
4315  }
4316  return SDValue();
4317}
4318
4319// If this is a case we can't handle, return null and let the default
4320// expansion code take care of it.
4321SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
4322                                             const ARMSubtarget *ST) const {
4323  BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
4324  DebugLoc dl = Op.getDebugLoc();
4325  EVT VT = Op.getValueType();
4326
4327  APInt SplatBits, SplatUndef;
4328  unsigned SplatBitSize;
4329  bool HasAnyUndefs;
4330  if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4331    if (SplatBitSize <= 64) {
4332      // Check if an immediate VMOV works.
4333      EVT VmovVT;
4334      SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
4335                                      SplatUndef.getZExtValue(), SplatBitSize,
4336                                      DAG, VmovVT, VT.is128BitVector(),
4337                                      VMOVModImm);
4338      if (Val.getNode()) {
4339        SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
4340        return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4341      }
4342
4343      // Try an immediate VMVN.
4344      uint64_t NegatedImm = (~SplatBits).getZExtValue();
4345      Val = isNEONModifiedImm(NegatedImm,
4346                                      SplatUndef.getZExtValue(), SplatBitSize,
4347                                      DAG, VmovVT, VT.is128BitVector(),
4348                                      VMVNModImm);
4349      if (Val.getNode()) {
4350        SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
4351        return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4352      }
4353
4354      // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
4355      if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
4356        int ImmVal = ARM_AM::getFP32Imm(SplatBits);
4357        if (ImmVal != -1) {
4358          SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
4359          return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
4360        }
4361      }
4362    }
4363  }
4364
4365  // Scan through the operands to see if only one value is used.
4366  //
4367  // As an optimisation, even if more than one value is used it may be more
4368  // profitable to splat with one value then change some lanes.
4369  //
4370  // Heuristically we decide to do this if the vector has a "dominant" value,
4371  // defined as splatted to more than half of the lanes.
4372  unsigned NumElts = VT.getVectorNumElements();
4373  bool isOnlyLowElement = true;
4374  bool usesOnlyOneValue = true;
4375  bool hasDominantValue = false;
4376  bool isConstant = true;
4377
4378  // Map of the number of times a particular SDValue appears in the
4379  // element list.
4380  DenseMap<SDValue, unsigned> ValueCounts;
4381  SDValue Value;
4382  for (unsigned i = 0; i < NumElts; ++i) {
4383    SDValue V = Op.getOperand(i);
4384    if (V.getOpcode() == ISD::UNDEF)
4385      continue;
4386    if (i > 0)
4387      isOnlyLowElement = false;
4388    if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
4389      isConstant = false;
4390
4391    ValueCounts.insert(std::make_pair(V, 0));
4392    unsigned &Count = ValueCounts[V];
4393
4394    // Is this value dominant? (takes up more than half of the lanes)
4395    if (++Count > (NumElts / 2)) {
4396      hasDominantValue = true;
4397      Value = V;
4398    }
4399  }
4400  if (ValueCounts.size() != 1)
4401    usesOnlyOneValue = false;
4402  if (!Value.getNode() && ValueCounts.size() > 0)
4403    Value = ValueCounts.begin()->first;
4404
4405  if (ValueCounts.size() == 0)
4406    return DAG.getUNDEF(VT);
4407
4408  if (isOnlyLowElement)
4409    return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
4410
4411  unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4412
4413  // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
4414  // i32 and try again.
4415  if (hasDominantValue && EltSize <= 32) {
4416    if (!isConstant) {
4417      SDValue N;
4418
4419      // If we are VDUPing a value that comes directly from a vector, that will
4420      // cause an unnecessary move to and from a GPR, where instead we could
4421      // just use VDUPLANE.
4422      if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
4423        // We need to create a new undef vector to use for the VDUPLANE if the
4424        // size of the vector from which we get the value is different than the
4425        // size of the vector that we need to create. We will insert the element
4426        // such that the register coalescer will remove unnecessary copies.
4427        if (VT != Value->getOperand(0).getValueType()) {
4428          ConstantSDNode *constIndex;
4429          constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
4430          assert(constIndex && "The index is not a constant!");
4431          unsigned index = constIndex->getAPIntValue().getLimitedValue() %
4432                             VT.getVectorNumElements();
4433          N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4434                 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
4435                        Value, DAG.getConstant(index, MVT::i32)),
4436                           DAG.getConstant(index, MVT::i32));
4437        } else {
4438          N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4439                        Value->getOperand(0), Value->getOperand(1));
4440        }
4441      }
4442      else
4443        N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
4444
4445      if (!usesOnlyOneValue) {
4446        // The dominant value was splatted as 'N', but we now have to insert
4447        // all differing elements.
4448        for (unsigned I = 0; I < NumElts; ++I) {
4449          if (Op.getOperand(I) == Value)
4450            continue;
4451          SmallVector<SDValue, 3> Ops;
4452          Ops.push_back(N);
4453          Ops.push_back(Op.getOperand(I));
4454          Ops.push_back(DAG.getConstant(I, MVT::i32));
4455          N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, &Ops[0], 3);
4456        }
4457      }
4458      return N;
4459    }
4460    if (VT.getVectorElementType().isFloatingPoint()) {
4461      SmallVector<SDValue, 8> Ops;
4462      for (unsigned i = 0; i < NumElts; ++i)
4463        Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
4464                                  Op.getOperand(i)));
4465      EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
4466      SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], NumElts);
4467      Val = LowerBUILD_VECTOR(Val, DAG, ST);
4468      if (Val.getNode())
4469        return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4470    }
4471    if (usesOnlyOneValue) {
4472      SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
4473      if (isConstant && Val.getNode())
4474        return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
4475    }
4476  }
4477
4478  // If all elements are constants and the case above didn't get hit, fall back
4479  // to the default expansion, which will generate a load from the constant
4480  // pool.
4481  if (isConstant)
4482    return SDValue();
4483
4484  // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
4485  if (NumElts >= 4) {
4486    SDValue shuffle = ReconstructShuffle(Op, DAG);
4487    if (shuffle != SDValue())
4488      return shuffle;
4489  }
4490
4491  // Vectors with 32- or 64-bit elements can be built by directly assigning
4492  // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
4493  // will be legalized.
4494  if (EltSize >= 32) {
4495    // Do the expansion with floating-point types, since that is what the VFP
4496    // registers are defined to use, and since i64 is not legal.
4497    EVT EltVT = EVT::getFloatingPointVT(EltSize);
4498    EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
4499    SmallVector<SDValue, 8> Ops;
4500    for (unsigned i = 0; i < NumElts; ++i)
4501      Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
4502    SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
4503    return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4504  }
4505
4506  return SDValue();
4507}
4508
4509// Gather data to see if the operation can be modelled as a
4510// shuffle in combination with VEXTs.
4511SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
4512                                              SelectionDAG &DAG) const {
4513  DebugLoc dl = Op.getDebugLoc();
4514  EVT VT = Op.getValueType();
4515  unsigned NumElts = VT.getVectorNumElements();
4516
4517  SmallVector<SDValue, 2> SourceVecs;
4518  SmallVector<unsigned, 2> MinElts;
4519  SmallVector<unsigned, 2> MaxElts;
4520
4521  for (unsigned i = 0; i < NumElts; ++i) {
4522    SDValue V = Op.getOperand(i);
4523    if (V.getOpcode() == ISD::UNDEF)
4524      continue;
4525    else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
4526      // A shuffle can only come from building a vector from various
4527      // elements of other vectors.
4528      return SDValue();
4529    } else if (V.getOperand(0).getValueType().getVectorElementType() !=
4530               VT.getVectorElementType()) {
4531      // This code doesn't know how to handle shuffles where the vector
4532      // element types do not match (this happens because type legalization
4533      // promotes the return type of EXTRACT_VECTOR_ELT).
4534      // FIXME: It might be appropriate to extend this code to handle
4535      // mismatched types.
4536      return SDValue();
4537    }
4538
4539    // Record this extraction against the appropriate vector if possible...
4540    SDValue SourceVec = V.getOperand(0);
4541    // If the element number isn't a constant, we can't effectively
4542    // analyze what's going on.
4543    if (!isa<ConstantSDNode>(V.getOperand(1)))
4544      return SDValue();
4545    unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
4546    bool FoundSource = false;
4547    for (unsigned j = 0; j < SourceVecs.size(); ++j) {
4548      if (SourceVecs[j] == SourceVec) {
4549        if (MinElts[j] > EltNo)
4550          MinElts[j] = EltNo;
4551        if (MaxElts[j] < EltNo)
4552          MaxElts[j] = EltNo;
4553        FoundSource = true;
4554        break;
4555      }
4556    }
4557
4558    // Or record a new source if not...
4559    if (!FoundSource) {
4560      SourceVecs.push_back(SourceVec);
4561      MinElts.push_back(EltNo);
4562      MaxElts.push_back(EltNo);
4563    }
4564  }
4565
4566  // Currently only do something sane when at most two source vectors
4567  // involved.
4568  if (SourceVecs.size() > 2)
4569    return SDValue();
4570
4571  SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
4572  int VEXTOffsets[2] = {0, 0};
4573
4574  // This loop extracts the usage patterns of the source vectors
4575  // and prepares appropriate SDValues for a shuffle if possible.
4576  for (unsigned i = 0; i < SourceVecs.size(); ++i) {
4577    if (SourceVecs[i].getValueType() == VT) {
4578      // No VEXT necessary
4579      ShuffleSrcs[i] = SourceVecs[i];
4580      VEXTOffsets[i] = 0;
4581      continue;
4582    } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
4583      // It probably isn't worth padding out a smaller vector just to
4584      // break it down again in a shuffle.
4585      return SDValue();
4586    }
4587
4588    // Since only 64-bit and 128-bit vectors are legal on ARM and
4589    // we've eliminated the other cases...
4590    assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
4591           "unexpected vector sizes in ReconstructShuffle");
4592
4593    if (MaxElts[i] - MinElts[i] >= NumElts) {
4594      // Span too large for a VEXT to cope
4595      return SDValue();
4596    }
4597
4598    if (MinElts[i] >= NumElts) {
4599      // The extraction can just take the second half
4600      VEXTOffsets[i] = NumElts;
4601      ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4602                                   SourceVecs[i],
4603                                   DAG.getIntPtrConstant(NumElts));
4604    } else if (MaxElts[i] < NumElts) {
4605      // The extraction can just take the first half
4606      VEXTOffsets[i] = 0;
4607      ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4608                                   SourceVecs[i],
4609                                   DAG.getIntPtrConstant(0));
4610    } else {
4611      // An actual VEXT is needed
4612      VEXTOffsets[i] = MinElts[i];
4613      SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4614                                     SourceVecs[i],
4615                                     DAG.getIntPtrConstant(0));
4616      SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4617                                     SourceVecs[i],
4618                                     DAG.getIntPtrConstant(NumElts));
4619      ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
4620                                   DAG.getConstant(VEXTOffsets[i], MVT::i32));
4621    }
4622  }
4623
4624  SmallVector<int, 8> Mask;
4625
4626  for (unsigned i = 0; i < NumElts; ++i) {
4627    SDValue Entry = Op.getOperand(i);
4628    if (Entry.getOpcode() == ISD::UNDEF) {
4629      Mask.push_back(-1);
4630      continue;
4631    }
4632
4633    SDValue ExtractVec = Entry.getOperand(0);
4634    int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
4635                                          .getOperand(1))->getSExtValue();
4636    if (ExtractVec == SourceVecs[0]) {
4637      Mask.push_back(ExtractElt - VEXTOffsets[0]);
4638    } else {
4639      Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
4640    }
4641  }
4642
4643  // Final check before we try to produce nonsense...
4644  if (isShuffleMaskLegal(Mask, VT))
4645    return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
4646                                &Mask[0]);
4647
4648  return SDValue();
4649}
4650
4651/// isShuffleMaskLegal - Targets can use this to indicate that they only
4652/// support *some* VECTOR_SHUFFLE operations, those with specific masks.
4653/// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
4654/// are assumed to be legal.
4655bool
4656ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
4657                                      EVT VT) const {
4658  if (VT.getVectorNumElements() == 4 &&
4659      (VT.is128BitVector() || VT.is64BitVector())) {
4660    unsigned PFIndexes[4];
4661    for (unsigned i = 0; i != 4; ++i) {
4662      if (M[i] < 0)
4663        PFIndexes[i] = 8;
4664      else
4665        PFIndexes[i] = M[i];
4666    }
4667
4668    // Compute the index in the perfect shuffle table.
4669    unsigned PFTableIndex =
4670      PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
4671    unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
4672    unsigned Cost = (PFEntry >> 30);
4673
4674    if (Cost <= 4)
4675      return true;
4676  }
4677
4678  bool ReverseVEXT;
4679  unsigned Imm, WhichResult;
4680
4681  unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4682  return (EltSize >= 32 ||
4683          ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
4684          isVREVMask(M, VT, 64) ||
4685          isVREVMask(M, VT, 32) ||
4686          isVREVMask(M, VT, 16) ||
4687          isVEXTMask(M, VT, ReverseVEXT, Imm) ||
4688          isVTBLMask(M, VT) ||
4689          isVTRNMask(M, VT, WhichResult) ||
4690          isVUZPMask(M, VT, WhichResult) ||
4691          isVZIPMask(M, VT, WhichResult) ||
4692          isVTRN_v_undef_Mask(M, VT, WhichResult) ||
4693          isVUZP_v_undef_Mask(M, VT, WhichResult) ||
4694          isVZIP_v_undef_Mask(M, VT, WhichResult));
4695}
4696
4697/// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
4698/// the specified operations to build the shuffle.
4699static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
4700                                      SDValue RHS, SelectionDAG &DAG,
4701                                      DebugLoc dl) {
4702  unsigned OpNum = (PFEntry >> 26) & 0x0F;
4703  unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
4704  unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
4705
4706  enum {
4707    OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
4708    OP_VREV,
4709    OP_VDUP0,
4710    OP_VDUP1,
4711    OP_VDUP2,
4712    OP_VDUP3,
4713    OP_VEXT1,
4714    OP_VEXT2,
4715    OP_VEXT3,
4716    OP_VUZPL, // VUZP, left result
4717    OP_VUZPR, // VUZP, right result
4718    OP_VZIPL, // VZIP, left result
4719    OP_VZIPR, // VZIP, right result
4720    OP_VTRNL, // VTRN, left result
4721    OP_VTRNR  // VTRN, right result
4722  };
4723
4724  if (OpNum == OP_COPY) {
4725    if (LHSID == (1*9+2)*9+3) return LHS;
4726    assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
4727    return RHS;
4728  }
4729
4730  SDValue OpLHS, OpRHS;
4731  OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
4732  OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
4733  EVT VT = OpLHS.getValueType();
4734
4735  switch (OpNum) {
4736  default: llvm_unreachable("Unknown shuffle opcode!");
4737  case OP_VREV:
4738    // VREV divides the vector in half and swaps within the half.
4739    if (VT.getVectorElementType() == MVT::i32 ||
4740        VT.getVectorElementType() == MVT::f32)
4741      return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
4742    // vrev <4 x i16> -> VREV32
4743    if (VT.getVectorElementType() == MVT::i16)
4744      return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
4745    // vrev <4 x i8> -> VREV16
4746    assert(VT.getVectorElementType() == MVT::i8);
4747    return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
4748  case OP_VDUP0:
4749  case OP_VDUP1:
4750  case OP_VDUP2:
4751  case OP_VDUP3:
4752    return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4753                       OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
4754  case OP_VEXT1:
4755  case OP_VEXT2:
4756  case OP_VEXT3:
4757    return DAG.getNode(ARMISD::VEXT, dl, VT,
4758                       OpLHS, OpRHS,
4759                       DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
4760  case OP_VUZPL:
4761  case OP_VUZPR:
4762    return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4763                       OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
4764  case OP_VZIPL:
4765  case OP_VZIPR:
4766    return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4767                       OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
4768  case OP_VTRNL:
4769  case OP_VTRNR:
4770    return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4771                       OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
4772  }
4773}
4774
4775static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
4776                                       ArrayRef<int> ShuffleMask,
4777                                       SelectionDAG &DAG) {
4778  // Check to see if we can use the VTBL instruction.
4779  SDValue V1 = Op.getOperand(0);
4780  SDValue V2 = Op.getOperand(1);
4781  DebugLoc DL = Op.getDebugLoc();
4782
4783  SmallVector<SDValue, 8> VTBLMask;
4784  for (ArrayRef<int>::iterator
4785         I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
4786    VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
4787
4788  if (V2.getNode()->getOpcode() == ISD::UNDEF)
4789    return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
4790                       DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
4791                                   &VTBLMask[0], 8));
4792
4793  return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
4794                     DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
4795                                 &VTBLMask[0], 8));
4796}
4797
4798static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
4799  SDValue V1 = Op.getOperand(0);
4800  SDValue V2 = Op.getOperand(1);
4801  DebugLoc dl = Op.getDebugLoc();
4802  EVT VT = Op.getValueType();
4803  ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
4804
4805  // Convert shuffles that are directly supported on NEON to target-specific
4806  // DAG nodes, instead of keeping them as shuffles and matching them again
4807  // during code selection.  This is more efficient and avoids the possibility
4808  // of inconsistencies between legalization and selection.
4809  // FIXME: floating-point vectors should be canonicalized to integer vectors
4810  // of the same time so that they get CSEd properly.
4811  ArrayRef<int> ShuffleMask = SVN->getMask();
4812
4813  unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4814  if (EltSize <= 32) {
4815    if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
4816      int Lane = SVN->getSplatIndex();
4817      // If this is undef splat, generate it via "just" vdup, if possible.
4818      if (Lane == -1) Lane = 0;
4819
4820      // Test if V1 is a SCALAR_TO_VECTOR.
4821      if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
4822        return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
4823      }
4824      // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
4825      // (and probably will turn into a SCALAR_TO_VECTOR once legalization
4826      // reaches it).
4827      if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
4828          !isa<ConstantSDNode>(V1.getOperand(0))) {
4829        bool IsScalarToVector = true;
4830        for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
4831          if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
4832            IsScalarToVector = false;
4833            break;
4834          }
4835        if (IsScalarToVector)
4836          return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
4837      }
4838      return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
4839                         DAG.getConstant(Lane, MVT::i32));
4840    }
4841
4842    bool ReverseVEXT;
4843    unsigned Imm;
4844    if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
4845      if (ReverseVEXT)
4846        std::swap(V1, V2);
4847      return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
4848                         DAG.getConstant(Imm, MVT::i32));
4849    }
4850
4851    if (isVREVMask(ShuffleMask, VT, 64))
4852      return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
4853    if (isVREVMask(ShuffleMask, VT, 32))
4854      return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
4855    if (isVREVMask(ShuffleMask, VT, 16))
4856      return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
4857
4858    if (V2->getOpcode() == ISD::UNDEF &&
4859        isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
4860      return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
4861                         DAG.getConstant(Imm, MVT::i32));
4862    }
4863
4864    // Check for Neon shuffles that modify both input vectors in place.
4865    // If both results are used, i.e., if there are two shuffles with the same
4866    // source operands and with masks corresponding to both results of one of
4867    // these operations, DAG memoization will ensure that a single node is
4868    // used for both shuffles.
4869    unsigned WhichResult;
4870    if (isVTRNMask(ShuffleMask, VT, WhichResult))
4871      return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4872                         V1, V2).getValue(WhichResult);
4873    if (isVUZPMask(ShuffleMask, VT, WhichResult))
4874      return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4875                         V1, V2).getValue(WhichResult);
4876    if (isVZIPMask(ShuffleMask, VT, WhichResult))
4877      return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4878                         V1, V2).getValue(WhichResult);
4879
4880    if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
4881      return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4882                         V1, V1).getValue(WhichResult);
4883    if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
4884      return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4885                         V1, V1).getValue(WhichResult);
4886    if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
4887      return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4888                         V1, V1).getValue(WhichResult);
4889  }
4890
4891  // If the shuffle is not directly supported and it has 4 elements, use
4892  // the PerfectShuffle-generated table to synthesize it from other shuffles.
4893  unsigned NumElts = VT.getVectorNumElements();
4894  if (NumElts == 4) {
4895    unsigned PFIndexes[4];
4896    for (unsigned i = 0; i != 4; ++i) {
4897      if (ShuffleMask[i] < 0)
4898        PFIndexes[i] = 8;
4899      else
4900        PFIndexes[i] = ShuffleMask[i];
4901    }
4902
4903    // Compute the index in the perfect shuffle table.
4904    unsigned PFTableIndex =
4905      PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
4906    unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
4907    unsigned Cost = (PFEntry >> 30);
4908
4909    if (Cost <= 4)
4910      return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
4911  }
4912
4913  // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
4914  if (EltSize >= 32) {
4915    // Do the expansion with floating-point types, since that is what the VFP
4916    // registers are defined to use, and since i64 is not legal.
4917    EVT EltVT = EVT::getFloatingPointVT(EltSize);
4918    EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
4919    V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
4920    V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
4921    SmallVector<SDValue, 8> Ops;
4922    for (unsigned i = 0; i < NumElts; ++i) {
4923      if (ShuffleMask[i] < 0)
4924        Ops.push_back(DAG.getUNDEF(EltVT));
4925      else
4926        Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
4927                                  ShuffleMask[i] < (int)NumElts ? V1 : V2,
4928                                  DAG.getConstant(ShuffleMask[i] & (NumElts-1),
4929                                                  MVT::i32)));
4930    }
4931    SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
4932    return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4933  }
4934
4935  if (VT == MVT::v8i8) {
4936    SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
4937    if (NewOp.getNode())
4938      return NewOp;
4939  }
4940
4941  return SDValue();
4942}
4943
4944static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4945  // INSERT_VECTOR_ELT is legal only for immediate indexes.
4946  SDValue Lane = Op.getOperand(2);
4947  if (!isa<ConstantSDNode>(Lane))
4948    return SDValue();
4949
4950  return Op;
4951}
4952
4953static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4954  // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
4955  SDValue Lane = Op.getOperand(1);
4956  if (!isa<ConstantSDNode>(Lane))
4957    return SDValue();
4958
4959  SDValue Vec = Op.getOperand(0);
4960  if (Op.getValueType() == MVT::i32 &&
4961      Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
4962    DebugLoc dl = Op.getDebugLoc();
4963    return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
4964  }
4965
4966  return Op;
4967}
4968
4969static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
4970  // The only time a CONCAT_VECTORS operation can have legal types is when
4971  // two 64-bit vectors are concatenated to a 128-bit vector.
4972  assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
4973         "unexpected CONCAT_VECTORS");
4974  DebugLoc dl = Op.getDebugLoc();
4975  SDValue Val = DAG.getUNDEF(MVT::v2f64);
4976  SDValue Op0 = Op.getOperand(0);
4977  SDValue Op1 = Op.getOperand(1);
4978  if (Op0.getOpcode() != ISD::UNDEF)
4979    Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
4980                      DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
4981                      DAG.getIntPtrConstant(0));
4982  if (Op1.getOpcode() != ISD::UNDEF)
4983    Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
4984                      DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
4985                      DAG.getIntPtrConstant(1));
4986  return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
4987}
4988
4989/// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
4990/// element has been zero/sign-extended, depending on the isSigned parameter,
4991/// from an integer type half its size.
4992static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
4993                                   bool isSigned) {
4994  // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
4995  EVT VT = N->getValueType(0);
4996  if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
4997    SDNode *BVN = N->getOperand(0).getNode();
4998    if (BVN->getValueType(0) != MVT::v4i32 ||
4999        BVN->getOpcode() != ISD::BUILD_VECTOR)
5000      return false;
5001    unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5002    unsigned HiElt = 1 - LoElt;
5003    ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
5004    ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
5005    ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
5006    ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
5007    if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
5008      return false;
5009    if (isSigned) {
5010      if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
5011          Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
5012        return true;
5013    } else {
5014      if (Hi0->isNullValue() && Hi1->isNullValue())
5015        return true;
5016    }
5017    return false;
5018  }
5019
5020  if (N->getOpcode() != ISD::BUILD_VECTOR)
5021    return false;
5022
5023  for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5024    SDNode *Elt = N->getOperand(i).getNode();
5025    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
5026      unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5027      unsigned HalfSize = EltSize / 2;
5028      if (isSigned) {
5029        if (!isIntN(HalfSize, C->getSExtValue()))
5030          return false;
5031      } else {
5032        if (!isUIntN(HalfSize, C->getZExtValue()))
5033          return false;
5034      }
5035      continue;
5036    }
5037    return false;
5038  }
5039
5040  return true;
5041}
5042
5043/// isSignExtended - Check if a node is a vector value that is sign-extended
5044/// or a constant BUILD_VECTOR with sign-extended elements.
5045static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
5046  if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
5047    return true;
5048  if (isExtendedBUILD_VECTOR(N, DAG, true))
5049    return true;
5050  return false;
5051}
5052
5053/// isZeroExtended - Check if a node is a vector value that is zero-extended
5054/// or a constant BUILD_VECTOR with zero-extended elements.
5055static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
5056  if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
5057    return true;
5058  if (isExtendedBUILD_VECTOR(N, DAG, false))
5059    return true;
5060  return false;
5061}
5062
5063/// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
5064/// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
5065/// We insert the required extension here to get the vector to fill a D register.
5066static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
5067                                            const EVT &OrigTy,
5068                                            const EVT &ExtTy,
5069                                            unsigned ExtOpcode) {
5070  // The vector originally had a size of OrigTy. It was then extended to ExtTy.
5071  // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
5072  // 64-bits we need to insert a new extension so that it will be 64-bits.
5073  assert(ExtTy.is128BitVector() && "Unexpected extension size");
5074  if (OrigTy.getSizeInBits() >= 64)
5075    return N;
5076
5077  // Must extend size to at least 64 bits to be used as an operand for VMULL.
5078  MVT::SimpleValueType OrigSimpleTy = OrigTy.getSimpleVT().SimpleTy;
5079  EVT NewVT;
5080  switch (OrigSimpleTy) {
5081  default: llvm_unreachable("Unexpected Orig Vector Type");
5082  case MVT::v2i8:
5083  case MVT::v2i16:
5084    NewVT = MVT::v2i32;
5085    break;
5086  case MVT::v4i8:
5087    NewVT = MVT::v4i16;
5088    break;
5089  }
5090  return DAG.getNode(ExtOpcode, N->getDebugLoc(), NewVT, N);
5091}
5092
5093/// SkipLoadExtensionForVMULL - return a load of the original vector size that
5094/// does not do any sign/zero extension. If the original vector is less
5095/// than 64 bits, an appropriate extension will be added after the load to
5096/// reach a total size of 64 bits. We have to add the extension separately
5097/// because ARM does not have a sign/zero extending load for vectors.
5098static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
5099  SDValue NonExtendingLoad =
5100    DAG.getLoad(LD->getMemoryVT(), LD->getDebugLoc(), LD->getChain(),
5101                LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
5102                LD->isNonTemporal(), LD->isInvariant(),
5103                LD->getAlignment());
5104  unsigned ExtOp = 0;
5105  switch (LD->getExtensionType()) {
5106  default: llvm_unreachable("Unexpected LoadExtType");
5107  case ISD::EXTLOAD:
5108  case ISD::SEXTLOAD: ExtOp = ISD::SIGN_EXTEND; break;
5109  case ISD::ZEXTLOAD: ExtOp = ISD::ZERO_EXTEND; break;
5110  }
5111  MVT::SimpleValueType MemType = LD->getMemoryVT().getSimpleVT().SimpleTy;
5112  MVT::SimpleValueType ExtType = LD->getValueType(0).getSimpleVT().SimpleTy;
5113  return AddRequiredExtensionForVMULL(NonExtendingLoad, DAG,
5114                                      MemType, ExtType, ExtOp);
5115}
5116
5117/// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
5118/// extending load, or BUILD_VECTOR with extended elements, return the
5119/// unextended value. The unextended vector should be 64 bits so that it can
5120/// be used as an operand to a VMULL instruction. If the original vector size
5121/// before extension is less than 64 bits we add a an extension to resize
5122/// the vector to 64 bits.
5123static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
5124  if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
5125    return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
5126                                        N->getOperand(0)->getValueType(0),
5127                                        N->getValueType(0),
5128                                        N->getOpcode());
5129
5130  if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
5131    return SkipLoadExtensionForVMULL(LD, DAG);
5132
5133  // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
5134  // have been legalized as a BITCAST from v4i32.
5135  if (N->getOpcode() == ISD::BITCAST) {
5136    SDNode *BVN = N->getOperand(0).getNode();
5137    assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
5138           BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
5139    unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5140    return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), MVT::v2i32,
5141                       BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
5142  }
5143  // Construct a new BUILD_VECTOR with elements truncated to half the size.
5144  assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
5145  EVT VT = N->getValueType(0);
5146  unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
5147  unsigned NumElts = VT.getVectorNumElements();
5148  MVT TruncVT = MVT::getIntegerVT(EltSize);
5149  SmallVector<SDValue, 8> Ops;
5150  for (unsigned i = 0; i != NumElts; ++i) {
5151    ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
5152    const APInt &CInt = C->getAPIntValue();
5153    // Element types smaller than 32 bits are not legal, so use i32 elements.
5154    // The values are implicitly truncated so sext vs. zext doesn't matter.
5155    Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
5156  }
5157  return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
5158                     MVT::getVectorVT(TruncVT, NumElts), Ops.data(), NumElts);
5159}
5160
5161static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
5162  unsigned Opcode = N->getOpcode();
5163  if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5164    SDNode *N0 = N->getOperand(0).getNode();
5165    SDNode *N1 = N->getOperand(1).getNode();
5166    return N0->hasOneUse() && N1->hasOneUse() &&
5167      isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
5168  }
5169  return false;
5170}
5171
5172static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
5173  unsigned Opcode = N->getOpcode();
5174  if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5175    SDNode *N0 = N->getOperand(0).getNode();
5176    SDNode *N1 = N->getOperand(1).getNode();
5177    return N0->hasOneUse() && N1->hasOneUse() &&
5178      isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
5179  }
5180  return false;
5181}
5182
5183static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
5184  // Multiplications are only custom-lowered for 128-bit vectors so that
5185  // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
5186  EVT VT = Op.getValueType();
5187  assert(VT.is128BitVector() && VT.isInteger() &&
5188         "unexpected type for custom-lowering ISD::MUL");
5189  SDNode *N0 = Op.getOperand(0).getNode();
5190  SDNode *N1 = Op.getOperand(1).getNode();
5191  unsigned NewOpc = 0;
5192  bool isMLA = false;
5193  bool isN0SExt = isSignExtended(N0, DAG);
5194  bool isN1SExt = isSignExtended(N1, DAG);
5195  if (isN0SExt && isN1SExt)
5196    NewOpc = ARMISD::VMULLs;
5197  else {
5198    bool isN0ZExt = isZeroExtended(N0, DAG);
5199    bool isN1ZExt = isZeroExtended(N1, DAG);
5200    if (isN0ZExt && isN1ZExt)
5201      NewOpc = ARMISD::VMULLu;
5202    else if (isN1SExt || isN1ZExt) {
5203      // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
5204      // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
5205      if (isN1SExt && isAddSubSExt(N0, DAG)) {
5206        NewOpc = ARMISD::VMULLs;
5207        isMLA = true;
5208      } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
5209        NewOpc = ARMISD::VMULLu;
5210        isMLA = true;
5211      } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
5212        std::swap(N0, N1);
5213        NewOpc = ARMISD::VMULLu;
5214        isMLA = true;
5215      }
5216    }
5217
5218    if (!NewOpc) {
5219      if (VT == MVT::v2i64)
5220        // Fall through to expand this.  It is not legal.
5221        return SDValue();
5222      else
5223        // Other vector multiplications are legal.
5224        return Op;
5225    }
5226  }
5227
5228  // Legalize to a VMULL instruction.
5229  DebugLoc DL = Op.getDebugLoc();
5230  SDValue Op0;
5231  SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
5232  if (!isMLA) {
5233    Op0 = SkipExtensionForVMULL(N0, DAG);
5234    assert(Op0.getValueType().is64BitVector() &&
5235           Op1.getValueType().is64BitVector() &&
5236           "unexpected types for extended operands to VMULL");
5237    return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
5238  }
5239
5240  // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
5241  // isel lowering to take advantage of no-stall back to back vmul + vmla.
5242  //   vmull q0, d4, d6
5243  //   vmlal q0, d5, d6
5244  // is faster than
5245  //   vaddl q0, d4, d5
5246  //   vmovl q1, d6
5247  //   vmul  q0, q0, q1
5248  SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
5249  SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
5250  EVT Op1VT = Op1.getValueType();
5251  return DAG.getNode(N0->getOpcode(), DL, VT,
5252                     DAG.getNode(NewOpc, DL, VT,
5253                               DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
5254                     DAG.getNode(NewOpc, DL, VT,
5255                               DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
5256}
5257
5258static SDValue
5259LowerSDIV_v4i8(SDValue X, SDValue Y, DebugLoc dl, SelectionDAG &DAG) {
5260  // Convert to float
5261  // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
5262  // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
5263  X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
5264  Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
5265  X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
5266  Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
5267  // Get reciprocal estimate.
5268  // float4 recip = vrecpeq_f32(yf);
5269  Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5270                   DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
5271  // Because char has a smaller range than uchar, we can actually get away
5272  // without any newton steps.  This requires that we use a weird bias
5273  // of 0xb000, however (again, this has been exhaustively tested).
5274  // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
5275  X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
5276  X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
5277  Y = DAG.getConstant(0xb000, MVT::i32);
5278  Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
5279  X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
5280  X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
5281  // Convert back to short.
5282  X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
5283  X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
5284  return X;
5285}
5286
5287static SDValue
5288LowerSDIV_v4i16(SDValue N0, SDValue N1, DebugLoc dl, SelectionDAG &DAG) {
5289  SDValue N2;
5290  // Convert to float.
5291  // float4 yf = vcvt_f32_s32(vmovl_s16(y));
5292  // float4 xf = vcvt_f32_s32(vmovl_s16(x));
5293  N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
5294  N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
5295  N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5296  N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5297
5298  // Use reciprocal estimate and one refinement step.
5299  // float4 recip = vrecpeq_f32(yf);
5300  // recip *= vrecpsq_f32(yf, recip);
5301  N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5302                   DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
5303  N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5304                   DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5305                   N1, N2);
5306  N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5307  // Because short has a smaller range than ushort, we can actually get away
5308  // with only a single newton step.  This requires that we use a weird bias
5309  // of 89, however (again, this has been exhaustively tested).
5310  // float4 result = as_float4(as_int4(xf*recip) + 0x89);
5311  N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5312  N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5313  N1 = DAG.getConstant(0x89, MVT::i32);
5314  N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5315  N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5316  N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5317  // Convert back to integer and return.
5318  // return vmovn_s32(vcvt_s32_f32(result));
5319  N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5320  N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5321  return N0;
5322}
5323
5324static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
5325  EVT VT = Op.getValueType();
5326  assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5327         "unexpected type for custom-lowering ISD::SDIV");
5328
5329  DebugLoc dl = Op.getDebugLoc();
5330  SDValue N0 = Op.getOperand(0);
5331  SDValue N1 = Op.getOperand(1);
5332  SDValue N2, N3;
5333
5334  if (VT == MVT::v8i8) {
5335    N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
5336    N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
5337
5338    N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5339                     DAG.getIntPtrConstant(4));
5340    N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5341                     DAG.getIntPtrConstant(4));
5342    N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5343                     DAG.getIntPtrConstant(0));
5344    N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5345                     DAG.getIntPtrConstant(0));
5346
5347    N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
5348    N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
5349
5350    N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5351    N0 = LowerCONCAT_VECTORS(N0, DAG);
5352
5353    N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
5354    return N0;
5355  }
5356  return LowerSDIV_v4i16(N0, N1, dl, DAG);
5357}
5358
5359static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
5360  EVT VT = Op.getValueType();
5361  assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5362         "unexpected type for custom-lowering ISD::UDIV");
5363
5364  DebugLoc dl = Op.getDebugLoc();
5365  SDValue N0 = Op.getOperand(0);
5366  SDValue N1 = Op.getOperand(1);
5367  SDValue N2, N3;
5368
5369  if (VT == MVT::v8i8) {
5370    N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
5371    N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
5372
5373    N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5374                     DAG.getIntPtrConstant(4));
5375    N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5376                     DAG.getIntPtrConstant(4));
5377    N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5378                     DAG.getIntPtrConstant(0));
5379    N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5380                     DAG.getIntPtrConstant(0));
5381
5382    N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
5383    N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
5384
5385    N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5386    N0 = LowerCONCAT_VECTORS(N0, DAG);
5387
5388    N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
5389                     DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
5390                     N0);
5391    return N0;
5392  }
5393
5394  // v4i16 sdiv ... Convert to float.
5395  // float4 yf = vcvt_f32_s32(vmovl_u16(y));
5396  // float4 xf = vcvt_f32_s32(vmovl_u16(x));
5397  N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
5398  N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
5399  N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5400  SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5401
5402  // Use reciprocal estimate and two refinement steps.
5403  // float4 recip = vrecpeq_f32(yf);
5404  // recip *= vrecpsq_f32(yf, recip);
5405  // recip *= vrecpsq_f32(yf, recip);
5406  N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5407                   DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
5408  N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5409                   DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5410                   BN1, N2);
5411  N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5412  N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5413                   DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5414                   BN1, N2);
5415  N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5416  // Simply multiplying by the reciprocal estimate can leave us a few ulps
5417  // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
5418  // and that it will never cause us to return an answer too large).
5419  // float4 result = as_float4(as_int4(xf*recip) + 2);
5420  N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5421  N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5422  N1 = DAG.getConstant(2, MVT::i32);
5423  N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5424  N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5425  N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5426  // Convert back to integer and return.
5427  // return vmovn_u32(vcvt_s32_f32(result));
5428  N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5429  N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5430  return N0;
5431}
5432
5433static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
5434  EVT VT = Op.getNode()->getValueType(0);
5435  SDVTList VTs = DAG.getVTList(VT, MVT::i32);
5436
5437  unsigned Opc;
5438  bool ExtraOp = false;
5439  switch (Op.getOpcode()) {
5440  default: llvm_unreachable("Invalid code");
5441  case ISD::ADDC: Opc = ARMISD::ADDC; break;
5442  case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
5443  case ISD::SUBC: Opc = ARMISD::SUBC; break;
5444  case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
5445  }
5446
5447  if (!ExtraOp)
5448    return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
5449                       Op.getOperand(1));
5450  return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
5451                     Op.getOperand(1), Op.getOperand(2));
5452}
5453
5454static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
5455  // Monotonic load/store is legal for all targets
5456  if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
5457    return Op;
5458
5459  // Aquire/Release load/store is not legal for targets without a
5460  // dmb or equivalent available.
5461  return SDValue();
5462}
5463
5464
5465static void
5466ReplaceATOMIC_OP_64(SDNode *Node, SmallVectorImpl<SDValue>& Results,
5467                    SelectionDAG &DAG, unsigned NewOp) {
5468  DebugLoc dl = Node->getDebugLoc();
5469  assert (Node->getValueType(0) == MVT::i64 &&
5470          "Only know how to expand i64 atomics");
5471
5472  SmallVector<SDValue, 6> Ops;
5473  Ops.push_back(Node->getOperand(0)); // Chain
5474  Ops.push_back(Node->getOperand(1)); // Ptr
5475  // Low part of Val1
5476  Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5477                            Node->getOperand(2), DAG.getIntPtrConstant(0)));
5478  // High part of Val1
5479  Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5480                            Node->getOperand(2), DAG.getIntPtrConstant(1)));
5481  if (NewOp == ARMISD::ATOMCMPXCHG64_DAG) {
5482    // High part of Val1
5483    Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5484                              Node->getOperand(3), DAG.getIntPtrConstant(0)));
5485    // High part of Val2
5486    Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5487                              Node->getOperand(3), DAG.getIntPtrConstant(1)));
5488  }
5489  SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
5490  SDValue Result =
5491    DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops.data(), Ops.size(), MVT::i64,
5492                            cast<MemSDNode>(Node)->getMemOperand());
5493  SDValue OpsF[] = { Result.getValue(0), Result.getValue(1) };
5494  Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
5495  Results.push_back(Result.getValue(2));
5496}
5497
5498SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
5499  switch (Op.getOpcode()) {
5500  default: llvm_unreachable("Don't know how to custom lower this!");
5501  case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
5502  case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
5503  case ISD::GlobalAddress:
5504    return Subtarget->isTargetDarwin() ? LowerGlobalAddressDarwin(Op, DAG) :
5505      LowerGlobalAddressELF(Op, DAG);
5506  case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
5507  case ISD::SELECT:        return LowerSELECT(Op, DAG);
5508  case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
5509  case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
5510  case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
5511  case ISD::VASTART:       return LowerVASTART(Op, DAG);
5512  case ISD::MEMBARRIER:    return LowerMEMBARRIER(Op, DAG, Subtarget);
5513  case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
5514  case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
5515  case ISD::SINT_TO_FP:
5516  case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
5517  case ISD::FP_TO_SINT:
5518  case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
5519  case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
5520  case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
5521  case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
5522  case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
5523  case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
5524  case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
5525  case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
5526                                                               Subtarget);
5527  case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
5528  case ISD::SHL:
5529  case ISD::SRL:
5530  case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
5531  case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
5532  case ISD::SRL_PARTS:
5533  case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
5534  case ISD::CTTZ:          return LowerCTTZ(Op.getNode(), DAG, Subtarget);
5535  case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
5536  case ISD::SETCC:         return LowerVSETCC(Op, DAG);
5537  case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
5538  case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
5539  case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
5540  case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
5541  case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
5542  case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
5543  case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
5544  case ISD::MUL:           return LowerMUL(Op, DAG);
5545  case ISD::SDIV:          return LowerSDIV(Op, DAG);
5546  case ISD::UDIV:          return LowerUDIV(Op, DAG);
5547  case ISD::ADDC:
5548  case ISD::ADDE:
5549  case ISD::SUBC:
5550  case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
5551  case ISD::ATOMIC_LOAD:
5552  case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
5553  }
5554}
5555
5556/// ReplaceNodeResults - Replace the results of node with an illegal result
5557/// type with new values built out of custom code.
5558void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
5559                                           SmallVectorImpl<SDValue>&Results,
5560                                           SelectionDAG &DAG) const {
5561  SDValue Res;
5562  switch (N->getOpcode()) {
5563  default:
5564    llvm_unreachable("Don't know how to custom expand this!");
5565  case ISD::BITCAST:
5566    Res = ExpandBITCAST(N, DAG);
5567    break;
5568  case ISD::SRL:
5569  case ISD::SRA:
5570    Res = Expand64BitShift(N, DAG, Subtarget);
5571    break;
5572  case ISD::ATOMIC_LOAD_ADD:
5573    ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMADD64_DAG);
5574    return;
5575  case ISD::ATOMIC_LOAD_AND:
5576    ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMAND64_DAG);
5577    return;
5578  case ISD::ATOMIC_LOAD_NAND:
5579    ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMNAND64_DAG);
5580    return;
5581  case ISD::ATOMIC_LOAD_OR:
5582    ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMOR64_DAG);
5583    return;
5584  case ISD::ATOMIC_LOAD_SUB:
5585    ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMSUB64_DAG);
5586    return;
5587  case ISD::ATOMIC_LOAD_XOR:
5588    ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMXOR64_DAG);
5589    return;
5590  case ISD::ATOMIC_SWAP:
5591    ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMSWAP64_DAG);
5592    return;
5593  case ISD::ATOMIC_CMP_SWAP:
5594    ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMCMPXCHG64_DAG);
5595    return;
5596  case ISD::ATOMIC_LOAD_MIN:
5597    ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMMIN64_DAG);
5598    return;
5599  case ISD::ATOMIC_LOAD_UMIN:
5600    ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMUMIN64_DAG);
5601    return;
5602  case ISD::ATOMIC_LOAD_MAX:
5603    ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMMAX64_DAG);
5604    return;
5605  case ISD::ATOMIC_LOAD_UMAX:
5606    ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMUMAX64_DAG);
5607    return;
5608  }
5609  if (Res.getNode())
5610    Results.push_back(Res);
5611}
5612
5613//===----------------------------------------------------------------------===//
5614//                           ARM Scheduler Hooks
5615//===----------------------------------------------------------------------===//
5616
5617MachineBasicBlock *
5618ARMTargetLowering::EmitAtomicCmpSwap(MachineInstr *MI,
5619                                     MachineBasicBlock *BB,
5620                                     unsigned Size) const {
5621  unsigned dest    = MI->getOperand(0).getReg();
5622  unsigned ptr     = MI->getOperand(1).getReg();
5623  unsigned oldval  = MI->getOperand(2).getReg();
5624  unsigned newval  = MI->getOperand(3).getReg();
5625  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5626  DebugLoc dl = MI->getDebugLoc();
5627  bool isThumb2 = Subtarget->isThumb2();
5628
5629  MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5630  unsigned scratch = MRI.createVirtualRegister(isThumb2 ?
5631    (const TargetRegisterClass*)&ARM::rGPRRegClass :
5632    (const TargetRegisterClass*)&ARM::GPRRegClass);
5633
5634  if (isThumb2) {
5635    MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
5636    MRI.constrainRegClass(oldval, &ARM::rGPRRegClass);
5637    MRI.constrainRegClass(newval, &ARM::rGPRRegClass);
5638  }
5639
5640  unsigned ldrOpc, strOpc;
5641  switch (Size) {
5642  default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5643  case 1:
5644    ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5645    strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5646    break;
5647  case 2:
5648    ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5649    strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5650    break;
5651  case 4:
5652    ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5653    strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5654    break;
5655  }
5656
5657  MachineFunction *MF = BB->getParent();
5658  const BasicBlock *LLVM_BB = BB->getBasicBlock();
5659  MachineFunction::iterator It = BB;
5660  ++It; // insert the new blocks after the current block
5661
5662  MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
5663  MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
5664  MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5665  MF->insert(It, loop1MBB);
5666  MF->insert(It, loop2MBB);
5667  MF->insert(It, exitMBB);
5668
5669  // Transfer the remainder of BB and its successor edges to exitMBB.
5670  exitMBB->splice(exitMBB->begin(), BB,
5671                  llvm::next(MachineBasicBlock::iterator(MI)),
5672                  BB->end());
5673  exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5674
5675  //  thisMBB:
5676  //   ...
5677  //   fallthrough --> loop1MBB
5678  BB->addSuccessor(loop1MBB);
5679
5680  // loop1MBB:
5681  //   ldrex dest, [ptr]
5682  //   cmp dest, oldval
5683  //   bne exitMBB
5684  BB = loop1MBB;
5685  MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5686  if (ldrOpc == ARM::t2LDREX)
5687    MIB.addImm(0);
5688  AddDefaultPred(MIB);
5689  AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
5690                 .addReg(dest).addReg(oldval));
5691  BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5692    .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5693  BB->addSuccessor(loop2MBB);
5694  BB->addSuccessor(exitMBB);
5695
5696  // loop2MBB:
5697  //   strex scratch, newval, [ptr]
5698  //   cmp scratch, #0
5699  //   bne loop1MBB
5700  BB = loop2MBB;
5701  MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(newval).addReg(ptr);
5702  if (strOpc == ARM::t2STREX)
5703    MIB.addImm(0);
5704  AddDefaultPred(MIB);
5705  AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5706                 .addReg(scratch).addImm(0));
5707  BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5708    .addMBB(loop1MBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5709  BB->addSuccessor(loop1MBB);
5710  BB->addSuccessor(exitMBB);
5711
5712  //  exitMBB:
5713  //   ...
5714  BB = exitMBB;
5715
5716  MI->eraseFromParent();   // The instruction is gone now.
5717
5718  return BB;
5719}
5720
5721MachineBasicBlock *
5722ARMTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
5723                                    unsigned Size, unsigned BinOpcode) const {
5724  // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
5725  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5726
5727  const BasicBlock *LLVM_BB = BB->getBasicBlock();
5728  MachineFunction *MF = BB->getParent();
5729  MachineFunction::iterator It = BB;
5730  ++It;
5731
5732  unsigned dest = MI->getOperand(0).getReg();
5733  unsigned ptr = MI->getOperand(1).getReg();
5734  unsigned incr = MI->getOperand(2).getReg();
5735  DebugLoc dl = MI->getDebugLoc();
5736  bool isThumb2 = Subtarget->isThumb2();
5737
5738  MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5739  if (isThumb2) {
5740    MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
5741    MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
5742  }
5743
5744  unsigned ldrOpc, strOpc;
5745  switch (Size) {
5746  default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5747  case 1:
5748    ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5749    strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5750    break;
5751  case 2:
5752    ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5753    strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5754    break;
5755  case 4:
5756    ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5757    strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5758    break;
5759  }
5760
5761  MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5762  MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5763  MF->insert(It, loopMBB);
5764  MF->insert(It, exitMBB);
5765
5766  // Transfer the remainder of BB and its successor edges to exitMBB.
5767  exitMBB->splice(exitMBB->begin(), BB,
5768                  llvm::next(MachineBasicBlock::iterator(MI)),
5769                  BB->end());
5770  exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5771
5772  const TargetRegisterClass *TRC = isThumb2 ?
5773    (const TargetRegisterClass*)&ARM::rGPRRegClass :
5774    (const TargetRegisterClass*)&ARM::GPRRegClass;
5775  unsigned scratch = MRI.createVirtualRegister(TRC);
5776  unsigned scratch2 = (!BinOpcode) ? incr : MRI.createVirtualRegister(TRC);
5777
5778  //  thisMBB:
5779  //   ...
5780  //   fallthrough --> loopMBB
5781  BB->addSuccessor(loopMBB);
5782
5783  //  loopMBB:
5784  //   ldrex dest, ptr
5785  //   <binop> scratch2, dest, incr
5786  //   strex scratch, scratch2, ptr
5787  //   cmp scratch, #0
5788  //   bne- loopMBB
5789  //   fallthrough --> exitMBB
5790  BB = loopMBB;
5791  MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5792  if (ldrOpc == ARM::t2LDREX)
5793    MIB.addImm(0);
5794  AddDefaultPred(MIB);
5795  if (BinOpcode) {
5796    // operand order needs to go the other way for NAND
5797    if (BinOpcode == ARM::BICrr || BinOpcode == ARM::t2BICrr)
5798      AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
5799                     addReg(incr).addReg(dest)).addReg(0);
5800    else
5801      AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
5802                     addReg(dest).addReg(incr)).addReg(0);
5803  }
5804
5805  MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
5806  if (strOpc == ARM::t2STREX)
5807    MIB.addImm(0);
5808  AddDefaultPred(MIB);
5809  AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5810                 .addReg(scratch).addImm(0));
5811  BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5812    .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5813
5814  BB->addSuccessor(loopMBB);
5815  BB->addSuccessor(exitMBB);
5816
5817  //  exitMBB:
5818  //   ...
5819  BB = exitMBB;
5820
5821  MI->eraseFromParent();   // The instruction is gone now.
5822
5823  return BB;
5824}
5825
5826MachineBasicBlock *
5827ARMTargetLowering::EmitAtomicBinaryMinMax(MachineInstr *MI,
5828                                          MachineBasicBlock *BB,
5829                                          unsigned Size,
5830                                          bool signExtend,
5831                                          ARMCC::CondCodes Cond) const {
5832  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5833
5834  const BasicBlock *LLVM_BB = BB->getBasicBlock();
5835  MachineFunction *MF = BB->getParent();
5836  MachineFunction::iterator It = BB;
5837  ++It;
5838
5839  unsigned dest = MI->getOperand(0).getReg();
5840  unsigned ptr = MI->getOperand(1).getReg();
5841  unsigned incr = MI->getOperand(2).getReg();
5842  unsigned oldval = dest;
5843  DebugLoc dl = MI->getDebugLoc();
5844  bool isThumb2 = Subtarget->isThumb2();
5845
5846  MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5847  if (isThumb2) {
5848    MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
5849    MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
5850  }
5851
5852  unsigned ldrOpc, strOpc, extendOpc;
5853  switch (Size) {
5854  default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5855  case 1:
5856    ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5857    strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5858    extendOpc = isThumb2 ? ARM::t2SXTB : ARM::SXTB;
5859    break;
5860  case 2:
5861    ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5862    strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5863    extendOpc = isThumb2 ? ARM::t2SXTH : ARM::SXTH;
5864    break;
5865  case 4:
5866    ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5867    strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5868    extendOpc = 0;
5869    break;
5870  }
5871
5872  MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5873  MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5874  MF->insert(It, loopMBB);
5875  MF->insert(It, exitMBB);
5876
5877  // Transfer the remainder of BB and its successor edges to exitMBB.
5878  exitMBB->splice(exitMBB->begin(), BB,
5879                  llvm::next(MachineBasicBlock::iterator(MI)),
5880                  BB->end());
5881  exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5882
5883  const TargetRegisterClass *TRC = isThumb2 ?
5884    (const TargetRegisterClass*)&ARM::rGPRRegClass :
5885    (const TargetRegisterClass*)&ARM::GPRRegClass;
5886  unsigned scratch = MRI.createVirtualRegister(TRC);
5887  unsigned scratch2 = MRI.createVirtualRegister(TRC);
5888
5889  //  thisMBB:
5890  //   ...
5891  //   fallthrough --> loopMBB
5892  BB->addSuccessor(loopMBB);
5893
5894  //  loopMBB:
5895  //   ldrex dest, ptr
5896  //   (sign extend dest, if required)
5897  //   cmp dest, incr
5898  //   cmov.cond scratch2, incr, dest
5899  //   strex scratch, scratch2, ptr
5900  //   cmp scratch, #0
5901  //   bne- loopMBB
5902  //   fallthrough --> exitMBB
5903  BB = loopMBB;
5904  MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5905  if (ldrOpc == ARM::t2LDREX)
5906    MIB.addImm(0);
5907  AddDefaultPred(MIB);
5908
5909  // Sign extend the value, if necessary.
5910  if (signExtend && extendOpc) {
5911    oldval = MRI.createVirtualRegister(&ARM::GPRRegClass);
5912    AddDefaultPred(BuildMI(BB, dl, TII->get(extendOpc), oldval)
5913                     .addReg(dest)
5914                     .addImm(0));
5915  }
5916
5917  // Build compare and cmov instructions.
5918  AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
5919                 .addReg(oldval).addReg(incr));
5920  BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2MOVCCr : ARM::MOVCCr), scratch2)
5921         .addReg(incr).addReg(oldval).addImm(Cond).addReg(ARM::CPSR);
5922
5923  MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
5924  if (strOpc == ARM::t2STREX)
5925    MIB.addImm(0);
5926  AddDefaultPred(MIB);
5927  AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5928                 .addReg(scratch).addImm(0));
5929  BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5930    .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5931
5932  BB->addSuccessor(loopMBB);
5933  BB->addSuccessor(exitMBB);
5934
5935  //  exitMBB:
5936  //   ...
5937  BB = exitMBB;
5938
5939  MI->eraseFromParent();   // The instruction is gone now.
5940
5941  return BB;
5942}
5943
5944MachineBasicBlock *
5945ARMTargetLowering::EmitAtomicBinary64(MachineInstr *MI, MachineBasicBlock *BB,
5946                                      unsigned Op1, unsigned Op2,
5947                                      bool NeedsCarry, bool IsCmpxchg,
5948                                      bool IsMinMax, ARMCC::CondCodes CC) const {
5949  // This also handles ATOMIC_SWAP, indicated by Op1==0.
5950  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5951
5952  const BasicBlock *LLVM_BB = BB->getBasicBlock();
5953  MachineFunction *MF = BB->getParent();
5954  MachineFunction::iterator It = BB;
5955  ++It;
5956
5957  unsigned destlo = MI->getOperand(0).getReg();
5958  unsigned desthi = MI->getOperand(1).getReg();
5959  unsigned ptr = MI->getOperand(2).getReg();
5960  unsigned vallo = MI->getOperand(3).getReg();
5961  unsigned valhi = MI->getOperand(4).getReg();
5962  DebugLoc dl = MI->getDebugLoc();
5963  bool isThumb2 = Subtarget->isThumb2();
5964
5965  MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5966  if (isThumb2) {
5967    MRI.constrainRegClass(destlo, &ARM::rGPRRegClass);
5968    MRI.constrainRegClass(desthi, &ARM::rGPRRegClass);
5969    MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
5970  }
5971
5972  unsigned ldrOpc = isThumb2 ? ARM::t2LDREXD : ARM::LDREXD;
5973  unsigned strOpc = isThumb2 ? ARM::t2STREXD : ARM::STREXD;
5974
5975  MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5976  MachineBasicBlock *contBB = 0, *cont2BB = 0;
5977  if (IsCmpxchg || IsMinMax)
5978    contBB = MF->CreateMachineBasicBlock(LLVM_BB);
5979  if (IsCmpxchg)
5980    cont2BB = MF->CreateMachineBasicBlock(LLVM_BB);
5981  MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5982
5983  MF->insert(It, loopMBB);
5984  if (IsCmpxchg || IsMinMax) MF->insert(It, contBB);
5985  if (IsCmpxchg) MF->insert(It, cont2BB);
5986  MF->insert(It, exitMBB);
5987
5988  // Transfer the remainder of BB and its successor edges to exitMBB.
5989  exitMBB->splice(exitMBB->begin(), BB,
5990                  llvm::next(MachineBasicBlock::iterator(MI)),
5991                  BB->end());
5992  exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5993
5994  const TargetRegisterClass *TRC = isThumb2 ?
5995    (const TargetRegisterClass*)&ARM::tGPRRegClass :
5996    (const TargetRegisterClass*)&ARM::GPRRegClass;
5997  unsigned storesuccess = MRI.createVirtualRegister(TRC);
5998
5999  //  thisMBB:
6000  //   ...
6001  //   fallthrough --> loopMBB
6002  BB->addSuccessor(loopMBB);
6003
6004  //  loopMBB:
6005  //   ldrexd r2, r3, ptr
6006  //   <binopa> r0, r2, incr
6007  //   <binopb> r1, r3, incr
6008  //   strexd storesuccess, r0, r1, ptr
6009  //   cmp storesuccess, #0
6010  //   bne- loopMBB
6011  //   fallthrough --> exitMBB
6012  //
6013  // Note that the registers are explicitly specified because there is not any
6014  // way to force the register allocator to allocate a register pair.
6015  //
6016  // FIXME: The hardcoded registers are not necessary for Thumb2, but we
6017  // need to properly enforce the restriction that the two output registers
6018  // for ldrexd must be different.
6019  BB = loopMBB;
6020  // Load
6021  unsigned GPRPair0 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6022  unsigned GPRPair1 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6023  unsigned GPRPair2;
6024  if (IsMinMax) {
6025    //We need an extra double register for doing min/max.
6026    unsigned undef = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6027    unsigned r1 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6028    GPRPair2 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6029    BuildMI(BB, dl, TII->get(TargetOpcode::IMPLICIT_DEF), undef);
6030    BuildMI(BB, dl, TII->get(TargetOpcode::INSERT_SUBREG), r1)
6031      .addReg(undef)
6032      .addReg(vallo)
6033      .addImm(ARM::gsub_0);
6034    BuildMI(BB, dl, TII->get(TargetOpcode::INSERT_SUBREG), GPRPair2)
6035      .addReg(r1)
6036      .addReg(valhi)
6037      .addImm(ARM::gsub_1);
6038  }
6039
6040  AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc))
6041                 .addReg(GPRPair0, RegState::Define).addReg(ptr));
6042  // Copy r2/r3 into dest.  (This copy will normally be coalesced.)
6043  BuildMI(BB, dl, TII->get(TargetOpcode::COPY), destlo)
6044    .addReg(GPRPair0, 0, ARM::gsub_0);
6045  BuildMI(BB, dl, TII->get(TargetOpcode::COPY), desthi)
6046    .addReg(GPRPair0, 0, ARM::gsub_1);
6047
6048  if (IsCmpxchg) {
6049    // Add early exit
6050    for (unsigned i = 0; i < 2; i++) {
6051      AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr :
6052                                                         ARM::CMPrr))
6053                     .addReg(i == 0 ? destlo : desthi)
6054                     .addReg(i == 0 ? vallo : valhi));
6055      BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6056        .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6057      BB->addSuccessor(exitMBB);
6058      BB->addSuccessor(i == 0 ? contBB : cont2BB);
6059      BB = (i == 0 ? contBB : cont2BB);
6060    }
6061
6062    // Copy to physregs for strexd
6063    unsigned setlo = MI->getOperand(5).getReg();
6064    unsigned sethi = MI->getOperand(6).getReg();
6065    unsigned undef = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6066    unsigned r1 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6067    BuildMI(BB, dl, TII->get(TargetOpcode::IMPLICIT_DEF), undef);
6068    BuildMI(BB, dl, TII->get(TargetOpcode::INSERT_SUBREG), r1)
6069      .addReg(undef)
6070      .addReg(setlo)
6071      .addImm(ARM::gsub_0);
6072    BuildMI(BB, dl, TII->get(TargetOpcode::INSERT_SUBREG), GPRPair1)
6073      .addReg(r1)
6074      .addReg(sethi)
6075      .addImm(ARM::gsub_1);
6076  } else if (Op1) {
6077    // Perform binary operation
6078    unsigned tmpRegLo = MRI.createVirtualRegister(TRC);
6079    AddDefaultPred(BuildMI(BB, dl, TII->get(Op1), tmpRegLo)
6080                   .addReg(destlo).addReg(vallo))
6081        .addReg(NeedsCarry ? ARM::CPSR : 0, getDefRegState(NeedsCarry));
6082    unsigned tmpRegHi = MRI.createVirtualRegister(TRC);
6083    AddDefaultPred(BuildMI(BB, dl, TII->get(Op2), tmpRegHi)
6084                   .addReg(desthi).addReg(valhi))
6085        .addReg(IsMinMax ? ARM::CPSR : 0, getDefRegState(IsMinMax));
6086
6087    unsigned UndefPair = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6088    BuildMI(BB, dl, TII->get(TargetOpcode::IMPLICIT_DEF), UndefPair);
6089    unsigned r1 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6090    BuildMI(BB, dl, TII->get(TargetOpcode::INSERT_SUBREG), r1)
6091      .addReg(UndefPair)
6092      .addReg(tmpRegLo)
6093      .addImm(ARM::gsub_0);
6094    BuildMI(BB, dl, TII->get(TargetOpcode::INSERT_SUBREG), GPRPair1)
6095      .addReg(r1)
6096      .addReg(tmpRegHi)
6097      .addImm(ARM::gsub_1);
6098  } else {
6099    // Copy to physregs for strexd
6100    unsigned UndefPair = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6101    unsigned r1 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6102    BuildMI(BB, dl, TII->get(TargetOpcode::IMPLICIT_DEF), UndefPair);
6103    BuildMI(BB, dl, TII->get(TargetOpcode::INSERT_SUBREG), r1)
6104      .addReg(UndefPair)
6105      .addReg(vallo)
6106      .addImm(ARM::gsub_0);
6107    BuildMI(BB, dl, TII->get(TargetOpcode::INSERT_SUBREG), GPRPair1)
6108      .addReg(r1)
6109      .addReg(valhi)
6110      .addImm(ARM::gsub_1);
6111  }
6112  unsigned GPRPairStore = GPRPair1;
6113  if (IsMinMax) {
6114    // Compare and branch to exit block.
6115    BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6116      .addMBB(exitMBB).addImm(CC).addReg(ARM::CPSR);
6117    BB->addSuccessor(exitMBB);
6118    BB->addSuccessor(contBB);
6119    BB = contBB;
6120    GPRPairStore = GPRPair2;
6121  }
6122
6123  // Store
6124  AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), storesuccess)
6125                 .addReg(GPRPairStore).addReg(ptr));
6126  // Cmp+jump
6127  AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6128                 .addReg(storesuccess).addImm(0));
6129  BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6130    .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6131
6132  BB->addSuccessor(loopMBB);
6133  BB->addSuccessor(exitMBB);
6134
6135  //  exitMBB:
6136  //   ...
6137  BB = exitMBB;
6138
6139  MI->eraseFromParent();   // The instruction is gone now.
6140
6141  return BB;
6142}
6143
6144/// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6145/// registers the function context.
6146void ARMTargetLowering::
6147SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6148                       MachineBasicBlock *DispatchBB, int FI) const {
6149  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6150  DebugLoc dl = MI->getDebugLoc();
6151  MachineFunction *MF = MBB->getParent();
6152  MachineRegisterInfo *MRI = &MF->getRegInfo();
6153  MachineConstantPool *MCP = MF->getConstantPool();
6154  ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6155  const Function *F = MF->getFunction();
6156
6157  bool isThumb = Subtarget->isThumb();
6158  bool isThumb2 = Subtarget->isThumb2();
6159
6160  unsigned PCLabelId = AFI->createPICLabelUId();
6161  unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6162  ARMConstantPoolValue *CPV =
6163    ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6164  unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6165
6166  const TargetRegisterClass *TRC = isThumb ?
6167    (const TargetRegisterClass*)&ARM::tGPRRegClass :
6168    (const TargetRegisterClass*)&ARM::GPRRegClass;
6169
6170  // Grab constant pool and fixed stack memory operands.
6171  MachineMemOperand *CPMMO =
6172    MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6173                             MachineMemOperand::MOLoad, 4, 4);
6174
6175  MachineMemOperand *FIMMOSt =
6176    MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6177                             MachineMemOperand::MOStore, 4, 4);
6178
6179  // Load the address of the dispatch MBB into the jump buffer.
6180  if (isThumb2) {
6181    // Incoming value: jbuf
6182    //   ldr.n  r5, LCPI1_1
6183    //   orr    r5, r5, #1
6184    //   add    r5, pc
6185    //   str    r5, [$jbuf, #+4] ; &jbuf[1]
6186    unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6187    AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6188                   .addConstantPoolIndex(CPI)
6189                   .addMemOperand(CPMMO));
6190    // Set the low bit because of thumb mode.
6191    unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6192    AddDefaultCC(
6193      AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6194                     .addReg(NewVReg1, RegState::Kill)
6195                     .addImm(0x01)));
6196    unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6197    BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6198      .addReg(NewVReg2, RegState::Kill)
6199      .addImm(PCLabelId);
6200    AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6201                   .addReg(NewVReg3, RegState::Kill)
6202                   .addFrameIndex(FI)
6203                   .addImm(36)  // &jbuf[1] :: pc
6204                   .addMemOperand(FIMMOSt));
6205  } else if (isThumb) {
6206    // Incoming value: jbuf
6207    //   ldr.n  r1, LCPI1_4
6208    //   add    r1, pc
6209    //   mov    r2, #1
6210    //   orrs   r1, r2
6211    //   add    r2, $jbuf, #+4 ; &jbuf[1]
6212    //   str    r1, [r2]
6213    unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6214    AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6215                   .addConstantPoolIndex(CPI)
6216                   .addMemOperand(CPMMO));
6217    unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6218    BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6219      .addReg(NewVReg1, RegState::Kill)
6220      .addImm(PCLabelId);
6221    // Set the low bit because of thumb mode.
6222    unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6223    AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6224                   .addReg(ARM::CPSR, RegState::Define)
6225                   .addImm(1));
6226    unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6227    AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6228                   .addReg(ARM::CPSR, RegState::Define)
6229                   .addReg(NewVReg2, RegState::Kill)
6230                   .addReg(NewVReg3, RegState::Kill));
6231    unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6232    AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tADDrSPi), NewVReg5)
6233                   .addFrameIndex(FI)
6234                   .addImm(36)); // &jbuf[1] :: pc
6235    AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6236                   .addReg(NewVReg4, RegState::Kill)
6237                   .addReg(NewVReg5, RegState::Kill)
6238                   .addImm(0)
6239                   .addMemOperand(FIMMOSt));
6240  } else {
6241    // Incoming value: jbuf
6242    //   ldr  r1, LCPI1_1
6243    //   add  r1, pc, r1
6244    //   str  r1, [$jbuf, #+4] ; &jbuf[1]
6245    unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6246    AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12),  NewVReg1)
6247                   .addConstantPoolIndex(CPI)
6248                   .addImm(0)
6249                   .addMemOperand(CPMMO));
6250    unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6251    AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6252                   .addReg(NewVReg1, RegState::Kill)
6253                   .addImm(PCLabelId));
6254    AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6255                   .addReg(NewVReg2, RegState::Kill)
6256                   .addFrameIndex(FI)
6257                   .addImm(36)  // &jbuf[1] :: pc
6258                   .addMemOperand(FIMMOSt));
6259  }
6260}
6261
6262MachineBasicBlock *ARMTargetLowering::
6263EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
6264  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6265  DebugLoc dl = MI->getDebugLoc();
6266  MachineFunction *MF = MBB->getParent();
6267  MachineRegisterInfo *MRI = &MF->getRegInfo();
6268  ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6269  MachineFrameInfo *MFI = MF->getFrameInfo();
6270  int FI = MFI->getFunctionContextIndex();
6271
6272  const TargetRegisterClass *TRC = Subtarget->isThumb() ?
6273    (const TargetRegisterClass*)&ARM::tGPRRegClass :
6274    (const TargetRegisterClass*)&ARM::GPRnopcRegClass;
6275
6276  // Get a mapping of the call site numbers to all of the landing pads they're
6277  // associated with.
6278  DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6279  unsigned MaxCSNum = 0;
6280  MachineModuleInfo &MMI = MF->getMMI();
6281  for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6282       ++BB) {
6283    if (!BB->isLandingPad()) continue;
6284
6285    // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6286    // pad.
6287    for (MachineBasicBlock::iterator
6288           II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6289      if (!II->isEHLabel()) continue;
6290
6291      MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6292      if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6293
6294      SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6295      for (SmallVectorImpl<unsigned>::iterator
6296             CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6297           CSI != CSE; ++CSI) {
6298        CallSiteNumToLPad[*CSI].push_back(BB);
6299        MaxCSNum = std::max(MaxCSNum, *CSI);
6300      }
6301      break;
6302    }
6303  }
6304
6305  // Get an ordered list of the machine basic blocks for the jump table.
6306  std::vector<MachineBasicBlock*> LPadList;
6307  SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6308  LPadList.reserve(CallSiteNumToLPad.size());
6309  for (unsigned I = 1; I <= MaxCSNum; ++I) {
6310    SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6311    for (SmallVectorImpl<MachineBasicBlock*>::iterator
6312           II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6313      LPadList.push_back(*II);
6314      InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6315    }
6316  }
6317
6318  assert(!LPadList.empty() &&
6319         "No landing pad destinations for the dispatch jump table!");
6320
6321  // Create the jump table and associated information.
6322  MachineJumpTableInfo *JTI =
6323    MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6324  unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6325  unsigned UId = AFI->createJumpTableUId();
6326
6327  // Create the MBBs for the dispatch code.
6328
6329  // Shove the dispatch's address into the return slot in the function context.
6330  MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6331  DispatchBB->setIsLandingPad();
6332
6333  MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6334  BuildMI(TrapBB, dl, TII->get(Subtarget->isThumb() ? ARM::tTRAP : ARM::TRAP));
6335  DispatchBB->addSuccessor(TrapBB);
6336
6337  MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6338  DispatchBB->addSuccessor(DispContBB);
6339
6340  // Insert and MBBs.
6341  MF->insert(MF->end(), DispatchBB);
6342  MF->insert(MF->end(), DispContBB);
6343  MF->insert(MF->end(), TrapBB);
6344
6345  // Insert code into the entry block that creates and registers the function
6346  // context.
6347  SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6348
6349  MachineMemOperand *FIMMOLd =
6350    MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6351                             MachineMemOperand::MOLoad |
6352                             MachineMemOperand::MOVolatile, 4, 4);
6353
6354  MachineInstrBuilder MIB;
6355  MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6356
6357  const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6358  const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6359
6360  // Add a register mask with no preserved registers.  This results in all
6361  // registers being marked as clobbered.
6362  MIB.addRegMask(RI.getNoPreservedMask());
6363
6364  unsigned NumLPads = LPadList.size();
6365  if (Subtarget->isThumb2()) {
6366    unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6367    AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6368                   .addFrameIndex(FI)
6369                   .addImm(4)
6370                   .addMemOperand(FIMMOLd));
6371
6372    if (NumLPads < 256) {
6373      AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6374                     .addReg(NewVReg1)
6375                     .addImm(LPadList.size()));
6376    } else {
6377      unsigned VReg1 = MRI->createVirtualRegister(TRC);
6378      AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6379                     .addImm(NumLPads & 0xFFFF));
6380
6381      unsigned VReg2 = VReg1;
6382      if ((NumLPads & 0xFFFF0000) != 0) {
6383        VReg2 = MRI->createVirtualRegister(TRC);
6384        AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6385                       .addReg(VReg1)
6386                       .addImm(NumLPads >> 16));
6387      }
6388
6389      AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6390                     .addReg(NewVReg1)
6391                     .addReg(VReg2));
6392    }
6393
6394    BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6395      .addMBB(TrapBB)
6396      .addImm(ARMCC::HI)
6397      .addReg(ARM::CPSR);
6398
6399    unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6400    AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6401                   .addJumpTableIndex(MJTI)
6402                   .addImm(UId));
6403
6404    unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6405    AddDefaultCC(
6406      AddDefaultPred(
6407        BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6408        .addReg(NewVReg3, RegState::Kill)
6409        .addReg(NewVReg1)
6410        .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6411
6412    BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6413      .addReg(NewVReg4, RegState::Kill)
6414      .addReg(NewVReg1)
6415      .addJumpTableIndex(MJTI)
6416      .addImm(UId);
6417  } else if (Subtarget->isThumb()) {
6418    unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6419    AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6420                   .addFrameIndex(FI)
6421                   .addImm(1)
6422                   .addMemOperand(FIMMOLd));
6423
6424    if (NumLPads < 256) {
6425      AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6426                     .addReg(NewVReg1)
6427                     .addImm(NumLPads));
6428    } else {
6429      MachineConstantPool *ConstantPool = MF->getConstantPool();
6430      Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6431      const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6432
6433      // MachineConstantPool wants an explicit alignment.
6434      unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6435      if (Align == 0)
6436        Align = getDataLayout()->getTypeAllocSize(C->getType());
6437      unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6438
6439      unsigned VReg1 = MRI->createVirtualRegister(TRC);
6440      AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6441                     .addReg(VReg1, RegState::Define)
6442                     .addConstantPoolIndex(Idx));
6443      AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
6444                     .addReg(NewVReg1)
6445                     .addReg(VReg1));
6446    }
6447
6448    BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
6449      .addMBB(TrapBB)
6450      .addImm(ARMCC::HI)
6451      .addReg(ARM::CPSR);
6452
6453    unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6454    AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
6455                   .addReg(ARM::CPSR, RegState::Define)
6456                   .addReg(NewVReg1)
6457                   .addImm(2));
6458
6459    unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6460    AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
6461                   .addJumpTableIndex(MJTI)
6462                   .addImm(UId));
6463
6464    unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6465    AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
6466                   .addReg(ARM::CPSR, RegState::Define)
6467                   .addReg(NewVReg2, RegState::Kill)
6468                   .addReg(NewVReg3));
6469
6470    MachineMemOperand *JTMMOLd =
6471      MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6472                               MachineMemOperand::MOLoad, 4, 4);
6473
6474    unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6475    AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
6476                   .addReg(NewVReg4, RegState::Kill)
6477                   .addImm(0)
6478                   .addMemOperand(JTMMOLd));
6479
6480    unsigned NewVReg6 = MRI->createVirtualRegister(TRC);
6481    AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
6482                   .addReg(ARM::CPSR, RegState::Define)
6483                   .addReg(NewVReg5, RegState::Kill)
6484                   .addReg(NewVReg3));
6485
6486    BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
6487      .addReg(NewVReg6, RegState::Kill)
6488      .addJumpTableIndex(MJTI)
6489      .addImm(UId);
6490  } else {
6491    unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6492    AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
6493                   .addFrameIndex(FI)
6494                   .addImm(4)
6495                   .addMemOperand(FIMMOLd));
6496
6497    if (NumLPads < 256) {
6498      AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
6499                     .addReg(NewVReg1)
6500                     .addImm(NumLPads));
6501    } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
6502      unsigned VReg1 = MRI->createVirtualRegister(TRC);
6503      AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
6504                     .addImm(NumLPads & 0xFFFF));
6505
6506      unsigned VReg2 = VReg1;
6507      if ((NumLPads & 0xFFFF0000) != 0) {
6508        VReg2 = MRI->createVirtualRegister(TRC);
6509        AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
6510                       .addReg(VReg1)
6511                       .addImm(NumLPads >> 16));
6512      }
6513
6514      AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6515                     .addReg(NewVReg1)
6516                     .addReg(VReg2));
6517    } else {
6518      MachineConstantPool *ConstantPool = MF->getConstantPool();
6519      Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6520      const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6521
6522      // MachineConstantPool wants an explicit alignment.
6523      unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6524      if (Align == 0)
6525        Align = getDataLayout()->getTypeAllocSize(C->getType());
6526      unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6527
6528      unsigned VReg1 = MRI->createVirtualRegister(TRC);
6529      AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
6530                     .addReg(VReg1, RegState::Define)
6531                     .addConstantPoolIndex(Idx)
6532                     .addImm(0));
6533      AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6534                     .addReg(NewVReg1)
6535                     .addReg(VReg1, RegState::Kill));
6536    }
6537
6538    BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
6539      .addMBB(TrapBB)
6540      .addImm(ARMCC::HI)
6541      .addReg(ARM::CPSR);
6542
6543    unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6544    AddDefaultCC(
6545      AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
6546                     .addReg(NewVReg1)
6547                     .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6548    unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6549    AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
6550                   .addJumpTableIndex(MJTI)
6551                   .addImm(UId));
6552
6553    MachineMemOperand *JTMMOLd =
6554      MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6555                               MachineMemOperand::MOLoad, 4, 4);
6556    unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6557    AddDefaultPred(
6558      BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
6559      .addReg(NewVReg3, RegState::Kill)
6560      .addReg(NewVReg4)
6561      .addImm(0)
6562      .addMemOperand(JTMMOLd));
6563
6564    BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
6565      .addReg(NewVReg5, RegState::Kill)
6566      .addReg(NewVReg4)
6567      .addJumpTableIndex(MJTI)
6568      .addImm(UId);
6569  }
6570
6571  // Add the jump table entries as successors to the MBB.
6572  SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
6573  for (std::vector<MachineBasicBlock*>::iterator
6574         I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
6575    MachineBasicBlock *CurMBB = *I;
6576    if (SeenMBBs.insert(CurMBB))
6577      DispContBB->addSuccessor(CurMBB);
6578  }
6579
6580  // N.B. the order the invoke BBs are processed in doesn't matter here.
6581  const uint16_t *SavedRegs = RI.getCalleeSavedRegs(MF);
6582  SmallVector<MachineBasicBlock*, 64> MBBLPads;
6583  for (SmallPtrSet<MachineBasicBlock*, 64>::iterator
6584         I = InvokeBBs.begin(), E = InvokeBBs.end(); I != E; ++I) {
6585    MachineBasicBlock *BB = *I;
6586
6587    // Remove the landing pad successor from the invoke block and replace it
6588    // with the new dispatch block.
6589    SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
6590                                                  BB->succ_end());
6591    while (!Successors.empty()) {
6592      MachineBasicBlock *SMBB = Successors.pop_back_val();
6593      if (SMBB->isLandingPad()) {
6594        BB->removeSuccessor(SMBB);
6595        MBBLPads.push_back(SMBB);
6596      }
6597    }
6598
6599    BB->addSuccessor(DispatchBB);
6600
6601    // Find the invoke call and mark all of the callee-saved registers as
6602    // 'implicit defined' so that they're spilled. This prevents code from
6603    // moving instructions to before the EH block, where they will never be
6604    // executed.
6605    for (MachineBasicBlock::reverse_iterator
6606           II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
6607      if (!II->isCall()) continue;
6608
6609      DenseMap<unsigned, bool> DefRegs;
6610      for (MachineInstr::mop_iterator
6611             OI = II->operands_begin(), OE = II->operands_end();
6612           OI != OE; ++OI) {
6613        if (!OI->isReg()) continue;
6614        DefRegs[OI->getReg()] = true;
6615      }
6616
6617      MachineInstrBuilder MIB(*MF, &*II);
6618
6619      for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
6620        unsigned Reg = SavedRegs[i];
6621        if (Subtarget->isThumb2() &&
6622            !ARM::tGPRRegClass.contains(Reg) &&
6623            !ARM::hGPRRegClass.contains(Reg))
6624          continue;
6625        if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
6626          continue;
6627        if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
6628          continue;
6629        if (!DefRegs[Reg])
6630          MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
6631      }
6632
6633      break;
6634    }
6635  }
6636
6637  // Mark all former landing pads as non-landing pads. The dispatch is the only
6638  // landing pad now.
6639  for (SmallVectorImpl<MachineBasicBlock*>::iterator
6640         I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
6641    (*I)->setIsLandingPad(false);
6642
6643  // The instruction is gone now.
6644  MI->eraseFromParent();
6645
6646  return MBB;
6647}
6648
6649static
6650MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
6651  for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
6652       E = MBB->succ_end(); I != E; ++I)
6653    if (*I != Succ)
6654      return *I;
6655  llvm_unreachable("Expecting a BB with two successors!");
6656}
6657
6658MachineBasicBlock *ARMTargetLowering::
6659EmitStructByval(MachineInstr *MI, MachineBasicBlock *BB) const {
6660  // This pseudo instruction has 3 operands: dst, src, size
6661  // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
6662  // Otherwise, we will generate unrolled scalar copies.
6663  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6664  const BasicBlock *LLVM_BB = BB->getBasicBlock();
6665  MachineFunction::iterator It = BB;
6666  ++It;
6667
6668  unsigned dest = MI->getOperand(0).getReg();
6669  unsigned src = MI->getOperand(1).getReg();
6670  unsigned SizeVal = MI->getOperand(2).getImm();
6671  unsigned Align = MI->getOperand(3).getImm();
6672  DebugLoc dl = MI->getDebugLoc();
6673
6674  bool isThumb2 = Subtarget->isThumb2();
6675  MachineFunction *MF = BB->getParent();
6676  MachineRegisterInfo &MRI = MF->getRegInfo();
6677  unsigned ldrOpc, strOpc, UnitSize = 0;
6678
6679  const TargetRegisterClass *TRC = isThumb2 ?
6680    (const TargetRegisterClass*)&ARM::tGPRRegClass :
6681    (const TargetRegisterClass*)&ARM::GPRRegClass;
6682  const TargetRegisterClass *TRC_Vec = 0;
6683
6684  if (Align & 1) {
6685    ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
6686    strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
6687    UnitSize = 1;
6688  } else if (Align & 2) {
6689    ldrOpc = isThumb2 ? ARM::t2LDRH_POST : ARM::LDRH_POST;
6690    strOpc = isThumb2 ? ARM::t2STRH_POST : ARM::STRH_POST;
6691    UnitSize = 2;
6692  } else {
6693    // Check whether we can use NEON instructions.
6694    if (!MF->getFunction()->getAttributes().
6695          hasAttribute(AttributeSet::FunctionIndex,
6696                       Attribute::NoImplicitFloat) &&
6697        Subtarget->hasNEON()) {
6698      if ((Align % 16 == 0) && SizeVal >= 16) {
6699        ldrOpc = ARM::VLD1q32wb_fixed;
6700        strOpc = ARM::VST1q32wb_fixed;
6701        UnitSize = 16;
6702        TRC_Vec = (const TargetRegisterClass*)&ARM::DPairRegClass;
6703      }
6704      else if ((Align % 8 == 0) && SizeVal >= 8) {
6705        ldrOpc = ARM::VLD1d32wb_fixed;
6706        strOpc = ARM::VST1d32wb_fixed;
6707        UnitSize = 8;
6708        TRC_Vec = (const TargetRegisterClass*)&ARM::DPRRegClass;
6709      }
6710    }
6711    // Can't use NEON instructions.
6712    if (UnitSize == 0) {
6713      ldrOpc = isThumb2 ? ARM::t2LDR_POST : ARM::LDR_POST_IMM;
6714      strOpc = isThumb2 ? ARM::t2STR_POST : ARM::STR_POST_IMM;
6715      UnitSize = 4;
6716    }
6717  }
6718
6719  unsigned BytesLeft = SizeVal % UnitSize;
6720  unsigned LoopSize = SizeVal - BytesLeft;
6721
6722  if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
6723    // Use LDR and STR to copy.
6724    // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
6725    // [destOut] = STR_POST(scratch, destIn, UnitSize)
6726    unsigned srcIn = src;
6727    unsigned destIn = dest;
6728    for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
6729      unsigned scratch = MRI.createVirtualRegister(UnitSize >= 8 ? TRC_Vec:TRC);
6730      unsigned srcOut = MRI.createVirtualRegister(TRC);
6731      unsigned destOut = MRI.createVirtualRegister(TRC);
6732      if (UnitSize >= 8) {
6733        AddDefaultPred(BuildMI(*BB, MI, dl,
6734          TII->get(ldrOpc), scratch)
6735          .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(0));
6736
6737        AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6738          .addReg(destIn).addImm(0).addReg(scratch));
6739      } else if (isThumb2) {
6740        AddDefaultPred(BuildMI(*BB, MI, dl,
6741          TII->get(ldrOpc), scratch)
6742          .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(UnitSize));
6743
6744        AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6745          .addReg(scratch).addReg(destIn)
6746          .addImm(UnitSize));
6747      } else {
6748        AddDefaultPred(BuildMI(*BB, MI, dl,
6749          TII->get(ldrOpc), scratch)
6750          .addReg(srcOut, RegState::Define).addReg(srcIn).addReg(0)
6751          .addImm(UnitSize));
6752
6753        AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6754          .addReg(scratch).addReg(destIn)
6755          .addReg(0).addImm(UnitSize));
6756      }
6757      srcIn = srcOut;
6758      destIn = destOut;
6759    }
6760
6761    // Handle the leftover bytes with LDRB and STRB.
6762    // [scratch, srcOut] = LDRB_POST(srcIn, 1)
6763    // [destOut] = STRB_POST(scratch, destIn, 1)
6764    ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
6765    strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
6766    for (unsigned i = 0; i < BytesLeft; i++) {
6767      unsigned scratch = MRI.createVirtualRegister(TRC);
6768      unsigned srcOut = MRI.createVirtualRegister(TRC);
6769      unsigned destOut = MRI.createVirtualRegister(TRC);
6770      if (isThumb2) {
6771        AddDefaultPred(BuildMI(*BB, MI, dl,
6772          TII->get(ldrOpc),scratch)
6773          .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(1));
6774
6775        AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6776          .addReg(scratch).addReg(destIn)
6777          .addReg(0).addImm(1));
6778      } else {
6779        AddDefaultPred(BuildMI(*BB, MI, dl,
6780          TII->get(ldrOpc),scratch)
6781          .addReg(srcOut, RegState::Define).addReg(srcIn)
6782          .addReg(0).addImm(1));
6783
6784        AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6785          .addReg(scratch).addReg(destIn)
6786          .addReg(0).addImm(1));
6787      }
6788      srcIn = srcOut;
6789      destIn = destOut;
6790    }
6791    MI->eraseFromParent();   // The instruction is gone now.
6792    return BB;
6793  }
6794
6795  // Expand the pseudo op to a loop.
6796  // thisMBB:
6797  //   ...
6798  //   movw varEnd, # --> with thumb2
6799  //   movt varEnd, #
6800  //   ldrcp varEnd, idx --> without thumb2
6801  //   fallthrough --> loopMBB
6802  // loopMBB:
6803  //   PHI varPhi, varEnd, varLoop
6804  //   PHI srcPhi, src, srcLoop
6805  //   PHI destPhi, dst, destLoop
6806  //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
6807  //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
6808  //   subs varLoop, varPhi, #UnitSize
6809  //   bne loopMBB
6810  //   fallthrough --> exitMBB
6811  // exitMBB:
6812  //   epilogue to handle left-over bytes
6813  //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
6814  //   [destOut] = STRB_POST(scratch, destLoop, 1)
6815  MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6816  MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6817  MF->insert(It, loopMBB);
6818  MF->insert(It, exitMBB);
6819
6820  // Transfer the remainder of BB and its successor edges to exitMBB.
6821  exitMBB->splice(exitMBB->begin(), BB,
6822                  llvm::next(MachineBasicBlock::iterator(MI)),
6823                  BB->end());
6824  exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6825
6826  // Load an immediate to varEnd.
6827  unsigned varEnd = MRI.createVirtualRegister(TRC);
6828  if (isThumb2) {
6829    unsigned VReg1 = varEnd;
6830    if ((LoopSize & 0xFFFF0000) != 0)
6831      VReg1 = MRI.createVirtualRegister(TRC);
6832    AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVi16), VReg1)
6833                   .addImm(LoopSize & 0xFFFF));
6834
6835    if ((LoopSize & 0xFFFF0000) != 0)
6836      AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVTi16), varEnd)
6837                     .addReg(VReg1)
6838                     .addImm(LoopSize >> 16));
6839  } else {
6840    MachineConstantPool *ConstantPool = MF->getConstantPool();
6841    Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6842    const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
6843
6844    // MachineConstantPool wants an explicit alignment.
6845    unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6846    if (Align == 0)
6847      Align = getDataLayout()->getTypeAllocSize(C->getType());
6848    unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6849
6850    AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::LDRcp))
6851                   .addReg(varEnd, RegState::Define)
6852                   .addConstantPoolIndex(Idx)
6853                   .addImm(0));
6854  }
6855  BB->addSuccessor(loopMBB);
6856
6857  // Generate the loop body:
6858  //   varPhi = PHI(varLoop, varEnd)
6859  //   srcPhi = PHI(srcLoop, src)
6860  //   destPhi = PHI(destLoop, dst)
6861  MachineBasicBlock *entryBB = BB;
6862  BB = loopMBB;
6863  unsigned varLoop = MRI.createVirtualRegister(TRC);
6864  unsigned varPhi = MRI.createVirtualRegister(TRC);
6865  unsigned srcLoop = MRI.createVirtualRegister(TRC);
6866  unsigned srcPhi = MRI.createVirtualRegister(TRC);
6867  unsigned destLoop = MRI.createVirtualRegister(TRC);
6868  unsigned destPhi = MRI.createVirtualRegister(TRC);
6869
6870  BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
6871    .addReg(varLoop).addMBB(loopMBB)
6872    .addReg(varEnd).addMBB(entryBB);
6873  BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
6874    .addReg(srcLoop).addMBB(loopMBB)
6875    .addReg(src).addMBB(entryBB);
6876  BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
6877    .addReg(destLoop).addMBB(loopMBB)
6878    .addReg(dest).addMBB(entryBB);
6879
6880  //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
6881  //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
6882  unsigned scratch = MRI.createVirtualRegister(UnitSize >= 8 ? TRC_Vec:TRC);
6883  if (UnitSize >= 8) {
6884    AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
6885      .addReg(srcLoop, RegState::Define).addReg(srcPhi).addImm(0));
6886
6887    AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
6888      .addReg(destPhi).addImm(0).addReg(scratch));
6889  } else if (isThumb2) {
6890    AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
6891      .addReg(srcLoop, RegState::Define).addReg(srcPhi).addImm(UnitSize));
6892
6893    AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
6894      .addReg(scratch).addReg(destPhi)
6895      .addImm(UnitSize));
6896  } else {
6897    AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
6898      .addReg(srcLoop, RegState::Define).addReg(srcPhi).addReg(0)
6899      .addImm(UnitSize));
6900
6901    AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
6902      .addReg(scratch).addReg(destPhi)
6903      .addReg(0).addImm(UnitSize));
6904  }
6905
6906  // Decrement loop variable by UnitSize.
6907  MachineInstrBuilder MIB = BuildMI(BB, dl,
6908    TII->get(isThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
6909  AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
6910  MIB->getOperand(5).setReg(ARM::CPSR);
6911  MIB->getOperand(5).setIsDef(true);
6912
6913  BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6914    .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6915
6916  // loopMBB can loop back to loopMBB or fall through to exitMBB.
6917  BB->addSuccessor(loopMBB);
6918  BB->addSuccessor(exitMBB);
6919
6920  // Add epilogue to handle BytesLeft.
6921  BB = exitMBB;
6922  MachineInstr *StartOfExit = exitMBB->begin();
6923  ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
6924  strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
6925
6926  //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
6927  //   [destOut] = STRB_POST(scratch, destLoop, 1)
6928  unsigned srcIn = srcLoop;
6929  unsigned destIn = destLoop;
6930  for (unsigned i = 0; i < BytesLeft; i++) {
6931    unsigned scratch = MRI.createVirtualRegister(TRC);
6932    unsigned srcOut = MRI.createVirtualRegister(TRC);
6933    unsigned destOut = MRI.createVirtualRegister(TRC);
6934    if (isThumb2) {
6935      AddDefaultPred(BuildMI(*BB, StartOfExit, dl,
6936        TII->get(ldrOpc),scratch)
6937        .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(1));
6938
6939      AddDefaultPred(BuildMI(*BB, StartOfExit, dl, TII->get(strOpc), destOut)
6940        .addReg(scratch).addReg(destIn)
6941        .addImm(1));
6942    } else {
6943      AddDefaultPred(BuildMI(*BB, StartOfExit, dl,
6944        TII->get(ldrOpc),scratch)
6945        .addReg(srcOut, RegState::Define).addReg(srcIn).addReg(0).addImm(1));
6946
6947      AddDefaultPred(BuildMI(*BB, StartOfExit, dl, TII->get(strOpc), destOut)
6948        .addReg(scratch).addReg(destIn)
6949        .addReg(0).addImm(1));
6950    }
6951    srcIn = srcOut;
6952    destIn = destOut;
6953  }
6954
6955  MI->eraseFromParent();   // The instruction is gone now.
6956  return BB;
6957}
6958
6959MachineBasicBlock *
6960ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
6961                                               MachineBasicBlock *BB) const {
6962  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6963  DebugLoc dl = MI->getDebugLoc();
6964  bool isThumb2 = Subtarget->isThumb2();
6965  switch (MI->getOpcode()) {
6966  default: {
6967    MI->dump();
6968    llvm_unreachable("Unexpected instr type to insert");
6969  }
6970  // The Thumb2 pre-indexed stores have the same MI operands, they just
6971  // define them differently in the .td files from the isel patterns, so
6972  // they need pseudos.
6973  case ARM::t2STR_preidx:
6974    MI->setDesc(TII->get(ARM::t2STR_PRE));
6975    return BB;
6976  case ARM::t2STRB_preidx:
6977    MI->setDesc(TII->get(ARM::t2STRB_PRE));
6978    return BB;
6979  case ARM::t2STRH_preidx:
6980    MI->setDesc(TII->get(ARM::t2STRH_PRE));
6981    return BB;
6982
6983  case ARM::STRi_preidx:
6984  case ARM::STRBi_preidx: {
6985    unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
6986      ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
6987    // Decode the offset.
6988    unsigned Offset = MI->getOperand(4).getImm();
6989    bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
6990    Offset = ARM_AM::getAM2Offset(Offset);
6991    if (isSub)
6992      Offset = -Offset;
6993
6994    MachineMemOperand *MMO = *MI->memoperands_begin();
6995    BuildMI(*BB, MI, dl, TII->get(NewOpc))
6996      .addOperand(MI->getOperand(0))  // Rn_wb
6997      .addOperand(MI->getOperand(1))  // Rt
6998      .addOperand(MI->getOperand(2))  // Rn
6999      .addImm(Offset)                 // offset (skip GPR==zero_reg)
7000      .addOperand(MI->getOperand(5))  // pred
7001      .addOperand(MI->getOperand(6))
7002      .addMemOperand(MMO);
7003    MI->eraseFromParent();
7004    return BB;
7005  }
7006  case ARM::STRr_preidx:
7007  case ARM::STRBr_preidx:
7008  case ARM::STRH_preidx: {
7009    unsigned NewOpc;
7010    switch (MI->getOpcode()) {
7011    default: llvm_unreachable("unexpected opcode!");
7012    case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7013    case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7014    case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7015    }
7016    MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7017    for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7018      MIB.addOperand(MI->getOperand(i));
7019    MI->eraseFromParent();
7020    return BB;
7021  }
7022  case ARM::ATOMIC_LOAD_ADD_I8:
7023     return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7024  case ARM::ATOMIC_LOAD_ADD_I16:
7025     return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7026  case ARM::ATOMIC_LOAD_ADD_I32:
7027     return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7028
7029  case ARM::ATOMIC_LOAD_AND_I8:
7030     return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7031  case ARM::ATOMIC_LOAD_AND_I16:
7032     return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7033  case ARM::ATOMIC_LOAD_AND_I32:
7034     return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7035
7036  case ARM::ATOMIC_LOAD_OR_I8:
7037     return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7038  case ARM::ATOMIC_LOAD_OR_I16:
7039     return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7040  case ARM::ATOMIC_LOAD_OR_I32:
7041     return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7042
7043  case ARM::ATOMIC_LOAD_XOR_I8:
7044     return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7045  case ARM::ATOMIC_LOAD_XOR_I16:
7046     return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7047  case ARM::ATOMIC_LOAD_XOR_I32:
7048     return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7049
7050  case ARM::ATOMIC_LOAD_NAND_I8:
7051     return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7052  case ARM::ATOMIC_LOAD_NAND_I16:
7053     return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7054  case ARM::ATOMIC_LOAD_NAND_I32:
7055     return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7056
7057  case ARM::ATOMIC_LOAD_SUB_I8:
7058     return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7059  case ARM::ATOMIC_LOAD_SUB_I16:
7060     return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7061  case ARM::ATOMIC_LOAD_SUB_I32:
7062     return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7063
7064  case ARM::ATOMIC_LOAD_MIN_I8:
7065     return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::LT);
7066  case ARM::ATOMIC_LOAD_MIN_I16:
7067     return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::LT);
7068  case ARM::ATOMIC_LOAD_MIN_I32:
7069     return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::LT);
7070
7071  case ARM::ATOMIC_LOAD_MAX_I8:
7072     return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::GT);
7073  case ARM::ATOMIC_LOAD_MAX_I16:
7074     return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::GT);
7075  case ARM::ATOMIC_LOAD_MAX_I32:
7076     return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::GT);
7077
7078  case ARM::ATOMIC_LOAD_UMIN_I8:
7079     return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::LO);
7080  case ARM::ATOMIC_LOAD_UMIN_I16:
7081     return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::LO);
7082  case ARM::ATOMIC_LOAD_UMIN_I32:
7083     return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::LO);
7084
7085  case ARM::ATOMIC_LOAD_UMAX_I8:
7086     return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::HI);
7087  case ARM::ATOMIC_LOAD_UMAX_I16:
7088     return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::HI);
7089  case ARM::ATOMIC_LOAD_UMAX_I32:
7090     return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::HI);
7091
7092  case ARM::ATOMIC_SWAP_I8:  return EmitAtomicBinary(MI, BB, 1, 0);
7093  case ARM::ATOMIC_SWAP_I16: return EmitAtomicBinary(MI, BB, 2, 0);
7094  case ARM::ATOMIC_SWAP_I32: return EmitAtomicBinary(MI, BB, 4, 0);
7095
7096  case ARM::ATOMIC_CMP_SWAP_I8:  return EmitAtomicCmpSwap(MI, BB, 1);
7097  case ARM::ATOMIC_CMP_SWAP_I16: return EmitAtomicCmpSwap(MI, BB, 2);
7098  case ARM::ATOMIC_CMP_SWAP_I32: return EmitAtomicCmpSwap(MI, BB, 4);
7099
7100
7101  case ARM::ATOMADD6432:
7102    return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr,
7103                              isThumb2 ? ARM::t2ADCrr : ARM::ADCrr,
7104                              /*NeedsCarry*/ true);
7105  case ARM::ATOMSUB6432:
7106    return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7107                              isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7108                              /*NeedsCarry*/ true);
7109  case ARM::ATOMOR6432:
7110    return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr,
7111                              isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7112  case ARM::ATOMXOR6432:
7113    return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2EORrr : ARM::EORrr,
7114                              isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7115  case ARM::ATOMAND6432:
7116    return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr,
7117                              isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7118  case ARM::ATOMSWAP6432:
7119    return EmitAtomicBinary64(MI, BB, 0, 0, false);
7120  case ARM::ATOMCMPXCHG6432:
7121    return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7122                              isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7123                              /*NeedsCarry*/ false, /*IsCmpxchg*/true);
7124  case ARM::ATOMMIN6432:
7125    return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7126                              isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7127                              /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7128                              /*IsMinMax*/ true, ARMCC::LT);
7129  case ARM::ATOMMAX6432:
7130    return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7131                              isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7132                              /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7133                              /*IsMinMax*/ true, ARMCC::GE);
7134  case ARM::ATOMUMIN6432:
7135    return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7136                              isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7137                              /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7138                              /*IsMinMax*/ true, ARMCC::LO);
7139  case ARM::ATOMUMAX6432:
7140    return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7141                              isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7142                              /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7143                              /*IsMinMax*/ true, ARMCC::HS);
7144
7145  case ARM::tMOVCCr_pseudo: {
7146    // To "insert" a SELECT_CC instruction, we actually have to insert the
7147    // diamond control-flow pattern.  The incoming instruction knows the
7148    // destination vreg to set, the condition code register to branch on, the
7149    // true/false values to select between, and a branch opcode to use.
7150    const BasicBlock *LLVM_BB = BB->getBasicBlock();
7151    MachineFunction::iterator It = BB;
7152    ++It;
7153
7154    //  thisMBB:
7155    //  ...
7156    //   TrueVal = ...
7157    //   cmpTY ccX, r1, r2
7158    //   bCC copy1MBB
7159    //   fallthrough --> copy0MBB
7160    MachineBasicBlock *thisMBB  = BB;
7161    MachineFunction *F = BB->getParent();
7162    MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7163    MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
7164    F->insert(It, copy0MBB);
7165    F->insert(It, sinkMBB);
7166
7167    // Transfer the remainder of BB and its successor edges to sinkMBB.
7168    sinkMBB->splice(sinkMBB->begin(), BB,
7169                    llvm::next(MachineBasicBlock::iterator(MI)),
7170                    BB->end());
7171    sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7172
7173    BB->addSuccessor(copy0MBB);
7174    BB->addSuccessor(sinkMBB);
7175
7176    BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7177      .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7178
7179    //  copy0MBB:
7180    //   %FalseValue = ...
7181    //   # fallthrough to sinkMBB
7182    BB = copy0MBB;
7183
7184    // Update machine-CFG edges
7185    BB->addSuccessor(sinkMBB);
7186
7187    //  sinkMBB:
7188    //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7189    //  ...
7190    BB = sinkMBB;
7191    BuildMI(*BB, BB->begin(), dl,
7192            TII->get(ARM::PHI), MI->getOperand(0).getReg())
7193      .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7194      .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7195
7196    MI->eraseFromParent();   // The pseudo instruction is gone now.
7197    return BB;
7198  }
7199
7200  case ARM::BCCi64:
7201  case ARM::BCCZi64: {
7202    // If there is an unconditional branch to the other successor, remove it.
7203    BB->erase(llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
7204
7205    // Compare both parts that make up the double comparison separately for
7206    // equality.
7207    bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7208
7209    unsigned LHS1 = MI->getOperand(1).getReg();
7210    unsigned LHS2 = MI->getOperand(2).getReg();
7211    if (RHSisZero) {
7212      AddDefaultPred(BuildMI(BB, dl,
7213                             TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7214                     .addReg(LHS1).addImm(0));
7215      BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7216        .addReg(LHS2).addImm(0)
7217        .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7218    } else {
7219      unsigned RHS1 = MI->getOperand(3).getReg();
7220      unsigned RHS2 = MI->getOperand(4).getReg();
7221      AddDefaultPred(BuildMI(BB, dl,
7222                             TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7223                     .addReg(LHS1).addReg(RHS1));
7224      BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7225        .addReg(LHS2).addReg(RHS2)
7226        .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7227    }
7228
7229    MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7230    MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7231    if (MI->getOperand(0).getImm() == ARMCC::NE)
7232      std::swap(destMBB, exitMBB);
7233
7234    BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7235      .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7236    if (isThumb2)
7237      AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7238    else
7239      BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7240
7241    MI->eraseFromParent();   // The pseudo instruction is gone now.
7242    return BB;
7243  }
7244
7245  case ARM::Int_eh_sjlj_setjmp:
7246  case ARM::Int_eh_sjlj_setjmp_nofp:
7247  case ARM::tInt_eh_sjlj_setjmp:
7248  case ARM::t2Int_eh_sjlj_setjmp:
7249  case ARM::t2Int_eh_sjlj_setjmp_nofp:
7250    EmitSjLjDispatchBlock(MI, BB);
7251    return BB;
7252
7253  case ARM::ABS:
7254  case ARM::t2ABS: {
7255    // To insert an ABS instruction, we have to insert the
7256    // diamond control-flow pattern.  The incoming instruction knows the
7257    // source vreg to test against 0, the destination vreg to set,
7258    // the condition code register to branch on, the
7259    // true/false values to select between, and a branch opcode to use.
7260    // It transforms
7261    //     V1 = ABS V0
7262    // into
7263    //     V2 = MOVS V0
7264    //     BCC                      (branch to SinkBB if V0 >= 0)
7265    //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
7266    //     SinkBB: V1 = PHI(V2, V3)
7267    const BasicBlock *LLVM_BB = BB->getBasicBlock();
7268    MachineFunction::iterator BBI = BB;
7269    ++BBI;
7270    MachineFunction *Fn = BB->getParent();
7271    MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7272    MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
7273    Fn->insert(BBI, RSBBB);
7274    Fn->insert(BBI, SinkBB);
7275
7276    unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7277    unsigned int ABSDstReg = MI->getOperand(0).getReg();
7278    bool isThumb2 = Subtarget->isThumb2();
7279    MachineRegisterInfo &MRI = Fn->getRegInfo();
7280    // In Thumb mode S must not be specified if source register is the SP or
7281    // PC and if destination register is the SP, so restrict register class
7282    unsigned NewRsbDstReg = MRI.createVirtualRegister(isThumb2 ?
7283      (const TargetRegisterClass*)&ARM::rGPRRegClass :
7284      (const TargetRegisterClass*)&ARM::GPRRegClass);
7285
7286    // Transfer the remainder of BB and its successor edges to sinkMBB.
7287    SinkBB->splice(SinkBB->begin(), BB,
7288      llvm::next(MachineBasicBlock::iterator(MI)),
7289      BB->end());
7290    SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7291
7292    BB->addSuccessor(RSBBB);
7293    BB->addSuccessor(SinkBB);
7294
7295    // fall through to SinkMBB
7296    RSBBB->addSuccessor(SinkBB);
7297
7298    // insert a cmp at the end of BB
7299    AddDefaultPred(BuildMI(BB, dl,
7300                           TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7301                   .addReg(ABSSrcReg).addImm(0));
7302
7303    // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7304    BuildMI(BB, dl,
7305      TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7306      .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7307
7308    // insert rsbri in RSBBB
7309    // Note: BCC and rsbri will be converted into predicated rsbmi
7310    // by if-conversion pass
7311    BuildMI(*RSBBB, RSBBB->begin(), dl,
7312      TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7313      .addReg(ABSSrcReg, RegState::Kill)
7314      .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7315
7316    // insert PHI in SinkBB,
7317    // reuse ABSDstReg to not change uses of ABS instruction
7318    BuildMI(*SinkBB, SinkBB->begin(), dl,
7319      TII->get(ARM::PHI), ABSDstReg)
7320      .addReg(NewRsbDstReg).addMBB(RSBBB)
7321      .addReg(ABSSrcReg).addMBB(BB);
7322
7323    // remove ABS instruction
7324    MI->eraseFromParent();
7325
7326    // return last added BB
7327    return SinkBB;
7328  }
7329  case ARM::COPY_STRUCT_BYVAL_I32:
7330    ++NumLoopByVals;
7331    return EmitStructByval(MI, BB);
7332  }
7333}
7334
7335void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7336                                                      SDNode *Node) const {
7337  if (!MI->hasPostISelHook()) {
7338    assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
7339           "Pseudo flag-setting opcodes must be marked with 'hasPostISelHook'");
7340    return;
7341  }
7342
7343  const MCInstrDesc *MCID = &MI->getDesc();
7344  // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7345  // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7346  // operand is still set to noreg. If needed, set the optional operand's
7347  // register to CPSR, and remove the redundant implicit def.
7348  //
7349  // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7350
7351  // Rename pseudo opcodes.
7352  unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7353  if (NewOpc) {
7354    const ARMBaseInstrInfo *TII =
7355      static_cast<const ARMBaseInstrInfo*>(getTargetMachine().getInstrInfo());
7356    MCID = &TII->get(NewOpc);
7357
7358    assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7359           "converted opcode should be the same except for cc_out");
7360
7361    MI->setDesc(*MCID);
7362
7363    // Add the optional cc_out operand
7364    MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7365  }
7366  unsigned ccOutIdx = MCID->getNumOperands() - 1;
7367
7368  // Any ARM instruction that sets the 's' bit should specify an optional
7369  // "cc_out" operand in the last operand position.
7370  if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7371    assert(!NewOpc && "Optional cc_out operand required");
7372    return;
7373  }
7374  // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7375  // since we already have an optional CPSR def.
7376  bool definesCPSR = false;
7377  bool deadCPSR = false;
7378  for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7379       i != e; ++i) {
7380    const MachineOperand &MO = MI->getOperand(i);
7381    if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7382      definesCPSR = true;
7383      if (MO.isDead())
7384        deadCPSR = true;
7385      MI->RemoveOperand(i);
7386      break;
7387    }
7388  }
7389  if (!definesCPSR) {
7390    assert(!NewOpc && "Optional cc_out operand required");
7391    return;
7392  }
7393  assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
7394  if (deadCPSR) {
7395    assert(!MI->getOperand(ccOutIdx).getReg() &&
7396           "expect uninitialized optional cc_out operand");
7397    return;
7398  }
7399
7400  // If this instruction was defined with an optional CPSR def and its dag node
7401  // had a live implicit CPSR def, then activate the optional CPSR def.
7402  MachineOperand &MO = MI->getOperand(ccOutIdx);
7403  MO.setReg(ARM::CPSR);
7404  MO.setIsDef(true);
7405}
7406
7407//===----------------------------------------------------------------------===//
7408//                           ARM Optimization Hooks
7409//===----------------------------------------------------------------------===//
7410
7411// Helper function that checks if N is a null or all ones constant.
7412static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
7413  ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
7414  if (!C)
7415    return false;
7416  return AllOnes ? C->isAllOnesValue() : C->isNullValue();
7417}
7418
7419// Return true if N is conditionally 0 or all ones.
7420// Detects these expressions where cc is an i1 value:
7421//
7422//   (select cc 0, y)   [AllOnes=0]
7423//   (select cc y, 0)   [AllOnes=0]
7424//   (zext cc)          [AllOnes=0]
7425//   (sext cc)          [AllOnes=0/1]
7426//   (select cc -1, y)  [AllOnes=1]
7427//   (select cc y, -1)  [AllOnes=1]
7428//
7429// Invert is set when N is the null/all ones constant when CC is false.
7430// OtherOp is set to the alternative value of N.
7431static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
7432                                       SDValue &CC, bool &Invert,
7433                                       SDValue &OtherOp,
7434                                       SelectionDAG &DAG) {
7435  switch (N->getOpcode()) {
7436  default: return false;
7437  case ISD::SELECT: {
7438    CC = N->getOperand(0);
7439    SDValue N1 = N->getOperand(1);
7440    SDValue N2 = N->getOperand(2);
7441    if (isZeroOrAllOnes(N1, AllOnes)) {
7442      Invert = false;
7443      OtherOp = N2;
7444      return true;
7445    }
7446    if (isZeroOrAllOnes(N2, AllOnes)) {
7447      Invert = true;
7448      OtherOp = N1;
7449      return true;
7450    }
7451    return false;
7452  }
7453  case ISD::ZERO_EXTEND:
7454    // (zext cc) can never be the all ones value.
7455    if (AllOnes)
7456      return false;
7457    // Fall through.
7458  case ISD::SIGN_EXTEND: {
7459    EVT VT = N->getValueType(0);
7460    CC = N->getOperand(0);
7461    if (CC.getValueType() != MVT::i1)
7462      return false;
7463    Invert = !AllOnes;
7464    if (AllOnes)
7465      // When looking for an AllOnes constant, N is an sext, and the 'other'
7466      // value is 0.
7467      OtherOp = DAG.getConstant(0, VT);
7468    else if (N->getOpcode() == ISD::ZERO_EXTEND)
7469      // When looking for a 0 constant, N can be zext or sext.
7470      OtherOp = DAG.getConstant(1, VT);
7471    else
7472      OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
7473    return true;
7474  }
7475  }
7476}
7477
7478// Combine a constant select operand into its use:
7479//
7480//   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
7481//   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
7482//   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
7483//   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
7484//   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
7485//
7486// The transform is rejected if the select doesn't have a constant operand that
7487// is null, or all ones when AllOnes is set.
7488//
7489// Also recognize sext/zext from i1:
7490//
7491//   (add (zext cc), x) -> (select cc (add x, 1), x)
7492//   (add (sext cc), x) -> (select cc (add x, -1), x)
7493//
7494// These transformations eventually create predicated instructions.
7495//
7496// @param N       The node to transform.
7497// @param Slct    The N operand that is a select.
7498// @param OtherOp The other N operand (x above).
7499// @param DCI     Context.
7500// @param AllOnes Require the select constant to be all ones instead of null.
7501// @returns The new node, or SDValue() on failure.
7502static
7503SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7504                            TargetLowering::DAGCombinerInfo &DCI,
7505                            bool AllOnes = false) {
7506  SelectionDAG &DAG = DCI.DAG;
7507  EVT VT = N->getValueType(0);
7508  SDValue NonConstantVal;
7509  SDValue CCOp;
7510  bool SwapSelectOps;
7511  if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
7512                                  NonConstantVal, DAG))
7513    return SDValue();
7514
7515  // Slct is now know to be the desired identity constant when CC is true.
7516  SDValue TrueVal = OtherOp;
7517  SDValue FalseVal = DAG.getNode(N->getOpcode(), N->getDebugLoc(), VT,
7518                                 OtherOp, NonConstantVal);
7519  // Unless SwapSelectOps says CC should be false.
7520  if (SwapSelectOps)
7521    std::swap(TrueVal, FalseVal);
7522
7523  return DAG.getNode(ISD::SELECT, N->getDebugLoc(), VT,
7524                     CCOp, TrueVal, FalseVal);
7525}
7526
7527// Attempt combineSelectAndUse on each operand of a commutative operator N.
7528static
7529SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
7530                                       TargetLowering::DAGCombinerInfo &DCI) {
7531  SDValue N0 = N->getOperand(0);
7532  SDValue N1 = N->getOperand(1);
7533  if (N0.getNode()->hasOneUse()) {
7534    SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
7535    if (Result.getNode())
7536      return Result;
7537  }
7538  if (N1.getNode()->hasOneUse()) {
7539    SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
7540    if (Result.getNode())
7541      return Result;
7542  }
7543  return SDValue();
7544}
7545
7546// AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
7547// (only after legalization).
7548static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
7549                                 TargetLowering::DAGCombinerInfo &DCI,
7550                                 const ARMSubtarget *Subtarget) {
7551
7552  // Only perform optimization if after legalize, and if NEON is available. We
7553  // also expected both operands to be BUILD_VECTORs.
7554  if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
7555      || N0.getOpcode() != ISD::BUILD_VECTOR
7556      || N1.getOpcode() != ISD::BUILD_VECTOR)
7557    return SDValue();
7558
7559  // Check output type since VPADDL operand elements can only be 8, 16, or 32.
7560  EVT VT = N->getValueType(0);
7561  if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
7562    return SDValue();
7563
7564  // Check that the vector operands are of the right form.
7565  // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
7566  // operands, where N is the size of the formed vector.
7567  // Each EXTRACT_VECTOR should have the same input vector and odd or even
7568  // index such that we have a pair wise add pattern.
7569
7570  // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
7571  if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7572    return SDValue();
7573  SDValue Vec = N0->getOperand(0)->getOperand(0);
7574  SDNode *V = Vec.getNode();
7575  unsigned nextIndex = 0;
7576
7577  // For each operands to the ADD which are BUILD_VECTORs,
7578  // check to see if each of their operands are an EXTRACT_VECTOR with
7579  // the same vector and appropriate index.
7580  for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
7581    if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
7582        && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7583
7584      SDValue ExtVec0 = N0->getOperand(i);
7585      SDValue ExtVec1 = N1->getOperand(i);
7586
7587      // First operand is the vector, verify its the same.
7588      if (V != ExtVec0->getOperand(0).getNode() ||
7589          V != ExtVec1->getOperand(0).getNode())
7590        return SDValue();
7591
7592      // Second is the constant, verify its correct.
7593      ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
7594      ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
7595
7596      // For the constant, we want to see all the even or all the odd.
7597      if (!C0 || !C1 || C0->getZExtValue() != nextIndex
7598          || C1->getZExtValue() != nextIndex+1)
7599        return SDValue();
7600
7601      // Increment index.
7602      nextIndex+=2;
7603    } else
7604      return SDValue();
7605  }
7606
7607  // Create VPADDL node.
7608  SelectionDAG &DAG = DCI.DAG;
7609  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7610
7611  // Build operand list.
7612  SmallVector<SDValue, 8> Ops;
7613  Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
7614                                TLI.getPointerTy()));
7615
7616  // Input is the vector.
7617  Ops.push_back(Vec);
7618
7619  // Get widened type and narrowed type.
7620  MVT widenType;
7621  unsigned numElem = VT.getVectorNumElements();
7622  switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
7623    case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
7624    case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
7625    case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
7626    default:
7627      llvm_unreachable("Invalid vector element type for padd optimization.");
7628  }
7629
7630  SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
7631                            widenType, &Ops[0], Ops.size());
7632  return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, tmp);
7633}
7634
7635static SDValue findMUL_LOHI(SDValue V) {
7636  if (V->getOpcode() == ISD::UMUL_LOHI ||
7637      V->getOpcode() == ISD::SMUL_LOHI)
7638    return V;
7639  return SDValue();
7640}
7641
7642static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
7643                                     TargetLowering::DAGCombinerInfo &DCI,
7644                                     const ARMSubtarget *Subtarget) {
7645
7646  if (Subtarget->isThumb1Only()) return SDValue();
7647
7648  // Only perform the checks after legalize when the pattern is available.
7649  if (DCI.isBeforeLegalize()) return SDValue();
7650
7651  // Look for multiply add opportunities.
7652  // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
7653  // each add nodes consumes a value from ISD::UMUL_LOHI and there is
7654  // a glue link from the first add to the second add.
7655  // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
7656  // a S/UMLAL instruction.
7657  //          loAdd   UMUL_LOHI
7658  //            \    / :lo    \ :hi
7659  //             \  /          \          [no multiline comment]
7660  //              ADDC         |  hiAdd
7661  //                 \ :glue  /  /
7662  //                  \      /  /
7663  //                    ADDE
7664  //
7665  assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
7666  SDValue AddcOp0 = AddcNode->getOperand(0);
7667  SDValue AddcOp1 = AddcNode->getOperand(1);
7668
7669  // Check if the two operands are from the same mul_lohi node.
7670  if (AddcOp0.getNode() == AddcOp1.getNode())
7671    return SDValue();
7672
7673  assert(AddcNode->getNumValues() == 2 &&
7674         AddcNode->getValueType(0) == MVT::i32 &&
7675         AddcNode->getValueType(1) == MVT::Glue &&
7676         "Expect ADDC with two result values: i32, glue");
7677
7678  // Check that the ADDC adds the low result of the S/UMUL_LOHI.
7679  if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
7680      AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
7681      AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
7682      AddcOp1->getOpcode() != ISD::SMUL_LOHI)
7683    return SDValue();
7684
7685  // Look for the glued ADDE.
7686  SDNode* AddeNode = AddcNode->getGluedUser();
7687  if (AddeNode == NULL)
7688    return SDValue();
7689
7690  // Make sure it is really an ADDE.
7691  if (AddeNode->getOpcode() != ISD::ADDE)
7692    return SDValue();
7693
7694  assert(AddeNode->getNumOperands() == 3 &&
7695         AddeNode->getOperand(2).getValueType() == MVT::Glue &&
7696         "ADDE node has the wrong inputs");
7697
7698  // Check for the triangle shape.
7699  SDValue AddeOp0 = AddeNode->getOperand(0);
7700  SDValue AddeOp1 = AddeNode->getOperand(1);
7701
7702  // Make sure that the ADDE operands are not coming from the same node.
7703  if (AddeOp0.getNode() == AddeOp1.getNode())
7704    return SDValue();
7705
7706  // Find the MUL_LOHI node walking up ADDE's operands.
7707  bool IsLeftOperandMUL = false;
7708  SDValue MULOp = findMUL_LOHI(AddeOp0);
7709  if (MULOp == SDValue())
7710   MULOp = findMUL_LOHI(AddeOp1);
7711  else
7712    IsLeftOperandMUL = true;
7713  if (MULOp == SDValue())
7714     return SDValue();
7715
7716  // Figure out the right opcode.
7717  unsigned Opc = MULOp->getOpcode();
7718  unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
7719
7720  // Figure out the high and low input values to the MLAL node.
7721  SDValue* HiMul = &MULOp;
7722  SDValue* HiAdd = NULL;
7723  SDValue* LoMul = NULL;
7724  SDValue* LowAdd = NULL;
7725
7726  if (IsLeftOperandMUL)
7727    HiAdd = &AddeOp1;
7728  else
7729    HiAdd = &AddeOp0;
7730
7731
7732  if (AddcOp0->getOpcode() == Opc) {
7733    LoMul = &AddcOp0;
7734    LowAdd = &AddcOp1;
7735  }
7736  if (AddcOp1->getOpcode() == Opc) {
7737    LoMul = &AddcOp1;
7738    LowAdd = &AddcOp0;
7739  }
7740
7741  if (LoMul == NULL)
7742    return SDValue();
7743
7744  if (LoMul->getNode() != HiMul->getNode())
7745    return SDValue();
7746
7747  // Create the merged node.
7748  SelectionDAG &DAG = DCI.DAG;
7749
7750  // Build operand list.
7751  SmallVector<SDValue, 8> Ops;
7752  Ops.push_back(LoMul->getOperand(0));
7753  Ops.push_back(LoMul->getOperand(1));
7754  Ops.push_back(*LowAdd);
7755  Ops.push_back(*HiAdd);
7756
7757  SDValue MLALNode =  DAG.getNode(FinalOpc, AddcNode->getDebugLoc(),
7758                                 DAG.getVTList(MVT::i32, MVT::i32),
7759                                 &Ops[0], Ops.size());
7760
7761  // Replace the ADDs' nodes uses by the MLA node's values.
7762  SDValue HiMLALResult(MLALNode.getNode(), 1);
7763  DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
7764
7765  SDValue LoMLALResult(MLALNode.getNode(), 0);
7766  DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
7767
7768  // Return original node to notify the driver to stop replacing.
7769  SDValue resNode(AddcNode, 0);
7770  return resNode;
7771}
7772
7773/// PerformADDCCombine - Target-specific dag combine transform from
7774/// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
7775static SDValue PerformADDCCombine(SDNode *N,
7776                                 TargetLowering::DAGCombinerInfo &DCI,
7777                                 const ARMSubtarget *Subtarget) {
7778
7779  return AddCombineTo64bitMLAL(N, DCI, Subtarget);
7780
7781}
7782
7783/// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
7784/// operands N0 and N1.  This is a helper for PerformADDCombine that is
7785/// called with the default operands, and if that fails, with commuted
7786/// operands.
7787static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
7788                                          TargetLowering::DAGCombinerInfo &DCI,
7789                                          const ARMSubtarget *Subtarget){
7790
7791  // Attempt to create vpaddl for this add.
7792  SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
7793  if (Result.getNode())
7794    return Result;
7795
7796  // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
7797  if (N0.getNode()->hasOneUse()) {
7798    SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
7799    if (Result.getNode()) return Result;
7800  }
7801  return SDValue();
7802}
7803
7804/// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
7805///
7806static SDValue PerformADDCombine(SDNode *N,
7807                                 TargetLowering::DAGCombinerInfo &DCI,
7808                                 const ARMSubtarget *Subtarget) {
7809  SDValue N0 = N->getOperand(0);
7810  SDValue N1 = N->getOperand(1);
7811
7812  // First try with the default operand order.
7813  SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
7814  if (Result.getNode())
7815    return Result;
7816
7817  // If that didn't work, try again with the operands commuted.
7818  return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
7819}
7820
7821/// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
7822///
7823static SDValue PerformSUBCombine(SDNode *N,
7824                                 TargetLowering::DAGCombinerInfo &DCI) {
7825  SDValue N0 = N->getOperand(0);
7826  SDValue N1 = N->getOperand(1);
7827
7828  // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
7829  if (N1.getNode()->hasOneUse()) {
7830    SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
7831    if (Result.getNode()) return Result;
7832  }
7833
7834  return SDValue();
7835}
7836
7837/// PerformVMULCombine
7838/// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
7839/// special multiplier accumulator forwarding.
7840///   vmul d3, d0, d2
7841///   vmla d3, d1, d2
7842/// is faster than
7843///   vadd d3, d0, d1
7844///   vmul d3, d3, d2
7845static SDValue PerformVMULCombine(SDNode *N,
7846                                  TargetLowering::DAGCombinerInfo &DCI,
7847                                  const ARMSubtarget *Subtarget) {
7848  if (!Subtarget->hasVMLxForwarding())
7849    return SDValue();
7850
7851  SelectionDAG &DAG = DCI.DAG;
7852  SDValue N0 = N->getOperand(0);
7853  SDValue N1 = N->getOperand(1);
7854  unsigned Opcode = N0.getOpcode();
7855  if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
7856      Opcode != ISD::FADD && Opcode != ISD::FSUB) {
7857    Opcode = N1.getOpcode();
7858    if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
7859        Opcode != ISD::FADD && Opcode != ISD::FSUB)
7860      return SDValue();
7861    std::swap(N0, N1);
7862  }
7863
7864  EVT VT = N->getValueType(0);
7865  DebugLoc DL = N->getDebugLoc();
7866  SDValue N00 = N0->getOperand(0);
7867  SDValue N01 = N0->getOperand(1);
7868  return DAG.getNode(Opcode, DL, VT,
7869                     DAG.getNode(ISD::MUL, DL, VT, N00, N1),
7870                     DAG.getNode(ISD::MUL, DL, VT, N01, N1));
7871}
7872
7873static SDValue PerformMULCombine(SDNode *N,
7874                                 TargetLowering::DAGCombinerInfo &DCI,
7875                                 const ARMSubtarget *Subtarget) {
7876  SelectionDAG &DAG = DCI.DAG;
7877
7878  if (Subtarget->isThumb1Only())
7879    return SDValue();
7880
7881  if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
7882    return SDValue();
7883
7884  EVT VT = N->getValueType(0);
7885  if (VT.is64BitVector() || VT.is128BitVector())
7886    return PerformVMULCombine(N, DCI, Subtarget);
7887  if (VT != MVT::i32)
7888    return SDValue();
7889
7890  ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
7891  if (!C)
7892    return SDValue();
7893
7894  int64_t MulAmt = C->getSExtValue();
7895  unsigned ShiftAmt = CountTrailingZeros_64(MulAmt);
7896
7897  ShiftAmt = ShiftAmt & (32 - 1);
7898  SDValue V = N->getOperand(0);
7899  DebugLoc DL = N->getDebugLoc();
7900
7901  SDValue Res;
7902  MulAmt >>= ShiftAmt;
7903
7904  if (MulAmt >= 0) {
7905    if (isPowerOf2_32(MulAmt - 1)) {
7906      // (mul x, 2^N + 1) => (add (shl x, N), x)
7907      Res = DAG.getNode(ISD::ADD, DL, VT,
7908                        V,
7909                        DAG.getNode(ISD::SHL, DL, VT,
7910                                    V,
7911                                    DAG.getConstant(Log2_32(MulAmt - 1),
7912                                                    MVT::i32)));
7913    } else if (isPowerOf2_32(MulAmt + 1)) {
7914      // (mul x, 2^N - 1) => (sub (shl x, N), x)
7915      Res = DAG.getNode(ISD::SUB, DL, VT,
7916                        DAG.getNode(ISD::SHL, DL, VT,
7917                                    V,
7918                                    DAG.getConstant(Log2_32(MulAmt + 1),
7919                                                    MVT::i32)),
7920                        V);
7921    } else
7922      return SDValue();
7923  } else {
7924    uint64_t MulAmtAbs = -MulAmt;
7925    if (isPowerOf2_32(MulAmtAbs + 1)) {
7926      // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
7927      Res = DAG.getNode(ISD::SUB, DL, VT,
7928                        V,
7929                        DAG.getNode(ISD::SHL, DL, VT,
7930                                    V,
7931                                    DAG.getConstant(Log2_32(MulAmtAbs + 1),
7932                                                    MVT::i32)));
7933    } else if (isPowerOf2_32(MulAmtAbs - 1)) {
7934      // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
7935      Res = DAG.getNode(ISD::ADD, DL, VT,
7936                        V,
7937                        DAG.getNode(ISD::SHL, DL, VT,
7938                                    V,
7939                                    DAG.getConstant(Log2_32(MulAmtAbs-1),
7940                                                    MVT::i32)));
7941      Res = DAG.getNode(ISD::SUB, DL, VT,
7942                        DAG.getConstant(0, MVT::i32),Res);
7943
7944    } else
7945      return SDValue();
7946  }
7947
7948  if (ShiftAmt != 0)
7949    Res = DAG.getNode(ISD::SHL, DL, VT,
7950                      Res, DAG.getConstant(ShiftAmt, MVT::i32));
7951
7952  // Do not add new nodes to DAG combiner worklist.
7953  DCI.CombineTo(N, Res, false);
7954  return SDValue();
7955}
7956
7957static SDValue PerformANDCombine(SDNode *N,
7958                                 TargetLowering::DAGCombinerInfo &DCI,
7959                                 const ARMSubtarget *Subtarget) {
7960
7961  // Attempt to use immediate-form VBIC
7962  BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
7963  DebugLoc dl = N->getDebugLoc();
7964  EVT VT = N->getValueType(0);
7965  SelectionDAG &DAG = DCI.DAG;
7966
7967  if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
7968    return SDValue();
7969
7970  APInt SplatBits, SplatUndef;
7971  unsigned SplatBitSize;
7972  bool HasAnyUndefs;
7973  if (BVN &&
7974      BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
7975    if (SplatBitSize <= 64) {
7976      EVT VbicVT;
7977      SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
7978                                      SplatUndef.getZExtValue(), SplatBitSize,
7979                                      DAG, VbicVT, VT.is128BitVector(),
7980                                      OtherModImm);
7981      if (Val.getNode()) {
7982        SDValue Input =
7983          DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
7984        SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
7985        return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
7986      }
7987    }
7988  }
7989
7990  if (!Subtarget->isThumb1Only()) {
7991    // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
7992    SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
7993    if (Result.getNode())
7994      return Result;
7995  }
7996
7997  return SDValue();
7998}
7999
8000/// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8001static SDValue PerformORCombine(SDNode *N,
8002                                TargetLowering::DAGCombinerInfo &DCI,
8003                                const ARMSubtarget *Subtarget) {
8004  // Attempt to use immediate-form VORR
8005  BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8006  DebugLoc dl = N->getDebugLoc();
8007  EVT VT = N->getValueType(0);
8008  SelectionDAG &DAG = DCI.DAG;
8009
8010  if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8011    return SDValue();
8012
8013  APInt SplatBits, SplatUndef;
8014  unsigned SplatBitSize;
8015  bool HasAnyUndefs;
8016  if (BVN && Subtarget->hasNEON() &&
8017      BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8018    if (SplatBitSize <= 64) {
8019      EVT VorrVT;
8020      SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8021                                      SplatUndef.getZExtValue(), SplatBitSize,
8022                                      DAG, VorrVT, VT.is128BitVector(),
8023                                      OtherModImm);
8024      if (Val.getNode()) {
8025        SDValue Input =
8026          DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8027        SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8028        return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8029      }
8030    }
8031  }
8032
8033  if (!Subtarget->isThumb1Only()) {
8034    // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8035    SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8036    if (Result.getNode())
8037      return Result;
8038  }
8039
8040  // The code below optimizes (or (and X, Y), Z).
8041  // The AND operand needs to have a single user to make these optimizations
8042  // profitable.
8043  SDValue N0 = N->getOperand(0);
8044  if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8045    return SDValue();
8046  SDValue N1 = N->getOperand(1);
8047
8048  // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8049  if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8050      DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8051    APInt SplatUndef;
8052    unsigned SplatBitSize;
8053    bool HasAnyUndefs;
8054
8055    BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8056    APInt SplatBits0;
8057    if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8058                                  HasAnyUndefs) && !HasAnyUndefs) {
8059      BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8060      APInt SplatBits1;
8061      if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8062                                    HasAnyUndefs) && !HasAnyUndefs &&
8063          SplatBits0 == ~SplatBits1) {
8064        // Canonicalize the vector type to make instruction selection simpler.
8065        EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8066        SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8067                                     N0->getOperand(1), N0->getOperand(0),
8068                                     N1->getOperand(0));
8069        return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8070      }
8071    }
8072  }
8073
8074  // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8075  // reasonable.
8076
8077  // BFI is only available on V6T2+
8078  if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8079    return SDValue();
8080
8081  DebugLoc DL = N->getDebugLoc();
8082  // 1) or (and A, mask), val => ARMbfi A, val, mask
8083  //      iff (val & mask) == val
8084  //
8085  // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8086  //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8087  //          && mask == ~mask2
8088  //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8089  //          && ~mask == mask2
8090  //  (i.e., copy a bitfield value into another bitfield of the same width)
8091
8092  if (VT != MVT::i32)
8093    return SDValue();
8094
8095  SDValue N00 = N0.getOperand(0);
8096
8097  // The value and the mask need to be constants so we can verify this is
8098  // actually a bitfield set. If the mask is 0xffff, we can do better
8099  // via a movt instruction, so don't use BFI in that case.
8100  SDValue MaskOp = N0.getOperand(1);
8101  ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8102  if (!MaskC)
8103    return SDValue();
8104  unsigned Mask = MaskC->getZExtValue();
8105  if (Mask == 0xffff)
8106    return SDValue();
8107  SDValue Res;
8108  // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8109  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8110  if (N1C) {
8111    unsigned Val = N1C->getZExtValue();
8112    if ((Val & ~Mask) != Val)
8113      return SDValue();
8114
8115    if (ARM::isBitFieldInvertedMask(Mask)) {
8116      Val >>= CountTrailingZeros_32(~Mask);
8117
8118      Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8119                        DAG.getConstant(Val, MVT::i32),
8120                        DAG.getConstant(Mask, MVT::i32));
8121
8122      // Do not add new nodes to DAG combiner worklist.
8123      DCI.CombineTo(N, Res, false);
8124      return SDValue();
8125    }
8126  } else if (N1.getOpcode() == ISD::AND) {
8127    // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8128    ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8129    if (!N11C)
8130      return SDValue();
8131    unsigned Mask2 = N11C->getZExtValue();
8132
8133    // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8134    // as is to match.
8135    if (ARM::isBitFieldInvertedMask(Mask) &&
8136        (Mask == ~Mask2)) {
8137      // The pack halfword instruction works better for masks that fit it,
8138      // so use that when it's available.
8139      if (Subtarget->hasT2ExtractPack() &&
8140          (Mask == 0xffff || Mask == 0xffff0000))
8141        return SDValue();
8142      // 2a
8143      unsigned amt = CountTrailingZeros_32(Mask2);
8144      Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8145                        DAG.getConstant(amt, MVT::i32));
8146      Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8147                        DAG.getConstant(Mask, MVT::i32));
8148      // Do not add new nodes to DAG combiner worklist.
8149      DCI.CombineTo(N, Res, false);
8150      return SDValue();
8151    } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8152               (~Mask == Mask2)) {
8153      // The pack halfword instruction works better for masks that fit it,
8154      // so use that when it's available.
8155      if (Subtarget->hasT2ExtractPack() &&
8156          (Mask2 == 0xffff || Mask2 == 0xffff0000))
8157        return SDValue();
8158      // 2b
8159      unsigned lsb = CountTrailingZeros_32(Mask);
8160      Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8161                        DAG.getConstant(lsb, MVT::i32));
8162      Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8163                        DAG.getConstant(Mask2, MVT::i32));
8164      // Do not add new nodes to DAG combiner worklist.
8165      DCI.CombineTo(N, Res, false);
8166      return SDValue();
8167    }
8168  }
8169
8170  if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8171      N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8172      ARM::isBitFieldInvertedMask(~Mask)) {
8173    // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8174    // where lsb(mask) == #shamt and masked bits of B are known zero.
8175    SDValue ShAmt = N00.getOperand(1);
8176    unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8177    unsigned LSB = CountTrailingZeros_32(Mask);
8178    if (ShAmtC != LSB)
8179      return SDValue();
8180
8181    Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8182                      DAG.getConstant(~Mask, MVT::i32));
8183
8184    // Do not add new nodes to DAG combiner worklist.
8185    DCI.CombineTo(N, Res, false);
8186  }
8187
8188  return SDValue();
8189}
8190
8191static SDValue PerformXORCombine(SDNode *N,
8192                                 TargetLowering::DAGCombinerInfo &DCI,
8193                                 const ARMSubtarget *Subtarget) {
8194  EVT VT = N->getValueType(0);
8195  SelectionDAG &DAG = DCI.DAG;
8196
8197  if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8198    return SDValue();
8199
8200  if (!Subtarget->isThumb1Only()) {
8201    // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8202    SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8203    if (Result.getNode())
8204      return Result;
8205  }
8206
8207  return SDValue();
8208}
8209
8210/// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8211/// the bits being cleared by the AND are not demanded by the BFI.
8212static SDValue PerformBFICombine(SDNode *N,
8213                                 TargetLowering::DAGCombinerInfo &DCI) {
8214  SDValue N1 = N->getOperand(1);
8215  if (N1.getOpcode() == ISD::AND) {
8216    ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8217    if (!N11C)
8218      return SDValue();
8219    unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8220    unsigned LSB = CountTrailingZeros_32(~InvMask);
8221    unsigned Width = (32 - CountLeadingZeros_32(~InvMask)) - LSB;
8222    unsigned Mask = (1 << Width)-1;
8223    unsigned Mask2 = N11C->getZExtValue();
8224    if ((Mask & (~Mask2)) == 0)
8225      return DCI.DAG.getNode(ARMISD::BFI, N->getDebugLoc(), N->getValueType(0),
8226                             N->getOperand(0), N1.getOperand(0),
8227                             N->getOperand(2));
8228  }
8229  return SDValue();
8230}
8231
8232/// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8233/// ARMISD::VMOVRRD.
8234static SDValue PerformVMOVRRDCombine(SDNode *N,
8235                                     TargetLowering::DAGCombinerInfo &DCI) {
8236  // vmovrrd(vmovdrr x, y) -> x,y
8237  SDValue InDouble = N->getOperand(0);
8238  if (InDouble.getOpcode() == ARMISD::VMOVDRR)
8239    return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8240
8241  // vmovrrd(load f64) -> (load i32), (load i32)
8242  SDNode *InNode = InDouble.getNode();
8243  if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8244      InNode->getValueType(0) == MVT::f64 &&
8245      InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8246      !cast<LoadSDNode>(InNode)->isVolatile()) {
8247    // TODO: Should this be done for non-FrameIndex operands?
8248    LoadSDNode *LD = cast<LoadSDNode>(InNode);
8249
8250    SelectionDAG &DAG = DCI.DAG;
8251    DebugLoc DL = LD->getDebugLoc();
8252    SDValue BasePtr = LD->getBasePtr();
8253    SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8254                                 LD->getPointerInfo(), LD->isVolatile(),
8255                                 LD->isNonTemporal(), LD->isInvariant(),
8256                                 LD->getAlignment());
8257
8258    SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8259                                    DAG.getConstant(4, MVT::i32));
8260    SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8261                                 LD->getPointerInfo(), LD->isVolatile(),
8262                                 LD->isNonTemporal(), LD->isInvariant(),
8263                                 std::min(4U, LD->getAlignment() / 2));
8264
8265    DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8266    SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8267    DCI.RemoveFromWorklist(LD);
8268    DAG.DeleteNode(LD);
8269    return Result;
8270  }
8271
8272  return SDValue();
8273}
8274
8275/// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8276/// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
8277static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8278  // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8279  SDValue Op0 = N->getOperand(0);
8280  SDValue Op1 = N->getOperand(1);
8281  if (Op0.getOpcode() == ISD::BITCAST)
8282    Op0 = Op0.getOperand(0);
8283  if (Op1.getOpcode() == ISD::BITCAST)
8284    Op1 = Op1.getOperand(0);
8285  if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8286      Op0.getNode() == Op1.getNode() &&
8287      Op0.getResNo() == 0 && Op1.getResNo() == 1)
8288    return DAG.getNode(ISD::BITCAST, N->getDebugLoc(),
8289                       N->getValueType(0), Op0.getOperand(0));
8290  return SDValue();
8291}
8292
8293/// PerformSTORECombine - Target-specific dag combine xforms for
8294/// ISD::STORE.
8295static SDValue PerformSTORECombine(SDNode *N,
8296                                   TargetLowering::DAGCombinerInfo &DCI) {
8297  StoreSDNode *St = cast<StoreSDNode>(N);
8298  if (St->isVolatile())
8299    return SDValue();
8300
8301  // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
8302  // pack all of the elements in one place.  Next, store to memory in fewer
8303  // chunks.
8304  SDValue StVal = St->getValue();
8305  EVT VT = StVal.getValueType();
8306  if (St->isTruncatingStore() && VT.isVector()) {
8307    SelectionDAG &DAG = DCI.DAG;
8308    const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8309    EVT StVT = St->getMemoryVT();
8310    unsigned NumElems = VT.getVectorNumElements();
8311    assert(StVT != VT && "Cannot truncate to the same type");
8312    unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
8313    unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
8314
8315    // From, To sizes and ElemCount must be pow of two
8316    if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
8317
8318    // We are going to use the original vector elt for storing.
8319    // Accumulated smaller vector elements must be a multiple of the store size.
8320    if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
8321
8322    unsigned SizeRatio  = FromEltSz / ToEltSz;
8323    assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
8324
8325    // Create a type on which we perform the shuffle.
8326    EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
8327                                     NumElems*SizeRatio);
8328    assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
8329
8330    DebugLoc DL = St->getDebugLoc();
8331    SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
8332    SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
8333    for (unsigned i = 0; i < NumElems; ++i) ShuffleVec[i] = i * SizeRatio;
8334
8335    // Can't shuffle using an illegal type.
8336    if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
8337
8338    SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
8339                                DAG.getUNDEF(WideVec.getValueType()),
8340                                ShuffleVec.data());
8341    // At this point all of the data is stored at the bottom of the
8342    // register. We now need to save it to mem.
8343
8344    // Find the largest store unit
8345    MVT StoreType = MVT::i8;
8346    for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
8347         tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
8348      MVT Tp = (MVT::SimpleValueType)tp;
8349      if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
8350        StoreType = Tp;
8351    }
8352    // Didn't find a legal store type.
8353    if (!TLI.isTypeLegal(StoreType))
8354      return SDValue();
8355
8356    // Bitcast the original vector into a vector of store-size units
8357    EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
8358            StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
8359    assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
8360    SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
8361    SmallVector<SDValue, 8> Chains;
8362    SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
8363                                        TLI.getPointerTy());
8364    SDValue BasePtr = St->getBasePtr();
8365
8366    // Perform one or more big stores into memory.
8367    unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
8368    for (unsigned I = 0; I < E; I++) {
8369      SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
8370                                   StoreType, ShuffWide,
8371                                   DAG.getIntPtrConstant(I));
8372      SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
8373                                St->getPointerInfo(), St->isVolatile(),
8374                                St->isNonTemporal(), St->getAlignment());
8375      BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
8376                            Increment);
8377      Chains.push_back(Ch);
8378    }
8379    return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, &Chains[0],
8380                       Chains.size());
8381  }
8382
8383  if (!ISD::isNormalStore(St))
8384    return SDValue();
8385
8386  // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
8387  // ARM stores of arguments in the same cache line.
8388  if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
8389      StVal.getNode()->hasOneUse()) {
8390    SelectionDAG  &DAG = DCI.DAG;
8391    DebugLoc DL = St->getDebugLoc();
8392    SDValue BasePtr = St->getBasePtr();
8393    SDValue NewST1 = DAG.getStore(St->getChain(), DL,
8394                                  StVal.getNode()->getOperand(0), BasePtr,
8395                                  St->getPointerInfo(), St->isVolatile(),
8396                                  St->isNonTemporal(), St->getAlignment());
8397
8398    SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8399                                    DAG.getConstant(4, MVT::i32));
8400    return DAG.getStore(NewST1.getValue(0), DL, StVal.getNode()->getOperand(1),
8401                        OffsetPtr, St->getPointerInfo(), St->isVolatile(),
8402                        St->isNonTemporal(),
8403                        std::min(4U, St->getAlignment() / 2));
8404  }
8405
8406  if (StVal.getValueType() != MVT::i64 ||
8407      StVal.getNode()->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8408    return SDValue();
8409
8410  // Bitcast an i64 store extracted from a vector to f64.
8411  // Otherwise, the i64 value will be legalized to a pair of i32 values.
8412  SelectionDAG &DAG = DCI.DAG;
8413  DebugLoc dl = StVal.getDebugLoc();
8414  SDValue IntVec = StVal.getOperand(0);
8415  EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8416                                 IntVec.getValueType().getVectorNumElements());
8417  SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
8418  SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8419                               Vec, StVal.getOperand(1));
8420  dl = N->getDebugLoc();
8421  SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
8422  // Make the DAGCombiner fold the bitcasts.
8423  DCI.AddToWorklist(Vec.getNode());
8424  DCI.AddToWorklist(ExtElt.getNode());
8425  DCI.AddToWorklist(V.getNode());
8426  return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
8427                      St->getPointerInfo(), St->isVolatile(),
8428                      St->isNonTemporal(), St->getAlignment(),
8429                      St->getTBAAInfo());
8430}
8431
8432/// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8433/// are normal, non-volatile loads.  If so, it is profitable to bitcast an
8434/// i64 vector to have f64 elements, since the value can then be loaded
8435/// directly into a VFP register.
8436static bool hasNormalLoadOperand(SDNode *N) {
8437  unsigned NumElts = N->getValueType(0).getVectorNumElements();
8438  for (unsigned i = 0; i < NumElts; ++i) {
8439    SDNode *Elt = N->getOperand(i).getNode();
8440    if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8441      return true;
8442  }
8443  return false;
8444}
8445
8446/// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
8447/// ISD::BUILD_VECTOR.
8448static SDValue PerformBUILD_VECTORCombine(SDNode *N,
8449                                          TargetLowering::DAGCombinerInfo &DCI){
8450  // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
8451  // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
8452  // into a pair of GPRs, which is fine when the value is used as a scalar,
8453  // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
8454  SelectionDAG &DAG = DCI.DAG;
8455  if (N->getNumOperands() == 2) {
8456    SDValue RV = PerformVMOVDRRCombine(N, DAG);
8457    if (RV.getNode())
8458      return RV;
8459  }
8460
8461  // Load i64 elements as f64 values so that type legalization does not split
8462  // them up into i32 values.
8463  EVT VT = N->getValueType(0);
8464  if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
8465    return SDValue();
8466  DebugLoc dl = N->getDebugLoc();
8467  SmallVector<SDValue, 8> Ops;
8468  unsigned NumElts = VT.getVectorNumElements();
8469  for (unsigned i = 0; i < NumElts; ++i) {
8470    SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
8471    Ops.push_back(V);
8472    // Make the DAGCombiner fold the bitcast.
8473    DCI.AddToWorklist(V.getNode());
8474  }
8475  EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
8476  SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops.data(), NumElts);
8477  return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8478}
8479
8480/// PerformInsertEltCombine - Target-specific dag combine xforms for
8481/// ISD::INSERT_VECTOR_ELT.
8482static SDValue PerformInsertEltCombine(SDNode *N,
8483                                       TargetLowering::DAGCombinerInfo &DCI) {
8484  // Bitcast an i64 load inserted into a vector to f64.
8485  // Otherwise, the i64 value will be legalized to a pair of i32 values.
8486  EVT VT = N->getValueType(0);
8487  SDNode *Elt = N->getOperand(1).getNode();
8488  if (VT.getVectorElementType() != MVT::i64 ||
8489      !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
8490    return SDValue();
8491
8492  SelectionDAG &DAG = DCI.DAG;
8493  DebugLoc dl = N->getDebugLoc();
8494  EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8495                                 VT.getVectorNumElements());
8496  SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
8497  SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
8498  // Make the DAGCombiner fold the bitcasts.
8499  DCI.AddToWorklist(Vec.getNode());
8500  DCI.AddToWorklist(V.getNode());
8501  SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
8502                               Vec, V, N->getOperand(2));
8503  return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
8504}
8505
8506/// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
8507/// ISD::VECTOR_SHUFFLE.
8508static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
8509  // The LLVM shufflevector instruction does not require the shuffle mask
8510  // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
8511  // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
8512  // operands do not match the mask length, they are extended by concatenating
8513  // them with undef vectors.  That is probably the right thing for other
8514  // targets, but for NEON it is better to concatenate two double-register
8515  // size vector operands into a single quad-register size vector.  Do that
8516  // transformation here:
8517  //   shuffle(concat(v1, undef), concat(v2, undef)) ->
8518  //   shuffle(concat(v1, v2), undef)
8519  SDValue Op0 = N->getOperand(0);
8520  SDValue Op1 = N->getOperand(1);
8521  if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
8522      Op1.getOpcode() != ISD::CONCAT_VECTORS ||
8523      Op0.getNumOperands() != 2 ||
8524      Op1.getNumOperands() != 2)
8525    return SDValue();
8526  SDValue Concat0Op1 = Op0.getOperand(1);
8527  SDValue Concat1Op1 = Op1.getOperand(1);
8528  if (Concat0Op1.getOpcode() != ISD::UNDEF ||
8529      Concat1Op1.getOpcode() != ISD::UNDEF)
8530    return SDValue();
8531  // Skip the transformation if any of the types are illegal.
8532  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8533  EVT VT = N->getValueType(0);
8534  if (!TLI.isTypeLegal(VT) ||
8535      !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
8536      !TLI.isTypeLegal(Concat1Op1.getValueType()))
8537    return SDValue();
8538
8539  SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, N->getDebugLoc(), VT,
8540                                  Op0.getOperand(0), Op1.getOperand(0));
8541  // Translate the shuffle mask.
8542  SmallVector<int, 16> NewMask;
8543  unsigned NumElts = VT.getVectorNumElements();
8544  unsigned HalfElts = NumElts/2;
8545  ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8546  for (unsigned n = 0; n < NumElts; ++n) {
8547    int MaskElt = SVN->getMaskElt(n);
8548    int NewElt = -1;
8549    if (MaskElt < (int)HalfElts)
8550      NewElt = MaskElt;
8551    else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
8552      NewElt = HalfElts + MaskElt - NumElts;
8553    NewMask.push_back(NewElt);
8554  }
8555  return DAG.getVectorShuffle(VT, N->getDebugLoc(), NewConcat,
8556                              DAG.getUNDEF(VT), NewMask.data());
8557}
8558
8559/// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP and
8560/// NEON load/store intrinsics to merge base address updates.
8561static SDValue CombineBaseUpdate(SDNode *N,
8562                                 TargetLowering::DAGCombinerInfo &DCI) {
8563  if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8564    return SDValue();
8565
8566  SelectionDAG &DAG = DCI.DAG;
8567  bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
8568                      N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
8569  unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
8570  SDValue Addr = N->getOperand(AddrOpIdx);
8571
8572  // Search for a use of the address operand that is an increment.
8573  for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
8574         UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
8575    SDNode *User = *UI;
8576    if (User->getOpcode() != ISD::ADD ||
8577        UI.getUse().getResNo() != Addr.getResNo())
8578      continue;
8579
8580    // Check that the add is independent of the load/store.  Otherwise, folding
8581    // it would create a cycle.
8582    if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
8583      continue;
8584
8585    // Find the new opcode for the updating load/store.
8586    bool isLoad = true;
8587    bool isLaneOp = false;
8588    unsigned NewOpc = 0;
8589    unsigned NumVecs = 0;
8590    if (isIntrinsic) {
8591      unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
8592      switch (IntNo) {
8593      default: llvm_unreachable("unexpected intrinsic for Neon base update");
8594      case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
8595        NumVecs = 1; break;
8596      case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
8597        NumVecs = 2; break;
8598      case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
8599        NumVecs = 3; break;
8600      case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
8601        NumVecs = 4; break;
8602      case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
8603        NumVecs = 2; isLaneOp = true; break;
8604      case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
8605        NumVecs = 3; isLaneOp = true; break;
8606      case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
8607        NumVecs = 4; isLaneOp = true; break;
8608      case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
8609        NumVecs = 1; isLoad = false; break;
8610      case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
8611        NumVecs = 2; isLoad = false; break;
8612      case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
8613        NumVecs = 3; isLoad = false; break;
8614      case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
8615        NumVecs = 4; isLoad = false; break;
8616      case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
8617        NumVecs = 2; isLoad = false; isLaneOp = true; break;
8618      case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
8619        NumVecs = 3; isLoad = false; isLaneOp = true; break;
8620      case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
8621        NumVecs = 4; isLoad = false; isLaneOp = true; break;
8622      }
8623    } else {
8624      isLaneOp = true;
8625      switch (N->getOpcode()) {
8626      default: llvm_unreachable("unexpected opcode for Neon base update");
8627      case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
8628      case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
8629      case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
8630      }
8631    }
8632
8633    // Find the size of memory referenced by the load/store.
8634    EVT VecTy;
8635    if (isLoad)
8636      VecTy = N->getValueType(0);
8637    else
8638      VecTy = N->getOperand(AddrOpIdx+1).getValueType();
8639    unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
8640    if (isLaneOp)
8641      NumBytes /= VecTy.getVectorNumElements();
8642
8643    // If the increment is a constant, it must match the memory ref size.
8644    SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8645    if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8646      uint64_t IncVal = CInc->getZExtValue();
8647      if (IncVal != NumBytes)
8648        continue;
8649    } else if (NumBytes >= 3 * 16) {
8650      // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
8651      // separate instructions that make it harder to use a non-constant update.
8652      continue;
8653    }
8654
8655    // Create the new updating load/store node.
8656    EVT Tys[6];
8657    unsigned NumResultVecs = (isLoad ? NumVecs : 0);
8658    unsigned n;
8659    for (n = 0; n < NumResultVecs; ++n)
8660      Tys[n] = VecTy;
8661    Tys[n++] = MVT::i32;
8662    Tys[n] = MVT::Other;
8663    SDVTList SDTys = DAG.getVTList(Tys, NumResultVecs+2);
8664    SmallVector<SDValue, 8> Ops;
8665    Ops.push_back(N->getOperand(0)); // incoming chain
8666    Ops.push_back(N->getOperand(AddrOpIdx));
8667    Ops.push_back(Inc);
8668    for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
8669      Ops.push_back(N->getOperand(i));
8670    }
8671    MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
8672    SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, N->getDebugLoc(), SDTys,
8673                                           Ops.data(), Ops.size(),
8674                                           MemInt->getMemoryVT(),
8675                                           MemInt->getMemOperand());
8676
8677    // Update the uses.
8678    std::vector<SDValue> NewResults;
8679    for (unsigned i = 0; i < NumResultVecs; ++i) {
8680      NewResults.push_back(SDValue(UpdN.getNode(), i));
8681    }
8682    NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
8683    DCI.CombineTo(N, NewResults);
8684    DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
8685
8686    break;
8687  }
8688  return SDValue();
8689}
8690
8691/// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
8692/// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
8693/// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
8694/// return true.
8695static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8696  SelectionDAG &DAG = DCI.DAG;
8697  EVT VT = N->getValueType(0);
8698  // vldN-dup instructions only support 64-bit vectors for N > 1.
8699  if (!VT.is64BitVector())
8700    return false;
8701
8702  // Check if the VDUPLANE operand is a vldN-dup intrinsic.
8703  SDNode *VLD = N->getOperand(0).getNode();
8704  if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
8705    return false;
8706  unsigned NumVecs = 0;
8707  unsigned NewOpc = 0;
8708  unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
8709  if (IntNo == Intrinsic::arm_neon_vld2lane) {
8710    NumVecs = 2;
8711    NewOpc = ARMISD::VLD2DUP;
8712  } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
8713    NumVecs = 3;
8714    NewOpc = ARMISD::VLD3DUP;
8715  } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
8716    NumVecs = 4;
8717    NewOpc = ARMISD::VLD4DUP;
8718  } else {
8719    return false;
8720  }
8721
8722  // First check that all the vldN-lane uses are VDUPLANEs and that the lane
8723  // numbers match the load.
8724  unsigned VLDLaneNo =
8725    cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
8726  for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
8727       UI != UE; ++UI) {
8728    // Ignore uses of the chain result.
8729    if (UI.getUse().getResNo() == NumVecs)
8730      continue;
8731    SDNode *User = *UI;
8732    if (User->getOpcode() != ARMISD::VDUPLANE ||
8733        VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
8734      return false;
8735  }
8736
8737  // Create the vldN-dup node.
8738  EVT Tys[5];
8739  unsigned n;
8740  for (n = 0; n < NumVecs; ++n)
8741    Tys[n] = VT;
8742  Tys[n] = MVT::Other;
8743  SDVTList SDTys = DAG.getVTList(Tys, NumVecs+1);
8744  SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
8745  MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
8746  SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, VLD->getDebugLoc(), SDTys,
8747                                           Ops, 2, VLDMemInt->getMemoryVT(),
8748                                           VLDMemInt->getMemOperand());
8749
8750  // Update the uses.
8751  for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
8752       UI != UE; ++UI) {
8753    unsigned ResNo = UI.getUse().getResNo();
8754    // Ignore uses of the chain result.
8755    if (ResNo == NumVecs)
8756      continue;
8757    SDNode *User = *UI;
8758    DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
8759  }
8760
8761  // Now the vldN-lane intrinsic is dead except for its chain result.
8762  // Update uses of the chain.
8763  std::vector<SDValue> VLDDupResults;
8764  for (unsigned n = 0; n < NumVecs; ++n)
8765    VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
8766  VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
8767  DCI.CombineTo(VLD, VLDDupResults);
8768
8769  return true;
8770}
8771
8772/// PerformVDUPLANECombine - Target-specific dag combine xforms for
8773/// ARMISD::VDUPLANE.
8774static SDValue PerformVDUPLANECombine(SDNode *N,
8775                                      TargetLowering::DAGCombinerInfo &DCI) {
8776  SDValue Op = N->getOperand(0);
8777
8778  // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
8779  // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
8780  if (CombineVLDDUP(N, DCI))
8781    return SDValue(N, 0);
8782
8783  // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
8784  // redundant.  Ignore bit_converts for now; element sizes are checked below.
8785  while (Op.getOpcode() == ISD::BITCAST)
8786    Op = Op.getOperand(0);
8787  if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
8788    return SDValue();
8789
8790  // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
8791  unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
8792  // The canonical VMOV for a zero vector uses a 32-bit element size.
8793  unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8794  unsigned EltBits;
8795  if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
8796    EltSize = 8;
8797  EVT VT = N->getValueType(0);
8798  if (EltSize > VT.getVectorElementType().getSizeInBits())
8799    return SDValue();
8800
8801  return DCI.DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
8802}
8803
8804// isConstVecPow2 - Return true if each vector element is a power of 2, all
8805// elements are the same constant, C, and Log2(C) ranges from 1 to 32.
8806static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
8807{
8808  integerPart cN;
8809  integerPart c0 = 0;
8810  for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
8811       I != E; I++) {
8812    ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
8813    if (!C)
8814      return false;
8815
8816    bool isExact;
8817    APFloat APF = C->getValueAPF();
8818    if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
8819        != APFloat::opOK || !isExact)
8820      return false;
8821
8822    c0 = (I == 0) ? cN : c0;
8823    if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
8824      return false;
8825  }
8826  C = c0;
8827  return true;
8828}
8829
8830/// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
8831/// can replace combinations of VMUL and VCVT (floating-point to integer)
8832/// when the VMUL has a constant operand that is a power of 2.
8833///
8834/// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
8835///  vmul.f32        d16, d17, d16
8836///  vcvt.s32.f32    d16, d16
8837/// becomes:
8838///  vcvt.s32.f32    d16, d16, #3
8839static SDValue PerformVCVTCombine(SDNode *N,
8840                                  TargetLowering::DAGCombinerInfo &DCI,
8841                                  const ARMSubtarget *Subtarget) {
8842  SelectionDAG &DAG = DCI.DAG;
8843  SDValue Op = N->getOperand(0);
8844
8845  if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
8846      Op.getOpcode() != ISD::FMUL)
8847    return SDValue();
8848
8849  uint64_t C;
8850  SDValue N0 = Op->getOperand(0);
8851  SDValue ConstVec = Op->getOperand(1);
8852  bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
8853
8854  if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
8855      !isConstVecPow2(ConstVec, isSigned, C))
8856    return SDValue();
8857
8858  unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
8859    Intrinsic::arm_neon_vcvtfp2fxu;
8860  return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
8861                     N->getValueType(0),
8862                     DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
8863                     DAG.getConstant(Log2_64(C), MVT::i32));
8864}
8865
8866/// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
8867/// can replace combinations of VCVT (integer to floating-point) and VDIV
8868/// when the VDIV has a constant operand that is a power of 2.
8869///
8870/// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
8871///  vcvt.f32.s32    d16, d16
8872///  vdiv.f32        d16, d17, d16
8873/// becomes:
8874///  vcvt.f32.s32    d16, d16, #3
8875static SDValue PerformVDIVCombine(SDNode *N,
8876                                  TargetLowering::DAGCombinerInfo &DCI,
8877                                  const ARMSubtarget *Subtarget) {
8878  SelectionDAG &DAG = DCI.DAG;
8879  SDValue Op = N->getOperand(0);
8880  unsigned OpOpcode = Op.getNode()->getOpcode();
8881
8882  if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
8883      (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
8884    return SDValue();
8885
8886  uint64_t C;
8887  SDValue ConstVec = N->getOperand(1);
8888  bool isSigned = OpOpcode == ISD::SINT_TO_FP;
8889
8890  if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
8891      !isConstVecPow2(ConstVec, isSigned, C))
8892    return SDValue();
8893
8894  unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
8895    Intrinsic::arm_neon_vcvtfxu2fp;
8896  return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
8897                     Op.getValueType(),
8898                     DAG.getConstant(IntrinsicOpcode, MVT::i32),
8899                     Op.getOperand(0), DAG.getConstant(Log2_64(C), MVT::i32));
8900}
8901
8902/// Getvshiftimm - Check if this is a valid build_vector for the immediate
8903/// operand of a vector shift operation, where all the elements of the
8904/// build_vector must have the same constant integer value.
8905static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
8906  // Ignore bit_converts.
8907  while (Op.getOpcode() == ISD::BITCAST)
8908    Op = Op.getOperand(0);
8909  BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
8910  APInt SplatBits, SplatUndef;
8911  unsigned SplatBitSize;
8912  bool HasAnyUndefs;
8913  if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
8914                                      HasAnyUndefs, ElementBits) ||
8915      SplatBitSize > ElementBits)
8916    return false;
8917  Cnt = SplatBits.getSExtValue();
8918  return true;
8919}
8920
8921/// isVShiftLImm - Check if this is a valid build_vector for the immediate
8922/// operand of a vector shift left operation.  That value must be in the range:
8923///   0 <= Value < ElementBits for a left shift; or
8924///   0 <= Value <= ElementBits for a long left shift.
8925static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
8926  assert(VT.isVector() && "vector shift count is not a vector type");
8927  unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
8928  if (! getVShiftImm(Op, ElementBits, Cnt))
8929    return false;
8930  return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
8931}
8932
8933/// isVShiftRImm - Check if this is a valid build_vector for the immediate
8934/// operand of a vector shift right operation.  For a shift opcode, the value
8935/// is positive, but for an intrinsic the value count must be negative. The
8936/// absolute value must be in the range:
8937///   1 <= |Value| <= ElementBits for a right shift; or
8938///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
8939static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
8940                         int64_t &Cnt) {
8941  assert(VT.isVector() && "vector shift count is not a vector type");
8942  unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
8943  if (! getVShiftImm(Op, ElementBits, Cnt))
8944    return false;
8945  if (isIntrinsic)
8946    Cnt = -Cnt;
8947  return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
8948}
8949
8950/// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
8951static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
8952  unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
8953  switch (IntNo) {
8954  default:
8955    // Don't do anything for most intrinsics.
8956    break;
8957
8958  // Vector shifts: check for immediate versions and lower them.
8959  // Note: This is done during DAG combining instead of DAG legalizing because
8960  // the build_vectors for 64-bit vector element shift counts are generally
8961  // not legal, and it is hard to see their values after they get legalized to
8962  // loads from a constant pool.
8963  case Intrinsic::arm_neon_vshifts:
8964  case Intrinsic::arm_neon_vshiftu:
8965  case Intrinsic::arm_neon_vshiftls:
8966  case Intrinsic::arm_neon_vshiftlu:
8967  case Intrinsic::arm_neon_vshiftn:
8968  case Intrinsic::arm_neon_vrshifts:
8969  case Intrinsic::arm_neon_vrshiftu:
8970  case Intrinsic::arm_neon_vrshiftn:
8971  case Intrinsic::arm_neon_vqshifts:
8972  case Intrinsic::arm_neon_vqshiftu:
8973  case Intrinsic::arm_neon_vqshiftsu:
8974  case Intrinsic::arm_neon_vqshiftns:
8975  case Intrinsic::arm_neon_vqshiftnu:
8976  case Intrinsic::arm_neon_vqshiftnsu:
8977  case Intrinsic::arm_neon_vqrshiftns:
8978  case Intrinsic::arm_neon_vqrshiftnu:
8979  case Intrinsic::arm_neon_vqrshiftnsu: {
8980    EVT VT = N->getOperand(1).getValueType();
8981    int64_t Cnt;
8982    unsigned VShiftOpc = 0;
8983
8984    switch (IntNo) {
8985    case Intrinsic::arm_neon_vshifts:
8986    case Intrinsic::arm_neon_vshiftu:
8987      if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
8988        VShiftOpc = ARMISD::VSHL;
8989        break;
8990      }
8991      if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
8992        VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
8993                     ARMISD::VSHRs : ARMISD::VSHRu);
8994        break;
8995      }
8996      return SDValue();
8997
8998    case Intrinsic::arm_neon_vshiftls:
8999    case Intrinsic::arm_neon_vshiftlu:
9000      if (isVShiftLImm(N->getOperand(2), VT, true, Cnt))
9001        break;
9002      llvm_unreachable("invalid shift count for vshll intrinsic");
9003
9004    case Intrinsic::arm_neon_vrshifts:
9005    case Intrinsic::arm_neon_vrshiftu:
9006      if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9007        break;
9008      return SDValue();
9009
9010    case Intrinsic::arm_neon_vqshifts:
9011    case Intrinsic::arm_neon_vqshiftu:
9012      if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9013        break;
9014      return SDValue();
9015
9016    case Intrinsic::arm_neon_vqshiftsu:
9017      if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9018        break;
9019      llvm_unreachable("invalid shift count for vqshlu intrinsic");
9020
9021    case Intrinsic::arm_neon_vshiftn:
9022    case Intrinsic::arm_neon_vrshiftn:
9023    case Intrinsic::arm_neon_vqshiftns:
9024    case Intrinsic::arm_neon_vqshiftnu:
9025    case Intrinsic::arm_neon_vqshiftnsu:
9026    case Intrinsic::arm_neon_vqrshiftns:
9027    case Intrinsic::arm_neon_vqrshiftnu:
9028    case Intrinsic::arm_neon_vqrshiftnsu:
9029      // Narrowing shifts require an immediate right shift.
9030      if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9031        break;
9032      llvm_unreachable("invalid shift count for narrowing vector shift "
9033                       "intrinsic");
9034
9035    default:
9036      llvm_unreachable("unhandled vector shift");
9037    }
9038
9039    switch (IntNo) {
9040    case Intrinsic::arm_neon_vshifts:
9041    case Intrinsic::arm_neon_vshiftu:
9042      // Opcode already set above.
9043      break;
9044    case Intrinsic::arm_neon_vshiftls:
9045    case Intrinsic::arm_neon_vshiftlu:
9046      if (Cnt == VT.getVectorElementType().getSizeInBits())
9047        VShiftOpc = ARMISD::VSHLLi;
9048      else
9049        VShiftOpc = (IntNo == Intrinsic::arm_neon_vshiftls ?
9050                     ARMISD::VSHLLs : ARMISD::VSHLLu);
9051      break;
9052    case Intrinsic::arm_neon_vshiftn:
9053      VShiftOpc = ARMISD::VSHRN; break;
9054    case Intrinsic::arm_neon_vrshifts:
9055      VShiftOpc = ARMISD::VRSHRs; break;
9056    case Intrinsic::arm_neon_vrshiftu:
9057      VShiftOpc = ARMISD::VRSHRu; break;
9058    case Intrinsic::arm_neon_vrshiftn:
9059      VShiftOpc = ARMISD::VRSHRN; break;
9060    case Intrinsic::arm_neon_vqshifts:
9061      VShiftOpc = ARMISD::VQSHLs; break;
9062    case Intrinsic::arm_neon_vqshiftu:
9063      VShiftOpc = ARMISD::VQSHLu; break;
9064    case Intrinsic::arm_neon_vqshiftsu:
9065      VShiftOpc = ARMISD::VQSHLsu; break;
9066    case Intrinsic::arm_neon_vqshiftns:
9067      VShiftOpc = ARMISD::VQSHRNs; break;
9068    case Intrinsic::arm_neon_vqshiftnu:
9069      VShiftOpc = ARMISD::VQSHRNu; break;
9070    case Intrinsic::arm_neon_vqshiftnsu:
9071      VShiftOpc = ARMISD::VQSHRNsu; break;
9072    case Intrinsic::arm_neon_vqrshiftns:
9073      VShiftOpc = ARMISD::VQRSHRNs; break;
9074    case Intrinsic::arm_neon_vqrshiftnu:
9075      VShiftOpc = ARMISD::VQRSHRNu; break;
9076    case Intrinsic::arm_neon_vqrshiftnsu:
9077      VShiftOpc = ARMISD::VQRSHRNsu; break;
9078    }
9079
9080    return DAG.getNode(VShiftOpc, N->getDebugLoc(), N->getValueType(0),
9081                       N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
9082  }
9083
9084  case Intrinsic::arm_neon_vshiftins: {
9085    EVT VT = N->getOperand(1).getValueType();
9086    int64_t Cnt;
9087    unsigned VShiftOpc = 0;
9088
9089    if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9090      VShiftOpc = ARMISD::VSLI;
9091    else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9092      VShiftOpc = ARMISD::VSRI;
9093    else {
9094      llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9095    }
9096
9097    return DAG.getNode(VShiftOpc, N->getDebugLoc(), N->getValueType(0),
9098                       N->getOperand(1), N->getOperand(2),
9099                       DAG.getConstant(Cnt, MVT::i32));
9100  }
9101
9102  case Intrinsic::arm_neon_vqrshifts:
9103  case Intrinsic::arm_neon_vqrshiftu:
9104    // No immediate versions of these to check for.
9105    break;
9106  }
9107
9108  return SDValue();
9109}
9110
9111/// PerformShiftCombine - Checks for immediate versions of vector shifts and
9112/// lowers them.  As with the vector shift intrinsics, this is done during DAG
9113/// combining instead of DAG legalizing because the build_vectors for 64-bit
9114/// vector element shift counts are generally not legal, and it is hard to see
9115/// their values after they get legalized to loads from a constant pool.
9116static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9117                                   const ARMSubtarget *ST) {
9118  EVT VT = N->getValueType(0);
9119  if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9120    // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9121    // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9122    SDValue N1 = N->getOperand(1);
9123    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9124      SDValue N0 = N->getOperand(0);
9125      if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9126          DAG.MaskedValueIsZero(N0.getOperand(0),
9127                                APInt::getHighBitsSet(32, 16)))
9128        return DAG.getNode(ISD::ROTR, N->getDebugLoc(), VT, N0, N1);
9129    }
9130  }
9131
9132  // Nothing to be done for scalar shifts.
9133  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9134  if (!VT.isVector() || !TLI.isTypeLegal(VT))
9135    return SDValue();
9136
9137  assert(ST->hasNEON() && "unexpected vector shift");
9138  int64_t Cnt;
9139
9140  switch (N->getOpcode()) {
9141  default: llvm_unreachable("unexpected shift opcode");
9142
9143  case ISD::SHL:
9144    if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
9145      return DAG.getNode(ARMISD::VSHL, N->getDebugLoc(), VT, N->getOperand(0),
9146                         DAG.getConstant(Cnt, MVT::i32));
9147    break;
9148
9149  case ISD::SRA:
9150  case ISD::SRL:
9151    if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
9152      unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
9153                            ARMISD::VSHRs : ARMISD::VSHRu);
9154      return DAG.getNode(VShiftOpc, N->getDebugLoc(), VT, N->getOperand(0),
9155                         DAG.getConstant(Cnt, MVT::i32));
9156    }
9157  }
9158  return SDValue();
9159}
9160
9161/// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
9162/// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
9163static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
9164                                    const ARMSubtarget *ST) {
9165  SDValue N0 = N->getOperand(0);
9166
9167  // Check for sign- and zero-extensions of vector extract operations of 8-
9168  // and 16-bit vector elements.  NEON supports these directly.  They are
9169  // handled during DAG combining because type legalization will promote them
9170  // to 32-bit types and it is messy to recognize the operations after that.
9171  if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9172    SDValue Vec = N0.getOperand(0);
9173    SDValue Lane = N0.getOperand(1);
9174    EVT VT = N->getValueType(0);
9175    EVT EltVT = N0.getValueType();
9176    const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9177
9178    if (VT == MVT::i32 &&
9179        (EltVT == MVT::i8 || EltVT == MVT::i16) &&
9180        TLI.isTypeLegal(Vec.getValueType()) &&
9181        isa<ConstantSDNode>(Lane)) {
9182
9183      unsigned Opc = 0;
9184      switch (N->getOpcode()) {
9185      default: llvm_unreachable("unexpected opcode");
9186      case ISD::SIGN_EXTEND:
9187        Opc = ARMISD::VGETLANEs;
9188        break;
9189      case ISD::ZERO_EXTEND:
9190      case ISD::ANY_EXTEND:
9191        Opc = ARMISD::VGETLANEu;
9192        break;
9193      }
9194      return DAG.getNode(Opc, N->getDebugLoc(), VT, Vec, Lane);
9195    }
9196  }
9197
9198  return SDValue();
9199}
9200
9201/// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
9202/// to match f32 max/min patterns to use NEON vmax/vmin instructions.
9203static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
9204                                       const ARMSubtarget *ST) {
9205  // If the target supports NEON, try to use vmax/vmin instructions for f32
9206  // selects like "x < y ? x : y".  Unless the NoNaNsFPMath option is set,
9207  // be careful about NaNs:  NEON's vmax/vmin return NaN if either operand is
9208  // a NaN; only do the transformation when it matches that behavior.
9209
9210  // For now only do this when using NEON for FP operations; if using VFP, it
9211  // is not obvious that the benefit outweighs the cost of switching to the
9212  // NEON pipeline.
9213  if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
9214      N->getValueType(0) != MVT::f32)
9215    return SDValue();
9216
9217  SDValue CondLHS = N->getOperand(0);
9218  SDValue CondRHS = N->getOperand(1);
9219  SDValue LHS = N->getOperand(2);
9220  SDValue RHS = N->getOperand(3);
9221  ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
9222
9223  unsigned Opcode = 0;
9224  bool IsReversed;
9225  if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
9226    IsReversed = false; // x CC y ? x : y
9227  } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
9228    IsReversed = true ; // x CC y ? y : x
9229  } else {
9230    return SDValue();
9231  }
9232
9233  bool IsUnordered;
9234  switch (CC) {
9235  default: break;
9236  case ISD::SETOLT:
9237  case ISD::SETOLE:
9238  case ISD::SETLT:
9239  case ISD::SETLE:
9240  case ISD::SETULT:
9241  case ISD::SETULE:
9242    // If LHS is NaN, an ordered comparison will be false and the result will
9243    // be the RHS, but vmin(NaN, RHS) = NaN.  Avoid this by checking that LHS
9244    // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9245    IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
9246    if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9247      break;
9248    // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
9249    // will return -0, so vmin can only be used for unsafe math or if one of
9250    // the operands is known to be nonzero.
9251    if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
9252        !DAG.getTarget().Options.UnsafeFPMath &&
9253        !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9254      break;
9255    Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
9256    break;
9257
9258  case ISD::SETOGT:
9259  case ISD::SETOGE:
9260  case ISD::SETGT:
9261  case ISD::SETGE:
9262  case ISD::SETUGT:
9263  case ISD::SETUGE:
9264    // If LHS is NaN, an ordered comparison will be false and the result will
9265    // be the RHS, but vmax(NaN, RHS) = NaN.  Avoid this by checking that LHS
9266    // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9267    IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
9268    if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9269      break;
9270    // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
9271    // will return +0, so vmax can only be used for unsafe math or if one of
9272    // the operands is known to be nonzero.
9273    if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
9274        !DAG.getTarget().Options.UnsafeFPMath &&
9275        !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9276      break;
9277    Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
9278    break;
9279  }
9280
9281  if (!Opcode)
9282    return SDValue();
9283  return DAG.getNode(Opcode, N->getDebugLoc(), N->getValueType(0), LHS, RHS);
9284}
9285
9286/// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
9287SDValue
9288ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
9289  SDValue Cmp = N->getOperand(4);
9290  if (Cmp.getOpcode() != ARMISD::CMPZ)
9291    // Only looking at EQ and NE cases.
9292    return SDValue();
9293
9294  EVT VT = N->getValueType(0);
9295  DebugLoc dl = N->getDebugLoc();
9296  SDValue LHS = Cmp.getOperand(0);
9297  SDValue RHS = Cmp.getOperand(1);
9298  SDValue FalseVal = N->getOperand(0);
9299  SDValue TrueVal = N->getOperand(1);
9300  SDValue ARMcc = N->getOperand(2);
9301  ARMCC::CondCodes CC =
9302    (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
9303
9304  // Simplify
9305  //   mov     r1, r0
9306  //   cmp     r1, x
9307  //   mov     r0, y
9308  //   moveq   r0, x
9309  // to
9310  //   cmp     r0, x
9311  //   movne   r0, y
9312  //
9313  //   mov     r1, r0
9314  //   cmp     r1, x
9315  //   mov     r0, x
9316  //   movne   r0, y
9317  // to
9318  //   cmp     r0, x
9319  //   movne   r0, y
9320  /// FIXME: Turn this into a target neutral optimization?
9321  SDValue Res;
9322  if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
9323    Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
9324                      N->getOperand(3), Cmp);
9325  } else if (CC == ARMCC::EQ && TrueVal == RHS) {
9326    SDValue ARMcc;
9327    SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
9328    Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
9329                      N->getOperand(3), NewCmp);
9330  }
9331
9332  if (Res.getNode()) {
9333    APInt KnownZero, KnownOne;
9334    DAG.ComputeMaskedBits(SDValue(N,0), KnownZero, KnownOne);
9335    // Capture demanded bits information that would be otherwise lost.
9336    if (KnownZero == 0xfffffffe)
9337      Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9338                        DAG.getValueType(MVT::i1));
9339    else if (KnownZero == 0xffffff00)
9340      Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9341                        DAG.getValueType(MVT::i8));
9342    else if (KnownZero == 0xffff0000)
9343      Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9344                        DAG.getValueType(MVT::i16));
9345  }
9346
9347  return Res;
9348}
9349
9350SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
9351                                             DAGCombinerInfo &DCI) const {
9352  switch (N->getOpcode()) {
9353  default: break;
9354  case ISD::ADDC:       return PerformADDCCombine(N, DCI, Subtarget);
9355  case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
9356  case ISD::SUB:        return PerformSUBCombine(N, DCI);
9357  case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
9358  case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
9359  case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
9360  case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
9361  case ARMISD::BFI:     return PerformBFICombine(N, DCI);
9362  case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI);
9363  case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
9364  case ISD::STORE:      return PerformSTORECombine(N, DCI);
9365  case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI);
9366  case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
9367  case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
9368  case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
9369  case ISD::FP_TO_SINT:
9370  case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
9371  case ISD::FDIV:       return PerformVDIVCombine(N, DCI, Subtarget);
9372  case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
9373  case ISD::SHL:
9374  case ISD::SRA:
9375  case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
9376  case ISD::SIGN_EXTEND:
9377  case ISD::ZERO_EXTEND:
9378  case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
9379  case ISD::SELECT_CC:  return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
9380  case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
9381  case ARMISD::VLD2DUP:
9382  case ARMISD::VLD3DUP:
9383  case ARMISD::VLD4DUP:
9384    return CombineBaseUpdate(N, DCI);
9385  case ISD::INTRINSIC_VOID:
9386  case ISD::INTRINSIC_W_CHAIN:
9387    switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9388    case Intrinsic::arm_neon_vld1:
9389    case Intrinsic::arm_neon_vld2:
9390    case Intrinsic::arm_neon_vld3:
9391    case Intrinsic::arm_neon_vld4:
9392    case Intrinsic::arm_neon_vld2lane:
9393    case Intrinsic::arm_neon_vld3lane:
9394    case Intrinsic::arm_neon_vld4lane:
9395    case Intrinsic::arm_neon_vst1:
9396    case Intrinsic::arm_neon_vst2:
9397    case Intrinsic::arm_neon_vst3:
9398    case Intrinsic::arm_neon_vst4:
9399    case Intrinsic::arm_neon_vst2lane:
9400    case Intrinsic::arm_neon_vst3lane:
9401    case Intrinsic::arm_neon_vst4lane:
9402      return CombineBaseUpdate(N, DCI);
9403    default: break;
9404    }
9405    break;
9406  }
9407  return SDValue();
9408}
9409
9410bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
9411                                                          EVT VT) const {
9412  return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
9413}
9414
9415bool ARMTargetLowering::allowsUnalignedMemoryAccesses(EVT VT, bool *Fast) const {
9416  // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
9417  bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
9418
9419  switch (VT.getSimpleVT().SimpleTy) {
9420  default:
9421    return false;
9422  case MVT::i8:
9423  case MVT::i16:
9424  case MVT::i32: {
9425    // Unaligned access can use (for example) LRDB, LRDH, LDR
9426    if (AllowsUnaligned) {
9427      if (Fast)
9428        *Fast = Subtarget->hasV7Ops();
9429      return true;
9430    }
9431    return false;
9432  }
9433  case MVT::f64:
9434  case MVT::v2f64: {
9435    // For any little-endian targets with neon, we can support unaligned ld/st
9436    // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
9437    // A big-endian target may also explictly support unaligned accesses
9438    if (Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian())) {
9439      if (Fast)
9440        *Fast = true;
9441      return true;
9442    }
9443    return false;
9444  }
9445  }
9446}
9447
9448static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
9449                       unsigned AlignCheck) {
9450  return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
9451          (DstAlign == 0 || DstAlign % AlignCheck == 0));
9452}
9453
9454EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
9455                                           unsigned DstAlign, unsigned SrcAlign,
9456                                           bool IsMemset, bool ZeroMemset,
9457                                           bool MemcpyStrSrc,
9458                                           MachineFunction &MF) const {
9459  const Function *F = MF.getFunction();
9460
9461  // See if we can use NEON instructions for this...
9462  if ((!IsMemset || ZeroMemset) &&
9463      Subtarget->hasNEON() &&
9464      !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
9465                                       Attribute::NoImplicitFloat)) {
9466    bool Fast;
9467    if (Size >= 16 &&
9468        (memOpAlign(SrcAlign, DstAlign, 16) ||
9469         (allowsUnalignedMemoryAccesses(MVT::v2f64, &Fast) && Fast))) {
9470      return MVT::v2f64;
9471    } else if (Size >= 8 &&
9472               (memOpAlign(SrcAlign, DstAlign, 8) ||
9473                (allowsUnalignedMemoryAccesses(MVT::f64, &Fast) && Fast))) {
9474      return MVT::f64;
9475    }
9476  }
9477
9478  // Lowering to i32/i16 if the size permits.
9479  if (Size >= 4)
9480    return MVT::i32;
9481  else if (Size >= 2)
9482    return MVT::i16;
9483
9484  // Let the target-independent logic figure it out.
9485  return MVT::Other;
9486}
9487
9488bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
9489  if (Val.getOpcode() != ISD::LOAD)
9490    return false;
9491
9492  EVT VT1 = Val.getValueType();
9493  if (!VT1.isSimple() || !VT1.isInteger() ||
9494      !VT2.isSimple() || !VT2.isInteger())
9495    return false;
9496
9497  switch (VT1.getSimpleVT().SimpleTy) {
9498  default: break;
9499  case MVT::i1:
9500  case MVT::i8:
9501  case MVT::i16:
9502    // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
9503    return true;
9504  }
9505
9506  return false;
9507}
9508
9509static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
9510  if (V < 0)
9511    return false;
9512
9513  unsigned Scale = 1;
9514  switch (VT.getSimpleVT().SimpleTy) {
9515  default: return false;
9516  case MVT::i1:
9517  case MVT::i8:
9518    // Scale == 1;
9519    break;
9520  case MVT::i16:
9521    // Scale == 2;
9522    Scale = 2;
9523    break;
9524  case MVT::i32:
9525    // Scale == 4;
9526    Scale = 4;
9527    break;
9528  }
9529
9530  if ((V & (Scale - 1)) != 0)
9531    return false;
9532  V /= Scale;
9533  return V == (V & ((1LL << 5) - 1));
9534}
9535
9536static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
9537                                      const ARMSubtarget *Subtarget) {
9538  bool isNeg = false;
9539  if (V < 0) {
9540    isNeg = true;
9541    V = - V;
9542  }
9543
9544  switch (VT.getSimpleVT().SimpleTy) {
9545  default: return false;
9546  case MVT::i1:
9547  case MVT::i8:
9548  case MVT::i16:
9549  case MVT::i32:
9550    // + imm12 or - imm8
9551    if (isNeg)
9552      return V == (V & ((1LL << 8) - 1));
9553    return V == (V & ((1LL << 12) - 1));
9554  case MVT::f32:
9555  case MVT::f64:
9556    // Same as ARM mode. FIXME: NEON?
9557    if (!Subtarget->hasVFP2())
9558      return false;
9559    if ((V & 3) != 0)
9560      return false;
9561    V >>= 2;
9562    return V == (V & ((1LL << 8) - 1));
9563  }
9564}
9565
9566/// isLegalAddressImmediate - Return true if the integer value can be used
9567/// as the offset of the target addressing mode for load / store of the
9568/// given type.
9569static bool isLegalAddressImmediate(int64_t V, EVT VT,
9570                                    const ARMSubtarget *Subtarget) {
9571  if (V == 0)
9572    return true;
9573
9574  if (!VT.isSimple())
9575    return false;
9576
9577  if (Subtarget->isThumb1Only())
9578    return isLegalT1AddressImmediate(V, VT);
9579  else if (Subtarget->isThumb2())
9580    return isLegalT2AddressImmediate(V, VT, Subtarget);
9581
9582  // ARM mode.
9583  if (V < 0)
9584    V = - V;
9585  switch (VT.getSimpleVT().SimpleTy) {
9586  default: return false;
9587  case MVT::i1:
9588  case MVT::i8:
9589  case MVT::i32:
9590    // +- imm12
9591    return V == (V & ((1LL << 12) - 1));
9592  case MVT::i16:
9593    // +- imm8
9594    return V == (V & ((1LL << 8) - 1));
9595  case MVT::f32:
9596  case MVT::f64:
9597    if (!Subtarget->hasVFP2()) // FIXME: NEON?
9598      return false;
9599    if ((V & 3) != 0)
9600      return false;
9601    V >>= 2;
9602    return V == (V & ((1LL << 8) - 1));
9603  }
9604}
9605
9606bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
9607                                                      EVT VT) const {
9608  int Scale = AM.Scale;
9609  if (Scale < 0)
9610    return false;
9611
9612  switch (VT.getSimpleVT().SimpleTy) {
9613  default: return false;
9614  case MVT::i1:
9615  case MVT::i8:
9616  case MVT::i16:
9617  case MVT::i32:
9618    if (Scale == 1)
9619      return true;
9620    // r + r << imm
9621    Scale = Scale & ~1;
9622    return Scale == 2 || Scale == 4 || Scale == 8;
9623  case MVT::i64:
9624    // r + r
9625    if (((unsigned)AM.HasBaseReg + Scale) <= 2)
9626      return true;
9627    return false;
9628  case MVT::isVoid:
9629    // Note, we allow "void" uses (basically, uses that aren't loads or
9630    // stores), because arm allows folding a scale into many arithmetic
9631    // operations.  This should be made more precise and revisited later.
9632
9633    // Allow r << imm, but the imm has to be a multiple of two.
9634    if (Scale & 1) return false;
9635    return isPowerOf2_32(Scale);
9636  }
9637}
9638
9639/// isLegalAddressingMode - Return true if the addressing mode represented
9640/// by AM is legal for this target, for a load/store of the specified type.
9641bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
9642                                              Type *Ty) const {
9643  EVT VT = getValueType(Ty, true);
9644  if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
9645    return false;
9646
9647  // Can never fold addr of global into load/store.
9648  if (AM.BaseGV)
9649    return false;
9650
9651  switch (AM.Scale) {
9652  case 0:  // no scale reg, must be "r+i" or "r", or "i".
9653    break;
9654  case 1:
9655    if (Subtarget->isThumb1Only())
9656      return false;
9657    // FALL THROUGH.
9658  default:
9659    // ARM doesn't support any R+R*scale+imm addr modes.
9660    if (AM.BaseOffs)
9661      return false;
9662
9663    if (!VT.isSimple())
9664      return false;
9665
9666    if (Subtarget->isThumb2())
9667      return isLegalT2ScaledAddressingMode(AM, VT);
9668
9669    int Scale = AM.Scale;
9670    switch (VT.getSimpleVT().SimpleTy) {
9671    default: return false;
9672    case MVT::i1:
9673    case MVT::i8:
9674    case MVT::i32:
9675      if (Scale < 0) Scale = -Scale;
9676      if (Scale == 1)
9677        return true;
9678      // r + r << imm
9679      return isPowerOf2_32(Scale & ~1);
9680    case MVT::i16:
9681    case MVT::i64:
9682      // r + r
9683      if (((unsigned)AM.HasBaseReg + Scale) <= 2)
9684        return true;
9685      return false;
9686
9687    case MVT::isVoid:
9688      // Note, we allow "void" uses (basically, uses that aren't loads or
9689      // stores), because arm allows folding a scale into many arithmetic
9690      // operations.  This should be made more precise and revisited later.
9691
9692      // Allow r << imm, but the imm has to be a multiple of two.
9693      if (Scale & 1) return false;
9694      return isPowerOf2_32(Scale);
9695    }
9696  }
9697  return true;
9698}
9699
9700/// isLegalICmpImmediate - Return true if the specified immediate is legal
9701/// icmp immediate, that is the target has icmp instructions which can compare
9702/// a register against the immediate without having to materialize the
9703/// immediate into a register.
9704bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
9705  // Thumb2 and ARM modes can use cmn for negative immediates.
9706  if (!Subtarget->isThumb())
9707    return ARM_AM::getSOImmVal(llvm::abs64(Imm)) != -1;
9708  if (Subtarget->isThumb2())
9709    return ARM_AM::getT2SOImmVal(llvm::abs64(Imm)) != -1;
9710  // Thumb1 doesn't have cmn, and only 8-bit immediates.
9711  return Imm >= 0 && Imm <= 255;
9712}
9713
9714/// isLegalAddImmediate - Return true if the specified immediate is a legal add
9715/// *or sub* immediate, that is the target has add or sub instructions which can
9716/// add a register with the immediate without having to materialize the
9717/// immediate into a register.
9718bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
9719  // Same encoding for add/sub, just flip the sign.
9720  int64_t AbsImm = llvm::abs64(Imm);
9721  if (!Subtarget->isThumb())
9722    return ARM_AM::getSOImmVal(AbsImm) != -1;
9723  if (Subtarget->isThumb2())
9724    return ARM_AM::getT2SOImmVal(AbsImm) != -1;
9725  // Thumb1 only has 8-bit unsigned immediate.
9726  return AbsImm >= 0 && AbsImm <= 255;
9727}
9728
9729static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
9730                                      bool isSEXTLoad, SDValue &Base,
9731                                      SDValue &Offset, bool &isInc,
9732                                      SelectionDAG &DAG) {
9733  if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
9734    return false;
9735
9736  if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
9737    // AddressingMode 3
9738    Base = Ptr->getOperand(0);
9739    if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9740      int RHSC = (int)RHS->getZExtValue();
9741      if (RHSC < 0 && RHSC > -256) {
9742        assert(Ptr->getOpcode() == ISD::ADD);
9743        isInc = false;
9744        Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9745        return true;
9746      }
9747    }
9748    isInc = (Ptr->getOpcode() == ISD::ADD);
9749    Offset = Ptr->getOperand(1);
9750    return true;
9751  } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
9752    // AddressingMode 2
9753    if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9754      int RHSC = (int)RHS->getZExtValue();
9755      if (RHSC < 0 && RHSC > -0x1000) {
9756        assert(Ptr->getOpcode() == ISD::ADD);
9757        isInc = false;
9758        Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9759        Base = Ptr->getOperand(0);
9760        return true;
9761      }
9762    }
9763
9764    if (Ptr->getOpcode() == ISD::ADD) {
9765      isInc = true;
9766      ARM_AM::ShiftOpc ShOpcVal=
9767        ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
9768      if (ShOpcVal != ARM_AM::no_shift) {
9769        Base = Ptr->getOperand(1);
9770        Offset = Ptr->getOperand(0);
9771      } else {
9772        Base = Ptr->getOperand(0);
9773        Offset = Ptr->getOperand(1);
9774      }
9775      return true;
9776    }
9777
9778    isInc = (Ptr->getOpcode() == ISD::ADD);
9779    Base = Ptr->getOperand(0);
9780    Offset = Ptr->getOperand(1);
9781    return true;
9782  }
9783
9784  // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
9785  return false;
9786}
9787
9788static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
9789                                     bool isSEXTLoad, SDValue &Base,
9790                                     SDValue &Offset, bool &isInc,
9791                                     SelectionDAG &DAG) {
9792  if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
9793    return false;
9794
9795  Base = Ptr->getOperand(0);
9796  if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9797    int RHSC = (int)RHS->getZExtValue();
9798    if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
9799      assert(Ptr->getOpcode() == ISD::ADD);
9800      isInc = false;
9801      Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9802      return true;
9803    } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
9804      isInc = Ptr->getOpcode() == ISD::ADD;
9805      Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
9806      return true;
9807    }
9808  }
9809
9810  return false;
9811}
9812
9813/// getPreIndexedAddressParts - returns true by value, base pointer and
9814/// offset pointer and addressing mode by reference if the node's address
9815/// can be legally represented as pre-indexed load / store address.
9816bool
9817ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
9818                                             SDValue &Offset,
9819                                             ISD::MemIndexedMode &AM,
9820                                             SelectionDAG &DAG) const {
9821  if (Subtarget->isThumb1Only())
9822    return false;
9823
9824  EVT VT;
9825  SDValue Ptr;
9826  bool isSEXTLoad = false;
9827  if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9828    Ptr = LD->getBasePtr();
9829    VT  = LD->getMemoryVT();
9830    isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
9831  } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9832    Ptr = ST->getBasePtr();
9833    VT  = ST->getMemoryVT();
9834  } else
9835    return false;
9836
9837  bool isInc;
9838  bool isLegal = false;
9839  if (Subtarget->isThumb2())
9840    isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
9841                                       Offset, isInc, DAG);
9842  else
9843    isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
9844                                        Offset, isInc, DAG);
9845  if (!isLegal)
9846    return false;
9847
9848  AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
9849  return true;
9850}
9851
9852/// getPostIndexedAddressParts - returns true by value, base pointer and
9853/// offset pointer and addressing mode by reference if this node can be
9854/// combined with a load / store to form a post-indexed load / store.
9855bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
9856                                                   SDValue &Base,
9857                                                   SDValue &Offset,
9858                                                   ISD::MemIndexedMode &AM,
9859                                                   SelectionDAG &DAG) const {
9860  if (Subtarget->isThumb1Only())
9861    return false;
9862
9863  EVT VT;
9864  SDValue Ptr;
9865  bool isSEXTLoad = false;
9866  if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9867    VT  = LD->getMemoryVT();
9868    Ptr = LD->getBasePtr();
9869    isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
9870  } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9871    VT  = ST->getMemoryVT();
9872    Ptr = ST->getBasePtr();
9873  } else
9874    return false;
9875
9876  bool isInc;
9877  bool isLegal = false;
9878  if (Subtarget->isThumb2())
9879    isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
9880                                       isInc, DAG);
9881  else
9882    isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
9883                                        isInc, DAG);
9884  if (!isLegal)
9885    return false;
9886
9887  if (Ptr != Base) {
9888    // Swap base ptr and offset to catch more post-index load / store when
9889    // it's legal. In Thumb2 mode, offset must be an immediate.
9890    if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
9891        !Subtarget->isThumb2())
9892      std::swap(Base, Offset);
9893
9894    // Post-indexed load / store update the base pointer.
9895    if (Ptr != Base)
9896      return false;
9897  }
9898
9899  AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
9900  return true;
9901}
9902
9903void ARMTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
9904                                                       APInt &KnownZero,
9905                                                       APInt &KnownOne,
9906                                                       const SelectionDAG &DAG,
9907                                                       unsigned Depth) const {
9908  KnownZero = KnownOne = APInt(KnownOne.getBitWidth(), 0);
9909  switch (Op.getOpcode()) {
9910  default: break;
9911  case ARMISD::CMOV: {
9912    // Bits are known zero/one if known on the LHS and RHS.
9913    DAG.ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
9914    if (KnownZero == 0 && KnownOne == 0) return;
9915
9916    APInt KnownZeroRHS, KnownOneRHS;
9917    DAG.ComputeMaskedBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
9918    KnownZero &= KnownZeroRHS;
9919    KnownOne  &= KnownOneRHS;
9920    return;
9921  }
9922  }
9923}
9924
9925//===----------------------------------------------------------------------===//
9926//                           ARM Inline Assembly Support
9927//===----------------------------------------------------------------------===//
9928
9929bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
9930  // Looking for "rev" which is V6+.
9931  if (!Subtarget->hasV6Ops())
9932    return false;
9933
9934  InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
9935  std::string AsmStr = IA->getAsmString();
9936  SmallVector<StringRef, 4> AsmPieces;
9937  SplitString(AsmStr, AsmPieces, ";\n");
9938
9939  switch (AsmPieces.size()) {
9940  default: return false;
9941  case 1:
9942    AsmStr = AsmPieces[0];
9943    AsmPieces.clear();
9944    SplitString(AsmStr, AsmPieces, " \t,");
9945
9946    // rev $0, $1
9947    if (AsmPieces.size() == 3 &&
9948        AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
9949        IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
9950      IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
9951      if (Ty && Ty->getBitWidth() == 32)
9952        return IntrinsicLowering::LowerToByteSwap(CI);
9953    }
9954    break;
9955  }
9956
9957  return false;
9958}
9959
9960/// getConstraintType - Given a constraint letter, return the type of
9961/// constraint it is for this target.
9962ARMTargetLowering::ConstraintType
9963ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
9964  if (Constraint.size() == 1) {
9965    switch (Constraint[0]) {
9966    default:  break;
9967    case 'l': return C_RegisterClass;
9968    case 'w': return C_RegisterClass;
9969    case 'h': return C_RegisterClass;
9970    case 'x': return C_RegisterClass;
9971    case 't': return C_RegisterClass;
9972    case 'j': return C_Other; // Constant for movw.
9973      // An address with a single base register. Due to the way we
9974      // currently handle addresses it is the same as an 'r' memory constraint.
9975    case 'Q': return C_Memory;
9976    }
9977  } else if (Constraint.size() == 2) {
9978    switch (Constraint[0]) {
9979    default: break;
9980    // All 'U+' constraints are addresses.
9981    case 'U': return C_Memory;
9982    }
9983  }
9984  return TargetLowering::getConstraintType(Constraint);
9985}
9986
9987/// Examine constraint type and operand type and determine a weight value.
9988/// This object must already have been set up with the operand type
9989/// and the current alternative constraint selected.
9990TargetLowering::ConstraintWeight
9991ARMTargetLowering::getSingleConstraintMatchWeight(
9992    AsmOperandInfo &info, const char *constraint) const {
9993  ConstraintWeight weight = CW_Invalid;
9994  Value *CallOperandVal = info.CallOperandVal;
9995    // If we don't have a value, we can't do a match,
9996    // but allow it at the lowest weight.
9997  if (CallOperandVal == NULL)
9998    return CW_Default;
9999  Type *type = CallOperandVal->getType();
10000  // Look at the constraint type.
10001  switch (*constraint) {
10002  default:
10003    weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10004    break;
10005  case 'l':
10006    if (type->isIntegerTy()) {
10007      if (Subtarget->isThumb())
10008        weight = CW_SpecificReg;
10009      else
10010        weight = CW_Register;
10011    }
10012    break;
10013  case 'w':
10014    if (type->isFloatingPointTy())
10015      weight = CW_Register;
10016    break;
10017  }
10018  return weight;
10019}
10020
10021typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10022RCPair
10023ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
10024                                                EVT VT) const {
10025  if (Constraint.size() == 1) {
10026    // GCC ARM Constraint Letters
10027    switch (Constraint[0]) {
10028    case 'l': // Low regs or general regs.
10029      if (Subtarget->isThumb())
10030        return RCPair(0U, &ARM::tGPRRegClass);
10031      return RCPair(0U, &ARM::GPRRegClass);
10032    case 'h': // High regs or no regs.
10033      if (Subtarget->isThumb())
10034        return RCPair(0U, &ARM::hGPRRegClass);
10035      break;
10036    case 'r':
10037      return RCPair(0U, &ARM::GPRRegClass);
10038    case 'w':
10039      if (VT == MVT::f32)
10040        return RCPair(0U, &ARM::SPRRegClass);
10041      if (VT.getSizeInBits() == 64)
10042        return RCPair(0U, &ARM::DPRRegClass);
10043      if (VT.getSizeInBits() == 128)
10044        return RCPair(0U, &ARM::QPRRegClass);
10045      break;
10046    case 'x':
10047      if (VT == MVT::f32)
10048        return RCPair(0U, &ARM::SPR_8RegClass);
10049      if (VT.getSizeInBits() == 64)
10050        return RCPair(0U, &ARM::DPR_8RegClass);
10051      if (VT.getSizeInBits() == 128)
10052        return RCPair(0U, &ARM::QPR_8RegClass);
10053      break;
10054    case 't':
10055      if (VT == MVT::f32)
10056        return RCPair(0U, &ARM::SPRRegClass);
10057      break;
10058    }
10059  }
10060  if (StringRef("{cc}").equals_lower(Constraint))
10061    return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10062
10063  return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
10064}
10065
10066/// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10067/// vector.  If it is invalid, don't add anything to Ops.
10068void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10069                                                     std::string &Constraint,
10070                                                     std::vector<SDValue>&Ops,
10071                                                     SelectionDAG &DAG) const {
10072  SDValue Result(0, 0);
10073
10074  // Currently only support length 1 constraints.
10075  if (Constraint.length() != 1) return;
10076
10077  char ConstraintLetter = Constraint[0];
10078  switch (ConstraintLetter) {
10079  default: break;
10080  case 'j':
10081  case 'I': case 'J': case 'K': case 'L':
10082  case 'M': case 'N': case 'O':
10083    ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10084    if (!C)
10085      return;
10086
10087    int64_t CVal64 = C->getSExtValue();
10088    int CVal = (int) CVal64;
10089    // None of these constraints allow values larger than 32 bits.  Check
10090    // that the value fits in an int.
10091    if (CVal != CVal64)
10092      return;
10093
10094    switch (ConstraintLetter) {
10095      case 'j':
10096        // Constant suitable for movw, must be between 0 and
10097        // 65535.
10098        if (Subtarget->hasV6T2Ops())
10099          if (CVal >= 0 && CVal <= 65535)
10100            break;
10101        return;
10102      case 'I':
10103        if (Subtarget->isThumb1Only()) {
10104          // This must be a constant between 0 and 255, for ADD
10105          // immediates.
10106          if (CVal >= 0 && CVal <= 255)
10107            break;
10108        } else if (Subtarget->isThumb2()) {
10109          // A constant that can be used as an immediate value in a
10110          // data-processing instruction.
10111          if (ARM_AM::getT2SOImmVal(CVal) != -1)
10112            break;
10113        } else {
10114          // A constant that can be used as an immediate value in a
10115          // data-processing instruction.
10116          if (ARM_AM::getSOImmVal(CVal) != -1)
10117            break;
10118        }
10119        return;
10120
10121      case 'J':
10122        if (Subtarget->isThumb()) {  // FIXME thumb2
10123          // This must be a constant between -255 and -1, for negated ADD
10124          // immediates. This can be used in GCC with an "n" modifier that
10125          // prints the negated value, for use with SUB instructions. It is
10126          // not useful otherwise but is implemented for compatibility.
10127          if (CVal >= -255 && CVal <= -1)
10128            break;
10129        } else {
10130          // This must be a constant between -4095 and 4095. It is not clear
10131          // what this constraint is intended for. Implemented for
10132          // compatibility with GCC.
10133          if (CVal >= -4095 && CVal <= 4095)
10134            break;
10135        }
10136        return;
10137
10138      case 'K':
10139        if (Subtarget->isThumb1Only()) {
10140          // A 32-bit value where only one byte has a nonzero value. Exclude
10141          // zero to match GCC. This constraint is used by GCC internally for
10142          // constants that can be loaded with a move/shift combination.
10143          // It is not useful otherwise but is implemented for compatibility.
10144          if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
10145            break;
10146        } else if (Subtarget->isThumb2()) {
10147          // A constant whose bitwise inverse can be used as an immediate
10148          // value in a data-processing instruction. This can be used in GCC
10149          // with a "B" modifier that prints the inverted value, for use with
10150          // BIC and MVN instructions. It is not useful otherwise but is
10151          // implemented for compatibility.
10152          if (ARM_AM::getT2SOImmVal(~CVal) != -1)
10153            break;
10154        } else {
10155          // A constant whose bitwise inverse can be used as an immediate
10156          // value in a data-processing instruction. This can be used in GCC
10157          // with a "B" modifier that prints the inverted value, for use with
10158          // BIC and MVN instructions. It is not useful otherwise but is
10159          // implemented for compatibility.
10160          if (ARM_AM::getSOImmVal(~CVal) != -1)
10161            break;
10162        }
10163        return;
10164
10165      case 'L':
10166        if (Subtarget->isThumb1Only()) {
10167          // This must be a constant between -7 and 7,
10168          // for 3-operand ADD/SUB immediate instructions.
10169          if (CVal >= -7 && CVal < 7)
10170            break;
10171        } else if (Subtarget->isThumb2()) {
10172          // A constant whose negation can be used as an immediate value in a
10173          // data-processing instruction. This can be used in GCC with an "n"
10174          // modifier that prints the negated value, for use with SUB
10175          // instructions. It is not useful otherwise but is implemented for
10176          // compatibility.
10177          if (ARM_AM::getT2SOImmVal(-CVal) != -1)
10178            break;
10179        } else {
10180          // A constant whose negation can be used as an immediate value in a
10181          // data-processing instruction. This can be used in GCC with an "n"
10182          // modifier that prints the negated value, for use with SUB
10183          // instructions. It is not useful otherwise but is implemented for
10184          // compatibility.
10185          if (ARM_AM::getSOImmVal(-CVal) != -1)
10186            break;
10187        }
10188        return;
10189
10190      case 'M':
10191        if (Subtarget->isThumb()) { // FIXME thumb2
10192          // This must be a multiple of 4 between 0 and 1020, for
10193          // ADD sp + immediate.
10194          if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
10195            break;
10196        } else {
10197          // A power of two or a constant between 0 and 32.  This is used in
10198          // GCC for the shift amount on shifted register operands, but it is
10199          // useful in general for any shift amounts.
10200          if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
10201            break;
10202        }
10203        return;
10204
10205      case 'N':
10206        if (Subtarget->isThumb()) {  // FIXME thumb2
10207          // This must be a constant between 0 and 31, for shift amounts.
10208          if (CVal >= 0 && CVal <= 31)
10209            break;
10210        }
10211        return;
10212
10213      case 'O':
10214        if (Subtarget->isThumb()) {  // FIXME thumb2
10215          // This must be a multiple of 4 between -508 and 508, for
10216          // ADD/SUB sp = sp + immediate.
10217          if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
10218            break;
10219        }
10220        return;
10221    }
10222    Result = DAG.getTargetConstant(CVal, Op.getValueType());
10223    break;
10224  }
10225
10226  if (Result.getNode()) {
10227    Ops.push_back(Result);
10228    return;
10229  }
10230  return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10231}
10232
10233bool
10234ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
10235  // The ARM target isn't yet aware of offsets.
10236  return false;
10237}
10238
10239bool ARM::isBitFieldInvertedMask(unsigned v) {
10240  if (v == 0xffffffff)
10241    return 0;
10242  // there can be 1's on either or both "outsides", all the "inside"
10243  // bits must be 0's
10244  unsigned int lsb = 0, msb = 31;
10245  while (v & (1 << msb)) --msb;
10246  while (v & (1 << lsb)) ++lsb;
10247  for (unsigned int i = lsb; i <= msb; ++i) {
10248    if (v & (1 << i))
10249      return 0;
10250  }
10251  return 1;
10252}
10253
10254/// isFPImmLegal - Returns true if the target can instruction select the
10255/// specified FP immediate natively. If false, the legalizer will
10256/// materialize the FP immediate as a load from a constant pool.
10257bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
10258  if (!Subtarget->hasVFP3())
10259    return false;
10260  if (VT == MVT::f32)
10261    return ARM_AM::getFP32Imm(Imm) != -1;
10262  if (VT == MVT::f64)
10263    return ARM_AM::getFP64Imm(Imm) != -1;
10264  return false;
10265}
10266
10267/// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
10268/// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
10269/// specified in the intrinsic calls.
10270bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
10271                                           const CallInst &I,
10272                                           unsigned Intrinsic) const {
10273  switch (Intrinsic) {
10274  case Intrinsic::arm_neon_vld1:
10275  case Intrinsic::arm_neon_vld2:
10276  case Intrinsic::arm_neon_vld3:
10277  case Intrinsic::arm_neon_vld4:
10278  case Intrinsic::arm_neon_vld2lane:
10279  case Intrinsic::arm_neon_vld3lane:
10280  case Intrinsic::arm_neon_vld4lane: {
10281    Info.opc = ISD::INTRINSIC_W_CHAIN;
10282    // Conservatively set memVT to the entire set of vectors loaded.
10283    uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
10284    Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10285    Info.ptrVal = I.getArgOperand(0);
10286    Info.offset = 0;
10287    Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10288    Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10289    Info.vol = false; // volatile loads with NEON intrinsics not supported
10290    Info.readMem = true;
10291    Info.writeMem = false;
10292    return true;
10293  }
10294  case Intrinsic::arm_neon_vst1:
10295  case Intrinsic::arm_neon_vst2:
10296  case Intrinsic::arm_neon_vst3:
10297  case Intrinsic::arm_neon_vst4:
10298  case Intrinsic::arm_neon_vst2lane:
10299  case Intrinsic::arm_neon_vst3lane:
10300  case Intrinsic::arm_neon_vst4lane: {
10301    Info.opc = ISD::INTRINSIC_VOID;
10302    // Conservatively set memVT to the entire set of vectors stored.
10303    unsigned NumElts = 0;
10304    for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
10305      Type *ArgTy = I.getArgOperand(ArgI)->getType();
10306      if (!ArgTy->isVectorTy())
10307        break;
10308      NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
10309    }
10310    Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10311    Info.ptrVal = I.getArgOperand(0);
10312    Info.offset = 0;
10313    Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10314    Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10315    Info.vol = false; // volatile stores with NEON intrinsics not supported
10316    Info.readMem = false;
10317    Info.writeMem = true;
10318    return true;
10319  }
10320  case Intrinsic::arm_strexd: {
10321    Info.opc = ISD::INTRINSIC_W_CHAIN;
10322    Info.memVT = MVT::i64;
10323    Info.ptrVal = I.getArgOperand(2);
10324    Info.offset = 0;
10325    Info.align = 8;
10326    Info.vol = true;
10327    Info.readMem = false;
10328    Info.writeMem = true;
10329    return true;
10330  }
10331  case Intrinsic::arm_ldrexd: {
10332    Info.opc = ISD::INTRINSIC_W_CHAIN;
10333    Info.memVT = MVT::i64;
10334    Info.ptrVal = I.getArgOperand(0);
10335    Info.offset = 0;
10336    Info.align = 8;
10337    Info.vol = true;
10338    Info.readMem = true;
10339    Info.writeMem = false;
10340    return true;
10341  }
10342  default:
10343    break;
10344  }
10345
10346  return false;
10347}
10348
10349