Add 'musttail' marker to call instructions
[oota-llvm.git] / lib / Target / ARM / ARMISelLowering.cpp
1 //===-- ARMISelLowering.cpp - ARM DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that ARM uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "ARMISelLowering.h"
16 #include "ARMCallingConv.h"
17 #include "ARMConstantPoolValue.h"
18 #include "ARMMachineFunctionInfo.h"
19 #include "ARMPerfectShuffle.h"
20 #include "ARMSubtarget.h"
21 #include "ARMTargetMachine.h"
22 #include "ARMTargetObjectFile.h"
23 #include "MCTargetDesc/ARMAddressingModes.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/ADT/StringExtras.h"
26 #include "llvm/CodeGen/CallingConvLower.h"
27 #include "llvm/CodeGen/IntrinsicLowering.h"
28 #include "llvm/CodeGen/MachineBasicBlock.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/MachineModuleInfo.h"
33 #include "llvm/CodeGen/MachineRegisterInfo.h"
34 #include "llvm/CodeGen/SelectionDAG.h"
35 #include "llvm/IR/CallingConv.h"
36 #include "llvm/IR/Constants.h"
37 #include "llvm/IR/Function.h"
38 #include "llvm/IR/GlobalValue.h"
39 #include "llvm/IR/IRBuilder.h"
40 #include "llvm/IR/Instruction.h"
41 #include "llvm/IR/Instructions.h"
42 #include "llvm/IR/Intrinsics.h"
43 #include "llvm/IR/Type.h"
44 #include "llvm/MC/MCSectionMachO.h"
45 #include "llvm/Support/CommandLine.h"
46 #include "llvm/Support/ErrorHandling.h"
47 #include "llvm/Support/MathExtras.h"
48 #include "llvm/Target/TargetOptions.h"
49 #include <utility>
50 using namespace llvm;
51
52 #define DEBUG_TYPE "arm-isel"
53
54 STATISTIC(NumTailCalls, "Number of tail calls");
55 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
56 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments");
57
58 cl::opt<bool>
59 EnableARMLongCalls("arm-long-calls", cl::Hidden,
60   cl::desc("Generate calls via indirect call instructions"),
61   cl::init(false));
62
63 static cl::opt<bool>
64 ARMInterworking("arm-interworking", cl::Hidden,
65   cl::desc("Enable / disable ARM interworking (for debugging only)"),
66   cl::init(true));
67
68 namespace {
69   class ARMCCState : public CCState {
70   public:
71     ARMCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
72                const TargetMachine &TM, SmallVectorImpl<CCValAssign> &locs,
73                LLVMContext &C, ParmContext PC)
74         : CCState(CC, isVarArg, MF, TM, locs, C) {
75       assert(((PC == Call) || (PC == Prologue)) &&
76              "ARMCCState users must specify whether their context is call"
77              "or prologue generation.");
78       CallOrPrologue = PC;
79     }
80   };
81 }
82
83 // The APCS parameter registers.
84 static const MCPhysReg GPRArgRegs[] = {
85   ARM::R0, ARM::R1, ARM::R2, ARM::R3
86 };
87
88 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT,
89                                        MVT PromotedBitwiseVT) {
90   if (VT != PromotedLdStVT) {
91     setOperationAction(ISD::LOAD, VT, Promote);
92     AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
93
94     setOperationAction(ISD::STORE, VT, Promote);
95     AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
96   }
97
98   MVT ElemTy = VT.getVectorElementType();
99   if (ElemTy != MVT::i64 && ElemTy != MVT::f64)
100     setOperationAction(ISD::SETCC, VT, Custom);
101   setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
102   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
103   if (ElemTy == MVT::i32) {
104     setOperationAction(ISD::SINT_TO_FP, VT, Custom);
105     setOperationAction(ISD::UINT_TO_FP, VT, Custom);
106     setOperationAction(ISD::FP_TO_SINT, VT, Custom);
107     setOperationAction(ISD::FP_TO_UINT, VT, Custom);
108   } else {
109     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
110     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
111     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
112     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
113   }
114   setOperationAction(ISD::BUILD_VECTOR,      VT, Custom);
115   setOperationAction(ISD::VECTOR_SHUFFLE,    VT, Custom);
116   setOperationAction(ISD::CONCAT_VECTORS,    VT, Legal);
117   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
118   setOperationAction(ISD::SELECT,            VT, Expand);
119   setOperationAction(ISD::SELECT_CC,         VT, Expand);
120   setOperationAction(ISD::VSELECT,           VT, Expand);
121   setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
122   if (VT.isInteger()) {
123     setOperationAction(ISD::SHL, VT, Custom);
124     setOperationAction(ISD::SRA, VT, Custom);
125     setOperationAction(ISD::SRL, VT, Custom);
126   }
127
128   // Promote all bit-wise operations.
129   if (VT.isInteger() && VT != PromotedBitwiseVT) {
130     setOperationAction(ISD::AND, VT, Promote);
131     AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT);
132     setOperationAction(ISD::OR,  VT, Promote);
133     AddPromotedToType (ISD::OR,  VT, PromotedBitwiseVT);
134     setOperationAction(ISD::XOR, VT, Promote);
135     AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT);
136   }
137
138   // Neon does not support vector divide/remainder operations.
139   setOperationAction(ISD::SDIV, VT, Expand);
140   setOperationAction(ISD::UDIV, VT, Expand);
141   setOperationAction(ISD::FDIV, VT, Expand);
142   setOperationAction(ISD::SREM, VT, Expand);
143   setOperationAction(ISD::UREM, VT, Expand);
144   setOperationAction(ISD::FREM, VT, Expand);
145 }
146
147 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
148   addRegisterClass(VT, &ARM::DPRRegClass);
149   addTypeForNEON(VT, MVT::f64, MVT::v2i32);
150 }
151
152 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
153   addRegisterClass(VT, &ARM::DPairRegClass);
154   addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
155 }
156
157 static TargetLoweringObjectFile *createTLOF(TargetMachine &TM) {
158   if (TM.getSubtarget<ARMSubtarget>().isTargetMachO())
159     return new TargetLoweringObjectFileMachO();
160
161   return new ARMElfTargetObjectFile();
162 }
163
164 ARMTargetLowering::ARMTargetLowering(TargetMachine &TM)
165     : TargetLowering(TM, createTLOF(TM)) {
166   Subtarget = &TM.getSubtarget<ARMSubtarget>();
167   RegInfo = TM.getRegisterInfo();
168   Itins = TM.getInstrItineraryData();
169
170   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
171
172   if (Subtarget->isTargetMachO()) {
173     // Uses VFP for Thumb libfuncs if available.
174     if (Subtarget->isThumb() && Subtarget->hasVFP2() &&
175         Subtarget->hasARMOps() && !TM.Options.UseSoftFloat) {
176       // Single-precision floating-point arithmetic.
177       setLibcallName(RTLIB::ADD_F32, "__addsf3vfp");
178       setLibcallName(RTLIB::SUB_F32, "__subsf3vfp");
179       setLibcallName(RTLIB::MUL_F32, "__mulsf3vfp");
180       setLibcallName(RTLIB::DIV_F32, "__divsf3vfp");
181
182       // Double-precision floating-point arithmetic.
183       setLibcallName(RTLIB::ADD_F64, "__adddf3vfp");
184       setLibcallName(RTLIB::SUB_F64, "__subdf3vfp");
185       setLibcallName(RTLIB::MUL_F64, "__muldf3vfp");
186       setLibcallName(RTLIB::DIV_F64, "__divdf3vfp");
187
188       // Single-precision comparisons.
189       setLibcallName(RTLIB::OEQ_F32, "__eqsf2vfp");
190       setLibcallName(RTLIB::UNE_F32, "__nesf2vfp");
191       setLibcallName(RTLIB::OLT_F32, "__ltsf2vfp");
192       setLibcallName(RTLIB::OLE_F32, "__lesf2vfp");
193       setLibcallName(RTLIB::OGE_F32, "__gesf2vfp");
194       setLibcallName(RTLIB::OGT_F32, "__gtsf2vfp");
195       setLibcallName(RTLIB::UO_F32,  "__unordsf2vfp");
196       setLibcallName(RTLIB::O_F32,   "__unordsf2vfp");
197
198       setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
199       setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETNE);
200       setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
201       setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
202       setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
203       setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
204       setCmpLibcallCC(RTLIB::UO_F32,  ISD::SETNE);
205       setCmpLibcallCC(RTLIB::O_F32,   ISD::SETEQ);
206
207       // Double-precision comparisons.
208       setLibcallName(RTLIB::OEQ_F64, "__eqdf2vfp");
209       setLibcallName(RTLIB::UNE_F64, "__nedf2vfp");
210       setLibcallName(RTLIB::OLT_F64, "__ltdf2vfp");
211       setLibcallName(RTLIB::OLE_F64, "__ledf2vfp");
212       setLibcallName(RTLIB::OGE_F64, "__gedf2vfp");
213       setLibcallName(RTLIB::OGT_F64, "__gtdf2vfp");
214       setLibcallName(RTLIB::UO_F64,  "__unorddf2vfp");
215       setLibcallName(RTLIB::O_F64,   "__unorddf2vfp");
216
217       setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
218       setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETNE);
219       setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
220       setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
221       setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
222       setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
223       setCmpLibcallCC(RTLIB::UO_F64,  ISD::SETNE);
224       setCmpLibcallCC(RTLIB::O_F64,   ISD::SETEQ);
225
226       // Floating-point to integer conversions.
227       // i64 conversions are done via library routines even when generating VFP
228       // instructions, so use the same ones.
229       setLibcallName(RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp");
230       setLibcallName(RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp");
231       setLibcallName(RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp");
232       setLibcallName(RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp");
233
234       // Conversions between floating types.
235       setLibcallName(RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp");
236       setLibcallName(RTLIB::FPEXT_F32_F64,   "__extendsfdf2vfp");
237
238       // Integer to floating-point conversions.
239       // i64 conversions are done via library routines even when generating VFP
240       // instructions, so use the same ones.
241       // FIXME: There appears to be some naming inconsistency in ARM libgcc:
242       // e.g., __floatunsidf vs. __floatunssidfvfp.
243       setLibcallName(RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp");
244       setLibcallName(RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp");
245       setLibcallName(RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp");
246       setLibcallName(RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp");
247     }
248   }
249
250   // These libcalls are not available in 32-bit.
251   setLibcallName(RTLIB::SHL_I128, 0);
252   setLibcallName(RTLIB::SRL_I128, 0);
253   setLibcallName(RTLIB::SRA_I128, 0);
254
255   if (Subtarget->isAAPCS_ABI() && !Subtarget->isTargetMachO() &&
256       !Subtarget->isTargetWindows()) {
257     // Double-precision floating-point arithmetic helper functions
258     // RTABI chapter 4.1.2, Table 2
259     setLibcallName(RTLIB::ADD_F64, "__aeabi_dadd");
260     setLibcallName(RTLIB::DIV_F64, "__aeabi_ddiv");
261     setLibcallName(RTLIB::MUL_F64, "__aeabi_dmul");
262     setLibcallName(RTLIB::SUB_F64, "__aeabi_dsub");
263     setLibcallCallingConv(RTLIB::ADD_F64, CallingConv::ARM_AAPCS);
264     setLibcallCallingConv(RTLIB::DIV_F64, CallingConv::ARM_AAPCS);
265     setLibcallCallingConv(RTLIB::MUL_F64, CallingConv::ARM_AAPCS);
266     setLibcallCallingConv(RTLIB::SUB_F64, CallingConv::ARM_AAPCS);
267
268     // Double-precision floating-point comparison helper functions
269     // RTABI chapter 4.1.2, Table 3
270     setLibcallName(RTLIB::OEQ_F64, "__aeabi_dcmpeq");
271     setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
272     setLibcallName(RTLIB::UNE_F64, "__aeabi_dcmpeq");
273     setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETEQ);
274     setLibcallName(RTLIB::OLT_F64, "__aeabi_dcmplt");
275     setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
276     setLibcallName(RTLIB::OLE_F64, "__aeabi_dcmple");
277     setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
278     setLibcallName(RTLIB::OGE_F64, "__aeabi_dcmpge");
279     setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
280     setLibcallName(RTLIB::OGT_F64, "__aeabi_dcmpgt");
281     setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
282     setLibcallName(RTLIB::UO_F64,  "__aeabi_dcmpun");
283     setCmpLibcallCC(RTLIB::UO_F64,  ISD::SETNE);
284     setLibcallName(RTLIB::O_F64,   "__aeabi_dcmpun");
285     setCmpLibcallCC(RTLIB::O_F64,   ISD::SETEQ);
286     setLibcallCallingConv(RTLIB::OEQ_F64, CallingConv::ARM_AAPCS);
287     setLibcallCallingConv(RTLIB::UNE_F64, CallingConv::ARM_AAPCS);
288     setLibcallCallingConv(RTLIB::OLT_F64, CallingConv::ARM_AAPCS);
289     setLibcallCallingConv(RTLIB::OLE_F64, CallingConv::ARM_AAPCS);
290     setLibcallCallingConv(RTLIB::OGE_F64, CallingConv::ARM_AAPCS);
291     setLibcallCallingConv(RTLIB::OGT_F64, CallingConv::ARM_AAPCS);
292     setLibcallCallingConv(RTLIB::UO_F64, CallingConv::ARM_AAPCS);
293     setLibcallCallingConv(RTLIB::O_F64, CallingConv::ARM_AAPCS);
294
295     // Single-precision floating-point arithmetic helper functions
296     // RTABI chapter 4.1.2, Table 4
297     setLibcallName(RTLIB::ADD_F32, "__aeabi_fadd");
298     setLibcallName(RTLIB::DIV_F32, "__aeabi_fdiv");
299     setLibcallName(RTLIB::MUL_F32, "__aeabi_fmul");
300     setLibcallName(RTLIB::SUB_F32, "__aeabi_fsub");
301     setLibcallCallingConv(RTLIB::ADD_F32, CallingConv::ARM_AAPCS);
302     setLibcallCallingConv(RTLIB::DIV_F32, CallingConv::ARM_AAPCS);
303     setLibcallCallingConv(RTLIB::MUL_F32, CallingConv::ARM_AAPCS);
304     setLibcallCallingConv(RTLIB::SUB_F32, CallingConv::ARM_AAPCS);
305
306     // Single-precision floating-point comparison helper functions
307     // RTABI chapter 4.1.2, Table 5
308     setLibcallName(RTLIB::OEQ_F32, "__aeabi_fcmpeq");
309     setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
310     setLibcallName(RTLIB::UNE_F32, "__aeabi_fcmpeq");
311     setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETEQ);
312     setLibcallName(RTLIB::OLT_F32, "__aeabi_fcmplt");
313     setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
314     setLibcallName(RTLIB::OLE_F32, "__aeabi_fcmple");
315     setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
316     setLibcallName(RTLIB::OGE_F32, "__aeabi_fcmpge");
317     setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
318     setLibcallName(RTLIB::OGT_F32, "__aeabi_fcmpgt");
319     setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
320     setLibcallName(RTLIB::UO_F32,  "__aeabi_fcmpun");
321     setCmpLibcallCC(RTLIB::UO_F32,  ISD::SETNE);
322     setLibcallName(RTLIB::O_F32,   "__aeabi_fcmpun");
323     setCmpLibcallCC(RTLIB::O_F32,   ISD::SETEQ);
324     setLibcallCallingConv(RTLIB::OEQ_F32, CallingConv::ARM_AAPCS);
325     setLibcallCallingConv(RTLIB::UNE_F32, CallingConv::ARM_AAPCS);
326     setLibcallCallingConv(RTLIB::OLT_F32, CallingConv::ARM_AAPCS);
327     setLibcallCallingConv(RTLIB::OLE_F32, CallingConv::ARM_AAPCS);
328     setLibcallCallingConv(RTLIB::OGE_F32, CallingConv::ARM_AAPCS);
329     setLibcallCallingConv(RTLIB::OGT_F32, CallingConv::ARM_AAPCS);
330     setLibcallCallingConv(RTLIB::UO_F32, CallingConv::ARM_AAPCS);
331     setLibcallCallingConv(RTLIB::O_F32, CallingConv::ARM_AAPCS);
332
333     // Floating-point to integer conversions.
334     // RTABI chapter 4.1.2, Table 6
335     setLibcallName(RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz");
336     setLibcallName(RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz");
337     setLibcallName(RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz");
338     setLibcallName(RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz");
339     setLibcallName(RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz");
340     setLibcallName(RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz");
341     setLibcallName(RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz");
342     setLibcallName(RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz");
343     setLibcallCallingConv(RTLIB::FPTOSINT_F64_I32, CallingConv::ARM_AAPCS);
344     setLibcallCallingConv(RTLIB::FPTOUINT_F64_I32, CallingConv::ARM_AAPCS);
345     setLibcallCallingConv(RTLIB::FPTOSINT_F64_I64, CallingConv::ARM_AAPCS);
346     setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::ARM_AAPCS);
347     setLibcallCallingConv(RTLIB::FPTOSINT_F32_I32, CallingConv::ARM_AAPCS);
348     setLibcallCallingConv(RTLIB::FPTOUINT_F32_I32, CallingConv::ARM_AAPCS);
349     setLibcallCallingConv(RTLIB::FPTOSINT_F32_I64, CallingConv::ARM_AAPCS);
350     setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::ARM_AAPCS);
351
352     // Conversions between floating types.
353     // RTABI chapter 4.1.2, Table 7
354     setLibcallName(RTLIB::FPROUND_F64_F32, "__aeabi_d2f");
355     setLibcallName(RTLIB::FPEXT_F32_F64,   "__aeabi_f2d");
356     setLibcallCallingConv(RTLIB::FPROUND_F64_F32, CallingConv::ARM_AAPCS);
357     setLibcallCallingConv(RTLIB::FPEXT_F32_F64, CallingConv::ARM_AAPCS);
358
359     // Integer to floating-point conversions.
360     // RTABI chapter 4.1.2, Table 8
361     setLibcallName(RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d");
362     setLibcallName(RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d");
363     setLibcallName(RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d");
364     setLibcallName(RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d");
365     setLibcallName(RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f");
366     setLibcallName(RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f");
367     setLibcallName(RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f");
368     setLibcallName(RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f");
369     setLibcallCallingConv(RTLIB::SINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
370     setLibcallCallingConv(RTLIB::UINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
371     setLibcallCallingConv(RTLIB::SINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
372     setLibcallCallingConv(RTLIB::UINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
373     setLibcallCallingConv(RTLIB::SINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
374     setLibcallCallingConv(RTLIB::UINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
375     setLibcallCallingConv(RTLIB::SINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
376     setLibcallCallingConv(RTLIB::UINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
377
378     // Long long helper functions
379     // RTABI chapter 4.2, Table 9
380     setLibcallName(RTLIB::MUL_I64,  "__aeabi_lmul");
381     setLibcallName(RTLIB::SHL_I64, "__aeabi_llsl");
382     setLibcallName(RTLIB::SRL_I64, "__aeabi_llsr");
383     setLibcallName(RTLIB::SRA_I64, "__aeabi_lasr");
384     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::ARM_AAPCS);
385     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::ARM_AAPCS);
386     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::ARM_AAPCS);
387     setLibcallCallingConv(RTLIB::SHL_I64, CallingConv::ARM_AAPCS);
388     setLibcallCallingConv(RTLIB::SRL_I64, CallingConv::ARM_AAPCS);
389     setLibcallCallingConv(RTLIB::SRA_I64, CallingConv::ARM_AAPCS);
390
391     // Integer division functions
392     // RTABI chapter 4.3.1
393     setLibcallName(RTLIB::SDIV_I8,  "__aeabi_idiv");
394     setLibcallName(RTLIB::SDIV_I16, "__aeabi_idiv");
395     setLibcallName(RTLIB::SDIV_I32, "__aeabi_idiv");
396     setLibcallName(RTLIB::SDIV_I64, "__aeabi_ldivmod");
397     setLibcallName(RTLIB::UDIV_I8,  "__aeabi_uidiv");
398     setLibcallName(RTLIB::UDIV_I16, "__aeabi_uidiv");
399     setLibcallName(RTLIB::UDIV_I32, "__aeabi_uidiv");
400     setLibcallName(RTLIB::UDIV_I64, "__aeabi_uldivmod");
401     setLibcallCallingConv(RTLIB::SDIV_I8, CallingConv::ARM_AAPCS);
402     setLibcallCallingConv(RTLIB::SDIV_I16, CallingConv::ARM_AAPCS);
403     setLibcallCallingConv(RTLIB::SDIV_I32, CallingConv::ARM_AAPCS);
404     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::ARM_AAPCS);
405     setLibcallCallingConv(RTLIB::UDIV_I8, CallingConv::ARM_AAPCS);
406     setLibcallCallingConv(RTLIB::UDIV_I16, CallingConv::ARM_AAPCS);
407     setLibcallCallingConv(RTLIB::UDIV_I32, CallingConv::ARM_AAPCS);
408     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::ARM_AAPCS);
409
410     // Memory operations
411     // RTABI chapter 4.3.4
412     setLibcallName(RTLIB::MEMCPY,  "__aeabi_memcpy");
413     setLibcallName(RTLIB::MEMMOVE, "__aeabi_memmove");
414     setLibcallName(RTLIB::MEMSET,  "__aeabi_memset");
415     setLibcallCallingConv(RTLIB::MEMCPY, CallingConv::ARM_AAPCS);
416     setLibcallCallingConv(RTLIB::MEMMOVE, CallingConv::ARM_AAPCS);
417     setLibcallCallingConv(RTLIB::MEMSET, CallingConv::ARM_AAPCS);
418   }
419
420   // Use divmod compiler-rt calls for iOS 5.0 and later.
421   if (Subtarget->getTargetTriple().isiOS() &&
422       !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) {
423     setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
424     setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
425   }
426
427   if (Subtarget->isThumb1Only())
428     addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
429   else
430     addRegisterClass(MVT::i32, &ARM::GPRRegClass);
431   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
432       !Subtarget->isThumb1Only()) {
433     addRegisterClass(MVT::f32, &ARM::SPRRegClass);
434     if (!Subtarget->isFPOnlySP())
435       addRegisterClass(MVT::f64, &ARM::DPRRegClass);
436
437     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
438   }
439
440   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
441        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
442     for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
443          InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
444       setTruncStoreAction((MVT::SimpleValueType)VT,
445                           (MVT::SimpleValueType)InnerVT, Expand);
446     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
447     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
448     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
449   }
450
451   setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
452   setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
453
454   if (Subtarget->hasNEON()) {
455     addDRTypeForNEON(MVT::v2f32);
456     addDRTypeForNEON(MVT::v8i8);
457     addDRTypeForNEON(MVT::v4i16);
458     addDRTypeForNEON(MVT::v2i32);
459     addDRTypeForNEON(MVT::v1i64);
460
461     addQRTypeForNEON(MVT::v4f32);
462     addQRTypeForNEON(MVT::v2f64);
463     addQRTypeForNEON(MVT::v16i8);
464     addQRTypeForNEON(MVT::v8i16);
465     addQRTypeForNEON(MVT::v4i32);
466     addQRTypeForNEON(MVT::v2i64);
467
468     // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
469     // neither Neon nor VFP support any arithmetic operations on it.
470     // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
471     // supported for v4f32.
472     setOperationAction(ISD::FADD, MVT::v2f64, Expand);
473     setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
474     setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
475     // FIXME: Code duplication: FDIV and FREM are expanded always, see
476     // ARMTargetLowering::addTypeForNEON method for details.
477     setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
478     setOperationAction(ISD::FREM, MVT::v2f64, Expand);
479     // FIXME: Create unittest.
480     // In another words, find a way when "copysign" appears in DAG with vector
481     // operands.
482     setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
483     // FIXME: Code duplication: SETCC has custom operation action, see
484     // ARMTargetLowering::addTypeForNEON method for details.
485     setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
486     // FIXME: Create unittest for FNEG and for FABS.
487     setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
488     setOperationAction(ISD::FABS, MVT::v2f64, Expand);
489     setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
490     setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
491     setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
492     setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
493     setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
494     setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
495     setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
496     setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
497     setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
498     setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
499     // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
500     setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
501     setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
502     setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
503     setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
504     setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
505     setOperationAction(ISD::FMA, MVT::v2f64, Expand);
506
507     setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
508     setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
509     setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
510     setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
511     setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
512     setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
513     setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
514     setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
515     setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
516     setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
517     setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
518     setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
519     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
520     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
521     setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
522
523     // Mark v2f32 intrinsics.
524     setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
525     setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
526     setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
527     setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
528     setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
529     setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
530     setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
531     setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
532     setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
533     setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
534     setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
535     setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
536     setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
537     setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
538     setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
539
540     // Neon does not support some operations on v1i64 and v2i64 types.
541     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
542     // Custom handling for some quad-vector types to detect VMULL.
543     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
544     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
545     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
546     // Custom handling for some vector types to avoid expensive expansions
547     setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
548     setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
549     setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
550     setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
551     setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
552     setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
553     // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
554     // a destination type that is wider than the source, and nor does
555     // it have a FP_TO_[SU]INT instruction with a narrower destination than
556     // source.
557     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
558     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
559     setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
560     setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
561
562     setOperationAction(ISD::FP_ROUND,   MVT::v2f32, Expand);
563     setOperationAction(ISD::FP_EXTEND,  MVT::v2f64, Expand);
564
565     // NEON does not have single instruction CTPOP for vectors with element
566     // types wider than 8-bits.  However, custom lowering can leverage the
567     // v8i8/v16i8 vcnt instruction.
568     setOperationAction(ISD::CTPOP,      MVT::v2i32, Custom);
569     setOperationAction(ISD::CTPOP,      MVT::v4i32, Custom);
570     setOperationAction(ISD::CTPOP,      MVT::v4i16, Custom);
571     setOperationAction(ISD::CTPOP,      MVT::v8i16, Custom);
572
573     // NEON only has FMA instructions as of VFP4.
574     if (!Subtarget->hasVFP4()) {
575       setOperationAction(ISD::FMA, MVT::v2f32, Expand);
576       setOperationAction(ISD::FMA, MVT::v4f32, Expand);
577     }
578
579     setTargetDAGCombine(ISD::INTRINSIC_VOID);
580     setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
581     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
582     setTargetDAGCombine(ISD::SHL);
583     setTargetDAGCombine(ISD::SRL);
584     setTargetDAGCombine(ISD::SRA);
585     setTargetDAGCombine(ISD::SIGN_EXTEND);
586     setTargetDAGCombine(ISD::ZERO_EXTEND);
587     setTargetDAGCombine(ISD::ANY_EXTEND);
588     setTargetDAGCombine(ISD::SELECT_CC);
589     setTargetDAGCombine(ISD::BUILD_VECTOR);
590     setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
591     setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
592     setTargetDAGCombine(ISD::STORE);
593     setTargetDAGCombine(ISD::FP_TO_SINT);
594     setTargetDAGCombine(ISD::FP_TO_UINT);
595     setTargetDAGCombine(ISD::FDIV);
596
597     // It is legal to extload from v4i8 to v4i16 or v4i32.
598     MVT Tys[6] = {MVT::v8i8, MVT::v4i8, MVT::v2i8,
599                   MVT::v4i16, MVT::v2i16,
600                   MVT::v2i32};
601     for (unsigned i = 0; i < 6; ++i) {
602       setLoadExtAction(ISD::EXTLOAD, Tys[i], Legal);
603       setLoadExtAction(ISD::ZEXTLOAD, Tys[i], Legal);
604       setLoadExtAction(ISD::SEXTLOAD, Tys[i], Legal);
605     }
606   }
607
608   // ARM and Thumb2 support UMLAL/SMLAL.
609   if (!Subtarget->isThumb1Only())
610     setTargetDAGCombine(ISD::ADDC);
611
612
613   computeRegisterProperties();
614
615   // ARM does not have f32 extending load.
616   setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
617
618   // ARM does not have i1 sign extending load.
619   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
620
621   // ARM supports all 4 flavors of integer indexed load / store.
622   if (!Subtarget->isThumb1Only()) {
623     for (unsigned im = (unsigned)ISD::PRE_INC;
624          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
625       setIndexedLoadAction(im,  MVT::i1,  Legal);
626       setIndexedLoadAction(im,  MVT::i8,  Legal);
627       setIndexedLoadAction(im,  MVT::i16, Legal);
628       setIndexedLoadAction(im,  MVT::i32, Legal);
629       setIndexedStoreAction(im, MVT::i1,  Legal);
630       setIndexedStoreAction(im, MVT::i8,  Legal);
631       setIndexedStoreAction(im, MVT::i16, Legal);
632       setIndexedStoreAction(im, MVT::i32, Legal);
633     }
634   }
635
636   // i64 operation support.
637   setOperationAction(ISD::MUL,     MVT::i64, Expand);
638   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
639   if (Subtarget->isThumb1Only()) {
640     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
641     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
642   }
643   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
644       || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
645     setOperationAction(ISD::MULHS, MVT::i32, Expand);
646
647   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
648   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
649   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
650   setOperationAction(ISD::SRL,       MVT::i64, Custom);
651   setOperationAction(ISD::SRA,       MVT::i64, Custom);
652
653   if (!Subtarget->isThumb1Only()) {
654     // FIXME: We should do this for Thumb1 as well.
655     setOperationAction(ISD::ADDC,    MVT::i32, Custom);
656     setOperationAction(ISD::ADDE,    MVT::i32, Custom);
657     setOperationAction(ISD::SUBC,    MVT::i32, Custom);
658     setOperationAction(ISD::SUBE,    MVT::i32, Custom);
659   }
660
661   // ARM does not have ROTL.
662   setOperationAction(ISD::ROTL,  MVT::i32, Expand);
663   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
664   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
665   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
666     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
667
668   // These just redirect to CTTZ and CTLZ on ARM.
669   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i32  , Expand);
670   setOperationAction(ISD::CTLZ_ZERO_UNDEF  , MVT::i32  , Expand);
671
672   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
673
674   // Only ARMv6 has BSWAP.
675   if (!Subtarget->hasV6Ops())
676     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
677
678   if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
679       !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
680     // These are expanded into libcalls if the cpu doesn't have HW divider.
681     setOperationAction(ISD::SDIV,  MVT::i32, Expand);
682     setOperationAction(ISD::UDIV,  MVT::i32, Expand);
683   }
684
685   // FIXME: Also set divmod for SREM on EABI
686   setOperationAction(ISD::SREM,  MVT::i32, Expand);
687   setOperationAction(ISD::UREM,  MVT::i32, Expand);
688   // Register based DivRem for AEABI (RTABI 4.2)
689   if (Subtarget->isTargetAEABI()) {
690     setLibcallName(RTLIB::SDIVREM_I8,  "__aeabi_idivmod");
691     setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod");
692     setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod");
693     setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod");
694     setLibcallName(RTLIB::UDIVREM_I8,  "__aeabi_uidivmod");
695     setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod");
696     setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod");
697     setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod");
698
699     setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS);
700     setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS);
701     setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS);
702     setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS);
703     setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS);
704     setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS);
705     setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS);
706     setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS);
707
708     setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
709     setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
710   } else {
711     setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
712     setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
713   }
714
715   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
716   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
717   setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
718   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
719   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
720
721   setOperationAction(ISD::TRAP, MVT::Other, Legal);
722
723   // Use the default implementation.
724   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
725   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
726   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
727   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
728   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
729   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
730
731   if (!Subtarget->isTargetMachO()) {
732     // Non-MachO platforms may return values in these registers via the
733     // personality function.
734     setExceptionPointerRegister(ARM::R0);
735     setExceptionSelectorRegister(ARM::R1);
736   }
737
738   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
739   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
740   // the default expansion.
741   if (Subtarget->hasAnyDataBarrier() && !Subtarget->isThumb1Only()) {
742     // ATOMIC_FENCE needs custom lowering; the others should have been expanded
743     // to ldrex/strex loops already.
744     setOperationAction(ISD::ATOMIC_FENCE,     MVT::Other, Custom);
745
746     // On v8, we have particularly efficient implementations of atomic fences
747     // if they can be combined with nearby atomic loads and stores.
748     if (!Subtarget->hasV8Ops()) {
749       // Automatically insert fences (dmb ist) around ATOMIC_SWAP etc.
750       setInsertFencesForAtomic(true);
751     }
752   } else {
753     // If there's anything we can use as a barrier, go through custom lowering
754     // for ATOMIC_FENCE.
755     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other,
756                        Subtarget->hasAnyDataBarrier() ? Custom : Expand);
757
758     // Set them all for expansion, which will force libcalls.
759     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
760     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
761     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
762     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
763     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
764     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
765     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
766     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
767     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
768     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
769     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
770     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
771     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
772     // Unordered/Monotonic case.
773     setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
774     setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
775   }
776
777   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
778
779   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
780   if (!Subtarget->hasV6Ops()) {
781     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
782     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
783   }
784   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
785
786   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
787       !Subtarget->isThumb1Only()) {
788     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
789     // iff target supports vfp2.
790     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
791     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
792   }
793
794   // We want to custom lower some of our intrinsics.
795   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
796   if (Subtarget->isTargetDarwin()) {
797     setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
798     setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
799     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
800   }
801
802   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
803   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
804   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
805   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
806   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
807   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
808   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
809   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
810   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
811
812   setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
813   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
814   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
815   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
816   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
817
818   // We don't support sin/cos/fmod/copysign/pow
819   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
820   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
821   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
822   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
823   setOperationAction(ISD::FSINCOS,   MVT::f64, Expand);
824   setOperationAction(ISD::FSINCOS,   MVT::f32, Expand);
825   setOperationAction(ISD::FREM,      MVT::f64, Expand);
826   setOperationAction(ISD::FREM,      MVT::f32, Expand);
827   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
828       !Subtarget->isThumb1Only()) {
829     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
830     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
831   }
832   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
833   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
834
835   if (!Subtarget->hasVFP4()) {
836     setOperationAction(ISD::FMA, MVT::f64, Expand);
837     setOperationAction(ISD::FMA, MVT::f32, Expand);
838   }
839
840   // Various VFP goodness
841   if (!TM.Options.UseSoftFloat && !Subtarget->isThumb1Only()) {
842     // int <-> fp are custom expanded into bit_convert + ARMISD ops.
843     if (Subtarget->hasVFP2()) {
844       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
845       setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
846       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
847       setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
848     }
849     // Special handling for half-precision FP.
850     if (!Subtarget->hasFP16()) {
851       setOperationAction(ISD::FP16_TO_FP32, MVT::f32, Expand);
852       setOperationAction(ISD::FP32_TO_FP16, MVT::i32, Expand);
853     }
854   }
855
856   // Combine sin / cos into one node or libcall if possible.
857   if (Subtarget->hasSinCos()) {
858     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
859     setLibcallName(RTLIB::SINCOS_F64, "sincos");
860     if (Subtarget->getTargetTriple().getOS() == Triple::IOS) {
861       // For iOS, we don't want to the normal expansion of a libcall to
862       // sincos. We want to issue a libcall to __sincos_stret.
863       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
864       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
865     }
866   }
867
868   // We have target-specific dag combine patterns for the following nodes:
869   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
870   setTargetDAGCombine(ISD::ADD);
871   setTargetDAGCombine(ISD::SUB);
872   setTargetDAGCombine(ISD::MUL);
873   setTargetDAGCombine(ISD::AND);
874   setTargetDAGCombine(ISD::OR);
875   setTargetDAGCombine(ISD::XOR);
876
877   if (Subtarget->hasV6Ops())
878     setTargetDAGCombine(ISD::SRL);
879
880   setStackPointerRegisterToSaveRestore(ARM::SP);
881
882   if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
883       !Subtarget->hasVFP2())
884     setSchedulingPreference(Sched::RegPressure);
885   else
886     setSchedulingPreference(Sched::Hybrid);
887
888   //// temporary - rewrite interface to use type
889   MaxStoresPerMemset = 8;
890   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
891   MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
892   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
893   MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
894   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
895
896   // On ARM arguments smaller than 4 bytes are extended, so all arguments
897   // are at least 4 bytes aligned.
898   setMinStackArgumentAlignment(4);
899
900   // Prefer likely predicted branches to selects on out-of-order cores.
901   PredictableSelectIsExpensive = Subtarget->isLikeA9();
902
903   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
904 }
905
906 // FIXME: It might make sense to define the representative register class as the
907 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
908 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
909 // SPR's representative would be DPR_VFP2. This should work well if register
910 // pressure tracking were modified such that a register use would increment the
911 // pressure of the register class's representative and all of it's super
912 // classes' representatives transitively. We have not implemented this because
913 // of the difficulty prior to coalescing of modeling operand register classes
914 // due to the common occurrence of cross class copies and subregister insertions
915 // and extractions.
916 std::pair<const TargetRegisterClass*, uint8_t>
917 ARMTargetLowering::findRepresentativeClass(MVT VT) const{
918   const TargetRegisterClass *RRC = 0;
919   uint8_t Cost = 1;
920   switch (VT.SimpleTy) {
921   default:
922     return TargetLowering::findRepresentativeClass(VT);
923   // Use DPR as representative register class for all floating point
924   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
925   // the cost is 1 for both f32 and f64.
926   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
927   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
928     RRC = &ARM::DPRRegClass;
929     // When NEON is used for SP, only half of the register file is available
930     // because operations that define both SP and DP results will be constrained
931     // to the VFP2 class (D0-D15). We currently model this constraint prior to
932     // coalescing by double-counting the SP regs. See the FIXME above.
933     if (Subtarget->useNEONForSinglePrecisionFP())
934       Cost = 2;
935     break;
936   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
937   case MVT::v4f32: case MVT::v2f64:
938     RRC = &ARM::DPRRegClass;
939     Cost = 2;
940     break;
941   case MVT::v4i64:
942     RRC = &ARM::DPRRegClass;
943     Cost = 4;
944     break;
945   case MVT::v8i64:
946     RRC = &ARM::DPRRegClass;
947     Cost = 8;
948     break;
949   }
950   return std::make_pair(RRC, Cost);
951 }
952
953 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
954   switch (Opcode) {
955   default: return 0;
956   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
957   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
958   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
959   case ARMISD::CALL:          return "ARMISD::CALL";
960   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
961   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
962   case ARMISD::tCALL:         return "ARMISD::tCALL";
963   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
964   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
965   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
966   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
967   case ARMISD::INTRET_FLAG:   return "ARMISD::INTRET_FLAG";
968   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
969   case ARMISD::CMP:           return "ARMISD::CMP";
970   case ARMISD::CMN:           return "ARMISD::CMN";
971   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
972   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
973   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
974   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
975   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
976
977   case ARMISD::CMOV:          return "ARMISD::CMOV";
978
979   case ARMISD::RBIT:          return "ARMISD::RBIT";
980
981   case ARMISD::FTOSI:         return "ARMISD::FTOSI";
982   case ARMISD::FTOUI:         return "ARMISD::FTOUI";
983   case ARMISD::SITOF:         return "ARMISD::SITOF";
984   case ARMISD::UITOF:         return "ARMISD::UITOF";
985
986   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
987   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
988   case ARMISD::RRX:           return "ARMISD::RRX";
989
990   case ARMISD::ADDC:          return "ARMISD::ADDC";
991   case ARMISD::ADDE:          return "ARMISD::ADDE";
992   case ARMISD::SUBC:          return "ARMISD::SUBC";
993   case ARMISD::SUBE:          return "ARMISD::SUBE";
994
995   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
996   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
997
998   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
999   case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
1000
1001   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
1002
1003   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1004
1005   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
1006
1007   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1008
1009   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
1010
1011   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
1012   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
1013   case ARMISD::VCGE:          return "ARMISD::VCGE";
1014   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
1015   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
1016   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
1017   case ARMISD::VCGT:          return "ARMISD::VCGT";
1018   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
1019   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
1020   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
1021   case ARMISD::VTST:          return "ARMISD::VTST";
1022
1023   case ARMISD::VSHL:          return "ARMISD::VSHL";
1024   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
1025   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
1026   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
1027   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
1028   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
1029   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
1030   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
1031   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
1032   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
1033   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
1034   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
1035   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
1036   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
1037   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
1038   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
1039   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
1040   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
1041   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
1042   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
1043   case ARMISD::VDUP:          return "ARMISD::VDUP";
1044   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
1045   case ARMISD::VEXT:          return "ARMISD::VEXT";
1046   case ARMISD::VREV64:        return "ARMISD::VREV64";
1047   case ARMISD::VREV32:        return "ARMISD::VREV32";
1048   case ARMISD::VREV16:        return "ARMISD::VREV16";
1049   case ARMISD::VZIP:          return "ARMISD::VZIP";
1050   case ARMISD::VUZP:          return "ARMISD::VUZP";
1051   case ARMISD::VTRN:          return "ARMISD::VTRN";
1052   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
1053   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
1054   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
1055   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
1056   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
1057   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
1058   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
1059   case ARMISD::FMAX:          return "ARMISD::FMAX";
1060   case ARMISD::FMIN:          return "ARMISD::FMIN";
1061   case ARMISD::VMAXNM:        return "ARMISD::VMAX";
1062   case ARMISD::VMINNM:        return "ARMISD::VMIN";
1063   case ARMISD::BFI:           return "ARMISD::BFI";
1064   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
1065   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
1066   case ARMISD::VBSL:          return "ARMISD::VBSL";
1067   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1068   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1069   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1070   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1071   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1072   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1073   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1074   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1075   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1076   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1077   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1078   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1079   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1080   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1081   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1082   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1083   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1084   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1085   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1086   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1087   }
1088 }
1089
1090 EVT ARMTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1091   if (!VT.isVector()) return getPointerTy();
1092   return VT.changeVectorElementTypeToInteger();
1093 }
1094
1095 /// getRegClassFor - Return the register class that should be used for the
1096 /// specified value type.
1097 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1098   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1099   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1100   // load / store 4 to 8 consecutive D registers.
1101   if (Subtarget->hasNEON()) {
1102     if (VT == MVT::v4i64)
1103       return &ARM::QQPRRegClass;
1104     if (VT == MVT::v8i64)
1105       return &ARM::QQQQPRRegClass;
1106   }
1107   return TargetLowering::getRegClassFor(VT);
1108 }
1109
1110 // Create a fast isel object.
1111 FastISel *
1112 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1113                                   const TargetLibraryInfo *libInfo) const {
1114   return ARM::createFastISel(funcInfo, libInfo);
1115 }
1116
1117 /// getMaximalGlobalOffset - Returns the maximal possible offset which can
1118 /// be used for loads / stores from the global.
1119 unsigned ARMTargetLowering::getMaximalGlobalOffset() const {
1120   return (Subtarget->isThumb1Only() ? 127 : 4095);
1121 }
1122
1123 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1124   unsigned NumVals = N->getNumValues();
1125   if (!NumVals)
1126     return Sched::RegPressure;
1127
1128   for (unsigned i = 0; i != NumVals; ++i) {
1129     EVT VT = N->getValueType(i);
1130     if (VT == MVT::Glue || VT == MVT::Other)
1131       continue;
1132     if (VT.isFloatingPoint() || VT.isVector())
1133       return Sched::ILP;
1134   }
1135
1136   if (!N->isMachineOpcode())
1137     return Sched::RegPressure;
1138
1139   // Load are scheduled for latency even if there instruction itinerary
1140   // is not available.
1141   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1142   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1143
1144   if (MCID.getNumDefs() == 0)
1145     return Sched::RegPressure;
1146   if (!Itins->isEmpty() &&
1147       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1148     return Sched::ILP;
1149
1150   return Sched::RegPressure;
1151 }
1152
1153 //===----------------------------------------------------------------------===//
1154 // Lowering Code
1155 //===----------------------------------------------------------------------===//
1156
1157 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1158 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1159   switch (CC) {
1160   default: llvm_unreachable("Unknown condition code!");
1161   case ISD::SETNE:  return ARMCC::NE;
1162   case ISD::SETEQ:  return ARMCC::EQ;
1163   case ISD::SETGT:  return ARMCC::GT;
1164   case ISD::SETGE:  return ARMCC::GE;
1165   case ISD::SETLT:  return ARMCC::LT;
1166   case ISD::SETLE:  return ARMCC::LE;
1167   case ISD::SETUGT: return ARMCC::HI;
1168   case ISD::SETUGE: return ARMCC::HS;
1169   case ISD::SETULT: return ARMCC::LO;
1170   case ISD::SETULE: return ARMCC::LS;
1171   }
1172 }
1173
1174 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1175 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1176                         ARMCC::CondCodes &CondCode2) {
1177   CondCode2 = ARMCC::AL;
1178   switch (CC) {
1179   default: llvm_unreachable("Unknown FP condition!");
1180   case ISD::SETEQ:
1181   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1182   case ISD::SETGT:
1183   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1184   case ISD::SETGE:
1185   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1186   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1187   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1188   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1189   case ISD::SETO:   CondCode = ARMCC::VC; break;
1190   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1191   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1192   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1193   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1194   case ISD::SETLT:
1195   case ISD::SETULT: CondCode = ARMCC::LT; break;
1196   case ISD::SETLE:
1197   case ISD::SETULE: CondCode = ARMCC::LE; break;
1198   case ISD::SETNE:
1199   case ISD::SETUNE: CondCode = ARMCC::NE; break;
1200   }
1201 }
1202
1203 //===----------------------------------------------------------------------===//
1204 //                      Calling Convention Implementation
1205 //===----------------------------------------------------------------------===//
1206
1207 #include "ARMGenCallingConv.inc"
1208
1209 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1210 /// given CallingConvention value.
1211 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1212                                                  bool Return,
1213                                                  bool isVarArg) const {
1214   switch (CC) {
1215   default:
1216     llvm_unreachable("Unsupported calling convention");
1217   case CallingConv::Fast:
1218     if (Subtarget->hasVFP2() && !isVarArg) {
1219       if (!Subtarget->isAAPCS_ABI())
1220         return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1221       // For AAPCS ABI targets, just use VFP variant of the calling convention.
1222       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1223     }
1224     // Fallthrough
1225   case CallingConv::C: {
1226     // Use target triple & subtarget features to do actual dispatch.
1227     if (!Subtarget->isAAPCS_ABI())
1228       return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1229     else if (Subtarget->hasVFP2() &&
1230              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1231              !isVarArg)
1232       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1233     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1234   }
1235   case CallingConv::ARM_AAPCS_VFP:
1236     if (!isVarArg)
1237       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1238     // Fallthrough
1239   case CallingConv::ARM_AAPCS:
1240     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1241   case CallingConv::ARM_APCS:
1242     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1243   case CallingConv::GHC:
1244     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1245   }
1246 }
1247
1248 /// LowerCallResult - Lower the result values of a call into the
1249 /// appropriate copies out of appropriate physical registers.
1250 SDValue
1251 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1252                                    CallingConv::ID CallConv, bool isVarArg,
1253                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1254                                    SDLoc dl, SelectionDAG &DAG,
1255                                    SmallVectorImpl<SDValue> &InVals,
1256                                    bool isThisReturn, SDValue ThisVal) const {
1257
1258   // Assign locations to each value returned by this call.
1259   SmallVector<CCValAssign, 16> RVLocs;
1260   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1261                     getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1262   CCInfo.AnalyzeCallResult(Ins,
1263                            CCAssignFnForNode(CallConv, /* Return*/ true,
1264                                              isVarArg));
1265
1266   // Copy all of the result registers out of their specified physreg.
1267   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1268     CCValAssign VA = RVLocs[i];
1269
1270     // Pass 'this' value directly from the argument to return value, to avoid
1271     // reg unit interference
1272     if (i == 0 && isThisReturn) {
1273       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1274              "unexpected return calling convention register assignment");
1275       InVals.push_back(ThisVal);
1276       continue;
1277     }
1278
1279     SDValue Val;
1280     if (VA.needsCustom()) {
1281       // Handle f64 or half of a v2f64.
1282       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1283                                       InFlag);
1284       Chain = Lo.getValue(1);
1285       InFlag = Lo.getValue(2);
1286       VA = RVLocs[++i]; // skip ahead to next loc
1287       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1288                                       InFlag);
1289       Chain = Hi.getValue(1);
1290       InFlag = Hi.getValue(2);
1291       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1292
1293       if (VA.getLocVT() == MVT::v2f64) {
1294         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1295         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1296                           DAG.getConstant(0, MVT::i32));
1297
1298         VA = RVLocs[++i]; // skip ahead to next loc
1299         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1300         Chain = Lo.getValue(1);
1301         InFlag = Lo.getValue(2);
1302         VA = RVLocs[++i]; // skip ahead to next loc
1303         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1304         Chain = Hi.getValue(1);
1305         InFlag = Hi.getValue(2);
1306         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1307         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1308                           DAG.getConstant(1, MVT::i32));
1309       }
1310     } else {
1311       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1312                                InFlag);
1313       Chain = Val.getValue(1);
1314       InFlag = Val.getValue(2);
1315     }
1316
1317     switch (VA.getLocInfo()) {
1318     default: llvm_unreachable("Unknown loc info!");
1319     case CCValAssign::Full: break;
1320     case CCValAssign::BCvt:
1321       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1322       break;
1323     }
1324
1325     InVals.push_back(Val);
1326   }
1327
1328   return Chain;
1329 }
1330
1331 /// LowerMemOpCallTo - Store the argument to the stack.
1332 SDValue
1333 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1334                                     SDValue StackPtr, SDValue Arg,
1335                                     SDLoc dl, SelectionDAG &DAG,
1336                                     const CCValAssign &VA,
1337                                     ISD::ArgFlagsTy Flags) const {
1338   unsigned LocMemOffset = VA.getLocMemOffset();
1339   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1340   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1341   return DAG.getStore(Chain, dl, Arg, PtrOff,
1342                       MachinePointerInfo::getStack(LocMemOffset),
1343                       false, false, 0);
1344 }
1345
1346 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1347                                          SDValue Chain, SDValue &Arg,
1348                                          RegsToPassVector &RegsToPass,
1349                                          CCValAssign &VA, CCValAssign &NextVA,
1350                                          SDValue &StackPtr,
1351                                          SmallVectorImpl<SDValue> &MemOpChains,
1352                                          ISD::ArgFlagsTy Flags) const {
1353
1354   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1355                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1356   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd));
1357
1358   if (NextVA.isRegLoc())
1359     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1)));
1360   else {
1361     assert(NextVA.isMemLoc());
1362     if (StackPtr.getNode() == 0)
1363       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1364
1365     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1),
1366                                            dl, DAG, NextVA,
1367                                            Flags));
1368   }
1369 }
1370
1371 /// LowerCall - Lowering a call into a callseq_start <-
1372 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1373 /// nodes.
1374 SDValue
1375 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1376                              SmallVectorImpl<SDValue> &InVals) const {
1377   SelectionDAG &DAG                     = CLI.DAG;
1378   SDLoc &dl                          = CLI.DL;
1379   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1380   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
1381   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
1382   SDValue Chain                         = CLI.Chain;
1383   SDValue Callee                        = CLI.Callee;
1384   bool &isTailCall                      = CLI.IsTailCall;
1385   CallingConv::ID CallConv              = CLI.CallConv;
1386   bool doesNotRet                       = CLI.DoesNotReturn;
1387   bool isVarArg                         = CLI.IsVarArg;
1388
1389   MachineFunction &MF = DAG.getMachineFunction();
1390   bool isStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1391   bool isThisReturn   = false;
1392   bool isSibCall      = false;
1393
1394   // Disable tail calls if they're not supported.
1395   if (!Subtarget->supportsTailCall() || MF.getTarget().Options.DisableTailCalls)
1396     isTailCall = false;
1397
1398   if (isTailCall) {
1399     // Check if it's really possible to do a tail call.
1400     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1401                     isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1402                                                    Outs, OutVals, Ins, DAG);
1403     if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
1404       report_fatal_error("failed to perform tail call elimination on a call "
1405                          "site marked musttail");
1406     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1407     // detected sibcalls.
1408     if (isTailCall) {
1409       ++NumTailCalls;
1410       isSibCall = true;
1411     }
1412   }
1413
1414   // Analyze operands of the call, assigning locations to each operand.
1415   SmallVector<CCValAssign, 16> ArgLocs;
1416   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1417                  getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1418   CCInfo.AnalyzeCallOperands(Outs,
1419                              CCAssignFnForNode(CallConv, /* Return*/ false,
1420                                                isVarArg));
1421
1422   // Get a count of how many bytes are to be pushed on the stack.
1423   unsigned NumBytes = CCInfo.getNextStackOffset();
1424
1425   // For tail calls, memory operands are available in our caller's stack.
1426   if (isSibCall)
1427     NumBytes = 0;
1428
1429   // Adjust the stack pointer for the new arguments...
1430   // These operations are automatically eliminated by the prolog/epilog pass
1431   if (!isSibCall)
1432     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
1433                                  dl);
1434
1435   SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1436
1437   RegsToPassVector RegsToPass;
1438   SmallVector<SDValue, 8> MemOpChains;
1439
1440   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1441   // of tail call optimization, arguments are handled later.
1442   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1443        i != e;
1444        ++i, ++realArgIdx) {
1445     CCValAssign &VA = ArgLocs[i];
1446     SDValue Arg = OutVals[realArgIdx];
1447     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1448     bool isByVal = Flags.isByVal();
1449
1450     // Promote the value if needed.
1451     switch (VA.getLocInfo()) {
1452     default: llvm_unreachable("Unknown loc info!");
1453     case CCValAssign::Full: break;
1454     case CCValAssign::SExt:
1455       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1456       break;
1457     case CCValAssign::ZExt:
1458       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1459       break;
1460     case CCValAssign::AExt:
1461       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1462       break;
1463     case CCValAssign::BCvt:
1464       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1465       break;
1466     }
1467
1468     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1469     if (VA.needsCustom()) {
1470       if (VA.getLocVT() == MVT::v2f64) {
1471         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1472                                   DAG.getConstant(0, MVT::i32));
1473         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1474                                   DAG.getConstant(1, MVT::i32));
1475
1476         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1477                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1478
1479         VA = ArgLocs[++i]; // skip ahead to next loc
1480         if (VA.isRegLoc()) {
1481           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1482                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1483         } else {
1484           assert(VA.isMemLoc());
1485
1486           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1487                                                  dl, DAG, VA, Flags));
1488         }
1489       } else {
1490         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1491                          StackPtr, MemOpChains, Flags);
1492       }
1493     } else if (VA.isRegLoc()) {
1494       if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1495         assert(VA.getLocVT() == MVT::i32 &&
1496                "unexpected calling convention register assignment");
1497         assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1498                "unexpected use of 'returned'");
1499         isThisReturn = true;
1500       }
1501       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1502     } else if (isByVal) {
1503       assert(VA.isMemLoc());
1504       unsigned offset = 0;
1505
1506       // True if this byval aggregate will be split between registers
1507       // and memory.
1508       unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1509       unsigned CurByValIdx = CCInfo.getInRegsParamsProceed();
1510
1511       if (CurByValIdx < ByValArgsCount) {
1512
1513         unsigned RegBegin, RegEnd;
1514         CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1515
1516         EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1517         unsigned int i, j;
1518         for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1519           SDValue Const = DAG.getConstant(4*i, MVT::i32);
1520           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1521           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1522                                      MachinePointerInfo(),
1523                                      false, false, false,
1524                                      DAG.InferPtrAlignment(AddArg));
1525           MemOpChains.push_back(Load.getValue(1));
1526           RegsToPass.push_back(std::make_pair(j, Load));
1527         }
1528
1529         // If parameter size outsides register area, "offset" value
1530         // helps us to calculate stack slot for remained part properly.
1531         offset = RegEnd - RegBegin;
1532
1533         CCInfo.nextInRegsParam();
1534       }
1535
1536       if (Flags.getByValSize() > 4*offset) {
1537         unsigned LocMemOffset = VA.getLocMemOffset();
1538         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1539         SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1540                                   StkPtrOff);
1541         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1542         SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1543         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1544                                            MVT::i32);
1545         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), MVT::i32);
1546
1547         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1548         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1549         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1550                                           Ops, array_lengthof(Ops)));
1551       }
1552     } else if (!isSibCall) {
1553       assert(VA.isMemLoc());
1554
1555       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1556                                              dl, DAG, VA, Flags));
1557     }
1558   }
1559
1560   if (!MemOpChains.empty())
1561     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1562                         &MemOpChains[0], MemOpChains.size());
1563
1564   // Build a sequence of copy-to-reg nodes chained together with token chain
1565   // and flag operands which copy the outgoing args into the appropriate regs.
1566   SDValue InFlag;
1567   // Tail call byval lowering might overwrite argument registers so in case of
1568   // tail call optimization the copies to registers are lowered later.
1569   if (!isTailCall)
1570     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1571       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1572                                RegsToPass[i].second, InFlag);
1573       InFlag = Chain.getValue(1);
1574     }
1575
1576   // For tail calls lower the arguments to the 'real' stack slot.
1577   if (isTailCall) {
1578     // Force all the incoming stack arguments to be loaded from the stack
1579     // before any new outgoing arguments are stored to the stack, because the
1580     // outgoing stack slots may alias the incoming argument stack slots, and
1581     // the alias isn't otherwise explicit. This is slightly more conservative
1582     // than necessary, because it means that each store effectively depends
1583     // on every argument instead of just those arguments it would clobber.
1584
1585     // Do not flag preceding copytoreg stuff together with the following stuff.
1586     InFlag = SDValue();
1587     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1588       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1589                                RegsToPass[i].second, InFlag);
1590       InFlag = Chain.getValue(1);
1591     }
1592     InFlag = SDValue();
1593   }
1594
1595   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1596   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1597   // node so that legalize doesn't hack it.
1598   bool isDirect = false;
1599   bool isARMFunc = false;
1600   bool isLocalARMFunc = false;
1601   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1602
1603   if (EnableARMLongCalls) {
1604     assert (getTargetMachine().getRelocationModel() == Reloc::Static
1605             && "long-calls with non-static relocation model!");
1606     // Handle a global address or an external symbol. If it's not one of
1607     // those, the target's already in a register, so we don't need to do
1608     // anything extra.
1609     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1610       const GlobalValue *GV = G->getGlobal();
1611       // Create a constant pool entry for the callee address
1612       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1613       ARMConstantPoolValue *CPV =
1614         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1615
1616       // Get the address of the callee into a register
1617       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1618       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1619       Callee = DAG.getLoad(getPointerTy(), dl,
1620                            DAG.getEntryNode(), CPAddr,
1621                            MachinePointerInfo::getConstantPool(),
1622                            false, false, false, 0);
1623     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1624       const char *Sym = S->getSymbol();
1625
1626       // Create a constant pool entry for the callee address
1627       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1628       ARMConstantPoolValue *CPV =
1629         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1630                                       ARMPCLabelIndex, 0);
1631       // Get the address of the callee into a register
1632       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1633       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1634       Callee = DAG.getLoad(getPointerTy(), dl,
1635                            DAG.getEntryNode(), CPAddr,
1636                            MachinePointerInfo::getConstantPool(),
1637                            false, false, false, 0);
1638     }
1639   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1640     const GlobalValue *GV = G->getGlobal();
1641     isDirect = true;
1642     bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1643     bool isStub = (isExt && Subtarget->isTargetMachO()) &&
1644                    getTargetMachine().getRelocationModel() != Reloc::Static;
1645     isARMFunc = !Subtarget->isThumb() || isStub;
1646     // ARM call to a local ARM function is predicable.
1647     isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1648     // tBX takes a register source operand.
1649     if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1650       assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
1651       Callee = DAG.getNode(ARMISD::WrapperPIC, dl, getPointerTy(),
1652                            DAG.getTargetGlobalAddress(GV, dl, getPointerTy()));
1653     } else {
1654       // On ELF targets for PIC code, direct calls should go through the PLT
1655       unsigned OpFlags = 0;
1656       if (Subtarget->isTargetELF() &&
1657           getTargetMachine().getRelocationModel() == Reloc::PIC_)
1658         OpFlags = ARMII::MO_PLT;
1659       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1660     }
1661   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1662     isDirect = true;
1663     bool isStub = Subtarget->isTargetMachO() &&
1664                   getTargetMachine().getRelocationModel() != Reloc::Static;
1665     isARMFunc = !Subtarget->isThumb() || isStub;
1666     // tBX takes a register source operand.
1667     const char *Sym = S->getSymbol();
1668     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1669       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1670       ARMConstantPoolValue *CPV =
1671         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1672                                       ARMPCLabelIndex, 4);
1673       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1674       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1675       Callee = DAG.getLoad(getPointerTy(), dl,
1676                            DAG.getEntryNode(), CPAddr,
1677                            MachinePointerInfo::getConstantPool(),
1678                            false, false, false, 0);
1679       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1680       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1681                            getPointerTy(), Callee, PICLabel);
1682     } else {
1683       unsigned OpFlags = 0;
1684       // On ELF targets for PIC code, direct calls should go through the PLT
1685       if (Subtarget->isTargetELF() &&
1686                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1687         OpFlags = ARMII::MO_PLT;
1688       Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1689     }
1690   }
1691
1692   // FIXME: handle tail calls differently.
1693   unsigned CallOpc;
1694   bool HasMinSizeAttr = Subtarget->isMinSize();
1695   if (Subtarget->isThumb()) {
1696     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1697       CallOpc = ARMISD::CALL_NOLINK;
1698     else
1699       CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1700   } else {
1701     if (!isDirect && !Subtarget->hasV5TOps())
1702       CallOpc = ARMISD::CALL_NOLINK;
1703     else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1704                // Emit regular call when code size is the priority
1705                !HasMinSizeAttr)
1706       // "mov lr, pc; b _foo" to avoid confusing the RSP
1707       CallOpc = ARMISD::CALL_NOLINK;
1708     else
1709       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1710   }
1711
1712   std::vector<SDValue> Ops;
1713   Ops.push_back(Chain);
1714   Ops.push_back(Callee);
1715
1716   // Add argument registers to the end of the list so that they are known live
1717   // into the call.
1718   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1719     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1720                                   RegsToPass[i].second.getValueType()));
1721
1722   // Add a register mask operand representing the call-preserved registers.
1723   if (!isTailCall) {
1724     const uint32_t *Mask;
1725     const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
1726     const ARMBaseRegisterInfo *ARI = static_cast<const ARMBaseRegisterInfo*>(TRI);
1727     if (isThisReturn) {
1728       // For 'this' returns, use the R0-preserving mask if applicable
1729       Mask = ARI->getThisReturnPreservedMask(CallConv);
1730       if (!Mask) {
1731         // Set isThisReturn to false if the calling convention is not one that
1732         // allows 'returned' to be modeled in this way, so LowerCallResult does
1733         // not try to pass 'this' straight through
1734         isThisReturn = false;
1735         Mask = ARI->getCallPreservedMask(CallConv);
1736       }
1737     } else
1738       Mask = ARI->getCallPreservedMask(CallConv);
1739
1740     assert(Mask && "Missing call preserved mask for calling convention");
1741     Ops.push_back(DAG.getRegisterMask(Mask));
1742   }
1743
1744   if (InFlag.getNode())
1745     Ops.push_back(InFlag);
1746
1747   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1748   if (isTailCall)
1749     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
1750
1751   // Returns a chain and a flag for retval copy to use.
1752   Chain = DAG.getNode(CallOpc, dl, NodeTys, &Ops[0], Ops.size());
1753   InFlag = Chain.getValue(1);
1754
1755   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1756                              DAG.getIntPtrConstant(0, true), InFlag, dl);
1757   if (!Ins.empty())
1758     InFlag = Chain.getValue(1);
1759
1760   // Handle result values, copying them out of physregs into vregs that we
1761   // return.
1762   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1763                          InVals, isThisReturn,
1764                          isThisReturn ? OutVals[0] : SDValue());
1765 }
1766
1767 /// HandleByVal - Every parameter *after* a byval parameter is passed
1768 /// on the stack.  Remember the next parameter register to allocate,
1769 /// and then confiscate the rest of the parameter registers to insure
1770 /// this.
1771 void
1772 ARMTargetLowering::HandleByVal(
1773     CCState *State, unsigned &size, unsigned Align) const {
1774   unsigned reg = State->AllocateReg(GPRArgRegs, 4);
1775   assert((State->getCallOrPrologue() == Prologue ||
1776           State->getCallOrPrologue() == Call) &&
1777          "unhandled ParmContext");
1778
1779   if ((ARM::R0 <= reg) && (reg <= ARM::R3)) {
1780     if (Subtarget->isAAPCS_ABI() && Align > 4) {
1781       unsigned AlignInRegs = Align / 4;
1782       unsigned Waste = (ARM::R4 - reg) % AlignInRegs;
1783       for (unsigned i = 0; i < Waste; ++i)
1784         reg = State->AllocateReg(GPRArgRegs, 4);
1785     }
1786     if (reg != 0) {
1787       unsigned excess = 4 * (ARM::R4 - reg);
1788
1789       // Special case when NSAA != SP and parameter size greater than size of
1790       // all remained GPR regs. In that case we can't split parameter, we must
1791       // send it to stack. We also must set NCRN to R4, so waste all
1792       // remained registers.
1793       const unsigned NSAAOffset = State->getNextStackOffset();
1794       if (Subtarget->isAAPCS_ABI() && NSAAOffset != 0 && size > excess) {
1795         while (State->AllocateReg(GPRArgRegs, 4))
1796           ;
1797         return;
1798       }
1799
1800       // First register for byval parameter is the first register that wasn't
1801       // allocated before this method call, so it would be "reg".
1802       // If parameter is small enough to be saved in range [reg, r4), then
1803       // the end (first after last) register would be reg + param-size-in-regs,
1804       // else parameter would be splitted between registers and stack,
1805       // end register would be r4 in this case.
1806       unsigned ByValRegBegin = reg;
1807       unsigned ByValRegEnd = (size < excess) ? reg + size/4 : (unsigned)ARM::R4;
1808       State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1809       // Note, first register is allocated in the beginning of function already,
1810       // allocate remained amount of registers we need.
1811       for (unsigned i = reg+1; i != ByValRegEnd; ++i)
1812         State->AllocateReg(GPRArgRegs, 4);
1813       // A byval parameter that is split between registers and memory needs its
1814       // size truncated here.
1815       // In the case where the entire structure fits in registers, we set the
1816       // size in memory to zero.
1817       if (size < excess)
1818         size = 0;
1819       else
1820         size -= excess;
1821     }
1822   }
1823 }
1824
1825 /// MatchingStackOffset - Return true if the given stack call argument is
1826 /// already available in the same position (relatively) of the caller's
1827 /// incoming argument stack.
1828 static
1829 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1830                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1831                          const TargetInstrInfo *TII) {
1832   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1833   int FI = INT_MAX;
1834   if (Arg.getOpcode() == ISD::CopyFromReg) {
1835     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1836     if (!TargetRegisterInfo::isVirtualRegister(VR))
1837       return false;
1838     MachineInstr *Def = MRI->getVRegDef(VR);
1839     if (!Def)
1840       return false;
1841     if (!Flags.isByVal()) {
1842       if (!TII->isLoadFromStackSlot(Def, FI))
1843         return false;
1844     } else {
1845       return false;
1846     }
1847   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1848     if (Flags.isByVal())
1849       // ByVal argument is passed in as a pointer but it's now being
1850       // dereferenced. e.g.
1851       // define @foo(%struct.X* %A) {
1852       //   tail call @bar(%struct.X* byval %A)
1853       // }
1854       return false;
1855     SDValue Ptr = Ld->getBasePtr();
1856     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1857     if (!FINode)
1858       return false;
1859     FI = FINode->getIndex();
1860   } else
1861     return false;
1862
1863   assert(FI != INT_MAX);
1864   if (!MFI->isFixedObjectIndex(FI))
1865     return false;
1866   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1867 }
1868
1869 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1870 /// for tail call optimization. Targets which want to do tail call
1871 /// optimization should implement this function.
1872 bool
1873 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1874                                                      CallingConv::ID CalleeCC,
1875                                                      bool isVarArg,
1876                                                      bool isCalleeStructRet,
1877                                                      bool isCallerStructRet,
1878                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
1879                                     const SmallVectorImpl<SDValue> &OutVals,
1880                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1881                                                      SelectionDAG& DAG) const {
1882   const Function *CallerF = DAG.getMachineFunction().getFunction();
1883   CallingConv::ID CallerCC = CallerF->getCallingConv();
1884   bool CCMatch = CallerCC == CalleeCC;
1885
1886   // Look for obvious safe cases to perform tail call optimization that do not
1887   // require ABI changes. This is what gcc calls sibcall.
1888
1889   // Do not sibcall optimize vararg calls unless the call site is not passing
1890   // any arguments.
1891   if (isVarArg && !Outs.empty())
1892     return false;
1893
1894   // Exception-handling functions need a special set of instructions to indicate
1895   // a return to the hardware. Tail-calling another function would probably
1896   // break this.
1897   if (CallerF->hasFnAttribute("interrupt"))
1898     return false;
1899
1900   // Also avoid sibcall optimization if either caller or callee uses struct
1901   // return semantics.
1902   if (isCalleeStructRet || isCallerStructRet)
1903     return false;
1904
1905   // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
1906   // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
1907   // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
1908   // support in the assembler and linker to be used. This would need to be
1909   // fixed to fully support tail calls in Thumb1.
1910   //
1911   // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
1912   // LR.  This means if we need to reload LR, it takes an extra instructions,
1913   // which outweighs the value of the tail call; but here we don't know yet
1914   // whether LR is going to be used.  Probably the right approach is to
1915   // generate the tail call here and turn it back into CALL/RET in
1916   // emitEpilogue if LR is used.
1917
1918   // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
1919   // but we need to make sure there are enough registers; the only valid
1920   // registers are the 4 used for parameters.  We don't currently do this
1921   // case.
1922   if (Subtarget->isThumb1Only())
1923     return false;
1924
1925   // If the calling conventions do not match, then we'd better make sure the
1926   // results are returned in the same way as what the caller expects.
1927   if (!CCMatch) {
1928     SmallVector<CCValAssign, 16> RVLocs1;
1929     ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
1930                        getTargetMachine(), RVLocs1, *DAG.getContext(), Call);
1931     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
1932
1933     SmallVector<CCValAssign, 16> RVLocs2;
1934     ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
1935                        getTargetMachine(), RVLocs2, *DAG.getContext(), Call);
1936     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
1937
1938     if (RVLocs1.size() != RVLocs2.size())
1939       return false;
1940     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
1941       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
1942         return false;
1943       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
1944         return false;
1945       if (RVLocs1[i].isRegLoc()) {
1946         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
1947           return false;
1948       } else {
1949         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
1950           return false;
1951       }
1952     }
1953   }
1954
1955   // If Caller's vararg or byval argument has been split between registers and
1956   // stack, do not perform tail call, since part of the argument is in caller's
1957   // local frame.
1958   const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
1959                                       getInfo<ARMFunctionInfo>();
1960   if (AFI_Caller->getArgRegsSaveSize())
1961     return false;
1962
1963   // If the callee takes no arguments then go on to check the results of the
1964   // call.
1965   if (!Outs.empty()) {
1966     // Check if stack adjustment is needed. For now, do not do this if any
1967     // argument is passed on the stack.
1968     SmallVector<CCValAssign, 16> ArgLocs;
1969     ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
1970                       getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1971     CCInfo.AnalyzeCallOperands(Outs,
1972                                CCAssignFnForNode(CalleeCC, false, isVarArg));
1973     if (CCInfo.getNextStackOffset()) {
1974       MachineFunction &MF = DAG.getMachineFunction();
1975
1976       // Check if the arguments are already laid out in the right way as
1977       // the caller's fixed stack objects.
1978       MachineFrameInfo *MFI = MF.getFrameInfo();
1979       const MachineRegisterInfo *MRI = &MF.getRegInfo();
1980       const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1981       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1982            i != e;
1983            ++i, ++realArgIdx) {
1984         CCValAssign &VA = ArgLocs[i];
1985         EVT RegVT = VA.getLocVT();
1986         SDValue Arg = OutVals[realArgIdx];
1987         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1988         if (VA.getLocInfo() == CCValAssign::Indirect)
1989           return false;
1990         if (VA.needsCustom()) {
1991           // f64 and vector types are split into multiple registers or
1992           // register/stack-slot combinations.  The types will not match
1993           // the registers; give up on memory f64 refs until we figure
1994           // out what to do about this.
1995           if (!VA.isRegLoc())
1996             return false;
1997           if (!ArgLocs[++i].isRegLoc())
1998             return false;
1999           if (RegVT == MVT::v2f64) {
2000             if (!ArgLocs[++i].isRegLoc())
2001               return false;
2002             if (!ArgLocs[++i].isRegLoc())
2003               return false;
2004           }
2005         } else if (!VA.isRegLoc()) {
2006           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2007                                    MFI, MRI, TII))
2008             return false;
2009         }
2010       }
2011     }
2012   }
2013
2014   return true;
2015 }
2016
2017 bool
2018 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2019                                   MachineFunction &MF, bool isVarArg,
2020                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
2021                                   LLVMContext &Context) const {
2022   SmallVector<CCValAssign, 16> RVLocs;
2023   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), RVLocs, Context);
2024   return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2025                                                     isVarArg));
2026 }
2027
2028 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2029                                     SDLoc DL, SelectionDAG &DAG) {
2030   const MachineFunction &MF = DAG.getMachineFunction();
2031   const Function *F = MF.getFunction();
2032
2033   StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2034
2035   // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2036   // version of the "preferred return address". These offsets affect the return
2037   // instruction if this is a return from PL1 without hypervisor extensions.
2038   //    IRQ/FIQ: +4     "subs pc, lr, #4"
2039   //    SWI:     0      "subs pc, lr, #0"
2040   //    ABORT:   +4     "subs pc, lr, #4"
2041   //    UNDEF:   +4/+2  "subs pc, lr, #0"
2042   // UNDEF varies depending on where the exception came from ARM or Thumb
2043   // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2044
2045   int64_t LROffset;
2046   if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2047       IntKind == "ABORT")
2048     LROffset = 4;
2049   else if (IntKind == "SWI" || IntKind == "UNDEF")
2050     LROffset = 0;
2051   else
2052     report_fatal_error("Unsupported interrupt attribute. If present, value "
2053                        "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2054
2055   RetOps.insert(RetOps.begin() + 1, DAG.getConstant(LROffset, MVT::i32, false));
2056
2057   return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other,
2058                      RetOps.data(), RetOps.size());
2059 }
2060
2061 SDValue
2062 ARMTargetLowering::LowerReturn(SDValue Chain,
2063                                CallingConv::ID CallConv, bool isVarArg,
2064                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2065                                const SmallVectorImpl<SDValue> &OutVals,
2066                                SDLoc dl, SelectionDAG &DAG) const {
2067
2068   // CCValAssign - represent the assignment of the return value to a location.
2069   SmallVector<CCValAssign, 16> RVLocs;
2070
2071   // CCState - Info about the registers and stack slots.
2072   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2073                     getTargetMachine(), RVLocs, *DAG.getContext(), Call);
2074
2075   // Analyze outgoing return values.
2076   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2077                                                isVarArg));
2078
2079   SDValue Flag;
2080   SmallVector<SDValue, 4> RetOps;
2081   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2082
2083   // Copy the result values into the output registers.
2084   for (unsigned i = 0, realRVLocIdx = 0;
2085        i != RVLocs.size();
2086        ++i, ++realRVLocIdx) {
2087     CCValAssign &VA = RVLocs[i];
2088     assert(VA.isRegLoc() && "Can only return in registers!");
2089
2090     SDValue Arg = OutVals[realRVLocIdx];
2091
2092     switch (VA.getLocInfo()) {
2093     default: llvm_unreachable("Unknown loc info!");
2094     case CCValAssign::Full: break;
2095     case CCValAssign::BCvt:
2096       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2097       break;
2098     }
2099
2100     if (VA.needsCustom()) {
2101       if (VA.getLocVT() == MVT::v2f64) {
2102         // Extract the first half and return it in two registers.
2103         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2104                                    DAG.getConstant(0, MVT::i32));
2105         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2106                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
2107
2108         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), HalfGPRs, Flag);
2109         Flag = Chain.getValue(1);
2110         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2111         VA = RVLocs[++i]; // skip ahead to next loc
2112         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2113                                  HalfGPRs.getValue(1), Flag);
2114         Flag = Chain.getValue(1);
2115         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2116         VA = RVLocs[++i]; // skip ahead to next loc
2117
2118         // Extract the 2nd half and fall through to handle it as an f64 value.
2119         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2120                           DAG.getConstant(1, MVT::i32));
2121       }
2122       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
2123       // available.
2124       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2125                                   DAG.getVTList(MVT::i32, MVT::i32), &Arg, 1);
2126       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd, Flag);
2127       Flag = Chain.getValue(1);
2128       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2129       VA = RVLocs[++i]; // skip ahead to next loc
2130       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd.getValue(1),
2131                                Flag);
2132     } else
2133       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2134
2135     // Guarantee that all emitted copies are
2136     // stuck together, avoiding something bad.
2137     Flag = Chain.getValue(1);
2138     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2139   }
2140
2141   // Update chain and glue.
2142   RetOps[0] = Chain;
2143   if (Flag.getNode())
2144     RetOps.push_back(Flag);
2145
2146   // CPUs which aren't M-class use a special sequence to return from
2147   // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2148   // though we use "subs pc, lr, #N").
2149   //
2150   // M-class CPUs actually use a normal return sequence with a special
2151   // (hardware-provided) value in LR, so the normal code path works.
2152   if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2153       !Subtarget->isMClass()) {
2154     if (Subtarget->isThumb1Only())
2155       report_fatal_error("interrupt attribute is not supported in Thumb1");
2156     return LowerInterruptReturn(RetOps, dl, DAG);
2157   }
2158
2159   return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other,
2160                      RetOps.data(), RetOps.size());
2161 }
2162
2163 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2164   if (N->getNumValues() != 1)
2165     return false;
2166   if (!N->hasNUsesOfValue(1, 0))
2167     return false;
2168
2169   SDValue TCChain = Chain;
2170   SDNode *Copy = *N->use_begin();
2171   if (Copy->getOpcode() == ISD::CopyToReg) {
2172     // If the copy has a glue operand, we conservatively assume it isn't safe to
2173     // perform a tail call.
2174     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2175       return false;
2176     TCChain = Copy->getOperand(0);
2177   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2178     SDNode *VMov = Copy;
2179     // f64 returned in a pair of GPRs.
2180     SmallPtrSet<SDNode*, 2> Copies;
2181     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2182          UI != UE; ++UI) {
2183       if (UI->getOpcode() != ISD::CopyToReg)
2184         return false;
2185       Copies.insert(*UI);
2186     }
2187     if (Copies.size() > 2)
2188       return false;
2189
2190     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2191          UI != UE; ++UI) {
2192       SDValue UseChain = UI->getOperand(0);
2193       if (Copies.count(UseChain.getNode()))
2194         // Second CopyToReg
2195         Copy = *UI;
2196       else
2197         // First CopyToReg
2198         TCChain = UseChain;
2199     }
2200   } else if (Copy->getOpcode() == ISD::BITCAST) {
2201     // f32 returned in a single GPR.
2202     if (!Copy->hasOneUse())
2203       return false;
2204     Copy = *Copy->use_begin();
2205     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2206       return false;
2207     TCChain = Copy->getOperand(0);
2208   } else {
2209     return false;
2210   }
2211
2212   bool HasRet = false;
2213   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2214        UI != UE; ++UI) {
2215     if (UI->getOpcode() != ARMISD::RET_FLAG &&
2216         UI->getOpcode() != ARMISD::INTRET_FLAG)
2217       return false;
2218     HasRet = true;
2219   }
2220
2221   if (!HasRet)
2222     return false;
2223
2224   Chain = TCChain;
2225   return true;
2226 }
2227
2228 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2229   if (!Subtarget->supportsTailCall())
2230     return false;
2231
2232   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2233     return false;
2234
2235   return !Subtarget->isThumb1Only();
2236 }
2237
2238 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2239 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2240 // one of the above mentioned nodes. It has to be wrapped because otherwise
2241 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2242 // be used to form addressing mode. These wrapped nodes will be selected
2243 // into MOVi.
2244 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2245   EVT PtrVT = Op.getValueType();
2246   // FIXME there is no actual debug info here
2247   SDLoc dl(Op);
2248   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2249   SDValue Res;
2250   if (CP->isMachineConstantPoolEntry())
2251     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2252                                     CP->getAlignment());
2253   else
2254     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2255                                     CP->getAlignment());
2256   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2257 }
2258
2259 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2260   return MachineJumpTableInfo::EK_Inline;
2261 }
2262
2263 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2264                                              SelectionDAG &DAG) const {
2265   MachineFunction &MF = DAG.getMachineFunction();
2266   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2267   unsigned ARMPCLabelIndex = 0;
2268   SDLoc DL(Op);
2269   EVT PtrVT = getPointerTy();
2270   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2271   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2272   SDValue CPAddr;
2273   if (RelocM == Reloc::Static) {
2274     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2275   } else {
2276     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2277     ARMPCLabelIndex = AFI->createPICLabelUId();
2278     ARMConstantPoolValue *CPV =
2279       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2280                                       ARMCP::CPBlockAddress, PCAdj);
2281     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2282   }
2283   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2284   SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2285                                MachinePointerInfo::getConstantPool(),
2286                                false, false, false, 0);
2287   if (RelocM == Reloc::Static)
2288     return Result;
2289   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2290   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2291 }
2292
2293 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2294 SDValue
2295 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2296                                                  SelectionDAG &DAG) const {
2297   SDLoc dl(GA);
2298   EVT PtrVT = getPointerTy();
2299   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2300   MachineFunction &MF = DAG.getMachineFunction();
2301   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2302   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2303   ARMConstantPoolValue *CPV =
2304     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2305                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2306   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2307   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2308   Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2309                          MachinePointerInfo::getConstantPool(),
2310                          false, false, false, 0);
2311   SDValue Chain = Argument.getValue(1);
2312
2313   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2314   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2315
2316   // call __tls_get_addr.
2317   ArgListTy Args;
2318   ArgListEntry Entry;
2319   Entry.Node = Argument;
2320   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2321   Args.push_back(Entry);
2322   // FIXME: is there useful debug info available here?
2323   TargetLowering::CallLoweringInfo CLI(Chain,
2324                 (Type *) Type::getInt32Ty(*DAG.getContext()),
2325                 false, false, false, false,
2326                 0, CallingConv::C, /*isTailCall=*/false,
2327                 /*doesNotRet=*/false, /*isReturnValueUsed=*/true,
2328                 DAG.getExternalSymbol("__tls_get_addr", PtrVT), Args, DAG, dl);
2329   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2330   return CallResult.first;
2331 }
2332
2333 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2334 // "local exec" model.
2335 SDValue
2336 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2337                                         SelectionDAG &DAG,
2338                                         TLSModel::Model model) const {
2339   const GlobalValue *GV = GA->getGlobal();
2340   SDLoc dl(GA);
2341   SDValue Offset;
2342   SDValue Chain = DAG.getEntryNode();
2343   EVT PtrVT = getPointerTy();
2344   // Get the Thread Pointer
2345   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2346
2347   if (model == TLSModel::InitialExec) {
2348     MachineFunction &MF = DAG.getMachineFunction();
2349     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2350     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2351     // Initial exec model.
2352     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2353     ARMConstantPoolValue *CPV =
2354       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2355                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2356                                       true);
2357     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2358     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2359     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2360                          MachinePointerInfo::getConstantPool(),
2361                          false, false, false, 0);
2362     Chain = Offset.getValue(1);
2363
2364     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2365     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2366
2367     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2368                          MachinePointerInfo::getConstantPool(),
2369                          false, false, false, 0);
2370   } else {
2371     // local exec model
2372     assert(model == TLSModel::LocalExec);
2373     ARMConstantPoolValue *CPV =
2374       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2375     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2376     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2377     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2378                          MachinePointerInfo::getConstantPool(),
2379                          false, false, false, 0);
2380   }
2381
2382   // The address of the thread local variable is the add of the thread
2383   // pointer with the offset of the variable.
2384   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2385 }
2386
2387 SDValue
2388 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2389   // TODO: implement the "local dynamic" model
2390   assert(Subtarget->isTargetELF() &&
2391          "TLS not implemented for non-ELF targets");
2392   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2393
2394   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2395
2396   switch (model) {
2397     case TLSModel::GeneralDynamic:
2398     case TLSModel::LocalDynamic:
2399       return LowerToTLSGeneralDynamicModel(GA, DAG);
2400     case TLSModel::InitialExec:
2401     case TLSModel::LocalExec:
2402       return LowerToTLSExecModels(GA, DAG, model);
2403   }
2404   llvm_unreachable("bogus TLS model");
2405 }
2406
2407 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2408                                                  SelectionDAG &DAG) const {
2409   EVT PtrVT = getPointerTy();
2410   SDLoc dl(Op);
2411   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2412   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2413     bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2414     ARMConstantPoolValue *CPV =
2415       ARMConstantPoolConstant::Create(GV,
2416                                       UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2417     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2418     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2419     SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2420                                  CPAddr,
2421                                  MachinePointerInfo::getConstantPool(),
2422                                  false, false, false, 0);
2423     SDValue Chain = Result.getValue(1);
2424     SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2425     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2426     if (!UseGOTOFF)
2427       Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2428                            MachinePointerInfo::getGOT(),
2429                            false, false, false, 0);
2430     return Result;
2431   }
2432
2433   // If we have T2 ops, we can materialize the address directly via movt/movw
2434   // pair. This is always cheaper.
2435   if (Subtarget->useMovt()) {
2436     ++NumMovwMovt;
2437     // FIXME: Once remat is capable of dealing with instructions with register
2438     // operands, expand this into two nodes.
2439     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2440                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2441   } else {
2442     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2443     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2444     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2445                        MachinePointerInfo::getConstantPool(),
2446                        false, false, false, 0);
2447   }
2448 }
2449
2450 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2451                                                     SelectionDAG &DAG) const {
2452   EVT PtrVT = getPointerTy();
2453   SDLoc dl(Op);
2454   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2455   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2456
2457   if (Subtarget->useMovt())
2458     ++NumMovwMovt;
2459
2460   // FIXME: Once remat is capable of dealing with instructions with register
2461   // operands, expand this into multiple nodes
2462   unsigned Wrapper =
2463       RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2464
2465   SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2466   SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2467
2468   if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2469     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2470                          MachinePointerInfo::getGOT(), false, false, false, 0);
2471   return Result;
2472 }
2473
2474 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2475                                                     SelectionDAG &DAG) const {
2476   assert(Subtarget->isTargetELF() &&
2477          "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2478   MachineFunction &MF = DAG.getMachineFunction();
2479   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2480   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2481   EVT PtrVT = getPointerTy();
2482   SDLoc dl(Op);
2483   unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2484   ARMConstantPoolValue *CPV =
2485     ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2486                                   ARMPCLabelIndex, PCAdj);
2487   SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2488   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2489   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2490                                MachinePointerInfo::getConstantPool(),
2491                                false, false, false, 0);
2492   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2493   return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2494 }
2495
2496 SDValue
2497 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2498   SDLoc dl(Op);
2499   SDValue Val = DAG.getConstant(0, MVT::i32);
2500   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2501                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2502                      Op.getOperand(1), Val);
2503 }
2504
2505 SDValue
2506 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2507   SDLoc dl(Op);
2508   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2509                      Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2510 }
2511
2512 SDValue
2513 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2514                                           const ARMSubtarget *Subtarget) const {
2515   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2516   SDLoc dl(Op);
2517   switch (IntNo) {
2518   default: return SDValue();    // Don't custom lower most intrinsics.
2519   case Intrinsic::arm_thread_pointer: {
2520     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2521     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2522   }
2523   case Intrinsic::eh_sjlj_lsda: {
2524     MachineFunction &MF = DAG.getMachineFunction();
2525     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2526     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2527     EVT PtrVT = getPointerTy();
2528     Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2529     SDValue CPAddr;
2530     unsigned PCAdj = (RelocM != Reloc::PIC_)
2531       ? 0 : (Subtarget->isThumb() ? 4 : 8);
2532     ARMConstantPoolValue *CPV =
2533       ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2534                                       ARMCP::CPLSDA, PCAdj);
2535     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2536     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2537     SDValue Result =
2538       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2539                   MachinePointerInfo::getConstantPool(),
2540                   false, false, false, 0);
2541
2542     if (RelocM == Reloc::PIC_) {
2543       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2544       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2545     }
2546     return Result;
2547   }
2548   case Intrinsic::arm_neon_vmulls:
2549   case Intrinsic::arm_neon_vmullu: {
2550     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2551       ? ARMISD::VMULLs : ARMISD::VMULLu;
2552     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2553                        Op.getOperand(1), Op.getOperand(2));
2554   }
2555   }
2556 }
2557
2558 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2559                                  const ARMSubtarget *Subtarget) {
2560   // FIXME: handle "fence singlethread" more efficiently.
2561   SDLoc dl(Op);
2562   if (!Subtarget->hasDataBarrier()) {
2563     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2564     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2565     // here.
2566     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2567            "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2568     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2569                        DAG.getConstant(0, MVT::i32));
2570   }
2571
2572   ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2573   AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2574   unsigned Domain = ARM_MB::ISH;
2575   if (Subtarget->isMClass()) {
2576     // Only a full system barrier exists in the M-class architectures.
2577     Domain = ARM_MB::SY;
2578   } else if (Subtarget->isSwift() && Ord == Release) {
2579     // Swift happens to implement ISHST barriers in a way that's compatible with
2580     // Release semantics but weaker than ISH so we'd be fools not to use
2581     // it. Beware: other processors probably don't!
2582     Domain = ARM_MB::ISHST;
2583   }
2584
2585   return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2586                      DAG.getConstant(Intrinsic::arm_dmb, MVT::i32),
2587                      DAG.getConstant(Domain, MVT::i32));
2588 }
2589
2590 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2591                              const ARMSubtarget *Subtarget) {
2592   // ARM pre v5TE and Thumb1 does not have preload instructions.
2593   if (!(Subtarget->isThumb2() ||
2594         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2595     // Just preserve the chain.
2596     return Op.getOperand(0);
2597
2598   SDLoc dl(Op);
2599   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2600   if (!isRead &&
2601       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2602     // ARMv7 with MP extension has PLDW.
2603     return Op.getOperand(0);
2604
2605   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2606   if (Subtarget->isThumb()) {
2607     // Invert the bits.
2608     isRead = ~isRead & 1;
2609     isData = ~isData & 1;
2610   }
2611
2612   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2613                      Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2614                      DAG.getConstant(isData, MVT::i32));
2615 }
2616
2617 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2618   MachineFunction &MF = DAG.getMachineFunction();
2619   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2620
2621   // vastart just stores the address of the VarArgsFrameIndex slot into the
2622   // memory location argument.
2623   SDLoc dl(Op);
2624   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2625   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2626   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2627   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2628                       MachinePointerInfo(SV), false, false, 0);
2629 }
2630
2631 SDValue
2632 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2633                                         SDValue &Root, SelectionDAG &DAG,
2634                                         SDLoc dl) const {
2635   MachineFunction &MF = DAG.getMachineFunction();
2636   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2637
2638   const TargetRegisterClass *RC;
2639   if (AFI->isThumb1OnlyFunction())
2640     RC = &ARM::tGPRRegClass;
2641   else
2642     RC = &ARM::GPRRegClass;
2643
2644   // Transform the arguments stored in physical registers into virtual ones.
2645   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2646   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2647
2648   SDValue ArgValue2;
2649   if (NextVA.isMemLoc()) {
2650     MachineFrameInfo *MFI = MF.getFrameInfo();
2651     int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2652
2653     // Create load node to retrieve arguments from the stack.
2654     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2655     ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2656                             MachinePointerInfo::getFixedStack(FI),
2657                             false, false, false, 0);
2658   } else {
2659     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2660     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2661   }
2662
2663   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2664 }
2665
2666 void
2667 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2668                                   unsigned InRegsParamRecordIdx,
2669                                   unsigned ArgSize,
2670                                   unsigned &ArgRegsSize,
2671                                   unsigned &ArgRegsSaveSize)
2672   const {
2673   unsigned NumGPRs;
2674   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2675     unsigned RBegin, REnd;
2676     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2677     NumGPRs = REnd - RBegin;
2678   } else {
2679     unsigned int firstUnalloced;
2680     firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs,
2681                                                 sizeof(GPRArgRegs) /
2682                                                 sizeof(GPRArgRegs[0]));
2683     NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2684   }
2685
2686   unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment();
2687   ArgRegsSize = NumGPRs * 4;
2688
2689   // If parameter is split between stack and GPRs...
2690   if (NumGPRs && Align > 4 &&
2691       (ArgRegsSize < ArgSize ||
2692         InRegsParamRecordIdx >= CCInfo.getInRegsParamsCount())) {
2693     // Add padding for part of param recovered from GPRs.  For example,
2694     // if Align == 8, its last byte must be at address K*8 - 1.
2695     // We need to do it, since remained (stack) part of parameter has
2696     // stack alignment, and we need to "attach" "GPRs head" without gaps
2697     // to it:
2698     // Stack:
2699     // |---- 8 bytes block ----| |---- 8 bytes block ----| |---- 8 bytes...
2700     // [ [padding] [GPRs head] ] [        Tail passed via stack       ....
2701     //
2702     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2703     unsigned Padding =
2704         OffsetToAlignment(ArgRegsSize + AFI->getArgRegsSaveSize(), Align);
2705     ArgRegsSaveSize = ArgRegsSize + Padding;
2706   } else
2707     // We don't need to extend regs save size for byval parameters if they
2708     // are passed via GPRs only.
2709     ArgRegsSaveSize = ArgRegsSize;
2710 }
2711
2712 // The remaining GPRs hold either the beginning of variable-argument
2713 // data, or the beginning of an aggregate passed by value (usually
2714 // byval).  Either way, we allocate stack slots adjacent to the data
2715 // provided by our caller, and store the unallocated registers there.
2716 // If this is a variadic function, the va_list pointer will begin with
2717 // these values; otherwise, this reassembles a (byval) structure that
2718 // was split between registers and memory.
2719 // Return: The frame index registers were stored into.
2720 int
2721 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2722                                   SDLoc dl, SDValue &Chain,
2723                                   const Value *OrigArg,
2724                                   unsigned InRegsParamRecordIdx,
2725                                   unsigned OffsetFromOrigArg,
2726                                   unsigned ArgOffset,
2727                                   unsigned ArgSize,
2728                                   bool ForceMutable,
2729                                   unsigned ByValStoreOffset,
2730                                   unsigned TotalArgRegsSaveSize) const {
2731
2732   // Currently, two use-cases possible:
2733   // Case #1. Non-var-args function, and we meet first byval parameter.
2734   //          Setup first unallocated register as first byval register;
2735   //          eat all remained registers
2736   //          (these two actions are performed by HandleByVal method).
2737   //          Then, here, we initialize stack frame with
2738   //          "store-reg" instructions.
2739   // Case #2. Var-args function, that doesn't contain byval parameters.
2740   //          The same: eat all remained unallocated registers,
2741   //          initialize stack frame.
2742
2743   MachineFunction &MF = DAG.getMachineFunction();
2744   MachineFrameInfo *MFI = MF.getFrameInfo();
2745   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2746   unsigned firstRegToSaveIndex, lastRegToSaveIndex;
2747   unsigned RBegin, REnd;
2748   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2749     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2750     firstRegToSaveIndex = RBegin - ARM::R0;
2751     lastRegToSaveIndex = REnd - ARM::R0;
2752   } else {
2753     firstRegToSaveIndex = CCInfo.getFirstUnallocated
2754       (GPRArgRegs, array_lengthof(GPRArgRegs));
2755     lastRegToSaveIndex = 4;
2756   }
2757
2758   unsigned ArgRegsSize, ArgRegsSaveSize;
2759   computeRegArea(CCInfo, MF, InRegsParamRecordIdx, ArgSize,
2760                  ArgRegsSize, ArgRegsSaveSize);
2761
2762   // Store any by-val regs to their spots on the stack so that they may be
2763   // loaded by deferencing the result of formal parameter pointer or va_next.
2764   // Note: once stack area for byval/varargs registers
2765   // was initialized, it can't be initialized again.
2766   if (ArgRegsSaveSize) {
2767     unsigned Padding = ArgRegsSaveSize - ArgRegsSize;
2768
2769     if (Padding) {
2770       assert(AFI->getStoredByValParamsPadding() == 0 &&
2771              "The only parameter may be padded.");
2772       AFI->setStoredByValParamsPadding(Padding);
2773     }
2774
2775     int FrameIndex = MFI->CreateFixedObject(ArgRegsSaveSize,
2776                                             Padding +
2777                                               ByValStoreOffset -
2778                                               (int64_t)TotalArgRegsSaveSize,
2779                                             false);
2780     SDValue FIN = DAG.getFrameIndex(FrameIndex, getPointerTy());
2781     if (Padding) {
2782        MFI->CreateFixedObject(Padding,
2783                               ArgOffset + ByValStoreOffset -
2784                                 (int64_t)ArgRegsSaveSize,
2785                               false);
2786     }
2787
2788     SmallVector<SDValue, 4> MemOps;
2789     for (unsigned i = 0; firstRegToSaveIndex < lastRegToSaveIndex;
2790          ++firstRegToSaveIndex, ++i) {
2791       const TargetRegisterClass *RC;
2792       if (AFI->isThumb1OnlyFunction())
2793         RC = &ARM::tGPRRegClass;
2794       else
2795         RC = &ARM::GPRRegClass;
2796
2797       unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2798       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2799       SDValue Store =
2800         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2801                      MachinePointerInfo(OrigArg, OffsetFromOrigArg + 4*i),
2802                      false, false, 0);
2803       MemOps.push_back(Store);
2804       FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2805                         DAG.getConstant(4, getPointerTy()));
2806     }
2807
2808     AFI->setArgRegsSaveSize(ArgRegsSaveSize + AFI->getArgRegsSaveSize());
2809
2810     if (!MemOps.empty())
2811       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2812                           &MemOps[0], MemOps.size());
2813     return FrameIndex;
2814   } else {
2815     if (ArgSize == 0) {
2816       // We cannot allocate a zero-byte object for the first variadic argument,
2817       // so just make up a size.
2818       ArgSize = 4;
2819     }
2820     // This will point to the next argument passed via stack.
2821     return MFI->CreateFixedObject(
2822       ArgSize, ArgOffset, !ForceMutable);
2823   }
2824 }
2825
2826 // Setup stack frame, the va_list pointer will start from.
2827 void
2828 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2829                                         SDLoc dl, SDValue &Chain,
2830                                         unsigned ArgOffset,
2831                                         unsigned TotalArgRegsSaveSize,
2832                                         bool ForceMutable) const {
2833   MachineFunction &MF = DAG.getMachineFunction();
2834   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2835
2836   // Try to store any remaining integer argument regs
2837   // to their spots on the stack so that they may be loaded by deferencing
2838   // the result of va_next.
2839   // If there is no regs to be stored, just point address after last
2840   // argument passed via stack.
2841   int FrameIndex =
2842     StoreByValRegs(CCInfo, DAG, dl, Chain, 0, CCInfo.getInRegsParamsCount(),
2843                    0, ArgOffset, 0, ForceMutable, 0, TotalArgRegsSaveSize);
2844
2845   AFI->setVarArgsFrameIndex(FrameIndex);
2846 }
2847
2848 SDValue
2849 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2850                                         CallingConv::ID CallConv, bool isVarArg,
2851                                         const SmallVectorImpl<ISD::InputArg>
2852                                           &Ins,
2853                                         SDLoc dl, SelectionDAG &DAG,
2854                                         SmallVectorImpl<SDValue> &InVals)
2855                                           const {
2856   MachineFunction &MF = DAG.getMachineFunction();
2857   MachineFrameInfo *MFI = MF.getFrameInfo();
2858
2859   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2860
2861   // Assign locations to all of the incoming arguments.
2862   SmallVector<CCValAssign, 16> ArgLocs;
2863   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2864                     getTargetMachine(), ArgLocs, *DAG.getContext(), Prologue);
2865   CCInfo.AnalyzeFormalArguments(Ins,
2866                                 CCAssignFnForNode(CallConv, /* Return*/ false,
2867                                                   isVarArg));
2868
2869   SmallVector<SDValue, 16> ArgValues;
2870   int lastInsIndex = -1;
2871   SDValue ArgValue;
2872   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2873   unsigned CurArgIdx = 0;
2874
2875   // Initially ArgRegsSaveSize is zero.
2876   // Then we increase this value each time we meet byval parameter.
2877   // We also increase this value in case of varargs function.
2878   AFI->setArgRegsSaveSize(0);
2879
2880   unsigned ByValStoreOffset = 0;
2881   unsigned TotalArgRegsSaveSize = 0;
2882   unsigned ArgRegsSaveSizeMaxAlign = 4;
2883
2884   // Calculate the amount of stack space that we need to allocate to store
2885   // byval and variadic arguments that are passed in registers.
2886   // We need to know this before we allocate the first byval or variadic
2887   // argument, as they will be allocated a stack slot below the CFA (Canonical
2888   // Frame Address, the stack pointer at entry to the function).
2889   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2890     CCValAssign &VA = ArgLocs[i];
2891     if (VA.isMemLoc()) {
2892       int index = VA.getValNo();
2893       if (index != lastInsIndex) {
2894         ISD::ArgFlagsTy Flags = Ins[index].Flags;
2895         if (Flags.isByVal()) {
2896           unsigned ExtraArgRegsSize;
2897           unsigned ExtraArgRegsSaveSize;
2898           computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsProceed(),
2899                          Flags.getByValSize(),
2900                          ExtraArgRegsSize, ExtraArgRegsSaveSize);
2901
2902           TotalArgRegsSaveSize += ExtraArgRegsSaveSize;
2903           if (Flags.getByValAlign() > ArgRegsSaveSizeMaxAlign)
2904               ArgRegsSaveSizeMaxAlign = Flags.getByValAlign();
2905           CCInfo.nextInRegsParam();
2906         }
2907         lastInsIndex = index;
2908       }
2909     }
2910   }
2911   CCInfo.rewindByValRegsInfo();
2912   lastInsIndex = -1;
2913   if (isVarArg) {
2914     unsigned ExtraArgRegsSize;
2915     unsigned ExtraArgRegsSaveSize;
2916     computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsCount(), 0,
2917                    ExtraArgRegsSize, ExtraArgRegsSaveSize);
2918     TotalArgRegsSaveSize += ExtraArgRegsSaveSize;
2919   }
2920   // If the arg regs save area contains N-byte aligned values, the
2921   // bottom of it must be at least N-byte aligned.
2922   TotalArgRegsSaveSize = RoundUpToAlignment(TotalArgRegsSaveSize, ArgRegsSaveSizeMaxAlign);
2923   TotalArgRegsSaveSize = std::min(TotalArgRegsSaveSize, 16U);
2924
2925   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2926     CCValAssign &VA = ArgLocs[i];
2927     std::advance(CurOrigArg, Ins[VA.getValNo()].OrigArgIndex - CurArgIdx);
2928     CurArgIdx = Ins[VA.getValNo()].OrigArgIndex;
2929     // Arguments stored in registers.
2930     if (VA.isRegLoc()) {
2931       EVT RegVT = VA.getLocVT();
2932
2933       if (VA.needsCustom()) {
2934         // f64 and vector types are split up into multiple registers or
2935         // combinations of registers and stack slots.
2936         if (VA.getLocVT() == MVT::v2f64) {
2937           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
2938                                                    Chain, DAG, dl);
2939           VA = ArgLocs[++i]; // skip ahead to next loc
2940           SDValue ArgValue2;
2941           if (VA.isMemLoc()) {
2942             int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
2943             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2944             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
2945                                     MachinePointerInfo::getFixedStack(FI),
2946                                     false, false, false, 0);
2947           } else {
2948             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
2949                                              Chain, DAG, dl);
2950           }
2951           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
2952           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2953                                  ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
2954           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2955                                  ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
2956         } else
2957           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
2958
2959       } else {
2960         const TargetRegisterClass *RC;
2961
2962         if (RegVT == MVT::f32)
2963           RC = &ARM::SPRRegClass;
2964         else if (RegVT == MVT::f64)
2965           RC = &ARM::DPRRegClass;
2966         else if (RegVT == MVT::v2f64)
2967           RC = &ARM::QPRRegClass;
2968         else if (RegVT == MVT::i32)
2969           RC = AFI->isThumb1OnlyFunction() ?
2970             (const TargetRegisterClass*)&ARM::tGPRRegClass :
2971             (const TargetRegisterClass*)&ARM::GPRRegClass;
2972         else
2973           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2974
2975         // Transform the arguments in physical registers into virtual ones.
2976         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2977         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2978       }
2979
2980       // If this is an 8 or 16-bit value, it is really passed promoted
2981       // to 32 bits.  Insert an assert[sz]ext to capture this, then
2982       // truncate to the right size.
2983       switch (VA.getLocInfo()) {
2984       default: llvm_unreachable("Unknown loc info!");
2985       case CCValAssign::Full: break;
2986       case CCValAssign::BCvt:
2987         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2988         break;
2989       case CCValAssign::SExt:
2990         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2991                                DAG.getValueType(VA.getValVT()));
2992         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2993         break;
2994       case CCValAssign::ZExt:
2995         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2996                                DAG.getValueType(VA.getValVT()));
2997         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2998         break;
2999       }
3000
3001       InVals.push_back(ArgValue);
3002
3003     } else { // VA.isRegLoc()
3004
3005       // sanity check
3006       assert(VA.isMemLoc());
3007       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3008
3009       int index = ArgLocs[i].getValNo();
3010
3011       // Some Ins[] entries become multiple ArgLoc[] entries.
3012       // Process them only once.
3013       if (index != lastInsIndex)
3014         {
3015           ISD::ArgFlagsTy Flags = Ins[index].Flags;
3016           // FIXME: For now, all byval parameter objects are marked mutable.
3017           // This can be changed with more analysis.
3018           // In case of tail call optimization mark all arguments mutable.
3019           // Since they could be overwritten by lowering of arguments in case of
3020           // a tail call.
3021           if (Flags.isByVal()) {
3022             unsigned CurByValIndex = CCInfo.getInRegsParamsProceed();
3023
3024             ByValStoreOffset = RoundUpToAlignment(ByValStoreOffset, Flags.getByValAlign());
3025             int FrameIndex = StoreByValRegs(
3026                 CCInfo, DAG, dl, Chain, CurOrigArg,
3027                 CurByValIndex,
3028                 Ins[VA.getValNo()].PartOffset,
3029                 VA.getLocMemOffset(),
3030                 Flags.getByValSize(),
3031                 true /*force mutable frames*/,
3032                 ByValStoreOffset,
3033                 TotalArgRegsSaveSize);
3034             ByValStoreOffset += Flags.getByValSize();
3035             ByValStoreOffset = std::min(ByValStoreOffset, 16U);
3036             InVals.push_back(DAG.getFrameIndex(FrameIndex, getPointerTy()));
3037             CCInfo.nextInRegsParam();
3038           } else {
3039             unsigned FIOffset = VA.getLocMemOffset();
3040             int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3041                                             FIOffset, true);
3042
3043             // Create load nodes to retrieve arguments from the stack.
3044             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3045             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3046                                          MachinePointerInfo::getFixedStack(FI),
3047                                          false, false, false, 0));
3048           }
3049           lastInsIndex = index;
3050         }
3051     }
3052   }
3053
3054   // varargs
3055   if (isVarArg)
3056     VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3057                          CCInfo.getNextStackOffset(),
3058                          TotalArgRegsSaveSize);
3059
3060   AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3061
3062   return Chain;
3063 }
3064
3065 /// isFloatingPointZero - Return true if this is +0.0.
3066 static bool isFloatingPointZero(SDValue Op) {
3067   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3068     return CFP->getValueAPF().isPosZero();
3069   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3070     // Maybe this has already been legalized into the constant pool?
3071     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3072       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3073       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3074         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3075           return CFP->getValueAPF().isPosZero();
3076     }
3077   }
3078   return false;
3079 }
3080
3081 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3082 /// the given operands.
3083 SDValue
3084 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3085                              SDValue &ARMcc, SelectionDAG &DAG,
3086                              SDLoc dl) const {
3087   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3088     unsigned C = RHSC->getZExtValue();
3089     if (!isLegalICmpImmediate(C)) {
3090       // Constant does not fit, try adjusting it by one?
3091       switch (CC) {
3092       default: break;
3093       case ISD::SETLT:
3094       case ISD::SETGE:
3095         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3096           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3097           RHS = DAG.getConstant(C-1, MVT::i32);
3098         }
3099         break;
3100       case ISD::SETULT:
3101       case ISD::SETUGE:
3102         if (C != 0 && isLegalICmpImmediate(C-1)) {
3103           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3104           RHS = DAG.getConstant(C-1, MVT::i32);
3105         }
3106         break;
3107       case ISD::SETLE:
3108       case ISD::SETGT:
3109         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3110           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3111           RHS = DAG.getConstant(C+1, MVT::i32);
3112         }
3113         break;
3114       case ISD::SETULE:
3115       case ISD::SETUGT:
3116         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3117           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3118           RHS = DAG.getConstant(C+1, MVT::i32);
3119         }
3120         break;
3121       }
3122     }
3123   }
3124
3125   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3126   ARMISD::NodeType CompareType;
3127   switch (CondCode) {
3128   default:
3129     CompareType = ARMISD::CMP;
3130     break;
3131   case ARMCC::EQ:
3132   case ARMCC::NE:
3133     // Uses only Z Flag
3134     CompareType = ARMISD::CMPZ;
3135     break;
3136   }
3137   ARMcc = DAG.getConstant(CondCode, MVT::i32);
3138   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3139 }
3140
3141 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3142 SDValue
3143 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3144                              SDLoc dl) const {
3145   SDValue Cmp;
3146   if (!isFloatingPointZero(RHS))
3147     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3148   else
3149     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3150   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3151 }
3152
3153 /// duplicateCmp - Glue values can have only one use, so this function
3154 /// duplicates a comparison node.
3155 SDValue
3156 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3157   unsigned Opc = Cmp.getOpcode();
3158   SDLoc DL(Cmp);
3159   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3160     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3161
3162   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3163   Cmp = Cmp.getOperand(0);
3164   Opc = Cmp.getOpcode();
3165   if (Opc == ARMISD::CMPFP)
3166     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3167   else {
3168     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3169     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3170   }
3171   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3172 }
3173
3174 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3175   SDValue Cond = Op.getOperand(0);
3176   SDValue SelectTrue = Op.getOperand(1);
3177   SDValue SelectFalse = Op.getOperand(2);
3178   SDLoc dl(Op);
3179
3180   // Convert:
3181   //
3182   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3183   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3184   //
3185   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3186     const ConstantSDNode *CMOVTrue =
3187       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3188     const ConstantSDNode *CMOVFalse =
3189       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3190
3191     if (CMOVTrue && CMOVFalse) {
3192       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3193       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3194
3195       SDValue True;
3196       SDValue False;
3197       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3198         True = SelectTrue;
3199         False = SelectFalse;
3200       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3201         True = SelectFalse;
3202         False = SelectTrue;
3203       }
3204
3205       if (True.getNode() && False.getNode()) {
3206         EVT VT = Op.getValueType();
3207         SDValue ARMcc = Cond.getOperand(2);
3208         SDValue CCR = Cond.getOperand(3);
3209         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3210         assert(True.getValueType() == VT);
3211         return DAG.getNode(ARMISD::CMOV, dl, VT, True, False, ARMcc, CCR, Cmp);
3212       }
3213     }
3214   }
3215
3216   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3217   // undefined bits before doing a full-word comparison with zero.
3218   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3219                      DAG.getConstant(1, Cond.getValueType()));
3220
3221   return DAG.getSelectCC(dl, Cond,
3222                          DAG.getConstant(0, Cond.getValueType()),
3223                          SelectTrue, SelectFalse, ISD::SETNE);
3224 }
3225
3226 static ISD::CondCode getInverseCCForVSEL(ISD::CondCode CC) {
3227   if (CC == ISD::SETNE)
3228     return ISD::SETEQ;
3229   return ISD::getSetCCInverse(CC, true);
3230 }
3231
3232 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3233                                  bool &swpCmpOps, bool &swpVselOps) {
3234   // Start by selecting the GE condition code for opcodes that return true for
3235   // 'equality'
3236   if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3237       CC == ISD::SETULE)
3238     CondCode = ARMCC::GE;
3239
3240   // and GT for opcodes that return false for 'equality'.
3241   else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3242            CC == ISD::SETULT)
3243     CondCode = ARMCC::GT;
3244
3245   // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3246   // to swap the compare operands.
3247   if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3248       CC == ISD::SETULT)
3249     swpCmpOps = true;
3250
3251   // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3252   // If we have an unordered opcode, we need to swap the operands to the VSEL
3253   // instruction (effectively negating the condition).
3254   //
3255   // This also has the effect of swapping which one of 'less' or 'greater'
3256   // returns true, so we also swap the compare operands. It also switches
3257   // whether we return true for 'equality', so we compensate by picking the
3258   // opposite condition code to our original choice.
3259   if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3260       CC == ISD::SETUGT) {
3261     swpCmpOps = !swpCmpOps;
3262     swpVselOps = !swpVselOps;
3263     CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3264   }
3265
3266   // 'ordered' is 'anything but unordered', so use the VS condition code and
3267   // swap the VSEL operands.
3268   if (CC == ISD::SETO) {
3269     CondCode = ARMCC::VS;
3270     swpVselOps = true;
3271   }
3272
3273   // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3274   // code and swap the VSEL operands.
3275   if (CC == ISD::SETUNE) {
3276     CondCode = ARMCC::EQ;
3277     swpVselOps = true;
3278   }
3279 }
3280
3281 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3282   EVT VT = Op.getValueType();
3283   SDValue LHS = Op.getOperand(0);
3284   SDValue RHS = Op.getOperand(1);
3285   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3286   SDValue TrueVal = Op.getOperand(2);
3287   SDValue FalseVal = Op.getOperand(3);
3288   SDLoc dl(Op);
3289
3290   if (LHS.getValueType() == MVT::i32) {
3291     // Try to generate VSEL on ARMv8.
3292     // The VSEL instruction can't use all the usual ARM condition
3293     // codes: it only has two bits to select the condition code, so it's
3294     // constrained to use only GE, GT, VS and EQ.
3295     //
3296     // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3297     // swap the operands of the previous compare instruction (effectively
3298     // inverting the compare condition, swapping 'less' and 'greater') and
3299     // sometimes need to swap the operands to the VSEL (which inverts the
3300     // condition in the sense of firing whenever the previous condition didn't)
3301     if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3302                                       TrueVal.getValueType() == MVT::f64)) {
3303       ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3304       if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3305           CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3306         CC = getInverseCCForVSEL(CC);
3307         std::swap(TrueVal, FalseVal);
3308       }
3309     }
3310
3311     SDValue ARMcc;
3312     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3313     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3314     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3315                        Cmp);
3316   }
3317
3318   ARMCC::CondCodes CondCode, CondCode2;
3319   FPCCToARMCC(CC, CondCode, CondCode2);
3320
3321   // Try to generate VSEL on ARMv8.
3322   if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3323                                     TrueVal.getValueType() == MVT::f64)) {
3324     // We can select VMAXNM/VMINNM from a compare followed by a select with the
3325     // same operands, as follows:
3326     //   c = fcmp [ogt, olt, ugt, ult] a, b
3327     //   select c, a, b
3328     // We only do this in unsafe-fp-math, because signed zeros and NaNs are
3329     // handled differently than the original code sequence.
3330     if (getTargetMachine().Options.UnsafeFPMath && LHS == TrueVal &&
3331         RHS == FalseVal) {
3332       if (CC == ISD::SETOGT || CC == ISD::SETUGT)
3333         return DAG.getNode(ARMISD::VMAXNM, dl, VT, TrueVal, FalseVal);
3334       if (CC == ISD::SETOLT || CC == ISD::SETULT)
3335         return DAG.getNode(ARMISD::VMINNM, dl, VT, TrueVal, FalseVal);
3336     }
3337
3338     bool swpCmpOps = false;
3339     bool swpVselOps = false;
3340     checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3341
3342     if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3343         CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3344       if (swpCmpOps)
3345         std::swap(LHS, RHS);
3346       if (swpVselOps)
3347         std::swap(TrueVal, FalseVal);
3348     }
3349   }
3350
3351   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3352   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3353   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3354   SDValue Result = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
3355                                ARMcc, CCR, Cmp);
3356   if (CondCode2 != ARMCC::AL) {
3357     SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
3358     // FIXME: Needs another CMP because flag can have but one use.
3359     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3360     Result = DAG.getNode(ARMISD::CMOV, dl, VT,
3361                          Result, TrueVal, ARMcc2, CCR, Cmp2);
3362   }
3363   return Result;
3364 }
3365
3366 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3367 /// to morph to an integer compare sequence.
3368 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3369                            const ARMSubtarget *Subtarget) {
3370   SDNode *N = Op.getNode();
3371   if (!N->hasOneUse())
3372     // Otherwise it requires moving the value from fp to integer registers.
3373     return false;
3374   if (!N->getNumValues())
3375     return false;
3376   EVT VT = Op.getValueType();
3377   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3378     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3379     // vmrs are very slow, e.g. cortex-a8.
3380     return false;
3381
3382   if (isFloatingPointZero(Op)) {
3383     SeenZero = true;
3384     return true;
3385   }
3386   return ISD::isNormalLoad(N);
3387 }
3388
3389 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3390   if (isFloatingPointZero(Op))
3391     return DAG.getConstant(0, MVT::i32);
3392
3393   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3394     return DAG.getLoad(MVT::i32, SDLoc(Op),
3395                        Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3396                        Ld->isVolatile(), Ld->isNonTemporal(),
3397                        Ld->isInvariant(), Ld->getAlignment());
3398
3399   llvm_unreachable("Unknown VFP cmp argument!");
3400 }
3401
3402 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3403                            SDValue &RetVal1, SDValue &RetVal2) {
3404   if (isFloatingPointZero(Op)) {
3405     RetVal1 = DAG.getConstant(0, MVT::i32);
3406     RetVal2 = DAG.getConstant(0, MVT::i32);
3407     return;
3408   }
3409
3410   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3411     SDValue Ptr = Ld->getBasePtr();
3412     RetVal1 = DAG.getLoad(MVT::i32, SDLoc(Op),
3413                           Ld->getChain(), Ptr,
3414                           Ld->getPointerInfo(),
3415                           Ld->isVolatile(), Ld->isNonTemporal(),
3416                           Ld->isInvariant(), Ld->getAlignment());
3417
3418     EVT PtrType = Ptr.getValueType();
3419     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3420     SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(Op),
3421                                  PtrType, Ptr, DAG.getConstant(4, PtrType));
3422     RetVal2 = DAG.getLoad(MVT::i32, SDLoc(Op),
3423                           Ld->getChain(), NewPtr,
3424                           Ld->getPointerInfo().getWithOffset(4),
3425                           Ld->isVolatile(), Ld->isNonTemporal(),
3426                           Ld->isInvariant(), NewAlign);
3427     return;
3428   }
3429
3430   llvm_unreachable("Unknown VFP cmp argument!");
3431 }
3432
3433 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3434 /// f32 and even f64 comparisons to integer ones.
3435 SDValue
3436 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3437   SDValue Chain = Op.getOperand(0);
3438   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3439   SDValue LHS = Op.getOperand(2);
3440   SDValue RHS = Op.getOperand(3);
3441   SDValue Dest = Op.getOperand(4);
3442   SDLoc dl(Op);
3443
3444   bool LHSSeenZero = false;
3445   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3446   bool RHSSeenZero = false;
3447   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3448   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3449     // If unsafe fp math optimization is enabled and there are no other uses of
3450     // the CMP operands, and the condition code is EQ or NE, we can optimize it
3451     // to an integer comparison.
3452     if (CC == ISD::SETOEQ)
3453       CC = ISD::SETEQ;
3454     else if (CC == ISD::SETUNE)
3455       CC = ISD::SETNE;
3456
3457     SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3458     SDValue ARMcc;
3459     if (LHS.getValueType() == MVT::f32) {
3460       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3461                         bitcastf32Toi32(LHS, DAG), Mask);
3462       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3463                         bitcastf32Toi32(RHS, DAG), Mask);
3464       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3465       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3466       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3467                          Chain, Dest, ARMcc, CCR, Cmp);
3468     }
3469
3470     SDValue LHS1, LHS2;
3471     SDValue RHS1, RHS2;
3472     expandf64Toi32(LHS, DAG, LHS1, LHS2);
3473     expandf64Toi32(RHS, DAG, RHS1, RHS2);
3474     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3475     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3476     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3477     ARMcc = DAG.getConstant(CondCode, MVT::i32);
3478     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3479     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3480     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops, 7);
3481   }
3482
3483   return SDValue();
3484 }
3485
3486 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3487   SDValue Chain = Op.getOperand(0);
3488   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3489   SDValue LHS = Op.getOperand(2);
3490   SDValue RHS = Op.getOperand(3);
3491   SDValue Dest = Op.getOperand(4);
3492   SDLoc dl(Op);
3493
3494   if (LHS.getValueType() == MVT::i32) {
3495     SDValue ARMcc;
3496     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3497     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3498     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3499                        Chain, Dest, ARMcc, CCR, Cmp);
3500   }
3501
3502   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3503
3504   if (getTargetMachine().Options.UnsafeFPMath &&
3505       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3506        CC == ISD::SETNE || CC == ISD::SETUNE)) {
3507     SDValue Result = OptimizeVFPBrcond(Op, DAG);
3508     if (Result.getNode())
3509       return Result;
3510   }
3511
3512   ARMCC::CondCodes CondCode, CondCode2;
3513   FPCCToARMCC(CC, CondCode, CondCode2);
3514
3515   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3516   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3517   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3518   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3519   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3520   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3521   if (CondCode2 != ARMCC::AL) {
3522     ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3523     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3524     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3525   }
3526   return Res;
3527 }
3528
3529 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3530   SDValue Chain = Op.getOperand(0);
3531   SDValue Table = Op.getOperand(1);
3532   SDValue Index = Op.getOperand(2);
3533   SDLoc dl(Op);
3534
3535   EVT PTy = getPointerTy();
3536   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3537   ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3538   SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3539   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3540   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3541   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3542   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3543   if (Subtarget->isThumb2()) {
3544     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3545     // which does another jump to the destination. This also makes it easier
3546     // to translate it to TBB / TBH later.
3547     // FIXME: This might not work if the function is extremely large.
3548     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3549                        Addr, Op.getOperand(2), JTI, UId);
3550   }
3551   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3552     Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3553                        MachinePointerInfo::getJumpTable(),
3554                        false, false, false, 0);
3555     Chain = Addr.getValue(1);
3556     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3557     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3558   } else {
3559     Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3560                        MachinePointerInfo::getJumpTable(),
3561                        false, false, false, 0);
3562     Chain = Addr.getValue(1);
3563     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3564   }
3565 }
3566
3567 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3568   EVT VT = Op.getValueType();
3569   SDLoc dl(Op);
3570
3571   if (Op.getValueType().getVectorElementType() == MVT::i32) {
3572     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3573       return Op;
3574     return DAG.UnrollVectorOp(Op.getNode());
3575   }
3576
3577   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3578          "Invalid type for custom lowering!");
3579   if (VT != MVT::v4i16)
3580     return DAG.UnrollVectorOp(Op.getNode());
3581
3582   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3583   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3584 }
3585
3586 static SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3587   EVT VT = Op.getValueType();
3588   if (VT.isVector())
3589     return LowerVectorFP_TO_INT(Op, DAG);
3590
3591   SDLoc dl(Op);
3592   unsigned Opc;
3593
3594   switch (Op.getOpcode()) {
3595   default: llvm_unreachable("Invalid opcode!");
3596   case ISD::FP_TO_SINT:
3597     Opc = ARMISD::FTOSI;
3598     break;
3599   case ISD::FP_TO_UINT:
3600     Opc = ARMISD::FTOUI;
3601     break;
3602   }
3603   Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3604   return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3605 }
3606
3607 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3608   EVT VT = Op.getValueType();
3609   SDLoc dl(Op);
3610
3611   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3612     if (VT.getVectorElementType() == MVT::f32)
3613       return Op;
3614     return DAG.UnrollVectorOp(Op.getNode());
3615   }
3616
3617   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3618          "Invalid type for custom lowering!");
3619   if (VT != MVT::v4f32)
3620     return DAG.UnrollVectorOp(Op.getNode());
3621
3622   unsigned CastOpc;
3623   unsigned Opc;
3624   switch (Op.getOpcode()) {
3625   default: llvm_unreachable("Invalid opcode!");
3626   case ISD::SINT_TO_FP:
3627     CastOpc = ISD::SIGN_EXTEND;
3628     Opc = ISD::SINT_TO_FP;
3629     break;
3630   case ISD::UINT_TO_FP:
3631     CastOpc = ISD::ZERO_EXTEND;
3632     Opc = ISD::UINT_TO_FP;
3633     break;
3634   }
3635
3636   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3637   return DAG.getNode(Opc, dl, VT, Op);
3638 }
3639
3640 static SDValue LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3641   EVT VT = Op.getValueType();
3642   if (VT.isVector())
3643     return LowerVectorINT_TO_FP(Op, DAG);
3644
3645   SDLoc dl(Op);
3646   unsigned Opc;
3647
3648   switch (Op.getOpcode()) {
3649   default: llvm_unreachable("Invalid opcode!");
3650   case ISD::SINT_TO_FP:
3651     Opc = ARMISD::SITOF;
3652     break;
3653   case ISD::UINT_TO_FP:
3654     Opc = ARMISD::UITOF;
3655     break;
3656   }
3657
3658   Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3659   return DAG.getNode(Opc, dl, VT, Op);
3660 }
3661
3662 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3663   // Implement fcopysign with a fabs and a conditional fneg.
3664   SDValue Tmp0 = Op.getOperand(0);
3665   SDValue Tmp1 = Op.getOperand(1);
3666   SDLoc dl(Op);
3667   EVT VT = Op.getValueType();
3668   EVT SrcVT = Tmp1.getValueType();
3669   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3670     Tmp0.getOpcode() == ARMISD::VMOVDRR;
3671   bool UseNEON = !InGPR && Subtarget->hasNEON();
3672
3673   if (UseNEON) {
3674     // Use VBSL to copy the sign bit.
3675     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3676     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3677                                DAG.getTargetConstant(EncodedVal, MVT::i32));
3678     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3679     if (VT == MVT::f64)
3680       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3681                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3682                          DAG.getConstant(32, MVT::i32));
3683     else /*if (VT == MVT::f32)*/
3684       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3685     if (SrcVT == MVT::f32) {
3686       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3687       if (VT == MVT::f64)
3688         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3689                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3690                            DAG.getConstant(32, MVT::i32));
3691     } else if (VT == MVT::f32)
3692       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3693                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
3694                          DAG.getConstant(32, MVT::i32));
3695     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
3696     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
3697
3698     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
3699                                             MVT::i32);
3700     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
3701     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
3702                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
3703
3704     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
3705                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
3706                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
3707     if (VT == MVT::f32) {
3708       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
3709       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
3710                         DAG.getConstant(0, MVT::i32));
3711     } else {
3712       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
3713     }
3714
3715     return Res;
3716   }
3717
3718   // Bitcast operand 1 to i32.
3719   if (SrcVT == MVT::f64)
3720     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3721                        &Tmp1, 1).getValue(1);
3722   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
3723
3724   // Or in the signbit with integer operations.
3725   SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
3726   SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
3727   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
3728   if (VT == MVT::f32) {
3729     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
3730                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
3731     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3732                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
3733   }
3734
3735   // f64: Or the high part with signbit and then combine two parts.
3736   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3737                      &Tmp0, 1);
3738   SDValue Lo = Tmp0.getValue(0);
3739   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
3740   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
3741   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
3742 }
3743
3744 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
3745   MachineFunction &MF = DAG.getMachineFunction();
3746   MachineFrameInfo *MFI = MF.getFrameInfo();
3747   MFI->setReturnAddressIsTaken(true);
3748
3749   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
3750     return SDValue();
3751
3752   EVT VT = Op.getValueType();
3753   SDLoc dl(Op);
3754   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3755   if (Depth) {
3756     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3757     SDValue Offset = DAG.getConstant(4, MVT::i32);
3758     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
3759                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
3760                        MachinePointerInfo(), false, false, false, 0);
3761   }
3762
3763   // Return LR, which contains the return address. Mark it an implicit live-in.
3764   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3765   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
3766 }
3767
3768 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
3769   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3770   MFI->setFrameAddressIsTaken(true);
3771
3772   EVT VT = Op.getValueType();
3773   SDLoc dl(Op);  // FIXME probably not meaningful
3774   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3775   unsigned FrameReg = (Subtarget->isThumb() || Subtarget->isTargetMachO())
3776     ? ARM::R7 : ARM::R11;
3777   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
3778   while (Depth--)
3779     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
3780                             MachinePointerInfo(),
3781                             false, false, false, 0);
3782   return FrameAddr;
3783 }
3784
3785 /// ExpandBITCAST - If the target supports VFP, this function is called to
3786 /// expand a bit convert where either the source or destination type is i64 to
3787 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
3788 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
3789 /// vectors), since the legalizer won't know what to do with that.
3790 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
3791   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3792   SDLoc dl(N);
3793   SDValue Op = N->getOperand(0);
3794
3795   // This function is only supposed to be called for i64 types, either as the
3796   // source or destination of the bit convert.
3797   EVT SrcVT = Op.getValueType();
3798   EVT DstVT = N->getValueType(0);
3799   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
3800          "ExpandBITCAST called for non-i64 type");
3801
3802   // Turn i64->f64 into VMOVDRR.
3803   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
3804     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3805                              DAG.getConstant(0, MVT::i32));
3806     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3807                              DAG.getConstant(1, MVT::i32));
3808     return DAG.getNode(ISD::BITCAST, dl, DstVT,
3809                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
3810   }
3811
3812   // Turn f64->i64 into VMOVRRD.
3813   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
3814     SDValue Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
3815                               DAG.getVTList(MVT::i32, MVT::i32), &Op, 1);
3816     // Merge the pieces into a single i64 value.
3817     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
3818   }
3819
3820   return SDValue();
3821 }
3822
3823 /// getZeroVector - Returns a vector of specified type with all zero elements.
3824 /// Zero vectors are used to represent vector negation and in those cases
3825 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
3826 /// not support i64 elements, so sometimes the zero vectors will need to be
3827 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
3828 /// zero vector.
3829 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
3830   assert(VT.isVector() && "Expected a vector type");
3831   // The canonical modified immediate encoding of a zero vector is....0!
3832   SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
3833   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
3834   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
3835   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
3836 }
3837
3838 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
3839 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3840 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
3841                                                 SelectionDAG &DAG) const {
3842   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3843   EVT VT = Op.getValueType();
3844   unsigned VTBits = VT.getSizeInBits();
3845   SDLoc dl(Op);
3846   SDValue ShOpLo = Op.getOperand(0);
3847   SDValue ShOpHi = Op.getOperand(1);
3848   SDValue ShAmt  = Op.getOperand(2);
3849   SDValue ARMcc;
3850   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
3851
3852   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
3853
3854   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3855                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
3856   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
3857   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3858                                    DAG.getConstant(VTBits, MVT::i32));
3859   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
3860   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3861   SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
3862
3863   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3864   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3865                           ARMcc, DAG, dl);
3866   SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
3867   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
3868                            CCR, Cmp);
3869
3870   SDValue Ops[2] = { Lo, Hi };
3871   return DAG.getMergeValues(Ops, 2, dl);
3872 }
3873
3874 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
3875 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3876 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
3877                                                SelectionDAG &DAG) const {
3878   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3879   EVT VT = Op.getValueType();
3880   unsigned VTBits = VT.getSizeInBits();
3881   SDLoc dl(Op);
3882   SDValue ShOpLo = Op.getOperand(0);
3883   SDValue ShOpHi = Op.getOperand(1);
3884   SDValue ShAmt  = Op.getOperand(2);
3885   SDValue ARMcc;
3886
3887   assert(Op.getOpcode() == ISD::SHL_PARTS);
3888   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3889                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
3890   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
3891   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3892                                    DAG.getConstant(VTBits, MVT::i32));
3893   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
3894   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
3895
3896   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3897   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3898   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3899                           ARMcc, DAG, dl);
3900   SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
3901   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
3902                            CCR, Cmp);
3903
3904   SDValue Ops[2] = { Lo, Hi };
3905   return DAG.getMergeValues(Ops, 2, dl);
3906 }
3907
3908 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
3909                                             SelectionDAG &DAG) const {
3910   // The rounding mode is in bits 23:22 of the FPSCR.
3911   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
3912   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
3913   // so that the shift + and get folded into a bitfield extract.
3914   SDLoc dl(Op);
3915   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
3916                               DAG.getConstant(Intrinsic::arm_get_fpscr,
3917                                               MVT::i32));
3918   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
3919                                   DAG.getConstant(1U << 22, MVT::i32));
3920   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
3921                               DAG.getConstant(22, MVT::i32));
3922   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
3923                      DAG.getConstant(3, MVT::i32));
3924 }
3925
3926 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
3927                          const ARMSubtarget *ST) {
3928   EVT VT = N->getValueType(0);
3929   SDLoc dl(N);
3930
3931   if (!ST->hasV6T2Ops())
3932     return SDValue();
3933
3934   SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
3935   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
3936 }
3937
3938 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
3939 /// for each 16-bit element from operand, repeated.  The basic idea is to
3940 /// leverage vcnt to get the 8-bit counts, gather and add the results.
3941 ///
3942 /// Trace for v4i16:
3943 /// input    = [v0    v1    v2    v3   ] (vi 16-bit element)
3944 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
3945 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
3946 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
3947 ///            [b0 b1 b2 b3 b4 b5 b6 b7]
3948 ///           +[b1 b0 b3 b2 b5 b4 b7 b6]
3949 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
3950 /// vuzp:    = [k0 k1 k2 k3 k0 k1 k2 k3]  each ki is 8-bits)
3951 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
3952   EVT VT = N->getValueType(0);
3953   SDLoc DL(N);
3954
3955   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
3956   SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
3957   SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
3958   SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
3959   SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
3960   return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
3961 }
3962
3963 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
3964 /// bit-count for each 16-bit element from the operand.  We need slightly
3965 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
3966 /// 64/128-bit registers.
3967 ///
3968 /// Trace for v4i16:
3969 /// input           = [v0    v1    v2    v3    ] (vi 16-bit element)
3970 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
3971 /// v8i16:Extended  = [k0    k1    k2    k3    k0    k1    k2    k3    ]
3972 /// v4i16:Extracted = [k0    k1    k2    k3    ]
3973 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
3974   EVT VT = N->getValueType(0);
3975   SDLoc DL(N);
3976
3977   SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
3978   if (VT.is64BitVector()) {
3979     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
3980     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
3981                        DAG.getIntPtrConstant(0));
3982   } else {
3983     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
3984                                     BitCounts, DAG.getIntPtrConstant(0));
3985     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
3986   }
3987 }
3988
3989 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
3990 /// bit-count for each 32-bit element from the operand.  The idea here is
3991 /// to split the vector into 16-bit elements, leverage the 16-bit count
3992 /// routine, and then combine the results.
3993 ///
3994 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
3995 /// input    = [v0    v1    ] (vi: 32-bit elements)
3996 /// Bitcast  = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
3997 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
3998 /// vrev: N0 = [k1 k0 k3 k2 ]
3999 ///            [k0 k1 k2 k3 ]
4000 ///       N1 =+[k1 k0 k3 k2 ]
4001 ///            [k0 k2 k1 k3 ]
4002 ///       N2 =+[k1 k3 k0 k2 ]
4003 ///            [k0    k2    k1    k3    ]
4004 /// Extended =+[k1    k3    k0    k2    ]
4005 ///            [k0    k2    ]
4006 /// Extracted=+[k1    k3    ]
4007 ///
4008 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4009   EVT VT = N->getValueType(0);
4010   SDLoc DL(N);
4011
4012   EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4013
4014   SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4015   SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4016   SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4017   SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4018   SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4019
4020   if (VT.is64BitVector()) {
4021     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4022     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4023                        DAG.getIntPtrConstant(0));
4024   } else {
4025     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4026                                     DAG.getIntPtrConstant(0));
4027     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4028   }
4029 }
4030
4031 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4032                           const ARMSubtarget *ST) {
4033   EVT VT = N->getValueType(0);
4034
4035   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4036   assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4037           VT == MVT::v4i16 || VT == MVT::v8i16) &&
4038          "Unexpected type for custom ctpop lowering");
4039
4040   if (VT.getVectorElementType() == MVT::i32)
4041     return lowerCTPOP32BitElements(N, DAG);
4042   else
4043     return lowerCTPOP16BitElements(N, DAG);
4044 }
4045
4046 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4047                           const ARMSubtarget *ST) {
4048   EVT VT = N->getValueType(0);
4049   SDLoc dl(N);
4050
4051   if (!VT.isVector())
4052     return SDValue();
4053
4054   // Lower vector shifts on NEON to use VSHL.
4055   assert(ST->hasNEON() && "unexpected vector shift");
4056
4057   // Left shifts translate directly to the vshiftu intrinsic.
4058   if (N->getOpcode() == ISD::SHL)
4059     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4060                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
4061                        N->getOperand(0), N->getOperand(1));
4062
4063   assert((N->getOpcode() == ISD::SRA ||
4064           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4065
4066   // NEON uses the same intrinsics for both left and right shifts.  For
4067   // right shifts, the shift amounts are negative, so negate the vector of
4068   // shift amounts.
4069   EVT ShiftVT = N->getOperand(1).getValueType();
4070   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4071                                      getZeroVector(ShiftVT, DAG, dl),
4072                                      N->getOperand(1));
4073   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4074                              Intrinsic::arm_neon_vshifts :
4075                              Intrinsic::arm_neon_vshiftu);
4076   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4077                      DAG.getConstant(vshiftInt, MVT::i32),
4078                      N->getOperand(0), NegatedCount);
4079 }
4080
4081 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4082                                 const ARMSubtarget *ST) {
4083   EVT VT = N->getValueType(0);
4084   SDLoc dl(N);
4085
4086   // We can get here for a node like i32 = ISD::SHL i32, i64
4087   if (VT != MVT::i64)
4088     return SDValue();
4089
4090   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4091          "Unknown shift to lower!");
4092
4093   // We only lower SRA, SRL of 1 here, all others use generic lowering.
4094   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4095       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4096     return SDValue();
4097
4098   // If we are in thumb mode, we don't have RRX.
4099   if (ST->isThumb1Only()) return SDValue();
4100
4101   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
4102   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4103                            DAG.getConstant(0, MVT::i32));
4104   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4105                            DAG.getConstant(1, MVT::i32));
4106
4107   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4108   // captures the result into a carry flag.
4109   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4110   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), &Hi, 1);
4111
4112   // The low part is an ARMISD::RRX operand, which shifts the carry in.
4113   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4114
4115   // Merge the pieces into a single i64 value.
4116  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4117 }
4118
4119 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4120   SDValue TmpOp0, TmpOp1;
4121   bool Invert = false;
4122   bool Swap = false;
4123   unsigned Opc = 0;
4124
4125   SDValue Op0 = Op.getOperand(0);
4126   SDValue Op1 = Op.getOperand(1);
4127   SDValue CC = Op.getOperand(2);
4128   EVT VT = Op.getValueType();
4129   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4130   SDLoc dl(Op);
4131
4132   if (Op.getOperand(1).getValueType().isFloatingPoint()) {
4133     switch (SetCCOpcode) {
4134     default: llvm_unreachable("Illegal FP comparison");
4135     case ISD::SETUNE:
4136     case ISD::SETNE:  Invert = true; // Fallthrough
4137     case ISD::SETOEQ:
4138     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4139     case ISD::SETOLT:
4140     case ISD::SETLT: Swap = true; // Fallthrough
4141     case ISD::SETOGT:
4142     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4143     case ISD::SETOLE:
4144     case ISD::SETLE:  Swap = true; // Fallthrough
4145     case ISD::SETOGE:
4146     case ISD::SETGE: Opc = ARMISD::VCGE; break;
4147     case ISD::SETUGE: Swap = true; // Fallthrough
4148     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4149     case ISD::SETUGT: Swap = true; // Fallthrough
4150     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4151     case ISD::SETUEQ: Invert = true; // Fallthrough
4152     case ISD::SETONE:
4153       // Expand this to (OLT | OGT).
4154       TmpOp0 = Op0;
4155       TmpOp1 = Op1;
4156       Opc = ISD::OR;
4157       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4158       Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
4159       break;
4160     case ISD::SETUO: Invert = true; // Fallthrough
4161     case ISD::SETO:
4162       // Expand this to (OLT | OGE).
4163       TmpOp0 = Op0;
4164       TmpOp1 = Op1;
4165       Opc = ISD::OR;
4166       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4167       Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
4168       break;
4169     }
4170   } else {
4171     // Integer comparisons.
4172     switch (SetCCOpcode) {
4173     default: llvm_unreachable("Illegal integer comparison");
4174     case ISD::SETNE:  Invert = true;
4175     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4176     case ISD::SETLT:  Swap = true;
4177     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4178     case ISD::SETLE:  Swap = true;
4179     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
4180     case ISD::SETULT: Swap = true;
4181     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4182     case ISD::SETULE: Swap = true;
4183     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4184     }
4185
4186     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4187     if (Opc == ARMISD::VCEQ) {
4188
4189       SDValue AndOp;
4190       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4191         AndOp = Op0;
4192       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4193         AndOp = Op1;
4194
4195       // Ignore bitconvert.
4196       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4197         AndOp = AndOp.getOperand(0);
4198
4199       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4200         Opc = ARMISD::VTST;
4201         Op0 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(0));
4202         Op1 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(1));
4203         Invert = !Invert;
4204       }
4205     }
4206   }
4207
4208   if (Swap)
4209     std::swap(Op0, Op1);
4210
4211   // If one of the operands is a constant vector zero, attempt to fold the
4212   // comparison to a specialized compare-against-zero form.
4213   SDValue SingleOp;
4214   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4215     SingleOp = Op0;
4216   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4217     if (Opc == ARMISD::VCGE)
4218       Opc = ARMISD::VCLEZ;
4219     else if (Opc == ARMISD::VCGT)
4220       Opc = ARMISD::VCLTZ;
4221     SingleOp = Op1;
4222   }
4223
4224   SDValue Result;
4225   if (SingleOp.getNode()) {
4226     switch (Opc) {
4227     case ARMISD::VCEQ:
4228       Result = DAG.getNode(ARMISD::VCEQZ, dl, VT, SingleOp); break;
4229     case ARMISD::VCGE:
4230       Result = DAG.getNode(ARMISD::VCGEZ, dl, VT, SingleOp); break;
4231     case ARMISD::VCLEZ:
4232       Result = DAG.getNode(ARMISD::VCLEZ, dl, VT, SingleOp); break;
4233     case ARMISD::VCGT:
4234       Result = DAG.getNode(ARMISD::VCGTZ, dl, VT, SingleOp); break;
4235     case ARMISD::VCLTZ:
4236       Result = DAG.getNode(ARMISD::VCLTZ, dl, VT, SingleOp); break;
4237     default:
4238       Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4239     }
4240   } else {
4241      Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4242   }
4243
4244   if (Invert)
4245     Result = DAG.getNOT(dl, Result, VT);
4246
4247   return Result;
4248 }
4249
4250 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4251 /// valid vector constant for a NEON instruction with a "modified immediate"
4252 /// operand (e.g., VMOV).  If so, return the encoded value.
4253 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4254                                  unsigned SplatBitSize, SelectionDAG &DAG,
4255                                  EVT &VT, bool is128Bits, NEONModImmType type) {
4256   unsigned OpCmode, Imm;
4257
4258   // SplatBitSize is set to the smallest size that splats the vector, so a
4259   // zero vector will always have SplatBitSize == 8.  However, NEON modified
4260   // immediate instructions others than VMOV do not support the 8-bit encoding
4261   // of a zero vector, and the default encoding of zero is supposed to be the
4262   // 32-bit version.
4263   if (SplatBits == 0)
4264     SplatBitSize = 32;
4265
4266   switch (SplatBitSize) {
4267   case 8:
4268     if (type != VMOVModImm)
4269       return SDValue();
4270     // Any 1-byte value is OK.  Op=0, Cmode=1110.
4271     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4272     OpCmode = 0xe;
4273     Imm = SplatBits;
4274     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4275     break;
4276
4277   case 16:
4278     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4279     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4280     if ((SplatBits & ~0xff) == 0) {
4281       // Value = 0x00nn: Op=x, Cmode=100x.
4282       OpCmode = 0x8;
4283       Imm = SplatBits;
4284       break;
4285     }
4286     if ((SplatBits & ~0xff00) == 0) {
4287       // Value = 0xnn00: Op=x, Cmode=101x.
4288       OpCmode = 0xa;
4289       Imm = SplatBits >> 8;
4290       break;
4291     }
4292     return SDValue();
4293
4294   case 32:
4295     // NEON's 32-bit VMOV supports splat values where:
4296     // * only one byte is nonzero, or
4297     // * the least significant byte is 0xff and the second byte is nonzero, or
4298     // * the least significant 2 bytes are 0xff and the third is nonzero.
4299     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4300     if ((SplatBits & ~0xff) == 0) {
4301       // Value = 0x000000nn: Op=x, Cmode=000x.
4302       OpCmode = 0;
4303       Imm = SplatBits;
4304       break;
4305     }
4306     if ((SplatBits & ~0xff00) == 0) {
4307       // Value = 0x0000nn00: Op=x, Cmode=001x.
4308       OpCmode = 0x2;
4309       Imm = SplatBits >> 8;
4310       break;
4311     }
4312     if ((SplatBits & ~0xff0000) == 0) {
4313       // Value = 0x00nn0000: Op=x, Cmode=010x.
4314       OpCmode = 0x4;
4315       Imm = SplatBits >> 16;
4316       break;
4317     }
4318     if ((SplatBits & ~0xff000000) == 0) {
4319       // Value = 0xnn000000: Op=x, Cmode=011x.
4320       OpCmode = 0x6;
4321       Imm = SplatBits >> 24;
4322       break;
4323     }
4324
4325     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4326     if (type == OtherModImm) return SDValue();
4327
4328     if ((SplatBits & ~0xffff) == 0 &&
4329         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4330       // Value = 0x0000nnff: Op=x, Cmode=1100.
4331       OpCmode = 0xc;
4332       Imm = SplatBits >> 8;
4333       break;
4334     }
4335
4336     if ((SplatBits & ~0xffffff) == 0 &&
4337         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4338       // Value = 0x00nnffff: Op=x, Cmode=1101.
4339       OpCmode = 0xd;
4340       Imm = SplatBits >> 16;
4341       break;
4342     }
4343
4344     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4345     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4346     // VMOV.I32.  A (very) minor optimization would be to replicate the value
4347     // and fall through here to test for a valid 64-bit splat.  But, then the
4348     // caller would also need to check and handle the change in size.
4349     return SDValue();
4350
4351   case 64: {
4352     if (type != VMOVModImm)
4353       return SDValue();
4354     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4355     uint64_t BitMask = 0xff;
4356     uint64_t Val = 0;
4357     unsigned ImmMask = 1;
4358     Imm = 0;
4359     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4360       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4361         Val |= BitMask;
4362         Imm |= ImmMask;
4363       } else if ((SplatBits & BitMask) != 0) {
4364         return SDValue();
4365       }
4366       BitMask <<= 8;
4367       ImmMask <<= 1;
4368     }
4369     // Op=1, Cmode=1110.
4370     OpCmode = 0x1e;
4371     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4372     break;
4373   }
4374
4375   default:
4376     llvm_unreachable("unexpected size for isNEONModifiedImm");
4377   }
4378
4379   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4380   return DAG.getTargetConstant(EncodedVal, MVT::i32);
4381 }
4382
4383 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4384                                            const ARMSubtarget *ST) const {
4385   if (!ST->hasVFP3())
4386     return SDValue();
4387
4388   bool IsDouble = Op.getValueType() == MVT::f64;
4389   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4390
4391   // Try splatting with a VMOV.f32...
4392   APFloat FPVal = CFP->getValueAPF();
4393   int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4394
4395   if (ImmVal != -1) {
4396     if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4397       // We have code in place to select a valid ConstantFP already, no need to
4398       // do any mangling.
4399       return Op;
4400     }
4401
4402     // It's a float and we are trying to use NEON operations where
4403     // possible. Lower it to a splat followed by an extract.
4404     SDLoc DL(Op);
4405     SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
4406     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4407                                       NewVal);
4408     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4409                        DAG.getConstant(0, MVT::i32));
4410   }
4411
4412   // The rest of our options are NEON only, make sure that's allowed before
4413   // proceeding..
4414   if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4415     return SDValue();
4416
4417   EVT VMovVT;
4418   uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4419
4420   // It wouldn't really be worth bothering for doubles except for one very
4421   // important value, which does happen to match: 0.0. So make sure we don't do
4422   // anything stupid.
4423   if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4424     return SDValue();
4425
4426   // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4427   SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4428                                      false, VMOVModImm);
4429   if (NewVal != SDValue()) {
4430     SDLoc DL(Op);
4431     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4432                                       NewVal);
4433     if (IsDouble)
4434       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4435
4436     // It's a float: cast and extract a vector element.
4437     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4438                                        VecConstant);
4439     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4440                        DAG.getConstant(0, MVT::i32));
4441   }
4442
4443   // Finally, try a VMVN.i32
4444   NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4445                              false, VMVNModImm);
4446   if (NewVal != SDValue()) {
4447     SDLoc DL(Op);
4448     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4449
4450     if (IsDouble)
4451       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4452
4453     // It's a float: cast and extract a vector element.
4454     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4455                                        VecConstant);
4456     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4457                        DAG.getConstant(0, MVT::i32));
4458   }
4459
4460   return SDValue();
4461 }
4462
4463 // check if an VEXT instruction can handle the shuffle mask when the
4464 // vector sources of the shuffle are the same.
4465 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4466   unsigned NumElts = VT.getVectorNumElements();
4467
4468   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4469   if (M[0] < 0)
4470     return false;
4471
4472   Imm = M[0];
4473
4474   // If this is a VEXT shuffle, the immediate value is the index of the first
4475   // element.  The other shuffle indices must be the successive elements after
4476   // the first one.
4477   unsigned ExpectedElt = Imm;
4478   for (unsigned i = 1; i < NumElts; ++i) {
4479     // Increment the expected index.  If it wraps around, just follow it
4480     // back to index zero and keep going.
4481     ++ExpectedElt;
4482     if (ExpectedElt == NumElts)
4483       ExpectedElt = 0;
4484
4485     if (M[i] < 0) continue; // ignore UNDEF indices
4486     if (ExpectedElt != static_cast<unsigned>(M[i]))
4487       return false;
4488   }
4489
4490   return true;
4491 }
4492
4493
4494 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4495                        bool &ReverseVEXT, unsigned &Imm) {
4496   unsigned NumElts = VT.getVectorNumElements();
4497   ReverseVEXT = false;
4498
4499   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4500   if (M[0] < 0)
4501     return false;
4502
4503   Imm = M[0];
4504
4505   // If this is a VEXT shuffle, the immediate value is the index of the first
4506   // element.  The other shuffle indices must be the successive elements after
4507   // the first one.
4508   unsigned ExpectedElt = Imm;
4509   for (unsigned i = 1; i < NumElts; ++i) {
4510     // Increment the expected index.  If it wraps around, it may still be
4511     // a VEXT but the source vectors must be swapped.
4512     ExpectedElt += 1;
4513     if (ExpectedElt == NumElts * 2) {
4514       ExpectedElt = 0;
4515       ReverseVEXT = true;
4516     }
4517
4518     if (M[i] < 0) continue; // ignore UNDEF indices
4519     if (ExpectedElt != static_cast<unsigned>(M[i]))
4520       return false;
4521   }
4522
4523   // Adjust the index value if the source operands will be swapped.
4524   if (ReverseVEXT)
4525     Imm -= NumElts;
4526
4527   return true;
4528 }
4529
4530 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4531 /// instruction with the specified blocksize.  (The order of the elements
4532 /// within each block of the vector is reversed.)
4533 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4534   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4535          "Only possible block sizes for VREV are: 16, 32, 64");
4536
4537   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4538   if (EltSz == 64)
4539     return false;
4540
4541   unsigned NumElts = VT.getVectorNumElements();
4542   unsigned BlockElts = M[0] + 1;
4543   // If the first shuffle index is UNDEF, be optimistic.
4544   if (M[0] < 0)
4545     BlockElts = BlockSize / EltSz;
4546
4547   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4548     return false;
4549
4550   for (unsigned i = 0; i < NumElts; ++i) {
4551     if (M[i] < 0) continue; // ignore UNDEF indices
4552     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4553       return false;
4554   }
4555
4556   return true;
4557 }
4558
4559 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
4560   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
4561   // range, then 0 is placed into the resulting vector. So pretty much any mask
4562   // of 8 elements can work here.
4563   return VT == MVT::v8i8 && M.size() == 8;
4564 }
4565
4566 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4567   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4568   if (EltSz == 64)
4569     return false;
4570
4571   unsigned NumElts = VT.getVectorNumElements();
4572   WhichResult = (M[0] == 0 ? 0 : 1);
4573   for (unsigned i = 0; i < NumElts; i += 2) {
4574     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4575         (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
4576       return false;
4577   }
4578   return true;
4579 }
4580
4581 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
4582 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4583 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4584 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4585   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4586   if (EltSz == 64)
4587     return false;
4588
4589   unsigned NumElts = VT.getVectorNumElements();
4590   WhichResult = (M[0] == 0 ? 0 : 1);
4591   for (unsigned i = 0; i < NumElts; i += 2) {
4592     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4593         (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4594       return false;
4595   }
4596   return true;
4597 }
4598
4599 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4600   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4601   if (EltSz == 64)
4602     return false;
4603
4604   unsigned NumElts = VT.getVectorNumElements();
4605   WhichResult = (M[0] == 0 ? 0 : 1);
4606   for (unsigned i = 0; i != NumElts; ++i) {
4607     if (M[i] < 0) continue; // ignore UNDEF indices
4608     if ((unsigned) M[i] != 2 * i + WhichResult)
4609       return false;
4610   }
4611
4612   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4613   if (VT.is64BitVector() && EltSz == 32)
4614     return false;
4615
4616   return true;
4617 }
4618
4619 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4620 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4621 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4622 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4623   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4624   if (EltSz == 64)
4625     return false;
4626
4627   unsigned Half = VT.getVectorNumElements() / 2;
4628   WhichResult = (M[0] == 0 ? 0 : 1);
4629   for (unsigned j = 0; j != 2; ++j) {
4630     unsigned Idx = WhichResult;
4631     for (unsigned i = 0; i != Half; ++i) {
4632       int MIdx = M[i + j * Half];
4633       if (MIdx >= 0 && (unsigned) MIdx != Idx)
4634         return false;
4635       Idx += 2;
4636     }
4637   }
4638
4639   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4640   if (VT.is64BitVector() && EltSz == 32)
4641     return false;
4642
4643   return true;
4644 }
4645
4646 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4647   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4648   if (EltSz == 64)
4649     return false;
4650
4651   unsigned NumElts = VT.getVectorNumElements();
4652   WhichResult = (M[0] == 0 ? 0 : 1);
4653   unsigned Idx = WhichResult * NumElts / 2;
4654   for (unsigned i = 0; i != NumElts; i += 2) {
4655     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4656         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
4657       return false;
4658     Idx += 1;
4659   }
4660
4661   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4662   if (VT.is64BitVector() && EltSz == 32)
4663     return false;
4664
4665   return true;
4666 }
4667
4668 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
4669 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4670 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4671 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4672   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4673   if (EltSz == 64)
4674     return false;
4675
4676   unsigned NumElts = VT.getVectorNumElements();
4677   WhichResult = (M[0] == 0 ? 0 : 1);
4678   unsigned Idx = WhichResult * NumElts / 2;
4679   for (unsigned i = 0; i != NumElts; i += 2) {
4680     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4681         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
4682       return false;
4683     Idx += 1;
4684   }
4685
4686   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4687   if (VT.is64BitVector() && EltSz == 32)
4688     return false;
4689
4690   return true;
4691 }
4692
4693 /// \return true if this is a reverse operation on an vector.
4694 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
4695   unsigned NumElts = VT.getVectorNumElements();
4696   // Make sure the mask has the right size.
4697   if (NumElts != M.size())
4698       return false;
4699
4700   // Look for <15, ..., 3, -1, 1, 0>.
4701   for (unsigned i = 0; i != NumElts; ++i)
4702     if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
4703       return false;
4704
4705   return true;
4706 }
4707
4708 // If N is an integer constant that can be moved into a register in one
4709 // instruction, return an SDValue of such a constant (will become a MOV
4710 // instruction).  Otherwise return null.
4711 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
4712                                      const ARMSubtarget *ST, SDLoc dl) {
4713   uint64_t Val;
4714   if (!isa<ConstantSDNode>(N))
4715     return SDValue();
4716   Val = cast<ConstantSDNode>(N)->getZExtValue();
4717
4718   if (ST->isThumb1Only()) {
4719     if (Val <= 255 || ~Val <= 255)
4720       return DAG.getConstant(Val, MVT::i32);
4721   } else {
4722     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
4723       return DAG.getConstant(Val, MVT::i32);
4724   }
4725   return SDValue();
4726 }
4727
4728 // If this is a case we can't handle, return null and let the default
4729 // expansion code take care of it.
4730 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
4731                                              const ARMSubtarget *ST) const {
4732   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
4733   SDLoc dl(Op);
4734   EVT VT = Op.getValueType();
4735
4736   APInt SplatBits, SplatUndef;
4737   unsigned SplatBitSize;
4738   bool HasAnyUndefs;
4739   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4740     if (SplatBitSize <= 64) {
4741       // Check if an immediate VMOV works.
4742       EVT VmovVT;
4743       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
4744                                       SplatUndef.getZExtValue(), SplatBitSize,
4745                                       DAG, VmovVT, VT.is128BitVector(),
4746                                       VMOVModImm);
4747       if (Val.getNode()) {
4748         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
4749         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4750       }
4751
4752       // Try an immediate VMVN.
4753       uint64_t NegatedImm = (~SplatBits).getZExtValue();
4754       Val = isNEONModifiedImm(NegatedImm,
4755                                       SplatUndef.getZExtValue(), SplatBitSize,
4756                                       DAG, VmovVT, VT.is128BitVector(),
4757                                       VMVNModImm);
4758       if (Val.getNode()) {
4759         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
4760         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4761       }
4762
4763       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
4764       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
4765         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
4766         if (ImmVal != -1) {
4767           SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
4768           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
4769         }
4770       }
4771     }
4772   }
4773
4774   // Scan through the operands to see if only one value is used.
4775   //
4776   // As an optimisation, even if more than one value is used it may be more
4777   // profitable to splat with one value then change some lanes.
4778   //
4779   // Heuristically we decide to do this if the vector has a "dominant" value,
4780   // defined as splatted to more than half of the lanes.
4781   unsigned NumElts = VT.getVectorNumElements();
4782   bool isOnlyLowElement = true;
4783   bool usesOnlyOneValue = true;
4784   bool hasDominantValue = false;
4785   bool isConstant = true;
4786
4787   // Map of the number of times a particular SDValue appears in the
4788   // element list.
4789   DenseMap<SDValue, unsigned> ValueCounts;
4790   SDValue Value;
4791   for (unsigned i = 0; i < NumElts; ++i) {
4792     SDValue V = Op.getOperand(i);
4793     if (V.getOpcode() == ISD::UNDEF)
4794       continue;
4795     if (i > 0)
4796       isOnlyLowElement = false;
4797     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
4798       isConstant = false;
4799
4800     ValueCounts.insert(std::make_pair(V, 0));
4801     unsigned &Count = ValueCounts[V];
4802
4803     // Is this value dominant? (takes up more than half of the lanes)
4804     if (++Count > (NumElts / 2)) {
4805       hasDominantValue = true;
4806       Value = V;
4807     }
4808   }
4809   if (ValueCounts.size() != 1)
4810     usesOnlyOneValue = false;
4811   if (!Value.getNode() && ValueCounts.size() > 0)
4812     Value = ValueCounts.begin()->first;
4813
4814   if (ValueCounts.size() == 0)
4815     return DAG.getUNDEF(VT);
4816
4817   // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
4818   // Keep going if we are hitting this case.
4819   if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
4820     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
4821
4822   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4823
4824   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
4825   // i32 and try again.
4826   if (hasDominantValue && EltSize <= 32) {
4827     if (!isConstant) {
4828       SDValue N;
4829
4830       // If we are VDUPing a value that comes directly from a vector, that will
4831       // cause an unnecessary move to and from a GPR, where instead we could
4832       // just use VDUPLANE. We can only do this if the lane being extracted
4833       // is at a constant index, as the VDUP from lane instructions only have
4834       // constant-index forms.
4835       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
4836           isa<ConstantSDNode>(Value->getOperand(1))) {
4837         // We need to create a new undef vector to use for the VDUPLANE if the
4838         // size of the vector from which we get the value is different than the
4839         // size of the vector that we need to create. We will insert the element
4840         // such that the register coalescer will remove unnecessary copies.
4841         if (VT != Value->getOperand(0).getValueType()) {
4842           ConstantSDNode *constIndex;
4843           constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
4844           assert(constIndex && "The index is not a constant!");
4845           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
4846                              VT.getVectorNumElements();
4847           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4848                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
4849                         Value, DAG.getConstant(index, MVT::i32)),
4850                            DAG.getConstant(index, MVT::i32));
4851         } else
4852           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4853                         Value->getOperand(0), Value->getOperand(1));
4854       } else
4855         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
4856
4857       if (!usesOnlyOneValue) {
4858         // The dominant value was splatted as 'N', but we now have to insert
4859         // all differing elements.
4860         for (unsigned I = 0; I < NumElts; ++I) {
4861           if (Op.getOperand(I) == Value)
4862             continue;
4863           SmallVector<SDValue, 3> Ops;
4864           Ops.push_back(N);
4865           Ops.push_back(Op.getOperand(I));
4866           Ops.push_back(DAG.getConstant(I, MVT::i32));
4867           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, &Ops[0], 3);
4868         }
4869       }
4870       return N;
4871     }
4872     if (VT.getVectorElementType().isFloatingPoint()) {
4873       SmallVector<SDValue, 8> Ops;
4874       for (unsigned i = 0; i < NumElts; ++i)
4875         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
4876                                   Op.getOperand(i)));
4877       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
4878       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], NumElts);
4879       Val = LowerBUILD_VECTOR(Val, DAG, ST);
4880       if (Val.getNode())
4881         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4882     }
4883     if (usesOnlyOneValue) {
4884       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
4885       if (isConstant && Val.getNode())
4886         return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
4887     }
4888   }
4889
4890   // If all elements are constants and the case above didn't get hit, fall back
4891   // to the default expansion, which will generate a load from the constant
4892   // pool.
4893   if (isConstant)
4894     return SDValue();
4895
4896   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
4897   if (NumElts >= 4) {
4898     SDValue shuffle = ReconstructShuffle(Op, DAG);
4899     if (shuffle != SDValue())
4900       return shuffle;
4901   }
4902
4903   // Vectors with 32- or 64-bit elements can be built by directly assigning
4904   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
4905   // will be legalized.
4906   if (EltSize >= 32) {
4907     // Do the expansion with floating-point types, since that is what the VFP
4908     // registers are defined to use, and since i64 is not legal.
4909     EVT EltVT = EVT::getFloatingPointVT(EltSize);
4910     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
4911     SmallVector<SDValue, 8> Ops;
4912     for (unsigned i = 0; i < NumElts; ++i)
4913       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
4914     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
4915     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4916   }
4917
4918   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
4919   // know the default expansion would otherwise fall back on something even
4920   // worse. For a vector with one or two non-undef values, that's
4921   // scalar_to_vector for the elements followed by a shuffle (provided the
4922   // shuffle is valid for the target) and materialization element by element
4923   // on the stack followed by a load for everything else.
4924   if (!isConstant && !usesOnlyOneValue) {
4925     SDValue Vec = DAG.getUNDEF(VT);
4926     for (unsigned i = 0 ; i < NumElts; ++i) {
4927       SDValue V = Op.getOperand(i);
4928       if (V.getOpcode() == ISD::UNDEF)
4929         continue;
4930       SDValue LaneIdx = DAG.getConstant(i, MVT::i32);
4931       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
4932     }
4933     return Vec;
4934   }
4935
4936   return SDValue();
4937 }
4938
4939 // Gather data to see if the operation can be modelled as a
4940 // shuffle in combination with VEXTs.
4941 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
4942                                               SelectionDAG &DAG) const {
4943   SDLoc dl(Op);
4944   EVT VT = Op.getValueType();
4945   unsigned NumElts = VT.getVectorNumElements();
4946
4947   SmallVector<SDValue, 2> SourceVecs;
4948   SmallVector<unsigned, 2> MinElts;
4949   SmallVector<unsigned, 2> MaxElts;
4950
4951   for (unsigned i = 0; i < NumElts; ++i) {
4952     SDValue V = Op.getOperand(i);
4953     if (V.getOpcode() == ISD::UNDEF)
4954       continue;
4955     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
4956       // A shuffle can only come from building a vector from various
4957       // elements of other vectors.
4958       return SDValue();
4959     } else if (V.getOperand(0).getValueType().getVectorElementType() !=
4960                VT.getVectorElementType()) {
4961       // This code doesn't know how to handle shuffles where the vector
4962       // element types do not match (this happens because type legalization
4963       // promotes the return type of EXTRACT_VECTOR_ELT).
4964       // FIXME: It might be appropriate to extend this code to handle
4965       // mismatched types.
4966       return SDValue();
4967     }
4968
4969     // Record this extraction against the appropriate vector if possible...
4970     SDValue SourceVec = V.getOperand(0);
4971     // If the element number isn't a constant, we can't effectively
4972     // analyze what's going on.
4973     if (!isa<ConstantSDNode>(V.getOperand(1)))
4974       return SDValue();
4975     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
4976     bool FoundSource = false;
4977     for (unsigned j = 0; j < SourceVecs.size(); ++j) {
4978       if (SourceVecs[j] == SourceVec) {
4979         if (MinElts[j] > EltNo)
4980           MinElts[j] = EltNo;
4981         if (MaxElts[j] < EltNo)
4982           MaxElts[j] = EltNo;
4983         FoundSource = true;
4984         break;
4985       }
4986     }
4987
4988     // Or record a new source if not...
4989     if (!FoundSource) {
4990       SourceVecs.push_back(SourceVec);
4991       MinElts.push_back(EltNo);
4992       MaxElts.push_back(EltNo);
4993     }
4994   }
4995
4996   // Currently only do something sane when at most two source vectors
4997   // involved.
4998   if (SourceVecs.size() > 2)
4999     return SDValue();
5000
5001   SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
5002   int VEXTOffsets[2] = {0, 0};
5003
5004   // This loop extracts the usage patterns of the source vectors
5005   // and prepares appropriate SDValues for a shuffle if possible.
5006   for (unsigned i = 0; i < SourceVecs.size(); ++i) {
5007     if (SourceVecs[i].getValueType() == VT) {
5008       // No VEXT necessary
5009       ShuffleSrcs[i] = SourceVecs[i];
5010       VEXTOffsets[i] = 0;
5011       continue;
5012     } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
5013       // It probably isn't worth padding out a smaller vector just to
5014       // break it down again in a shuffle.
5015       return SDValue();
5016     }
5017
5018     // Since only 64-bit and 128-bit vectors are legal on ARM and
5019     // we've eliminated the other cases...
5020     assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
5021            "unexpected vector sizes in ReconstructShuffle");
5022
5023     if (MaxElts[i] - MinElts[i] >= NumElts) {
5024       // Span too large for a VEXT to cope
5025       return SDValue();
5026     }
5027
5028     if (MinElts[i] >= NumElts) {
5029       // The extraction can just take the second half
5030       VEXTOffsets[i] = NumElts;
5031       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5032                                    SourceVecs[i],
5033                                    DAG.getIntPtrConstant(NumElts));
5034     } else if (MaxElts[i] < NumElts) {
5035       // The extraction can just take the first half
5036       VEXTOffsets[i] = 0;
5037       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5038                                    SourceVecs[i],
5039                                    DAG.getIntPtrConstant(0));
5040     } else {
5041       // An actual VEXT is needed
5042       VEXTOffsets[i] = MinElts[i];
5043       SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5044                                      SourceVecs[i],
5045                                      DAG.getIntPtrConstant(0));
5046       SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5047                                      SourceVecs[i],
5048                                      DAG.getIntPtrConstant(NumElts));
5049       ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
5050                                    DAG.getConstant(VEXTOffsets[i], MVT::i32));
5051     }
5052   }
5053
5054   SmallVector<int, 8> Mask;
5055
5056   for (unsigned i = 0; i < NumElts; ++i) {
5057     SDValue Entry = Op.getOperand(i);
5058     if (Entry.getOpcode() == ISD::UNDEF) {
5059       Mask.push_back(-1);
5060       continue;
5061     }
5062
5063     SDValue ExtractVec = Entry.getOperand(0);
5064     int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
5065                                           .getOperand(1))->getSExtValue();
5066     if (ExtractVec == SourceVecs[0]) {
5067       Mask.push_back(ExtractElt - VEXTOffsets[0]);
5068     } else {
5069       Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
5070     }
5071   }
5072
5073   // Final check before we try to produce nonsense...
5074   if (isShuffleMaskLegal(Mask, VT))
5075     return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
5076                                 &Mask[0]);
5077
5078   return SDValue();
5079 }
5080
5081 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5082 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5083 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5084 /// are assumed to be legal.
5085 bool
5086 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5087                                       EVT VT) const {
5088   if (VT.getVectorNumElements() == 4 &&
5089       (VT.is128BitVector() || VT.is64BitVector())) {
5090     unsigned PFIndexes[4];
5091     for (unsigned i = 0; i != 4; ++i) {
5092       if (M[i] < 0)
5093         PFIndexes[i] = 8;
5094       else
5095         PFIndexes[i] = M[i];
5096     }
5097
5098     // Compute the index in the perfect shuffle table.
5099     unsigned PFTableIndex =
5100       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5101     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5102     unsigned Cost = (PFEntry >> 30);
5103
5104     if (Cost <= 4)
5105       return true;
5106   }
5107
5108   bool ReverseVEXT;
5109   unsigned Imm, WhichResult;
5110
5111   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5112   return (EltSize >= 32 ||
5113           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5114           isVREVMask(M, VT, 64) ||
5115           isVREVMask(M, VT, 32) ||
5116           isVREVMask(M, VT, 16) ||
5117           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5118           isVTBLMask(M, VT) ||
5119           isVTRNMask(M, VT, WhichResult) ||
5120           isVUZPMask(M, VT, WhichResult) ||
5121           isVZIPMask(M, VT, WhichResult) ||
5122           isVTRN_v_undef_Mask(M, VT, WhichResult) ||
5123           isVUZP_v_undef_Mask(M, VT, WhichResult) ||
5124           isVZIP_v_undef_Mask(M, VT, WhichResult) ||
5125           ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5126 }
5127
5128 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5129 /// the specified operations to build the shuffle.
5130 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5131                                       SDValue RHS, SelectionDAG &DAG,
5132                                       SDLoc dl) {
5133   unsigned OpNum = (PFEntry >> 26) & 0x0F;
5134   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5135   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
5136
5137   enum {
5138     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5139     OP_VREV,
5140     OP_VDUP0,
5141     OP_VDUP1,
5142     OP_VDUP2,
5143     OP_VDUP3,
5144     OP_VEXT1,
5145     OP_VEXT2,
5146     OP_VEXT3,
5147     OP_VUZPL, // VUZP, left result
5148     OP_VUZPR, // VUZP, right result
5149     OP_VZIPL, // VZIP, left result
5150     OP_VZIPR, // VZIP, right result
5151     OP_VTRNL, // VTRN, left result
5152     OP_VTRNR  // VTRN, right result
5153   };
5154
5155   if (OpNum == OP_COPY) {
5156     if (LHSID == (1*9+2)*9+3) return LHS;
5157     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5158     return RHS;
5159   }
5160
5161   SDValue OpLHS, OpRHS;
5162   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5163   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5164   EVT VT = OpLHS.getValueType();
5165
5166   switch (OpNum) {
5167   default: llvm_unreachable("Unknown shuffle opcode!");
5168   case OP_VREV:
5169     // VREV divides the vector in half and swaps within the half.
5170     if (VT.getVectorElementType() == MVT::i32 ||
5171         VT.getVectorElementType() == MVT::f32)
5172       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5173     // vrev <4 x i16> -> VREV32
5174     if (VT.getVectorElementType() == MVT::i16)
5175       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5176     // vrev <4 x i8> -> VREV16
5177     assert(VT.getVectorElementType() == MVT::i8);
5178     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5179   case OP_VDUP0:
5180   case OP_VDUP1:
5181   case OP_VDUP2:
5182   case OP_VDUP3:
5183     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5184                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
5185   case OP_VEXT1:
5186   case OP_VEXT2:
5187   case OP_VEXT3:
5188     return DAG.getNode(ARMISD::VEXT, dl, VT,
5189                        OpLHS, OpRHS,
5190                        DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
5191   case OP_VUZPL:
5192   case OP_VUZPR:
5193     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5194                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5195   case OP_VZIPL:
5196   case OP_VZIPR:
5197     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5198                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5199   case OP_VTRNL:
5200   case OP_VTRNR:
5201     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5202                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5203   }
5204 }
5205
5206 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5207                                        ArrayRef<int> ShuffleMask,
5208                                        SelectionDAG &DAG) {
5209   // Check to see if we can use the VTBL instruction.
5210   SDValue V1 = Op.getOperand(0);
5211   SDValue V2 = Op.getOperand(1);
5212   SDLoc DL(Op);
5213
5214   SmallVector<SDValue, 8> VTBLMask;
5215   for (ArrayRef<int>::iterator
5216          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5217     VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
5218
5219   if (V2.getNode()->getOpcode() == ISD::UNDEF)
5220     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5221                        DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
5222                                    &VTBLMask[0], 8));
5223
5224   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5225                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
5226                                  &VTBLMask[0], 8));
5227 }
5228
5229 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5230                                                       SelectionDAG &DAG) {
5231   SDLoc DL(Op);
5232   SDValue OpLHS = Op.getOperand(0);
5233   EVT VT = OpLHS.getValueType();
5234
5235   assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5236          "Expect an v8i16/v16i8 type");
5237   OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5238   // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5239   // extract the first 8 bytes into the top double word and the last 8 bytes
5240   // into the bottom double word. The v8i16 case is similar.
5241   unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5242   return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5243                      DAG.getConstant(ExtractNum, MVT::i32));
5244 }
5245
5246 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5247   SDValue V1 = Op.getOperand(0);
5248   SDValue V2 = Op.getOperand(1);
5249   SDLoc dl(Op);
5250   EVT VT = Op.getValueType();
5251   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5252
5253   // Convert shuffles that are directly supported on NEON to target-specific
5254   // DAG nodes, instead of keeping them as shuffles and matching them again
5255   // during code selection.  This is more efficient and avoids the possibility
5256   // of inconsistencies between legalization and selection.
5257   // FIXME: floating-point vectors should be canonicalized to integer vectors
5258   // of the same time so that they get CSEd properly.
5259   ArrayRef<int> ShuffleMask = SVN->getMask();
5260
5261   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5262   if (EltSize <= 32) {
5263     if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5264       int Lane = SVN->getSplatIndex();
5265       // If this is undef splat, generate it via "just" vdup, if possible.
5266       if (Lane == -1) Lane = 0;
5267
5268       // Test if V1 is a SCALAR_TO_VECTOR.
5269       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5270         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5271       }
5272       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5273       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5274       // reaches it).
5275       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5276           !isa<ConstantSDNode>(V1.getOperand(0))) {
5277         bool IsScalarToVector = true;
5278         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5279           if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5280             IsScalarToVector = false;
5281             break;
5282           }
5283         if (IsScalarToVector)
5284           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5285       }
5286       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5287                          DAG.getConstant(Lane, MVT::i32));
5288     }
5289
5290     bool ReverseVEXT;
5291     unsigned Imm;
5292     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5293       if (ReverseVEXT)
5294         std::swap(V1, V2);
5295       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5296                          DAG.getConstant(Imm, MVT::i32));
5297     }
5298
5299     if (isVREVMask(ShuffleMask, VT, 64))
5300       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5301     if (isVREVMask(ShuffleMask, VT, 32))
5302       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5303     if (isVREVMask(ShuffleMask, VT, 16))
5304       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5305
5306     if (V2->getOpcode() == ISD::UNDEF &&
5307         isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5308       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5309                          DAG.getConstant(Imm, MVT::i32));
5310     }
5311
5312     // Check for Neon shuffles that modify both input vectors in place.
5313     // If both results are used, i.e., if there are two shuffles with the same
5314     // source operands and with masks corresponding to both results of one of
5315     // these operations, DAG memoization will ensure that a single node is
5316     // used for both shuffles.
5317     unsigned WhichResult;
5318     if (isVTRNMask(ShuffleMask, VT, WhichResult))
5319       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5320                          V1, V2).getValue(WhichResult);
5321     if (isVUZPMask(ShuffleMask, VT, WhichResult))
5322       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5323                          V1, V2).getValue(WhichResult);
5324     if (isVZIPMask(ShuffleMask, VT, WhichResult))
5325       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5326                          V1, V2).getValue(WhichResult);
5327
5328     if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5329       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5330                          V1, V1).getValue(WhichResult);
5331     if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5332       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5333                          V1, V1).getValue(WhichResult);
5334     if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5335       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5336                          V1, V1).getValue(WhichResult);
5337   }
5338
5339   // If the shuffle is not directly supported and it has 4 elements, use
5340   // the PerfectShuffle-generated table to synthesize it from other shuffles.
5341   unsigned NumElts = VT.getVectorNumElements();
5342   if (NumElts == 4) {
5343     unsigned PFIndexes[4];
5344     for (unsigned i = 0; i != 4; ++i) {
5345       if (ShuffleMask[i] < 0)
5346         PFIndexes[i] = 8;
5347       else
5348         PFIndexes[i] = ShuffleMask[i];
5349     }
5350
5351     // Compute the index in the perfect shuffle table.
5352     unsigned PFTableIndex =
5353       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5354     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5355     unsigned Cost = (PFEntry >> 30);
5356
5357     if (Cost <= 4)
5358       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5359   }
5360
5361   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
5362   if (EltSize >= 32) {
5363     // Do the expansion with floating-point types, since that is what the VFP
5364     // registers are defined to use, and since i64 is not legal.
5365     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5366     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5367     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
5368     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
5369     SmallVector<SDValue, 8> Ops;
5370     for (unsigned i = 0; i < NumElts; ++i) {
5371       if (ShuffleMask[i] < 0)
5372         Ops.push_back(DAG.getUNDEF(EltVT));
5373       else
5374         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
5375                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
5376                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
5377                                                   MVT::i32)));
5378     }
5379     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
5380     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5381   }
5382
5383   if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
5384     return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
5385
5386   if (VT == MVT::v8i8) {
5387     SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
5388     if (NewOp.getNode())
5389       return NewOp;
5390   }
5391
5392   return SDValue();
5393 }
5394
5395 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5396   // INSERT_VECTOR_ELT is legal only for immediate indexes.
5397   SDValue Lane = Op.getOperand(2);
5398   if (!isa<ConstantSDNode>(Lane))
5399     return SDValue();
5400
5401   return Op;
5402 }
5403
5404 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5405   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
5406   SDValue Lane = Op.getOperand(1);
5407   if (!isa<ConstantSDNode>(Lane))
5408     return SDValue();
5409
5410   SDValue Vec = Op.getOperand(0);
5411   if (Op.getValueType() == MVT::i32 &&
5412       Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
5413     SDLoc dl(Op);
5414     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
5415   }
5416
5417   return Op;
5418 }
5419
5420 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5421   // The only time a CONCAT_VECTORS operation can have legal types is when
5422   // two 64-bit vectors are concatenated to a 128-bit vector.
5423   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
5424          "unexpected CONCAT_VECTORS");
5425   SDLoc dl(Op);
5426   SDValue Val = DAG.getUNDEF(MVT::v2f64);
5427   SDValue Op0 = Op.getOperand(0);
5428   SDValue Op1 = Op.getOperand(1);
5429   if (Op0.getOpcode() != ISD::UNDEF)
5430     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5431                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
5432                       DAG.getIntPtrConstant(0));
5433   if (Op1.getOpcode() != ISD::UNDEF)
5434     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5435                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
5436                       DAG.getIntPtrConstant(1));
5437   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
5438 }
5439
5440 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
5441 /// element has been zero/sign-extended, depending on the isSigned parameter,
5442 /// from an integer type half its size.
5443 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
5444                                    bool isSigned) {
5445   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
5446   EVT VT = N->getValueType(0);
5447   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
5448     SDNode *BVN = N->getOperand(0).getNode();
5449     if (BVN->getValueType(0) != MVT::v4i32 ||
5450         BVN->getOpcode() != ISD::BUILD_VECTOR)
5451       return false;
5452     unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5453     unsigned HiElt = 1 - LoElt;
5454     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
5455     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
5456     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
5457     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
5458     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
5459       return false;
5460     if (isSigned) {
5461       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
5462           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
5463         return true;
5464     } else {
5465       if (Hi0->isNullValue() && Hi1->isNullValue())
5466         return true;
5467     }
5468     return false;
5469   }
5470
5471   if (N->getOpcode() != ISD::BUILD_VECTOR)
5472     return false;
5473
5474   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5475     SDNode *Elt = N->getOperand(i).getNode();
5476     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
5477       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5478       unsigned HalfSize = EltSize / 2;
5479       if (isSigned) {
5480         if (!isIntN(HalfSize, C->getSExtValue()))
5481           return false;
5482       } else {
5483         if (!isUIntN(HalfSize, C->getZExtValue()))
5484           return false;
5485       }
5486       continue;
5487     }
5488     return false;
5489   }
5490
5491   return true;
5492 }
5493
5494 /// isSignExtended - Check if a node is a vector value that is sign-extended
5495 /// or a constant BUILD_VECTOR with sign-extended elements.
5496 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
5497   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
5498     return true;
5499   if (isExtendedBUILD_VECTOR(N, DAG, true))
5500     return true;
5501   return false;
5502 }
5503
5504 /// isZeroExtended - Check if a node is a vector value that is zero-extended
5505 /// or a constant BUILD_VECTOR with zero-extended elements.
5506 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
5507   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
5508     return true;
5509   if (isExtendedBUILD_VECTOR(N, DAG, false))
5510     return true;
5511   return false;
5512 }
5513
5514 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
5515   if (OrigVT.getSizeInBits() >= 64)
5516     return OrigVT;
5517
5518   assert(OrigVT.isSimple() && "Expecting a simple value type");
5519
5520   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
5521   switch (OrigSimpleTy) {
5522   default: llvm_unreachable("Unexpected Vector Type");
5523   case MVT::v2i8:
5524   case MVT::v2i16:
5525      return MVT::v2i32;
5526   case MVT::v4i8:
5527     return  MVT::v4i16;
5528   }
5529 }
5530
5531 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
5532 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
5533 /// We insert the required extension here to get the vector to fill a D register.
5534 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
5535                                             const EVT &OrigTy,
5536                                             const EVT &ExtTy,
5537                                             unsigned ExtOpcode) {
5538   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
5539   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
5540   // 64-bits we need to insert a new extension so that it will be 64-bits.
5541   assert(ExtTy.is128BitVector() && "Unexpected extension size");
5542   if (OrigTy.getSizeInBits() >= 64)
5543     return N;
5544
5545   // Must extend size to at least 64 bits to be used as an operand for VMULL.
5546   EVT NewVT = getExtensionTo64Bits(OrigTy);
5547
5548   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
5549 }
5550
5551 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
5552 /// does not do any sign/zero extension. If the original vector is less
5553 /// than 64 bits, an appropriate extension will be added after the load to
5554 /// reach a total size of 64 bits. We have to add the extension separately
5555 /// because ARM does not have a sign/zero extending load for vectors.
5556 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
5557   EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
5558
5559   // The load already has the right type.
5560   if (ExtendedTy == LD->getMemoryVT())
5561     return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
5562                 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
5563                 LD->isNonTemporal(), LD->isInvariant(),
5564                 LD->getAlignment());
5565
5566   // We need to create a zextload/sextload. We cannot just create a load
5567   // followed by a zext/zext node because LowerMUL is also run during normal
5568   // operation legalization where we can't create illegal types.
5569   return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
5570                         LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
5571                         LD->getMemoryVT(), LD->isVolatile(),
5572                         LD->isNonTemporal(), LD->getAlignment());
5573 }
5574
5575 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
5576 /// extending load, or BUILD_VECTOR with extended elements, return the
5577 /// unextended value. The unextended vector should be 64 bits so that it can
5578 /// be used as an operand to a VMULL instruction. If the original vector size
5579 /// before extension is less than 64 bits we add a an extension to resize
5580 /// the vector to 64 bits.
5581 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
5582   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
5583     return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
5584                                         N->getOperand(0)->getValueType(0),
5585                                         N->getValueType(0),
5586                                         N->getOpcode());
5587
5588   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
5589     return SkipLoadExtensionForVMULL(LD, DAG);
5590
5591   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
5592   // have been legalized as a BITCAST from v4i32.
5593   if (N->getOpcode() == ISD::BITCAST) {
5594     SDNode *BVN = N->getOperand(0).getNode();
5595     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
5596            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
5597     unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5598     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
5599                        BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
5600   }
5601   // Construct a new BUILD_VECTOR with elements truncated to half the size.
5602   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
5603   EVT VT = N->getValueType(0);
5604   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
5605   unsigned NumElts = VT.getVectorNumElements();
5606   MVT TruncVT = MVT::getIntegerVT(EltSize);
5607   SmallVector<SDValue, 8> Ops;
5608   for (unsigned i = 0; i != NumElts; ++i) {
5609     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
5610     const APInt &CInt = C->getAPIntValue();
5611     // Element types smaller than 32 bits are not legal, so use i32 elements.
5612     // The values are implicitly truncated so sext vs. zext doesn't matter.
5613     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
5614   }
5615   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
5616                      MVT::getVectorVT(TruncVT, NumElts), Ops.data(), NumElts);
5617 }
5618
5619 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
5620   unsigned Opcode = N->getOpcode();
5621   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5622     SDNode *N0 = N->getOperand(0).getNode();
5623     SDNode *N1 = N->getOperand(1).getNode();
5624     return N0->hasOneUse() && N1->hasOneUse() &&
5625       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
5626   }
5627   return false;
5628 }
5629
5630 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
5631   unsigned Opcode = N->getOpcode();
5632   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5633     SDNode *N0 = N->getOperand(0).getNode();
5634     SDNode *N1 = N->getOperand(1).getNode();
5635     return N0->hasOneUse() && N1->hasOneUse() &&
5636       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
5637   }
5638   return false;
5639 }
5640
5641 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
5642   // Multiplications are only custom-lowered for 128-bit vectors so that
5643   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
5644   EVT VT = Op.getValueType();
5645   assert(VT.is128BitVector() && VT.isInteger() &&
5646          "unexpected type for custom-lowering ISD::MUL");
5647   SDNode *N0 = Op.getOperand(0).getNode();
5648   SDNode *N1 = Op.getOperand(1).getNode();
5649   unsigned NewOpc = 0;
5650   bool isMLA = false;
5651   bool isN0SExt = isSignExtended(N0, DAG);
5652   bool isN1SExt = isSignExtended(N1, DAG);
5653   if (isN0SExt && isN1SExt)
5654     NewOpc = ARMISD::VMULLs;
5655   else {
5656     bool isN0ZExt = isZeroExtended(N0, DAG);
5657     bool isN1ZExt = isZeroExtended(N1, DAG);
5658     if (isN0ZExt && isN1ZExt)
5659       NewOpc = ARMISD::VMULLu;
5660     else if (isN1SExt || isN1ZExt) {
5661       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
5662       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
5663       if (isN1SExt && isAddSubSExt(N0, DAG)) {
5664         NewOpc = ARMISD::VMULLs;
5665         isMLA = true;
5666       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
5667         NewOpc = ARMISD::VMULLu;
5668         isMLA = true;
5669       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
5670         std::swap(N0, N1);
5671         NewOpc = ARMISD::VMULLu;
5672         isMLA = true;
5673       }
5674     }
5675
5676     if (!NewOpc) {
5677       if (VT == MVT::v2i64)
5678         // Fall through to expand this.  It is not legal.
5679         return SDValue();
5680       else
5681         // Other vector multiplications are legal.
5682         return Op;
5683     }
5684   }
5685
5686   // Legalize to a VMULL instruction.
5687   SDLoc DL(Op);
5688   SDValue Op0;
5689   SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
5690   if (!isMLA) {
5691     Op0 = SkipExtensionForVMULL(N0, DAG);
5692     assert(Op0.getValueType().is64BitVector() &&
5693            Op1.getValueType().is64BitVector() &&
5694            "unexpected types for extended operands to VMULL");
5695     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
5696   }
5697
5698   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
5699   // isel lowering to take advantage of no-stall back to back vmul + vmla.
5700   //   vmull q0, d4, d6
5701   //   vmlal q0, d5, d6
5702   // is faster than
5703   //   vaddl q0, d4, d5
5704   //   vmovl q1, d6
5705   //   vmul  q0, q0, q1
5706   SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
5707   SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
5708   EVT Op1VT = Op1.getValueType();
5709   return DAG.getNode(N0->getOpcode(), DL, VT,
5710                      DAG.getNode(NewOpc, DL, VT,
5711                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
5712                      DAG.getNode(NewOpc, DL, VT,
5713                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
5714 }
5715
5716 static SDValue
5717 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
5718   // Convert to float
5719   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
5720   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
5721   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
5722   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
5723   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
5724   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
5725   // Get reciprocal estimate.
5726   // float4 recip = vrecpeq_f32(yf);
5727   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5728                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
5729   // Because char has a smaller range than uchar, we can actually get away
5730   // without any newton steps.  This requires that we use a weird bias
5731   // of 0xb000, however (again, this has been exhaustively tested).
5732   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
5733   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
5734   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
5735   Y = DAG.getConstant(0xb000, MVT::i32);
5736   Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
5737   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
5738   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
5739   // Convert back to short.
5740   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
5741   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
5742   return X;
5743 }
5744
5745 static SDValue
5746 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
5747   SDValue N2;
5748   // Convert to float.
5749   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
5750   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
5751   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
5752   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
5753   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5754   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5755
5756   // Use reciprocal estimate and one refinement step.
5757   // float4 recip = vrecpeq_f32(yf);
5758   // recip *= vrecpsq_f32(yf, recip);
5759   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5760                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
5761   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5762                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5763                    N1, N2);
5764   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5765   // Because short has a smaller range than ushort, we can actually get away
5766   // with only a single newton step.  This requires that we use a weird bias
5767   // of 89, however (again, this has been exhaustively tested).
5768   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
5769   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5770   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5771   N1 = DAG.getConstant(0x89, MVT::i32);
5772   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5773   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5774   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5775   // Convert back to integer and return.
5776   // return vmovn_s32(vcvt_s32_f32(result));
5777   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5778   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5779   return N0;
5780 }
5781
5782 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
5783   EVT VT = Op.getValueType();
5784   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5785          "unexpected type for custom-lowering ISD::SDIV");
5786
5787   SDLoc dl(Op);
5788   SDValue N0 = Op.getOperand(0);
5789   SDValue N1 = Op.getOperand(1);
5790   SDValue N2, N3;
5791
5792   if (VT == MVT::v8i8) {
5793     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
5794     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
5795
5796     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5797                      DAG.getIntPtrConstant(4));
5798     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5799                      DAG.getIntPtrConstant(4));
5800     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5801                      DAG.getIntPtrConstant(0));
5802     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5803                      DAG.getIntPtrConstant(0));
5804
5805     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
5806     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
5807
5808     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5809     N0 = LowerCONCAT_VECTORS(N0, DAG);
5810
5811     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
5812     return N0;
5813   }
5814   return LowerSDIV_v4i16(N0, N1, dl, DAG);
5815 }
5816
5817 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
5818   EVT VT = Op.getValueType();
5819   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5820          "unexpected type for custom-lowering ISD::UDIV");
5821
5822   SDLoc dl(Op);
5823   SDValue N0 = Op.getOperand(0);
5824   SDValue N1 = Op.getOperand(1);
5825   SDValue N2, N3;
5826
5827   if (VT == MVT::v8i8) {
5828     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
5829     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
5830
5831     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5832                      DAG.getIntPtrConstant(4));
5833     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5834                      DAG.getIntPtrConstant(4));
5835     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5836                      DAG.getIntPtrConstant(0));
5837     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5838                      DAG.getIntPtrConstant(0));
5839
5840     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
5841     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
5842
5843     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5844     N0 = LowerCONCAT_VECTORS(N0, DAG);
5845
5846     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
5847                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
5848                      N0);
5849     return N0;
5850   }
5851
5852   // v4i16 sdiv ... Convert to float.
5853   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
5854   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
5855   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
5856   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
5857   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5858   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5859
5860   // Use reciprocal estimate and two refinement steps.
5861   // float4 recip = vrecpeq_f32(yf);
5862   // recip *= vrecpsq_f32(yf, recip);
5863   // recip *= vrecpsq_f32(yf, recip);
5864   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5865                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
5866   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5867                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5868                    BN1, N2);
5869   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5870   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5871                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5872                    BN1, N2);
5873   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5874   // Simply multiplying by the reciprocal estimate can leave us a few ulps
5875   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
5876   // and that it will never cause us to return an answer too large).
5877   // float4 result = as_float4(as_int4(xf*recip) + 2);
5878   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5879   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5880   N1 = DAG.getConstant(2, MVT::i32);
5881   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5882   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5883   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5884   // Convert back to integer and return.
5885   // return vmovn_u32(vcvt_s32_f32(result));
5886   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5887   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5888   return N0;
5889 }
5890
5891 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
5892   EVT VT = Op.getNode()->getValueType(0);
5893   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
5894
5895   unsigned Opc;
5896   bool ExtraOp = false;
5897   switch (Op.getOpcode()) {
5898   default: llvm_unreachable("Invalid code");
5899   case ISD::ADDC: Opc = ARMISD::ADDC; break;
5900   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
5901   case ISD::SUBC: Opc = ARMISD::SUBC; break;
5902   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
5903   }
5904
5905   if (!ExtraOp)
5906     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
5907                        Op.getOperand(1));
5908   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
5909                      Op.getOperand(1), Op.getOperand(2));
5910 }
5911
5912 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
5913   assert(Subtarget->isTargetDarwin());
5914
5915   // For iOS, we want to call an alternative entry point: __sincos_stret,
5916   // return values are passed via sret.
5917   SDLoc dl(Op);
5918   SDValue Arg = Op.getOperand(0);
5919   EVT ArgVT = Arg.getValueType();
5920   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
5921
5922   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
5923   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5924
5925   // Pair of floats / doubles used to pass the result.
5926   StructType *RetTy = StructType::get(ArgTy, ArgTy, NULL);
5927
5928   // Create stack object for sret.
5929   const uint64_t ByteSize = TLI.getDataLayout()->getTypeAllocSize(RetTy);
5930   const unsigned StackAlign = TLI.getDataLayout()->getPrefTypeAlignment(RetTy);
5931   int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
5932   SDValue SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy());
5933
5934   ArgListTy Args;
5935   ArgListEntry Entry;
5936
5937   Entry.Node = SRet;
5938   Entry.Ty = RetTy->getPointerTo();
5939   Entry.isSExt = false;
5940   Entry.isZExt = false;
5941   Entry.isSRet = true;
5942   Args.push_back(Entry);
5943
5944   Entry.Node = Arg;
5945   Entry.Ty = ArgTy;
5946   Entry.isSExt = false;
5947   Entry.isZExt = false;
5948   Args.push_back(Entry);
5949
5950   const char *LibcallName  = (ArgVT == MVT::f64)
5951   ? "__sincos_stret" : "__sincosf_stret";
5952   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
5953
5954   TargetLowering::
5955   CallLoweringInfo CLI(DAG.getEntryNode(), Type::getVoidTy(*DAG.getContext()),
5956                        false, false, false, false, 0,
5957                        CallingConv::C, /*isTaillCall=*/false,
5958                        /*doesNotRet=*/false, /*isReturnValueUsed*/false,
5959                        Callee, Args, DAG, dl);
5960   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
5961
5962   SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
5963                                 MachinePointerInfo(), false, false, false, 0);
5964
5965   // Address of cos field.
5966   SDValue Add = DAG.getNode(ISD::ADD, dl, getPointerTy(), SRet,
5967                             DAG.getIntPtrConstant(ArgVT.getStoreSize()));
5968   SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
5969                                 MachinePointerInfo(), false, false, false, 0);
5970
5971   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
5972   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
5973                      LoadSin.getValue(0), LoadCos.getValue(0));
5974 }
5975
5976 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
5977   // Monotonic load/store is legal for all targets
5978   if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
5979     return Op;
5980
5981   // Acquire/Release load/store is not legal for targets without a
5982   // dmb or equivalent available.
5983   return SDValue();
5984 }
5985
5986 static void ReplaceREADCYCLECOUNTER(SDNode *N,
5987                                     SmallVectorImpl<SDValue> &Results,
5988                                     SelectionDAG &DAG,
5989                                     const ARMSubtarget *Subtarget) {
5990   SDLoc DL(N);
5991   SDValue Cycles32, OutChain;
5992
5993   if (Subtarget->hasPerfMon()) {
5994     // Under Power Management extensions, the cycle-count is:
5995     //    mrc p15, #0, <Rt>, c9, c13, #0
5996     SDValue Ops[] = { N->getOperand(0), // Chain
5997                       DAG.getConstant(Intrinsic::arm_mrc, MVT::i32),
5998                       DAG.getConstant(15, MVT::i32),
5999                       DAG.getConstant(0, MVT::i32),
6000                       DAG.getConstant(9, MVT::i32),
6001                       DAG.getConstant(13, MVT::i32),
6002                       DAG.getConstant(0, MVT::i32)
6003     };
6004
6005     Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6006                            DAG.getVTList(MVT::i32, MVT::Other), &Ops[0],
6007                            array_lengthof(Ops));
6008     OutChain = Cycles32.getValue(1);
6009   } else {
6010     // Intrinsic is defined to return 0 on unsupported platforms. Technically
6011     // there are older ARM CPUs that have implementation-specific ways of
6012     // obtaining this information (FIXME!).
6013     Cycles32 = DAG.getConstant(0, MVT::i32);
6014     OutChain = DAG.getEntryNode();
6015   }
6016
6017
6018   SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
6019                                  Cycles32, DAG.getConstant(0, MVT::i32));
6020   Results.push_back(Cycles64);
6021   Results.push_back(OutChain);
6022 }
6023
6024 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6025   switch (Op.getOpcode()) {
6026   default: llvm_unreachable("Don't know how to custom lower this!");
6027   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
6028   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
6029   case ISD::GlobalAddress:
6030     return Subtarget->isTargetMachO() ? LowerGlobalAddressDarwin(Op, DAG) :
6031       LowerGlobalAddressELF(Op, DAG);
6032   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6033   case ISD::SELECT:        return LowerSELECT(Op, DAG);
6034   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
6035   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
6036   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
6037   case ISD::VASTART:       return LowerVASTART(Op, DAG);
6038   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6039   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
6040   case ISD::SINT_TO_FP:
6041   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
6042   case ISD::FP_TO_SINT:
6043   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
6044   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
6045   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
6046   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
6047   case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
6048   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6049   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6050   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6051                                                                Subtarget);
6052   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
6053   case ISD::SHL:
6054   case ISD::SRL:
6055   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
6056   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
6057   case ISD::SRL_PARTS:
6058   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
6059   case ISD::CTTZ:          return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6060   case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6061   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
6062   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
6063   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6064   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6065   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6066   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6067   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6068   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
6069   case ISD::MUL:           return LowerMUL(Op, DAG);
6070   case ISD::SDIV:          return LowerSDIV(Op, DAG);
6071   case ISD::UDIV:          return LowerUDIV(Op, DAG);
6072   case ISD::ADDC:
6073   case ISD::ADDE:
6074   case ISD::SUBC:
6075   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6076   case ISD::ATOMIC_LOAD:
6077   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
6078   case ISD::FSINCOS:       return LowerFSINCOS(Op, DAG);
6079   case ISD::SDIVREM:
6080   case ISD::UDIVREM:       return LowerDivRem(Op, DAG);
6081   }
6082 }
6083
6084 /// ReplaceNodeResults - Replace the results of node with an illegal result
6085 /// type with new values built out of custom code.
6086 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6087                                            SmallVectorImpl<SDValue>&Results,
6088                                            SelectionDAG &DAG) const {
6089   SDValue Res;
6090   switch (N->getOpcode()) {
6091   default:
6092     llvm_unreachable("Don't know how to custom expand this!");
6093   case ISD::BITCAST:
6094     Res = ExpandBITCAST(N, DAG);
6095     break;
6096   case ISD::SRL:
6097   case ISD::SRA:
6098     Res = Expand64BitShift(N, DAG, Subtarget);
6099     break;
6100   case ISD::READCYCLECOUNTER:
6101     ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6102     return;
6103   }
6104   if (Res.getNode())
6105     Results.push_back(Res);
6106 }
6107
6108 //===----------------------------------------------------------------------===//
6109 //                           ARM Scheduler Hooks
6110 //===----------------------------------------------------------------------===//
6111
6112 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6113 /// registers the function context.
6114 void ARMTargetLowering::
6115 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6116                        MachineBasicBlock *DispatchBB, int FI) const {
6117   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6118   DebugLoc dl = MI->getDebugLoc();
6119   MachineFunction *MF = MBB->getParent();
6120   MachineRegisterInfo *MRI = &MF->getRegInfo();
6121   MachineConstantPool *MCP = MF->getConstantPool();
6122   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6123   const Function *F = MF->getFunction();
6124
6125   bool isThumb = Subtarget->isThumb();
6126   bool isThumb2 = Subtarget->isThumb2();
6127
6128   unsigned PCLabelId = AFI->createPICLabelUId();
6129   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6130   ARMConstantPoolValue *CPV =
6131     ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6132   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6133
6134   const TargetRegisterClass *TRC = isThumb ?
6135     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6136     (const TargetRegisterClass*)&ARM::GPRRegClass;
6137
6138   // Grab constant pool and fixed stack memory operands.
6139   MachineMemOperand *CPMMO =
6140     MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6141                              MachineMemOperand::MOLoad, 4, 4);
6142
6143   MachineMemOperand *FIMMOSt =
6144     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6145                              MachineMemOperand::MOStore, 4, 4);
6146
6147   // Load the address of the dispatch MBB into the jump buffer.
6148   if (isThumb2) {
6149     // Incoming value: jbuf
6150     //   ldr.n  r5, LCPI1_1
6151     //   orr    r5, r5, #1
6152     //   add    r5, pc
6153     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
6154     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6155     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6156                    .addConstantPoolIndex(CPI)
6157                    .addMemOperand(CPMMO));
6158     // Set the low bit because of thumb mode.
6159     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6160     AddDefaultCC(
6161       AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6162                      .addReg(NewVReg1, RegState::Kill)
6163                      .addImm(0x01)));
6164     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6165     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6166       .addReg(NewVReg2, RegState::Kill)
6167       .addImm(PCLabelId);
6168     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6169                    .addReg(NewVReg3, RegState::Kill)
6170                    .addFrameIndex(FI)
6171                    .addImm(36)  // &jbuf[1] :: pc
6172                    .addMemOperand(FIMMOSt));
6173   } else if (isThumb) {
6174     // Incoming value: jbuf
6175     //   ldr.n  r1, LCPI1_4
6176     //   add    r1, pc
6177     //   mov    r2, #1
6178     //   orrs   r1, r2
6179     //   add    r2, $jbuf, #+4 ; &jbuf[1]
6180     //   str    r1, [r2]
6181     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6182     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6183                    .addConstantPoolIndex(CPI)
6184                    .addMemOperand(CPMMO));
6185     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6186     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6187       .addReg(NewVReg1, RegState::Kill)
6188       .addImm(PCLabelId);
6189     // Set the low bit because of thumb mode.
6190     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6191     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6192                    .addReg(ARM::CPSR, RegState::Define)
6193                    .addImm(1));
6194     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6195     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6196                    .addReg(ARM::CPSR, RegState::Define)
6197                    .addReg(NewVReg2, RegState::Kill)
6198                    .addReg(NewVReg3, RegState::Kill));
6199     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6200     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tADDrSPi), NewVReg5)
6201                    .addFrameIndex(FI)
6202                    .addImm(36)); // &jbuf[1] :: pc
6203     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6204                    .addReg(NewVReg4, RegState::Kill)
6205                    .addReg(NewVReg5, RegState::Kill)
6206                    .addImm(0)
6207                    .addMemOperand(FIMMOSt));
6208   } else {
6209     // Incoming value: jbuf
6210     //   ldr  r1, LCPI1_1
6211     //   add  r1, pc, r1
6212     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
6213     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6214     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12),  NewVReg1)
6215                    .addConstantPoolIndex(CPI)
6216                    .addImm(0)
6217                    .addMemOperand(CPMMO));
6218     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6219     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6220                    .addReg(NewVReg1, RegState::Kill)
6221                    .addImm(PCLabelId));
6222     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6223                    .addReg(NewVReg2, RegState::Kill)
6224                    .addFrameIndex(FI)
6225                    .addImm(36)  // &jbuf[1] :: pc
6226                    .addMemOperand(FIMMOSt));
6227   }
6228 }
6229
6230 MachineBasicBlock *ARMTargetLowering::
6231 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
6232   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6233   DebugLoc dl = MI->getDebugLoc();
6234   MachineFunction *MF = MBB->getParent();
6235   MachineRegisterInfo *MRI = &MF->getRegInfo();
6236   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6237   MachineFrameInfo *MFI = MF->getFrameInfo();
6238   int FI = MFI->getFunctionContextIndex();
6239
6240   const TargetRegisterClass *TRC = Subtarget->isThumb() ?
6241     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6242     (const TargetRegisterClass*)&ARM::GPRnopcRegClass;
6243
6244   // Get a mapping of the call site numbers to all of the landing pads they're
6245   // associated with.
6246   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6247   unsigned MaxCSNum = 0;
6248   MachineModuleInfo &MMI = MF->getMMI();
6249   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6250        ++BB) {
6251     if (!BB->isLandingPad()) continue;
6252
6253     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6254     // pad.
6255     for (MachineBasicBlock::iterator
6256            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6257       if (!II->isEHLabel()) continue;
6258
6259       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6260       if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6261
6262       SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6263       for (SmallVectorImpl<unsigned>::iterator
6264              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6265            CSI != CSE; ++CSI) {
6266         CallSiteNumToLPad[*CSI].push_back(BB);
6267         MaxCSNum = std::max(MaxCSNum, *CSI);
6268       }
6269       break;
6270     }
6271   }
6272
6273   // Get an ordered list of the machine basic blocks for the jump table.
6274   std::vector<MachineBasicBlock*> LPadList;
6275   SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6276   LPadList.reserve(CallSiteNumToLPad.size());
6277   for (unsigned I = 1; I <= MaxCSNum; ++I) {
6278     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6279     for (SmallVectorImpl<MachineBasicBlock*>::iterator
6280            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6281       LPadList.push_back(*II);
6282       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6283     }
6284   }
6285
6286   assert(!LPadList.empty() &&
6287          "No landing pad destinations for the dispatch jump table!");
6288
6289   // Create the jump table and associated information.
6290   MachineJumpTableInfo *JTI =
6291     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6292   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6293   unsigned UId = AFI->createJumpTableUId();
6294   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
6295
6296   // Create the MBBs for the dispatch code.
6297
6298   // Shove the dispatch's address into the return slot in the function context.
6299   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6300   DispatchBB->setIsLandingPad();
6301
6302   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6303   unsigned trap_opcode;
6304   if (Subtarget->isThumb())
6305     trap_opcode = ARM::tTRAP;
6306   else
6307     trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
6308
6309   BuildMI(TrapBB, dl, TII->get(trap_opcode));
6310   DispatchBB->addSuccessor(TrapBB);
6311
6312   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6313   DispatchBB->addSuccessor(DispContBB);
6314
6315   // Insert and MBBs.
6316   MF->insert(MF->end(), DispatchBB);
6317   MF->insert(MF->end(), DispContBB);
6318   MF->insert(MF->end(), TrapBB);
6319
6320   // Insert code into the entry block that creates and registers the function
6321   // context.
6322   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6323
6324   MachineMemOperand *FIMMOLd =
6325     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6326                              MachineMemOperand::MOLoad |
6327                              MachineMemOperand::MOVolatile, 4, 4);
6328
6329   MachineInstrBuilder MIB;
6330   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6331
6332   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6333   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6334
6335   // Add a register mask with no preserved registers.  This results in all
6336   // registers being marked as clobbered.
6337   MIB.addRegMask(RI.getNoPreservedMask());
6338
6339   unsigned NumLPads = LPadList.size();
6340   if (Subtarget->isThumb2()) {
6341     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6342     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6343                    .addFrameIndex(FI)
6344                    .addImm(4)
6345                    .addMemOperand(FIMMOLd));
6346
6347     if (NumLPads < 256) {
6348       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6349                      .addReg(NewVReg1)
6350                      .addImm(LPadList.size()));
6351     } else {
6352       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6353       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6354                      .addImm(NumLPads & 0xFFFF));
6355
6356       unsigned VReg2 = VReg1;
6357       if ((NumLPads & 0xFFFF0000) != 0) {
6358         VReg2 = MRI->createVirtualRegister(TRC);
6359         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6360                        .addReg(VReg1)
6361                        .addImm(NumLPads >> 16));
6362       }
6363
6364       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6365                      .addReg(NewVReg1)
6366                      .addReg(VReg2));
6367     }
6368
6369     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6370       .addMBB(TrapBB)
6371       .addImm(ARMCC::HI)
6372       .addReg(ARM::CPSR);
6373
6374     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6375     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6376                    .addJumpTableIndex(MJTI)
6377                    .addImm(UId));
6378
6379     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6380     AddDefaultCC(
6381       AddDefaultPred(
6382         BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6383         .addReg(NewVReg3, RegState::Kill)
6384         .addReg(NewVReg1)
6385         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6386
6387     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6388       .addReg(NewVReg4, RegState::Kill)
6389       .addReg(NewVReg1)
6390       .addJumpTableIndex(MJTI)
6391       .addImm(UId);
6392   } else if (Subtarget->isThumb()) {
6393     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6394     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6395                    .addFrameIndex(FI)
6396                    .addImm(1)
6397                    .addMemOperand(FIMMOLd));
6398
6399     if (NumLPads < 256) {
6400       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6401                      .addReg(NewVReg1)
6402                      .addImm(NumLPads));
6403     } else {
6404       MachineConstantPool *ConstantPool = MF->getConstantPool();
6405       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6406       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6407
6408       // MachineConstantPool wants an explicit alignment.
6409       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6410       if (Align == 0)
6411         Align = getDataLayout()->getTypeAllocSize(C->getType());
6412       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6413
6414       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6415       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6416                      .addReg(VReg1, RegState::Define)
6417                      .addConstantPoolIndex(Idx));
6418       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
6419                      .addReg(NewVReg1)
6420                      .addReg(VReg1));
6421     }
6422
6423     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
6424       .addMBB(TrapBB)
6425       .addImm(ARMCC::HI)
6426       .addReg(ARM::CPSR);
6427
6428     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6429     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
6430                    .addReg(ARM::CPSR, RegState::Define)
6431                    .addReg(NewVReg1)
6432                    .addImm(2));
6433
6434     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6435     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
6436                    .addJumpTableIndex(MJTI)
6437                    .addImm(UId));
6438
6439     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6440     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
6441                    .addReg(ARM::CPSR, RegState::Define)
6442                    .addReg(NewVReg2, RegState::Kill)
6443                    .addReg(NewVReg3));
6444
6445     MachineMemOperand *JTMMOLd =
6446       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6447                                MachineMemOperand::MOLoad, 4, 4);
6448
6449     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6450     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
6451                    .addReg(NewVReg4, RegState::Kill)
6452                    .addImm(0)
6453                    .addMemOperand(JTMMOLd));
6454
6455     unsigned NewVReg6 = NewVReg5;
6456     if (RelocM == Reloc::PIC_) {
6457       NewVReg6 = MRI->createVirtualRegister(TRC);
6458       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
6459                      .addReg(ARM::CPSR, RegState::Define)
6460                      .addReg(NewVReg5, RegState::Kill)
6461                      .addReg(NewVReg3));
6462     }
6463
6464     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
6465       .addReg(NewVReg6, RegState::Kill)
6466       .addJumpTableIndex(MJTI)
6467       .addImm(UId);
6468   } else {
6469     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6470     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
6471                    .addFrameIndex(FI)
6472                    .addImm(4)
6473                    .addMemOperand(FIMMOLd));
6474
6475     if (NumLPads < 256) {
6476       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
6477                      .addReg(NewVReg1)
6478                      .addImm(NumLPads));
6479     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
6480       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6481       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
6482                      .addImm(NumLPads & 0xFFFF));
6483
6484       unsigned VReg2 = VReg1;
6485       if ((NumLPads & 0xFFFF0000) != 0) {
6486         VReg2 = MRI->createVirtualRegister(TRC);
6487         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
6488                        .addReg(VReg1)
6489                        .addImm(NumLPads >> 16));
6490       }
6491
6492       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6493                      .addReg(NewVReg1)
6494                      .addReg(VReg2));
6495     } else {
6496       MachineConstantPool *ConstantPool = MF->getConstantPool();
6497       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6498       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6499
6500       // MachineConstantPool wants an explicit alignment.
6501       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6502       if (Align == 0)
6503         Align = getDataLayout()->getTypeAllocSize(C->getType());
6504       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6505
6506       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6507       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
6508                      .addReg(VReg1, RegState::Define)
6509                      .addConstantPoolIndex(Idx)
6510                      .addImm(0));
6511       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6512                      .addReg(NewVReg1)
6513                      .addReg(VReg1, RegState::Kill));
6514     }
6515
6516     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
6517       .addMBB(TrapBB)
6518       .addImm(ARMCC::HI)
6519       .addReg(ARM::CPSR);
6520
6521     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6522     AddDefaultCC(
6523       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
6524                      .addReg(NewVReg1)
6525                      .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6526     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6527     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
6528                    .addJumpTableIndex(MJTI)
6529                    .addImm(UId));
6530
6531     MachineMemOperand *JTMMOLd =
6532       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6533                                MachineMemOperand::MOLoad, 4, 4);
6534     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6535     AddDefaultPred(
6536       BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
6537       .addReg(NewVReg3, RegState::Kill)
6538       .addReg(NewVReg4)
6539       .addImm(0)
6540       .addMemOperand(JTMMOLd));
6541
6542     if (RelocM == Reloc::PIC_) {
6543       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
6544         .addReg(NewVReg5, RegState::Kill)
6545         .addReg(NewVReg4)
6546         .addJumpTableIndex(MJTI)
6547         .addImm(UId);
6548     } else {
6549       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
6550         .addReg(NewVReg5, RegState::Kill)
6551         .addJumpTableIndex(MJTI)
6552         .addImm(UId);
6553     }
6554   }
6555
6556   // Add the jump table entries as successors to the MBB.
6557   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
6558   for (std::vector<MachineBasicBlock*>::iterator
6559          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
6560     MachineBasicBlock *CurMBB = *I;
6561     if (SeenMBBs.insert(CurMBB))
6562       DispContBB->addSuccessor(CurMBB);
6563   }
6564
6565   // N.B. the order the invoke BBs are processed in doesn't matter here.
6566   const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
6567   SmallVector<MachineBasicBlock*, 64> MBBLPads;
6568   for (SmallPtrSet<MachineBasicBlock*, 64>::iterator
6569          I = InvokeBBs.begin(), E = InvokeBBs.end(); I != E; ++I) {
6570     MachineBasicBlock *BB = *I;
6571
6572     // Remove the landing pad successor from the invoke block and replace it
6573     // with the new dispatch block.
6574     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
6575                                                   BB->succ_end());
6576     while (!Successors.empty()) {
6577       MachineBasicBlock *SMBB = Successors.pop_back_val();
6578       if (SMBB->isLandingPad()) {
6579         BB->removeSuccessor(SMBB);
6580         MBBLPads.push_back(SMBB);
6581       }
6582     }
6583
6584     BB->addSuccessor(DispatchBB);
6585
6586     // Find the invoke call and mark all of the callee-saved registers as
6587     // 'implicit defined' so that they're spilled. This prevents code from
6588     // moving instructions to before the EH block, where they will never be
6589     // executed.
6590     for (MachineBasicBlock::reverse_iterator
6591            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
6592       if (!II->isCall()) continue;
6593
6594       DenseMap<unsigned, bool> DefRegs;
6595       for (MachineInstr::mop_iterator
6596              OI = II->operands_begin(), OE = II->operands_end();
6597            OI != OE; ++OI) {
6598         if (!OI->isReg()) continue;
6599         DefRegs[OI->getReg()] = true;
6600       }
6601
6602       MachineInstrBuilder MIB(*MF, &*II);
6603
6604       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
6605         unsigned Reg = SavedRegs[i];
6606         if (Subtarget->isThumb2() &&
6607             !ARM::tGPRRegClass.contains(Reg) &&
6608             !ARM::hGPRRegClass.contains(Reg))
6609           continue;
6610         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
6611           continue;
6612         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
6613           continue;
6614         if (!DefRegs[Reg])
6615           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
6616       }
6617
6618       break;
6619     }
6620   }
6621
6622   // Mark all former landing pads as non-landing pads. The dispatch is the only
6623   // landing pad now.
6624   for (SmallVectorImpl<MachineBasicBlock*>::iterator
6625          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
6626     (*I)->setIsLandingPad(false);
6627
6628   // The instruction is gone now.
6629   MI->eraseFromParent();
6630
6631   return MBB;
6632 }
6633
6634 static
6635 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
6636   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
6637        E = MBB->succ_end(); I != E; ++I)
6638     if (*I != Succ)
6639       return *I;
6640   llvm_unreachable("Expecting a BB with two successors!");
6641 }
6642
6643 /// Return the load opcode for a given load size. If load size >= 8,
6644 /// neon opcode will be returned.
6645 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
6646   if (LdSize >= 8)
6647     return LdSize == 16 ? ARM::VLD1q32wb_fixed
6648                         : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
6649   if (IsThumb1)
6650     return LdSize == 4 ? ARM::tLDRi
6651                        : LdSize == 2 ? ARM::tLDRHi
6652                                      : LdSize == 1 ? ARM::tLDRBi : 0;
6653   if (IsThumb2)
6654     return LdSize == 4 ? ARM::t2LDR_POST
6655                        : LdSize == 2 ? ARM::t2LDRH_POST
6656                                      : LdSize == 1 ? ARM::t2LDRB_POST : 0;
6657   return LdSize == 4 ? ARM::LDR_POST_IMM
6658                      : LdSize == 2 ? ARM::LDRH_POST
6659                                    : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
6660 }
6661
6662 /// Return the store opcode for a given store size. If store size >= 8,
6663 /// neon opcode will be returned.
6664 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
6665   if (StSize >= 8)
6666     return StSize == 16 ? ARM::VST1q32wb_fixed
6667                         : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
6668   if (IsThumb1)
6669     return StSize == 4 ? ARM::tSTRi
6670                        : StSize == 2 ? ARM::tSTRHi
6671                                      : StSize == 1 ? ARM::tSTRBi : 0;
6672   if (IsThumb2)
6673     return StSize == 4 ? ARM::t2STR_POST
6674                        : StSize == 2 ? ARM::t2STRH_POST
6675                                      : StSize == 1 ? ARM::t2STRB_POST : 0;
6676   return StSize == 4 ? ARM::STR_POST_IMM
6677                      : StSize == 2 ? ARM::STRH_POST
6678                                    : StSize == 1 ? ARM::STRB_POST_IMM : 0;
6679 }
6680
6681 /// Emit a post-increment load operation with given size. The instructions
6682 /// will be added to BB at Pos.
6683 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
6684                        const TargetInstrInfo *TII, DebugLoc dl,
6685                        unsigned LdSize, unsigned Data, unsigned AddrIn,
6686                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
6687   unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
6688   assert(LdOpc != 0 && "Should have a load opcode");
6689   if (LdSize >= 8) {
6690     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6691                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
6692                        .addImm(0));
6693   } else if (IsThumb1) {
6694     // load + update AddrIn
6695     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6696                        .addReg(AddrIn).addImm(0));
6697     MachineInstrBuilder MIB =
6698         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
6699     MIB = AddDefaultT1CC(MIB);
6700     MIB.addReg(AddrIn).addImm(LdSize);
6701     AddDefaultPred(MIB);
6702   } else if (IsThumb2) {
6703     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6704                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
6705                        .addImm(LdSize));
6706   } else { // arm
6707     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6708                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
6709                        .addReg(0).addImm(LdSize));
6710   }
6711 }
6712
6713 /// Emit a post-increment store operation with given size. The instructions
6714 /// will be added to BB at Pos.
6715 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
6716                        const TargetInstrInfo *TII, DebugLoc dl,
6717                        unsigned StSize, unsigned Data, unsigned AddrIn,
6718                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
6719   unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
6720   assert(StOpc != 0 && "Should have a store opcode");
6721   if (StSize >= 8) {
6722     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
6723                        .addReg(AddrIn).addImm(0).addReg(Data));
6724   } else if (IsThumb1) {
6725     // store + update AddrIn
6726     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
6727                        .addReg(AddrIn).addImm(0));
6728     MachineInstrBuilder MIB =
6729         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
6730     MIB = AddDefaultT1CC(MIB);
6731     MIB.addReg(AddrIn).addImm(StSize);
6732     AddDefaultPred(MIB);
6733   } else if (IsThumb2) {
6734     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
6735                        .addReg(Data).addReg(AddrIn).addImm(StSize));
6736   } else { // arm
6737     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
6738                        .addReg(Data).addReg(AddrIn).addReg(0)
6739                        .addImm(StSize));
6740   }
6741 }
6742
6743 MachineBasicBlock *
6744 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
6745                                    MachineBasicBlock *BB) const {
6746   // This pseudo instruction has 3 operands: dst, src, size
6747   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
6748   // Otherwise, we will generate unrolled scalar copies.
6749   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6750   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6751   MachineFunction::iterator It = BB;
6752   ++It;
6753
6754   unsigned dest = MI->getOperand(0).getReg();
6755   unsigned src = MI->getOperand(1).getReg();
6756   unsigned SizeVal = MI->getOperand(2).getImm();
6757   unsigned Align = MI->getOperand(3).getImm();
6758   DebugLoc dl = MI->getDebugLoc();
6759
6760   MachineFunction *MF = BB->getParent();
6761   MachineRegisterInfo &MRI = MF->getRegInfo();
6762   unsigned UnitSize = 0;
6763   const TargetRegisterClass *TRC = 0;
6764   const TargetRegisterClass *VecTRC = 0;
6765
6766   bool IsThumb1 = Subtarget->isThumb1Only();
6767   bool IsThumb2 = Subtarget->isThumb2();
6768
6769   if (Align & 1) {
6770     UnitSize = 1;
6771   } else if (Align & 2) {
6772     UnitSize = 2;
6773   } else {
6774     // Check whether we can use NEON instructions.
6775     if (!MF->getFunction()->getAttributes().
6776           hasAttribute(AttributeSet::FunctionIndex,
6777                        Attribute::NoImplicitFloat) &&
6778         Subtarget->hasNEON()) {
6779       if ((Align % 16 == 0) && SizeVal >= 16)
6780         UnitSize = 16;
6781       else if ((Align % 8 == 0) && SizeVal >= 8)
6782         UnitSize = 8;
6783     }
6784     // Can't use NEON instructions.
6785     if (UnitSize == 0)
6786       UnitSize = 4;
6787   }
6788
6789   // Select the correct opcode and register class for unit size load/store
6790   bool IsNeon = UnitSize >= 8;
6791   TRC = (IsThumb1 || IsThumb2) ? (const TargetRegisterClass *)&ARM::tGPRRegClass
6792                                : (const TargetRegisterClass *)&ARM::GPRRegClass;
6793   if (IsNeon)
6794     VecTRC = UnitSize == 16
6795                  ? (const TargetRegisterClass *)&ARM::DPairRegClass
6796                  : UnitSize == 8
6797                        ? (const TargetRegisterClass *)&ARM::DPRRegClass
6798                        : 0;
6799
6800   unsigned BytesLeft = SizeVal % UnitSize;
6801   unsigned LoopSize = SizeVal - BytesLeft;
6802
6803   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
6804     // Use LDR and STR to copy.
6805     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
6806     // [destOut] = STR_POST(scratch, destIn, UnitSize)
6807     unsigned srcIn = src;
6808     unsigned destIn = dest;
6809     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
6810       unsigned srcOut = MRI.createVirtualRegister(TRC);
6811       unsigned destOut = MRI.createVirtualRegister(TRC);
6812       unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
6813       emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
6814                  IsThumb1, IsThumb2);
6815       emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
6816                  IsThumb1, IsThumb2);
6817       srcIn = srcOut;
6818       destIn = destOut;
6819     }
6820
6821     // Handle the leftover bytes with LDRB and STRB.
6822     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
6823     // [destOut] = STRB_POST(scratch, destIn, 1)
6824     for (unsigned i = 0; i < BytesLeft; i++) {
6825       unsigned srcOut = MRI.createVirtualRegister(TRC);
6826       unsigned destOut = MRI.createVirtualRegister(TRC);
6827       unsigned scratch = MRI.createVirtualRegister(TRC);
6828       emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
6829                  IsThumb1, IsThumb2);
6830       emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
6831                  IsThumb1, IsThumb2);
6832       srcIn = srcOut;
6833       destIn = destOut;
6834     }
6835     MI->eraseFromParent();   // The instruction is gone now.
6836     return BB;
6837   }
6838
6839   // Expand the pseudo op to a loop.
6840   // thisMBB:
6841   //   ...
6842   //   movw varEnd, # --> with thumb2
6843   //   movt varEnd, #
6844   //   ldrcp varEnd, idx --> without thumb2
6845   //   fallthrough --> loopMBB
6846   // loopMBB:
6847   //   PHI varPhi, varEnd, varLoop
6848   //   PHI srcPhi, src, srcLoop
6849   //   PHI destPhi, dst, destLoop
6850   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
6851   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
6852   //   subs varLoop, varPhi, #UnitSize
6853   //   bne loopMBB
6854   //   fallthrough --> exitMBB
6855   // exitMBB:
6856   //   epilogue to handle left-over bytes
6857   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
6858   //   [destOut] = STRB_POST(scratch, destLoop, 1)
6859   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6860   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6861   MF->insert(It, loopMBB);
6862   MF->insert(It, exitMBB);
6863
6864   // Transfer the remainder of BB and its successor edges to exitMBB.
6865   exitMBB->splice(exitMBB->begin(), BB,
6866                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
6867   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6868
6869   // Load an immediate to varEnd.
6870   unsigned varEnd = MRI.createVirtualRegister(TRC);
6871   if (IsThumb2) {
6872     unsigned Vtmp = varEnd;
6873     if ((LoopSize & 0xFFFF0000) != 0)
6874       Vtmp = MRI.createVirtualRegister(TRC);
6875     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVi16), Vtmp)
6876                        .addImm(LoopSize & 0xFFFF));
6877
6878     if ((LoopSize & 0xFFFF0000) != 0)
6879       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVTi16), varEnd)
6880                          .addReg(Vtmp).addImm(LoopSize >> 16));
6881   } else {
6882     MachineConstantPool *ConstantPool = MF->getConstantPool();
6883     Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6884     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
6885
6886     // MachineConstantPool wants an explicit alignment.
6887     unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6888     if (Align == 0)
6889       Align = getDataLayout()->getTypeAllocSize(C->getType());
6890     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6891
6892     if (IsThumb1)
6893       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
6894           varEnd, RegState::Define).addConstantPoolIndex(Idx));
6895     else
6896       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
6897           varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
6898   }
6899   BB->addSuccessor(loopMBB);
6900
6901   // Generate the loop body:
6902   //   varPhi = PHI(varLoop, varEnd)
6903   //   srcPhi = PHI(srcLoop, src)
6904   //   destPhi = PHI(destLoop, dst)
6905   MachineBasicBlock *entryBB = BB;
6906   BB = loopMBB;
6907   unsigned varLoop = MRI.createVirtualRegister(TRC);
6908   unsigned varPhi = MRI.createVirtualRegister(TRC);
6909   unsigned srcLoop = MRI.createVirtualRegister(TRC);
6910   unsigned srcPhi = MRI.createVirtualRegister(TRC);
6911   unsigned destLoop = MRI.createVirtualRegister(TRC);
6912   unsigned destPhi = MRI.createVirtualRegister(TRC);
6913
6914   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
6915     .addReg(varLoop).addMBB(loopMBB)
6916     .addReg(varEnd).addMBB(entryBB);
6917   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
6918     .addReg(srcLoop).addMBB(loopMBB)
6919     .addReg(src).addMBB(entryBB);
6920   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
6921     .addReg(destLoop).addMBB(loopMBB)
6922     .addReg(dest).addMBB(entryBB);
6923
6924   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
6925   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
6926   unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
6927   emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
6928              IsThumb1, IsThumb2);
6929   emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
6930              IsThumb1, IsThumb2);
6931
6932   // Decrement loop variable by UnitSize.
6933   if (IsThumb1) {
6934     MachineInstrBuilder MIB =
6935         BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
6936     MIB = AddDefaultT1CC(MIB);
6937     MIB.addReg(varPhi).addImm(UnitSize);
6938     AddDefaultPred(MIB);
6939   } else {
6940     MachineInstrBuilder MIB =
6941         BuildMI(*BB, BB->end(), dl,
6942                 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
6943     AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
6944     MIB->getOperand(5).setReg(ARM::CPSR);
6945     MIB->getOperand(5).setIsDef(true);
6946   }
6947   BuildMI(*BB, BB->end(), dl,
6948           TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
6949       .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6950
6951   // loopMBB can loop back to loopMBB or fall through to exitMBB.
6952   BB->addSuccessor(loopMBB);
6953   BB->addSuccessor(exitMBB);
6954
6955   // Add epilogue to handle BytesLeft.
6956   BB = exitMBB;
6957   MachineInstr *StartOfExit = exitMBB->begin();
6958
6959   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
6960   //   [destOut] = STRB_POST(scratch, destLoop, 1)
6961   unsigned srcIn = srcLoop;
6962   unsigned destIn = destLoop;
6963   for (unsigned i = 0; i < BytesLeft; i++) {
6964     unsigned srcOut = MRI.createVirtualRegister(TRC);
6965     unsigned destOut = MRI.createVirtualRegister(TRC);
6966     unsigned scratch = MRI.createVirtualRegister(TRC);
6967     emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
6968                IsThumb1, IsThumb2);
6969     emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
6970                IsThumb1, IsThumb2);
6971     srcIn = srcOut;
6972     destIn = destOut;
6973   }
6974
6975   MI->eraseFromParent();   // The instruction is gone now.
6976   return BB;
6977 }
6978
6979 MachineBasicBlock *
6980 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
6981                                                MachineBasicBlock *BB) const {
6982   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6983   DebugLoc dl = MI->getDebugLoc();
6984   bool isThumb2 = Subtarget->isThumb2();
6985   switch (MI->getOpcode()) {
6986   default: {
6987     MI->dump();
6988     llvm_unreachable("Unexpected instr type to insert");
6989   }
6990   // The Thumb2 pre-indexed stores have the same MI operands, they just
6991   // define them differently in the .td files from the isel patterns, so
6992   // they need pseudos.
6993   case ARM::t2STR_preidx:
6994     MI->setDesc(TII->get(ARM::t2STR_PRE));
6995     return BB;
6996   case ARM::t2STRB_preidx:
6997     MI->setDesc(TII->get(ARM::t2STRB_PRE));
6998     return BB;
6999   case ARM::t2STRH_preidx:
7000     MI->setDesc(TII->get(ARM::t2STRH_PRE));
7001     return BB;
7002
7003   case ARM::STRi_preidx:
7004   case ARM::STRBi_preidx: {
7005     unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7006       ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7007     // Decode the offset.
7008     unsigned Offset = MI->getOperand(4).getImm();
7009     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7010     Offset = ARM_AM::getAM2Offset(Offset);
7011     if (isSub)
7012       Offset = -Offset;
7013
7014     MachineMemOperand *MMO = *MI->memoperands_begin();
7015     BuildMI(*BB, MI, dl, TII->get(NewOpc))
7016       .addOperand(MI->getOperand(0))  // Rn_wb
7017       .addOperand(MI->getOperand(1))  // Rt
7018       .addOperand(MI->getOperand(2))  // Rn
7019       .addImm(Offset)                 // offset (skip GPR==zero_reg)
7020       .addOperand(MI->getOperand(5))  // pred
7021       .addOperand(MI->getOperand(6))
7022       .addMemOperand(MMO);
7023     MI->eraseFromParent();
7024     return BB;
7025   }
7026   case ARM::STRr_preidx:
7027   case ARM::STRBr_preidx:
7028   case ARM::STRH_preidx: {
7029     unsigned NewOpc;
7030     switch (MI->getOpcode()) {
7031     default: llvm_unreachable("unexpected opcode!");
7032     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7033     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7034     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7035     }
7036     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7037     for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7038       MIB.addOperand(MI->getOperand(i));
7039     MI->eraseFromParent();
7040     return BB;
7041   }
7042
7043   case ARM::tMOVCCr_pseudo: {
7044     // To "insert" a SELECT_CC instruction, we actually have to insert the
7045     // diamond control-flow pattern.  The incoming instruction knows the
7046     // destination vreg to set, the condition code register to branch on, the
7047     // true/false values to select between, and a branch opcode to use.
7048     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7049     MachineFunction::iterator It = BB;
7050     ++It;
7051
7052     //  thisMBB:
7053     //  ...
7054     //   TrueVal = ...
7055     //   cmpTY ccX, r1, r2
7056     //   bCC copy1MBB
7057     //   fallthrough --> copy0MBB
7058     MachineBasicBlock *thisMBB  = BB;
7059     MachineFunction *F = BB->getParent();
7060     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7061     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
7062     F->insert(It, copy0MBB);
7063     F->insert(It, sinkMBB);
7064
7065     // Transfer the remainder of BB and its successor edges to sinkMBB.
7066     sinkMBB->splice(sinkMBB->begin(), BB,
7067                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
7068     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7069
7070     BB->addSuccessor(copy0MBB);
7071     BB->addSuccessor(sinkMBB);
7072
7073     BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7074       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7075
7076     //  copy0MBB:
7077     //   %FalseValue = ...
7078     //   # fallthrough to sinkMBB
7079     BB = copy0MBB;
7080
7081     // Update machine-CFG edges
7082     BB->addSuccessor(sinkMBB);
7083
7084     //  sinkMBB:
7085     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7086     //  ...
7087     BB = sinkMBB;
7088     BuildMI(*BB, BB->begin(), dl,
7089             TII->get(ARM::PHI), MI->getOperand(0).getReg())
7090       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7091       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7092
7093     MI->eraseFromParent();   // The pseudo instruction is gone now.
7094     return BB;
7095   }
7096
7097   case ARM::BCCi64:
7098   case ARM::BCCZi64: {
7099     // If there is an unconditional branch to the other successor, remove it.
7100     BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
7101
7102     // Compare both parts that make up the double comparison separately for
7103     // equality.
7104     bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7105
7106     unsigned LHS1 = MI->getOperand(1).getReg();
7107     unsigned LHS2 = MI->getOperand(2).getReg();
7108     if (RHSisZero) {
7109       AddDefaultPred(BuildMI(BB, dl,
7110                              TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7111                      .addReg(LHS1).addImm(0));
7112       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7113         .addReg(LHS2).addImm(0)
7114         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7115     } else {
7116       unsigned RHS1 = MI->getOperand(3).getReg();
7117       unsigned RHS2 = MI->getOperand(4).getReg();
7118       AddDefaultPred(BuildMI(BB, dl,
7119                              TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7120                      .addReg(LHS1).addReg(RHS1));
7121       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7122         .addReg(LHS2).addReg(RHS2)
7123         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7124     }
7125
7126     MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7127     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7128     if (MI->getOperand(0).getImm() == ARMCC::NE)
7129       std::swap(destMBB, exitMBB);
7130
7131     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7132       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7133     if (isThumb2)
7134       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7135     else
7136       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7137
7138     MI->eraseFromParent();   // The pseudo instruction is gone now.
7139     return BB;
7140   }
7141
7142   case ARM::Int_eh_sjlj_setjmp:
7143   case ARM::Int_eh_sjlj_setjmp_nofp:
7144   case ARM::tInt_eh_sjlj_setjmp:
7145   case ARM::t2Int_eh_sjlj_setjmp:
7146   case ARM::t2Int_eh_sjlj_setjmp_nofp:
7147     EmitSjLjDispatchBlock(MI, BB);
7148     return BB;
7149
7150   case ARM::ABS:
7151   case ARM::t2ABS: {
7152     // To insert an ABS instruction, we have to insert the
7153     // diamond control-flow pattern.  The incoming instruction knows the
7154     // source vreg to test against 0, the destination vreg to set,
7155     // the condition code register to branch on, the
7156     // true/false values to select between, and a branch opcode to use.
7157     // It transforms
7158     //     V1 = ABS V0
7159     // into
7160     //     V2 = MOVS V0
7161     //     BCC                      (branch to SinkBB if V0 >= 0)
7162     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
7163     //     SinkBB: V1 = PHI(V2, V3)
7164     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7165     MachineFunction::iterator BBI = BB;
7166     ++BBI;
7167     MachineFunction *Fn = BB->getParent();
7168     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7169     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
7170     Fn->insert(BBI, RSBBB);
7171     Fn->insert(BBI, SinkBB);
7172
7173     unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7174     unsigned int ABSDstReg = MI->getOperand(0).getReg();
7175     bool isThumb2 = Subtarget->isThumb2();
7176     MachineRegisterInfo &MRI = Fn->getRegInfo();
7177     // In Thumb mode S must not be specified if source register is the SP or
7178     // PC and if destination register is the SP, so restrict register class
7179     unsigned NewRsbDstReg = MRI.createVirtualRegister(isThumb2 ?
7180       (const TargetRegisterClass*)&ARM::rGPRRegClass :
7181       (const TargetRegisterClass*)&ARM::GPRRegClass);
7182
7183     // Transfer the remainder of BB and its successor edges to sinkMBB.
7184     SinkBB->splice(SinkBB->begin(), BB,
7185                    std::next(MachineBasicBlock::iterator(MI)), BB->end());
7186     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7187
7188     BB->addSuccessor(RSBBB);
7189     BB->addSuccessor(SinkBB);
7190
7191     // fall through to SinkMBB
7192     RSBBB->addSuccessor(SinkBB);
7193
7194     // insert a cmp at the end of BB
7195     AddDefaultPred(BuildMI(BB, dl,
7196                            TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7197                    .addReg(ABSSrcReg).addImm(0));
7198
7199     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7200     BuildMI(BB, dl,
7201       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7202       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7203
7204     // insert rsbri in RSBBB
7205     // Note: BCC and rsbri will be converted into predicated rsbmi
7206     // by if-conversion pass
7207     BuildMI(*RSBBB, RSBBB->begin(), dl,
7208       TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7209       .addReg(ABSSrcReg, RegState::Kill)
7210       .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7211
7212     // insert PHI in SinkBB,
7213     // reuse ABSDstReg to not change uses of ABS instruction
7214     BuildMI(*SinkBB, SinkBB->begin(), dl,
7215       TII->get(ARM::PHI), ABSDstReg)
7216       .addReg(NewRsbDstReg).addMBB(RSBBB)
7217       .addReg(ABSSrcReg).addMBB(BB);
7218
7219     // remove ABS instruction
7220     MI->eraseFromParent();
7221
7222     // return last added BB
7223     return SinkBB;
7224   }
7225   case ARM::COPY_STRUCT_BYVAL_I32:
7226     ++NumLoopByVals;
7227     return EmitStructByval(MI, BB);
7228   }
7229 }
7230
7231 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7232                                                       SDNode *Node) const {
7233   if (!MI->hasPostISelHook()) {
7234     assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
7235            "Pseudo flag-setting opcodes must be marked with 'hasPostISelHook'");
7236     return;
7237   }
7238
7239   const MCInstrDesc *MCID = &MI->getDesc();
7240   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7241   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7242   // operand is still set to noreg. If needed, set the optional operand's
7243   // register to CPSR, and remove the redundant implicit def.
7244   //
7245   // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7246
7247   // Rename pseudo opcodes.
7248   unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7249   if (NewOpc) {
7250     const ARMBaseInstrInfo *TII =
7251       static_cast<const ARMBaseInstrInfo*>(getTargetMachine().getInstrInfo());
7252     MCID = &TII->get(NewOpc);
7253
7254     assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7255            "converted opcode should be the same except for cc_out");
7256
7257     MI->setDesc(*MCID);
7258
7259     // Add the optional cc_out operand
7260     MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7261   }
7262   unsigned ccOutIdx = MCID->getNumOperands() - 1;
7263
7264   // Any ARM instruction that sets the 's' bit should specify an optional
7265   // "cc_out" operand in the last operand position.
7266   if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7267     assert(!NewOpc && "Optional cc_out operand required");
7268     return;
7269   }
7270   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7271   // since we already have an optional CPSR def.
7272   bool definesCPSR = false;
7273   bool deadCPSR = false;
7274   for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7275        i != e; ++i) {
7276     const MachineOperand &MO = MI->getOperand(i);
7277     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7278       definesCPSR = true;
7279       if (MO.isDead())
7280         deadCPSR = true;
7281       MI->RemoveOperand(i);
7282       break;
7283     }
7284   }
7285   if (!definesCPSR) {
7286     assert(!NewOpc && "Optional cc_out operand required");
7287     return;
7288   }
7289   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
7290   if (deadCPSR) {
7291     assert(!MI->getOperand(ccOutIdx).getReg() &&
7292            "expect uninitialized optional cc_out operand");
7293     return;
7294   }
7295
7296   // If this instruction was defined with an optional CPSR def and its dag node
7297   // had a live implicit CPSR def, then activate the optional CPSR def.
7298   MachineOperand &MO = MI->getOperand(ccOutIdx);
7299   MO.setReg(ARM::CPSR);
7300   MO.setIsDef(true);
7301 }
7302
7303 //===----------------------------------------------------------------------===//
7304 //                           ARM Optimization Hooks
7305 //===----------------------------------------------------------------------===//
7306
7307 // Helper function that checks if N is a null or all ones constant.
7308 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
7309   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
7310   if (!C)
7311     return false;
7312   return AllOnes ? C->isAllOnesValue() : C->isNullValue();
7313 }
7314
7315 // Return true if N is conditionally 0 or all ones.
7316 // Detects these expressions where cc is an i1 value:
7317 //
7318 //   (select cc 0, y)   [AllOnes=0]
7319 //   (select cc y, 0)   [AllOnes=0]
7320 //   (zext cc)          [AllOnes=0]
7321 //   (sext cc)          [AllOnes=0/1]
7322 //   (select cc -1, y)  [AllOnes=1]
7323 //   (select cc y, -1)  [AllOnes=1]
7324 //
7325 // Invert is set when N is the null/all ones constant when CC is false.
7326 // OtherOp is set to the alternative value of N.
7327 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
7328                                        SDValue &CC, bool &Invert,
7329                                        SDValue &OtherOp,
7330                                        SelectionDAG &DAG) {
7331   switch (N->getOpcode()) {
7332   default: return false;
7333   case ISD::SELECT: {
7334     CC = N->getOperand(0);
7335     SDValue N1 = N->getOperand(1);
7336     SDValue N2 = N->getOperand(2);
7337     if (isZeroOrAllOnes(N1, AllOnes)) {
7338       Invert = false;
7339       OtherOp = N2;
7340       return true;
7341     }
7342     if (isZeroOrAllOnes(N2, AllOnes)) {
7343       Invert = true;
7344       OtherOp = N1;
7345       return true;
7346     }
7347     return false;
7348   }
7349   case ISD::ZERO_EXTEND:
7350     // (zext cc) can never be the all ones value.
7351     if (AllOnes)
7352       return false;
7353     // Fall through.
7354   case ISD::SIGN_EXTEND: {
7355     EVT VT = N->getValueType(0);
7356     CC = N->getOperand(0);
7357     if (CC.getValueType() != MVT::i1)
7358       return false;
7359     Invert = !AllOnes;
7360     if (AllOnes)
7361       // When looking for an AllOnes constant, N is an sext, and the 'other'
7362       // value is 0.
7363       OtherOp = DAG.getConstant(0, VT);
7364     else if (N->getOpcode() == ISD::ZERO_EXTEND)
7365       // When looking for a 0 constant, N can be zext or sext.
7366       OtherOp = DAG.getConstant(1, VT);
7367     else
7368       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
7369     return true;
7370   }
7371   }
7372 }
7373
7374 // Combine a constant select operand into its use:
7375 //
7376 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
7377 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
7378 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
7379 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
7380 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
7381 //
7382 // The transform is rejected if the select doesn't have a constant operand that
7383 // is null, or all ones when AllOnes is set.
7384 //
7385 // Also recognize sext/zext from i1:
7386 //
7387 //   (add (zext cc), x) -> (select cc (add x, 1), x)
7388 //   (add (sext cc), x) -> (select cc (add x, -1), x)
7389 //
7390 // These transformations eventually create predicated instructions.
7391 //
7392 // @param N       The node to transform.
7393 // @param Slct    The N operand that is a select.
7394 // @param OtherOp The other N operand (x above).
7395 // @param DCI     Context.
7396 // @param AllOnes Require the select constant to be all ones instead of null.
7397 // @returns The new node, or SDValue() on failure.
7398 static
7399 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7400                             TargetLowering::DAGCombinerInfo &DCI,
7401                             bool AllOnes = false) {
7402   SelectionDAG &DAG = DCI.DAG;
7403   EVT VT = N->getValueType(0);
7404   SDValue NonConstantVal;
7405   SDValue CCOp;
7406   bool SwapSelectOps;
7407   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
7408                                   NonConstantVal, DAG))
7409     return SDValue();
7410
7411   // Slct is now know to be the desired identity constant when CC is true.
7412   SDValue TrueVal = OtherOp;
7413   SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
7414                                  OtherOp, NonConstantVal);
7415   // Unless SwapSelectOps says CC should be false.
7416   if (SwapSelectOps)
7417     std::swap(TrueVal, FalseVal);
7418
7419   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
7420                      CCOp, TrueVal, FalseVal);
7421 }
7422
7423 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7424 static
7425 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
7426                                        TargetLowering::DAGCombinerInfo &DCI) {
7427   SDValue N0 = N->getOperand(0);
7428   SDValue N1 = N->getOperand(1);
7429   if (N0.getNode()->hasOneUse()) {
7430     SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
7431     if (Result.getNode())
7432       return Result;
7433   }
7434   if (N1.getNode()->hasOneUse()) {
7435     SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
7436     if (Result.getNode())
7437       return Result;
7438   }
7439   return SDValue();
7440 }
7441
7442 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
7443 // (only after legalization).
7444 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
7445                                  TargetLowering::DAGCombinerInfo &DCI,
7446                                  const ARMSubtarget *Subtarget) {
7447
7448   // Only perform optimization if after legalize, and if NEON is available. We
7449   // also expected both operands to be BUILD_VECTORs.
7450   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
7451       || N0.getOpcode() != ISD::BUILD_VECTOR
7452       || N1.getOpcode() != ISD::BUILD_VECTOR)
7453     return SDValue();
7454
7455   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
7456   EVT VT = N->getValueType(0);
7457   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
7458     return SDValue();
7459
7460   // Check that the vector operands are of the right form.
7461   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
7462   // operands, where N is the size of the formed vector.
7463   // Each EXTRACT_VECTOR should have the same input vector and odd or even
7464   // index such that we have a pair wise add pattern.
7465
7466   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
7467   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7468     return SDValue();
7469   SDValue Vec = N0->getOperand(0)->getOperand(0);
7470   SDNode *V = Vec.getNode();
7471   unsigned nextIndex = 0;
7472
7473   // For each operands to the ADD which are BUILD_VECTORs,
7474   // check to see if each of their operands are an EXTRACT_VECTOR with
7475   // the same vector and appropriate index.
7476   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
7477     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
7478         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7479
7480       SDValue ExtVec0 = N0->getOperand(i);
7481       SDValue ExtVec1 = N1->getOperand(i);
7482
7483       // First operand is the vector, verify its the same.
7484       if (V != ExtVec0->getOperand(0).getNode() ||
7485           V != ExtVec1->getOperand(0).getNode())
7486         return SDValue();
7487
7488       // Second is the constant, verify its correct.
7489       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
7490       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
7491
7492       // For the constant, we want to see all the even or all the odd.
7493       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
7494           || C1->getZExtValue() != nextIndex+1)
7495         return SDValue();
7496
7497       // Increment index.
7498       nextIndex+=2;
7499     } else
7500       return SDValue();
7501   }
7502
7503   // Create VPADDL node.
7504   SelectionDAG &DAG = DCI.DAG;
7505   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7506
7507   // Build operand list.
7508   SmallVector<SDValue, 8> Ops;
7509   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
7510                                 TLI.getPointerTy()));
7511
7512   // Input is the vector.
7513   Ops.push_back(Vec);
7514
7515   // Get widened type and narrowed type.
7516   MVT widenType;
7517   unsigned numElem = VT.getVectorNumElements();
7518   
7519   EVT inputLaneType = Vec.getValueType().getVectorElementType();
7520   switch (inputLaneType.getSimpleVT().SimpleTy) {
7521     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
7522     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
7523     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
7524     default:
7525       llvm_unreachable("Invalid vector element type for padd optimization.");
7526   }
7527
7528   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
7529                             widenType, &Ops[0], Ops.size());
7530   unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
7531   return DAG.getNode(ExtOp, SDLoc(N), VT, tmp);
7532 }
7533
7534 static SDValue findMUL_LOHI(SDValue V) {
7535   if (V->getOpcode() == ISD::UMUL_LOHI ||
7536       V->getOpcode() == ISD::SMUL_LOHI)
7537     return V;
7538   return SDValue();
7539 }
7540
7541 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
7542                                      TargetLowering::DAGCombinerInfo &DCI,
7543                                      const ARMSubtarget *Subtarget) {
7544
7545   if (Subtarget->isThumb1Only()) return SDValue();
7546
7547   // Only perform the checks after legalize when the pattern is available.
7548   if (DCI.isBeforeLegalize()) return SDValue();
7549
7550   // Look for multiply add opportunities.
7551   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
7552   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
7553   // a glue link from the first add to the second add.
7554   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
7555   // a S/UMLAL instruction.
7556   //          loAdd   UMUL_LOHI
7557   //            \    / :lo    \ :hi
7558   //             \  /          \          [no multiline comment]
7559   //              ADDC         |  hiAdd
7560   //                 \ :glue  /  /
7561   //                  \      /  /
7562   //                    ADDE
7563   //
7564   assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
7565   SDValue AddcOp0 = AddcNode->getOperand(0);
7566   SDValue AddcOp1 = AddcNode->getOperand(1);
7567
7568   // Check if the two operands are from the same mul_lohi node.
7569   if (AddcOp0.getNode() == AddcOp1.getNode())
7570     return SDValue();
7571
7572   assert(AddcNode->getNumValues() == 2 &&
7573          AddcNode->getValueType(0) == MVT::i32 &&
7574          "Expect ADDC with two result values. First: i32");
7575
7576   // Check that we have a glued ADDC node.
7577   if (AddcNode->getValueType(1) != MVT::Glue)
7578     return SDValue();
7579
7580   // Check that the ADDC adds the low result of the S/UMUL_LOHI.
7581   if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
7582       AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
7583       AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
7584       AddcOp1->getOpcode() != ISD::SMUL_LOHI)
7585     return SDValue();
7586
7587   // Look for the glued ADDE.
7588   SDNode* AddeNode = AddcNode->getGluedUser();
7589   if (AddeNode == NULL)
7590     return SDValue();
7591
7592   // Make sure it is really an ADDE.
7593   if (AddeNode->getOpcode() != ISD::ADDE)
7594     return SDValue();
7595
7596   assert(AddeNode->getNumOperands() == 3 &&
7597          AddeNode->getOperand(2).getValueType() == MVT::Glue &&
7598          "ADDE node has the wrong inputs");
7599
7600   // Check for the triangle shape.
7601   SDValue AddeOp0 = AddeNode->getOperand(0);
7602   SDValue AddeOp1 = AddeNode->getOperand(1);
7603
7604   // Make sure that the ADDE operands are not coming from the same node.
7605   if (AddeOp0.getNode() == AddeOp1.getNode())
7606     return SDValue();
7607
7608   // Find the MUL_LOHI node walking up ADDE's operands.
7609   bool IsLeftOperandMUL = false;
7610   SDValue MULOp = findMUL_LOHI(AddeOp0);
7611   if (MULOp == SDValue())
7612    MULOp = findMUL_LOHI(AddeOp1);
7613   else
7614     IsLeftOperandMUL = true;
7615   if (MULOp == SDValue())
7616      return SDValue();
7617
7618   // Figure out the right opcode.
7619   unsigned Opc = MULOp->getOpcode();
7620   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
7621
7622   // Figure out the high and low input values to the MLAL node.
7623   SDValue* HiMul = &MULOp;
7624   SDValue* HiAdd = NULL;
7625   SDValue* LoMul = NULL;
7626   SDValue* LowAdd = NULL;
7627
7628   if (IsLeftOperandMUL)
7629     HiAdd = &AddeOp1;
7630   else
7631     HiAdd = &AddeOp0;
7632
7633
7634   if (AddcOp0->getOpcode() == Opc) {
7635     LoMul = &AddcOp0;
7636     LowAdd = &AddcOp1;
7637   }
7638   if (AddcOp1->getOpcode() == Opc) {
7639     LoMul = &AddcOp1;
7640     LowAdd = &AddcOp0;
7641   }
7642
7643   if (LoMul == NULL)
7644     return SDValue();
7645
7646   if (LoMul->getNode() != HiMul->getNode())
7647     return SDValue();
7648
7649   // Create the merged node.
7650   SelectionDAG &DAG = DCI.DAG;
7651
7652   // Build operand list.
7653   SmallVector<SDValue, 8> Ops;
7654   Ops.push_back(LoMul->getOperand(0));
7655   Ops.push_back(LoMul->getOperand(1));
7656   Ops.push_back(*LowAdd);
7657   Ops.push_back(*HiAdd);
7658
7659   SDValue MLALNode =  DAG.getNode(FinalOpc, SDLoc(AddcNode),
7660                                  DAG.getVTList(MVT::i32, MVT::i32),
7661                                  &Ops[0], Ops.size());
7662
7663   // Replace the ADDs' nodes uses by the MLA node's values.
7664   SDValue HiMLALResult(MLALNode.getNode(), 1);
7665   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
7666
7667   SDValue LoMLALResult(MLALNode.getNode(), 0);
7668   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
7669
7670   // Return original node to notify the driver to stop replacing.
7671   SDValue resNode(AddcNode, 0);
7672   return resNode;
7673 }
7674
7675 /// PerformADDCCombine - Target-specific dag combine transform from
7676 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
7677 static SDValue PerformADDCCombine(SDNode *N,
7678                                  TargetLowering::DAGCombinerInfo &DCI,
7679                                  const ARMSubtarget *Subtarget) {
7680
7681   return AddCombineTo64bitMLAL(N, DCI, Subtarget);
7682
7683 }
7684
7685 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
7686 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
7687 /// called with the default operands, and if that fails, with commuted
7688 /// operands.
7689 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
7690                                           TargetLowering::DAGCombinerInfo &DCI,
7691                                           const ARMSubtarget *Subtarget){
7692
7693   // Attempt to create vpaddl for this add.
7694   SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
7695   if (Result.getNode())
7696     return Result;
7697
7698   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
7699   if (N0.getNode()->hasOneUse()) {
7700     SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
7701     if (Result.getNode()) return Result;
7702   }
7703   return SDValue();
7704 }
7705
7706 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
7707 ///
7708 static SDValue PerformADDCombine(SDNode *N,
7709                                  TargetLowering::DAGCombinerInfo &DCI,
7710                                  const ARMSubtarget *Subtarget) {
7711   SDValue N0 = N->getOperand(0);
7712   SDValue N1 = N->getOperand(1);
7713
7714   // First try with the default operand order.
7715   SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
7716   if (Result.getNode())
7717     return Result;
7718
7719   // If that didn't work, try again with the operands commuted.
7720   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
7721 }
7722
7723 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
7724 ///
7725 static SDValue PerformSUBCombine(SDNode *N,
7726                                  TargetLowering::DAGCombinerInfo &DCI) {
7727   SDValue N0 = N->getOperand(0);
7728   SDValue N1 = N->getOperand(1);
7729
7730   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
7731   if (N1.getNode()->hasOneUse()) {
7732     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
7733     if (Result.getNode()) return Result;
7734   }
7735
7736   return SDValue();
7737 }
7738
7739 /// PerformVMULCombine
7740 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
7741 /// special multiplier accumulator forwarding.
7742 ///   vmul d3, d0, d2
7743 ///   vmla d3, d1, d2
7744 /// is faster than
7745 ///   vadd d3, d0, d1
7746 ///   vmul d3, d3, d2
7747 //  However, for (A + B) * (A + B),
7748 //    vadd d2, d0, d1
7749 //    vmul d3, d0, d2
7750 //    vmla d3, d1, d2
7751 //  is slower than
7752 //    vadd d2, d0, d1
7753 //    vmul d3, d2, d2
7754 static SDValue PerformVMULCombine(SDNode *N,
7755                                   TargetLowering::DAGCombinerInfo &DCI,
7756                                   const ARMSubtarget *Subtarget) {
7757   if (!Subtarget->hasVMLxForwarding())
7758     return SDValue();
7759
7760   SelectionDAG &DAG = DCI.DAG;
7761   SDValue N0 = N->getOperand(0);
7762   SDValue N1 = N->getOperand(1);
7763   unsigned Opcode = N0.getOpcode();
7764   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
7765       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
7766     Opcode = N1.getOpcode();
7767     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
7768         Opcode != ISD::FADD && Opcode != ISD::FSUB)
7769       return SDValue();
7770     std::swap(N0, N1);
7771   }
7772
7773   if (N0 == N1)
7774     return SDValue();
7775
7776   EVT VT = N->getValueType(0);
7777   SDLoc DL(N);
7778   SDValue N00 = N0->getOperand(0);
7779   SDValue N01 = N0->getOperand(1);
7780   return DAG.getNode(Opcode, DL, VT,
7781                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
7782                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
7783 }
7784
7785 static SDValue PerformMULCombine(SDNode *N,
7786                                  TargetLowering::DAGCombinerInfo &DCI,
7787                                  const ARMSubtarget *Subtarget) {
7788   SelectionDAG &DAG = DCI.DAG;
7789
7790   if (Subtarget->isThumb1Only())
7791     return SDValue();
7792
7793   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
7794     return SDValue();
7795
7796   EVT VT = N->getValueType(0);
7797   if (VT.is64BitVector() || VT.is128BitVector())
7798     return PerformVMULCombine(N, DCI, Subtarget);
7799   if (VT != MVT::i32)
7800     return SDValue();
7801
7802   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
7803   if (!C)
7804     return SDValue();
7805
7806   int64_t MulAmt = C->getSExtValue();
7807   unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
7808
7809   ShiftAmt = ShiftAmt & (32 - 1);
7810   SDValue V = N->getOperand(0);
7811   SDLoc DL(N);
7812
7813   SDValue Res;
7814   MulAmt >>= ShiftAmt;
7815
7816   if (MulAmt >= 0) {
7817     if (isPowerOf2_32(MulAmt - 1)) {
7818       // (mul x, 2^N + 1) => (add (shl x, N), x)
7819       Res = DAG.getNode(ISD::ADD, DL, VT,
7820                         V,
7821                         DAG.getNode(ISD::SHL, DL, VT,
7822                                     V,
7823                                     DAG.getConstant(Log2_32(MulAmt - 1),
7824                                                     MVT::i32)));
7825     } else if (isPowerOf2_32(MulAmt + 1)) {
7826       // (mul x, 2^N - 1) => (sub (shl x, N), x)
7827       Res = DAG.getNode(ISD::SUB, DL, VT,
7828                         DAG.getNode(ISD::SHL, DL, VT,
7829                                     V,
7830                                     DAG.getConstant(Log2_32(MulAmt + 1),
7831                                                     MVT::i32)),
7832                         V);
7833     } else
7834       return SDValue();
7835   } else {
7836     uint64_t MulAmtAbs = -MulAmt;
7837     if (isPowerOf2_32(MulAmtAbs + 1)) {
7838       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
7839       Res = DAG.getNode(ISD::SUB, DL, VT,
7840                         V,
7841                         DAG.getNode(ISD::SHL, DL, VT,
7842                                     V,
7843                                     DAG.getConstant(Log2_32(MulAmtAbs + 1),
7844                                                     MVT::i32)));
7845     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
7846       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
7847       Res = DAG.getNode(ISD::ADD, DL, VT,
7848                         V,
7849                         DAG.getNode(ISD::SHL, DL, VT,
7850                                     V,
7851                                     DAG.getConstant(Log2_32(MulAmtAbs-1),
7852                                                     MVT::i32)));
7853       Res = DAG.getNode(ISD::SUB, DL, VT,
7854                         DAG.getConstant(0, MVT::i32),Res);
7855
7856     } else
7857       return SDValue();
7858   }
7859
7860   if (ShiftAmt != 0)
7861     Res = DAG.getNode(ISD::SHL, DL, VT,
7862                       Res, DAG.getConstant(ShiftAmt, MVT::i32));
7863
7864   // Do not add new nodes to DAG combiner worklist.
7865   DCI.CombineTo(N, Res, false);
7866   return SDValue();
7867 }
7868
7869 static SDValue PerformANDCombine(SDNode *N,
7870                                  TargetLowering::DAGCombinerInfo &DCI,
7871                                  const ARMSubtarget *Subtarget) {
7872
7873   // Attempt to use immediate-form VBIC
7874   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
7875   SDLoc dl(N);
7876   EVT VT = N->getValueType(0);
7877   SelectionDAG &DAG = DCI.DAG;
7878
7879   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
7880     return SDValue();
7881
7882   APInt SplatBits, SplatUndef;
7883   unsigned SplatBitSize;
7884   bool HasAnyUndefs;
7885   if (BVN &&
7886       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
7887     if (SplatBitSize <= 64) {
7888       EVT VbicVT;
7889       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
7890                                       SplatUndef.getZExtValue(), SplatBitSize,
7891                                       DAG, VbicVT, VT.is128BitVector(),
7892                                       OtherModImm);
7893       if (Val.getNode()) {
7894         SDValue Input =
7895           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
7896         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
7897         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
7898       }
7899     }
7900   }
7901
7902   if (!Subtarget->isThumb1Only()) {
7903     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
7904     SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
7905     if (Result.getNode())
7906       return Result;
7907   }
7908
7909   return SDValue();
7910 }
7911
7912 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
7913 static SDValue PerformORCombine(SDNode *N,
7914                                 TargetLowering::DAGCombinerInfo &DCI,
7915                                 const ARMSubtarget *Subtarget) {
7916   // Attempt to use immediate-form VORR
7917   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
7918   SDLoc dl(N);
7919   EVT VT = N->getValueType(0);
7920   SelectionDAG &DAG = DCI.DAG;
7921
7922   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
7923     return SDValue();
7924
7925   APInt SplatBits, SplatUndef;
7926   unsigned SplatBitSize;
7927   bool HasAnyUndefs;
7928   if (BVN && Subtarget->hasNEON() &&
7929       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
7930     if (SplatBitSize <= 64) {
7931       EVT VorrVT;
7932       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
7933                                       SplatUndef.getZExtValue(), SplatBitSize,
7934                                       DAG, VorrVT, VT.is128BitVector(),
7935                                       OtherModImm);
7936       if (Val.getNode()) {
7937         SDValue Input =
7938           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
7939         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
7940         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
7941       }
7942     }
7943   }
7944
7945   if (!Subtarget->isThumb1Only()) {
7946     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
7947     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
7948     if (Result.getNode())
7949       return Result;
7950   }
7951
7952   // The code below optimizes (or (and X, Y), Z).
7953   // The AND operand needs to have a single user to make these optimizations
7954   // profitable.
7955   SDValue N0 = N->getOperand(0);
7956   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
7957     return SDValue();
7958   SDValue N1 = N->getOperand(1);
7959
7960   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
7961   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
7962       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
7963     APInt SplatUndef;
7964     unsigned SplatBitSize;
7965     bool HasAnyUndefs;
7966
7967     APInt SplatBits0, SplatBits1;
7968     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
7969     BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
7970     // Ensure that the second operand of both ands are constants
7971     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
7972                                       HasAnyUndefs) && !HasAnyUndefs) {
7973         if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
7974                                           HasAnyUndefs) && !HasAnyUndefs) {
7975             // Ensure that the bit width of the constants are the same and that
7976             // the splat arguments are logical inverses as per the pattern we
7977             // are trying to simplify.
7978             if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
7979                 SplatBits0 == ~SplatBits1) {
7980                 // Canonicalize the vector type to make instruction selection
7981                 // simpler.
7982                 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
7983                 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
7984                                              N0->getOperand(1),
7985                                              N0->getOperand(0),
7986                                              N1->getOperand(0));
7987                 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
7988             }
7989         }
7990     }
7991   }
7992
7993   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
7994   // reasonable.
7995
7996   // BFI is only available on V6T2+
7997   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
7998     return SDValue();
7999
8000   SDLoc DL(N);
8001   // 1) or (and A, mask), val => ARMbfi A, val, mask
8002   //      iff (val & mask) == val
8003   //
8004   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8005   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8006   //          && mask == ~mask2
8007   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8008   //          && ~mask == mask2
8009   //  (i.e., copy a bitfield value into another bitfield of the same width)
8010
8011   if (VT != MVT::i32)
8012     return SDValue();
8013
8014   SDValue N00 = N0.getOperand(0);
8015
8016   // The value and the mask need to be constants so we can verify this is
8017   // actually a bitfield set. If the mask is 0xffff, we can do better
8018   // via a movt instruction, so don't use BFI in that case.
8019   SDValue MaskOp = N0.getOperand(1);
8020   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8021   if (!MaskC)
8022     return SDValue();
8023   unsigned Mask = MaskC->getZExtValue();
8024   if (Mask == 0xffff)
8025     return SDValue();
8026   SDValue Res;
8027   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8028   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8029   if (N1C) {
8030     unsigned Val = N1C->getZExtValue();
8031     if ((Val & ~Mask) != Val)
8032       return SDValue();
8033
8034     if (ARM::isBitFieldInvertedMask(Mask)) {
8035       Val >>= countTrailingZeros(~Mask);
8036
8037       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8038                         DAG.getConstant(Val, MVT::i32),
8039                         DAG.getConstant(Mask, MVT::i32));
8040
8041       // Do not add new nodes to DAG combiner worklist.
8042       DCI.CombineTo(N, Res, false);
8043       return SDValue();
8044     }
8045   } else if (N1.getOpcode() == ISD::AND) {
8046     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8047     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8048     if (!N11C)
8049       return SDValue();
8050     unsigned Mask2 = N11C->getZExtValue();
8051
8052     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8053     // as is to match.
8054     if (ARM::isBitFieldInvertedMask(Mask) &&
8055         (Mask == ~Mask2)) {
8056       // The pack halfword instruction works better for masks that fit it,
8057       // so use that when it's available.
8058       if (Subtarget->hasT2ExtractPack() &&
8059           (Mask == 0xffff || Mask == 0xffff0000))
8060         return SDValue();
8061       // 2a
8062       unsigned amt = countTrailingZeros(Mask2);
8063       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8064                         DAG.getConstant(amt, MVT::i32));
8065       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8066                         DAG.getConstant(Mask, MVT::i32));
8067       // Do not add new nodes to DAG combiner worklist.
8068       DCI.CombineTo(N, Res, false);
8069       return SDValue();
8070     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8071                (~Mask == Mask2)) {
8072       // The pack halfword instruction works better for masks that fit it,
8073       // so use that when it's available.
8074       if (Subtarget->hasT2ExtractPack() &&
8075           (Mask2 == 0xffff || Mask2 == 0xffff0000))
8076         return SDValue();
8077       // 2b
8078       unsigned lsb = countTrailingZeros(Mask);
8079       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8080                         DAG.getConstant(lsb, MVT::i32));
8081       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8082                         DAG.getConstant(Mask2, MVT::i32));
8083       // Do not add new nodes to DAG combiner worklist.
8084       DCI.CombineTo(N, Res, false);
8085       return SDValue();
8086     }
8087   }
8088
8089   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8090       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8091       ARM::isBitFieldInvertedMask(~Mask)) {
8092     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8093     // where lsb(mask) == #shamt and masked bits of B are known zero.
8094     SDValue ShAmt = N00.getOperand(1);
8095     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8096     unsigned LSB = countTrailingZeros(Mask);
8097     if (ShAmtC != LSB)
8098       return SDValue();
8099
8100     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8101                       DAG.getConstant(~Mask, MVT::i32));
8102
8103     // Do not add new nodes to DAG combiner worklist.
8104     DCI.CombineTo(N, Res, false);
8105   }
8106
8107   return SDValue();
8108 }
8109
8110 static SDValue PerformXORCombine(SDNode *N,
8111                                  TargetLowering::DAGCombinerInfo &DCI,
8112                                  const ARMSubtarget *Subtarget) {
8113   EVT VT = N->getValueType(0);
8114   SelectionDAG &DAG = DCI.DAG;
8115
8116   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8117     return SDValue();
8118
8119   if (!Subtarget->isThumb1Only()) {
8120     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8121     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8122     if (Result.getNode())
8123       return Result;
8124   }
8125
8126   return SDValue();
8127 }
8128
8129 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8130 /// the bits being cleared by the AND are not demanded by the BFI.
8131 static SDValue PerformBFICombine(SDNode *N,
8132                                  TargetLowering::DAGCombinerInfo &DCI) {
8133   SDValue N1 = N->getOperand(1);
8134   if (N1.getOpcode() == ISD::AND) {
8135     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8136     if (!N11C)
8137       return SDValue();
8138     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8139     unsigned LSB = countTrailingZeros(~InvMask);
8140     unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
8141     unsigned Mask = (1 << Width)-1;
8142     unsigned Mask2 = N11C->getZExtValue();
8143     if ((Mask & (~Mask2)) == 0)
8144       return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
8145                              N->getOperand(0), N1.getOperand(0),
8146                              N->getOperand(2));
8147   }
8148   return SDValue();
8149 }
8150
8151 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8152 /// ARMISD::VMOVRRD.
8153 static SDValue PerformVMOVRRDCombine(SDNode *N,
8154                                      TargetLowering::DAGCombinerInfo &DCI) {
8155   // vmovrrd(vmovdrr x, y) -> x,y
8156   SDValue InDouble = N->getOperand(0);
8157   if (InDouble.getOpcode() == ARMISD::VMOVDRR)
8158     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8159
8160   // vmovrrd(load f64) -> (load i32), (load i32)
8161   SDNode *InNode = InDouble.getNode();
8162   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8163       InNode->getValueType(0) == MVT::f64 &&
8164       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8165       !cast<LoadSDNode>(InNode)->isVolatile()) {
8166     // TODO: Should this be done for non-FrameIndex operands?
8167     LoadSDNode *LD = cast<LoadSDNode>(InNode);
8168
8169     SelectionDAG &DAG = DCI.DAG;
8170     SDLoc DL(LD);
8171     SDValue BasePtr = LD->getBasePtr();
8172     SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8173                                  LD->getPointerInfo(), LD->isVolatile(),
8174                                  LD->isNonTemporal(), LD->isInvariant(),
8175                                  LD->getAlignment());
8176
8177     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8178                                     DAG.getConstant(4, MVT::i32));
8179     SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8180                                  LD->getPointerInfo(), LD->isVolatile(),
8181                                  LD->isNonTemporal(), LD->isInvariant(),
8182                                  std::min(4U, LD->getAlignment() / 2));
8183
8184     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8185     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8186     DCI.RemoveFromWorklist(LD);
8187     DAG.DeleteNode(LD);
8188     return Result;
8189   }
8190
8191   return SDValue();
8192 }
8193
8194 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8195 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
8196 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8197   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8198   SDValue Op0 = N->getOperand(0);
8199   SDValue Op1 = N->getOperand(1);
8200   if (Op0.getOpcode() == ISD::BITCAST)
8201     Op0 = Op0.getOperand(0);
8202   if (Op1.getOpcode() == ISD::BITCAST)
8203     Op1 = Op1.getOperand(0);
8204   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8205       Op0.getNode() == Op1.getNode() &&
8206       Op0.getResNo() == 0 && Op1.getResNo() == 1)
8207     return DAG.getNode(ISD::BITCAST, SDLoc(N),
8208                        N->getValueType(0), Op0.getOperand(0));
8209   return SDValue();
8210 }
8211
8212 /// PerformSTORECombine - Target-specific dag combine xforms for
8213 /// ISD::STORE.
8214 static SDValue PerformSTORECombine(SDNode *N,
8215                                    TargetLowering::DAGCombinerInfo &DCI) {
8216   StoreSDNode *St = cast<StoreSDNode>(N);
8217   if (St->isVolatile())
8218     return SDValue();
8219
8220   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
8221   // pack all of the elements in one place.  Next, store to memory in fewer
8222   // chunks.
8223   SDValue StVal = St->getValue();
8224   EVT VT = StVal.getValueType();
8225   if (St->isTruncatingStore() && VT.isVector()) {
8226     SelectionDAG &DAG = DCI.DAG;
8227     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8228     EVT StVT = St->getMemoryVT();
8229     unsigned NumElems = VT.getVectorNumElements();
8230     assert(StVT != VT && "Cannot truncate to the same type");
8231     unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
8232     unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
8233
8234     // From, To sizes and ElemCount must be pow of two
8235     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
8236
8237     // We are going to use the original vector elt for storing.
8238     // Accumulated smaller vector elements must be a multiple of the store size.
8239     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
8240
8241     unsigned SizeRatio  = FromEltSz / ToEltSz;
8242     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
8243
8244     // Create a type on which we perform the shuffle.
8245     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
8246                                      NumElems*SizeRatio);
8247     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
8248
8249     SDLoc DL(St);
8250     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
8251     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
8252     for (unsigned i = 0; i < NumElems; ++i) ShuffleVec[i] = i * SizeRatio;
8253
8254     // Can't shuffle using an illegal type.
8255     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
8256
8257     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
8258                                 DAG.getUNDEF(WideVec.getValueType()),
8259                                 ShuffleVec.data());
8260     // At this point all of the data is stored at the bottom of the
8261     // register. We now need to save it to mem.
8262
8263     // Find the largest store unit
8264     MVT StoreType = MVT::i8;
8265     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
8266          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
8267       MVT Tp = (MVT::SimpleValueType)tp;
8268       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
8269         StoreType = Tp;
8270     }
8271     // Didn't find a legal store type.
8272     if (!TLI.isTypeLegal(StoreType))
8273       return SDValue();
8274
8275     // Bitcast the original vector into a vector of store-size units
8276     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
8277             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
8278     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
8279     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
8280     SmallVector<SDValue, 8> Chains;
8281     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
8282                                         TLI.getPointerTy());
8283     SDValue BasePtr = St->getBasePtr();
8284
8285     // Perform one or more big stores into memory.
8286     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
8287     for (unsigned I = 0; I < E; I++) {
8288       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
8289                                    StoreType, ShuffWide,
8290                                    DAG.getIntPtrConstant(I));
8291       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
8292                                 St->getPointerInfo(), St->isVolatile(),
8293                                 St->isNonTemporal(), St->getAlignment());
8294       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
8295                             Increment);
8296       Chains.push_back(Ch);
8297     }
8298     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, &Chains[0],
8299                        Chains.size());
8300   }
8301
8302   if (!ISD::isNormalStore(St))
8303     return SDValue();
8304
8305   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
8306   // ARM stores of arguments in the same cache line.
8307   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
8308       StVal.getNode()->hasOneUse()) {
8309     SelectionDAG  &DAG = DCI.DAG;
8310     SDLoc DL(St);
8311     SDValue BasePtr = St->getBasePtr();
8312     SDValue NewST1 = DAG.getStore(St->getChain(), DL,
8313                                   StVal.getNode()->getOperand(0), BasePtr,
8314                                   St->getPointerInfo(), St->isVolatile(),
8315                                   St->isNonTemporal(), St->getAlignment());
8316
8317     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8318                                     DAG.getConstant(4, MVT::i32));
8319     return DAG.getStore(NewST1.getValue(0), DL, StVal.getNode()->getOperand(1),
8320                         OffsetPtr, St->getPointerInfo(), St->isVolatile(),
8321                         St->isNonTemporal(),
8322                         std::min(4U, St->getAlignment() / 2));
8323   }
8324
8325   if (StVal.getValueType() != MVT::i64 ||
8326       StVal.getNode()->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8327     return SDValue();
8328
8329   // Bitcast an i64 store extracted from a vector to f64.
8330   // Otherwise, the i64 value will be legalized to a pair of i32 values.
8331   SelectionDAG &DAG = DCI.DAG;
8332   SDLoc dl(StVal);
8333   SDValue IntVec = StVal.getOperand(0);
8334   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8335                                  IntVec.getValueType().getVectorNumElements());
8336   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
8337   SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8338                                Vec, StVal.getOperand(1));
8339   dl = SDLoc(N);
8340   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
8341   // Make the DAGCombiner fold the bitcasts.
8342   DCI.AddToWorklist(Vec.getNode());
8343   DCI.AddToWorklist(ExtElt.getNode());
8344   DCI.AddToWorklist(V.getNode());
8345   return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
8346                       St->getPointerInfo(), St->isVolatile(),
8347                       St->isNonTemporal(), St->getAlignment(),
8348                       St->getTBAAInfo());
8349 }
8350
8351 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8352 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
8353 /// i64 vector to have f64 elements, since the value can then be loaded
8354 /// directly into a VFP register.
8355 static bool hasNormalLoadOperand(SDNode *N) {
8356   unsigned NumElts = N->getValueType(0).getVectorNumElements();
8357   for (unsigned i = 0; i < NumElts; ++i) {
8358     SDNode *Elt = N->getOperand(i).getNode();
8359     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8360       return true;
8361   }
8362   return false;
8363 }
8364
8365 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
8366 /// ISD::BUILD_VECTOR.
8367 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
8368                                           TargetLowering::DAGCombinerInfo &DCI){
8369   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
8370   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
8371   // into a pair of GPRs, which is fine when the value is used as a scalar,
8372   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
8373   SelectionDAG &DAG = DCI.DAG;
8374   if (N->getNumOperands() == 2) {
8375     SDValue RV = PerformVMOVDRRCombine(N, DAG);
8376     if (RV.getNode())
8377       return RV;
8378   }
8379
8380   // Load i64 elements as f64 values so that type legalization does not split
8381   // them up into i32 values.
8382   EVT VT = N->getValueType(0);
8383   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
8384     return SDValue();
8385   SDLoc dl(N);
8386   SmallVector<SDValue, 8> Ops;
8387   unsigned NumElts = VT.getVectorNumElements();
8388   for (unsigned i = 0; i < NumElts; ++i) {
8389     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
8390     Ops.push_back(V);
8391     // Make the DAGCombiner fold the bitcast.
8392     DCI.AddToWorklist(V.getNode());
8393   }
8394   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
8395   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops.data(), NumElts);
8396   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8397 }
8398
8399 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
8400 static SDValue
8401 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8402   // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
8403   // At that time, we may have inserted bitcasts from integer to float.
8404   // If these bitcasts have survived DAGCombine, change the lowering of this
8405   // BUILD_VECTOR in something more vector friendly, i.e., that does not
8406   // force to use floating point types.
8407
8408   // Make sure we can change the type of the vector.
8409   // This is possible iff:
8410   // 1. The vector is only used in a bitcast to a integer type. I.e.,
8411   //    1.1. Vector is used only once.
8412   //    1.2. Use is a bit convert to an integer type.
8413   // 2. The size of its operands are 32-bits (64-bits are not legal).
8414   EVT VT = N->getValueType(0);
8415   EVT EltVT = VT.getVectorElementType();
8416
8417   // Check 1.1. and 2.
8418   if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
8419     return SDValue();
8420
8421   // By construction, the input type must be float.
8422   assert(EltVT == MVT::f32 && "Unexpected type!");
8423
8424   // Check 1.2.
8425   SDNode *Use = *N->use_begin();
8426   if (Use->getOpcode() != ISD::BITCAST ||
8427       Use->getValueType(0).isFloatingPoint())
8428     return SDValue();
8429
8430   // Check profitability.
8431   // Model is, if more than half of the relevant operands are bitcast from
8432   // i32, turn the build_vector into a sequence of insert_vector_elt.
8433   // Relevant operands are everything that is not statically
8434   // (i.e., at compile time) bitcasted.
8435   unsigned NumOfBitCastedElts = 0;
8436   unsigned NumElts = VT.getVectorNumElements();
8437   unsigned NumOfRelevantElts = NumElts;
8438   for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
8439     SDValue Elt = N->getOperand(Idx);
8440     if (Elt->getOpcode() == ISD::BITCAST) {
8441       // Assume only bit cast to i32 will go away.
8442       if (Elt->getOperand(0).getValueType() == MVT::i32)
8443         ++NumOfBitCastedElts;
8444     } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
8445       // Constants are statically casted, thus do not count them as
8446       // relevant operands.
8447       --NumOfRelevantElts;
8448   }
8449
8450   // Check if more than half of the elements require a non-free bitcast.
8451   if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
8452     return SDValue();
8453
8454   SelectionDAG &DAG = DCI.DAG;
8455   // Create the new vector type.
8456   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
8457   // Check if the type is legal.
8458   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8459   if (!TLI.isTypeLegal(VecVT))
8460     return SDValue();
8461
8462   // Combine:
8463   // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
8464   // => BITCAST INSERT_VECTOR_ELT
8465   //                      (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
8466   //                      (BITCAST EN), N.
8467   SDValue Vec = DAG.getUNDEF(VecVT);
8468   SDLoc dl(N);
8469   for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
8470     SDValue V = N->getOperand(Idx);
8471     if (V.getOpcode() == ISD::UNDEF)
8472       continue;
8473     if (V.getOpcode() == ISD::BITCAST &&
8474         V->getOperand(0).getValueType() == MVT::i32)
8475       // Fold obvious case.
8476       V = V.getOperand(0);
8477     else {
8478       V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
8479       // Make the DAGCombiner fold the bitcasts.
8480       DCI.AddToWorklist(V.getNode());
8481     }
8482     SDValue LaneIdx = DAG.getConstant(Idx, MVT::i32);
8483     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
8484   }
8485   Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
8486   // Make the DAGCombiner fold the bitcasts.
8487   DCI.AddToWorklist(Vec.getNode());
8488   return Vec;
8489 }
8490
8491 /// PerformInsertEltCombine - Target-specific dag combine xforms for
8492 /// ISD::INSERT_VECTOR_ELT.
8493 static SDValue PerformInsertEltCombine(SDNode *N,
8494                                        TargetLowering::DAGCombinerInfo &DCI) {
8495   // Bitcast an i64 load inserted into a vector to f64.
8496   // Otherwise, the i64 value will be legalized to a pair of i32 values.
8497   EVT VT = N->getValueType(0);
8498   SDNode *Elt = N->getOperand(1).getNode();
8499   if (VT.getVectorElementType() != MVT::i64 ||
8500       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
8501     return SDValue();
8502
8503   SelectionDAG &DAG = DCI.DAG;
8504   SDLoc dl(N);
8505   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8506                                  VT.getVectorNumElements());
8507   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
8508   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
8509   // Make the DAGCombiner fold the bitcasts.
8510   DCI.AddToWorklist(Vec.getNode());
8511   DCI.AddToWorklist(V.getNode());
8512   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
8513                                Vec, V, N->getOperand(2));
8514   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
8515 }
8516
8517 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
8518 /// ISD::VECTOR_SHUFFLE.
8519 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
8520   // The LLVM shufflevector instruction does not require the shuffle mask
8521   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
8522   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
8523   // operands do not match the mask length, they are extended by concatenating
8524   // them with undef vectors.  That is probably the right thing for other
8525   // targets, but for NEON it is better to concatenate two double-register
8526   // size vector operands into a single quad-register size vector.  Do that
8527   // transformation here:
8528   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
8529   //   shuffle(concat(v1, v2), undef)
8530   SDValue Op0 = N->getOperand(0);
8531   SDValue Op1 = N->getOperand(1);
8532   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
8533       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
8534       Op0.getNumOperands() != 2 ||
8535       Op1.getNumOperands() != 2)
8536     return SDValue();
8537   SDValue Concat0Op1 = Op0.getOperand(1);
8538   SDValue Concat1Op1 = Op1.getOperand(1);
8539   if (Concat0Op1.getOpcode() != ISD::UNDEF ||
8540       Concat1Op1.getOpcode() != ISD::UNDEF)
8541     return SDValue();
8542   // Skip the transformation if any of the types are illegal.
8543   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8544   EVT VT = N->getValueType(0);
8545   if (!TLI.isTypeLegal(VT) ||
8546       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
8547       !TLI.isTypeLegal(Concat1Op1.getValueType()))
8548     return SDValue();
8549
8550   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
8551                                   Op0.getOperand(0), Op1.getOperand(0));
8552   // Translate the shuffle mask.
8553   SmallVector<int, 16> NewMask;
8554   unsigned NumElts = VT.getVectorNumElements();
8555   unsigned HalfElts = NumElts/2;
8556   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8557   for (unsigned n = 0; n < NumElts; ++n) {
8558     int MaskElt = SVN->getMaskElt(n);
8559     int NewElt = -1;
8560     if (MaskElt < (int)HalfElts)
8561       NewElt = MaskElt;
8562     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
8563       NewElt = HalfElts + MaskElt - NumElts;
8564     NewMask.push_back(NewElt);
8565   }
8566   return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
8567                               DAG.getUNDEF(VT), NewMask.data());
8568 }
8569
8570 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP and
8571 /// NEON load/store intrinsics to merge base address updates.
8572 static SDValue CombineBaseUpdate(SDNode *N,
8573                                  TargetLowering::DAGCombinerInfo &DCI) {
8574   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8575     return SDValue();
8576
8577   SelectionDAG &DAG = DCI.DAG;
8578   bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
8579                       N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
8580   unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
8581   SDValue Addr = N->getOperand(AddrOpIdx);
8582
8583   // Search for a use of the address operand that is an increment.
8584   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
8585          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
8586     SDNode *User = *UI;
8587     if (User->getOpcode() != ISD::ADD ||
8588         UI.getUse().getResNo() != Addr.getResNo())
8589       continue;
8590
8591     // Check that the add is independent of the load/store.  Otherwise, folding
8592     // it would create a cycle.
8593     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
8594       continue;
8595
8596     // Find the new opcode for the updating load/store.
8597     bool isLoad = true;
8598     bool isLaneOp = false;
8599     unsigned NewOpc = 0;
8600     unsigned NumVecs = 0;
8601     if (isIntrinsic) {
8602       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
8603       switch (IntNo) {
8604       default: llvm_unreachable("unexpected intrinsic for Neon base update");
8605       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
8606         NumVecs = 1; break;
8607       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
8608         NumVecs = 2; break;
8609       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
8610         NumVecs = 3; break;
8611       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
8612         NumVecs = 4; break;
8613       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
8614         NumVecs = 2; isLaneOp = true; break;
8615       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
8616         NumVecs = 3; isLaneOp = true; break;
8617       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
8618         NumVecs = 4; isLaneOp = true; break;
8619       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
8620         NumVecs = 1; isLoad = false; break;
8621       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
8622         NumVecs = 2; isLoad = false; break;
8623       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
8624         NumVecs = 3; isLoad = false; break;
8625       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
8626         NumVecs = 4; isLoad = false; break;
8627       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
8628         NumVecs = 2; isLoad = false; isLaneOp = true; break;
8629       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
8630         NumVecs = 3; isLoad = false; isLaneOp = true; break;
8631       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
8632         NumVecs = 4; isLoad = false; isLaneOp = true; break;
8633       }
8634     } else {
8635       isLaneOp = true;
8636       switch (N->getOpcode()) {
8637       default: llvm_unreachable("unexpected opcode for Neon base update");
8638       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
8639       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
8640       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
8641       }
8642     }
8643
8644     // Find the size of memory referenced by the load/store.
8645     EVT VecTy;
8646     if (isLoad)
8647       VecTy = N->getValueType(0);
8648     else
8649       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
8650     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
8651     if (isLaneOp)
8652       NumBytes /= VecTy.getVectorNumElements();
8653
8654     // If the increment is a constant, it must match the memory ref size.
8655     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8656     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8657       uint64_t IncVal = CInc->getZExtValue();
8658       if (IncVal != NumBytes)
8659         continue;
8660     } else if (NumBytes >= 3 * 16) {
8661       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
8662       // separate instructions that make it harder to use a non-constant update.
8663       continue;
8664     }
8665
8666     // Create the new updating load/store node.
8667     EVT Tys[6];
8668     unsigned NumResultVecs = (isLoad ? NumVecs : 0);
8669     unsigned n;
8670     for (n = 0; n < NumResultVecs; ++n)
8671       Tys[n] = VecTy;
8672     Tys[n++] = MVT::i32;
8673     Tys[n] = MVT::Other;
8674     SDVTList SDTys = DAG.getVTList(ArrayRef<EVT>(Tys, NumResultVecs+2));
8675     SmallVector<SDValue, 8> Ops;
8676     Ops.push_back(N->getOperand(0)); // incoming chain
8677     Ops.push_back(N->getOperand(AddrOpIdx));
8678     Ops.push_back(Inc);
8679     for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
8680       Ops.push_back(N->getOperand(i));
8681     }
8682     MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
8683     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys,
8684                                            Ops.data(), Ops.size(),
8685                                            MemInt->getMemoryVT(),
8686                                            MemInt->getMemOperand());
8687
8688     // Update the uses.
8689     std::vector<SDValue> NewResults;
8690     for (unsigned i = 0; i < NumResultVecs; ++i) {
8691       NewResults.push_back(SDValue(UpdN.getNode(), i));
8692     }
8693     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
8694     DCI.CombineTo(N, NewResults);
8695     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
8696
8697     break;
8698   }
8699   return SDValue();
8700 }
8701
8702 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
8703 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
8704 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
8705 /// return true.
8706 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8707   SelectionDAG &DAG = DCI.DAG;
8708   EVT VT = N->getValueType(0);
8709   // vldN-dup instructions only support 64-bit vectors for N > 1.
8710   if (!VT.is64BitVector())
8711     return false;
8712
8713   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
8714   SDNode *VLD = N->getOperand(0).getNode();
8715   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
8716     return false;
8717   unsigned NumVecs = 0;
8718   unsigned NewOpc = 0;
8719   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
8720   if (IntNo == Intrinsic::arm_neon_vld2lane) {
8721     NumVecs = 2;
8722     NewOpc = ARMISD::VLD2DUP;
8723   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
8724     NumVecs = 3;
8725     NewOpc = ARMISD::VLD3DUP;
8726   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
8727     NumVecs = 4;
8728     NewOpc = ARMISD::VLD4DUP;
8729   } else {
8730     return false;
8731   }
8732
8733   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
8734   // numbers match the load.
8735   unsigned VLDLaneNo =
8736     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
8737   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
8738        UI != UE; ++UI) {
8739     // Ignore uses of the chain result.
8740     if (UI.getUse().getResNo() == NumVecs)
8741       continue;
8742     SDNode *User = *UI;
8743     if (User->getOpcode() != ARMISD::VDUPLANE ||
8744         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
8745       return false;
8746   }
8747
8748   // Create the vldN-dup node.
8749   EVT Tys[5];
8750   unsigned n;
8751   for (n = 0; n < NumVecs; ++n)
8752     Tys[n] = VT;
8753   Tys[n] = MVT::Other;
8754   SDVTList SDTys = DAG.getVTList(ArrayRef<EVT>(Tys, NumVecs+1));
8755   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
8756   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
8757   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
8758                                            Ops, 2, VLDMemInt->getMemoryVT(),
8759                                            VLDMemInt->getMemOperand());
8760
8761   // Update the uses.
8762   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
8763        UI != UE; ++UI) {
8764     unsigned ResNo = UI.getUse().getResNo();
8765     // Ignore uses of the chain result.
8766     if (ResNo == NumVecs)
8767       continue;
8768     SDNode *User = *UI;
8769     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
8770   }
8771
8772   // Now the vldN-lane intrinsic is dead except for its chain result.
8773   // Update uses of the chain.
8774   std::vector<SDValue> VLDDupResults;
8775   for (unsigned n = 0; n < NumVecs; ++n)
8776     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
8777   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
8778   DCI.CombineTo(VLD, VLDDupResults);
8779
8780   return true;
8781 }
8782
8783 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
8784 /// ARMISD::VDUPLANE.
8785 static SDValue PerformVDUPLANECombine(SDNode *N,
8786                                       TargetLowering::DAGCombinerInfo &DCI) {
8787   SDValue Op = N->getOperand(0);
8788
8789   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
8790   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
8791   if (CombineVLDDUP(N, DCI))
8792     return SDValue(N, 0);
8793
8794   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
8795   // redundant.  Ignore bit_converts for now; element sizes are checked below.
8796   while (Op.getOpcode() == ISD::BITCAST)
8797     Op = Op.getOperand(0);
8798   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
8799     return SDValue();
8800
8801   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
8802   unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
8803   // The canonical VMOV for a zero vector uses a 32-bit element size.
8804   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8805   unsigned EltBits;
8806   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
8807     EltSize = 8;
8808   EVT VT = N->getValueType(0);
8809   if (EltSize > VT.getVectorElementType().getSizeInBits())
8810     return SDValue();
8811
8812   return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
8813 }
8814
8815 // isConstVecPow2 - Return true if each vector element is a power of 2, all
8816 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
8817 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
8818 {
8819   integerPart cN;
8820   integerPart c0 = 0;
8821   for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
8822        I != E; I++) {
8823     ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
8824     if (!C)
8825       return false;
8826
8827     bool isExact;
8828     APFloat APF = C->getValueAPF();
8829     if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
8830         != APFloat::opOK || !isExact)
8831       return false;
8832
8833     c0 = (I == 0) ? cN : c0;
8834     if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
8835       return false;
8836   }
8837   C = c0;
8838   return true;
8839 }
8840
8841 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
8842 /// can replace combinations of VMUL and VCVT (floating-point to integer)
8843 /// when the VMUL has a constant operand that is a power of 2.
8844 ///
8845 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
8846 ///  vmul.f32        d16, d17, d16
8847 ///  vcvt.s32.f32    d16, d16
8848 /// becomes:
8849 ///  vcvt.s32.f32    d16, d16, #3
8850 static SDValue PerformVCVTCombine(SDNode *N,
8851                                   TargetLowering::DAGCombinerInfo &DCI,
8852                                   const ARMSubtarget *Subtarget) {
8853   SelectionDAG &DAG = DCI.DAG;
8854   SDValue Op = N->getOperand(0);
8855
8856   if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
8857       Op.getOpcode() != ISD::FMUL)
8858     return SDValue();
8859
8860   uint64_t C;
8861   SDValue N0 = Op->getOperand(0);
8862   SDValue ConstVec = Op->getOperand(1);
8863   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
8864
8865   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
8866       !isConstVecPow2(ConstVec, isSigned, C))
8867     return SDValue();
8868
8869   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
8870   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
8871   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
8872     // These instructions only exist converting from f32 to i32. We can handle
8873     // smaller integers by generating an extra truncate, but larger ones would
8874     // be lossy.
8875     return SDValue();
8876   }
8877
8878   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
8879     Intrinsic::arm_neon_vcvtfp2fxu;
8880   unsigned NumLanes = Op.getValueType().getVectorNumElements();
8881   SDValue FixConv =  DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
8882                                  NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
8883                                  DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
8884                                  DAG.getConstant(Log2_64(C), MVT::i32));
8885
8886   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
8887     FixConv = DAG.getNode(ISD::TRUNCATE, SDLoc(N), N->getValueType(0), FixConv);
8888
8889   return FixConv;
8890 }
8891
8892 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
8893 /// can replace combinations of VCVT (integer to floating-point) and VDIV
8894 /// when the VDIV has a constant operand that is a power of 2.
8895 ///
8896 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
8897 ///  vcvt.f32.s32    d16, d16
8898 ///  vdiv.f32        d16, d17, d16
8899 /// becomes:
8900 ///  vcvt.f32.s32    d16, d16, #3
8901 static SDValue PerformVDIVCombine(SDNode *N,
8902                                   TargetLowering::DAGCombinerInfo &DCI,
8903                                   const ARMSubtarget *Subtarget) {
8904   SelectionDAG &DAG = DCI.DAG;
8905   SDValue Op = N->getOperand(0);
8906   unsigned OpOpcode = Op.getNode()->getOpcode();
8907
8908   if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
8909       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
8910     return SDValue();
8911
8912   uint64_t C;
8913   SDValue ConstVec = N->getOperand(1);
8914   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
8915
8916   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
8917       !isConstVecPow2(ConstVec, isSigned, C))
8918     return SDValue();
8919
8920   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
8921   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
8922   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
8923     // These instructions only exist converting from i32 to f32. We can handle
8924     // smaller integers by generating an extra extend, but larger ones would
8925     // be lossy.
8926     return SDValue();
8927   }
8928
8929   SDValue ConvInput = Op.getOperand(0);
8930   unsigned NumLanes = Op.getValueType().getVectorNumElements();
8931   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
8932     ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
8933                             SDLoc(N), NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
8934                             ConvInput);
8935
8936   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
8937     Intrinsic::arm_neon_vcvtfxu2fp;
8938   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
8939                      Op.getValueType(),
8940                      DAG.getConstant(IntrinsicOpcode, MVT::i32),
8941                      ConvInput, DAG.getConstant(Log2_64(C), MVT::i32));
8942 }
8943
8944 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
8945 /// operand of a vector shift operation, where all the elements of the
8946 /// build_vector must have the same constant integer value.
8947 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
8948   // Ignore bit_converts.
8949   while (Op.getOpcode() == ISD::BITCAST)
8950     Op = Op.getOperand(0);
8951   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
8952   APInt SplatBits, SplatUndef;
8953   unsigned SplatBitSize;
8954   bool HasAnyUndefs;
8955   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
8956                                       HasAnyUndefs, ElementBits) ||
8957       SplatBitSize > ElementBits)
8958     return false;
8959   Cnt = SplatBits.getSExtValue();
8960   return true;
8961 }
8962
8963 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
8964 /// operand of a vector shift left operation.  That value must be in the range:
8965 ///   0 <= Value < ElementBits for a left shift; or
8966 ///   0 <= Value <= ElementBits for a long left shift.
8967 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
8968   assert(VT.isVector() && "vector shift count is not a vector type");
8969   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
8970   if (! getVShiftImm(Op, ElementBits, Cnt))
8971     return false;
8972   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
8973 }
8974
8975 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
8976 /// operand of a vector shift right operation.  For a shift opcode, the value
8977 /// is positive, but for an intrinsic the value count must be negative. The
8978 /// absolute value must be in the range:
8979 ///   1 <= |Value| <= ElementBits for a right shift; or
8980 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
8981 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
8982                          int64_t &Cnt) {
8983   assert(VT.isVector() && "vector shift count is not a vector type");
8984   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
8985   if (! getVShiftImm(Op, ElementBits, Cnt))
8986     return false;
8987   if (isIntrinsic)
8988     Cnt = -Cnt;
8989   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
8990 }
8991
8992 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
8993 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
8994   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
8995   switch (IntNo) {
8996   default:
8997     // Don't do anything for most intrinsics.
8998     break;
8999
9000   // Vector shifts: check for immediate versions and lower them.
9001   // Note: This is done during DAG combining instead of DAG legalizing because
9002   // the build_vectors for 64-bit vector element shift counts are generally
9003   // not legal, and it is hard to see their values after they get legalized to
9004   // loads from a constant pool.
9005   case Intrinsic::arm_neon_vshifts:
9006   case Intrinsic::arm_neon_vshiftu:
9007   case Intrinsic::arm_neon_vrshifts:
9008   case Intrinsic::arm_neon_vrshiftu:
9009   case Intrinsic::arm_neon_vrshiftn:
9010   case Intrinsic::arm_neon_vqshifts:
9011   case Intrinsic::arm_neon_vqshiftu:
9012   case Intrinsic::arm_neon_vqshiftsu:
9013   case Intrinsic::arm_neon_vqshiftns:
9014   case Intrinsic::arm_neon_vqshiftnu:
9015   case Intrinsic::arm_neon_vqshiftnsu:
9016   case Intrinsic::arm_neon_vqrshiftns:
9017   case Intrinsic::arm_neon_vqrshiftnu:
9018   case Intrinsic::arm_neon_vqrshiftnsu: {
9019     EVT VT = N->getOperand(1).getValueType();
9020     int64_t Cnt;
9021     unsigned VShiftOpc = 0;
9022
9023     switch (IntNo) {
9024     case Intrinsic::arm_neon_vshifts:
9025     case Intrinsic::arm_neon_vshiftu:
9026       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9027         VShiftOpc = ARMISD::VSHL;
9028         break;
9029       }
9030       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9031         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9032                      ARMISD::VSHRs : ARMISD::VSHRu);
9033         break;
9034       }
9035       return SDValue();
9036
9037     case Intrinsic::arm_neon_vrshifts:
9038     case Intrinsic::arm_neon_vrshiftu:
9039       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9040         break;
9041       return SDValue();
9042
9043     case Intrinsic::arm_neon_vqshifts:
9044     case Intrinsic::arm_neon_vqshiftu:
9045       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9046         break;
9047       return SDValue();
9048
9049     case Intrinsic::arm_neon_vqshiftsu:
9050       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9051         break;
9052       llvm_unreachable("invalid shift count for vqshlu intrinsic");
9053
9054     case Intrinsic::arm_neon_vrshiftn:
9055     case Intrinsic::arm_neon_vqshiftns:
9056     case Intrinsic::arm_neon_vqshiftnu:
9057     case Intrinsic::arm_neon_vqshiftnsu:
9058     case Intrinsic::arm_neon_vqrshiftns:
9059     case Intrinsic::arm_neon_vqrshiftnu:
9060     case Intrinsic::arm_neon_vqrshiftnsu:
9061       // Narrowing shifts require an immediate right shift.
9062       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9063         break;
9064       llvm_unreachable("invalid shift count for narrowing vector shift "
9065                        "intrinsic");
9066
9067     default:
9068       llvm_unreachable("unhandled vector shift");
9069     }
9070
9071     switch (IntNo) {
9072     case Intrinsic::arm_neon_vshifts:
9073     case Intrinsic::arm_neon_vshiftu:
9074       // Opcode already set above.
9075       break;
9076     case Intrinsic::arm_neon_vrshifts:
9077       VShiftOpc = ARMISD::VRSHRs; break;
9078     case Intrinsic::arm_neon_vrshiftu:
9079       VShiftOpc = ARMISD::VRSHRu; break;
9080     case Intrinsic::arm_neon_vrshiftn:
9081       VShiftOpc = ARMISD::VRSHRN; break;
9082     case Intrinsic::arm_neon_vqshifts:
9083       VShiftOpc = ARMISD::VQSHLs; break;
9084     case Intrinsic::arm_neon_vqshiftu:
9085       VShiftOpc = ARMISD::VQSHLu; break;
9086     case Intrinsic::arm_neon_vqshiftsu:
9087       VShiftOpc = ARMISD::VQSHLsu; break;
9088     case Intrinsic::arm_neon_vqshiftns:
9089       VShiftOpc = ARMISD::VQSHRNs; break;
9090     case Intrinsic::arm_neon_vqshiftnu:
9091       VShiftOpc = ARMISD::VQSHRNu; break;
9092     case Intrinsic::arm_neon_vqshiftnsu:
9093       VShiftOpc = ARMISD::VQSHRNsu; break;
9094     case Intrinsic::arm_neon_vqrshiftns:
9095       VShiftOpc = ARMISD::VQRSHRNs; break;
9096     case Intrinsic::arm_neon_vqrshiftnu:
9097       VShiftOpc = ARMISD::VQRSHRNu; break;
9098     case Intrinsic::arm_neon_vqrshiftnsu:
9099       VShiftOpc = ARMISD::VQRSHRNsu; break;
9100     }
9101
9102     return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9103                        N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
9104   }
9105
9106   case Intrinsic::arm_neon_vshiftins: {
9107     EVT VT = N->getOperand(1).getValueType();
9108     int64_t Cnt;
9109     unsigned VShiftOpc = 0;
9110
9111     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9112       VShiftOpc = ARMISD::VSLI;
9113     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9114       VShiftOpc = ARMISD::VSRI;
9115     else {
9116       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9117     }
9118
9119     return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9120                        N->getOperand(1), N->getOperand(2),
9121                        DAG.getConstant(Cnt, MVT::i32));
9122   }
9123
9124   case Intrinsic::arm_neon_vqrshifts:
9125   case Intrinsic::arm_neon_vqrshiftu:
9126     // No immediate versions of these to check for.
9127     break;
9128   }
9129
9130   return SDValue();
9131 }
9132
9133 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9134 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
9135 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9136 /// vector element shift counts are generally not legal, and it is hard to see
9137 /// their values after they get legalized to loads from a constant pool.
9138 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9139                                    const ARMSubtarget *ST) {
9140   EVT VT = N->getValueType(0);
9141   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9142     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9143     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9144     SDValue N1 = N->getOperand(1);
9145     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9146       SDValue N0 = N->getOperand(0);
9147       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9148           DAG.MaskedValueIsZero(N0.getOperand(0),
9149                                 APInt::getHighBitsSet(32, 16)))
9150         return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
9151     }
9152   }
9153
9154   // Nothing to be done for scalar shifts.
9155   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9156   if (!VT.isVector() || !TLI.isTypeLegal(VT))
9157     return SDValue();
9158
9159   assert(ST->hasNEON() && "unexpected vector shift");
9160   int64_t Cnt;
9161
9162   switch (N->getOpcode()) {
9163   default: llvm_unreachable("unexpected shift opcode");
9164
9165   case ISD::SHL:
9166     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
9167       return DAG.getNode(ARMISD::VSHL, SDLoc(N), VT, N->getOperand(0),
9168                          DAG.getConstant(Cnt, MVT::i32));
9169     break;
9170
9171   case ISD::SRA:
9172   case ISD::SRL:
9173     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
9174       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
9175                             ARMISD::VSHRs : ARMISD::VSHRu);
9176       return DAG.getNode(VShiftOpc, SDLoc(N), VT, N->getOperand(0),
9177                          DAG.getConstant(Cnt, MVT::i32));
9178     }
9179   }
9180   return SDValue();
9181 }
9182
9183 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
9184 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
9185 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
9186                                     const ARMSubtarget *ST) {
9187   SDValue N0 = N->getOperand(0);
9188
9189   // Check for sign- and zero-extensions of vector extract operations of 8-
9190   // and 16-bit vector elements.  NEON supports these directly.  They are
9191   // handled during DAG combining because type legalization will promote them
9192   // to 32-bit types and it is messy to recognize the operations after that.
9193   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9194     SDValue Vec = N0.getOperand(0);
9195     SDValue Lane = N0.getOperand(1);
9196     EVT VT = N->getValueType(0);
9197     EVT EltVT = N0.getValueType();
9198     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9199
9200     if (VT == MVT::i32 &&
9201         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
9202         TLI.isTypeLegal(Vec.getValueType()) &&
9203         isa<ConstantSDNode>(Lane)) {
9204
9205       unsigned Opc = 0;
9206       switch (N->getOpcode()) {
9207       default: llvm_unreachable("unexpected opcode");
9208       case ISD::SIGN_EXTEND:
9209         Opc = ARMISD::VGETLANEs;
9210         break;
9211       case ISD::ZERO_EXTEND:
9212       case ISD::ANY_EXTEND:
9213         Opc = ARMISD::VGETLANEu;
9214         break;
9215       }
9216       return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
9217     }
9218   }
9219
9220   return SDValue();
9221 }
9222
9223 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
9224 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
9225 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
9226                                        const ARMSubtarget *ST) {
9227   // If the target supports NEON, try to use vmax/vmin instructions for f32
9228   // selects like "x < y ? x : y".  Unless the NoNaNsFPMath option is set,
9229   // be careful about NaNs:  NEON's vmax/vmin return NaN if either operand is
9230   // a NaN; only do the transformation when it matches that behavior.
9231
9232   // For now only do this when using NEON for FP operations; if using VFP, it
9233   // is not obvious that the benefit outweighs the cost of switching to the
9234   // NEON pipeline.
9235   if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
9236       N->getValueType(0) != MVT::f32)
9237     return SDValue();
9238
9239   SDValue CondLHS = N->getOperand(0);
9240   SDValue CondRHS = N->getOperand(1);
9241   SDValue LHS = N->getOperand(2);
9242   SDValue RHS = N->getOperand(3);
9243   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
9244
9245   unsigned Opcode = 0;
9246   bool IsReversed;
9247   if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
9248     IsReversed = false; // x CC y ? x : y
9249   } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
9250     IsReversed = true ; // x CC y ? y : x
9251   } else {
9252     return SDValue();
9253   }
9254
9255   bool IsUnordered;
9256   switch (CC) {
9257   default: break;
9258   case ISD::SETOLT:
9259   case ISD::SETOLE:
9260   case ISD::SETLT:
9261   case ISD::SETLE:
9262   case ISD::SETULT:
9263   case ISD::SETULE:
9264     // If LHS is NaN, an ordered comparison will be false and the result will
9265     // be the RHS, but vmin(NaN, RHS) = NaN.  Avoid this by checking that LHS
9266     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9267     IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
9268     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9269       break;
9270     // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
9271     // will return -0, so vmin can only be used for unsafe math or if one of
9272     // the operands is known to be nonzero.
9273     if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
9274         !DAG.getTarget().Options.UnsafeFPMath &&
9275         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9276       break;
9277     Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
9278     break;
9279
9280   case ISD::SETOGT:
9281   case ISD::SETOGE:
9282   case ISD::SETGT:
9283   case ISD::SETGE:
9284   case ISD::SETUGT:
9285   case ISD::SETUGE:
9286     // If LHS is NaN, an ordered comparison will be false and the result will
9287     // be the RHS, but vmax(NaN, RHS) = NaN.  Avoid this by checking that LHS
9288     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9289     IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
9290     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9291       break;
9292     // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
9293     // will return +0, so vmax can only be used for unsafe math or if one of
9294     // the operands is known to be nonzero.
9295     if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
9296         !DAG.getTarget().Options.UnsafeFPMath &&
9297         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9298       break;
9299     Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
9300     break;
9301   }
9302
9303   if (!Opcode)
9304     return SDValue();
9305   return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), LHS, RHS);
9306 }
9307
9308 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
9309 SDValue
9310 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
9311   SDValue Cmp = N->getOperand(4);
9312   if (Cmp.getOpcode() != ARMISD::CMPZ)
9313     // Only looking at EQ and NE cases.
9314     return SDValue();
9315
9316   EVT VT = N->getValueType(0);
9317   SDLoc dl(N);
9318   SDValue LHS = Cmp.getOperand(0);
9319   SDValue RHS = Cmp.getOperand(1);
9320   SDValue FalseVal = N->getOperand(0);
9321   SDValue TrueVal = N->getOperand(1);
9322   SDValue ARMcc = N->getOperand(2);
9323   ARMCC::CondCodes CC =
9324     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
9325
9326   // Simplify
9327   //   mov     r1, r0
9328   //   cmp     r1, x
9329   //   mov     r0, y
9330   //   moveq   r0, x
9331   // to
9332   //   cmp     r0, x
9333   //   movne   r0, y
9334   //
9335   //   mov     r1, r0
9336   //   cmp     r1, x
9337   //   mov     r0, x
9338   //   movne   r0, y
9339   // to
9340   //   cmp     r0, x
9341   //   movne   r0, y
9342   /// FIXME: Turn this into a target neutral optimization?
9343   SDValue Res;
9344   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
9345     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
9346                       N->getOperand(3), Cmp);
9347   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
9348     SDValue ARMcc;
9349     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
9350     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
9351                       N->getOperand(3), NewCmp);
9352   }
9353
9354   if (Res.getNode()) {
9355     APInt KnownZero, KnownOne;
9356     DAG.ComputeMaskedBits(SDValue(N,0), KnownZero, KnownOne);
9357     // Capture demanded bits information that would be otherwise lost.
9358     if (KnownZero == 0xfffffffe)
9359       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9360                         DAG.getValueType(MVT::i1));
9361     else if (KnownZero == 0xffffff00)
9362       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9363                         DAG.getValueType(MVT::i8));
9364     else if (KnownZero == 0xffff0000)
9365       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9366                         DAG.getValueType(MVT::i16));
9367   }
9368
9369   return Res;
9370 }
9371
9372 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
9373                                              DAGCombinerInfo &DCI) const {
9374   switch (N->getOpcode()) {
9375   default: break;
9376   case ISD::ADDC:       return PerformADDCCombine(N, DCI, Subtarget);
9377   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
9378   case ISD::SUB:        return PerformSUBCombine(N, DCI);
9379   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
9380   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
9381   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
9382   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
9383   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
9384   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI);
9385   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
9386   case ISD::STORE:      return PerformSTORECombine(N, DCI);
9387   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI);
9388   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
9389   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
9390   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
9391   case ISD::FP_TO_SINT:
9392   case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
9393   case ISD::FDIV:       return PerformVDIVCombine(N, DCI, Subtarget);
9394   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
9395   case ISD::SHL:
9396   case ISD::SRA:
9397   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
9398   case ISD::SIGN_EXTEND:
9399   case ISD::ZERO_EXTEND:
9400   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
9401   case ISD::SELECT_CC:  return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
9402   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
9403   case ARMISD::VLD2DUP:
9404   case ARMISD::VLD3DUP:
9405   case ARMISD::VLD4DUP:
9406     return CombineBaseUpdate(N, DCI);
9407   case ARMISD::BUILD_VECTOR:
9408     return PerformARMBUILD_VECTORCombine(N, DCI);
9409   case ISD::INTRINSIC_VOID:
9410   case ISD::INTRINSIC_W_CHAIN:
9411     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9412     case Intrinsic::arm_neon_vld1:
9413     case Intrinsic::arm_neon_vld2:
9414     case Intrinsic::arm_neon_vld3:
9415     case Intrinsic::arm_neon_vld4:
9416     case Intrinsic::arm_neon_vld2lane:
9417     case Intrinsic::arm_neon_vld3lane:
9418     case Intrinsic::arm_neon_vld4lane:
9419     case Intrinsic::arm_neon_vst1:
9420     case Intrinsic::arm_neon_vst2:
9421     case Intrinsic::arm_neon_vst3:
9422     case Intrinsic::arm_neon_vst4:
9423     case Intrinsic::arm_neon_vst2lane:
9424     case Intrinsic::arm_neon_vst3lane:
9425     case Intrinsic::arm_neon_vst4lane:
9426       return CombineBaseUpdate(N, DCI);
9427     default: break;
9428     }
9429     break;
9430   }
9431   return SDValue();
9432 }
9433
9434 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
9435                                                           EVT VT) const {
9436   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
9437 }
9438
9439 bool ARMTargetLowering::allowsUnalignedMemoryAccesses(EVT VT, unsigned,
9440                                                       bool *Fast) const {
9441   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
9442   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
9443
9444   switch (VT.getSimpleVT().SimpleTy) {
9445   default:
9446     return false;
9447   case MVT::i8:
9448   case MVT::i16:
9449   case MVT::i32: {
9450     // Unaligned access can use (for example) LRDB, LRDH, LDR
9451     if (AllowsUnaligned) {
9452       if (Fast)
9453         *Fast = Subtarget->hasV7Ops();
9454       return true;
9455     }
9456     return false;
9457   }
9458   case MVT::f64:
9459   case MVT::v2f64: {
9460     // For any little-endian targets with neon, we can support unaligned ld/st
9461     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
9462     // A big-endian target may also explicitly support unaligned accesses
9463     if (Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian())) {
9464       if (Fast)
9465         *Fast = true;
9466       return true;
9467     }
9468     return false;
9469   }
9470   }
9471 }
9472
9473 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
9474                        unsigned AlignCheck) {
9475   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
9476           (DstAlign == 0 || DstAlign % AlignCheck == 0));
9477 }
9478
9479 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
9480                                            unsigned DstAlign, unsigned SrcAlign,
9481                                            bool IsMemset, bool ZeroMemset,
9482                                            bool MemcpyStrSrc,
9483                                            MachineFunction &MF) const {
9484   const Function *F = MF.getFunction();
9485
9486   // See if we can use NEON instructions for this...
9487   if ((!IsMemset || ZeroMemset) &&
9488       Subtarget->hasNEON() &&
9489       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
9490                                        Attribute::NoImplicitFloat)) {
9491     bool Fast;
9492     if (Size >= 16 &&
9493         (memOpAlign(SrcAlign, DstAlign, 16) ||
9494          (allowsUnalignedMemoryAccesses(MVT::v2f64, 0, &Fast) && Fast))) {
9495       return MVT::v2f64;
9496     } else if (Size >= 8 &&
9497                (memOpAlign(SrcAlign, DstAlign, 8) ||
9498                 (allowsUnalignedMemoryAccesses(MVT::f64, 0, &Fast) && Fast))) {
9499       return MVT::f64;
9500     }
9501   }
9502
9503   // Lowering to i32/i16 if the size permits.
9504   if (Size >= 4)
9505     return MVT::i32;
9506   else if (Size >= 2)
9507     return MVT::i16;
9508
9509   // Let the target-independent logic figure it out.
9510   return MVT::Other;
9511 }
9512
9513 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
9514   if (Val.getOpcode() != ISD::LOAD)
9515     return false;
9516
9517   EVT VT1 = Val.getValueType();
9518   if (!VT1.isSimple() || !VT1.isInteger() ||
9519       !VT2.isSimple() || !VT2.isInteger())
9520     return false;
9521
9522   switch (VT1.getSimpleVT().SimpleTy) {
9523   default: break;
9524   case MVT::i1:
9525   case MVT::i8:
9526   case MVT::i16:
9527     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
9528     return true;
9529   }
9530
9531   return false;
9532 }
9533
9534 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
9535   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9536     return false;
9537
9538   if (!isTypeLegal(EVT::getEVT(Ty1)))
9539     return false;
9540
9541   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
9542
9543   // Assuming the caller doesn't have a zeroext or signext return parameter,
9544   // truncation all the way down to i1 is valid.
9545   return true;
9546 }
9547
9548
9549 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
9550   if (V < 0)
9551     return false;
9552
9553   unsigned Scale = 1;
9554   switch (VT.getSimpleVT().SimpleTy) {
9555   default: return false;
9556   case MVT::i1:
9557   case MVT::i8:
9558     // Scale == 1;
9559     break;
9560   case MVT::i16:
9561     // Scale == 2;
9562     Scale = 2;
9563     break;
9564   case MVT::i32:
9565     // Scale == 4;
9566     Scale = 4;
9567     break;
9568   }
9569
9570   if ((V & (Scale - 1)) != 0)
9571     return false;
9572   V /= Scale;
9573   return V == (V & ((1LL << 5) - 1));
9574 }
9575
9576 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
9577                                       const ARMSubtarget *Subtarget) {
9578   bool isNeg = false;
9579   if (V < 0) {
9580     isNeg = true;
9581     V = - V;
9582   }
9583
9584   switch (VT.getSimpleVT().SimpleTy) {
9585   default: return false;
9586   case MVT::i1:
9587   case MVT::i8:
9588   case MVT::i16:
9589   case MVT::i32:
9590     // + imm12 or - imm8
9591     if (isNeg)
9592       return V == (V & ((1LL << 8) - 1));
9593     return V == (V & ((1LL << 12) - 1));
9594   case MVT::f32:
9595   case MVT::f64:
9596     // Same as ARM mode. FIXME: NEON?
9597     if (!Subtarget->hasVFP2())
9598       return false;
9599     if ((V & 3) != 0)
9600       return false;
9601     V >>= 2;
9602     return V == (V & ((1LL << 8) - 1));
9603   }
9604 }
9605
9606 /// isLegalAddressImmediate - Return true if the integer value can be used
9607 /// as the offset of the target addressing mode for load / store of the
9608 /// given type.
9609 static bool isLegalAddressImmediate(int64_t V, EVT VT,
9610                                     const ARMSubtarget *Subtarget) {
9611   if (V == 0)
9612     return true;
9613
9614   if (!VT.isSimple())
9615     return false;
9616
9617   if (Subtarget->isThumb1Only())
9618     return isLegalT1AddressImmediate(V, VT);
9619   else if (Subtarget->isThumb2())
9620     return isLegalT2AddressImmediate(V, VT, Subtarget);
9621
9622   // ARM mode.
9623   if (V < 0)
9624     V = - V;
9625   switch (VT.getSimpleVT().SimpleTy) {
9626   default: return false;
9627   case MVT::i1:
9628   case MVT::i8:
9629   case MVT::i32:
9630     // +- imm12
9631     return V == (V & ((1LL << 12) - 1));
9632   case MVT::i16:
9633     // +- imm8
9634     return V == (V & ((1LL << 8) - 1));
9635   case MVT::f32:
9636   case MVT::f64:
9637     if (!Subtarget->hasVFP2()) // FIXME: NEON?
9638       return false;
9639     if ((V & 3) != 0)
9640       return false;
9641     V >>= 2;
9642     return V == (V & ((1LL << 8) - 1));
9643   }
9644 }
9645
9646 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
9647                                                       EVT VT) const {
9648   int Scale = AM.Scale;
9649   if (Scale < 0)
9650     return false;
9651
9652   switch (VT.getSimpleVT().SimpleTy) {
9653   default: return false;
9654   case MVT::i1:
9655   case MVT::i8:
9656   case MVT::i16:
9657   case MVT::i32:
9658     if (Scale == 1)
9659       return true;
9660     // r + r << imm
9661     Scale = Scale & ~1;
9662     return Scale == 2 || Scale == 4 || Scale == 8;
9663   case MVT::i64:
9664     // r + r
9665     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
9666       return true;
9667     return false;
9668   case MVT::isVoid:
9669     // Note, we allow "void" uses (basically, uses that aren't loads or
9670     // stores), because arm allows folding a scale into many arithmetic
9671     // operations.  This should be made more precise and revisited later.
9672
9673     // Allow r << imm, but the imm has to be a multiple of two.
9674     if (Scale & 1) return false;
9675     return isPowerOf2_32(Scale);
9676   }
9677 }
9678
9679 /// isLegalAddressingMode - Return true if the addressing mode represented
9680 /// by AM is legal for this target, for a load/store of the specified type.
9681 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
9682                                               Type *Ty) const {
9683   EVT VT = getValueType(Ty, true);
9684   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
9685     return false;
9686
9687   // Can never fold addr of global into load/store.
9688   if (AM.BaseGV)
9689     return false;
9690
9691   switch (AM.Scale) {
9692   case 0:  // no scale reg, must be "r+i" or "r", or "i".
9693     break;
9694   case 1:
9695     if (Subtarget->isThumb1Only())
9696       return false;
9697     // FALL THROUGH.
9698   default:
9699     // ARM doesn't support any R+R*scale+imm addr modes.
9700     if (AM.BaseOffs)
9701       return false;
9702
9703     if (!VT.isSimple())
9704       return false;
9705
9706     if (Subtarget->isThumb2())
9707       return isLegalT2ScaledAddressingMode(AM, VT);
9708
9709     int Scale = AM.Scale;
9710     switch (VT.getSimpleVT().SimpleTy) {
9711     default: return false;
9712     case MVT::i1:
9713     case MVT::i8:
9714     case MVT::i32:
9715       if (Scale < 0) Scale = -Scale;
9716       if (Scale == 1)
9717         return true;
9718       // r + r << imm
9719       return isPowerOf2_32(Scale & ~1);
9720     case MVT::i16:
9721     case MVT::i64:
9722       // r + r
9723       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
9724         return true;
9725       return false;
9726
9727     case MVT::isVoid:
9728       // Note, we allow "void" uses (basically, uses that aren't loads or
9729       // stores), because arm allows folding a scale into many arithmetic
9730       // operations.  This should be made more precise and revisited later.
9731
9732       // Allow r << imm, but the imm has to be a multiple of two.
9733       if (Scale & 1) return false;
9734       return isPowerOf2_32(Scale);
9735     }
9736   }
9737   return true;
9738 }
9739
9740 /// isLegalICmpImmediate - Return true if the specified immediate is legal
9741 /// icmp immediate, that is the target has icmp instructions which can compare
9742 /// a register against the immediate without having to materialize the
9743 /// immediate into a register.
9744 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
9745   // Thumb2 and ARM modes can use cmn for negative immediates.
9746   if (!Subtarget->isThumb())
9747     return ARM_AM::getSOImmVal(llvm::abs64(Imm)) != -1;
9748   if (Subtarget->isThumb2())
9749     return ARM_AM::getT2SOImmVal(llvm::abs64(Imm)) != -1;
9750   // Thumb1 doesn't have cmn, and only 8-bit immediates.
9751   return Imm >= 0 && Imm <= 255;
9752 }
9753
9754 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
9755 /// *or sub* immediate, that is the target has add or sub instructions which can
9756 /// add a register with the immediate without having to materialize the
9757 /// immediate into a register.
9758 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
9759   // Same encoding for add/sub, just flip the sign.
9760   int64_t AbsImm = llvm::abs64(Imm);
9761   if (!Subtarget->isThumb())
9762     return ARM_AM::getSOImmVal(AbsImm) != -1;
9763   if (Subtarget->isThumb2())
9764     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
9765   // Thumb1 only has 8-bit unsigned immediate.
9766   return AbsImm >= 0 && AbsImm <= 255;
9767 }
9768
9769 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
9770                                       bool isSEXTLoad, SDValue &Base,
9771                                       SDValue &Offset, bool &isInc,
9772                                       SelectionDAG &DAG) {
9773   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
9774     return false;
9775
9776   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
9777     // AddressingMode 3
9778     Base = Ptr->getOperand(0);
9779     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9780       int RHSC = (int)RHS->getZExtValue();
9781       if (RHSC < 0 && RHSC > -256) {
9782         assert(Ptr->getOpcode() == ISD::ADD);
9783         isInc = false;
9784         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9785         return true;
9786       }
9787     }
9788     isInc = (Ptr->getOpcode() == ISD::ADD);
9789     Offset = Ptr->getOperand(1);
9790     return true;
9791   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
9792     // AddressingMode 2
9793     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9794       int RHSC = (int)RHS->getZExtValue();
9795       if (RHSC < 0 && RHSC > -0x1000) {
9796         assert(Ptr->getOpcode() == ISD::ADD);
9797         isInc = false;
9798         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9799         Base = Ptr->getOperand(0);
9800         return true;
9801       }
9802     }
9803
9804     if (Ptr->getOpcode() == ISD::ADD) {
9805       isInc = true;
9806       ARM_AM::ShiftOpc ShOpcVal=
9807         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
9808       if (ShOpcVal != ARM_AM::no_shift) {
9809         Base = Ptr->getOperand(1);
9810         Offset = Ptr->getOperand(0);
9811       } else {
9812         Base = Ptr->getOperand(0);
9813         Offset = Ptr->getOperand(1);
9814       }
9815       return true;
9816     }
9817
9818     isInc = (Ptr->getOpcode() == ISD::ADD);
9819     Base = Ptr->getOperand(0);
9820     Offset = Ptr->getOperand(1);
9821     return true;
9822   }
9823
9824   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
9825   return false;
9826 }
9827
9828 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
9829                                      bool isSEXTLoad, SDValue &Base,
9830                                      SDValue &Offset, bool &isInc,
9831                                      SelectionDAG &DAG) {
9832   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
9833     return false;
9834
9835   Base = Ptr->getOperand(0);
9836   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9837     int RHSC = (int)RHS->getZExtValue();
9838     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
9839       assert(Ptr->getOpcode() == ISD::ADD);
9840       isInc = false;
9841       Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9842       return true;
9843     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
9844       isInc = Ptr->getOpcode() == ISD::ADD;
9845       Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
9846       return true;
9847     }
9848   }
9849
9850   return false;
9851 }
9852
9853 /// getPreIndexedAddressParts - returns true by value, base pointer and
9854 /// offset pointer and addressing mode by reference if the node's address
9855 /// can be legally represented as pre-indexed load / store address.
9856 bool
9857 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
9858                                              SDValue &Offset,
9859                                              ISD::MemIndexedMode &AM,
9860                                              SelectionDAG &DAG) const {
9861   if (Subtarget->isThumb1Only())
9862     return false;
9863
9864   EVT VT;
9865   SDValue Ptr;
9866   bool isSEXTLoad = false;
9867   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9868     Ptr = LD->getBasePtr();
9869     VT  = LD->getMemoryVT();
9870     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
9871   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9872     Ptr = ST->getBasePtr();
9873     VT  = ST->getMemoryVT();
9874   } else
9875     return false;
9876
9877   bool isInc;
9878   bool isLegal = false;
9879   if (Subtarget->isThumb2())
9880     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
9881                                        Offset, isInc, DAG);
9882   else
9883     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
9884                                         Offset, isInc, DAG);
9885   if (!isLegal)
9886     return false;
9887
9888   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
9889   return true;
9890 }
9891
9892 /// getPostIndexedAddressParts - returns true by value, base pointer and
9893 /// offset pointer and addressing mode by reference if this node can be
9894 /// combined with a load / store to form a post-indexed load / store.
9895 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
9896                                                    SDValue &Base,
9897                                                    SDValue &Offset,
9898                                                    ISD::MemIndexedMode &AM,
9899                                                    SelectionDAG &DAG) const {
9900   if (Subtarget->isThumb1Only())
9901     return false;
9902
9903   EVT VT;
9904   SDValue Ptr;
9905   bool isSEXTLoad = false;
9906   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9907     VT  = LD->getMemoryVT();
9908     Ptr = LD->getBasePtr();
9909     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
9910   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9911     VT  = ST->getMemoryVT();
9912     Ptr = ST->getBasePtr();
9913   } else
9914     return false;
9915
9916   bool isInc;
9917   bool isLegal = false;
9918   if (Subtarget->isThumb2())
9919     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
9920                                        isInc, DAG);
9921   else
9922     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
9923                                         isInc, DAG);
9924   if (!isLegal)
9925     return false;
9926
9927   if (Ptr != Base) {
9928     // Swap base ptr and offset to catch more post-index load / store when
9929     // it's legal. In Thumb2 mode, offset must be an immediate.
9930     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
9931         !Subtarget->isThumb2())
9932       std::swap(Base, Offset);
9933
9934     // Post-indexed load / store update the base pointer.
9935     if (Ptr != Base)
9936       return false;
9937   }
9938
9939   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
9940   return true;
9941 }
9942
9943 void ARMTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
9944                                                        APInt &KnownZero,
9945                                                        APInt &KnownOne,
9946                                                        const SelectionDAG &DAG,
9947                                                        unsigned Depth) const {
9948   unsigned BitWidth = KnownOne.getBitWidth();
9949   KnownZero = KnownOne = APInt(BitWidth, 0);
9950   switch (Op.getOpcode()) {
9951   default: break;
9952   case ARMISD::ADDC:
9953   case ARMISD::ADDE:
9954   case ARMISD::SUBC:
9955   case ARMISD::SUBE:
9956     // These nodes' second result is a boolean
9957     if (Op.getResNo() == 0)
9958       break;
9959     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
9960     break;
9961   case ARMISD::CMOV: {
9962     // Bits are known zero/one if known on the LHS and RHS.
9963     DAG.ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
9964     if (KnownZero == 0 && KnownOne == 0) return;
9965
9966     APInt KnownZeroRHS, KnownOneRHS;
9967     DAG.ComputeMaskedBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
9968     KnownZero &= KnownZeroRHS;
9969     KnownOne  &= KnownOneRHS;
9970     return;
9971   }
9972   case ISD::INTRINSIC_W_CHAIN: {
9973     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
9974     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
9975     switch (IntID) {
9976     default: return;
9977     case Intrinsic::arm_ldaex:
9978     case Intrinsic::arm_ldrex: {
9979       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
9980       unsigned MemBits = VT.getScalarType().getSizeInBits();
9981       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
9982       return;
9983     }
9984     }
9985   }
9986   }
9987 }
9988
9989 //===----------------------------------------------------------------------===//
9990 //                           ARM Inline Assembly Support
9991 //===----------------------------------------------------------------------===//
9992
9993 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
9994   // Looking for "rev" which is V6+.
9995   if (!Subtarget->hasV6Ops())
9996     return false;
9997
9998   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
9999   std::string AsmStr = IA->getAsmString();
10000   SmallVector<StringRef, 4> AsmPieces;
10001   SplitString(AsmStr, AsmPieces, ";\n");
10002
10003   switch (AsmPieces.size()) {
10004   default: return false;
10005   case 1:
10006     AsmStr = AsmPieces[0];
10007     AsmPieces.clear();
10008     SplitString(AsmStr, AsmPieces, " \t,");
10009
10010     // rev $0, $1
10011     if (AsmPieces.size() == 3 &&
10012         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10013         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10014       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10015       if (Ty && Ty->getBitWidth() == 32)
10016         return IntrinsicLowering::LowerToByteSwap(CI);
10017     }
10018     break;
10019   }
10020
10021   return false;
10022 }
10023
10024 /// getConstraintType - Given a constraint letter, return the type of
10025 /// constraint it is for this target.
10026 ARMTargetLowering::ConstraintType
10027 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
10028   if (Constraint.size() == 1) {
10029     switch (Constraint[0]) {
10030     default:  break;
10031     case 'l': return C_RegisterClass;
10032     case 'w': return C_RegisterClass;
10033     case 'h': return C_RegisterClass;
10034     case 'x': return C_RegisterClass;
10035     case 't': return C_RegisterClass;
10036     case 'j': return C_Other; // Constant for movw.
10037       // An address with a single base register. Due to the way we
10038       // currently handle addresses it is the same as an 'r' memory constraint.
10039     case 'Q': return C_Memory;
10040     }
10041   } else if (Constraint.size() == 2) {
10042     switch (Constraint[0]) {
10043     default: break;
10044     // All 'U+' constraints are addresses.
10045     case 'U': return C_Memory;
10046     }
10047   }
10048   return TargetLowering::getConstraintType(Constraint);
10049 }
10050
10051 /// Examine constraint type and operand type and determine a weight value.
10052 /// This object must already have been set up with the operand type
10053 /// and the current alternative constraint selected.
10054 TargetLowering::ConstraintWeight
10055 ARMTargetLowering::getSingleConstraintMatchWeight(
10056     AsmOperandInfo &info, const char *constraint) const {
10057   ConstraintWeight weight = CW_Invalid;
10058   Value *CallOperandVal = info.CallOperandVal;
10059     // If we don't have a value, we can't do a match,
10060     // but allow it at the lowest weight.
10061   if (CallOperandVal == NULL)
10062     return CW_Default;
10063   Type *type = CallOperandVal->getType();
10064   // Look at the constraint type.
10065   switch (*constraint) {
10066   default:
10067     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10068     break;
10069   case 'l':
10070     if (type->isIntegerTy()) {
10071       if (Subtarget->isThumb())
10072         weight = CW_SpecificReg;
10073       else
10074         weight = CW_Register;
10075     }
10076     break;
10077   case 'w':
10078     if (type->isFloatingPointTy())
10079       weight = CW_Register;
10080     break;
10081   }
10082   return weight;
10083 }
10084
10085 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10086 RCPair
10087 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
10088                                                 MVT VT) const {
10089   if (Constraint.size() == 1) {
10090     // GCC ARM Constraint Letters
10091     switch (Constraint[0]) {
10092     case 'l': // Low regs or general regs.
10093       if (Subtarget->isThumb())
10094         return RCPair(0U, &ARM::tGPRRegClass);
10095       return RCPair(0U, &ARM::GPRRegClass);
10096     case 'h': // High regs or no regs.
10097       if (Subtarget->isThumb())
10098         return RCPair(0U, &ARM::hGPRRegClass);
10099       break;
10100     case 'r':
10101       return RCPair(0U, &ARM::GPRRegClass);
10102     case 'w':
10103       if (VT == MVT::Other)
10104         break;
10105       if (VT == MVT::f32)
10106         return RCPair(0U, &ARM::SPRRegClass);
10107       if (VT.getSizeInBits() == 64)
10108         return RCPair(0U, &ARM::DPRRegClass);
10109       if (VT.getSizeInBits() == 128)
10110         return RCPair(0U, &ARM::QPRRegClass);
10111       break;
10112     case 'x':
10113       if (VT == MVT::Other)
10114         break;
10115       if (VT == MVT::f32)
10116         return RCPair(0U, &ARM::SPR_8RegClass);
10117       if (VT.getSizeInBits() == 64)
10118         return RCPair(0U, &ARM::DPR_8RegClass);
10119       if (VT.getSizeInBits() == 128)
10120         return RCPair(0U, &ARM::QPR_8RegClass);
10121       break;
10122     case 't':
10123       if (VT == MVT::f32)
10124         return RCPair(0U, &ARM::SPRRegClass);
10125       break;
10126     }
10127   }
10128   if (StringRef("{cc}").equals_lower(Constraint))
10129     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10130
10131   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
10132 }
10133
10134 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10135 /// vector.  If it is invalid, don't add anything to Ops.
10136 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10137                                                      std::string &Constraint,
10138                                                      std::vector<SDValue>&Ops,
10139                                                      SelectionDAG &DAG) const {
10140   SDValue Result(0, 0);
10141
10142   // Currently only support length 1 constraints.
10143   if (Constraint.length() != 1) return;
10144
10145   char ConstraintLetter = Constraint[0];
10146   switch (ConstraintLetter) {
10147   default: break;
10148   case 'j':
10149   case 'I': case 'J': case 'K': case 'L':
10150   case 'M': case 'N': case 'O':
10151     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10152     if (!C)
10153       return;
10154
10155     int64_t CVal64 = C->getSExtValue();
10156     int CVal = (int) CVal64;
10157     // None of these constraints allow values larger than 32 bits.  Check
10158     // that the value fits in an int.
10159     if (CVal != CVal64)
10160       return;
10161
10162     switch (ConstraintLetter) {
10163       case 'j':
10164         // Constant suitable for movw, must be between 0 and
10165         // 65535.
10166         if (Subtarget->hasV6T2Ops())
10167           if (CVal >= 0 && CVal <= 65535)
10168             break;
10169         return;
10170       case 'I':
10171         if (Subtarget->isThumb1Only()) {
10172           // This must be a constant between 0 and 255, for ADD
10173           // immediates.
10174           if (CVal >= 0 && CVal <= 255)
10175             break;
10176         } else if (Subtarget->isThumb2()) {
10177           // A constant that can be used as an immediate value in a
10178           // data-processing instruction.
10179           if (ARM_AM::getT2SOImmVal(CVal) != -1)
10180             break;
10181         } else {
10182           // A constant that can be used as an immediate value in a
10183           // data-processing instruction.
10184           if (ARM_AM::getSOImmVal(CVal) != -1)
10185             break;
10186         }
10187         return;
10188
10189       case 'J':
10190         if (Subtarget->isThumb()) {  // FIXME thumb2
10191           // This must be a constant between -255 and -1, for negated ADD
10192           // immediates. This can be used in GCC with an "n" modifier that
10193           // prints the negated value, for use with SUB instructions. It is
10194           // not useful otherwise but is implemented for compatibility.
10195           if (CVal >= -255 && CVal <= -1)
10196             break;
10197         } else {
10198           // This must be a constant between -4095 and 4095. It is not clear
10199           // what this constraint is intended for. Implemented for
10200           // compatibility with GCC.
10201           if (CVal >= -4095 && CVal <= 4095)
10202             break;
10203         }
10204         return;
10205
10206       case 'K':
10207         if (Subtarget->isThumb1Only()) {
10208           // A 32-bit value where only one byte has a nonzero value. Exclude
10209           // zero to match GCC. This constraint is used by GCC internally for
10210           // constants that can be loaded with a move/shift combination.
10211           // It is not useful otherwise but is implemented for compatibility.
10212           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
10213             break;
10214         } else if (Subtarget->isThumb2()) {
10215           // A constant whose bitwise inverse can be used as an immediate
10216           // value in a data-processing instruction. This can be used in GCC
10217           // with a "B" modifier that prints the inverted value, for use with
10218           // BIC and MVN instructions. It is not useful otherwise but is
10219           // implemented for compatibility.
10220           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
10221             break;
10222         } else {
10223           // A constant whose bitwise inverse can be used as an immediate
10224           // value in a data-processing instruction. This can be used in GCC
10225           // with a "B" modifier that prints the inverted value, for use with
10226           // BIC and MVN instructions. It is not useful otherwise but is
10227           // implemented for compatibility.
10228           if (ARM_AM::getSOImmVal(~CVal) != -1)
10229             break;
10230         }
10231         return;
10232
10233       case 'L':
10234         if (Subtarget->isThumb1Only()) {
10235           // This must be a constant between -7 and 7,
10236           // for 3-operand ADD/SUB immediate instructions.
10237           if (CVal >= -7 && CVal < 7)
10238             break;
10239         } else if (Subtarget->isThumb2()) {
10240           // A constant whose negation can be used as an immediate value in a
10241           // data-processing instruction. This can be used in GCC with an "n"
10242           // modifier that prints the negated value, for use with SUB
10243           // instructions. It is not useful otherwise but is implemented for
10244           // compatibility.
10245           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
10246             break;
10247         } else {
10248           // A constant whose negation can be used as an immediate value in a
10249           // data-processing instruction. This can be used in GCC with an "n"
10250           // modifier that prints the negated value, for use with SUB
10251           // instructions. It is not useful otherwise but is implemented for
10252           // compatibility.
10253           if (ARM_AM::getSOImmVal(-CVal) != -1)
10254             break;
10255         }
10256         return;
10257
10258       case 'M':
10259         if (Subtarget->isThumb()) { // FIXME thumb2
10260           // This must be a multiple of 4 between 0 and 1020, for
10261           // ADD sp + immediate.
10262           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
10263             break;
10264         } else {
10265           // A power of two or a constant between 0 and 32.  This is used in
10266           // GCC for the shift amount on shifted register operands, but it is
10267           // useful in general for any shift amounts.
10268           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
10269             break;
10270         }
10271         return;
10272
10273       case 'N':
10274         if (Subtarget->isThumb()) {  // FIXME thumb2
10275           // This must be a constant between 0 and 31, for shift amounts.
10276           if (CVal >= 0 && CVal <= 31)
10277             break;
10278         }
10279         return;
10280
10281       case 'O':
10282         if (Subtarget->isThumb()) {  // FIXME thumb2
10283           // This must be a multiple of 4 between -508 and 508, for
10284           // ADD/SUB sp = sp + immediate.
10285           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
10286             break;
10287         }
10288         return;
10289     }
10290     Result = DAG.getTargetConstant(CVal, Op.getValueType());
10291     break;
10292   }
10293
10294   if (Result.getNode()) {
10295     Ops.push_back(Result);
10296     return;
10297   }
10298   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10299 }
10300
10301 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
10302   assert(Subtarget->isTargetAEABI() && "Register-based DivRem lowering only");
10303   unsigned Opcode = Op->getOpcode();
10304   assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
10305       "Invalid opcode for Div/Rem lowering");
10306   bool isSigned = (Opcode == ISD::SDIVREM);
10307   EVT VT = Op->getValueType(0);
10308   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
10309
10310   RTLIB::Libcall LC;
10311   switch (VT.getSimpleVT().SimpleTy) {
10312   default: llvm_unreachable("Unexpected request for libcall!");
10313   case MVT::i8:   LC= isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
10314   case MVT::i16:  LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
10315   case MVT::i32:  LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
10316   case MVT::i64:  LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
10317   }
10318
10319   SDValue InChain = DAG.getEntryNode();
10320
10321   TargetLowering::ArgListTy Args;
10322   TargetLowering::ArgListEntry Entry;
10323   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
10324     EVT ArgVT = Op->getOperand(i).getValueType();
10325     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
10326     Entry.Node = Op->getOperand(i);
10327     Entry.Ty = ArgTy;
10328     Entry.isSExt = isSigned;
10329     Entry.isZExt = !isSigned;
10330     Args.push_back(Entry);
10331   }
10332
10333   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
10334                                          getPointerTy());
10335
10336   Type *RetTy = (Type*)StructType::get(Ty, Ty, NULL);
10337
10338   SDLoc dl(Op);
10339   TargetLowering::
10340   CallLoweringInfo CLI(InChain, RetTy, isSigned, !isSigned, false, true,
10341                     0, getLibcallCallingConv(LC), /*isTailCall=*/false,
10342                     /*doesNotReturn=*/false, /*isReturnValueUsed=*/true,
10343                     Callee, Args, DAG, dl);
10344   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
10345
10346   return CallInfo.first;
10347 }
10348
10349 bool
10350 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
10351   // The ARM target isn't yet aware of offsets.
10352   return false;
10353 }
10354
10355 bool ARM::isBitFieldInvertedMask(unsigned v) {
10356   if (v == 0xffffffff)
10357     return false;
10358
10359   // there can be 1's on either or both "outsides", all the "inside"
10360   // bits must be 0's
10361   unsigned TO = CountTrailingOnes_32(v);
10362   unsigned LO = CountLeadingOnes_32(v);
10363   v = (v >> TO) << TO;
10364   v = (v << LO) >> LO;
10365   return v == 0;
10366 }
10367
10368 /// isFPImmLegal - Returns true if the target can instruction select the
10369 /// specified FP immediate natively. If false, the legalizer will
10370 /// materialize the FP immediate as a load from a constant pool.
10371 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
10372   if (!Subtarget->hasVFP3())
10373     return false;
10374   if (VT == MVT::f32)
10375     return ARM_AM::getFP32Imm(Imm) != -1;
10376   if (VT == MVT::f64)
10377     return ARM_AM::getFP64Imm(Imm) != -1;
10378   return false;
10379 }
10380
10381 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
10382 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
10383 /// specified in the intrinsic calls.
10384 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
10385                                            const CallInst &I,
10386                                            unsigned Intrinsic) const {
10387   switch (Intrinsic) {
10388   case Intrinsic::arm_neon_vld1:
10389   case Intrinsic::arm_neon_vld2:
10390   case Intrinsic::arm_neon_vld3:
10391   case Intrinsic::arm_neon_vld4:
10392   case Intrinsic::arm_neon_vld2lane:
10393   case Intrinsic::arm_neon_vld3lane:
10394   case Intrinsic::arm_neon_vld4lane: {
10395     Info.opc = ISD::INTRINSIC_W_CHAIN;
10396     // Conservatively set memVT to the entire set of vectors loaded.
10397     uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
10398     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10399     Info.ptrVal = I.getArgOperand(0);
10400     Info.offset = 0;
10401     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10402     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10403     Info.vol = false; // volatile loads with NEON intrinsics not supported
10404     Info.readMem = true;
10405     Info.writeMem = false;
10406     return true;
10407   }
10408   case Intrinsic::arm_neon_vst1:
10409   case Intrinsic::arm_neon_vst2:
10410   case Intrinsic::arm_neon_vst3:
10411   case Intrinsic::arm_neon_vst4:
10412   case Intrinsic::arm_neon_vst2lane:
10413   case Intrinsic::arm_neon_vst3lane:
10414   case Intrinsic::arm_neon_vst4lane: {
10415     Info.opc = ISD::INTRINSIC_VOID;
10416     // Conservatively set memVT to the entire set of vectors stored.
10417     unsigned NumElts = 0;
10418     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
10419       Type *ArgTy = I.getArgOperand(ArgI)->getType();
10420       if (!ArgTy->isVectorTy())
10421         break;
10422       NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
10423     }
10424     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10425     Info.ptrVal = I.getArgOperand(0);
10426     Info.offset = 0;
10427     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10428     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10429     Info.vol = false; // volatile stores with NEON intrinsics not supported
10430     Info.readMem = false;
10431     Info.writeMem = true;
10432     return true;
10433   }
10434   case Intrinsic::arm_ldaex:
10435   case Intrinsic::arm_ldrex: {
10436     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
10437     Info.opc = ISD::INTRINSIC_W_CHAIN;
10438     Info.memVT = MVT::getVT(PtrTy->getElementType());
10439     Info.ptrVal = I.getArgOperand(0);
10440     Info.offset = 0;
10441     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
10442     Info.vol = true;
10443     Info.readMem = true;
10444     Info.writeMem = false;
10445     return true;
10446   }
10447   case Intrinsic::arm_stlex:
10448   case Intrinsic::arm_strex: {
10449     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
10450     Info.opc = ISD::INTRINSIC_W_CHAIN;
10451     Info.memVT = MVT::getVT(PtrTy->getElementType());
10452     Info.ptrVal = I.getArgOperand(1);
10453     Info.offset = 0;
10454     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
10455     Info.vol = true;
10456     Info.readMem = false;
10457     Info.writeMem = true;
10458     return true;
10459   }
10460   case Intrinsic::arm_stlexd:
10461   case Intrinsic::arm_strexd: {
10462     Info.opc = ISD::INTRINSIC_W_CHAIN;
10463     Info.memVT = MVT::i64;
10464     Info.ptrVal = I.getArgOperand(2);
10465     Info.offset = 0;
10466     Info.align = 8;
10467     Info.vol = true;
10468     Info.readMem = false;
10469     Info.writeMem = true;
10470     return true;
10471   }
10472   case Intrinsic::arm_ldaexd:
10473   case Intrinsic::arm_ldrexd: {
10474     Info.opc = ISD::INTRINSIC_W_CHAIN;
10475     Info.memVT = MVT::i64;
10476     Info.ptrVal = I.getArgOperand(0);
10477     Info.offset = 0;
10478     Info.align = 8;
10479     Info.vol = true;
10480     Info.readMem = true;
10481     Info.writeMem = false;
10482     return true;
10483   }
10484   default:
10485     break;
10486   }
10487
10488   return false;
10489 }
10490
10491 /// \brief Returns true if it is beneficial to convert a load of a constant
10492 /// to just the constant itself.
10493 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
10494                                                           Type *Ty) const {
10495   assert(Ty->isIntegerTy());
10496
10497   unsigned Bits = Ty->getPrimitiveSizeInBits();
10498   if (Bits == 0 || Bits > 32)
10499     return false;
10500   return true;
10501 }
10502
10503 bool ARMTargetLowering::shouldExpandAtomicInIR(Instruction *Inst) const {
10504   // Loads and stores less than 64-bits are already atomic; ones above that
10505   // are doomed anyway, so defer to the default libcall and blame the OS when
10506   // things go wrong:
10507   if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
10508     return SI->getValueOperand()->getType()->getPrimitiveSizeInBits() == 64;
10509   else if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
10510     return LI->getType()->getPrimitiveSizeInBits() == 64;
10511
10512   // For the real atomic operations, we have ldrex/strex up to 64 bits.
10513   return Inst->getType()->getPrimitiveSizeInBits() <= 64;
10514 }
10515
10516 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
10517                                          AtomicOrdering Ord) const {
10518   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10519   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
10520   bool IsAcquire =
10521       Ord == Acquire || Ord == AcquireRelease || Ord == SequentiallyConsistent;
10522
10523   // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
10524   // intrinsic must return {i32, i32} and we have to recombine them into a
10525   // single i64 here.
10526   if (ValTy->getPrimitiveSizeInBits() == 64) {
10527     Intrinsic::ID Int =
10528         IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
10529     Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int);
10530
10531     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
10532     Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
10533
10534     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
10535     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
10536     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
10537     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
10538     return Builder.CreateOr(
10539         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
10540   }
10541
10542   Type *Tys[] = { Addr->getType() };
10543   Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
10544   Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys);
10545
10546   return Builder.CreateTruncOrBitCast(
10547       Builder.CreateCall(Ldrex, Addr),
10548       cast<PointerType>(Addr->getType())->getElementType());
10549 }
10550
10551 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
10552                                                Value *Addr,
10553                                                AtomicOrdering Ord) const {
10554   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10555   bool IsRelease =
10556       Ord == Release || Ord == AcquireRelease || Ord == SequentiallyConsistent;
10557
10558   // Since the intrinsics must have legal type, the i64 intrinsics take two
10559   // parameters: "i32, i32". We must marshal Val into the appropriate form
10560   // before the call.
10561   if (Val->getType()->getPrimitiveSizeInBits() == 64) {
10562     Intrinsic::ID Int =
10563         IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
10564     Function *Strex = Intrinsic::getDeclaration(M, Int);
10565     Type *Int32Ty = Type::getInt32Ty(M->getContext());
10566
10567     Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
10568     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
10569     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
10570     return Builder.CreateCall3(Strex, Lo, Hi, Addr);
10571   }
10572
10573   Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
10574   Type *Tys[] = { Addr->getType() };
10575   Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
10576
10577   return Builder.CreateCall2(
10578       Strex, Builder.CreateZExtOrBitCast(
10579                  Val, Strex->getFunctionType()->getParamType(0)),
10580       Addr);
10581 }